@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,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fast float parsing directly from byte buffers and strings (plain JS module
|
|
3
|
+
* so it can be shared with the GloVe worker threads without a loader).
|
|
4
|
+
*
|
|
5
|
+
* Plain decimal numbers (the common case in `.txt` embedding files) are
|
|
6
|
+
* decoded with a small hand-rolled scanner that never allocates strings.
|
|
7
|
+
* Values with at most 15 significant digits are reconstructed in a single
|
|
8
|
+
* correctly-rounded step, so the result is bit-identical to `parseFloat`.
|
|
9
|
+
* `parseFloat` is only used as a fallback for unusual inputs (`nan`, `inf`,
|
|
10
|
+
* very long digit runs, huge exponents).
|
|
11
|
+
*
|
|
12
|
+
* The hot path is `parse_floats_str`, which parses an entire line (e.g. all
|
|
13
|
+
* 300 values of one row) in a single call over a string; string scanning is
|
|
14
|
+
* significantly faster than `Buffer` byte scanning in V8, and keeping the
|
|
15
|
+
* per-value loop inside one function lets the JIT inline it.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const POW10 = new Float64Array(31);
|
|
19
|
+
POW10[0] = 1;
|
|
20
|
+
for (let i = 1; i <= 30; i++) POW10[i] = POW10[i - 1] * 10;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Parse `out.length` space-separated floats from `buf[start .. end)` into
|
|
24
|
+
* `out`. Returns the position just past the last parsed number.
|
|
25
|
+
*/
|
|
26
|
+
export function parse_floats(buf, start, end, out) {
|
|
27
|
+
// Clamp so that `i < end` below implies a valid buffer index (lets the JIT
|
|
28
|
+
// elide per-access bounds checks in the hot loops).
|
|
29
|
+
if (end > buf.length) end = buf.length;
|
|
30
|
+
|
|
31
|
+
const n = out.length;
|
|
32
|
+
let i = start;
|
|
33
|
+
for (let v = 0; v < n; v++) {
|
|
34
|
+
while (i < end && buf[i] === 32) i++; // ' '
|
|
35
|
+
|
|
36
|
+
let sign = 1;
|
|
37
|
+
if (i < end && buf[i] === 45) sign = -1; // '-'
|
|
38
|
+
else if (i < end && buf[i] === 43) i++; // '+'
|
|
39
|
+
|
|
40
|
+
const numStart = i;
|
|
41
|
+
let intPart = 0;
|
|
42
|
+
let nInt = 0;
|
|
43
|
+
while (i < end) {
|
|
44
|
+
const c = buf[i];
|
|
45
|
+
if (c < 48 || c > 57) break;
|
|
46
|
+
intPart = intPart * 10 + (c - 48);
|
|
47
|
+
nInt++;
|
|
48
|
+
i++;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let frac = 0;
|
|
52
|
+
let nFrac = 0;
|
|
53
|
+
if (i < end && buf[i] === 46) {
|
|
54
|
+
i++; // '.'
|
|
55
|
+
while (i < end) {
|
|
56
|
+
const c = buf[i];
|
|
57
|
+
if (c < 48 || c > 57) break;
|
|
58
|
+
frac = frac * 10 + (c - 48);
|
|
59
|
+
nFrac++;
|
|
60
|
+
i++;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Not a plain decimal (e.g. "nan", "inf"): let the standard parser handle it.
|
|
65
|
+
if (nInt === 0 && nFrac === 0) {
|
|
66
|
+
let e = i;
|
|
67
|
+
while (e < end && buf[e] !== 32) e++;
|
|
68
|
+
out[v] = parseFloat(buf.toString("latin1", numStart, e));
|
|
69
|
+
i = e;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Consume the exponent part first, so the fallbacks below always see the
|
|
74
|
+
// complete token.
|
|
75
|
+
let exp = 0;
|
|
76
|
+
let eSign = 1;
|
|
77
|
+
if (i < end && (buf[i] === 101 || buf[i] === 69)) {
|
|
78
|
+
i++; // 'e' / 'E'
|
|
79
|
+
if (i < end && buf[i] === 45) {
|
|
80
|
+
eSign = -1;
|
|
81
|
+
i++;
|
|
82
|
+
} else if (i < end && buf[i] === 43) {
|
|
83
|
+
i++;
|
|
84
|
+
}
|
|
85
|
+
let expDigits = 0;
|
|
86
|
+
while (i < end) {
|
|
87
|
+
const c = buf[i];
|
|
88
|
+
if (c < 48 || c > 57) break;
|
|
89
|
+
if (exp < 999) exp = exp * 10 + (c - 48); // cap; exact value not needed
|
|
90
|
+
expDigits++;
|
|
91
|
+
i++;
|
|
92
|
+
}
|
|
93
|
+
if (expDigits === 0) {
|
|
94
|
+
// Malformed exponent (e.g. "1e"): let the standard parser decide.
|
|
95
|
+
out[v] = parseFloat(buf.toString("latin1", numStart, i));
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Too many significant digits to reconstruct exactly: standard parser.
|
|
101
|
+
if (nInt + nFrac > 15) {
|
|
102
|
+
out[v] = sign * parseFloat(buf.toString("latin1", numStart, i));
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Reconstruct the value in a single correctly-rounded step:
|
|
107
|
+
// value = mantissa * 10^power, where
|
|
108
|
+
// mantissa = intPart * 10^nFrac + frac (exact integer, <= 15 digits)
|
|
109
|
+
// power = eSign * exp - nFrac
|
|
110
|
+
// Since both mantissa and 10^power are exactly representable, one
|
|
111
|
+
// IEEE multiply/divide gives the same float64 as parseFloat.
|
|
112
|
+
const mantissa = intPart * POW10[nFrac] + frac;
|
|
113
|
+
const power = (eSign > 0 ? exp : -exp) - nFrac;
|
|
114
|
+
if (power >= 0 && power <= 30) {
|
|
115
|
+
out[v] = sign * mantissa * POW10[power];
|
|
116
|
+
} else if (power < 0 && -power <= 30) {
|
|
117
|
+
out[v] = sign * mantissa / POW10[-power];
|
|
118
|
+
} else {
|
|
119
|
+
out[v] = sign * parseFloat(buf.toString("latin1", numStart, i));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return i;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Incremental single-value parser, a thin wrapper around `parse_floats` for
|
|
127
|
+
* callers that parse one value at a time. The result keeps full float64
|
|
128
|
+
* precision (the scratch slot is a Float64Array).
|
|
129
|
+
*/
|
|
130
|
+
export class FloatParser {
|
|
131
|
+
/** Position of the next character to parse (set before calling `next`). */
|
|
132
|
+
pos = 0;
|
|
133
|
+
|
|
134
|
+
#scratch = new Float64Array(1);
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Parse the next space-separated float from `buf[pos .. end)`.
|
|
138
|
+
* Advances `pos` to just past the parsed number.
|
|
139
|
+
*/
|
|
140
|
+
next(buf, end) {
|
|
141
|
+
this.pos = parse_floats(buf, this.pos, end, this.#scratch);
|
|
142
|
+
return this.#scratch[0];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* String-based twin of `parse_floats` (same algorithm, bit-identical
|
|
148
|
+
* results): parses `out.length` space-separated floats from `line[start ..)`
|
|
149
|
+
* into `out`.
|
|
150
|
+
*/
|
|
151
|
+
export function parse_floats_str(line, start, out) {
|
|
152
|
+
const end = line.length;
|
|
153
|
+
const n = out.length;
|
|
154
|
+
let i = start;
|
|
155
|
+
for (let v = 0; v < n; v++) {
|
|
156
|
+
while (i < end && line.charCodeAt(i) === 32) i++; // ' '
|
|
157
|
+
|
|
158
|
+
let sign = 1;
|
|
159
|
+
if (i < end && line.charCodeAt(i) === 45) sign = -1; // '-'
|
|
160
|
+
else if (i < end && line.charCodeAt(i) === 43) i++; // '+'
|
|
161
|
+
|
|
162
|
+
const numStart = i;
|
|
163
|
+
let intPart = 0;
|
|
164
|
+
let nInt = 0;
|
|
165
|
+
while (i < end) {
|
|
166
|
+
const c = line.charCodeAt(i);
|
|
167
|
+
if (c < 48 || c > 57) break;
|
|
168
|
+
intPart = intPart * 10 + (c - 48);
|
|
169
|
+
nInt++;
|
|
170
|
+
i++;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let frac = 0;
|
|
174
|
+
let nFrac = 0;
|
|
175
|
+
if (i < end && line.charCodeAt(i) === 46) {
|
|
176
|
+
i++; // '.'
|
|
177
|
+
while (i < end) {
|
|
178
|
+
const c = line.charCodeAt(i);
|
|
179
|
+
if (c < 48 || c > 57) break;
|
|
180
|
+
frac = frac * 10 + (c - 48);
|
|
181
|
+
nFrac++;
|
|
182
|
+
i++;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Not a plain decimal (e.g. "nan", "inf"): let the standard parser handle it.
|
|
187
|
+
if (nInt === 0 && nFrac === 0) {
|
|
188
|
+
let e = i;
|
|
189
|
+
while (e < end && line.charCodeAt(e) !== 32) e++;
|
|
190
|
+
out[v] = parseFloat(line.substring(numStart, e));
|
|
191
|
+
i = e;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Consume the exponent part first, so the fallbacks below always see the
|
|
196
|
+
// complete token.
|
|
197
|
+
let exp = 0;
|
|
198
|
+
let eSign = 1;
|
|
199
|
+
if (i < end && (line.charCodeAt(i) === 101 || line.charCodeAt(i) === 69)) {
|
|
200
|
+
i++; // 'e' / 'E'
|
|
201
|
+
if (i < end && line.charCodeAt(i) === 45) {
|
|
202
|
+
eSign = -1;
|
|
203
|
+
i++;
|
|
204
|
+
} else if (i < end && line.charCodeAt(i) === 43) {
|
|
205
|
+
i++;
|
|
206
|
+
}
|
|
207
|
+
let expDigits = 0;
|
|
208
|
+
while (i < end) {
|
|
209
|
+
const c = line.charCodeAt(i);
|
|
210
|
+
if (c < 48 || c > 57) break;
|
|
211
|
+
if (exp < 999) exp = exp * 10 + (c - 48); // cap; exact value not needed
|
|
212
|
+
expDigits++;
|
|
213
|
+
i++;
|
|
214
|
+
}
|
|
215
|
+
if (expDigits === 0) {
|
|
216
|
+
// Malformed exponent (e.g. "1e"): let the standard parser decide.
|
|
217
|
+
out[v] = parseFloat(line.substring(numStart, i));
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Too many significant digits to reconstruct exactly: standard parser.
|
|
223
|
+
if (nInt + nFrac > 15) {
|
|
224
|
+
out[v] = sign * parseFloat(line.substring(numStart, i));
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Reconstruct the value in a single correctly-rounded step:
|
|
229
|
+
// value = mantissa * 10^power, where
|
|
230
|
+
// mantissa = intPart * 10^nFrac + frac (exact integer, <= 15 digits)
|
|
231
|
+
// power = eSign * exp - nFrac
|
|
232
|
+
// Since both mantissa and 10^power are exactly representable, one
|
|
233
|
+
// IEEE multiply/divide gives the same float64 as parseFloat.
|
|
234
|
+
const mantissa = intPart * POW10[nFrac] + frac;
|
|
235
|
+
const power = (eSign > 0 ? exp : -exp) - nFrac;
|
|
236
|
+
if (power >= 0 && power <= 30) {
|
|
237
|
+
out[v] = sign * mantissa * POW10[power];
|
|
238
|
+
} else if (power < 0 && -power <= 30) {
|
|
239
|
+
out[v] = sign * mantissa / POW10[-power];
|
|
240
|
+
} else {
|
|
241
|
+
out[v] = sign * parseFloat(line.substring(numStart, i));
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return i;
|
|
245
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import zlib from "node:zlib";
|
|
3
|
+
import { finalize_model, resolve_options, type LoadOptions } from "./matrix";
|
|
4
|
+
import type { WordModel } from "../common";
|
|
5
|
+
|
|
6
|
+
/** Cache of already-loaded models, keyed by path + options. */
|
|
7
|
+
const w2v_cache = new Map<string, WordModel>();
|
|
8
|
+
|
|
9
|
+
const EMPTY = Buffer.alloc(0);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Load a word2vec model from a gzip-compressed binary `.bin` file (or an
|
|
13
|
+
* already-decompressed `.bin` file), streaming the data in 1 MB chunks.
|
|
14
|
+
*
|
|
15
|
+
* Format: a header line `COUNT SIZE`, then per word: the word, a space, and
|
|
16
|
+
* `SIZE` little-endian float32 values.
|
|
17
|
+
*
|
|
18
|
+
* Fast loading notes:
|
|
19
|
+
* - Vector rows are copied into one contiguous row-major matrix with a single
|
|
20
|
+
* `Buffer.copy` (memcpy) per word instead of `SIZE` individual
|
|
21
|
+
* `readFloatLE` calls.
|
|
22
|
+
* - The header gives the exact word count, so the matrix is pre-allocated
|
|
23
|
+
* exactly once.
|
|
24
|
+
*
|
|
25
|
+
* Before using make sure the Google News Word2Vec model is downloaded.
|
|
26
|
+
* `wget https://github.com/mmihaltz/word2vec-GoogleNews-vectors/raw/refs/heads/master/GoogleNews-vectors-negative300.bin.gz`
|
|
27
|
+
*/
|
|
28
|
+
export async function load_word2vec(model_path: string, options?: LoadOptions): Promise<WordModel> {
|
|
29
|
+
const opts = resolve_options(options);
|
|
30
|
+
const key = model_path + "\u0000" + JSON.stringify(opts);
|
|
31
|
+
const cached = w2v_cache.get(key);
|
|
32
|
+
if (cached) return cached;
|
|
33
|
+
|
|
34
|
+
const is_gzip = model_path.endsWith(".gz");
|
|
35
|
+
|
|
36
|
+
// With `cache: true`, a decompressed sibling file (`.bin`) is reused when
|
|
37
|
+
// it is at least as new as the source `.gz`, skipping decompression.
|
|
38
|
+
let source_path = model_path;
|
|
39
|
+
let write_bin_path: string | null = null;
|
|
40
|
+
if (is_gzip && opts.cache) {
|
|
41
|
+
const bin_path = model_path.slice(0, -3);
|
|
42
|
+
try {
|
|
43
|
+
const gz_stat = await fs.promises.stat(model_path);
|
|
44
|
+
const bin_stat = await fs.promises.stat(bin_path);
|
|
45
|
+
if (bin_stat.mtimeMs >= gz_stat.mtimeMs)
|
|
46
|
+
source_path = bin_path; // fresh cache hit
|
|
47
|
+
else write_bin_path = bin_path; // load from the .gz and (re)build the cache
|
|
48
|
+
} catch {
|
|
49
|
+
write_bin_path = bin_path; // no cache yet
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Plain `.bin` files are read directly; everything else is gunzipped on the
|
|
54
|
+
// fly. A large `chunkSize` keeps the per-chunk overhead of the zlib stream
|
|
55
|
+
// low (3-4x faster than the default for large files).
|
|
56
|
+
const read_stream = fs.createReadStream(source_path, { highWaterMark: 1 << 22 });
|
|
57
|
+
const pipeline =
|
|
58
|
+
source_path === model_path && is_gzip ? read_stream.pipe(zlib.createGunzip({ chunkSize: 4 << 20 })) : read_stream;
|
|
59
|
+
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
let header: { count: number; size: number } | null = null;
|
|
62
|
+
let header_buf: Buffer<ArrayBufferLike> = EMPTY; // stream chunks may be backed by a SharedArrayBuffer
|
|
63
|
+
let matrix = EMPTY;
|
|
64
|
+
let capacity = 0;
|
|
65
|
+
let vecBytes = 0;
|
|
66
|
+
let rows = 0;
|
|
67
|
+
const words: string[] = [];
|
|
68
|
+
const index = new Map<string, number>();
|
|
69
|
+
|
|
70
|
+
let word: string | null = null; // word awaiting its vector
|
|
71
|
+
let word_tail = EMPTY; // partial word bytes
|
|
72
|
+
let vec_tail = EMPTY; // partial vector bytes
|
|
73
|
+
let stopped = false;
|
|
74
|
+
let resolved = false;
|
|
75
|
+
|
|
76
|
+
// When building a decompression cache, tee the (decompressed) stream into
|
|
77
|
+
// a temporary file that is renamed atomically once fully written.
|
|
78
|
+
let write_stream: fs.WriteStream | null = null;
|
|
79
|
+
let cache_ok = false;
|
|
80
|
+
if (write_bin_path !== null) {
|
|
81
|
+
const tmp_path = write_bin_path + ".tmp";
|
|
82
|
+
write_stream = fs.createWriteStream(tmp_path, { highWaterMark: 1 << 22 });
|
|
83
|
+
write_stream.on("error", (err: any) => reject(err));
|
|
84
|
+
write_stream.on("close", async () => {
|
|
85
|
+
if (!cache_ok) {
|
|
86
|
+
// Interrupted (e.g. `limit`): never persist a partial cache.
|
|
87
|
+
fs.promises.unlink(tmp_path).catch(() => undefined);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
await fs.promises.rename(tmp_path, write_bin_path);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
reject(err);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const finish = () => {
|
|
99
|
+
if (resolved) return;
|
|
100
|
+
resolved = true;
|
|
101
|
+
if (header === null) {
|
|
102
|
+
reject(new Error("Incomplete model file (missing header)"));
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const model = finalize_model(matrix, rows, header.size, words, index, opts);
|
|
106
|
+
w2v_cache.set(key, model);
|
|
107
|
+
resolve(model);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const grow = () => {
|
|
111
|
+
const newCap = capacity * 2 || 65536;
|
|
112
|
+
const newMatrix = Buffer.alloc(newCap * vecBytes);
|
|
113
|
+
matrix.copy(newMatrix, 0);
|
|
114
|
+
matrix = newMatrix;
|
|
115
|
+
capacity = newCap;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const process_body = (buf: Buffer, start: number) => {
|
|
119
|
+
let off = start;
|
|
120
|
+
while (off < buf.length && !stopped) {
|
|
121
|
+
if (word === null) {
|
|
122
|
+
const sp = buf.indexOf(0x20, off);
|
|
123
|
+
if (sp === -1) {
|
|
124
|
+
// Word split across chunks (or the whole chunk is still a word).
|
|
125
|
+
word_tail =
|
|
126
|
+
word_tail.length > 0 ? Buffer.concat([word_tail, buf.subarray(off)]) : Buffer.from(buf.subarray(off));
|
|
127
|
+
off = buf.length;
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
word =
|
|
131
|
+
word_tail.length > 0
|
|
132
|
+
? word_tail.toString("utf8") + buf.toString("utf8", off, sp)
|
|
133
|
+
: buf.toString("utf8", off, sp);
|
|
134
|
+
word_tail = EMPTY;
|
|
135
|
+
off = sp + 1;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const w = word;
|
|
139
|
+
const existing = index.get(w);
|
|
140
|
+
const isNew = existing === undefined;
|
|
141
|
+
const r = isNew ? rows : existing;
|
|
142
|
+
if (isNew) {
|
|
143
|
+
if (rows >= capacity) grow();
|
|
144
|
+
index.set(w, r);
|
|
145
|
+
words.push(w);
|
|
146
|
+
rows++;
|
|
147
|
+
}
|
|
148
|
+
const rowOff = r * vecBytes;
|
|
149
|
+
|
|
150
|
+
if (vec_tail.length > 0) {
|
|
151
|
+
const need = vecBytes - vec_tail.length;
|
|
152
|
+
if (buf.length - off < need) {
|
|
153
|
+
vec_tail = Buffer.concat([vec_tail, buf.subarray(off)]);
|
|
154
|
+
off = buf.length;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
vec_tail.copy(matrix, rowOff, 0, vec_tail.length);
|
|
158
|
+
buf.copy(matrix, rowOff + vec_tail.length, off, off + need);
|
|
159
|
+
off += need;
|
|
160
|
+
vec_tail = EMPTY;
|
|
161
|
+
} else if (buf.length - off >= vecBytes) {
|
|
162
|
+
buf.copy(matrix, rowOff, off, off + vecBytes);
|
|
163
|
+
off += vecBytes;
|
|
164
|
+
} else {
|
|
165
|
+
vec_tail = Buffer.from(buf.subarray(off)); // vector split across chunks
|
|
166
|
+
off = buf.length;
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
word = null;
|
|
171
|
+
if (opts.limit !== undefined && rows >= opts.limit) {
|
|
172
|
+
stopped = true;
|
|
173
|
+
if (write_stream !== null) write_stream.destroy(); // partial cache: discard
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
pipeline.on("data", (chunk: Buffer) => {
|
|
180
|
+
if (stopped) return;
|
|
181
|
+
if (write_stream !== null) write_stream.write(chunk);
|
|
182
|
+
|
|
183
|
+
if (header === null) {
|
|
184
|
+
header_buf = header_buf.length > 0 ? Buffer.concat([header_buf, chunk]) : chunk;
|
|
185
|
+
const nl = header_buf.indexOf(0x0a);
|
|
186
|
+
if (nl === -1) return; // header split across chunks
|
|
187
|
+
const header_line = header_buf.subarray(0, nl).toString("utf8").trim();
|
|
188
|
+
const parts = header_line.split(" ");
|
|
189
|
+
const size = parseInt(parts[1], 10);
|
|
190
|
+
header = { count: parseInt(parts[0], 10), size };
|
|
191
|
+
vecBytes = size * 4;
|
|
192
|
+
// The header tells us the exact word count: pre-allocate once.
|
|
193
|
+
capacity = opts.limit !== undefined ? Math.min(opts.limit, header.count) : header.count;
|
|
194
|
+
matrix = Buffer.alloc(capacity * vecBytes);
|
|
195
|
+
// The body starts right after the header line, wherever it landed
|
|
196
|
+
// (in this chunk, or in a concatenated buffer if the header spanned).
|
|
197
|
+
process_body(header_buf, nl + 1);
|
|
198
|
+
header_buf = EMPTY;
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
process_body(chunk, 0);
|
|
203
|
+
if (stopped) pipeline.destroy();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
pipeline.on("end", () => {
|
|
207
|
+
if (write_stream !== null) {
|
|
208
|
+
cache_ok = true;
|
|
209
|
+
write_stream.end(); // renamed to the cache path in the 'close' handler
|
|
210
|
+
}
|
|
211
|
+
finish();
|
|
212
|
+
});
|
|
213
|
+
pipeline.on("close", finish);
|
|
214
|
+
pipeline.on("error", (err: any) => {
|
|
215
|
+
// Ignore the error raised by an intentional destroy due to `limit`...
|
|
216
|
+
if (stopped) finish();
|
|
217
|
+
else {
|
|
218
|
+
if (write_stream !== null) write_stream.destroy();
|
|
219
|
+
reject(err);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
}
|
package/test/glove.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { load_glove } from "../dist";
|
|
3
|
+
|
|
4
|
+
const model_path = path.join(process.cwd(), "./embeddings/glove.840B.300d.txt");
|
|
5
|
+
async function main() {
|
|
6
|
+
const model = await load_glove(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();
|
package/test/word2vec.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { load_word2vec } from "../dist";
|
|
3
|
+
|
|
4
|
+
const model_path = path.join(process.cwd(), "./embeddings/word2vec-300d-GoogleNews.bin.gz");
|
|
5
|
+
async function main() {
|
|
6
|
+
const model = await load_word2vec(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();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "es2017",
|
|
4
|
+
"module": "nodenext",
|
|
5
|
+
"lib": ["dom", "es6", "es2023", "esnext.asynciterable"],
|
|
6
|
+
"skipLibCheck": true,
|
|
7
|
+
"sourceMap": true,
|
|
8
|
+
"rootDir": "./src",
|
|
9
|
+
"outDir": "./dist",
|
|
10
|
+
"moduleResolution": "nodenext",
|
|
11
|
+
"removeComments": true,
|
|
12
|
+
"noImplicitAny": true,
|
|
13
|
+
"strict": true,
|
|
14
|
+
"strictNullChecks": true,
|
|
15
|
+
"strictFunctionTypes": true,
|
|
16
|
+
"noImplicitThis": true,
|
|
17
|
+
// "noUnusedLocals": true,
|
|
18
|
+
// "noUnusedParameters": true,
|
|
19
|
+
"noImplicitReturns": true,
|
|
20
|
+
"noFallthroughCasesInSwitch": true,
|
|
21
|
+
"allowSyntheticDefaultImports": true,
|
|
22
|
+
"esModuleInterop": true,
|
|
23
|
+
"emitDecoratorMetadata": true,
|
|
24
|
+
"experimentalDecorators": true,
|
|
25
|
+
"resolveJsonModule": true,
|
|
26
|
+
"declaration": true,
|
|
27
|
+
"types": ["node"]
|
|
28
|
+
},
|
|
29
|
+
"exclude": ["node_modules"],
|
|
30
|
+
"include": ["./src/**/*.ts", "./src/**/*.mjs"]
|
|
31
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "es2017",
|
|
4
|
+
"module": "nodenext",
|
|
5
|
+
"lib": ["dom", "es6", "es2023", "esnext.asynciterable"],
|
|
6
|
+
"skipLibCheck": true,
|
|
7
|
+
"sourceMap": true,
|
|
8
|
+
"outDir": "./dist",
|
|
9
|
+
"moduleResolution": "nodenext",
|
|
10
|
+
"removeComments": true,
|
|
11
|
+
"noImplicitAny": true,
|
|
12
|
+
"strict": true,
|
|
13
|
+
"strictNullChecks": true,
|
|
14
|
+
"strictFunctionTypes": true,
|
|
15
|
+
"noImplicitThis": true,
|
|
16
|
+
// "noUnusedLocals": true,
|
|
17
|
+
// "noUnusedParameters": true,
|
|
18
|
+
"noImplicitReturns": true,
|
|
19
|
+
"noFallthroughCasesInSwitch": true,
|
|
20
|
+
"allowSyntheticDefaultImports": true,
|
|
21
|
+
"esModuleInterop": true,
|
|
22
|
+
"emitDecoratorMetadata": true,
|
|
23
|
+
"experimentalDecorators": true,
|
|
24
|
+
"resolveJsonModule": true,
|
|
25
|
+
"declaration": true,
|
|
26
|
+
"types": ["node"]
|
|
27
|
+
},
|
|
28
|
+
"exclude": ["node_modules"],
|
|
29
|
+
"include": ["./src/**/*.ts", "./example/**/*.ts", "./test/**/*.ts"]
|
|
30
|
+
}
|