@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,193 @@
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_word2vec = load_word2vec;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_zlib_1 = __importDefault(require("node:zlib"));
9
+ const matrix_1 = require("./matrix");
10
+ const w2v_cache = new Map();
11
+ const EMPTY = Buffer.alloc(0);
12
+ async function load_word2vec(model_path, options) {
13
+ const opts = (0, matrix_1.resolve_options)(options);
14
+ const key = model_path + "\u0000" + JSON.stringify(opts);
15
+ const cached = w2v_cache.get(key);
16
+ if (cached)
17
+ return cached;
18
+ const is_gzip = model_path.endsWith(".gz");
19
+ let source_path = model_path;
20
+ let write_bin_path = null;
21
+ if (is_gzip && opts.cache) {
22
+ const bin_path = model_path.slice(0, -3);
23
+ try {
24
+ const gz_stat = await node_fs_1.default.promises.stat(model_path);
25
+ const bin_stat = await node_fs_1.default.promises.stat(bin_path);
26
+ if (bin_stat.mtimeMs >= gz_stat.mtimeMs)
27
+ source_path = bin_path;
28
+ else
29
+ write_bin_path = bin_path;
30
+ }
31
+ catch (_a) {
32
+ write_bin_path = bin_path;
33
+ }
34
+ }
35
+ const read_stream = node_fs_1.default.createReadStream(source_path, { highWaterMark: 1 << 22 });
36
+ const pipeline = source_path === model_path && is_gzip ? read_stream.pipe(node_zlib_1.default.createGunzip({ chunkSize: 4 << 20 })) : read_stream;
37
+ return new Promise((resolve, reject) => {
38
+ let header = null;
39
+ let header_buf = EMPTY;
40
+ let matrix = EMPTY;
41
+ let capacity = 0;
42
+ let vecBytes = 0;
43
+ let rows = 0;
44
+ const words = [];
45
+ const index = new Map();
46
+ let word = null;
47
+ let word_tail = EMPTY;
48
+ let vec_tail = EMPTY;
49
+ let stopped = false;
50
+ let resolved = false;
51
+ let write_stream = null;
52
+ let cache_ok = false;
53
+ if (write_bin_path !== null) {
54
+ const tmp_path = write_bin_path + ".tmp";
55
+ write_stream = node_fs_1.default.createWriteStream(tmp_path, { highWaterMark: 1 << 22 });
56
+ write_stream.on("error", (err) => reject(err));
57
+ write_stream.on("close", async () => {
58
+ if (!cache_ok) {
59
+ node_fs_1.default.promises.unlink(tmp_path).catch(() => undefined);
60
+ return;
61
+ }
62
+ try {
63
+ await node_fs_1.default.promises.rename(tmp_path, write_bin_path);
64
+ }
65
+ catch (err) {
66
+ reject(err);
67
+ }
68
+ });
69
+ }
70
+ const finish = () => {
71
+ if (resolved)
72
+ return;
73
+ resolved = true;
74
+ if (header === null) {
75
+ reject(new Error("Incomplete model file (missing header)"));
76
+ return;
77
+ }
78
+ const model = (0, matrix_1.finalize_model)(matrix, rows, header.size, words, index, opts);
79
+ w2v_cache.set(key, model);
80
+ resolve(model);
81
+ };
82
+ const grow = () => {
83
+ const newCap = capacity * 2 || 65536;
84
+ const newMatrix = Buffer.alloc(newCap * vecBytes);
85
+ matrix.copy(newMatrix, 0);
86
+ matrix = newMatrix;
87
+ capacity = newCap;
88
+ };
89
+ const process_body = (buf, start) => {
90
+ let off = start;
91
+ while (off < buf.length && !stopped) {
92
+ if (word === null) {
93
+ const sp = buf.indexOf(0x20, off);
94
+ if (sp === -1) {
95
+ word_tail =
96
+ word_tail.length > 0 ? Buffer.concat([word_tail, buf.subarray(off)]) : Buffer.from(buf.subarray(off));
97
+ off = buf.length;
98
+ break;
99
+ }
100
+ word =
101
+ word_tail.length > 0
102
+ ? word_tail.toString("utf8") + buf.toString("utf8", off, sp)
103
+ : buf.toString("utf8", off, sp);
104
+ word_tail = EMPTY;
105
+ off = sp + 1;
106
+ }
107
+ const w = word;
108
+ const existing = index.get(w);
109
+ const isNew = existing === undefined;
110
+ const r = isNew ? rows : existing;
111
+ if (isNew) {
112
+ if (rows >= capacity)
113
+ grow();
114
+ index.set(w, r);
115
+ words.push(w);
116
+ rows++;
117
+ }
118
+ const rowOff = r * vecBytes;
119
+ if (vec_tail.length > 0) {
120
+ const need = vecBytes - vec_tail.length;
121
+ if (buf.length - off < need) {
122
+ vec_tail = Buffer.concat([vec_tail, buf.subarray(off)]);
123
+ off = buf.length;
124
+ break;
125
+ }
126
+ vec_tail.copy(matrix, rowOff, 0, vec_tail.length);
127
+ buf.copy(matrix, rowOff + vec_tail.length, off, off + need);
128
+ off += need;
129
+ vec_tail = EMPTY;
130
+ }
131
+ else if (buf.length - off >= vecBytes) {
132
+ buf.copy(matrix, rowOff, off, off + vecBytes);
133
+ off += vecBytes;
134
+ }
135
+ else {
136
+ vec_tail = Buffer.from(buf.subarray(off));
137
+ off = buf.length;
138
+ break;
139
+ }
140
+ word = null;
141
+ if (opts.limit !== undefined && rows >= opts.limit) {
142
+ stopped = true;
143
+ if (write_stream !== null)
144
+ write_stream.destroy();
145
+ return;
146
+ }
147
+ }
148
+ };
149
+ pipeline.on("data", (chunk) => {
150
+ if (stopped)
151
+ return;
152
+ if (write_stream !== null)
153
+ write_stream.write(chunk);
154
+ if (header === null) {
155
+ header_buf = header_buf.length > 0 ? Buffer.concat([header_buf, chunk]) : chunk;
156
+ const nl = header_buf.indexOf(0x0a);
157
+ if (nl === -1)
158
+ return;
159
+ const header_line = header_buf.subarray(0, nl).toString("utf8").trim();
160
+ const parts = header_line.split(" ");
161
+ const size = parseInt(parts[1], 10);
162
+ header = { count: parseInt(parts[0], 10), size };
163
+ vecBytes = size * 4;
164
+ capacity = opts.limit !== undefined ? Math.min(opts.limit, header.count) : header.count;
165
+ matrix = Buffer.alloc(capacity * vecBytes);
166
+ process_body(header_buf, nl + 1);
167
+ header_buf = EMPTY;
168
+ return;
169
+ }
170
+ process_body(chunk, 0);
171
+ if (stopped)
172
+ pipeline.destroy();
173
+ });
174
+ pipeline.on("end", () => {
175
+ if (write_stream !== null) {
176
+ cache_ok = true;
177
+ write_stream.end();
178
+ }
179
+ finish();
180
+ });
181
+ pipeline.on("close", finish);
182
+ pipeline.on("error", (err) => {
183
+ if (stopped)
184
+ finish();
185
+ else {
186
+ if (write_stream !== null)
187
+ write_stream.destroy();
188
+ reject(err);
189
+ }
190
+ });
191
+ });
192
+ }
193
+ //# sourceMappingURL=word2vec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"word2vec.js","sourceRoot":"","sources":["../../src/models/word2vec.ts"],"names":[],"mappings":";;;;;;AAAA,sDAAyB;AACzB,0DAA6B;AAC7B,qCAA6E;AAI7E,MAAM,SAAS,GAAG,IAAI,GAAG,EAAqB,CAAC;AAE/C,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAmBvB,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,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAClC,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAE1B,MAAM,OAAO,GAAG,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAI3C,IAAI,WAAW,GAAG,UAAU,CAAC;IAC7B,IAAI,cAAc,GAAkB,IAAI,CAAC;IACzC,IAAI,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QAC1B,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACzC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,iBAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YACnD,MAAM,QAAQ,GAAG,MAAM,iBAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAClD,IAAI,QAAQ,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;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EAAE,CAAC;iBACjB,CAAC;gBACJ,IAAI,YAAY,KAAK,IAAI;oBAAE,YAAY,CAAC,OAAO,EAAE,CAAC;gBAClD,MAAM,CAAC,GAAG,CAAC,CAAC;YACd,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
package/opencode.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "https://opencode.ai/config.json",
3
+ "policies": [{ "action": "provider.use", "resource": "llama", "effect": "allow" }],
4
+ "providers": {
5
+ "llama": {
6
+ "name": "llama.cpp",
7
+ "package": "aisdk:@ai-sdk/openai-compatible",
8
+ "settings": { "baseURL": "http://192.168.0.78:8080/v1" },
9
+ "models": {
10
+ "Qwen3.8-27B-ASCII-Condensed-UD-IQ4_XS": {
11
+ "modelID": "bsaleh/Qwen3.8-27B-ASCII-Condensed:UD-IQ4_XS",
12
+ "name": "bsaleh/Qwen3.8-27B-ASCII-Condensed:UD-IQ4_XS",
13
+ "limit": { "context": 262144, "output": 131072 }
14
+ }
15
+ }
16
+ }
17
+ },
18
+ "mcp": {
19
+ "servers": {
20
+ "searxng": {
21
+ "type": "local",
22
+ "command": ["npx", "-y", "@nitish-raj/searxng-mcp-bridge"],
23
+ "environment": { "SEARXNG_INSTANCE_URL": "http://192.168.0.109:6967" }
24
+ }
25
+ }
26
+ }
27
+ }
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "@scinorandex/embeddings",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "tc": "tsc --noEmit",
8
+ "build": "tsc --project tsconfig.build.json && node scripts/copy-assets.mjs"
9
+ },
10
+ "keywords": [],
11
+ "author": "",
12
+ "license": "ISC",
13
+ "type": "commonjs",
14
+ "dependencies": {},
15
+ "devDependencies": {
16
+ "@types/node": "^26.6.6",
17
+ "typescript": "^7.0.2"
18
+ }
19
+ }
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copy non-TypeScript assets (e.g. the plain-JS `.mjs` float parser and
4
+ * GloVe worker) from `src/` to `dist/`, preserving the directory structure.
5
+ * tsc only emits `.ts` sources, so any other runtime asset must be copied
6
+ * over by hand after the build. Runs after `tsc` in the `build` script.
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
13
+ const src = path.join(root, "src");
14
+ const out = path.join(root, "dist");
15
+
16
+ const is_ts = (name) => /\.(ts|tsx|mts|cts)$/.test(name);
17
+
18
+ const walk = (dir) => {
19
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
20
+ const from = path.join(dir, entry.name);
21
+ if (entry.isDirectory()) {
22
+ walk(from);
23
+ continue;
24
+ }
25
+ if (is_ts(entry.name)) continue; // emitted by tsc
26
+ const to = path.join(out, path.relative(src, from));
27
+ fs.mkdirSync(path.dirname(to), { recursive: true });
28
+ fs.copyFileSync(from, to);
29
+ }
30
+ };
31
+
32
+ walk(src);
package/src/common.ts ADDED
@@ -0,0 +1,260 @@
1
+ export class WordVector {
2
+ constructor(
3
+ /** the word this vector represents (`null` for computed vectors such as sums) */
4
+ public readonly word: string | null,
5
+ /** the elements of the word vector */
6
+ public readonly values: Float32Array,
7
+ ) {}
8
+
9
+ /**
10
+ * Add another word vector to this word vector.
11
+ * @returns a new WordVector holding the result of the addition
12
+ */
13
+ add(other: WordVector): WordVector {
14
+ const values = new Float32Array(this.values.length);
15
+ for (let i = 0; i < values.length; i++) values[i] = this.values[i] + other.values[i];
16
+ return new WordVector(null, values);
17
+ }
18
+
19
+ /**
20
+ * Subtract another word vector from this word vector.
21
+ * @returns a new WordVector holding the result of the subtraction
22
+ */
23
+ subtract(other: WordVector): WordVector {
24
+ const values = new Float32Array(this.values.length);
25
+ for (let i = 0; i < values.length; i++) values[i] = this.values[i] - other.values[i];
26
+ return new WordVector(null, values);
27
+ }
28
+
29
+ to_number_array(): number[] {
30
+ return [...this.values];
31
+ }
32
+ }
33
+
34
+ /** A word and its distance (cosine similarity) to a query vector. */
35
+ export interface WordDist {
36
+ word: string;
37
+ dist: number;
38
+ }
39
+
40
+ /** A loaded word embedding model (word2vec or GloVe). */
41
+ export interface WordModel {
42
+ /** number of words in the vocabulary */
43
+ words: number;
44
+ /** dimensionality of the word vectors */
45
+ size: number;
46
+
47
+ /** Get the vector for a single word, or `null` if the word is out of dictionary. */
48
+ get_vector(word: string): WordVector | null;
49
+
50
+ /** Get all word vectors, or only those whose word is contained in `words`. */
51
+ get_vectors(words?: string[]): WordVector[];
52
+
53
+ /** Dot-product similarity of two words, or `null` if at least one is out of dictionary. */
54
+ similarity(word1: string, word2: string): number | null;
55
+
56
+ /** The word most similar to the given vector. */
57
+ get_nearest_word(vec: WordVector | Float32Array): WordDist;
58
+
59
+ /** The `n` words most similar to the given vector (default 10). */
60
+ get_nearest_words(vec: WordVector | Float32Array, n?: number): WordDist[];
61
+
62
+ /**
63
+ * The `n` words most similar to a space-separated phrase (default 40).
64
+ * Returns `null` when none of the phrase words are in the dictionary.
65
+ */
66
+ most_similar(phrase: string, n?: number): WordDist[] | null;
67
+
68
+ /**
69
+ * Words most similar to the vector `pair[1] - pair[0] + word` (default 40).
70
+ * The words of `pair` and `word` must all be in the dictionary.
71
+ */
72
+ analogy(word: string, pair: [string, string], n?: number): WordDist[];
73
+
74
+ get_zero_vector(): WordVector;
75
+ }
76
+
77
+ /**
78
+ * Create a word model from a map of word vectors.
79
+ * Vectors are expected to be stored normalized, so a dot product equals cosine similarity.
80
+ */
81
+ export function create_model(vectors: Map<string, WordVector>, size: number): WordModel {
82
+ const vocab = [...vectors.values()];
83
+
84
+ return {
85
+ words: vocab.length,
86
+ size,
87
+
88
+ get_vector(word: string): WordVector | null {
89
+ return vectors.get(word) ?? null;
90
+ },
91
+
92
+ get_zero_vector() {
93
+ return new WordVector(null, new Float32Array(size));
94
+ },
95
+
96
+ get_vectors(filter?: string[]): WordVector[] {
97
+ if (!filter) return vocab;
98
+ return vocab.filter((v) => filter.includes(word_of(v)));
99
+ },
100
+
101
+ similarity(word1: string, word2: string): number | null {
102
+ const v1 = vectors.get(word1);
103
+ const v2 = vectors.get(word2);
104
+ // Case: at least one of the words is not available in the vocabulary
105
+ if (!v1 || !v2) return null;
106
+ // Case: word1 and word2 are identical
107
+ if (word1 === word2) return 1.0;
108
+ // Vectors are stored normalized, so a dot product equals cosine similarity
109
+ return dot(v1.values, v2.values);
110
+ },
111
+
112
+ get_nearest_word(vec: WordVector | Float32Array): WordDist {
113
+ const values = normalize(to_values(vec));
114
+ let best_word = "";
115
+ let best_dist = -Infinity;
116
+ for (const v of vocab) {
117
+ const dist = dot(values, v.values);
118
+ if (dist > best_dist) {
119
+ best_dist = dist;
120
+ best_word = word_of(v);
121
+ }
122
+ }
123
+ return { word: best_word, dist: best_dist };
124
+ },
125
+
126
+ get_nearest_words(vec: WordVector | Float32Array, n = 10): WordDist[] {
127
+ const values = normalize(to_values(vec));
128
+ const best_words = new Array<string>(n).fill("");
129
+ const best_dists = new Array<number>(n).fill(-1);
130
+ for (const v of vocab) {
131
+ insert_top_n(best_words, best_dists, word_of(v), dot(values, v.values));
132
+ }
133
+ return top_n_to_results(best_words, best_dists);
134
+ },
135
+
136
+ most_similar(phrase: string, n = 40): WordDist[] | null {
137
+ const phrase_words = phrase.split(" ");
138
+ const phrase_set = new Set(phrase_words);
139
+
140
+ // Check whether at least one phrase word is in the dictionary...
141
+ let found = false;
142
+ for (const w of phrase_words) {
143
+ if (vectors.has(w)) {
144
+ found = true;
145
+ } else {
146
+ console.log(`Out of dictionary word: ${w}`);
147
+ }
148
+ }
149
+
150
+ // All words are out-of-dictionary
151
+ if (!found) return null;
152
+
153
+ const vec = new Float32Array(size);
154
+ for (const w of phrase_words) {
155
+ const values = vectors.get(w)?.values;
156
+ if (values) {
157
+ for (let a = 0; a < size; a++) {
158
+ vec[a] += values[a];
159
+ }
160
+ }
161
+ }
162
+
163
+ // Normalize the summed vector...
164
+ const normalized = normalize(vec);
165
+
166
+ const best_words = new Array<string>(n).fill("");
167
+ const best_dists = new Array<number>(n).fill(-1);
168
+ for (const v of vocab) {
169
+ // Skip words that are part of the phrase
170
+ if (phrase_set.has(word_of(v))) continue;
171
+ insert_top_n(best_words, best_dists, word_of(v), dot(normalized, v.values));
172
+ }
173
+ return top_n_to_results(best_words, best_dists);
174
+ },
175
+
176
+ analogy(word: string, pair: [string, string], n = 40): WordDist[] {
177
+ if (typeof word !== "string") throw new TypeError("Word of interest has to be supplied as string.");
178
+ if (!Array.isArray(pair)) throw new TypeError("Word pair has to be supplied in string Array.");
179
+
180
+ const phrase = [pair[0], pair[1], word];
181
+ for (const w of phrase) {
182
+ if (!vectors.has(w)) console.log(`Out of dictionary word: ${w}`);
183
+ }
184
+
185
+ if (phrase.some((w) => !vectors.has(w)))
186
+ throw new Error("Words of the analogy must all be in the model vocabulary.");
187
+
188
+ // vec = pair[1] - pair[0] + word
189
+ const word_vec = vectors.get(word)!.values;
190
+ const pair0_vec = vectors.get(pair[0])!.values;
191
+ const pair1_vec = vectors.get(pair[1])!.values;
192
+ const vec = new Float32Array(size);
193
+ for (let a = 0; a < size; a++) {
194
+ vec[a] = pair1_vec[a] - pair0_vec[a] + word_vec[a];
195
+ }
196
+
197
+ // Normalize the vector...
198
+ const normalized = normalize(vec);
199
+
200
+ const best_words = new Array<string>(n).fill("");
201
+ const best_dists = new Array<number>(n).fill(0);
202
+ const phrase_set = new Set(phrase);
203
+ for (const v of vocab) {
204
+ // Skip words that are part of the phrase
205
+ if (phrase_set.has(word_of(v))) continue;
206
+ insert_top_n(best_words, best_dists, word_of(v), dot(normalized, v.values));
207
+ }
208
+
209
+ return top_n_to_results(best_words, best_dists);
210
+ },
211
+ };
212
+ }
213
+
214
+ function to_values(vec: WordVector | Float32Array): Float32Array {
215
+ return vec instanceof WordVector ? vec.values : vec;
216
+ }
217
+
218
+ /** The word of a vocabulary vector (vocabulary vectors always carry a word). */
219
+ function word_of(v: WordVector): string {
220
+ return v.word ?? "";
221
+ }
222
+
223
+ /** Return a unit-length copy of the given vector. */
224
+ export function normalize(values: Float32Array): Float32Array {
225
+ let len = 0;
226
+ for (let a = 0; a < values.length; a++) {
227
+ len += values[a] * values[a];
228
+ }
229
+ len = Math.sqrt(len);
230
+ const out = new Float32Array(values.length);
231
+ for (let a = 0; a < values.length; a++) {
232
+ out[a] = values[a] / len;
233
+ }
234
+ return out;
235
+ }
236
+
237
+ function dot(a: Float32Array, b: Float32Array): number {
238
+ let sum = 0;
239
+ for (let i = 0; i < a.length; i++) sum += a[i] * b[i];
240
+ return sum;
241
+ }
242
+
243
+ /** Insert a candidate into the top-n lists, keeping them sorted by descending distance. */
244
+ function insert_top_n(best_words: string[], best_dists: number[], word: string, dist: number): void {
245
+ for (let a = 0; a < best_words.length; a++) {
246
+ if (dist > best_dists[a]) {
247
+ for (let d = best_words.length - 1; d > a; d--) {
248
+ best_dists[d] = best_dists[d - 1];
249
+ best_words[d] = best_words[d - 1];
250
+ }
251
+ best_dists[a] = dist;
252
+ best_words[a] = word;
253
+ return;
254
+ }
255
+ }
256
+ }
257
+
258
+ function top_n_to_results(best_words: string[], best_dists: number[]): WordDist[] {
259
+ return best_words.map((word, i) => ({ word, dist: best_dists[i] }));
260
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./common";
2
+ export * from "./models/matrix";
3
+ export * from "./models/word2vec";
4
+ export * from "./models/glove";
5
+ export * from "./models/fasttext";