@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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "js/ts.tsdk.path": "node_modules/typescript"
3
+ }
package/README.md CHANGED
@@ -1,3 +1,122 @@
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 and word2vec binary) in Node.js.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { load_glove, load_word2vec, type WordModel, type LoadOptions } from "@scinorandex/embeddings";
9
+
10
+ const glove = await load_glove("embeddings/glove.840B.300d.txt");
11
+ const w2v = await load_word2vec("embeddings/word2vec-300d-GoogleNews.bin.gz");
12
+
13
+ glove.similarity("king", "queen"); // cosine similarity
14
+ glove.get_nearest_words(glove.get_vector("king")!, 5);
15
+ glove.most_similar("the king of france");
16
+ glove.analogy("princess", ["king", "queen"]);
17
+ glove.get_vector("walk"); // WordVector | null
18
+ ```
19
+
20
+ Both loaders accept the same `LoadOptions`:
21
+
22
+ ```ts
23
+ interface LoadOptions {
24
+ /** Normalize vectors to unit length while loading. Default: `true`. */
25
+ normalize?: boolean;
26
+ /** Storage precision. Default: `"f32"`. */
27
+ precision?: "f32" | "f16" | "i8";
28
+ /** Load only the first `limit` words. */
29
+ limit?: number;
30
+ /** Keep a binary cache next to the source file and reuse it. Default: `false`. */
31
+ cache?: boolean;
32
+ }
33
+ ```
34
+
35
+ - **`precision`** trades memory for accuracy:
36
+ - `f32` (default) - exact, 4 bytes/value, `get_vector` returns zero-copy views.
37
+ - `f16` - half the matrix memory, similarity error ~2e-5.
38
+ - `i8` - per-row quantized integers, a quarter of the f32 matrix memory;
39
+ similarities are computed with integer dot products (error ~0.003).
40
+ - **`cache`** writes a binary file next to the source and reuses it on later
41
+ loads (written to a `.tmp` name and renamed atomically; a corrupt cache
42
+ falls back to parsing the source):
43
+ - word2vec `.gz` input: the decompressed file (same path without `.gz`) -
44
+ skips gunzip.
45
+ - GloVe `.txt` input: `<name>.glovecache` (raw matrix + words) - skips the
46
+ text parse entirely.
47
+
48
+ ## Performance
49
+
50
+ GloVe 840B 300d (2,196,017 words, 5.6 GB text) - original loader: **120.5 s
51
+ load, 4409 MB RSS**:
52
+
53
+ | Load path | Load time | RSS (steady) |
54
+ | ----------------------------------------------- | --------- | ------------ |
55
+ | `f32`, parallel (default) | 17.9 s | 3181 MB |
56
+ | `f32` + `cache: true` (cache hit) | **6.4 s** | 2891 MB |
57
+ | `f32` + `cache: true` (first run, writes cache) | ~24 s | ~3100 MB |
58
+ | `f16` | 20.0 s | 1755 MB |
59
+ | `i8` | 27.8 s | 1219 MB |
60
+
61
+ word2vec GoogleNews 300d (3,000,000 words, 1.7 GB `.gz`) - original loader:
62
+ **107.2 s load, 5130 MB RSS**:
63
+
64
+ | Load path | Load time | RSS (steady) |
65
+ | ---------------------------------------------- | --------- | ------------ |
66
+ | `f32` (default) | 18.5 s | 3856 MB |
67
+ | `f32` + `cache: true` (decompressed cache hit) | 13.0 s | 3858 MB |
68
+ | `f16` | 20.7 s | 2114 MB |
69
+ | `i8` | 31.4 s | 1315 MB |
70
+
71
+ Query times (nearest-10 over the full vocabulary): ~0.8 s for GloVe, ~1.1 s
72
+ for word2vec. All f32 results are bit-identical to the original loader's
73
+ (cosine similarities and nearest-neighbor lists match to full precision; f16
74
+ matches to ~2e-5).
75
+
76
+ RSS figures are measured after the model is fully loaded and garbage has
77
+ settled (worker-thread teardown is asynchronous), with `tsx --expose-gc`.
78
+
79
+ ## Embedding database sources
80
+
81
+ - [Word2Vec GoogleNews 300d](https://github.com/mmihaltz/word2vec-GoogleNews-vectors/raw/refs/heads/master/GoogleNews-vectors-negative300.bin.gz)
82
+ - [GloVe Common Crawl 300d](https://huggingface.co/stanfordnlp/glove/resolve/main/glove.840B.300d.zip)
83
+
84
+ This library is compatible with the canonical Word2Vec and GloVe distribution formats and can be used with any compatible pre-trained embedding database.
85
+
86
+ ## Running tests and benches
87
+
88
+ ```sh
89
+ tsx test/glove.ts # public-API smoke test (GloVe)
90
+ tsx test/word2vec.ts # public-API smoke test (word2vec)
91
+
92
+ tsx --expose-gc bench/optimized.ts glove # one of: glove, glove-f16,
93
+ # glove-i8, glove-raw, w2v,
94
+ # w2v-f16, w2v-i8, w2v-cache
95
+ tsx --expose-gc bench/glove_cache_bench.ts build # build the GloVe cache
96
+ tsx --expose-gc bench/glove_cache_bench.ts read # load from the cache
97
+ npx -y -p typescript@5.8.3 tsc --noEmit -p tsconfig.json # typecheck
98
+ ```
99
+
100
+ `bench/float_check.ts` validates the fast float parser against `parseFloat`
101
+ bit-for-bit, and `bench/limit_check.ts` exercises the `limit` option paths.
102
+
103
+ ## Implementation notes
104
+
105
+ - **Flat matrix storage** (`src/models/matrix.ts`): one typed array holds the
106
+ whole vocabulary row-major; `get_vector` for `f32` hands back a zero-copy
107
+ `Float32Array` view. `finalize_model` applies normalization/quantization in
108
+ place.
109
+ - **Fast float parser** (`src/models/parse_fast.mjs`): byte-level, no
110
+ `split`/`parseFloat` in the hot path; bit-identical to `parseFloat` for all
111
+ tokens with <= 15 significant digits (verified on 59.9 M real GloVe
112
+ fields), with a `parseFloat` fallback for exotic tokens.
113
+ - **Parallel GloVe parsing** (`src/models/glove.ts` + `glove_worker.mjs`):
114
+ the file is split into `min(availableParallelism(), 8)` byte ranges, each
115
+ parsed by a worker thread (plain-JS workers; they own a pre-window line so
116
+ no line is parsed by two workers). The main thread merges in file order,
117
+ deduplicating duplicate words in place. Small files, `limit` loads, and
118
+ worker failures fall back to a sequential read.
119
+ - **Cache writes** are chunked to <= 1 GiB per `fd.write` call: Node's
120
+ `writev`-based plumbing (used by `WriteStream` and single large
121
+ `fs.read`/`fs.write` calls) 32-bit-limits a single operation to 2 GiB,
122
+ 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;
package/dist/common.js ADDED
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WordVector = void 0;
4
+ exports.create_model = create_model;
5
+ exports.normalize = normalize;
6
+ class WordVector {
7
+ constructor(word, values) {
8
+ this.word = word;
9
+ this.values = values;
10
+ }
11
+ add(other) {
12
+ const values = new Float32Array(this.values.length);
13
+ for (let i = 0; i < values.length; i++)
14
+ values[i] = this.values[i] + other.values[i];
15
+ return new WordVector(null, values);
16
+ }
17
+ subtract(other) {
18
+ const values = new Float32Array(this.values.length);
19
+ for (let i = 0; i < values.length; i++)
20
+ values[i] = this.values[i] - other.values[i];
21
+ return new WordVector(null, values);
22
+ }
23
+ to_number_array() {
24
+ return [...this.values];
25
+ }
26
+ }
27
+ exports.WordVector = WordVector;
28
+ function create_model(vectors, size) {
29
+ const vocab = [...vectors.values()];
30
+ return {
31
+ words: vocab.length,
32
+ size,
33
+ get_vector(word) {
34
+ var _a;
35
+ return (_a = vectors.get(word)) !== null && _a !== void 0 ? _a : null;
36
+ },
37
+ get_zero_vector() {
38
+ return new WordVector(null, new Float32Array(size));
39
+ },
40
+ get_vectors(filter) {
41
+ if (!filter)
42
+ return vocab;
43
+ return vocab.filter((v) => filter.includes(word_of(v)));
44
+ },
45
+ similarity(word1, word2) {
46
+ const v1 = vectors.get(word1);
47
+ const v2 = vectors.get(word2);
48
+ if (!v1 || !v2)
49
+ return null;
50
+ if (word1 === word2)
51
+ return 1.0;
52
+ return dot(v1.values, v2.values);
53
+ },
54
+ get_nearest_word(vec) {
55
+ const values = normalize(to_values(vec));
56
+ let best_word = "";
57
+ let best_dist = -Infinity;
58
+ for (const v of vocab) {
59
+ const dist = dot(values, v.values);
60
+ if (dist > best_dist) {
61
+ best_dist = dist;
62
+ best_word = word_of(v);
63
+ }
64
+ }
65
+ return { word: best_word, dist: best_dist };
66
+ },
67
+ get_nearest_words(vec, n = 10) {
68
+ const values = normalize(to_values(vec));
69
+ const best_words = new Array(n).fill("");
70
+ const best_dists = new Array(n).fill(-1);
71
+ for (const v of vocab) {
72
+ insert_top_n(best_words, best_dists, word_of(v), dot(values, v.values));
73
+ }
74
+ return top_n_to_results(best_words, best_dists);
75
+ },
76
+ most_similar(phrase, n = 40) {
77
+ var _a;
78
+ const phrase_words = phrase.split(" ");
79
+ const phrase_set = new Set(phrase_words);
80
+ let found = false;
81
+ for (const w of phrase_words) {
82
+ if (vectors.has(w)) {
83
+ found = true;
84
+ }
85
+ else {
86
+ console.log(`Out of dictionary word: ${w}`);
87
+ }
88
+ }
89
+ if (!found)
90
+ return null;
91
+ const vec = new Float32Array(size);
92
+ for (const w of phrase_words) {
93
+ const values = (_a = vectors.get(w)) === null || _a === void 0 ? void 0 : _a.values;
94
+ if (values) {
95
+ for (let a = 0; a < size; a++) {
96
+ vec[a] += values[a];
97
+ }
98
+ }
99
+ }
100
+ const normalized = normalize(vec);
101
+ const best_words = new Array(n).fill("");
102
+ const best_dists = new Array(n).fill(-1);
103
+ for (const v of vocab) {
104
+ if (phrase_set.has(word_of(v)))
105
+ continue;
106
+ insert_top_n(best_words, best_dists, word_of(v), dot(normalized, v.values));
107
+ }
108
+ return top_n_to_results(best_words, best_dists);
109
+ },
110
+ analogy(word, pair, n = 40) {
111
+ if (typeof word !== "string")
112
+ throw new TypeError("Word of interest has to be supplied as string.");
113
+ if (!Array.isArray(pair))
114
+ throw new TypeError("Word pair has to be supplied in string Array.");
115
+ const phrase = [pair[0], pair[1], word];
116
+ for (const w of phrase) {
117
+ if (!vectors.has(w))
118
+ console.log(`Out of dictionary word: ${w}`);
119
+ }
120
+ if (phrase.some((w) => !vectors.has(w)))
121
+ throw new Error("Words of the analogy must all be in the model vocabulary.");
122
+ const word_vec = vectors.get(word).values;
123
+ const pair0_vec = vectors.get(pair[0]).values;
124
+ const pair1_vec = vectors.get(pair[1]).values;
125
+ const vec = new Float32Array(size);
126
+ for (let a = 0; a < size; a++) {
127
+ vec[a] = pair1_vec[a] - pair0_vec[a] + word_vec[a];
128
+ }
129
+ const normalized = normalize(vec);
130
+ const best_words = new Array(n).fill("");
131
+ const best_dists = new Array(n).fill(0);
132
+ const phrase_set = new Set(phrase);
133
+ for (const v of vocab) {
134
+ if (phrase_set.has(word_of(v)))
135
+ continue;
136
+ insert_top_n(best_words, best_dists, word_of(v), dot(normalized, v.values));
137
+ }
138
+ return top_n_to_results(best_words, best_dists);
139
+ },
140
+ };
141
+ }
142
+ function to_values(vec) {
143
+ return vec instanceof WordVector ? vec.values : vec;
144
+ }
145
+ function word_of(v) {
146
+ var _a;
147
+ return (_a = v.word) !== null && _a !== void 0 ? _a : "";
148
+ }
149
+ function normalize(values) {
150
+ let len = 0;
151
+ for (let a = 0; a < values.length; a++) {
152
+ len += values[a] * values[a];
153
+ }
154
+ len = Math.sqrt(len);
155
+ const out = new Float32Array(values.length);
156
+ for (let a = 0; a < values.length; a++) {
157
+ out[a] = values[a] / len;
158
+ }
159
+ return out;
160
+ }
161
+ function dot(a, b) {
162
+ let sum = 0;
163
+ for (let i = 0; i < a.length; i++)
164
+ sum += a[i] * b[i];
165
+ return sum;
166
+ }
167
+ function insert_top_n(best_words, best_dists, word, dist) {
168
+ for (let a = 0; a < best_words.length; a++) {
169
+ if (dist > best_dists[a]) {
170
+ for (let d = best_words.length - 1; d > a; d--) {
171
+ best_dists[d] = best_dists[d - 1];
172
+ best_words[d] = best_words[d - 1];
173
+ }
174
+ best_dists[a] = dist;
175
+ best_words[a] = word;
176
+ return;
177
+ }
178
+ }
179
+ }
180
+ function top_n_to_results(best_words, best_dists) {
181
+ return best_words.map((word, i) => ({ word, dist: best_dists[i] }));
182
+ }
183
+ //# sourceMappingURL=common.js.map