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