@scinorandex/embeddings 0.0.1 → 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/README.md +32 -13
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- 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_worker.mjs +8 -5
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/models/fasttext.ts +560 -0
- package/src/models/glove_worker.mjs +8 -5
- package/test/fasttext.ts +13 -0
package/README.md
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
# @scinorandex/embeddings
|
|
2
2
|
|
|
3
|
-
Optimized loaders for word-embedding models (GloVe text and word2vec binary) in Node.js.
|
|
3
|
+
Optimized loaders for word-embedding models (GloVe text, fastText text, and word2vec binary) in Node.js.
|
|
4
4
|
|
|
5
5
|
## Usage
|
|
6
6
|
|
|
7
7
|
```ts
|
|
8
|
-
import { load_glove, load_word2vec, type WordModel, type LoadOptions } from "@scinorandex/embeddings";
|
|
8
|
+
import { load_glove, load_fasttext, load_word2vec, type WordModel, type LoadOptions } from "@scinorandex/embeddings";
|
|
9
9
|
|
|
10
10
|
const glove = await load_glove("embeddings/glove.840B.300d.txt");
|
|
11
|
+
const ft = await load_fasttext("embeddings/fasttext-crawl-300d-2M.vec");
|
|
11
12
|
const w2v = await load_word2vec("embeddings/word2vec-300d-GoogleNews.bin.gz");
|
|
12
13
|
|
|
13
14
|
glove.similarity("king", "queen"); // cosine similarity
|
|
@@ -44,6 +45,8 @@ interface LoadOptions {
|
|
|
44
45
|
skips gunzip.
|
|
45
46
|
- GloVe `.txt` input: `<name>.glovecache` (raw matrix + words) - skips the
|
|
46
47
|
text parse entirely.
|
|
48
|
+
- fastText `.vec` input: `<name>.fasttextcache` (raw matrix + words) -
|
|
49
|
+
skips the text parse entirely.
|
|
47
50
|
|
|
48
51
|
## Performance
|
|
49
52
|
|
|
@@ -58,6 +61,16 @@ load, 4409 MB RSS**:
|
|
|
58
61
|
| `f16` | 20.0 s | 1755 MB |
|
|
59
62
|
| `i8` | 27.8 s | 1219 MB |
|
|
60
63
|
|
|
64
|
+
fastText Crawl 300d 2M (1,999,995 words, 4.5 GB text):
|
|
65
|
+
|
|
66
|
+
| Load path | Load time | RSS (steady) |
|
|
67
|
+
| ----------------------------------------------- | --------- | ------------ |
|
|
68
|
+
| `f32`, parallel (default) | 16.5 s | 2672 MB |
|
|
69
|
+
| `f32` + `cache: true` (first run, writes cache) | 19.9 s | ~2660 MB |
|
|
70
|
+
| `f32` + `cache: true` (cache hit, warm) | **4.7 s** | 2570 MB |
|
|
71
|
+
| `f16` | 16.9 s | 1505 MB |
|
|
72
|
+
| `i8` | 25.8 s | 996 MB |
|
|
73
|
+
|
|
61
74
|
word2vec GoogleNews 300d (3,000,000 words, 1.7 GB `.gz`) - original loader:
|
|
62
75
|
**107.2 s load, 5130 MB RSS**:
|
|
63
76
|
|
|
@@ -68,10 +81,10 @@ word2vec GoogleNews 300d (3,000,000 words, 1.7 GB `.gz`) - original loader:
|
|
|
68
81
|
| `f16` | 20.7 s | 2114 MB |
|
|
69
82
|
| `i8` | 31.4 s | 1315 MB |
|
|
70
83
|
|
|
71
|
-
Query times (nearest-10 over the full vocabulary): ~0.8 s for GloVe, ~
|
|
72
|
-
for word2vec. All f32 results are bit-identical to the
|
|
73
|
-
(cosine similarities and nearest-neighbor lists match to
|
|
74
|
-
matches to ~2e-5).
|
|
84
|
+
Query times (nearest-10 over the full vocabulary): ~0.8 s for GloVe, ~0.7 s
|
|
85
|
+
for fastText, ~1.1 s for word2vec. All f32 results are bit-identical to the
|
|
86
|
+
original loader's (cosine similarities and nearest-neighbor lists match to
|
|
87
|
+
full precision; f16 matches to ~2e-5).
|
|
75
88
|
|
|
76
89
|
RSS figures are measured after the model is fully loaded and garbage has
|
|
77
90
|
settled (worker-thread teardown is asynchronous), with `tsx --expose-gc`.
|
|
@@ -80,13 +93,17 @@ settled (worker-thread teardown is asynchronous), with `tsx --expose-gc`.
|
|
|
80
93
|
|
|
81
94
|
- [Word2Vec GoogleNews 300d](https://github.com/mmihaltz/word2vec-GoogleNews-vectors/raw/refs/heads/master/GoogleNews-vectors-negative300.bin.gz)
|
|
82
95
|
- [GloVe Common Crawl 300d](https://huggingface.co/stanfordnlp/glove/resolve/main/glove.840B.300d.zip)
|
|
96
|
+
- [fastText Crawl 2M 300d 2M](https://dl.fbaipublicfiles.com/fasttext/vectors-english/crawl-300d-2M.vec.zip)
|
|
83
97
|
|
|
84
|
-
This library is compatible with the canonical Word2Vec
|
|
98
|
+
This library is compatible with the canonical Word2Vec, GloVe, and fastText
|
|
99
|
+
distribution formats and can be used with any compatible pre-trained
|
|
100
|
+
embedding database.
|
|
85
101
|
|
|
86
102
|
## Running tests and benches
|
|
87
103
|
|
|
88
104
|
```sh
|
|
89
105
|
tsx test/glove.ts # public-API smoke test (GloVe)
|
|
106
|
+
tsx test/fasttext.ts # public-API smoke test (fastText)
|
|
90
107
|
tsx test/word2vec.ts # public-API smoke test (word2vec)
|
|
91
108
|
|
|
92
109
|
tsx --expose-gc bench/optimized.ts glove # one of: glove, glove-f16,
|
|
@@ -110,12 +127,14 @@ bit-for-bit, and `bench/limit_check.ts` exercises the `limit` option paths.
|
|
|
110
127
|
`split`/`parseFloat` in the hot path; bit-identical to `parseFloat` for all
|
|
111
128
|
tokens with <= 15 significant digits (verified on 59.9 M real GloVe
|
|
112
129
|
fields), with a `parseFloat` fallback for exotic tokens.
|
|
113
|
-
- **Parallel
|
|
114
|
-
the file
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
130
|
+
- **Parallel text parsing** (`src/models/glove.ts`, `src/models/fasttext.ts`
|
|
131
|
+
+ `glove_worker.mjs`): the file (for fastText, the body after the `COUNT
|
|
132
|
+
SIZE` header) is split into `min(availableParallelism(), 8)` byte ranges,
|
|
133
|
+
each parsed by a worker thread (one plain-JS worker is shared by GloVe and
|
|
134
|
+
fastText; workers own a pre-window line so no line is parsed by two
|
|
135
|
+
workers). The main thread merges in file order, deduplicating duplicate
|
|
136
|
+
words in place. Small files, `limit` loads, and worker failures fall back
|
|
137
|
+
to a sequential read.
|
|
119
138
|
- **Cache writes** are chunked to <= 1 GiB per `fd.write` call: Node's
|
|
120
139
|
`writev`-based plumbing (used by `WriteStream` and single large
|
|
121
140
|
`fs.read`/`fs.write` calls) 32-bit-limits a single operation to 2 GiB,
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -18,4 +18,5 @@ __exportStar(require("./common"), exports);
|
|
|
18
18
|
__exportStar(require("./models/matrix"), exports);
|
|
19
19
|
__exportStar(require("./models/word2vec"), exports);
|
|
20
20
|
__exportStar(require("./models/glove"), exports);
|
|
21
|
+
__exportStar(require("./models/fasttext"), exports);
|
|
21
22
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,kDAAgC;AAChC,oDAAkC;AAClC,iDAA+B"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,kDAAgC;AAChC,oDAAkC;AAClC,iDAA+B;AAC/B,oDAAkC"}
|
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.load_fasttext = load_fasttext;
|
|
7
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
8
|
+
const node_os_1 = __importDefault(require("node:os"));
|
|
9
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
10
|
+
const node_worker_threads_1 = require("node:worker_threads");
|
|
11
|
+
const parse_fast_mjs_1 = require("./parse_fast.mjs");
|
|
12
|
+
const matrix_1 = require("./matrix");
|
|
13
|
+
const fasttext_cache = new Map();
|
|
14
|
+
const EMPTY = Buffer.alloc(0);
|
|
15
|
+
const CACHE_MAGIC = "FASTTEXT";
|
|
16
|
+
const CACHE_HEADER = 20;
|
|
17
|
+
const PARALLEL_MIN_BYTES = 64 << 20;
|
|
18
|
+
const MAX_WORKERS = 8;
|
|
19
|
+
async function load_fasttext(model_path, options) {
|
|
20
|
+
const opts = (0, matrix_1.resolve_options)(options);
|
|
21
|
+
const key = model_path + "\u0000" + JSON.stringify(opts);
|
|
22
|
+
const cached = fasttext_cache.get(key);
|
|
23
|
+
if (cached)
|
|
24
|
+
return cached;
|
|
25
|
+
let cache_path = null;
|
|
26
|
+
if (opts.cache) {
|
|
27
|
+
cache_path = model_path.endsWith(".vec") ? model_path.slice(0, -4) + ".fasttextcache" : model_path + ".fasttextcache";
|
|
28
|
+
let fresh = false;
|
|
29
|
+
try {
|
|
30
|
+
const src_stat = await node_fs_1.default.promises.stat(model_path);
|
|
31
|
+
const cstat = await node_fs_1.default.promises.stat(cache_path);
|
|
32
|
+
if (cstat.mtimeMs >= src_stat.mtimeMs)
|
|
33
|
+
fresh = true;
|
|
34
|
+
}
|
|
35
|
+
catch (_a) {
|
|
36
|
+
}
|
|
37
|
+
if (fresh) {
|
|
38
|
+
try {
|
|
39
|
+
const model = await read_fasttext_cache(cache_path, opts);
|
|
40
|
+
fasttext_cache.set(key, model);
|
|
41
|
+
return model;
|
|
42
|
+
}
|
|
43
|
+
catch (_b) {
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
let fileSize = 0;
|
|
48
|
+
try {
|
|
49
|
+
fileSize = (await node_fs_1.default.promises.stat(model_path)).size;
|
|
50
|
+
}
|
|
51
|
+
catch (_c) {
|
|
52
|
+
}
|
|
53
|
+
if (fileSize >= PARALLEL_MIN_BYTES && opts.limit === undefined && node_os_1.default.availableParallelism() > 1) {
|
|
54
|
+
try {
|
|
55
|
+
const parsed = await parse_fasttext_parallel(model_path, fileSize);
|
|
56
|
+
return await build_model(parsed, opts, cache_path, key);
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
if (err instanceof Error && err.message.startsWith("Incomplete model file"))
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return load_fasttext_sequential(model_path, fileSize, opts, cache_path, key);
|
|
64
|
+
}
|
|
65
|
+
async function build_model(parsed, opts, cache_path, key) {
|
|
66
|
+
if (cache_path !== null) {
|
|
67
|
+
await write_fasttext_cache(cache_path, parsed.size, parsed.rows, parsed.matrix, parsed.words);
|
|
68
|
+
}
|
|
69
|
+
const model = (0, matrix_1.finalize_model)(parsed.matrix, parsed.rows, parsed.size, parsed.words, parsed.index, opts);
|
|
70
|
+
fasttext_cache.set(key, model);
|
|
71
|
+
return model;
|
|
72
|
+
}
|
|
73
|
+
function parse_header(line) {
|
|
74
|
+
const sp = line.indexOf(" ");
|
|
75
|
+
if (sp === -1)
|
|
76
|
+
throw new Error(`Invalid fastText header line (expected 'COUNT SIZE'): ${line}`);
|
|
77
|
+
const count = parse_header_int(line, 0, sp);
|
|
78
|
+
const size = parse_header_int(line, sp + 1, line.length);
|
|
79
|
+
if (count === null || size === null)
|
|
80
|
+
throw new Error(`Invalid fastText header line (expected 'COUNT SIZE'): ${line}`);
|
|
81
|
+
return { count, size };
|
|
82
|
+
}
|
|
83
|
+
function parse_header_int(line, start, end) {
|
|
84
|
+
let i = start;
|
|
85
|
+
while (i < end && line.charCodeAt(i) === 32)
|
|
86
|
+
i++;
|
|
87
|
+
let v = 0;
|
|
88
|
+
let n = 0;
|
|
89
|
+
while (i < end) {
|
|
90
|
+
const c = line.charCodeAt(i);
|
|
91
|
+
if (c < 48 || c > 57)
|
|
92
|
+
return null;
|
|
93
|
+
v = v * 10 + (c - 48);
|
|
94
|
+
n++;
|
|
95
|
+
i++;
|
|
96
|
+
}
|
|
97
|
+
if (n === 0 || v === 0)
|
|
98
|
+
return null;
|
|
99
|
+
return v;
|
|
100
|
+
}
|
|
101
|
+
async function parse_fasttext_parallel(model_path, fileSize) {
|
|
102
|
+
const probeLen = Math.min(1 << 20, fileSize);
|
|
103
|
+
const probe = Buffer.alloc(probeLen);
|
|
104
|
+
const fd0 = await node_fs_1.default.promises.open(model_path, "r");
|
|
105
|
+
let probed = 0;
|
|
106
|
+
while (probed < probeLen) {
|
|
107
|
+
const r = await fd0.read(probe, probed, probeLen - probed, probed);
|
|
108
|
+
if (r.bytesRead === 0)
|
|
109
|
+
break;
|
|
110
|
+
probed += r.bytesRead;
|
|
111
|
+
}
|
|
112
|
+
await fd0.close();
|
|
113
|
+
if (probed === 0)
|
|
114
|
+
throw new Error("Incomplete model file (empty)");
|
|
115
|
+
const firstNl = probe.indexOf(0x0a, 0, probed);
|
|
116
|
+
if (firstNl === -1)
|
|
117
|
+
throw new Error("Incomplete model file (no complete line)");
|
|
118
|
+
let headerEnd = firstNl;
|
|
119
|
+
if (headerEnd > 0 && probe[headerEnd - 1] === 13)
|
|
120
|
+
headerEnd--;
|
|
121
|
+
const header = parse_header(probe.toString("utf8", 0, headerEnd));
|
|
122
|
+
const bodyStart = firstNl + 1;
|
|
123
|
+
const bodyLen = fileSize - bodyStart;
|
|
124
|
+
if (bodyLen <= 0)
|
|
125
|
+
throw new Error("Incomplete model file (no vector data)");
|
|
126
|
+
const n = Math.min(node_os_1.default.availableParallelism(), MAX_WORKERS);
|
|
127
|
+
const ranges = [];
|
|
128
|
+
for (let i = 0; i < n; i++) {
|
|
129
|
+
const a = bodyStart + Math.floor((bodyLen * i) / n);
|
|
130
|
+
const b = i === n - 1 ? fileSize : bodyStart + Math.floor((bodyLen * (i + 1)) / n);
|
|
131
|
+
ranges.push([a, b]);
|
|
132
|
+
}
|
|
133
|
+
const worker_path = node_path_1.default.join(__dirname, "glove_worker.mjs");
|
|
134
|
+
const estRowsFor = (a, b) => Math.max(1, Math.ceil((header.count * (b - a)) / bodyLen) + 2);
|
|
135
|
+
const slots = new Array(ranges.length);
|
|
136
|
+
const exited = [];
|
|
137
|
+
let pending = ranges.length;
|
|
138
|
+
await new Promise((resolveAll, rejectAll) => {
|
|
139
|
+
ranges.forEach(([a, b], k) => {
|
|
140
|
+
const w = new node_worker_threads_1.Worker(worker_path, {
|
|
141
|
+
workerData: { path: model_path, start: a, end: b, dims: header.size, estRows: estRowsFor(a, b) },
|
|
142
|
+
resourceLimits: { maxOldGenerationSizeMb: 1024 },
|
|
143
|
+
});
|
|
144
|
+
let exitRes;
|
|
145
|
+
exited.push(new Promise((res) => {
|
|
146
|
+
exitRes = res;
|
|
147
|
+
}));
|
|
148
|
+
w.on("exit", (code) => {
|
|
149
|
+
exitRes();
|
|
150
|
+
if (slots[k] === undefined)
|
|
151
|
+
rejectAll(new Error(`fastText worker exited with code ${code} before completing`));
|
|
152
|
+
});
|
|
153
|
+
w.on("message", (res) => {
|
|
154
|
+
slots[k] = res;
|
|
155
|
+
w.terminate();
|
|
156
|
+
if (--pending === 0)
|
|
157
|
+
resolveAll();
|
|
158
|
+
});
|
|
159
|
+
w.on("error", (err) => {
|
|
160
|
+
if (slots[k] === undefined)
|
|
161
|
+
rejectAll(err);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
await Promise.all(exited);
|
|
166
|
+
const rows_total = slots.reduce((s, r) => s + r.rows, 0);
|
|
167
|
+
if (rows_total === 0)
|
|
168
|
+
throw new Error("Incomplete model file (no complete line)");
|
|
169
|
+
const rowBytes = header.size * 4;
|
|
170
|
+
const merged = Buffer.alloc(rows_total * rowBytes);
|
|
171
|
+
const words_all = new Array(rows_total);
|
|
172
|
+
let cursor = 0;
|
|
173
|
+
for (let k = 0; k < slots.length; k++) {
|
|
174
|
+
const res = slots[k];
|
|
175
|
+
const rb = Buffer.from(res.buf);
|
|
176
|
+
rb.copy(merged, cursor * rowBytes, 0, res.rows * rowBytes);
|
|
177
|
+
for (let i = 0; i < res.words.length; i++)
|
|
178
|
+
words_all[cursor + i] = res.words[i];
|
|
179
|
+
cursor += res.rows;
|
|
180
|
+
slots[k] = null;
|
|
181
|
+
}
|
|
182
|
+
const index = new Map();
|
|
183
|
+
let dups = 0;
|
|
184
|
+
for (let i = 0; i < rows_total; i++) {
|
|
185
|
+
const w = words_all[i];
|
|
186
|
+
if (index.has(w))
|
|
187
|
+
dups++;
|
|
188
|
+
else
|
|
189
|
+
index.set(w, i);
|
|
190
|
+
}
|
|
191
|
+
let rows = rows_total;
|
|
192
|
+
if (dups > 0) {
|
|
193
|
+
index.clear();
|
|
194
|
+
let outRow = 0;
|
|
195
|
+
for (let i = 0; i < rows_total; i++) {
|
|
196
|
+
const w = words_all[i];
|
|
197
|
+
const existing = index.get(w);
|
|
198
|
+
if (existing === undefined) {
|
|
199
|
+
index.set(w, outRow);
|
|
200
|
+
if (outRow !== i) {
|
|
201
|
+
words_all[outRow] = w;
|
|
202
|
+
merged.copyWithin(outRow * rowBytes, i * rowBytes, (i + 1) * rowBytes);
|
|
203
|
+
}
|
|
204
|
+
outRow++;
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
merged.copyWithin(existing * rowBytes, i * rowBytes, (i + 1) * rowBytes);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
rows = outRow;
|
|
211
|
+
words_all.length = outRow;
|
|
212
|
+
}
|
|
213
|
+
return { matrix: merged.subarray(0, rows * rowBytes), rows, size: header.size, words: words_all, index };
|
|
214
|
+
}
|
|
215
|
+
function load_fasttext_sequential(model_path, fileSize, opts, cache_path, key) {
|
|
216
|
+
return new Promise((resolve, reject) => {
|
|
217
|
+
const read_stream = node_fs_1.default.createReadStream(model_path, { highWaterMark: 1 << 22 });
|
|
218
|
+
let vector_size = 0;
|
|
219
|
+
let rows = 0;
|
|
220
|
+
let capacity = 0;
|
|
221
|
+
let matrix = EMPTY;
|
|
222
|
+
const words = [];
|
|
223
|
+
const index = new Map();
|
|
224
|
+
let tail = EMPTY;
|
|
225
|
+
let in_header = true;
|
|
226
|
+
let stopped = false;
|
|
227
|
+
let resolved = false;
|
|
228
|
+
const finish = () => {
|
|
229
|
+
if (resolved)
|
|
230
|
+
return;
|
|
231
|
+
resolved = true;
|
|
232
|
+
if (vector_size === 0) {
|
|
233
|
+
reject(new Error("Incomplete model file (missing header)"));
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (rows === 0) {
|
|
237
|
+
reject(new Error("Incomplete model file (no complete line)"));
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
(async () => {
|
|
241
|
+
try {
|
|
242
|
+
const model = await build_model({ matrix, rows, size: vector_size, words, index }, opts, cache_path, key);
|
|
243
|
+
matrix = EMPTY;
|
|
244
|
+
read_stream.removeAllListeners();
|
|
245
|
+
resolve(model);
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
reject(err);
|
|
249
|
+
}
|
|
250
|
+
})();
|
|
251
|
+
};
|
|
252
|
+
const ensure_rows = (need) => {
|
|
253
|
+
if (need <= capacity)
|
|
254
|
+
return;
|
|
255
|
+
const newCap = Math.max(need, capacity + Math.ceil(capacity / 8));
|
|
256
|
+
const newMatrix = Buffer.alloc(newCap * vector_size * 4);
|
|
257
|
+
matrix.copy(newMatrix, 0);
|
|
258
|
+
matrix = newMatrix;
|
|
259
|
+
capacity = newCap;
|
|
260
|
+
};
|
|
261
|
+
const parse_line = (line) => {
|
|
262
|
+
const sp = line.indexOf(" ");
|
|
263
|
+
if (sp === -1 || sp === line.length - 1)
|
|
264
|
+
return;
|
|
265
|
+
const word = line.slice(0, sp);
|
|
266
|
+
const existing = index.get(word);
|
|
267
|
+
const isNew = existing === undefined;
|
|
268
|
+
const r = isNew ? rows : existing;
|
|
269
|
+
if (isNew) {
|
|
270
|
+
ensure_rows(rows + 1);
|
|
271
|
+
index.set(word, r);
|
|
272
|
+
words.push(word);
|
|
273
|
+
rows++;
|
|
274
|
+
}
|
|
275
|
+
const m = matrix;
|
|
276
|
+
const rrow = new Float32Array(m.buffer, m.byteOffset + r * vector_size * 4, vector_size);
|
|
277
|
+
(0, parse_fast_mjs_1.parse_floats_str)(line, sp + 1, rrow);
|
|
278
|
+
};
|
|
279
|
+
const handle_line = (line) => {
|
|
280
|
+
if (in_header) {
|
|
281
|
+
in_header = false;
|
|
282
|
+
try {
|
|
283
|
+
const header = parse_header(line);
|
|
284
|
+
vector_size = header.size;
|
|
285
|
+
capacity = opts.limit !== undefined ? Math.min(header.count, opts.limit) : header.count;
|
|
286
|
+
matrix = Buffer.alloc(capacity * vector_size * 4);
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
stopped = true;
|
|
290
|
+
resolved = true;
|
|
291
|
+
reject(err);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (opts.limit !== undefined && rows >= opts.limit) {
|
|
297
|
+
stopped = true;
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
parse_line(line);
|
|
301
|
+
};
|
|
302
|
+
const process_chunk = (buf, start) => {
|
|
303
|
+
let lineStart = start;
|
|
304
|
+
while (lineStart < buf.length && !stopped) {
|
|
305
|
+
const nl = buf.indexOf(0x0a, lineStart);
|
|
306
|
+
if (nl === -1) {
|
|
307
|
+
tail = Buffer.from(buf.subarray(lineStart));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
let end = nl;
|
|
311
|
+
if (end > lineStart && buf[end - 1] === 13)
|
|
312
|
+
end--;
|
|
313
|
+
if (end > lineStart)
|
|
314
|
+
handle_line(buf.toString("utf8", lineStart, end));
|
|
315
|
+
lineStart = nl + 1;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
read_stream.on("data", (chunk) => {
|
|
319
|
+
if (stopped)
|
|
320
|
+
return;
|
|
321
|
+
if (tail.length > 0) {
|
|
322
|
+
const nl = chunk.indexOf(0x0a);
|
|
323
|
+
if (nl === -1) {
|
|
324
|
+
tail = Buffer.concat([tail, chunk]);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const line = Buffer.allocUnsafe(tail.length + nl);
|
|
328
|
+
tail.copy(line, 0);
|
|
329
|
+
chunk.copy(line, tail.length, 0, nl);
|
|
330
|
+
tail = EMPTY;
|
|
331
|
+
let lineEnd = line.length;
|
|
332
|
+
if (lineEnd > 0 && line[lineEnd - 1] === 13)
|
|
333
|
+
lineEnd--;
|
|
334
|
+
handle_line(line.toString("utf8", 0, lineEnd));
|
|
335
|
+
process_chunk(chunk, nl + 1);
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
process_chunk(chunk, 0);
|
|
339
|
+
}
|
|
340
|
+
if (stopped)
|
|
341
|
+
read_stream.destroy();
|
|
342
|
+
});
|
|
343
|
+
read_stream.on("end", finish);
|
|
344
|
+
read_stream.on("close", finish);
|
|
345
|
+
read_stream.on("error", (err) => {
|
|
346
|
+
if (stopped)
|
|
347
|
+
finish();
|
|
348
|
+
else
|
|
349
|
+
reject(err);
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
async function read_fasttext_cache(path, opts) {
|
|
354
|
+
const stat = await node_fs_1.default.promises.stat(path);
|
|
355
|
+
const fd = await node_fs_1.default.promises.open(path, "r");
|
|
356
|
+
try {
|
|
357
|
+
const MAX_IO = 1 << 30;
|
|
358
|
+
const readFull = async (buf, off, len) => {
|
|
359
|
+
let got = 0;
|
|
360
|
+
while (got < len) {
|
|
361
|
+
const r = await fd.read(buf, got, Math.min(MAX_IO, len - got), off + got);
|
|
362
|
+
if (r.bytesRead === 0)
|
|
363
|
+
throw new Error("Unexpected end of fastText cache file");
|
|
364
|
+
got += r.bytesRead;
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
const header = Buffer.alloc(CACHE_HEADER);
|
|
368
|
+
await readFull(header, 0, CACHE_HEADER);
|
|
369
|
+
if (header.toString("ascii", 0, 8) !== CACHE_MAGIC)
|
|
370
|
+
throw new Error("Not a fastText cache file");
|
|
371
|
+
const dims = header.readUInt32LE(8);
|
|
372
|
+
const rows = header.readUInt32LE(12);
|
|
373
|
+
const n = opts.limit !== undefined ? Math.min(opts.limit, rows) : rows;
|
|
374
|
+
const matrix_bytes = n * dims * 4;
|
|
375
|
+
const matrix = Buffer.alloc(matrix_bytes);
|
|
376
|
+
await readFull(matrix, CACHE_HEADER, matrix_bytes);
|
|
377
|
+
const ws_off = CACHE_HEADER + rows * dims * 4;
|
|
378
|
+
let budget = Math.min(n * 64 + 64, stat.size - ws_off);
|
|
379
|
+
let words = [];
|
|
380
|
+
for (;;) {
|
|
381
|
+
const ws = Buffer.alloc(budget);
|
|
382
|
+
await readFull(ws, ws_off, budget);
|
|
383
|
+
words = [];
|
|
384
|
+
let off = 0;
|
|
385
|
+
let ok = true;
|
|
386
|
+
for (let i = 0; i < n; i++) {
|
|
387
|
+
if (off + 4 > budget)
|
|
388
|
+
break;
|
|
389
|
+
const len = ws.readUInt32LE(off);
|
|
390
|
+
if (off + 4 + len > budget) {
|
|
391
|
+
ok = false;
|
|
392
|
+
break;
|
|
393
|
+
}
|
|
394
|
+
words.push(ws.toString("utf8", off + 4, off + 4 + len));
|
|
395
|
+
off += 4 + len;
|
|
396
|
+
}
|
|
397
|
+
if (ok || budget >= stat.size - ws_off)
|
|
398
|
+
break;
|
|
399
|
+
budget = Math.min(budget * 4, stat.size - ws_off);
|
|
400
|
+
}
|
|
401
|
+
const index = new Map();
|
|
402
|
+
for (let i = 0; i < n; i++)
|
|
403
|
+
index.set(words[i], i);
|
|
404
|
+
return (0, matrix_1.finalize_model)(matrix, n, dims, words, index, opts);
|
|
405
|
+
}
|
|
406
|
+
finally {
|
|
407
|
+
await fd.close();
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
async function write_fasttext_cache(path, dims, rows, matrix, words) {
|
|
411
|
+
if (CACHE_MAGIC.length !== 8)
|
|
412
|
+
throw new Error("CACHE_MAGIC must be exactly 8 characters");
|
|
413
|
+
const header = Buffer.alloc(CACHE_HEADER);
|
|
414
|
+
header.write(CACHE_MAGIC, 0, 8, "ascii");
|
|
415
|
+
header.writeUInt32LE(dims, 8);
|
|
416
|
+
header.writeUInt32LE(rows, 12);
|
|
417
|
+
let word_bytes = 0;
|
|
418
|
+
for (const w of words)
|
|
419
|
+
word_bytes += Buffer.byteLength(w, "utf8");
|
|
420
|
+
header.writeUInt32LE(word_bytes, 16);
|
|
421
|
+
const matrix_bytes = rows * dims * 4;
|
|
422
|
+
const ws = Buffer.alloc(word_bytes + rows * 4);
|
|
423
|
+
let off = 0;
|
|
424
|
+
for (const w of words) {
|
|
425
|
+
const bl = Buffer.byteLength(w, "utf8");
|
|
426
|
+
ws.writeUInt32LE(bl, off);
|
|
427
|
+
off += 4;
|
|
428
|
+
ws.write(w, off, "utf8");
|
|
429
|
+
off += bl;
|
|
430
|
+
}
|
|
431
|
+
const tmp = path + ".tmp";
|
|
432
|
+
const MAX_IO = 1 << 30;
|
|
433
|
+
const fd = await node_fs_1.default.promises.open(tmp, "w");
|
|
434
|
+
try {
|
|
435
|
+
const writeFull = async (buf, off, len, pos) => {
|
|
436
|
+
let written = 0;
|
|
437
|
+
while (written < len) {
|
|
438
|
+
const r = await fd.write(buf, off + written, Math.min(MAX_IO, len - written), pos + written);
|
|
439
|
+
written += r.bytesWritten;
|
|
440
|
+
}
|
|
441
|
+
return pos + len;
|
|
442
|
+
};
|
|
443
|
+
let pos = 0;
|
|
444
|
+
pos = await writeFull(header, 0, header.length, pos);
|
|
445
|
+
pos = await writeFull(matrix, 0, matrix_bytes, pos);
|
|
446
|
+
pos = await writeFull(ws, 0, ws.length, pos);
|
|
447
|
+
}
|
|
448
|
+
finally {
|
|
449
|
+
await fd.close();
|
|
450
|
+
}
|
|
451
|
+
await node_fs_1.default.promises.rename(tmp, path);
|
|
452
|
+
}
|
|
453
|
+
//# sourceMappingURL=fasttext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fasttext.js","sourceRoot":"","sources":["../../src/models/fasttext.ts"],"names":[],"mappings":";;;;;;AAAA,sDAAyB;AACzB,sDAAyB;AACzB,0DAA6B;AAC7B,6DAA6C;AAC7C,qDAAoD;AACpD,qCAAmG;AAInG,MAAM,cAAc,GAAG,IAAI,GAAG,EAAqB,CAAC;AAEpD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAE9B,MAAM,WAAW,GAAG,UAAU,CAAC;AAC/B,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,MAAM,kBAAkB,GAAG,EAAE,IAAI,EAAE,CAAC;AAEpC,MAAM,WAAW,GAAG,CAAC,CAAC;AA4Bf,KAAK,wBAAwB,UAAkB,EAAE,OAAqB;IAC3E,MAAM,IAAI,GAAG,IAAA,wBAAe,EAAC,OAAO,CAAC,CAAC;IACtC,MAAM,GAAG,GAAG,UAAU,GAAG,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACzD,MAAM,MAAM,GAAG,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACvC,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAI1B,IAAI,UAAU,GAAkB,IAAI,CAAC;IACrC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,UAAU,GAAG,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,UAAU,GAAG,gBAAgB,CAAC;QACtH,IAAI,KAAK,GAAG,KAAK,CAAC;QAClB,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,M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AC,MAAM,EAAE,CAAC,EAAE,YAAY,EAAE,GAAG,CAAC,CAAC;QACpD,GAAG,GAAG,MAAM,SAAS,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/C,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;IACD,MAAM,iBAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AACtC,CAAC"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Worker thread that parses one byte range of a GloVe text file
|
|
3
|
-
* row-major float32 matrix plus a word list
|
|
4
|
-
*
|
|
2
|
+
* Worker thread that parses one byte range of a GloVe or fastText text file
|
|
3
|
+
* into a row-major float32 matrix plus a word list (both formats share the
|
|
4
|
+
* `word v1 v2 ... vN` line format). Spawned by `glove.ts` and `fasttext.ts`
|
|
5
|
+
* to parse large files in parallel.
|
|
5
6
|
*
|
|
6
7
|
* Line ownership: a line belongs to the worker whose range contains the
|
|
7
8
|
* line's start position. Each worker therefore reads a small pre-window
|
|
@@ -72,7 +73,9 @@ const processBuf = (buf, lineStart, r) => {
|
|
|
72
73
|
}
|
|
73
74
|
};
|
|
74
75
|
|
|
75
|
-
|
|
76
|
+
// `start` may be smaller than the pre-window (e.g. the fastText body starts
|
|
77
|
+
// right after a short header line): clamp so the read position stays >= 0.
|
|
78
|
+
const readStart = start === 0 ? 0 : Math.max(0, start - PRE);
|
|
76
79
|
const fd = fs.openSync(file_path, "r");
|
|
77
80
|
try {
|
|
78
81
|
// Locate the first line this worker owns: just after the last \n before
|
|
@@ -95,7 +98,7 @@ try {
|
|
|
95
98
|
}
|
|
96
99
|
}
|
|
97
100
|
if (lastNl === -1) {
|
|
98
|
-
throw new Error("
|
|
101
|
+
throw new Error("Text line longer than 1 MiB crosses a worker boundary");
|
|
99
102
|
}
|
|
100
103
|
firstOwned = lastNl + 1;
|
|
101
104
|
}
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -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
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Worker thread that parses one byte range of a GloVe text file
|
|
3
|
-
* row-major float32 matrix plus a word list
|
|
4
|
-
*
|
|
2
|
+
* Worker thread that parses one byte range of a GloVe or fastText text file
|
|
3
|
+
* into a row-major float32 matrix plus a word list (both formats share the
|
|
4
|
+
* `word v1 v2 ... vN` line format). Spawned by `glove.ts` and `fasttext.ts`
|
|
5
|
+
* to parse large files in parallel.
|
|
5
6
|
*
|
|
6
7
|
* Line ownership: a line belongs to the worker whose range contains the
|
|
7
8
|
* line's start position. Each worker therefore reads a small pre-window
|
|
@@ -72,7 +73,9 @@ const processBuf = (buf, lineStart, r) => {
|
|
|
72
73
|
}
|
|
73
74
|
};
|
|
74
75
|
|
|
75
|
-
|
|
76
|
+
// `start` may be smaller than the pre-window (e.g. the fastText body starts
|
|
77
|
+
// right after a short header line): clamp so the read position stays >= 0.
|
|
78
|
+
const readStart = start === 0 ? 0 : Math.max(0, start - PRE);
|
|
76
79
|
const fd = fs.openSync(file_path, "r");
|
|
77
80
|
try {
|
|
78
81
|
// Locate the first line this worker owns: just after the last \n before
|
|
@@ -95,7 +98,7 @@ try {
|
|
|
95
98
|
}
|
|
96
99
|
}
|
|
97
100
|
if (lastNl === -1) {
|
|
98
|
-
throw new Error("
|
|
101
|
+
throw new Error("Text line longer than 1 MiB crosses a worker boundary");
|
|
99
102
|
}
|
|
100
103
|
firstOwned = lastNl + 1;
|
|
101
104
|
}
|
package/test/fasttext.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { load_fasttext } from "../dist";
|
|
3
|
+
|
|
4
|
+
const model_path = path.join(process.cwd(), "./embeddings/fasttext-crawl-300d-2M.vec");
|
|
5
|
+
async function main() {
|
|
6
|
+
const model = await load_fasttext(model_path, { cache: true });
|
|
7
|
+
console.log(model.words);
|
|
8
|
+
console.log(model.get_vector("walk"));
|
|
9
|
+
console.log(model.analogy("prince", ["king", "queen"]));
|
|
10
|
+
console.log(model.analogy("queen", ["king", "prince"]));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
main();
|