@scinorandex/embeddings 0.0.0-stage → 0.0.2
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.
- package/.vscode/settings.json +3 -0
- package/README.md +140 -2
- package/bench/baseline.ts +41 -0
- package/bench/float_check.ts +123 -0
- package/bench/glove_cache_bench.ts +44 -0
- package/bench/limit_check.ts +32 -0
- package/bench/memdiag.ts +17 -0
- package/bench/optimized.ts +82 -0
- package/dist/common.d.ts +26 -0
- package/dist/common.js +183 -0
- package/dist/common.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/models/fasttext.d.ts +3 -0
- package/dist/models/fasttext.js +453 -0
- package/dist/models/fasttext.js.map +1 -0
- package/dist/models/glove.d.ts +3 -0
- package/dist/models/glove.js +429 -0
- package/dist/models/glove.js.map +1 -0
- package/dist/models/glove_worker.mjs +143 -0
- package/dist/models/matrix.d.ts +50 -0
- package/dist/models/matrix.js +362 -0
- package/dist/models/matrix.js.map +1 -0
- package/dist/models/parse_fast.mjs +245 -0
- package/dist/models/word2vec.d.ts +3 -0
- package/dist/models/word2vec.js +193 -0
- package/dist/models/word2vec.js.map +1 -0
- package/opencode.json +27 -0
- package/package.json +17 -4
- package/scripts/copy-assets.mjs +32 -0
- package/src/common.ts +260 -0
- package/src/index.ts +5 -0
- package/src/models/fasttext.ts +560 -0
- package/src/models/glove.ts +521 -0
- package/src/models/glove_worker.mjs +143 -0
- package/src/models/matrix.ts +461 -0
- package/src/models/parse_fast.d.mts +30 -0
- package/src/models/parse_fast.mjs +245 -0
- package/src/models/word2vec.ts +223 -0
- package/test/fasttext.ts +13 -0
- package/test/glove.ts +13 -0
- package/test/word2vec.ts +13 -0
- package/tsconfig.build.json +31 -0
- package/tsconfig.json +30 -0
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import { normalize, WordVector, type WordDist, type WordModel } from "../common";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Storage precision of the embedding matrix.
|
|
5
|
+
*
|
|
6
|
+
* - `"f32"` (default): float32, exact storage, 4 bytes per value.
|
|
7
|
+
* - `"f16"`: float16, half the memory, negligible accuracy loss.
|
|
8
|
+
* - `"i8"`: signed 8-bit with a per-vector scale, a quarter of the memory of
|
|
9
|
+
* `"f32"`. Similarity is computed with integer dot products, so queries are
|
|
10
|
+
* also fast; expect a similarity error of ~0.003 at most.
|
|
11
|
+
*/
|
|
12
|
+
export type Precision = "f32" | "f16" | "i8";
|
|
13
|
+
|
|
14
|
+
/** Options accepted by the model loaders. */
|
|
15
|
+
export interface LoadOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Normalize every vector to unit length while loading (default: `true`).
|
|
18
|
+
* With `true`, stored vectors are unit-length, so a plain dot product is a
|
|
19
|
+
* cosine similarity. With `false` the raw vectors are stored (loading is a
|
|
20
|
+
* bit faster); `get_vector` then returns raw values, while
|
|
21
|
+
* `similarity` / nearest-neighbor queries still report true cosine
|
|
22
|
+
* similarity (per-vector norms are kept).
|
|
23
|
+
*/
|
|
24
|
+
normalize?: boolean;
|
|
25
|
+
/** Storage precision (default: `"f32"`). */
|
|
26
|
+
precision?: Precision;
|
|
27
|
+
/** Only load the first `limit` words (default: all). */
|
|
28
|
+
limit?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Keep a binary cache of the parsed model next to the source file and
|
|
31
|
+
* reuse it on subsequent loads:
|
|
32
|
+
* - word2vec (`.gz` input): the decompressed file (same path without the
|
|
33
|
+
* `.gz` suffix) skips gunzip entirely.
|
|
34
|
+
* - GloVe (`.txt` input): a compact binary file (`.txt` replaced by
|
|
35
|
+
* `.glovecache`) skips the text parse entirely.
|
|
36
|
+
* The file is written to a temporary name and renamed atomically, so a
|
|
37
|
+
* crashed load never leaves a stale cache behind. Default: `false`.
|
|
38
|
+
*/
|
|
39
|
+
cache?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ResolvedOptions {
|
|
43
|
+
normalize: boolean;
|
|
44
|
+
precision: Precision;
|
|
45
|
+
limit?: number;
|
|
46
|
+
cache: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function resolve_options(options?: LoadOptions | number): ResolvedOptions {
|
|
50
|
+
if (typeof options === "number") options = { limit: options };
|
|
51
|
+
options = options ?? {};
|
|
52
|
+
return {
|
|
53
|
+
normalize: options.normalize ?? true,
|
|
54
|
+
precision: options.precision ?? "f32",
|
|
55
|
+
limit: options.limit,
|
|
56
|
+
cache: options.cache ?? false,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Parameters describing a fully parsed model, ready to be wrapped. */
|
|
61
|
+
export interface MatrixModelParams {
|
|
62
|
+
/** Row-major matrix with one row per word (`rows * size` elements). */
|
|
63
|
+
matrix: Float32Array | Float16Array | Int8Array;
|
|
64
|
+
precision: Precision;
|
|
65
|
+
size: number;
|
|
66
|
+
/** Word of row `i`, in file order. */
|
|
67
|
+
words: string[];
|
|
68
|
+
/** Word -> row index. */
|
|
69
|
+
index: Map<string, number>;
|
|
70
|
+
/** `true` when the stored rows are already unit-normalized. */
|
|
71
|
+
normalized: boolean;
|
|
72
|
+
/** Raw per-row norms; required when `normalized` is `false`. */
|
|
73
|
+
rawNorms: Float32Array | null;
|
|
74
|
+
/** Per-row dequantization factors (stored value * factor = original); required when `precision` is `"i8"`. */
|
|
75
|
+
i8Scales: Float32Array | null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A word model backed by a single contiguous matrix.
|
|
80
|
+
*
|
|
81
|
+
* Instead of one `WordVector` (and one `Float32Array`) object per word, the
|
|
82
|
+
* whole vocabulary is stored row-major in one typed array. This removes the
|
|
83
|
+
* per-word object overhead (hundreds of MB for large models), keeps the query
|
|
84
|
+
* hot loop cache-friendly, and lets `get_vector` hand out zero-copy views for
|
|
85
|
+
* the `"f32"` precision.
|
|
86
|
+
*/
|
|
87
|
+
export class MatrixModel implements WordModel {
|
|
88
|
+
readonly words: number;
|
|
89
|
+
readonly size: number;
|
|
90
|
+
readonly precision: Precision;
|
|
91
|
+
|
|
92
|
+
private readonly m: Float32Array | Float16Array | Int8Array;
|
|
93
|
+
private readonly wordList: string[];
|
|
94
|
+
private readonly index: Map<string, number>;
|
|
95
|
+
private readonly normalized: boolean;
|
|
96
|
+
/** Per-row `1 / |row|`; `null` when rows are stored unit-normalized. */
|
|
97
|
+
private readonly invNorms: Float32Array | null;
|
|
98
|
+
/** Per-row `dequant / |row|` factors for `"i8"` similarity math. */
|
|
99
|
+
private readonly i8Factors: Float32Array | null;
|
|
100
|
+
/** Per-row dequantization factors: original value = stored value * factor (`"i8"` only). */
|
|
101
|
+
private readonly i8Scales: Float32Array | null;
|
|
102
|
+
|
|
103
|
+
constructor(params: MatrixModelParams) {
|
|
104
|
+
this.m = params.matrix;
|
|
105
|
+
this.precision = params.precision;
|
|
106
|
+
this.size = params.size;
|
|
107
|
+
this.words = params.words.length;
|
|
108
|
+
this.wordList = params.words;
|
|
109
|
+
this.index = params.index;
|
|
110
|
+
this.normalized = params.normalized;
|
|
111
|
+
this.i8Scales = params.i8Scales;
|
|
112
|
+
|
|
113
|
+
if (params.normalized) {
|
|
114
|
+
this.invNorms = null;
|
|
115
|
+
} else {
|
|
116
|
+
const norms = params.rawNorms!;
|
|
117
|
+
this.invNorms = new Float32Array(norms.length);
|
|
118
|
+
for (let i = 0; i < norms.length; i++) this.invNorms[i] = 1 / norms[i];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (params.precision === "i8") {
|
|
122
|
+
const scales = params.i8Scales!;
|
|
123
|
+
const inv = this.invNorms;
|
|
124
|
+
this.i8Factors = new Float32Array(scales.length);
|
|
125
|
+
for (let i = 0; i < scales.length; i++) this.i8Factors[i] = inv === null ? scales[i] : scales[i] * inv[i];
|
|
126
|
+
} else {
|
|
127
|
+
this.i8Factors = null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
get_vector(word: string): WordVector | null {
|
|
132
|
+
const i = this.index.get(word);
|
|
133
|
+
if (i === undefined) return null;
|
|
134
|
+
return this.row_vector(i, word);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The `WordVector` for row `i` (zero-copy view for `"f32"`). */
|
|
138
|
+
private row_vector(i: number, word: string): WordVector {
|
|
139
|
+
const size = this.size;
|
|
140
|
+
const off = i * size;
|
|
141
|
+
if (this.precision === "f32") {
|
|
142
|
+
const m = this.m as Float32Array;
|
|
143
|
+
return new WordVector(word, new Float32Array(m.buffer, m.byteOffset + off * 4, size));
|
|
144
|
+
}
|
|
145
|
+
const out = new Float32Array(size);
|
|
146
|
+
if (this.precision === "f16") {
|
|
147
|
+
const m = this.m as Float16Array;
|
|
148
|
+
for (let a = 0; a < size; a++) out[a] = m[off + a];
|
|
149
|
+
} else {
|
|
150
|
+
const m = this.m as Int8Array;
|
|
151
|
+
const s = this.i8Scales![i];
|
|
152
|
+
for (let a = 0; a < size; a++) out[a] = m[off + a] * s;
|
|
153
|
+
}
|
|
154
|
+
return new WordVector(word, out);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
get_vectors(filter?: string[]): WordVector[] {
|
|
158
|
+
if (!filter) {
|
|
159
|
+
const out = new Array<WordVector>(this.words);
|
|
160
|
+
for (let i = 0; i < this.words; i++) out[i] = this.row_vector(i, this.wordList[i]);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
const fset = new Set(filter);
|
|
164
|
+
const out: WordVector[] = [];
|
|
165
|
+
for (let i = 0; i < this.wordList.length; i++) {
|
|
166
|
+
const w = this.wordList[i];
|
|
167
|
+
if (fset.has(w)) out.push(this.row_vector(i, w));
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
similarity(word1: string, word2: string): number | null {
|
|
173
|
+
const i1 = this.index.get(word1);
|
|
174
|
+
if (i1 === undefined) return null;
|
|
175
|
+
const i2 = this.index.get(word2);
|
|
176
|
+
if (i2 === undefined) return null;
|
|
177
|
+
if (word1 === word2) return 1.0;
|
|
178
|
+
|
|
179
|
+
const size = this.size;
|
|
180
|
+
const m = this.m;
|
|
181
|
+
const off1 = i1 * size;
|
|
182
|
+
const off2 = i2 * size;
|
|
183
|
+
let s = 0;
|
|
184
|
+
for (let a = 0; a < size; a++) s += m[off1 + a] * m[off2 + a];
|
|
185
|
+
|
|
186
|
+
if (this.precision === "i8") {
|
|
187
|
+
const f = this.i8Factors!;
|
|
188
|
+
return s * f[i1] * f[i2];
|
|
189
|
+
}
|
|
190
|
+
const inv = this.invNorms;
|
|
191
|
+
return inv === null ? s : s * inv[i1] * inv[i2];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
get_nearest_word(vec: WordVector | Float32Array): WordDist {
|
|
195
|
+
return this.search(to_values(vec), 1, null)[0];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
get_nearest_words(vec: WordVector | Float32Array, n = 10): WordDist[] {
|
|
199
|
+
return this.search(to_values(vec), n, null);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
most_similar(phrase: string, n = 40): WordDist[] | null {
|
|
203
|
+
const phrase_words = phrase.split(" ");
|
|
204
|
+
const phrase_set = new Set(phrase_words);
|
|
205
|
+
|
|
206
|
+
// Check whether at least one phrase word is in the dictionary...
|
|
207
|
+
let found = false;
|
|
208
|
+
for (const w of phrase_words) {
|
|
209
|
+
if (this.index.has(w)) found = true;
|
|
210
|
+
else console.log(`Out of dictionary word: ${w}`);
|
|
211
|
+
}
|
|
212
|
+
if (!found) return null;
|
|
213
|
+
|
|
214
|
+
// Sum the (unit) vectors of the in-dictionary phrase words...
|
|
215
|
+
const vec = new Float32Array(this.size);
|
|
216
|
+
for (const w of phrase_words) {
|
|
217
|
+
const i = this.index.get(w);
|
|
218
|
+
if (i !== undefined) this.unit_row(i, vec, true);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return this.search(vec, n, phrase_set);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
analogy(word: string, pair: [string, string], n = 40): WordDist[] {
|
|
225
|
+
if (typeof word !== "string") throw new TypeError("Word of interest has to be supplied as string.");
|
|
226
|
+
if (!Array.isArray(pair)) throw new TypeError("Word pair has to be supplied in string Array.");
|
|
227
|
+
|
|
228
|
+
const phrase = [pair[0], pair[1], word];
|
|
229
|
+
for (const w of phrase) {
|
|
230
|
+
if (!this.index.has(w)) console.log(`Out of dictionary word: ${w}`);
|
|
231
|
+
}
|
|
232
|
+
if (phrase.some((w) => !this.index.has(w)))
|
|
233
|
+
throw new Error("Words of the analogy must all be in the model vocabulary.");
|
|
234
|
+
|
|
235
|
+
// vec = pair[1] - pair[0] + word (unit vectors, as before)
|
|
236
|
+
const size = this.size;
|
|
237
|
+
const vec = new Float32Array(size);
|
|
238
|
+
const i0 = this.index.get(pair[0])!;
|
|
239
|
+
const i1 = this.index.get(pair[1])!;
|
|
240
|
+
const iw = this.index.get(word)!;
|
|
241
|
+
this.unit_row(i1, vec, false);
|
|
242
|
+
const tmp = new Float32Array(size);
|
|
243
|
+
this.unit_row(i0, tmp, false);
|
|
244
|
+
for (let a = 0; a < size; a++) vec[a] -= tmp[a];
|
|
245
|
+
this.unit_row(iw, vec, true);
|
|
246
|
+
|
|
247
|
+
const phrase_set = new Set(phrase);
|
|
248
|
+
return this.search(vec, n, phrase_set);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
get_zero_vector(): WordVector {
|
|
252
|
+
return new WordVector(null, new Float32Array(this.size));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Write the unit vector of row `i` into `out` (or accumulate into it when
|
|
257
|
+
* `accumulate` is set).
|
|
258
|
+
*/
|
|
259
|
+
private unit_row(i: number, out: Float32Array, accumulate: boolean): void {
|
|
260
|
+
const size = this.size;
|
|
261
|
+
const off = i * size;
|
|
262
|
+
const m = this.m;
|
|
263
|
+
if (this.precision === "i8") {
|
|
264
|
+
const f = this.i8Factors![i];
|
|
265
|
+
if (accumulate) for (let a = 0; a < size; a++) out[a] += m[off + a] * f;
|
|
266
|
+
else for (let a = 0; a < size; a++) out[a] = m[off + a] * f;
|
|
267
|
+
} else {
|
|
268
|
+
const inv = this.invNorms === null ? 1 : this.invNorms![i];
|
|
269
|
+
if (accumulate) for (let a = 0; a < size; a++) out[a] += m[off + a] * inv;
|
|
270
|
+
else for (let a = 0; a < size; a++) out[a] = m[off + a] * inv;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Rank all words against the query vector, returning the top `n`. */
|
|
275
|
+
private search(q: Float32Array, n: number, skip: Set<string> | null): WordDist[] {
|
|
276
|
+
const size = this.size;
|
|
277
|
+
const wordList = this.wordList;
|
|
278
|
+
const count = wordList.length;
|
|
279
|
+
const wordsOut = new Array<string>(n);
|
|
280
|
+
const distsOut = new Array<number>(n + 1);
|
|
281
|
+
let pos = 0;
|
|
282
|
+
|
|
283
|
+
if (this.precision === "i8") {
|
|
284
|
+
// Quantize the query to i8 with its own scale...
|
|
285
|
+
const m = this.m as Int8Array;
|
|
286
|
+
const f8 = this.i8Factors!;
|
|
287
|
+
let maxAbs = 0;
|
|
288
|
+
let normSq = 0;
|
|
289
|
+
for (let a = 0; a < size; a++) {
|
|
290
|
+
const v = q[a];
|
|
291
|
+
normSq += v * v;
|
|
292
|
+
const av = v < 0 ? -v : v;
|
|
293
|
+
if (av > maxAbs) maxAbs = av;
|
|
294
|
+
}
|
|
295
|
+
const qScale = maxAbs > 0 ? 127 / maxAbs : 1;
|
|
296
|
+
const qNorm = Math.sqrt(normSq) || 1;
|
|
297
|
+
const q8 = new Int8Array(size);
|
|
298
|
+
for (let a = 0; a < size; a++) {
|
|
299
|
+
let v = Math.round(q[a] * qScale);
|
|
300
|
+
if (v > 127) v = 127;
|
|
301
|
+
else if (v < -127) v = -127;
|
|
302
|
+
q8[a] = v;
|
|
303
|
+
}
|
|
304
|
+
// Dequantization factor of the query: 1/qScale, divided by the query
|
|
305
|
+
// norm since cosine = inner product / (|q| * |row|).
|
|
306
|
+
const qFactor = 1 / (qScale * qNorm);
|
|
307
|
+
for (let i = 0; i < count; i++) {
|
|
308
|
+
const off = i * size;
|
|
309
|
+
let s = 0;
|
|
310
|
+
for (let a = 0; a < size; a++) s += q8[a] * m[off + a];
|
|
311
|
+
const d = s * qFactor * f8[i];
|
|
312
|
+
if (skip !== null && skip.has(wordList[i])) continue;
|
|
313
|
+
pos = insert_topn(wordsOut, distsOut, pos, n, wordList[i], d);
|
|
314
|
+
}
|
|
315
|
+
} else {
|
|
316
|
+
const m = this.m as Float32Array | Float16Array;
|
|
317
|
+
const qf = normalize(q);
|
|
318
|
+
const inv = this.invNorms;
|
|
319
|
+
for (let i = 0; i < count; i++) {
|
|
320
|
+
const off = i * size;
|
|
321
|
+
let s = 0;
|
|
322
|
+
for (let a = 0; a < size; a++) s += qf[a] * m[off + a];
|
|
323
|
+
const d = inv === null ? s : s * inv[i];
|
|
324
|
+
if (skip !== null && skip.has(wordList[i])) continue;
|
|
325
|
+
pos = insert_topn(wordsOut, distsOut, pos, n, wordList[i], d);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const out: WordDist[] = new Array(n);
|
|
330
|
+
for (let i = 0; i < n; i++) {
|
|
331
|
+
out[i] = { word: i < pos ? wordsOut[i] : "", dist: i < pos ? distsOut[i] : -1 };
|
|
332
|
+
}
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Turn a fully parsed model (row-major `Buffer` matrix, word list, index)
|
|
339
|
+
* into a `WordModel`: computes norms, applies the requested normalization
|
|
340
|
+
* and precision, and wraps the result in a `MatrixModel`.
|
|
341
|
+
*/
|
|
342
|
+
export function finalize_model(
|
|
343
|
+
matrix: Buffer,
|
|
344
|
+
rows: number,
|
|
345
|
+
size: number,
|
|
346
|
+
words: string[],
|
|
347
|
+
index: Map<string, number>,
|
|
348
|
+
opts: ResolvedOptions,
|
|
349
|
+
): WordModel {
|
|
350
|
+
const total = rows * size;
|
|
351
|
+
|
|
352
|
+
// Release any allocation headroom beyond the rows we actually filled.
|
|
353
|
+
let data: Float32Array;
|
|
354
|
+
const usedBytes = total * 4;
|
|
355
|
+
if (matrix.length - usedBytes > 1 << 24) {
|
|
356
|
+
const trimmed = Buffer.from(matrix.subarray(0, usedBytes));
|
|
357
|
+
data = new Float32Array(trimmed.buffer, trimmed.byteOffset, total);
|
|
358
|
+
} else {
|
|
359
|
+
data = new Float32Array(matrix.buffer, matrix.byteOffset, total);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
let rawNorms: Float32Array | null = null;
|
|
363
|
+
if (opts.normalize) {
|
|
364
|
+
// Single in-place pass: normalize every row to unit length, so plain
|
|
365
|
+
// dot products are cosine similarities.
|
|
366
|
+
for (let r = 0; r < rows; r++) {
|
|
367
|
+
const off = r * size;
|
|
368
|
+
let n = 0;
|
|
369
|
+
for (let a = 0; a < size; a++) {
|
|
370
|
+
const v = data[off + a];
|
|
371
|
+
n += v * v;
|
|
372
|
+
}
|
|
373
|
+
n = Math.sqrt(n) || 1;
|
|
374
|
+
for (let a = 0; a < size; a++) data[off + a] /= n;
|
|
375
|
+
}
|
|
376
|
+
} else {
|
|
377
|
+
// Keep the raw per-row norms so cosine similarity can be recovered.
|
|
378
|
+
rawNorms = new Float32Array(rows);
|
|
379
|
+
for (let r = 0; r < rows; r++) {
|
|
380
|
+
const off = r * size;
|
|
381
|
+
let n = 0;
|
|
382
|
+
for (let a = 0; a < size; a++) {
|
|
383
|
+
const v = data[off + a];
|
|
384
|
+
n += v * v;
|
|
385
|
+
}
|
|
386
|
+
rawNorms[r] = Math.sqrt(n) || 1;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Convert to the requested storage precision.
|
|
391
|
+
let m: Float32Array | Float16Array | Int8Array = data;
|
|
392
|
+
let i8Scales: Float32Array | null = null;
|
|
393
|
+
if (opts.precision === "f16") {
|
|
394
|
+
m = new Float16Array(data);
|
|
395
|
+
} else if (opts.precision === "i8") {
|
|
396
|
+
// Per-row symmetric quantization to the range [-127, 127].
|
|
397
|
+
const q = new Int8Array(total);
|
|
398
|
+
i8Scales = new Float32Array(rows);
|
|
399
|
+
for (let r = 0; r < rows; r++) {
|
|
400
|
+
const off = r * size;
|
|
401
|
+
let max = 0;
|
|
402
|
+
for (let a = 0; a < size; a++) {
|
|
403
|
+
const v = data[off + a];
|
|
404
|
+
const av = v < 0 ? -v : v;
|
|
405
|
+
if (av > max) max = av;
|
|
406
|
+
}
|
|
407
|
+
const s = max > 0 ? 127 / max : 1;
|
|
408
|
+
// Store the dequantization factor (1/s): original value = stored value * factor.
|
|
409
|
+
i8Scales[r] = 1 / s;
|
|
410
|
+
for (let a = 0; a < size; a++) {
|
|
411
|
+
let v = Math.round(data[off + a] * s);
|
|
412
|
+
if (v > 127) v = 127;
|
|
413
|
+
else if (v < -127) v = -127;
|
|
414
|
+
q[off + a] = v;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
m = q;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return new MatrixModel({
|
|
421
|
+
matrix: m,
|
|
422
|
+
precision: opts.precision,
|
|
423
|
+
size,
|
|
424
|
+
words,
|
|
425
|
+
index,
|
|
426
|
+
normalized: opts.normalize,
|
|
427
|
+
rawNorms,
|
|
428
|
+
i8Scales,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Insert a candidate into the descending top-`n` lists using binary
|
|
434
|
+
* insertion. `distsOut` must have `n + 1` slots (the last one is scratch).
|
|
435
|
+
* Non-finite distances are skipped (rows containing NaN are garbage).
|
|
436
|
+
* Returns the new number of entries.
|
|
437
|
+
*/
|
|
438
|
+
function insert_topn(wordsOut: string[], distsOut: number[], pos: number, n: number, word: string, d: number): number {
|
|
439
|
+
if (!Number.isFinite(d)) return pos;
|
|
440
|
+
const cap = pos < n ? pos : n;
|
|
441
|
+
if (cap === n && d <= distsOut[n - 1]) return pos; // not better than the worst of the top n
|
|
442
|
+
// Find the first slot holding a value < d (the list is kept descending).
|
|
443
|
+
let lo = 0;
|
|
444
|
+
let hi = cap;
|
|
445
|
+
while (lo < hi) {
|
|
446
|
+
const mid = (lo + hi) >> 1;
|
|
447
|
+
if (distsOut[mid] >= d) lo = mid + 1;
|
|
448
|
+
else hi = mid;
|
|
449
|
+
}
|
|
450
|
+
for (let i = cap - 1; i >= lo; i--) {
|
|
451
|
+
distsOut[i + 1] = distsOut[i];
|
|
452
|
+
wordsOut[i + 1] = wordsOut[i];
|
|
453
|
+
}
|
|
454
|
+
distsOut[lo] = d;
|
|
455
|
+
wordsOut[lo] = word;
|
|
456
|
+
return pos < n ? pos + 1 : n;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function to_values(vec: WordVector | Float32Array): Float32Array {
|
|
460
|
+
return vec instanceof WordVector ? vec.values : vec;
|
|
461
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Type declarations for the plain-JS module `parse_fast.mjs`. */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parse `out.length` space-separated floats from `buf[start .. end)` into
|
|
5
|
+
* `out`. Returns the position just past the last parsed number. Results are
|
|
6
|
+
* bit-identical to `parseFloat` for plain decimals with <= 15 significant
|
|
7
|
+
* digits.
|
|
8
|
+
*/
|
|
9
|
+
export function parse_floats(buf: Buffer, start: number, end: number, out: Float32Array | Float64Array): number;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Incremental single-value parser wrapping `parse_floats`. The result keeps
|
|
13
|
+
* full float64 precision.
|
|
14
|
+
*/
|
|
15
|
+
export class FloatParser {
|
|
16
|
+
/** Position of the next character to parse (set before calling `next`). */
|
|
17
|
+
pos: number;
|
|
18
|
+
/**
|
|
19
|
+
* Parse the next space-separated float from `buf[pos .. end)`.
|
|
20
|
+
* Advances `pos` to just past the parsed number.
|
|
21
|
+
*/
|
|
22
|
+
next(buf: Buffer, end: number): number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* String-based twin of `parse_floats` (same algorithm, bit-identical
|
|
27
|
+
* results): parses `out.length` space-separated floats from `line[start ..)`
|
|
28
|
+
* into `out`.
|
|
29
|
+
*/
|
|
30
|
+
export function parse_floats_str(line: string, start: number, out: Float32Array): number;
|