@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,3 @@
1
+ {
2
+ "js/ts.tsdk.path": "node_modules/typescript"
3
+ }
package/README.md CHANGED
@@ -1,3 +1,141 @@
1
- # Temporary Holding Version
1
+ # @scinorandex/embeddings
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optimized loaders for word-embedding models (GloVe text, fastText text, and word2vec binary) in Node.js.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { load_glove, load_fasttext, load_word2vec, type WordModel, type LoadOptions } from "@scinorandex/embeddings";
9
+
10
+ const glove = await load_glove("embeddings/glove.840B.300d.txt");
11
+ const ft = await load_fasttext("embeddings/fasttext-crawl-300d-2M.vec");
12
+ const w2v = await load_word2vec("embeddings/word2vec-300d-GoogleNews.bin.gz");
13
+
14
+ glove.similarity("king", "queen"); // cosine similarity
15
+ glove.get_nearest_words(glove.get_vector("king")!, 5);
16
+ glove.most_similar("the king of france");
17
+ glove.analogy("princess", ["king", "queen"]);
18
+ glove.get_vector("walk"); // WordVector | null
19
+ ```
20
+
21
+ Both loaders accept the same `LoadOptions`:
22
+
23
+ ```ts
24
+ interface LoadOptions {
25
+ /** Normalize vectors to unit length while loading. Default: `true`. */
26
+ normalize?: boolean;
27
+ /** Storage precision. Default: `"f32"`. */
28
+ precision?: "f32" | "f16" | "i8";
29
+ /** Load only the first `limit` words. */
30
+ limit?: number;
31
+ /** Keep a binary cache next to the source file and reuse it. Default: `false`. */
32
+ cache?: boolean;
33
+ }
34
+ ```
35
+
36
+ - **`precision`** trades memory for accuracy:
37
+ - `f32` (default) - exact, 4 bytes/value, `get_vector` returns zero-copy views.
38
+ - `f16` - half the matrix memory, similarity error ~2e-5.
39
+ - `i8` - per-row quantized integers, a quarter of the f32 matrix memory;
40
+ similarities are computed with integer dot products (error ~0.003).
41
+ - **`cache`** writes a binary file next to the source and reuses it on later
42
+ loads (written to a `.tmp` name and renamed atomically; a corrupt cache
43
+ falls back to parsing the source):
44
+ - word2vec `.gz` input: the decompressed file (same path without `.gz`) -
45
+ skips gunzip.
46
+ - GloVe `.txt` input: `<name>.glovecache` (raw matrix + words) - skips the
47
+ text parse entirely.
48
+ - fastText `.vec` input: `<name>.fasttextcache` (raw matrix + words) -
49
+ skips the text parse entirely.
50
+
51
+ ## Performance
52
+
53
+ GloVe 840B 300d (2,196,017 words, 5.6 GB text) - original loader: **120.5 s
54
+ load, 4409 MB RSS**:
55
+
56
+ | Load path | Load time | RSS (steady) |
57
+ | ----------------------------------------------- | --------- | ------------ |
58
+ | `f32`, parallel (default) | 17.9 s | 3181 MB |
59
+ | `f32` + `cache: true` (cache hit) | **6.4 s** | 2891 MB |
60
+ | `f32` + `cache: true` (first run, writes cache) | ~24 s | ~3100 MB |
61
+ | `f16` | 20.0 s | 1755 MB |
62
+ | `i8` | 27.8 s | 1219 MB |
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
+
74
+ word2vec GoogleNews 300d (3,000,000 words, 1.7 GB `.gz`) - original loader:
75
+ **107.2 s load, 5130 MB RSS**:
76
+
77
+ | Load path | Load time | RSS (steady) |
78
+ | ---------------------------------------------- | --------- | ------------ |
79
+ | `f32` (default) | 18.5 s | 3856 MB |
80
+ | `f32` + `cache: true` (decompressed cache hit) | 13.0 s | 3858 MB |
81
+ | `f16` | 20.7 s | 2114 MB |
82
+ | `i8` | 31.4 s | 1315 MB |
83
+
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).
88
+
89
+ RSS figures are measured after the model is fully loaded and garbage has
90
+ settled (worker-thread teardown is asynchronous), with `tsx --expose-gc`.
91
+
92
+ ## Embedding database sources
93
+
94
+ - [Word2Vec GoogleNews 300d](https://github.com/mmihaltz/word2vec-GoogleNews-vectors/raw/refs/heads/master/GoogleNews-vectors-negative300.bin.gz)
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)
97
+
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.
101
+
102
+ ## Running tests and benches
103
+
104
+ ```sh
105
+ tsx test/glove.ts # public-API smoke test (GloVe)
106
+ tsx test/fasttext.ts # public-API smoke test (fastText)
107
+ tsx test/word2vec.ts # public-API smoke test (word2vec)
108
+
109
+ tsx --expose-gc bench/optimized.ts glove # one of: glove, glove-f16,
110
+ # glove-i8, glove-raw, w2v,
111
+ # w2v-f16, w2v-i8, w2v-cache
112
+ tsx --expose-gc bench/glove_cache_bench.ts build # build the GloVe cache
113
+ tsx --expose-gc bench/glove_cache_bench.ts read # load from the cache
114
+ npx -y -p typescript@5.8.3 tsc --noEmit -p tsconfig.json # typecheck
115
+ ```
116
+
117
+ `bench/float_check.ts` validates the fast float parser against `parseFloat`
118
+ bit-for-bit, and `bench/limit_check.ts` exercises the `limit` option paths.
119
+
120
+ ## Implementation notes
121
+
122
+ - **Flat matrix storage** (`src/models/matrix.ts`): one typed array holds the
123
+ whole vocabulary row-major; `get_vector` for `f32` hands back a zero-copy
124
+ `Float32Array` view. `finalize_model` applies normalization/quantization in
125
+ place.
126
+ - **Fast float parser** (`src/models/parse_fast.mjs`): byte-level, no
127
+ `split`/`parseFloat` in the hot path; bit-identical to `parseFloat` for all
128
+ tokens with <= 15 significant digits (verified on 59.9 M real GloVe
129
+ fields), with a `parseFloat` fallback for exotic tokens.
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.
138
+ - **Cache writes** are chunked to <= 1 GiB per `fd.write` call: Node's
139
+ `writev`-based plumbing (used by `WriteStream` and single large
140
+ `fs.read`/`fs.write` calls) 32-bit-limits a single operation to 2 GiB,
141
+ while the GloVe matrix alone is 2.6 GB.
@@ -0,0 +1,41 @@
1
+ import path from "node:path";
2
+ import { load_word2vec, load_glove } from "../src";
3
+
4
+ const which = process.argv[2] === "glove" ? "glove" : "w2v";
5
+
6
+ function rssMB() {
7
+ return process.memoryUsage.rss() / 1024 / 1024;
8
+ }
9
+
10
+ async function main() {
11
+ const model_path = which === "glove"
12
+ ? path.join(process.cwd(), "embeddings/glove.840B.300d.txt")
13
+ : path.join(process.cwd(), "embeddings/word2vec-300d-GoogleNews.bin.gz");
14
+
15
+ const rss0 = rssMB();
16
+ const t0 = performance.now();
17
+ const model = which === "glove" ? await load_glove(model_path) : await load_word2vec(model_path);
18
+ const t1 = performance.now();
19
+ const rss1 = rssMB();
20
+
21
+ // Sanity / query-side benchmark
22
+ const t2 = performance.now();
23
+ const v = model.get_vector("king");
24
+ const s = model.similarity("king", "queen");
25
+ const near = v ? model.get_nearest_words(v, 5) : null;
26
+ const t3 = performance.now();
27
+
28
+ console.log(JSON.stringify({
29
+ model: which,
30
+ words: model.words,
31
+ size: model.size,
32
+ load_ms: Math.round(t1 - t0),
33
+ query_ms: Math.round(t3 - t2),
34
+ rss_start_MB: Math.round(rss0),
35
+ rss_after_load_MB: Math.round(rss1),
36
+ king_queen_sim: s,
37
+ nearest: near,
38
+ }));
39
+ }
40
+
41
+ main();
@@ -0,0 +1,123 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { FloatParser } from "../src/models/parse_fast.mjs";
4
+
5
+ // --- 1) Synthetic edge cases -------------------------------------------------
6
+ const cases = [
7
+ "0.123456", "-0.082752", "2.0817", "123", "-123", "+45", ".5", "-.25", "5.",
8
+ "1e5", "1E5", "1.5e-3", "-2.5E+10", "3e+2", "0.000001", "0.99999999999999999999", // >15 digits
9
+ "12345678901234567890.12345678901234567890", // long
10
+ "nan", "inf", "-inf", "NaN", "Infinity", "-Infinity",
11
+ "1e400", "-1e-400", "0", "-0", "12345678901234567", // 17 digits
12
+ "1e", "2.5E", "4.0447e-05", "1.0e-30", "9.999999999999999e-31", "123.456e2",
13
+ "-0.000040447", "7e-32", "1.5e-300", "-1.5e-300",
14
+ ];
15
+
16
+ const parser = new FloatParser();
17
+ let failures = 0;
18
+ for (const c of cases) {
19
+ const buf = Buffer.from(c + " ");
20
+ parser.pos = 0;
21
+ const got = parser.next(buf, c.length);
22
+ const want = parseFloat(c);
23
+ const ok = (Object.is(got, want) || (Number.isFinite(want) && Math.abs(got - want) <= Math.abs(want) * 1e-15)) &&
24
+ parser.pos === c.length;
25
+ if (!ok) {
26
+ failures++;
27
+ console.log(`FAIL synthetic: ${JSON.stringify(c)} got=${got} want=${want} pos=${parser.pos} len=${c.length}`);
28
+ }
29
+ }
30
+ console.log(`synthetic: ${cases.length - failures}/${cases.length} ok`);
31
+
32
+ // --- 2) Real GloVe data: compare every field against parseFloat --------------
33
+ const model_path = path.join(process.cwd(), "embeddings/glove.840B.300d.txt");
34
+ const target_lines = 200_000;
35
+ const fd = fs.openSync(model_path, "r");
36
+ let buf = Buffer.alloc(1 << 20);
37
+ let lines = 0;
38
+ let fields = 0;
39
+ let mismatches = 0;
40
+ let ulp1 = 0; // values differing by 1 ulp in float32 (expected: ~0)
41
+
42
+ const check_line = (b: Buffer, start: number, end: number) => {
43
+ const sp = b.indexOf(0x20, start);
44
+ if (sp === -1 || sp === end) return;
45
+ parser.pos = sp + 1;
46
+ let i = sp + 1;
47
+ while (i < end) {
48
+ // reference: parseFloat of the token
49
+ let f = i;
50
+ while (f < end && b[f] === 32) f++;
51
+ if (f >= end) break;
52
+ const tokStart = f;
53
+ while (f < end && b[f] !== 32 && b[f] !== 13) f++;
54
+ const want = parseFloat(b.toString("latin1", tokStart, f));
55
+ const got = parser.next(b, end);
56
+ fields++;
57
+ if (Object.is(got, want)) {
58
+ i = parser.pos;
59
+ continue;
60
+ }
61
+ // allow a 1 ulp float32 difference (float64 double-rounding edge)
62
+ const g32 = new Float32Array([got])[0];
63
+ const w32 = new Float32Array([want])[0];
64
+ if (g32 === w32) {
65
+ ulp1++;
66
+ } else {
67
+ mismatches++;
68
+ if (mismatches < 10)
69
+ console.log(`MISMATCH at field ${fields}: token=${JSON.stringify(b.toString("latin1", tokStart, f))} got=${got} want=${want}`);
70
+ }
71
+ i = parser.pos;
72
+ }
73
+ };
74
+
75
+ let tail = Buffer.alloc(0);
76
+ let bytes = 0;
77
+ while (lines < target_lines) {
78
+ const n = fs.readSync(fd, buf, 0, buf.length, bytes);
79
+ if (n === 0) break;
80
+ bytes += n;
81
+ if (tail.length > 0) {
82
+ const nl = buf.indexOf(0x0a, 0, n);
83
+ if (nl === -1) {
84
+ tail = Buffer.concat([tail, buf.subarray(0, n)]);
85
+ continue;
86
+ }
87
+ const line = Buffer.concat([tail, buf.subarray(0, nl + 1)]);
88
+ tail = Buffer.alloc(0);
89
+ check_line(line, 0, nl);
90
+ lines++;
91
+ let s = nl + 1;
92
+ while (s < n) {
93
+ const nl2 = buf.indexOf(0x0a, s);
94
+ if (nl2 === -1) {
95
+ tail = Buffer.from(buf.subarray(s, n));
96
+ s = n;
97
+ break;
98
+ }
99
+ check_line(buf, s, nl2);
100
+ lines++;
101
+ s = nl2 + 1;
102
+ }
103
+ } else {
104
+ let s = 0;
105
+ while (s < n) {
106
+ const nl = buf.indexOf(0x0a, s);
107
+ if (nl === -1) {
108
+ tail = Buffer.from(buf.subarray(s, n));
109
+ break;
110
+ }
111
+ check_line(buf, s, nl);
112
+ lines++;
113
+ s = nl + 1;
114
+ if (lines >= target_lines) break;
115
+ }
116
+ }
117
+ }
118
+ fs.closeSync(fd);
119
+
120
+ console.log(
121
+ `glove: lines=${lines} fields=${fields} exact=${fields - mismatches - ulp1} float32-identical-but-float64-off=${ulp1} mismatched=${mismatches}`,
122
+ );
123
+ if (mismatches > 0) process.exit(1);
@@ -0,0 +1,44 @@
1
+ // GloVe cache build (first run) + cache-hit read (second run) benchmark.
2
+ // usage: tsx --expose-gc bench/glove_cache_bench.ts [build|read]
3
+ import path from "node:path";
4
+ import { load_glove } from "../src";
5
+
6
+ const mode = process.argv[2] ?? "build";
7
+ const model_path = path.join(process.cwd(), "embeddings/glove.840B.300d.txt");
8
+
9
+ function rssMB() {
10
+ return process.memoryUsage.rss() / 1024 / 1024;
11
+ }
12
+
13
+ async function main() {
14
+ const rss0 = rssMB();
15
+ const t0 = performance.now();
16
+ const model = await load_glove(model_path, { cache: true });
17
+ const t1 = performance.now();
18
+ await new Promise((r) => setTimeout(r, 3000));
19
+ const gc = (globalThis as any).gc;
20
+ if (typeof gc === "function") {
21
+ gc();
22
+ gc();
23
+ }
24
+ const rss1 = rssMB();
25
+ const t2 = performance.now();
26
+ const s = model.similarity("king", "queen");
27
+ const v = model.get_vector("king");
28
+ const near = v ? model.get_nearest_words(v, 5) : null;
29
+ const t3 = performance.now();
30
+ console.log(
31
+ JSON.stringify({
32
+ mode,
33
+ words: model.words,
34
+ load_ms: Math.round(t1 - t0),
35
+ query_ms: Math.round(t3 - t2),
36
+ rss_start_MB: Math.round(rss0),
37
+ rss_after_load_MB: Math.round(rss1),
38
+ king_queen_sim: s,
39
+ nearest: near,
40
+ }),
41
+ );
42
+ }
43
+
44
+ main();
@@ -0,0 +1,32 @@
1
+ import path from "node:path";
2
+ import { load_glove, load_word2vec } from "../src";
3
+
4
+ const glove_path = path.join(process.cwd(), "embeddings/glove.840B.300d.txt");
5
+ const w2v_path = path.join(process.cwd(), "embeddings/word2vec-300d-GoogleNews.bin.gz");
6
+
7
+ async function main() {
8
+ // GloVe text with limit (sequential path)
9
+ const g = await load_glove(glove_path, { limit: 5000 });
10
+ console.log(JSON.stringify({
11
+ glove_limit: g.words,
12
+ king_in: g.get_vector("king") !== null,
13
+ sim: g.similarity("king", "queen"),
14
+ }));
15
+
16
+ // GloVe cache read with limit
17
+ const g2 = await load_glove(glove_path, { limit: 5000, cache: true });
18
+ console.log(JSON.stringify({
19
+ glove_cache_limit: g2.words,
20
+ king_in: g2.get_vector("king") !== null,
21
+ sim: g2.similarity("king", "queen"),
22
+ }));
23
+
24
+ // word2vec with limit
25
+ const w = await load_word2vec(w2v_path, { limit: 100000 });
26
+ console.log(JSON.stringify({
27
+ w2v_limit: w.words,
28
+ king_in: w.get_vector("king") !== null,
29
+ sim: w.similarity("king", "queen"),
30
+ }));
31
+ }
32
+ main();
@@ -0,0 +1,17 @@
1
+ import path from "node:path";
2
+ import { load_glove } from "../src";
3
+
4
+ const model_path = path.join(process.cwd(), "embeddings/glove.840B.300d.txt");
5
+ async function main() {
6
+ const m = await load_glove(model_path);
7
+ const mu0 = process.memoryUsage();
8
+ (globalThis as any).gc();
9
+ (globalThis as any).gc();
10
+ const mu1 = process.memoryUsage();
11
+ console.log(JSON.stringify({
12
+ before_gc: { rss: mu0.rss / 1e6, heapTotal: mu0.heapTotal / 1e6, heapUsed: mu0.heapUsed / 1e6, external: mu0.external / 1e6, arrayBuffers: (mu0 as any).arrayBuffers / 1e6 },
13
+ after_gc: { rss: mu1.rss / 1e6, heapTotal: mu1.heapTotal / 1e6, heapUsed: mu1.heapUsed / 1e6, external: mu1.external / 1e6, arrayBuffers: (mu1 as any).arrayBuffers / 1e6 },
14
+ words: m.words,
15
+ }, null, 1));
16
+ }
17
+ main();
@@ -0,0 +1,82 @@
1
+ import path from "node:path";
2
+ import { load_word2vec, load_glove } from "../src";
3
+
4
+ // usage: tsx bench/optimized.ts <variant>
5
+ // variants: w2v | w2v-f16 | w2v-i8 | glove | glove-f16 | glove-i8 | glove-raw
6
+ const variant = process.argv[2] ?? "w2v";
7
+
8
+ function rssMB() {
9
+ return process.memoryUsage.rss() / 1024 / 1024;
10
+ }
11
+
12
+ function options_for(variant: string): { model: string; options?: any } {
13
+ const is_glove = variant.startsWith("glove");
14
+ const model = is_glove
15
+ ? path.join(process.cwd(), "embeddings/glove.840B.300d.txt")
16
+ : path.join(process.cwd(), "embeddings/word2vec-300d-GoogleNews.bin.gz");
17
+ switch (variant) {
18
+ case "w2v-f16":
19
+ return { model, options: { precision: "f16" } };
20
+ case "w2v-i8":
21
+ return { model, options: { precision: "i8" } };
22
+ case "w2v-cache":
23
+ return { model, options: { cache: true } };
24
+ case "glove-f16":
25
+ return { model, options: { precision: "f16" } };
26
+ case "glove-i8":
27
+ return { model, options: { precision: "i8" } };
28
+ case "glove-raw":
29
+ return { model, options: { normalize: false } };
30
+ default:
31
+ return { model };
32
+ }
33
+ }
34
+
35
+ async function main() {
36
+ const { model: model_path, options } = options_for(variant);
37
+ const rss0 = rssMB();
38
+ const t0 = performance.now();
39
+ const model = variant.startsWith("glove") ? await load_glove(model_path, options) : await load_word2vec(model_path, options);
40
+ const t1 = performance.now();
41
+ // Let deferred deallocations (worker-isolate teardown) settle, then force
42
+ // GCs so RSS reflects the steady-state model size.
43
+ await new Promise((r) => setTimeout(r, 3000));
44
+ const gc = (globalThis as any).gc;
45
+ if (typeof gc === "function") {
46
+ gc();
47
+ gc();
48
+ }
49
+ const rss1 = rssMB();
50
+
51
+ // Same workload as bench/baseline.ts for comparability:
52
+ const t2 = performance.now();
53
+ const v = model.get_vector("king");
54
+ const s = model.similarity("king", "queen");
55
+ const near = v ? model.get_nearest_words(v, 5) : null;
56
+ const t3 = performance.now();
57
+
58
+ // Extended workload: phrase search + analogy (as in test/*.ts)
59
+ const t4 = performance.now();
60
+ const ms = model.most_similar("king queen", 5);
61
+ const an = model.analogy("prince", ["king", "queen"]);
62
+ const t5 = performance.now();
63
+
64
+ console.log(
65
+ JSON.stringify({
66
+ variant,
67
+ words: model.words,
68
+ size: model.size,
69
+ load_ms: Math.round(t1 - t0),
70
+ query_ms: Math.round(t3 - t2), // similarity + nearest-5
71
+ phrase_analogy_ms: Math.round(t5 - t4),
72
+ rss_start_MB: Math.round(rss0),
73
+ rss_after_load_MB: Math.round(rss1),
74
+ king_queen_sim: s,
75
+ nearest: near,
76
+ most_similar: ms,
77
+ analogy_top3: an.slice(0, 3),
78
+ }),
79
+ );
80
+ }
81
+
82
+ main();
@@ -0,0 +1,26 @@
1
+ export declare class WordVector {
2
+ readonly word: string | null;
3
+ readonly values: Float32Array;
4
+ constructor(word: string | null, values: Float32Array);
5
+ add(other: WordVector): WordVector;
6
+ subtract(other: WordVector): WordVector;
7
+ to_number_array(): number[];
8
+ }
9
+ export interface WordDist {
10
+ word: string;
11
+ dist: number;
12
+ }
13
+ export interface WordModel {
14
+ words: number;
15
+ size: number;
16
+ get_vector(word: string): WordVector | null;
17
+ get_vectors(words?: string[]): WordVector[];
18
+ similarity(word1: string, word2: string): number | null;
19
+ get_nearest_word(vec: WordVector | Float32Array): WordDist;
20
+ get_nearest_words(vec: WordVector | Float32Array, n?: number): WordDist[];
21
+ most_similar(phrase: string, n?: number): WordDist[] | null;
22
+ analogy(word: string, pair: [string, string], n?: number): WordDist[];
23
+ get_zero_vector(): WordVector;
24
+ }
25
+ export declare function create_model(vectors: Map<string, WordVector>, size: number): WordModel;
26
+ export declare function normalize(values: Float32Array): Float32Array;