pikelet-wasm 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,231 +0,0 @@
1
- const MAGIC = 'PSTU';
2
- const VERSION = 1;
3
- const HEADER_BYTES = 32;
4
- const TOKEN_RE = /[a-z0-9]+/g;
5
-
6
- function align4(value) {
7
- return (value + 3) & ~3;
8
- }
9
-
10
- function hash32(text, seed) {
11
- let hash = seed >>> 0;
12
- for (let i = 0; i < text.length; i++) {
13
- hash ^= text.charCodeAt(i);
14
- hash = Math.imul(hash, 16777619);
15
- }
16
- return hash >>> 0;
17
- }
18
-
19
- export function extractStudentFeatures(text, model) {
20
- return extractStudentFeatureRecords(text, model).map((feature) => feature.bucket);
21
- }
22
-
23
- export function extractStudentFeatureRecords(text, model) {
24
- const tokens = String(text || '').toLowerCase().match(TOKEN_RE) || [];
25
- const features = [];
26
- const limit = model.maxFeatures;
27
-
28
- const push = (feature, family) => {
29
- if (features.length < limit) {
30
- features.push({
31
- bucket: hash32(feature, model.hashSeed) % model.bucketCount,
32
- family
33
- });
34
- }
35
- };
36
-
37
- for (let tokenIndex = 0; tokenIndex < tokens.length && features.length < limit; tokenIndex++) {
38
- const token = tokens[tokenIndex].slice(0, 48);
39
- push(`w:${token}`, 'word');
40
-
41
- const padded = `^${token}$`;
42
- for (let width = 3; width <= 5 && features.length < limit; width++) {
43
- for (let start = 0; start + width <= padded.length && features.length < limit; start++) {
44
- push(`c${width}:${padded.slice(start, start + width)}`, 'char');
45
- }
46
- }
47
-
48
- if (tokenIndex > 0) {
49
- push(`b:${tokens[tokenIndex - 1].slice(0, 48)}:${token}`, 'word');
50
- }
51
- }
52
-
53
- return features;
54
- }
55
-
56
- export function loadStudentModel(input) {
57
- const bytes = input instanceof Uint8Array
58
- ? input
59
- : input instanceof ArrayBuffer
60
- ? new Uint8Array(input)
61
- : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
62
- if (bytes.byteLength < HEADER_BYTES) throw new Error('Student model is truncated');
63
-
64
- const magic = String.fromCharCode(...bytes.subarray(0, 4));
65
- if (magic !== MAGIC) throw new Error(`Invalid student model magic: ${magic}`);
66
-
67
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
68
- const version = view.getUint32(4, true);
69
- if (version !== VERSION) throw new Error(`Unsupported student model version: ${version}`);
70
-
71
- const bucketCount = view.getUint32(8, true);
72
- const hiddenDim = view.getUint32(12, true);
73
- const outputDim = view.getUint32(16, true);
74
- const hashSeed = view.getUint32(20, true);
75
- const maxFeatures = view.getUint32(24, true);
76
- if (!bucketCount || !hiddenDim || !outputDim || !maxFeatures) {
77
- throw new Error('Student model has invalid dimensions');
78
- }
79
-
80
- let offset = HEADER_BYTES;
81
- const embeddingScalesBytes = bucketCount * 4;
82
- const embeddingBytes = bucketCount * hiddenDim;
83
- const projectionScalesBytes = outputDim * 4;
84
- const projectionBytes = outputDim * hiddenDim;
85
- const biasBytes = outputDim * 4;
86
- const required = align4(offset + embeddingScalesBytes + embeddingBytes)
87
- + projectionScalesBytes + projectionBytes + biasBytes;
88
- if (required !== bytes.byteLength) {
89
- throw new Error(`Student model size mismatch: expected ${required}, received ${bytes.byteLength}`);
90
- }
91
-
92
- const embeddingScales = new Float32Array(
93
- bytes.buffer,
94
- bytes.byteOffset + offset,
95
- bucketCount
96
- );
97
- offset += embeddingScalesBytes;
98
- const embeddingWeights = new Int8Array(
99
- bytes.buffer,
100
- bytes.byteOffset + offset,
101
- embeddingBytes
102
- );
103
- offset = align4(offset + embeddingBytes);
104
- const projectionScales = new Float32Array(
105
- bytes.buffer,
106
- bytes.byteOffset + offset,
107
- outputDim
108
- );
109
- offset += projectionScalesBytes;
110
- const projectionWeights = new Int8Array(
111
- bytes.buffer,
112
- bytes.byteOffset + offset,
113
- projectionBytes
114
- );
115
- offset += projectionBytes;
116
- const projectionBias = new Float32Array(
117
- bytes.buffer,
118
- bytes.byteOffset + offset,
119
- outputDim
120
- );
121
-
122
- return {
123
- version,
124
- bucketCount,
125
- hiddenDim,
126
- outputDim,
127
- hashSeed,
128
- maxFeatures,
129
- embeddingScales,
130
- embeddingWeights,
131
- projectionScales,
132
- projectionWeights,
133
- projectionBias,
134
- byteLength: bytes.byteLength,
135
- _bytes: bytes,
136
- };
137
- }
138
-
139
- export function embedTextWithStudent(text, model) {
140
- const features = extractStudentFeatureRecords(text, model);
141
- const hidden = new Float32Array(model.hiddenDim);
142
- const output = new Float32Array(model.outputDim);
143
- if (features.length === 0) {
144
- return { vector: output, preNorm: 0, features, hidden };
145
- }
146
-
147
- for (const { bucket } of features) {
148
- const scale = model.embeddingScales[bucket];
149
- const rowOffset = bucket * model.hiddenDim;
150
- for (let column = 0; column < model.hiddenDim; column++) {
151
- hidden[column] += model.embeddingWeights[rowOffset + column] * scale;
152
- }
153
- }
154
-
155
- const inverseCount = 1 / features.length;
156
- for (let column = 0; column < model.hiddenDim; column++) {
157
- hidden[column] = Math.tanh(hidden[column] * inverseCount);
158
- }
159
- const hiddenOutput = new Float32Array(hidden);
160
-
161
- let normSquared = 0;
162
- for (let row = 0; row < model.outputDim; row++) {
163
- const scale = model.projectionScales[row];
164
- const rowOffset = row * model.hiddenDim;
165
- let value = model.projectionBias[row];
166
- for (let column = 0; column < model.hiddenDim; column++) {
167
- value += model.projectionWeights[rowOffset + column] * scale * hidden[column];
168
- }
169
- output[row] = value;
170
- normSquared += value * value;
171
- }
172
-
173
- const norm = Math.sqrt(normSquared);
174
- if (!(norm > 0) || !Number.isFinite(norm)) {
175
- return { vector: new Float32Array(model.outputDim), preNorm: 0, features, hidden: hiddenOutput };
176
- }
177
- const inverseNorm = 1 / norm;
178
- for (let row = 0; row < model.outputDim; row++) output[row] *= inverseNorm;
179
- return { vector: output, preNorm: norm, features, hidden: hiddenOutput };
180
- }
181
-
182
- function sigmoid(value) {
183
- if (value >= 0) {
184
- const z = Math.exp(-value);
185
- return 1 / (1 + z);
186
- }
187
- const z = Math.exp(value);
188
- return z / (1 + z);
189
- }
190
-
191
- export function scoreQuery(signals, abstention) {
192
- if (!abstention) {
193
- return { match_quality: 'unscored' };
194
- }
195
- const featureNames = abstention.features || ['d0', 'margin', 'pre_norm', 'known_word', 'known_char'];
196
- const weights = abstention.weights || [];
197
- let logit = Number(abstention.bias) || 0;
198
- for (let i = 0; i < featureNames.length; i++) {
199
- logit += (Number(weights[i]) || 0) * (Number(signals[featureNames[i]]) || 0);
200
- }
201
-
202
- const confidence = sigmoid(logit);
203
- const thresholds = abstention.thresholds || {};
204
- const hard = Number.isFinite(thresholds.hard) ? thresholds.hard : 0.05;
205
- const weak = Number.isFinite(thresholds.weak) ? thresholds.weak : 0;
206
- const preNormFloor = Number.isFinite(thresholds.preNormFloor) ? thresholds.preNormFloor : 0.4;
207
- const minFeatures = Number.isInteger(thresholds.minFeatures) ? thresholds.minFeatures : 3;
208
- const epsilon = 1e-6;
209
- const floorTriggered = confidence < hard
210
- || (Number(signals.n_feats) || 0) < minFeatures
211
- || (Number(signals.pre_norm) || 0) < preNormFloor;
212
- const match_quality = floorTriggered
213
- ? 'none'
214
- : confidence + epsilon >= weak
215
- ? 'strong'
216
- : 'weak';
217
- return {
218
- match_quality,
219
- score: confidence,
220
- confidence: Math.round(confidence * 1000) / 1000,
221
- signals: {
222
- d0: signals.d0,
223
- margin: signals.margin,
224
- pre_norm: signals.pre_norm,
225
- known_word: signals.known_word,
226
- known_char: signals.known_char,
227
- hidden_probe: signals.hidden_probe,
228
- n_feats: signals.n_feats
229
- }
230
- };
231
- }