@mailwoman/mtf 10.7.0 → 10.8.0

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 (92) hide show
  1. package/README.md +35 -5
  2. package/crates/mtf-channels/tests/fixtures/README.md +13 -0
  3. package/crates/mtf-sampler/tests/fixtures/README.md +120 -0
  4. package/lib/code-units.ts +45 -0
  5. package/out/code-units.d.ts +24 -0
  6. package/out/code-units.d.ts.map +1 -0
  7. package/out/code-units.js +36 -0
  8. package/out/code-units.js.map +1 -0
  9. package/out/tools/build-wasm.run.js +2 -2
  10. package/out/tools/build-wasm.run.js.map +1 -1
  11. package/out/tools/sampler/native.d.ts +314 -0
  12. package/out/tools/sampler/native.d.ts.map +1 -0
  13. package/out/tools/sampler/native.js +114 -0
  14. package/out/tools/sampler/native.js.map +1 -0
  15. package/out/tools/tokenizer/binary.d.ts +38 -0
  16. package/out/tools/tokenizer/binary.d.ts.map +1 -0
  17. package/out/tools/tokenizer/binary.js +94 -0
  18. package/out/tools/tokenizer/binary.js.map +1 -0
  19. package/out/tools/tokenizer/byte-fallback.d.ts +39 -0
  20. package/out/tools/tokenizer/byte-fallback.d.ts.map +1 -0
  21. package/out/tools/tokenizer/byte-fallback.js +49 -0
  22. package/out/tools/tokenizer/byte-fallback.js.map +1 -0
  23. package/out/tools/tokenizer/model.d.ts +70 -0
  24. package/out/tools/tokenizer/model.d.ts.map +1 -0
  25. package/out/tools/tokenizer/model.js +56 -0
  26. package/out/tools/tokenizer/model.js.map +1 -0
  27. package/out/tools/tokenizer/prune.d.ts +69 -0
  28. package/out/tools/tokenizer/prune.d.ts.map +1 -0
  29. package/out/tools/tokenizer/prune.js +126 -0
  30. package/out/tools/tokenizer/prune.js.map +1 -0
  31. package/out/tools/tokenizer/prune.run.d.ts +16 -0
  32. package/out/tools/tokenizer/prune.run.d.ts.map +1 -0
  33. package/out/tools/tokenizer/prune.run.js +34 -0
  34. package/out/tools/tokenizer/prune.run.js.map +1 -0
  35. package/out/tools/tokenizer/sentencepiece.d.ts +63 -0
  36. package/out/tools/tokenizer/sentencepiece.d.ts.map +1 -0
  37. package/out/tools/tokenizer/sentencepiece.js +90 -0
  38. package/out/tools/tokenizer/sentencepiece.js.map +1 -0
  39. package/out/tools/tokenizer/splice.d.ts +117 -0
  40. package/out/tools/tokenizer/splice.d.ts.map +1 -0
  41. package/out/tools/tokenizer/splice.js +398 -0
  42. package/out/tools/tokenizer/splice.js.map +1 -0
  43. package/out/tools/tokenizer/splice.run.d.ts +29 -0
  44. package/out/tools/tokenizer/splice.run.d.ts.map +1 -0
  45. package/out/tools/tokenizer/splice.run.js +114 -0
  46. package/out/tools/tokenizer/splice.run.js.map +1 -0
  47. package/out/tools/tokenizer/symbols.d.ts +42 -0
  48. package/out/tools/tokenizer/symbols.d.ts.map +1 -0
  49. package/out/tools/tokenizer/symbols.js +113 -0
  50. package/out/tools/tokenizer/symbols.js.map +1 -0
  51. package/out/tools/tokenizer/train/text.run.d.ts +16 -0
  52. package/out/tools/tokenizer/train/text.run.d.ts.map +1 -0
  53. package/out/tools/tokenizer/train/text.run.js +67 -0
  54. package/out/tools/tokenizer/train/text.run.js.map +1 -0
  55. package/out/tools/tokenizer/train.d.ts +113 -0
  56. package/out/tools/tokenizer/train.d.ts.map +1 -0
  57. package/out/tools/tokenizer/train.js +162 -0
  58. package/out/tools/tokenizer/train.js.map +1 -0
  59. package/out/tools/tokenizer/train.run.d.ts +24 -0
  60. package/out/tools/tokenizer/train.run.d.ts.map +1 -0
  61. package/out/tools/tokenizer/train.run.js +131 -0
  62. package/out/tools/tokenizer/train.run.js.map +1 -0
  63. package/out/tools/tokenizer/utilization.run.d.ts +17 -0
  64. package/out/tools/tokenizer/utilization.run.d.ts.map +1 -0
  65. package/out/tools/tokenizer/utilization.run.js +80 -0
  66. package/out/tools/tokenizer/utilization.run.js.map +1 -0
  67. package/out/tools/tokenizer/verify.d.ts +94 -0
  68. package/out/tools/tokenizer/verify.d.ts.map +1 -0
  69. package/out/tools/tokenizer/verify.js +193 -0
  70. package/out/tools/tokenizer/verify.js.map +1 -0
  71. package/out/tools/tokenizer/verify.run.d.ts +22 -0
  72. package/out/tools/tokenizer/verify.run.d.ts.map +1 -0
  73. package/out/tools/tokenizer/verify.run.js +71 -0
  74. package/out/tools/tokenizer/verify.run.js.map +1 -0
  75. package/package.json +15 -3
  76. package/tools/build-wasm.run.ts +2 -2
  77. package/tools/sampler/native.ts +433 -0
  78. package/tools/tokenizer/binary.ts +118 -0
  79. package/tools/tokenizer/byte-fallback.ts +80 -0
  80. package/tools/tokenizer/model.ts +110 -0
  81. package/tools/tokenizer/prune.run.ts +37 -0
  82. package/tools/tokenizer/prune.ts +195 -0
  83. package/tools/tokenizer/sentencepiece.ts +142 -0
  84. package/tools/tokenizer/splice.run.ts +141 -0
  85. package/tools/tokenizer/splice.ts +592 -0
  86. package/tools/tokenizer/symbols.ts +119 -0
  87. package/tools/tokenizer/train/text.run.ts +80 -0
  88. package/tools/tokenizer/train.run.ts +151 -0
  89. package/tools/tokenizer/train.ts +266 -0
  90. package/tools/tokenizer/utilization.run.ts +96 -0
  91. package/tools/tokenizer/verify.run.ts +77 -0
  92. package/tools/tokenizer/verify.ts +313 -0
@@ -0,0 +1,398 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Splice the diacritic pieces of a locale tokenizer into a frozen unigram vocabulary, and grow an exported model's
7
+ * embedding table to match.
8
+ *
9
+ * An appended piece contains a code point outside ASCII, so it cannot match any span of an ASCII string, and ASCII
10
+ * text tokenizes exactly as before. `verifySourceIdentical` checks that on a probe rather than assuming it. A
11
+ * trained locale that shares a code point with the new pieces can re-tokenize. `checkCodepointOverlap`
12
+ * reports and refuses unless the locale is accepted. The method does not scale to CJK.
13
+ */
14
+ import { readFileRange, readLocalBuffer, readLocalJSONFile, readLocalTextFile } from "@mailwoman/core/fs/readers";
15
+ import { isDirectory, isFile } from "@mailwoman/core/fs/readers/stat";
16
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary";
17
+ import { makeDirectories, writeLocalBuffer, writeLocalJSONFile, writeLocalTextFile } from "@mailwoman/core/fs/writers";
18
+ import { prettyJSON, stringifyJSON } from "@mailwoman/core/json";
19
+ import { codePointLength } from "@mailwoman/core/strings/code-points";
20
+ import { splitLines } from "@mailwoman/core/strings/unicode";
21
+ import { CSVSpliterator } from "spliterator";
22
+ import { Globerator } from "spliterator/node/fs";
23
+ import { runMTFTokenizer } from "./binary.js";
24
+ import { editModel, loadEncoder, PieceType, readModelPieces } from "./model.js";
25
+ import { trainSentencePiece } from "./sentencepiece.js";
26
+ /**
27
+ * The corpus sample size and the seed of its shuffle.
28
+ */
29
+ const CORPUS_SAMPLE = 350_000;
30
+ const CORPUS_SEED = 42;
31
+ /**
32
+ * ASCII address lines, the default probe of the English-identity check.
33
+ */
34
+ export const ENGLISH_PROBE = [
35
+ "109 Seminary Dr, Mill Valley, CA 94941",
36
+ "5210 South Ingleside Avenue, Chicago, IL 60615",
37
+ "1600 Pennsylvania Ave NW, Washington, DC 20500",
38
+ "350 Fifth Avenue, New York, NY 10118",
39
+ "1 Infinite Loop, Cupertino, CA 95014",
40
+ ];
41
+ /**
42
+ * The piece text without SentencePiece's word-boundary marker.
43
+ */
44
+ function core(piece) {
45
+ return piece.replaceAll("▁", "");
46
+ }
47
+ /**
48
+ * The first code point outside ASCII.
49
+ */
50
+ const NON_ASCII = 0x80;
51
+ /**
52
+ * Corpus lines this long or longer, in code points, are left out: they are run-on records rather than names.
53
+ */
54
+ const MAX_LINE_CODE_POINTS = 80;
55
+ /**
56
+ * The int8 check accepts at most one mismatched value for each configured group
57
+ * of values in the reconstructed row.
58
+ */
59
+ const QUANTIZE_MISMATCH_DIVISOR = 20;
60
+ function isNonASCII(c) {
61
+ return c.codePointAt(0) >= NON_ASCII;
62
+ }
63
+ function isASCII(text) {
64
+ return ![...text].some(isNonASCII);
65
+ }
66
+ /**
67
+ * The distinct `STREET`, `CITY` and `STREET CITY` lines of each locale's OpenAddresses CSVs,
68
+ * under 80 code points, shuffled and capped at 350,000, then the extra lines.
69
+ * Returns the number of lines written.
70
+ *
71
+ * The files of a locale are read in name order and the lines kept in first-seen order,
72
+ * so the corpus is the same on every run.
73
+ */
74
+ export async function buildSlavicCorpus(options) {
75
+ const perFileCap = options.perFileCap ?? 400_000;
76
+ const lines = new Set();
77
+ for (const locale of options.locales) {
78
+ const directory = `${options.oaRoot}/${locale}`;
79
+ if (!(await isDirectory(directory)))
80
+ continue;
81
+ const names = await Globerator.from("*.csv", { cwd: directory, absolute: false }).toSorted();
82
+ for (const name of names) {
83
+ try {
84
+ const rows = CSVSpliterator.fromAsync(`${directory}/${name}`, {
85
+ normalizeKeys: false,
86
+ take: perFileCap + 2,
87
+ });
88
+ for await (const row of rows) {
89
+ const street = row["STREET"] || "";
90
+ const city = row["CITY"] || "";
91
+ if (street) {
92
+ lines.add(street);
93
+ }
94
+ if (city) {
95
+ lines.add(city);
96
+ }
97
+ if (street && city) {
98
+ lines.add(`${street} ${city}`);
99
+ }
100
+ }
101
+ }
102
+ catch (error) {
103
+ console.warn(`skipped the rest of ${directory}/${name}: ${error.message}`);
104
+ }
105
+ }
106
+ }
107
+ await using scratch = await temporaryDirectory("mtf-slavic-");
108
+ const unshuffled = scratch.path("lines.json").toString();
109
+ const shuffled = scratch.path("shuffled.json").toString();
110
+ await writeLocalJSONFile([...lines].filter((line) => line && codePointLength(line) < MAX_LINE_CODE_POINTS), unshuffled);
111
+ await runMTFTokenizer(["shuffle", "--seed", String(CORPUS_SEED), "--input", unshuffled, "--out", shuffled]);
112
+ const corpus = (await readLocalJSONFile(shuffled)).slice(0, CORPUS_SAMPLE);
113
+ if (options.extraText && (await isFile(options.extraText))) {
114
+ const extra = splitLines(await readLocalTextFile(options.extraText))
115
+ .map((line) => line.trim())
116
+ .filter((line) => line && codePointLength(line) < MAX_LINE_CODE_POINTS);
117
+ for (let i = 0; i < Math.max(1, options.extraRepeat ?? 10); i++) {
118
+ corpus.push(...extra);
119
+ }
120
+ }
121
+ await writeLocalTextFile(corpus.join("\n"), options.outPath);
122
+ return corpus.length;
123
+ }
124
+ /**
125
+ * Train the locale unigram model the splice draws its pieces from, and return its `.model` path.
126
+ */
127
+ export async function trainDiacriticSentencePiece(corpusPath, outPrefix, options) {
128
+ await using scratch = await temporaryDirectory("mtf-diacritic-");
129
+ const trained = await trainSentencePiece({
130
+ input: corpusPath,
131
+ model_prefix: outPrefix,
132
+ vocab_size: options.vocabSize ?? 24_000,
133
+ model_type: "unigram",
134
+ character_coverage: 1,
135
+ normalization_rule_name: "identity",
136
+ num_threads: 8,
137
+ }, { spmTrain: options.spmTrain, workDirectory: scratch.path.toString() });
138
+ return trained.model;
139
+ }
140
+ /**
141
+ * Raise when `probe` tokenizes differently under the spliced vocabulary than under the base one.
142
+ */
143
+ export async function verifySourceIdentical(baseTokenizer, splicedTokenizer, probe = ENGLISH_PROBE) {
144
+ using base = await loadEncoder(baseTokenizer);
145
+ using spliced = await loadEncoder(splicedTokenizer);
146
+ const differing = probe.filter((text) => base.encode(text).pieces.join("\0") !== spliced.encode(text).pieces.join("\0"));
147
+ if (differing.length) {
148
+ throw new Error(`source tokenization changed on ${differing.length}/${probe.length} probe strings: a piece containing ASCII ` +
149
+ `was spliced in. First: ${stringifyJSON(differing[0])}`);
150
+ }
151
+ }
152
+ /**
153
+ * Append the pieces of `donor` whose core holds a code point outside ASCII and that `base`
154
+ * lacks, with their scores, as normal pieces, then check the English identity.
155
+ * Returns the appended pieces.
156
+ */
157
+ export async function spliceVocabulary(base, donor, out) {
158
+ const basePieces = new Set((await readModelPieces(base)).map(([piece]) => piece));
159
+ const appended = (await readModelPieces(donor))
160
+ .filter(([piece]) => {
161
+ const text = core(piece);
162
+ return text && !isASCII(text) && !basePieces.has(piece);
163
+ })
164
+ .map(([piece, score]) => [piece, score, PieceType.Normal]);
165
+ await makeDirectories(out.slice(0, out.lastIndexOf("/")) || ".");
166
+ await editModel(base, out, { append: appended });
167
+ await verifySourceIdentical(base, out);
168
+ return appended.map(([piece]) => piece);
169
+ }
170
+ function byCodePoint(a, b) {
171
+ return a.codePointAt(0) - b.codePointAt(0);
172
+ }
173
+ const REPLACEMENT_CHARACTER = "�";
174
+ /**
175
+ * The code points outside ASCII in the first `capBytes` of a locale sample,
176
+ * read as UTF-8 with undecodable bytes ignored.
177
+ * A character split by the byte cap is left out.
178
+ *
179
+ * The sample is read as raw text rather than parsed, because the check needs a locale's
180
+ * character inventory and not its records, and any sample format then works.
181
+ */
182
+ export async function collectSampleCodepoints(samplePath, capBytes = 4_000_000) {
183
+ const bytes = await readFileRange(samplePath, 0, capBytes);
184
+ // A streaming decode holds back an incomplete final sequence instead of replacing it.
185
+ const text = new TextDecoder("utf-8").decode(bytes, { stream: true });
186
+ const out = new Set();
187
+ for (const c of text) {
188
+ if (isNonASCII(c)) {
189
+ out.add(c);
190
+ }
191
+ }
192
+ // The decoder replaces an invalid byte with U+FFFD, where Python's `errors="ignore"` drops it.
193
+ if (!bytes.includes(Buffer.from(REPLACEMENT_CHARACTER))) {
194
+ out.delete(REPLACEMENT_CHARACTER);
195
+ }
196
+ return out;
197
+ }
198
+ /**
199
+ * Report the code points outside ASCII that the new pieces share with each trained locale's
200
+ * sample, write the report, and raise when an overlapping locale is not in `acceptedOverlap`.
201
+ *
202
+ * The evaluation for an accepted locale must meet a registered per-locale non-inferiority
203
+ * comparison for it before the first measurement.
204
+ */
205
+ export async function checkCodepointOverlap(newPieces, localeSamples, reportPath, acceptedOverlap = new Set()) {
206
+ const newCodepoints = new Set();
207
+ for (const piece of newPieces) {
208
+ for (const c of core(piece)) {
209
+ if (isNonASCII(c)) {
210
+ newCodepoints.add(c);
211
+ }
212
+ }
213
+ }
214
+ const report = {};
215
+ for (const locale of Object.keys(localeSamples).toSorted()) {
216
+ const sample = await collectSampleCodepoints(localeSamples[locale]);
217
+ report[locale] = [...newCodepoints].filter((c) => sample.has(c)).toSorted(byCodePoint);
218
+ }
219
+ const written = {
220
+ new_piece_codepoints: [...newCodepoints].toSorted(byCodePoint),
221
+ per_locale_overlap: report,
222
+ accepted_overlap: [...acceptedOverlap].toSorted(),
223
+ };
224
+ await writeLocalTextFile(prettyJSON(written, true, 2), reportPath);
225
+ const offending = Object.entries(report)
226
+ .filter(([locale, codepoints]) => codepoints.length > 0 && !acceptedOverlap.has(locale))
227
+ .map(([locale]) => locale);
228
+ if (offending.length) {
229
+ const detail = offending.map((locale) => `${locale}: ${report[locale].slice(0, 12).join("")}`).join("; ");
230
+ throw new Error(`splice check: code point overlap with trained locale(s) ${offending.join(", ")} (${detail}). Either the ` +
231
+ `overlap is a defect, or register a per-locale non-inferiority comparison for each and pass ` +
232
+ `--accept-overlap ${offending.join(",")}. Report: ${reportPath}`);
233
+ }
234
+ return report;
235
+ }
236
+ /**
237
+ * The ONNX element type codes this module reads.
238
+ */
239
+ const ONNX_FLOAT = 1;
240
+ const ONNX_UINT8 = 2;
241
+ /**
242
+ * Refuses a table initializer whose dims or byte length differ from `[rows, columns]` at `bytesPerValue`.
243
+ *
244
+ * @throws Naming the initializer, its dims and byte length, and the shape it was expected to have.
245
+ */
246
+ export function assertTableShape(label, tensor, [rows, columns], bytesPerValue) {
247
+ const expectedBytes = rows * columns * bytesPerValue;
248
+ if (tensor.dims.length !== 2 ||
249
+ tensor.dims[0] !== rows ||
250
+ tensor.dims[1] !== columns ||
251
+ tensor.bytes.length !== expectedBytes) {
252
+ throw new Error(`${label} has dims [${tensor.dims.join(", ")}] and ${tensor.bytes.length} bytes; ` +
253
+ `expected [${rows}, ${columns}] in ${expectedBytes} bytes`);
254
+ }
255
+ }
256
+ async function readInitializer(model, name, directory) {
257
+ const raw = `${directory}/${name.replaceAll("/", "_")}.bin`;
258
+ const meta = await runMTFTokenizer([
259
+ "onnx-read",
260
+ "--model",
261
+ model,
262
+ "--name",
263
+ name,
264
+ "--raw-out",
265
+ raw,
266
+ ]);
267
+ return { ...meta, bytes: await readLocalBuffer(raw) };
268
+ }
269
+ async function writeInitializer(model, out, name, tensor, directory) {
270
+ const raw = `${directory}/${name.replaceAll("/", "_")}.out.bin`;
271
+ await writeLocalBuffer(tensor.bytes, raw);
272
+ await makeDirectories(out.slice(0, out.lastIndexOf("/")) || ".");
273
+ await runMTFTokenizer([
274
+ "onnx-write",
275
+ "--model",
276
+ model,
277
+ "--name",
278
+ name,
279
+ "--dims",
280
+ tensor.dims.join(","),
281
+ "--data-type",
282
+ String(tensor.data_type),
283
+ "--raw",
284
+ raw,
285
+ "--out",
286
+ out,
287
+ ]);
288
+ }
289
+ /**
290
+ * The mean, in `float32`, of the rows of `table` at `rows`: each column summed row
291
+ * by row in `float32`, then divided by the row count.
292
+ * NumPy reduces `table[rows].mean(0)` the same way.
293
+ */
294
+ function meanRow(table, hidden, rows) {
295
+ const out = new Float32Array(hidden);
296
+ for (let j = 0; j < hidden; j++) {
297
+ let sum = table[rows[0] * hidden + j];
298
+ for (let r = 1; r < rows.length; r++) {
299
+ sum = Math.fround(sum + table[rows[r] * hidden + j]);
300
+ }
301
+ out[j] = Math.fround(sum / rows.length);
302
+ }
303
+ return out;
304
+ }
305
+ /**
306
+ * NumPy's `np.round` for one value: to the nearest integer, ties to even.
307
+ */
308
+ function roundHalfEven(value) {
309
+ const floor = Math.floor(value);
310
+ const fraction = value - floor;
311
+ if (fraction > 0.5)
312
+ return floor + 1;
313
+ if (fraction < 0.5)
314
+ return floor;
315
+ return floor % 2 === 0 ? floor : floor + 1;
316
+ }
317
+ function quantize(value, scale, zeroPoint) {
318
+ const scaled = Math.fround(value / scale);
319
+ return Math.min(255, Math.max(0, Math.fround(roundHalfEven(scaled) + zeroPoint)));
320
+ }
321
+ /**
322
+ * Grow an exported model's token embedding table to the spliced vocabulary.
323
+ *
324
+ * Each new row is the mean of the base tokenizer's pieces for the new piece's surface (FVT),
325
+ * or the mean of every row when the surface has no piece inside the old vocabulary.
326
+ * The embedding is the only vocabulary-sized tensor of the token classifier,
327
+ * so the rest of the graph is unchanged.
328
+ *
329
+ * For an int8 twin the new rows are quantized with the table's own scale and zero point,
330
+ * after checking that those parameters reproduce the table's last row.
331
+ */
332
+ export async function meanInitONNXEmbeddings(options) {
333
+ const name = options.embeddingName ?? "inner.token_embeddings.weight";
334
+ await using scratch = await temporaryDirectory("mtf-mean-init-");
335
+ const directory = scratch.path.toString();
336
+ const embedding = await readInitializer(options.fp32ONNX, name, directory);
337
+ if (embedding.data_type !== ONNX_FLOAT || embedding.dims.length !== 2) {
338
+ throw new Error(`${name} in ${options.fp32ONNX} is not a float32 matrix`);
339
+ }
340
+ const [oldVocab, hidden] = embedding.dims;
341
+ // A short `raw_data` would read as a table of zeros past its end, and every spliced row would average them in.
342
+ assertTableShape(`${name} in ${options.fp32ONNX}`, embedding, [oldVocab, hidden], Float32Array.BYTES_PER_ELEMENT);
343
+ // A copy, because a `Float32Array` view needs a 4-byte-aligned offset that a read buffer need not have.
344
+ const table = new Float32Array(new Uint8Array(embedding.bytes).buffer, 0, oldVocab * hidden);
345
+ const spliced = await readModelPieces(options.splicedTokenizer);
346
+ const newVocab = spliced.length;
347
+ if (newVocab < oldVocab) {
348
+ throw new Error(`spliced vocab ${newVocab} < embedding vocab ${oldVocab}: wrong tokenizer?`);
349
+ }
350
+ const globalMean = meanRow(table, hidden, Array.from({ length: oldVocab }, (_, i) => i));
351
+ const newRows = new Float32Array((newVocab - oldVocab) * hidden);
352
+ {
353
+ using base = await loadEncoder(options.baseTokenizer);
354
+ for (let id = oldVocab; id < newVocab; id++) {
355
+ const surface = spliced[id][0].replaceAll("▁", " ");
356
+ const constituents = base.encode(surface).ids.filter((i) => i < oldVocab);
357
+ newRows.set(constituents.length ? meanRow(table, hidden, constituents) : globalMean, (id - oldVocab) * hidden);
358
+ }
359
+ }
360
+ const grown = new Float32Array(newVocab * hidden);
361
+ grown.set(table);
362
+ grown.set(newRows, oldVocab * hidden);
363
+ await writeInitializer(options.fp32ONNX, options.outFp32, name, { dims: [newVocab, hidden], data_type: ONNX_FLOAT, bytes: new Uint8Array(grown.buffer) }, directory);
364
+ if (options.int8ONNX && options.outInt8) {
365
+ const quantized = await readInitializer(options.int8ONNX, `${name}_quantized`, directory);
366
+ const scaleTensor = await readInitializer(options.int8ONNX, `${name}_scale`, directory);
367
+ const zeroTensor = await readInitializer(options.int8ONNX, `${name}_zero_point`, directory);
368
+ if (quantized.data_type !== ONNX_UINT8)
369
+ throw new Error(`${name}_quantized is not a uint8 table`);
370
+ // The int8 table must describe the same vocabulary and width as the fp32 one, or the grown table mixes rows.
371
+ assertTableShape(`${name}_quantized in ${options.int8ONNX}`, quantized, [oldVocab, hidden], 1);
372
+ if (scaleTensor.bytes.length < Float32Array.BYTES_PER_ELEMENT || !zeroTensor.bytes.length) {
373
+ throw new Error(`${name}_scale or ${name}_zero_point in ${options.int8ONNX} holds no value`);
374
+ }
375
+ const scale = scaleTensor.bytes.readFloatLE(0);
376
+ const zeroPoint = zeroTensor.bytes[0];
377
+ const lastRow = oldVocab - 1;
378
+ let mismatched = 0;
379
+ for (let j = 0; j < hidden; j++) {
380
+ if (quantize(table[lastRow * hidden + j], scale, zeroPoint) !== quantized.bytes[lastRow * hidden + j]) {
381
+ mismatched++;
382
+ }
383
+ }
384
+ // Up to one value in twenty may sit on the other side of a rounding boundary.
385
+ // More means the wrong scale or zero point.
386
+ if (mismatched > Math.floor(hidden / QUANTIZE_MISMATCH_DIVISOR)) {
387
+ throw new Error(`int8 inverse mismatch on row ${lastRow}: ${mismatched}/${hidden}; scale or zero point wrong?`);
388
+ }
389
+ const grownQuantized = new Uint8Array(newVocab * hidden);
390
+ grownQuantized.set(quantized.bytes.subarray(0, oldVocab * hidden));
391
+ for (let i = 0; i < newRows.length; i++) {
392
+ grownQuantized[oldVocab * hidden + i] = quantize(newRows[i], scale, zeroPoint);
393
+ }
394
+ await writeInitializer(options.int8ONNX, options.outInt8, `${name}_quantized`, { dims: [newVocab, hidden], data_type: quantized.data_type, bytes: grownQuantized }, directory);
395
+ }
396
+ return [oldVocab, newVocab];
397
+ }
398
+ //# sourceMappingURL=splice.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"splice.js","sourceRoot":"","sources":["../../../tools/tokenizer/splice.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AACjH,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,iCAAiC,CAAA;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAA;AACjE,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAA;AACtH,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAA;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAEhD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,eAAe,EAAwB,MAAM,YAAY,CAAA;AACrG,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAEvD;;GAEG;AACH,MAAM,aAAa,GAAG,OAAO,CAAA;AAC7B,MAAM,WAAW,GAAG,EAAE,CAAA;AAEtB;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB;IAC/C,wCAAwC;IACxC,gDAAgD;IAChD,gDAAgD;IAChD,sCAAsC;IACtC,sCAAsC;CACtC,CAAA;AAED;;GAEG;AACH,SAAS,IAAI,CAAC,KAAa;IAC1B,OAAO,KAAK,CA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B,CAAC,EAAE,CAAC;YACjE,MAAM,IAAI,KAAK,CAAC,gCAAgC,OAAO,KAAK,UAAU,IAAI,MAAM,8BAA8B,CAAC,CAAA;QAChH,CAAC;QAED,MAAM,cAAc,GAAG,IAAI,UAAU,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAA;QAExD,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAA;QAElE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACzC,cAAc,CAAC,QAAQ,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAE,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QAChF,CAAC;QAED,MAAM,gBAAgB,CACrB,OAAO,CAAC,QAAQ,EAChB,OAAO,CAAC,OAAO,EACf,GAAG,IAAI,YAAY,EACnB,EAAE,IAAI,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,KAAK,EAAE,cAAc,EAAE,EACnF,SAAS,CACT,CAAA;IACF,CAAC;IAED,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAA;AAC5B,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Splice locale diacritic pieces into a frozen tokenizer, or grow an exported model onto a spliced tokenizer.
7
+ *
8
+ * `build-tokenizer` reads the locales' OpenAddresses street and city names, trains a locale unigram model on them,
9
+ * appends that model's pieces that hold a code point outside ASCII to the base tokenizer, and checks that English
10
+ * tokenizes as before. With `--trained-samples`, it also writes the code point overlap report beside the spliced
11
+ * tokenizer and fails on an overlap no `--accept-overlap` entry accepts.
12
+ *
13
+ * `onnx-mean-init` grows an exported model's token embedding table, and its int8 twin's, to the spliced vocabulary.
14
+ *
15
+ * Usage:
16
+ *
17
+ * node packages/mtf/tools/tokenizer/splice.run.ts build-tokenizer --oa-root <dir> --base-tokenizer <model>
18
+ * --out-tokenizer <model> [--locales cz,pl,sk,si] [--vocab-size 24000] [--per-file-cap 400000]
19
+ * [--work-dir out/bsplice-work] [--trained-samples fr=<path>,de=<path>] [--accept-overlap fr]
20
+ * [--extra-text <txt>] [--extra-repeat 10] [--spm-train <path>]
21
+ * node packages/mtf/tools/tokenizer/splice.run.ts onnx-mean-init --fp32-onnx <onnx> --base-tokenizer <model>
22
+ * --spliced-tokenizer <model> --out-fp32 <onnx> [--int8-onnx <onnx> --out-int8 <onnx>]
23
+ *
24
+ * A per-file cap that reads a whole small regional file can read only the first departments of a country published
25
+ * as one national file, such as France's. Raise it, or pass a sampled national extract, to keep the corpus spread
26
+ * across the country.
27
+ */
28
+ export {};
29
+ //# sourceMappingURL=splice.run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"splice.run.d.ts","sourceRoot":"","sources":["../../../tools/tokenizer/splice.run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"}
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Splice locale diacritic pieces into a frozen tokenizer, or grow an exported model onto a spliced tokenizer.
7
+ *
8
+ * `build-tokenizer` reads the locales' OpenAddresses street and city names, trains a locale unigram model on them,
9
+ * appends that model's pieces that hold a code point outside ASCII to the base tokenizer, and checks that English
10
+ * tokenizes as before. With `--trained-samples`, it also writes the code point overlap report beside the spliced
11
+ * tokenizer and fails on an overlap no `--accept-overlap` entry accepts.
12
+ *
13
+ * `onnx-mean-init` grows an exported model's token embedding table, and its int8 twin's, to the spliced vocabulary.
14
+ *
15
+ * Usage:
16
+ *
17
+ * node packages/mtf/tools/tokenizer/splice.run.ts build-tokenizer --oa-root <dir> --base-tokenizer <model>
18
+ * --out-tokenizer <model> [--locales cz,pl,sk,si] [--vocab-size 24000] [--per-file-cap 400000]
19
+ * [--work-dir out/bsplice-work] [--trained-samples fr=<path>,de=<path>] [--accept-overlap fr]
20
+ * [--extra-text <txt>] [--extra-repeat 10] [--spm-train <path>]
21
+ * node packages/mtf/tools/tokenizer/splice.run.ts onnx-mean-init --fp32-onnx <onnx> --base-tokenizer <model>
22
+ * --spliced-tokenizer <model> --out-fp32 <onnx> [--int8-onnx <onnx> --out-int8 <onnx>]
23
+ *
24
+ * A per-file cap that reads a whole small regional file can read only the first departments of a country published
25
+ * as one national file, such as France's. Raise it, or pass a sampled national extract, to keep the corpus spread
26
+ * across the country.
27
+ */
28
+ import { makeDirectories } from "@mailwoman/core/fs/writers";
29
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments";
30
+ import { resolvePath } from "path-ts";
31
+ import { spmTrainBinary } from "./binary.js";
32
+ import { buildSlavicCorpus, checkCodepointOverlap, meanInitONNXEmbeddings, spliceVocabulary, trainDiacriticSentencePiece, } from "./splice.js";
33
+ const { values, positionals } = parseArguments({
34
+ allowPositionals: true,
35
+ options: {
36
+ "oa-root": { type: "string" },
37
+ locales: { type: "string", default: "cz,pl,sk,si" },
38
+ "base-tokenizer": { type: "string" },
39
+ "out-tokenizer": { type: "string" },
40
+ "vocab-size": { type: "string", default: "24000" },
41
+ "per-file-cap": { type: "string", default: "400000" },
42
+ "work-dir": { type: "string", default: "out/bsplice-work" },
43
+ "trained-samples": { type: "string", default: "" },
44
+ "extra-text": { type: "string" },
45
+ "extra-repeat": { type: "string", default: "10" },
46
+ "accept-overlap": { type: "string", default: "" },
47
+ "spm-train": { type: "string" },
48
+ "fp32-onnx": { type: "string" },
49
+ "spliced-tokenizer": { type: "string" },
50
+ "out-fp32": { type: "string" },
51
+ "int8-onnx": { type: "string" },
52
+ "out-int8": { type: "string" },
53
+ },
54
+ });
55
+ function list(value) {
56
+ return value
57
+ .split(",")
58
+ .map((entry) => entry.trim())
59
+ .filter((entry) => entry.length > 0);
60
+ }
61
+ const command = positionals[0];
62
+ if (command === "build-tokenizer") {
63
+ const workDirectory = resolvePath(values["work-dir"]);
64
+ const baseTokenizer = resolvePath(requiredArgument(command, "base-tokenizer", values["base-tokenizer"]));
65
+ const outTokenizer = resolvePath(requiredArgument(command, "out-tokenizer", values["out-tokenizer"]));
66
+ const corpus = `${workDirectory}/slavic-corpus.txt`;
67
+ await makeDirectories(workDirectory);
68
+ const lines = await buildSlavicCorpus({
69
+ oaRoot: resolvePath(requiredArgument(command, "oa-root", values["oa-root"])),
70
+ locales: values.locales.split(","),
71
+ outPath: corpus,
72
+ perFileCap: Number(values["per-file-cap"]),
73
+ extraText: values["extra-text"] ?? null,
74
+ extraRepeat: Number(values["extra-repeat"]),
75
+ });
76
+ console.log(`corpus: ${lines} lines`);
77
+ const donor = await trainDiacriticSentencePiece(corpus, `${workDirectory}/slavic-sp`, {
78
+ spmTrain: await spmTrainBinary(values["spm-train"]),
79
+ vocabSize: Number(values["vocab-size"]),
80
+ });
81
+ const pieces = await spliceVocabulary(baseTokenizer, donor, outTokenizer);
82
+ console.log(`spliced ${pieces.length} diacritic pieces -> ${outTokenizer}`);
83
+ console.log("English tokenization verified identical (0 differences).");
84
+ if (values["trained-samples"]) {
85
+ const samples = Object.fromEntries(list(values["trained-samples"]).map((pair) => {
86
+ const at = pair.indexOf("=");
87
+ return [pair.slice(0, at).trim(), pair.slice(at + 1).trim()];
88
+ }));
89
+ const reportPath = outTokenizer.replace(/\.[^./]*$/, "") + ".overlap-report.json";
90
+ const report = await checkCodepointOverlap(pieces, samples, reportPath, new Set(list(values["accept-overlap"])));
91
+ const overlapping = Object.entries(report).flatMap(([locale, codepoints]) => (codepoints.length ? [locale] : []));
92
+ console.log(`overlap check passed; report ${reportPath}; overlapping (accepted): ${overlapping.join(", ") || "none"}`);
93
+ }
94
+ }
95
+ else if (command === "onnx-mean-init") {
96
+ const outFp32 = resolvePath(requiredArgument(command, "out-fp32", values["out-fp32"]));
97
+ const [oldVocab, newVocab] = await meanInitONNXEmbeddings({
98
+ fp32ONNX: resolvePath(requiredArgument(command, "fp32-onnx", values["fp32-onnx"])),
99
+ baseTokenizer: resolvePath(requiredArgument(command, "base-tokenizer", values["base-tokenizer"])),
100
+ splicedTokenizer: resolvePath(requiredArgument(command, "spliced-tokenizer", values["spliced-tokenizer"])),
101
+ outFp32,
102
+ int8ONNX: values["int8-onnx"] ?? null,
103
+ outInt8: values["out-int8"] ?? null,
104
+ });
105
+ console.log(`expanded ONNX token_embeddings ${oldVocab} -> ${newVocab}; wrote ${outFp32}`);
106
+ if (values["out-int8"]) {
107
+ console.log(` int8 twin written ${values["out-int8"]}`);
108
+ }
109
+ }
110
+ else {
111
+ console.error("usage: splice.run.ts build-tokenizer|onnx-mean-init [options]");
112
+ process.exitCode = 2;
113
+ }
114
+ //# sourceMappingURL=splice.run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"splice.run.js","sourceRoot":"","sources":["../../../tools/tokenizer/splice.run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;AAC5D,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAA;AACtF,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,OAAO,EACN,iBAAiB,EACjB,qBAAqB,EACrB,sBAAsB,EACtB,gBAAgB,EAChB,2BAA2B,GAC3B,MAAM,aAAa,CAAA;AAEpB,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,cAAc,CAAC;IAC9C,gBAAgB,EAAE,IAAI;IACtB,OAAO,EAAE;QACR,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EA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
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The strings a trained tokenizer keeps whole, and how they reach SentencePiece.
7
+ *
8
+ * A user-defined symbol bypasses unigram inference and is always emitted as one piece. The literal a caller writes
9
+ * is not the literal SentencePiece matches: it turns whitespace into `▁` before matching, so `PO Box` is passed as
10
+ * `PO▁Box`. The symbols also compete with the vocabulary budget, so a list longer than a quarter of the vocabulary
11
+ * is truncated.
12
+ */
13
+ /**
14
+ * The default symbols: US state and territory codes, country abbreviations
15
+ * and names, and postal-form anchors.
16
+ *
17
+ * A state code beside a postcode (`NY 10001`) stays one piece, so the region and postcode stay adjacent.
18
+ * Postal markers (`PO Box`, `Cedex`, `BP`) are fixed surface forms that are
19
+ * cheaper to add once than to learn.
20
+ *
21
+ * A hyphen is not listed because it already tokenizes as one piece.
22
+ * Whole Japanese postcodes come from mined postcode literals.
23
+ *
24
+ * The list keeps its duplicates (`CA`, `DE`), which the trainer removes.
25
+ */
26
+ export declare const DEFAULT_USER_DEFINED_SYMBOLS: readonly string[];
27
+ /**
28
+ * One literal per line.
29
+ *
30
+ * A blank line or a `#` comment is skipped, and only line ends are trimmed,
31
+ * because a symbol may hold a space (`PO Box`).
32
+ */
33
+ export declare function readUserDefinedSymbolsFile(path: string): Promise<string[]>;
34
+ /**
35
+ * A symbol with each ASCII space replaced by SentencePiece's whitespace placeholder, `▁`.
36
+ */
37
+ export declare function sentencePieceSymbol(symbol: string): string;
38
+ /**
39
+ * The non-empty entries, first occurrences only, in order.
40
+ */
41
+ export declare function dedupeKeepOrder(items: Iterable<string>): string[];
42
+ //# sourceMappingURL=symbols.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"symbols.d.ts","sourceRoot":"","sources":["../../../tools/tokenizer/symbols.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAKH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EA+DzD,CAAA;AAED;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAIhF;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE,CAEjE"}