@scinorandex/embeddings 0.0.0-stage → 0.0.1
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 +121 -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 +4 -0
- package/dist/index.js +21 -0
- package/dist/index.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 +140 -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 +4 -0
- package/src/models/glove.ts +521 -0
- package/src/models/glove_worker.mjs +140 -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/glove.ts +13 -0
- package/test/word2vec.ts +13 -0
- package/tsconfig.build.json +31 -0
- package/tsconfig.json +30 -0
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Worker } from "node:worker_threads";
|
|
5
|
+
import { parse_floats_str } from "./parse_fast.mjs";
|
|
6
|
+
import { finalize_model, resolve_options, type LoadOptions, type ResolvedOptions } from "./matrix";
|
|
7
|
+
import type { WordModel } from "../common";
|
|
8
|
+
|
|
9
|
+
/** Cache of already-loaded models, keyed by path + options. */
|
|
10
|
+
const glove_cache = new Map<string, WordModel>();
|
|
11
|
+
|
|
12
|
+
const EMPTY = Buffer.alloc(0);
|
|
13
|
+
const CACHE_MAGIC = "GLOVEBIN";
|
|
14
|
+
const CACHE_HEADER = 20;
|
|
15
|
+
/** Files below this size are parsed sequentially (workers would not pay off). */
|
|
16
|
+
const PARALLEL_MIN_BYTES = 64 << 20;
|
|
17
|
+
/** Maximum number of worker threads used for parallel parsing. */
|
|
18
|
+
const MAX_WORKERS = 8;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Load a GloVe model from a plain-text `.txt` file.
|
|
22
|
+
*
|
|
23
|
+
* The file has one word per line, followed by its space-separated vector
|
|
24
|
+
* values (no header line): `word v1 v2 ... v300`. The dimensionality is taken
|
|
25
|
+
* from the first line.
|
|
26
|
+
*
|
|
27
|
+
* Fast loading notes:
|
|
28
|
+
* - Large files are parsed in parallel: the file is split into byte ranges
|
|
29
|
+
* that are handled by worker threads (up to `os.availableParallelism()`,
|
|
30
|
+
* capped at 8).
|
|
31
|
+
* - Each line is decoded to a string once, and its values are parsed with a
|
|
32
|
+
* hand-rolled scanner (no `split`, no per-token allocations, no
|
|
33
|
+
* `parseFloat` in the hot path; results are bit-identical to `parseFloat`).
|
|
34
|
+
* - Values are parsed directly into the rows of one contiguous row-major
|
|
35
|
+
* matrix (no per-word `Float32Array` + `WordVector` objects, no per-row
|
|
36
|
+
* copy), which saves hundreds of MB of object overhead for large
|
|
37
|
+
* vocabularies.
|
|
38
|
+
* - With `cache: true`, the parsed model is stored in a compact binary
|
|
39
|
+
* sibling file (`<path>` with `.txt` replaced by `.glovecache`) and reused
|
|
40
|
+
* on later loads, turning the text parse into a fast binary read.
|
|
41
|
+
*
|
|
42
|
+
* Before using make sure the GloVe 840B 300d model is downloaded.
|
|
43
|
+
* `wget https://nlp.stanford.edu/projects/glove/glove.840B.300d.txt`
|
|
44
|
+
*/
|
|
45
|
+
export async function load_glove(model_path: string, options?: LoadOptions): Promise<WordModel> {
|
|
46
|
+
const opts = resolve_options(options);
|
|
47
|
+
const key = model_path + "\u0000" + JSON.stringify(opts);
|
|
48
|
+
const cached = glove_cache.get(key);
|
|
49
|
+
if (cached) return cached;
|
|
50
|
+
|
|
51
|
+
// With `cache: true`, a parsed binary model is kept next to the source file
|
|
52
|
+
// and reused when it is at least as new as the source.
|
|
53
|
+
let cache_path: string | null = null;
|
|
54
|
+
if (opts.cache) {
|
|
55
|
+
cache_path = model_path.endsWith(".txt") ? model_path.slice(0, -4) + ".glovecache" : model_path + ".glovecache";
|
|
56
|
+
let fresh = false;
|
|
57
|
+
try {
|
|
58
|
+
const src_stat = await fs.promises.stat(model_path);
|
|
59
|
+
const cstat = await fs.promises.stat(cache_path);
|
|
60
|
+
if (cstat.mtimeMs >= src_stat.mtimeMs) fresh = true;
|
|
61
|
+
} catch {
|
|
62
|
+
// No cache yet (or unreadable): parse and (re)build.
|
|
63
|
+
}
|
|
64
|
+
if (fresh) {
|
|
65
|
+
try {
|
|
66
|
+
const model = await read_glove_cache(cache_path, opts);
|
|
67
|
+
glove_cache.set(key, model);
|
|
68
|
+
return model;
|
|
69
|
+
} catch {
|
|
70
|
+
// Corrupt or truncated cache: fall through and rebuild from the text.
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let fileSize = 0;
|
|
76
|
+
try {
|
|
77
|
+
fileSize = (await fs.promises.stat(model_path)).size;
|
|
78
|
+
} catch {
|
|
79
|
+
// Unknown size: the sequential loader grows the matrix as needed.
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (fileSize >= PARALLEL_MIN_BYTES && opts.limit === undefined && os.availableParallelism() > 1) {
|
|
83
|
+
try {
|
|
84
|
+
const parsed = await parse_glove_parallel(model_path, fileSize);
|
|
85
|
+
return await build_model(parsed, opts, cache_path, key);
|
|
86
|
+
} catch (err) {
|
|
87
|
+
// Worker trouble (e.g. a pathological line): fall back to sequential.
|
|
88
|
+
if (err instanceof Error && err.message.startsWith("Incomplete model file")) throw err;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return load_glove_sequential(model_path, fileSize, opts, cache_path, key);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Parsed model, ready to be wrapped by `finalize_model`. */
|
|
96
|
+
interface ParsedGlove {
|
|
97
|
+
matrix: Buffer; // raw float32 rows, `rows * size * 4` bytes
|
|
98
|
+
rows: number;
|
|
99
|
+
size: number;
|
|
100
|
+
words: string[];
|
|
101
|
+
index: Map<string, number>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Shared tail: optionally persist a cache, finalize, memoize, return. */
|
|
105
|
+
async function build_model(
|
|
106
|
+
parsed: ParsedGlove,
|
|
107
|
+
opts: ResolvedOptions,
|
|
108
|
+
cache_path: string | null,
|
|
109
|
+
key: string,
|
|
110
|
+
): Promise<WordModel> {
|
|
111
|
+
// The cache stores the RAW vectors, so it must be written before
|
|
112
|
+
// `finalize_model` rewrites the matrix in place.
|
|
113
|
+
if (cache_path !== null) {
|
|
114
|
+
await write_glove_cache(cache_path, parsed.size, parsed.rows, parsed.matrix, parsed.words);
|
|
115
|
+
}
|
|
116
|
+
const model = finalize_model(parsed.matrix, parsed.rows, parsed.size, parsed.words, parsed.index, opts);
|
|
117
|
+
glove_cache.set(key, model);
|
|
118
|
+
return model;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Parse the file in parallel. The first 1 MiB is probed in the main thread
|
|
123
|
+
* to learn the dimensionality and the average line length; the file is then
|
|
124
|
+
* split into `n` byte ranges, each parsed by a worker thread. Boundary lines
|
|
125
|
+
* are parsed by both adjacent workers, so the merge dedups them ("first
|
|
126
|
+
* occurrence keeps the row, last occurrence wins the values"), which is
|
|
127
|
+
* exactly the sequential semantics.
|
|
128
|
+
*/
|
|
129
|
+
async function parse_glove_parallel(model_path: string, fileSize: number): Promise<ParsedGlove> {
|
|
130
|
+
const probeLen = Math.min(1 << 20, fileSize);
|
|
131
|
+
const probe = Buffer.alloc(probeLen);
|
|
132
|
+
const fd0 = await fs.promises.open(model_path, "r");
|
|
133
|
+
let probed = 0;
|
|
134
|
+
while (probed < probeLen) {
|
|
135
|
+
const r = await fd0.read(probe, probed, probeLen - probed, probed);
|
|
136
|
+
if (r.bytesRead === 0) break;
|
|
137
|
+
probed += r.bytesRead;
|
|
138
|
+
}
|
|
139
|
+
await fd0.close();
|
|
140
|
+
if (probed === 0) throw new Error("Incomplete model file (empty)");
|
|
141
|
+
const firstNl = probe.indexOf(0x0a, 0, probed);
|
|
142
|
+
if (firstNl === -1) throw new Error("Incomplete model file (no complete line)");
|
|
143
|
+
const firstLine = probe.toString("utf8", 0, firstNl);
|
|
144
|
+
const sp = firstLine.indexOf(" ");
|
|
145
|
+
if (sp === -1 || sp === firstLine.length - 1) throw new Error("Incomplete model file (no vector data)");
|
|
146
|
+
let size = 0;
|
|
147
|
+
for (let q = sp; q < firstLine.length; q++) if (firstLine.charCodeAt(q) === 32) size++;
|
|
148
|
+
if (size === 0) throw new Error("Incomplete model file (no vector data)");
|
|
149
|
+
let nl_count = 0;
|
|
150
|
+
for (let q = 0; q < probed; q++) if (probe[q] === 0x0a) nl_count++;
|
|
151
|
+
const avgLine = probed / nl_count;
|
|
152
|
+
|
|
153
|
+
const n = Math.min(os.availableParallelism(), MAX_WORKERS);
|
|
154
|
+
const ranges: Array<[number, number]> = [];
|
|
155
|
+
for (let i = 0; i < n; i++) {
|
|
156
|
+
const a = Math.floor((fileSize * i) / n);
|
|
157
|
+
const b = i === n - 1 ? fileSize : Math.floor((fileSize * (i + 1)) / n);
|
|
158
|
+
ranges.push([a, b]);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const worker_path = path.join(__dirname, "glove_worker.mjs");
|
|
162
|
+
const estRowsFor = (a: number, b: number) => Math.max(1, Math.ceil((b - a) / avgLine) + 2);
|
|
163
|
+
|
|
164
|
+
// Collect results per worker slot (merge must happen in worker order ==
|
|
165
|
+
// file order); terminate each worker as soon as its result arrives.
|
|
166
|
+
const slots: any[] = new Array(ranges.length);
|
|
167
|
+
const exited: Array<Promise<void>> = [];
|
|
168
|
+
let pending = ranges.length;
|
|
169
|
+
await new Promise<void>((resolveAll, rejectAll) => {
|
|
170
|
+
ranges.forEach(([a, b], k) => {
|
|
171
|
+
const w = new Worker(worker_path, {
|
|
172
|
+
workerData: { path: model_path, start: a, end: b, dims: size, estRows: estRowsFor(a, b) },
|
|
173
|
+
resourceLimits: { maxOldGenerationSizeMb: 1024 },
|
|
174
|
+
});
|
|
175
|
+
let exitRes: () => void;
|
|
176
|
+
exited.push(
|
|
177
|
+
new Promise<void>((res) => {
|
|
178
|
+
exitRes = res;
|
|
179
|
+
}),
|
|
180
|
+
);
|
|
181
|
+
w.on("exit", (code) => {
|
|
182
|
+
exitRes();
|
|
183
|
+
if (slots[k] === undefined) rejectAll(new Error(`GloVe worker exited with code ${code} before completing`));
|
|
184
|
+
});
|
|
185
|
+
w.on("message", (res: any) => {
|
|
186
|
+
slots[k] = res;
|
|
187
|
+
w.terminate();
|
|
188
|
+
if (--pending === 0) resolveAll();
|
|
189
|
+
});
|
|
190
|
+
w.on("error", (err) => {
|
|
191
|
+
if (slots[k] === undefined) rejectAll(err);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
// Wait for the worker threads to fully terminate, so their isolates (a few
|
|
196
|
+
// hundred MB each) are released before the model is handed back.
|
|
197
|
+
await Promise.all(exited);
|
|
198
|
+
|
|
199
|
+
// Merge the worker results (in range order == file order).
|
|
200
|
+
const rows_total = slots.reduce((s: number, r: any) => s + r.rows, 0);
|
|
201
|
+
if (rows_total === 0) throw new Error("Incomplete model file (no complete line)");
|
|
202
|
+
const rowBytes = size * 4;
|
|
203
|
+
const merged = Buffer.alloc(rows_total * rowBytes);
|
|
204
|
+
const words_all: string[] = new Array<string>(rows_total);
|
|
205
|
+
let cursor = 0;
|
|
206
|
+
for (let k = 0; k < slots.length; k++) {
|
|
207
|
+
const res = slots[k];
|
|
208
|
+
const rb = Buffer.from(res.buf);
|
|
209
|
+
// The worker's buffer may carry pre-allocation headroom: copy only the
|
|
210
|
+
// rows it actually parsed.
|
|
211
|
+
rb.copy(merged, cursor * rowBytes, 0, res.rows * rowBytes);
|
|
212
|
+
for (let i = 0; i < res.words.length; i++) words_all[cursor + i] = res.words[i];
|
|
213
|
+
cursor += res.rows;
|
|
214
|
+
slots[k] = null; // release the worker's buffer
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Global index; boundary lines appear in two adjacent workers, so dedup
|
|
218
|
+
// in place with "first occurrence keeps the row, last occurrence wins the
|
|
219
|
+
// values" (exactly the sequential semantics; no extra buffer is needed).
|
|
220
|
+
const index = new Map<string, number>();
|
|
221
|
+
let dups = 0;
|
|
222
|
+
for (let i = 0; i < rows_total; i++) {
|
|
223
|
+
const w = words_all[i];
|
|
224
|
+
if (index.has(w)) dups++;
|
|
225
|
+
else index.set(w, i);
|
|
226
|
+
}
|
|
227
|
+
let rows = rows_total;
|
|
228
|
+
if (dups > 0) {
|
|
229
|
+
index.clear();
|
|
230
|
+
let outRow = 0;
|
|
231
|
+
for (let i = 0; i < rows_total; i++) {
|
|
232
|
+
const w = words_all[i];
|
|
233
|
+
const existing = index.get(w);
|
|
234
|
+
if (existing === undefined) {
|
|
235
|
+
index.set(w, outRow);
|
|
236
|
+
if (outRow !== i) {
|
|
237
|
+
words_all[outRow] = w;
|
|
238
|
+
merged.copyWithin(outRow * rowBytes, i * rowBytes, (i + 1) * rowBytes);
|
|
239
|
+
}
|
|
240
|
+
outRow++;
|
|
241
|
+
} else {
|
|
242
|
+
merged.copyWithin(existing * rowBytes, i * rowBytes, (i + 1) * rowBytes); // later values win
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
rows = outRow;
|
|
246
|
+
words_all.length = outRow;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return { matrix: merged.subarray(0, rows * rowBytes), rows, size, words: words_all, index };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Sequential streaming parse (small files, `limit`, or worker fallback). */
|
|
253
|
+
function load_glove_sequential(
|
|
254
|
+
model_path: string,
|
|
255
|
+
fileSize: number,
|
|
256
|
+
opts: ResolvedOptions,
|
|
257
|
+
cache_path: string | null,
|
|
258
|
+
key: string,
|
|
259
|
+
): Promise<WordModel> {
|
|
260
|
+
return new Promise((resolve, reject) => {
|
|
261
|
+
const read_stream = fs.createReadStream(model_path, { highWaterMark: 1 << 22 });
|
|
262
|
+
|
|
263
|
+
let vector_size = 0;
|
|
264
|
+
let rows = 0;
|
|
265
|
+
let capacity = 0;
|
|
266
|
+
let matrix = EMPTY;
|
|
267
|
+
const words: string[] = [];
|
|
268
|
+
const index = new Map<string, number>();
|
|
269
|
+
let tail = EMPTY; // trailing partial line awaiting more data
|
|
270
|
+
let first_chunk = true;
|
|
271
|
+
let stopped = false;
|
|
272
|
+
let resolved = false;
|
|
273
|
+
|
|
274
|
+
const finish = () => {
|
|
275
|
+
if (resolved) return;
|
|
276
|
+
resolved = true;
|
|
277
|
+
if (vector_size === 0) {
|
|
278
|
+
reject(new Error("Incomplete model file (no complete line)"));
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
(async () => {
|
|
282
|
+
try {
|
|
283
|
+
const model = await build_model({ matrix, rows, size: vector_size, words, index }, opts, cache_path, key);
|
|
284
|
+
matrix = EMPTY; // drop the closure's reference to the matrix buffer
|
|
285
|
+
read_stream.removeAllListeners();
|
|
286
|
+
resolve(model);
|
|
287
|
+
} catch (err) {
|
|
288
|
+
reject(err);
|
|
289
|
+
}
|
|
290
|
+
})();
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const ensure_rows = (need: number) => {
|
|
294
|
+
if (need <= capacity) return;
|
|
295
|
+
// Grow by 12.5% (not double) to keep over-allocation -- and any later
|
|
296
|
+
// trim copy -- small.
|
|
297
|
+
const newCap = Math.max(need, capacity + Math.ceil(capacity / 8));
|
|
298
|
+
const newMatrix = Buffer.alloc(newCap * vector_size * 4);
|
|
299
|
+
matrix.copy(newMatrix, 0);
|
|
300
|
+
matrix = newMatrix;
|
|
301
|
+
capacity = newCap;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const parse_line = (line: string) => {
|
|
305
|
+
const sp = line.indexOf(" ");
|
|
306
|
+
if (sp === -1 || sp === line.length - 1) return; // no vector data on this line
|
|
307
|
+
|
|
308
|
+
const word = line.slice(0, sp);
|
|
309
|
+
if (vector_size === 0) {
|
|
310
|
+
// No header line: the first line determines the dimensionality.
|
|
311
|
+
// `word v1 ... vn` has exactly n spaces after the word.
|
|
312
|
+
let fields = 0;
|
|
313
|
+
for (let q = sp; q < line.length; q++) if (line.charCodeAt(q) === 32) fields++;
|
|
314
|
+
vector_size = fields;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const existing = index.get(word);
|
|
318
|
+
const isNew = existing === undefined;
|
|
319
|
+
const r = isNew ? rows : existing;
|
|
320
|
+
if (isNew) {
|
|
321
|
+
ensure_rows(rows + 1);
|
|
322
|
+
index.set(word, r);
|
|
323
|
+
words.push(word);
|
|
324
|
+
rows++;
|
|
325
|
+
}
|
|
326
|
+
// Parse the values directly into the row's slot in the matrix
|
|
327
|
+
// (zero extra copies; duplicates overwrite the same row, last wins).
|
|
328
|
+
const m = matrix;
|
|
329
|
+
const rrow = new Float32Array(m.buffer, m.byteOffset + r * vector_size * 4, vector_size);
|
|
330
|
+
parse_floats_str(line, sp + 1, rrow);
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
const process_chunk = (buf: Buffer, start: number) => {
|
|
334
|
+
let lineStart = start;
|
|
335
|
+
while (lineStart < buf.length && !stopped) {
|
|
336
|
+
const nl = buf.indexOf(0x0a, lineStart);
|
|
337
|
+
if (nl === -1) {
|
|
338
|
+
tail = Buffer.from(buf.subarray(lineStart)); // line split across chunks
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
let end = nl;
|
|
342
|
+
if (end > lineStart && buf[end - 1] === 13) end--; // tolerate CRLF
|
|
343
|
+
if (end > lineStart) {
|
|
344
|
+
if (opts.limit !== undefined && rows >= opts.limit) {
|
|
345
|
+
stopped = true;
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
parse_line(buf.toString("utf8", lineStart, end));
|
|
349
|
+
}
|
|
350
|
+
lineStart = nl + 1;
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
read_stream.on("data", (chunk: Buffer) => {
|
|
355
|
+
if (stopped) return;
|
|
356
|
+
|
|
357
|
+
if (tail.length > 0) {
|
|
358
|
+
const nl = chunk.indexOf(0x0a);
|
|
359
|
+
if (nl === -1) {
|
|
360
|
+
tail = Buffer.concat([tail, chunk]); // whole chunk extends the partial line
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const line = Buffer.allocUnsafe(tail.length + nl);
|
|
364
|
+
tail.copy(line, 0);
|
|
365
|
+
chunk.copy(line, tail.length, 0, nl);
|
|
366
|
+
tail = EMPTY;
|
|
367
|
+
let lineEnd = line.length;
|
|
368
|
+
if (lineEnd > 0 && line[lineEnd - 1] === 13) lineEnd--; // tolerate CRLF
|
|
369
|
+
if (opts.limit === undefined || rows < opts.limit) parse_line(line.toString("utf8", 0, lineEnd));
|
|
370
|
+
// Continue with the rest of the chunk, after the line we just completed.
|
|
371
|
+
process_chunk(chunk, nl + 1);
|
|
372
|
+
} else {
|
|
373
|
+
process_chunk(chunk, 0);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (first_chunk) {
|
|
377
|
+
first_chunk = false;
|
|
378
|
+
// Estimate the total row count from the average line length of the
|
|
379
|
+
// first chunk, so the matrix is (almost) pre-allocated exactly once.
|
|
380
|
+
if (fileSize > 0 && vector_size > 0) {
|
|
381
|
+
let nl_count = 0;
|
|
382
|
+
for (let q = 0; q < chunk.length; q++) if (chunk[q] === 0x0a) nl_count++;
|
|
383
|
+
if (nl_count > 0) {
|
|
384
|
+
const est = Math.ceil(fileSize / (chunk.length / nl_count));
|
|
385
|
+
ensure_rows(opts.limit !== undefined ? Math.min(est, opts.limit) : est);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (stopped) read_stream.destroy();
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
read_stream.on("end", finish);
|
|
394
|
+
read_stream.on("close", finish);
|
|
395
|
+
read_stream.on("error", (err: any) => {
|
|
396
|
+
// Ignore the error raised by an intentional destroy due to `limit`...
|
|
397
|
+
if (stopped) finish();
|
|
398
|
+
else reject(err);
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Read a GloVe binary cache file:
|
|
405
|
+
*
|
|
406
|
+
* 0: magic "GLOVEBIN" (8 bytes)
|
|
407
|
+
* 8: dims (u32 LE)
|
|
408
|
+
* 12: rows (u32 LE)
|
|
409
|
+
* 16: word-section byte size (u32 LE)
|
|
410
|
+
* 20: matrix, rows * dims * 4 bytes of little-endian float32 (raw values)
|
|
411
|
+
* ... word section: per word, u32 LE byte length + UTF-8 bytes
|
|
412
|
+
*/
|
|
413
|
+
async function read_glove_cache(path: string, opts: ResolvedOptions): Promise<WordModel> {
|
|
414
|
+
const stat = await fs.promises.stat(path);
|
|
415
|
+
const fd = await fs.promises.open(path, "r");
|
|
416
|
+
try {
|
|
417
|
+
// Node's fs read/write plumbing 32-bit limits single operations to 2 GiB,
|
|
418
|
+
// so bound each syscall to 1 GiB.
|
|
419
|
+
const MAX_IO = 1 << 30;
|
|
420
|
+
const readFull = async (buf: Buffer, off: number, len: number) => {
|
|
421
|
+
let got = 0;
|
|
422
|
+
while (got < len) {
|
|
423
|
+
const r = await fd.read(buf, got, Math.min(MAX_IO, len - got), off + got);
|
|
424
|
+
if (r.bytesRead === 0) throw new Error("Unexpected end of GloVe cache file");
|
|
425
|
+
got += r.bytesRead;
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const header = Buffer.alloc(CACHE_HEADER);
|
|
430
|
+
await readFull(header, 0, CACHE_HEADER);
|
|
431
|
+
if (header.toString("ascii", 0, 8) !== CACHE_MAGIC) throw new Error("Not a GloVe cache file");
|
|
432
|
+
const dims = header.readUInt32LE(8);
|
|
433
|
+
const rows = header.readUInt32LE(12);
|
|
434
|
+
const n = opts.limit !== undefined ? Math.min(opts.limit, rows) : rows;
|
|
435
|
+
|
|
436
|
+
const matrix_bytes = n * dims * 4;
|
|
437
|
+
const matrix = Buffer.alloc(matrix_bytes);
|
|
438
|
+
await readFull(matrix, CACHE_HEADER, matrix_bytes);
|
|
439
|
+
// The word section lives after the full (all-rows) matrix; only the first
|
|
440
|
+
// `n` entries are needed, so read a growing budget until they are covered.
|
|
441
|
+
const ws_off = CACHE_HEADER + rows * dims * 4;
|
|
442
|
+
let budget = Math.min(n * 64 + 64, stat.size - ws_off);
|
|
443
|
+
let words: string[] = [];
|
|
444
|
+
for (;;) {
|
|
445
|
+
const ws = Buffer.alloc(budget);
|
|
446
|
+
await readFull(ws, ws_off, budget);
|
|
447
|
+
words = [];
|
|
448
|
+
let off = 0;
|
|
449
|
+
let ok = true;
|
|
450
|
+
for (let i = 0; i < n; i++) {
|
|
451
|
+
if (off + 4 > budget) break; // ok stays false
|
|
452
|
+
const len = ws.readUInt32LE(off);
|
|
453
|
+
if (off + 4 + len > budget) {
|
|
454
|
+
ok = false;
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
words.push(ws.toString("utf8", off + 4, off + 4 + len));
|
|
458
|
+
off += 4 + len;
|
|
459
|
+
}
|
|
460
|
+
if (ok || budget >= stat.size - ws_off) break;
|
|
461
|
+
budget = Math.min(budget * 4, stat.size - ws_off);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const index = new Map<string, number>();
|
|
465
|
+
for (let i = 0; i < n; i++) index.set(words[i], i);
|
|
466
|
+
return finalize_model(matrix, n, dims, words, index, opts);
|
|
467
|
+
} finally {
|
|
468
|
+
await fd.close();
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Write the raw (unnormalized) parsed model to a cache file, atomically. */
|
|
473
|
+
async function write_glove_cache(
|
|
474
|
+
path: string,
|
|
475
|
+
dims: number,
|
|
476
|
+
rows: number,
|
|
477
|
+
matrix: Buffer,
|
|
478
|
+
words: string[],
|
|
479
|
+
): Promise<void> {
|
|
480
|
+
const header = Buffer.alloc(CACHE_HEADER);
|
|
481
|
+
header.write(CACHE_MAGIC, 0, 8, "ascii");
|
|
482
|
+
header.writeUInt32LE(dims, 8);
|
|
483
|
+
header.writeUInt32LE(rows, 12);
|
|
484
|
+
let word_bytes = 0;
|
|
485
|
+
for (const w of words) word_bytes += Buffer.byteLength(w, "utf8");
|
|
486
|
+
header.writeUInt32LE(word_bytes, 16);
|
|
487
|
+
const matrix_bytes = rows * dims * 4;
|
|
488
|
+
|
|
489
|
+
const ws = Buffer.alloc(word_bytes + rows * 4);
|
|
490
|
+
let off = 0;
|
|
491
|
+
for (const w of words) {
|
|
492
|
+
const bl = Buffer.byteLength(w, "utf8");
|
|
493
|
+
ws.writeUInt32LE(bl, off);
|
|
494
|
+
off += 4;
|
|
495
|
+
ws.write(w, off, "utf8");
|
|
496
|
+
off += bl;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const tmp = path + ".tmp";
|
|
500
|
+
// Write in <= 1 GiB operations: Node's writev path 32-bit-limits a single
|
|
501
|
+
// operation to 2 GiB, and the matrix alone is larger than that.
|
|
502
|
+
const MAX_IO = 1 << 30;
|
|
503
|
+
const fd = await fs.promises.open(tmp, "w");
|
|
504
|
+
try {
|
|
505
|
+
const writeFull = async (buf: Buffer, off: number, len: number, pos: number) => {
|
|
506
|
+
let written = 0;
|
|
507
|
+
while (written < len) {
|
|
508
|
+
const r = await fd.write(buf, off + written, Math.min(MAX_IO, len - written), pos + written);
|
|
509
|
+
written += r.bytesWritten;
|
|
510
|
+
}
|
|
511
|
+
return pos + len;
|
|
512
|
+
};
|
|
513
|
+
let pos = 0;
|
|
514
|
+
pos = await writeFull(header, 0, header.length, pos);
|
|
515
|
+
pos = await writeFull(matrix, 0, matrix_bytes, pos);
|
|
516
|
+
pos = await writeFull(ws, 0, ws.length, pos);
|
|
517
|
+
} finally {
|
|
518
|
+
await fd.close();
|
|
519
|
+
}
|
|
520
|
+
await fs.promises.rename(tmp, path);
|
|
521
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker thread that parses one byte range of a GloVe text file into a
|
|
3
|
+
* row-major float32 matrix plus a word list. Spawned by `glove.ts` to parse
|
|
4
|
+
* large files in parallel.
|
|
5
|
+
*
|
|
6
|
+
* Line ownership: a line belongs to the worker whose range contains the
|
|
7
|
+
* line's start position. Each worker therefore reads a small pre-window
|
|
8
|
+
* before its range start to find the boundary line, and it also parses its
|
|
9
|
+
* trailing partial line (which may be truncated at the range end). Lines
|
|
10
|
+
* that cross a boundary are parsed by both adjacent workers; the main thread
|
|
11
|
+
* merges the results with "first occurrence, last values" dedup, which
|
|
12
|
+
* yields exactly the same model as a sequential parse.
|
|
13
|
+
*
|
|
14
|
+
* This file is plain JS (no TS) on purpose: worker threads do not run tsx's
|
|
15
|
+
* loader in this package, and a `.mjs` file loads natively in every context.
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
19
|
+
import { parse_floats_str } from "./parse_fast.mjs";
|
|
20
|
+
|
|
21
|
+
const task = workerData;
|
|
22
|
+
const { path: file_path, start, end, dims } = task;
|
|
23
|
+
const PRE = 1 << 20; // pre-window: lines longer than this trip the sequential fallback
|
|
24
|
+
const CHUNK = 1 << 23;
|
|
25
|
+
|
|
26
|
+
const words = [];
|
|
27
|
+
const index = new Map(); // local (in-range) dedup
|
|
28
|
+
let capacity = task.estRows;
|
|
29
|
+
let matrix = Buffer.alloc(capacity * dims * 4);
|
|
30
|
+
let rows = 0;
|
|
31
|
+
let tail = null; // trailing partial line
|
|
32
|
+
|
|
33
|
+
const ensure = (need) => {
|
|
34
|
+
if (need <= capacity) return;
|
|
35
|
+
const newCap = Math.max(need, capacity + Math.ceil(capacity / 8));
|
|
36
|
+
const m = Buffer.alloc(newCap * dims * 4);
|
|
37
|
+
matrix.copy(m, 0);
|
|
38
|
+
matrix = m;
|
|
39
|
+
capacity = newCap;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const parseLine = (line) => {
|
|
43
|
+
const sp = line.indexOf(" ");
|
|
44
|
+
if (sp === -1 || sp === line.length - 1) return; // no vector data on this line
|
|
45
|
+
const word = line.slice(0, sp);
|
|
46
|
+
const existing = index.get(word);
|
|
47
|
+
const isNew = existing === undefined;
|
|
48
|
+
const r = isNew ? rows : existing;
|
|
49
|
+
if (isNew) {
|
|
50
|
+
ensure(rows + 1);
|
|
51
|
+
index.set(word, r);
|
|
52
|
+
words.push(word);
|
|
53
|
+
rows++;
|
|
54
|
+
}
|
|
55
|
+
// Parse directly into the row's slot of the matrix (no per-row copy).
|
|
56
|
+
const m = matrix;
|
|
57
|
+
const rrow = new Float32Array(m.buffer, m.byteOffset + r * dims * 4, dims);
|
|
58
|
+
parse_floats_str(line, sp + 1, rrow);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const processBuf = (buf, lineStart, r) => {
|
|
62
|
+
while (lineStart < r) {
|
|
63
|
+
const nl = buf.indexOf(0x0a, lineStart);
|
|
64
|
+
if (nl === -1) {
|
|
65
|
+
tail = Buffer.from(buf.subarray(lineStart, r));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
let e = nl;
|
|
69
|
+
if (e > lineStart && buf[e - 1] === 13) e--; // tolerate CRLF
|
|
70
|
+
if (e > lineStart) parseLine(buf.toString("utf8", lineStart, e));
|
|
71
|
+
lineStart = nl + 1;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const readStart = start === 0 ? 0 : start - PRE;
|
|
76
|
+
const fd = fs.openSync(file_path, "r");
|
|
77
|
+
try {
|
|
78
|
+
// Locate the first line this worker owns: just after the last \n before
|
|
79
|
+
// `start` (scan the pre-window, at most 1 MiB, in one buffer).
|
|
80
|
+
let firstOwned = readStart;
|
|
81
|
+
if (start > 0) {
|
|
82
|
+
const winLen = start - readStart;
|
|
83
|
+
const win = Buffer.alloc(winLen);
|
|
84
|
+
let got = 0;
|
|
85
|
+
while (got < winLen) {
|
|
86
|
+
const r = fs.readSync(fd, win, got, winLen - got, readStart + got);
|
|
87
|
+
if (r === 0) break;
|
|
88
|
+
got += r;
|
|
89
|
+
}
|
|
90
|
+
let lastNl = -1;
|
|
91
|
+
for (let p = got - 1; p >= 0; p--) {
|
|
92
|
+
if (win[p] === 0x0a) {
|
|
93
|
+
lastNl = readStart + p;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (lastNl === -1) {
|
|
98
|
+
throw new Error("GloVe line longer than 1 MiB crosses a worker boundary");
|
|
99
|
+
}
|
|
100
|
+
firstOwned = lastNl + 1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Read and parse [firstOwned, end).
|
|
104
|
+
let off = firstOwned;
|
|
105
|
+
while (off < end) {
|
|
106
|
+
const len = Math.min(CHUNK, end - off);
|
|
107
|
+
const buf = Buffer.allocUnsafe(len);
|
|
108
|
+
const r = fs.readSync(fd, buf, 0, len, off);
|
|
109
|
+
if (r === 0) break;
|
|
110
|
+
off += r;
|
|
111
|
+
|
|
112
|
+
if (tail !== null) {
|
|
113
|
+
const nl = buf.indexOf(0x0a);
|
|
114
|
+
if (nl === -1) {
|
|
115
|
+
tail = Buffer.concat([tail, buf.subarray(0, r)]);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const line = Buffer.allocUnsafe(tail.length + nl);
|
|
119
|
+
tail.copy(line, 0);
|
|
120
|
+
buf.copy(line, tail.length, 0, nl);
|
|
121
|
+
tail = null;
|
|
122
|
+
let lineEnd = line.length;
|
|
123
|
+
if (lineEnd > 0 && line[lineEnd - 1] === 13) lineEnd--; // tolerate CRLF
|
|
124
|
+
parseLine(line.toString("utf8", 0, lineEnd));
|
|
125
|
+
processBuf(buf, nl + 1, r);
|
|
126
|
+
} else {
|
|
127
|
+
processBuf(buf, 0, r);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// A trailing partial line (no \n in this worker's range): it is either the
|
|
131
|
+
// file's last line or a boundary line that the next worker completes.
|
|
132
|
+
if (tail !== null) parseLine(tail.toString("utf8"));
|
|
133
|
+
} finally {
|
|
134
|
+
fs.closeSync(fd);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Transfer the matrix buffer itself (zero copy). It may carry a little
|
|
138
|
+
// pre-allocation headroom beyond `rows`; the main thread copies only
|
|
139
|
+
// `rows * dims * 4` bytes.
|
|
140
|
+
parentPort.postMessage({ words, rows, buf: matrix.buffer }, [matrix.buffer]);
|