@mailwoman/mtf 10.7.0 → 11.0.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 (97) hide show
  1. package/README.md +37 -7
  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/lib/index.ts +6 -2
  6. package/out/code-units.d.ts +24 -0
  7. package/out/code-units.d.ts.map +1 -0
  8. package/out/code-units.js +36 -0
  9. package/out/code-units.js.map +1 -0
  10. package/out/index.d.ts +4 -2
  11. package/out/index.d.ts.map +1 -1
  12. package/out/index.js +6 -2
  13. package/out/index.js.map +1 -1
  14. package/out/tools/build-wasm.run.js +2 -2
  15. package/out/tools/build-wasm.run.js.map +1 -1
  16. package/out/tools/sampler/native.d.ts +314 -0
  17. package/out/tools/sampler/native.d.ts.map +1 -0
  18. package/out/tools/sampler/native.js +114 -0
  19. package/out/tools/sampler/native.js.map +1 -0
  20. package/out/tools/tokenizer/binary.d.ts +38 -0
  21. package/out/tools/tokenizer/binary.d.ts.map +1 -0
  22. package/out/tools/tokenizer/binary.js +94 -0
  23. package/out/tools/tokenizer/binary.js.map +1 -0
  24. package/out/tools/tokenizer/byte-fallback.d.ts +39 -0
  25. package/out/tools/tokenizer/byte-fallback.d.ts.map +1 -0
  26. package/out/tools/tokenizer/byte-fallback.js +49 -0
  27. package/out/tools/tokenizer/byte-fallback.js.map +1 -0
  28. package/out/tools/tokenizer/model.d.ts +70 -0
  29. package/out/tools/tokenizer/model.d.ts.map +1 -0
  30. package/out/tools/tokenizer/model.js +56 -0
  31. package/out/tools/tokenizer/model.js.map +1 -0
  32. package/out/tools/tokenizer/prune.d.ts +69 -0
  33. package/out/tools/tokenizer/prune.d.ts.map +1 -0
  34. package/out/tools/tokenizer/prune.js +126 -0
  35. package/out/tools/tokenizer/prune.js.map +1 -0
  36. package/out/tools/tokenizer/prune.run.d.ts +16 -0
  37. package/out/tools/tokenizer/prune.run.d.ts.map +1 -0
  38. package/out/tools/tokenizer/prune.run.js +34 -0
  39. package/out/tools/tokenizer/prune.run.js.map +1 -0
  40. package/out/tools/tokenizer/sentencepiece.d.ts +63 -0
  41. package/out/tools/tokenizer/sentencepiece.d.ts.map +1 -0
  42. package/out/tools/tokenizer/sentencepiece.js +90 -0
  43. package/out/tools/tokenizer/sentencepiece.js.map +1 -0
  44. package/out/tools/tokenizer/splice.d.ts +117 -0
  45. package/out/tools/tokenizer/splice.d.ts.map +1 -0
  46. package/out/tools/tokenizer/splice.js +398 -0
  47. package/out/tools/tokenizer/splice.js.map +1 -0
  48. package/out/tools/tokenizer/splice.run.d.ts +29 -0
  49. package/out/tools/tokenizer/splice.run.d.ts.map +1 -0
  50. package/out/tools/tokenizer/splice.run.js +114 -0
  51. package/out/tools/tokenizer/splice.run.js.map +1 -0
  52. package/out/tools/tokenizer/symbols.d.ts +42 -0
  53. package/out/tools/tokenizer/symbols.d.ts.map +1 -0
  54. package/out/tools/tokenizer/symbols.js +113 -0
  55. package/out/tools/tokenizer/symbols.js.map +1 -0
  56. package/out/tools/tokenizer/train/text.run.d.ts +16 -0
  57. package/out/tools/tokenizer/train/text.run.d.ts.map +1 -0
  58. package/out/tools/tokenizer/train/text.run.js +67 -0
  59. package/out/tools/tokenizer/train/text.run.js.map +1 -0
  60. package/out/tools/tokenizer/train.d.ts +113 -0
  61. package/out/tools/tokenizer/train.d.ts.map +1 -0
  62. package/out/tools/tokenizer/train.js +162 -0
  63. package/out/tools/tokenizer/train.js.map +1 -0
  64. package/out/tools/tokenizer/train.run.d.ts +24 -0
  65. package/out/tools/tokenizer/train.run.d.ts.map +1 -0
  66. package/out/tools/tokenizer/train.run.js +131 -0
  67. package/out/tools/tokenizer/train.run.js.map +1 -0
  68. package/out/tools/tokenizer/utilization.run.d.ts +17 -0
  69. package/out/tools/tokenizer/utilization.run.d.ts.map +1 -0
  70. package/out/tools/tokenizer/utilization.run.js +80 -0
  71. package/out/tools/tokenizer/utilization.run.js.map +1 -0
  72. package/out/tools/tokenizer/verify.d.ts +94 -0
  73. package/out/tools/tokenizer/verify.d.ts.map +1 -0
  74. package/out/tools/tokenizer/verify.js +193 -0
  75. package/out/tools/tokenizer/verify.js.map +1 -0
  76. package/out/tools/tokenizer/verify.run.d.ts +22 -0
  77. package/out/tools/tokenizer/verify.run.d.ts.map +1 -0
  78. package/out/tools/tokenizer/verify.run.js +71 -0
  79. package/out/tools/tokenizer/verify.run.js.map +1 -0
  80. package/package.json +15 -3
  81. package/tools/build-wasm.run.ts +2 -2
  82. package/tools/sampler/native.ts +433 -0
  83. package/tools/tokenizer/binary.ts +118 -0
  84. package/tools/tokenizer/byte-fallback.ts +80 -0
  85. package/tools/tokenizer/model.ts +110 -0
  86. package/tools/tokenizer/prune.run.ts +37 -0
  87. package/tools/tokenizer/prune.ts +195 -0
  88. package/tools/tokenizer/sentencepiece.ts +142 -0
  89. package/tools/tokenizer/splice.run.ts +141 -0
  90. package/tools/tokenizer/splice.ts +592 -0
  91. package/tools/tokenizer/symbols.ts +119 -0
  92. package/tools/tokenizer/train/text.run.ts +80 -0
  93. package/tools/tokenizer/train.run.ts +151 -0
  94. package/tools/tokenizer/train.ts +266 -0
  95. package/tools/tokenizer/utilization.run.ts +96 -0
  96. package/tools/tokenizer/verify.run.ts +77 -0
  97. package/tools/tokenizer/verify.ts +313 -0
@@ -0,0 +1,110 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * A SentencePiece model's vocabulary, read and edited through `mtf-tokenizer`, and an encoder over it through the
7
+ * `@mailwoman/mtf` runtime.
8
+ */
9
+
10
+ import { readLocalBuffer, readLocalJSONFile } from "@mailwoman/core/fs/readers"
11
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
12
+ import { replaceFileAtomically, writeLocalJSONFile } from "@mailwoman/core/fs/writers"
13
+
14
+ import { type MTFModel, MTFRuntime, mtfWASMURL } from "#index"
15
+
16
+ import { runMTFTokenizer } from "./binary.ts"
17
+
18
+ /**
19
+ * `ModelProto.SentencePiece.Type`, by wire value.
20
+ */
21
+ export const PieceType = {
22
+ Normal: 1,
23
+ Unknown: 2,
24
+ Control: 3,
25
+ UserDefined: 4,
26
+ Unused: 5,
27
+ Byte: 6,
28
+ } as const
29
+
30
+ export type PieceType = (typeof PieceType)[keyof typeof PieceType]
31
+
32
+ /**
33
+ * One vocabulary entry.
34
+ * `score` is the stored `float32`, widened exactly.
35
+ */
36
+ export type VocabularyPiece = readonly [piece: string, score: number, type: PieceType]
37
+
38
+ /**
39
+ * Every piece of the model at `path`, in id order.
40
+ */
41
+ export async function readModelPieces(path: string): Promise<VocabularyPiece[]> {
42
+ await using scratch = await temporaryDirectory("mtf-inspect-")
43
+ const out = scratch.path("pieces.json").toString()
44
+
45
+ await runMTFTokenizer<object>(["inspect", path, "--out", out])
46
+ const { pieces } = await readLocalJSONFile<{ pieces: VocabularyPiece[] }>(out)
47
+
48
+ return pieces
49
+ }
50
+
51
+ /**
52
+ * The edits `mtf-tokenizer edit` applies, in this order.
53
+ */
54
+ export interface ModelEdit {
55
+ /**
56
+ * The piece ids to keep, in the order to keep them.
57
+ */
58
+ keep?: readonly number[]
59
+ /**
60
+ * Pieces to append after the kept ones.
61
+ */
62
+ append?: readonly VocabularyPiece[]
63
+ /**
64
+ * The flag names of the training call that wrote the model.
65
+ *
66
+ * The trainer and normalizer spec fields without a corresponding flag are dropped.
67
+ * This turns a native `spm_train` model into the bytes the Python wheel writes.
68
+ */
69
+ wheelFlags?: readonly string[]
70
+ }
71
+
72
+ /**
73
+ * What an edit dropped from each spec, by field number.
74
+ */
75
+ export interface ModelEditSummary {
76
+ pieces: number
77
+ dropped_fields: { trainer?: number[]; normalizer?: number[] }
78
+ }
79
+
80
+ /**
81
+ * Write `source` with `edit` applied to `destination`, which may be `source` itself.
82
+ */
83
+ export async function editModel(source: string, destination: string, edit: ModelEdit): Promise<ModelEditSummary> {
84
+ await using scratch = await temporaryDirectory("mtf-edit-")
85
+ const plan = scratch.path("plan.json").toString()
86
+ const staged = scratch.path("model").toString()
87
+
88
+ await writeLocalJSONFile(
89
+ { keep: edit.keep ?? null, append: edit.append ?? null, wheel_flags: edit.wheelFlags ?? null },
90
+ plan
91
+ )
92
+
93
+ const summary = await runMTFTokenizer<ModelEditSummary>(["edit", source, "--plan", plan, "--out", staged])
94
+
95
+ await replaceFileAtomically(staged, destination)
96
+
97
+ return summary
98
+ }
99
+
100
+ let runtime: Promise<MTFRuntime> | null = null
101
+
102
+ /**
103
+ * The model at `path`, loaded into the WebAssembly runtime.
104
+ * Dispose it after use.
105
+ */
106
+ export async function loadEncoder(path: string): Promise<MTFModel> {
107
+ runtime ??= readLocalBuffer(mtfWASMURL()).then((bytes) => MTFRuntime.instantiate(new Uint8Array(bytes)))
108
+
109
+ return (await runtime).loadModel(await readLocalBuffer(path))
110
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Prune a tokenizer's unused pieces and the int8 model's matching embedding rows.
7
+ *
8
+ * `--train-counts` is the per-piece count `utilization.run.ts` writes; `--eval-fired` is a JSON file whose
9
+ * `fired_ids` lists the pieces the evaluation surface uses. The tool writes `tokenizer.model`, `model.onnx`,
10
+ * `id-map.json` and `prune-report.json` under `--out-dir`. `verify.run.ts prune` then checks the result.
11
+ *
12
+ * Usage: `node packages/mtf/tools/tokenizer/prune.run.ts --tokenizer <model> --onnx <int8 onnx>
13
+ * --train-counts <json> --eval-fired <json> --out-dir <dir>`
14
+ */
15
+
16
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments"
17
+ import { resolvePath } from "path-ts"
18
+
19
+ import { prunePieces } from "./prune.ts"
20
+
21
+ const { values } = parseArguments({
22
+ options: {
23
+ tokenizer: { type: "string" },
24
+ onnx: { type: "string" },
25
+ "train-counts": { type: "string" },
26
+ "eval-fired": { type: "string" },
27
+ "out-dir": { type: "string" },
28
+ },
29
+ })
30
+
31
+ await prunePieces({
32
+ tokenizer: resolvePath(requiredArgument("prune", "tokenizer", values.tokenizer)),
33
+ onnx: resolvePath(requiredArgument("prune", "onnx", values.onnx)),
34
+ trainCounts: resolvePath(requiredArgument("prune", "train-counts", values["train-counts"])),
35
+ evalFired: resolvePath(requiredArgument("prune", "eval-fired", values["eval-fired"])),
36
+ outDirectory: resolvePath(requiredArgument("prune", "out-dir", values["out-dir"])),
37
+ })
@@ -0,0 +1,195 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Prune a tokenizer's unused pieces and the matching rows of an int8 model's embedding table.
7
+ *
8
+ * A piece that never won a Viterbi path contributes no score to any other path, so segmentation is unchanged for
9
+ * every input whose best path avoided the pruned pieces. The kept pieces stay in their order. The embedding rows
10
+ * are gathered by the old-to-new id map with the scale and zero point untouched, so each kept row stays the same
11
+ * bytes.
12
+ */
13
+
14
+ import { readLocalBuffer, readLocalJSONFile } from "@mailwoman/core/fs/readers"
15
+ import { readFileSize } 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 } from "@mailwoman/core/json"
19
+
20
+ import { runMTFTokenizer } from "./binary.ts"
21
+ import { editModel, PieceType, readModelPieces } from "./model.ts"
22
+
23
+ /**
24
+ * The quantized embedding table of the BIO token classifier.
25
+ */
26
+ export const QUANTIZED_EMBEDDING = "inner.token_embeddings.weight_quantized"
27
+
28
+ /**
29
+ * The id map `prunePieces` writes as `id-map.json`: the kept old ids in order,
30
+ * and each old id's new id or -1.
31
+ */
32
+ export interface PruneIDMap {
33
+ kept_ids: number[]
34
+ old_to_new: number[]
35
+ }
36
+
37
+ export interface PruneReport {
38
+ vocab_before: number
39
+ vocab_after: number
40
+ train_fired: number
41
+ eval_fired: number
42
+ single_codepoint_kept: number
43
+ tokenizer_bytes: { before: number; after: number }
44
+ onnx_bytes: { before: number; after: number }
45
+ }
46
+
47
+ export interface PruneOptions {
48
+ tokenizer: string
49
+ onnx: string
50
+ /**
51
+ * A JSON file whose `counts` is each piece's use count over the training corpus,
52
+ * as `utilization.run.ts` writes.
53
+ */
54
+ trainCounts: string
55
+ /**
56
+ * A JSON file whose `fired_ids` lists the pieces the evaluation surface uses.
57
+ */
58
+ evalFired: string
59
+ outDirectory: string
60
+ }
61
+
62
+ /**
63
+ * The pieces to keep: every piece the training corpus or the evaluation surface used, every
64
+ * piece that is not a normal piece (control, unknown, user-defined, unused and byte pieces),
65
+ * and every piece of at most one code point once a leading `▁` is removed.
66
+ * This keeps every character reachable.
67
+ */
68
+ export function keepSet(
69
+ vocabulary: readonly (readonly [string, number, number])[],
70
+ counts: readonly number[],
71
+ evalFired: readonly number[]
72
+ ): { keep: boolean[]; singleCodepoint: number } {
73
+ if (counts.length !== vocabulary.length) {
74
+ throw new Error(`the counts cover ${counts.length} pieces and the tokenizer has ${vocabulary.length}`)
75
+ }
76
+
77
+ const keep = counts.map((n) => n > 0)
78
+
79
+ for (const id of evalFired) {
80
+ if (id < 0 || id >= keep.length) throw new Error(`eval-fired id ${id} is outside the vocabulary`)
81
+ keep[id] = true
82
+ }
83
+
84
+ let singleCodepoint = 0
85
+
86
+ vocabulary.forEach(([piece, , type], id) => {
87
+ if (type !== PieceType.Normal) {
88
+ keep[id] = true
89
+
90
+ return
91
+ }
92
+
93
+ const literal = piece.startsWith("▁") ? piece.slice(1) : piece
94
+
95
+ if ([...literal].length <= 1) {
96
+ keep[id] = true
97
+
98
+ singleCodepoint++
99
+ }
100
+ })
101
+
102
+ return { keep, singleCodepoint }
103
+ }
104
+
105
+ /**
106
+ * Write the pruned `tokenizer.model`, `model.onnx`, `id-map.json`
107
+ * and `prune-report.json` under the output directory.
108
+ */
109
+ export async function prunePieces(options: PruneOptions): Promise<PruneReport> {
110
+ const vocabulary = await readModelPieces(options.tokenizer)
111
+ const { counts } = await readLocalJSONFile<{ counts: number[] }>(options.trainCounts)
112
+ const { fired_ids: evalFired } = await readLocalJSONFile<{ fired_ids: number[] }>(options.evalFired)
113
+ const { keep, singleCodepoint } = keepSet(vocabulary, counts, evalFired)
114
+ const keptIDs = keep.flatMap((kept, id) => (kept ? [id] : []))
115
+ const oldToNew = new Array<number>(vocabulary.length).fill(-1)
116
+
117
+ keptIDs.forEach((id, i) => {
118
+ oldToNew[id] = i
119
+ })
120
+
121
+ const trainFired = counts.filter((n) => n > 0).length
122
+ const evalCount = new Set(evalFired).size
123
+
124
+ console.info(
125
+ `[prune] vocab ${vocabulary.length} → keep ${keptIDs.length} (${((100 * keptIDs.length) / vocabulary.length).toFixed(1)}%)`
126
+ )
127
+ console.info(`[prune] train-fired ${trainFired}, eval-fired ${evalCount}, single-codepoint kept ${singleCodepoint}`)
128
+
129
+ await makeDirectories(options.outDirectory)
130
+ const tokenizerOut = `${options.outDirectory}/tokenizer.model`
131
+
132
+ await editModel(options.tokenizer, tokenizerOut, { keep: keptIDs })
133
+
134
+ await using scratch = await temporaryDirectory("mtf-prune-")
135
+ const table = scratch.path("table.bin").toString()
136
+ const gathered = scratch.path("gathered.bin").toString()
137
+ const onnxOut = `${options.outDirectory}/model.onnx`
138
+
139
+ const meta = await runMTFTokenizer<{ dims: number[]; data_type: number }>([
140
+ "onnx-read",
141
+ "--model",
142
+ options.onnx,
143
+ "--name",
144
+ QUANTIZED_EMBEDDING,
145
+ "--raw-out",
146
+ table,
147
+ ])
148
+
149
+ if (meta.dims[0] !== vocabulary.length) {
150
+ throw new Error(`embedding rows ${meta.dims[0]} != vocab ${vocabulary.length}`)
151
+ }
152
+
153
+ const rowBytes = (await readFileSize(table)) / vocabulary.length
154
+ const rows = await readLocalBuffer(table)
155
+ const out = Buffer.alloc(keptIDs.length * rowBytes)
156
+
157
+ keptIDs.forEach((id, i) => rows.copy(out, i * rowBytes, id * rowBytes, (id + 1) * rowBytes))
158
+ await writeLocalBuffer(out, gathered)
159
+
160
+ await runMTFTokenizer([
161
+ "onnx-write",
162
+ "--model",
163
+ options.onnx,
164
+ "--name",
165
+ QUANTIZED_EMBEDDING,
166
+ "--dims",
167
+ [keptIDs.length, ...meta.dims.slice(1)].join(","),
168
+ "--data-type",
169
+ String(meta.data_type),
170
+ "--raw",
171
+ gathered,
172
+ "--out",
173
+ onnxOut,
174
+ ])
175
+
176
+ const idMap: PruneIDMap = { kept_ids: keptIDs, old_to_new: oldToNew }
177
+
178
+ await writeLocalJSONFile(idMap, `${options.outDirectory}/id-map.json`)
179
+
180
+ const report: PruneReport = {
181
+ vocab_before: vocabulary.length,
182
+ vocab_after: keptIDs.length,
183
+ train_fired: trainFired,
184
+ eval_fired: evalCount,
185
+ single_codepoint_kept: singleCodepoint,
186
+ tokenizer_bytes: { before: await readFileSize(options.tokenizer), after: await readFileSize(tokenizerOut) },
187
+ onnx_bytes: { before: await readFileSize(options.onnx), after: await readFileSize(onnxOut) },
188
+ }
189
+
190
+ await writeLocalTextFile(prettyJSON(report, true, 1), `${options.outDirectory}/prune-report.json`)
191
+
192
+ console.info(prettyJSON(report, false, 1))
193
+
194
+ return report
195
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * One SentencePiece training call, made with native `spm_train` and written in the Python wheel's model form.
7
+ *
8
+ * The flags are the keyword arguments a `SentencePieceTrainer.train(**flags)` call took, in the same order and with
9
+ * the same values. Two lists go through files rather than the command line, because the CLI splits an inline list
10
+ * on commas and a user-defined symbol may itself be a comma. `minloglevel` sets only the wheel's log level and has
11
+ * no CLI flag, so it is left off the command line.
12
+ *
13
+ * `spm_train` sets every trainer flag on its spec, so the model records defaults the caller did not supply.
14
+ * The wheel's spec holds only fields supplied in the call. After training, the rewrite drops trainer and normalizer
15
+ * fields absent from the flags. This produces the same bytes the wheel produces for that call.
16
+ */
17
+
18
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers"
19
+ import { stringifyJSON } from "@mailwoman/core/json"
20
+ import { runFile } from "@mailwoman/core/process"
21
+ import { resolvePath } from "path-ts"
22
+
23
+ import { editModel, type ModelEditSummary } from "./model.ts"
24
+
25
+ /**
26
+ * One training argument's value.
27
+ */
28
+ export type TrainerFlagValue = string | number | boolean | readonly string[]
29
+
30
+ /**
31
+ * The keyword arguments of one training call, in call order.
32
+ */
33
+ export type TrainerFlags = Readonly<Record<string, TrainerFlagValue>>
34
+
35
+ /**
36
+ * The list flags `spm_train` reads one entry per line from a file.
37
+ */
38
+ const FILE_LIST_FLAGS: Readonly<Record<string, string>> = {
39
+ user_defined_symbols: "user_defined_symbols_file",
40
+ control_symbols: "control_symbols_file",
41
+ }
42
+
43
+ /**
44
+ * The flags only the wheel reads.
45
+ */
46
+ const WHEEL_ONLY_FLAGS = new Set(["minloglevel"])
47
+
48
+ /**
49
+ * This function serializes a list as one CSV row, matching the format Python's
50
+ * `csv.writer` produces for a list flag.
51
+ */
52
+ export function csvRow(values: readonly string[]): string {
53
+ return values
54
+ .map((value) =>
55
+ /[",\r\n]/.test(value) || (values.length === 1 && value === "") ? `"${value.replaceAll('"', '""')}"` : value
56
+ )
57
+ .join(",")
58
+ }
59
+
60
+ /**
61
+ * A scalar flag as the wheel's `str(value)` renders it.
62
+ */
63
+ function scalar(value: string | number | boolean): string {
64
+ if (typeof value === "boolean") return value ? "true" : "false"
65
+
66
+ return String(value)
67
+ }
68
+
69
+ export interface TrainedModel {
70
+ model: string
71
+ vocab: string
72
+ /**
73
+ * The command line `spm_train` ran with.
74
+ */
75
+ argv: string[]
76
+ /**
77
+ * The spec fields the wheel's form dropped.
78
+ */
79
+ dropped: ModelEditSummary["dropped_fields"]
80
+ }
81
+
82
+ export interface TrainOptions {
83
+ spmTrain: string
84
+ /**
85
+ * Where the list files and the trainer's log go.
86
+ */
87
+ workDirectory: string
88
+ /**
89
+ * The directory where `spm_train` runs.
90
+ *
91
+ * Relative `input` and `model_prefix` values resolve from this directory.
92
+ *
93
+ * The model records both paths as given, so a recipe written with relative paths
94
+ * trains to the same bytes in any directory.
95
+ */
96
+ cwd?: string
97
+ }
98
+
99
+ /**
100
+ * Train with `flags` containing `model_prefix`, then rewrite `<model_prefix>.model` in the wheel's form.
101
+ */
102
+ export async function trainSentencePiece(flags: TrainerFlags, options: TrainOptions): Promise<TrainedModel> {
103
+ const prefix = flags["model_prefix"]
104
+
105
+ if (typeof prefix !== "string") throw new Error("a training call needs a model_prefix")
106
+ const argv: string[] = []
107
+
108
+ for (const [name, value] of Object.entries(flags)) {
109
+ if (WHEEL_ONLY_FLAGS.has(name)) continue
110
+
111
+ if (Array.isArray(value)) {
112
+ const listed = value as readonly string[]
113
+ const fileFlag = FILE_LIST_FLAGS[name]
114
+
115
+ if (fileFlag) {
116
+ if (!listed.length) continue
117
+
118
+ for (const entry of listed) {
119
+ if (/[\r\n]/.test(entry)) throw new Error(`${name} entry ${stringifyJSON(entry)} holds a line break`)
120
+ }
121
+
122
+ const file = `${options.workDirectory}/${fileFlag}.txt`
123
+
124
+ await writeLocalTextFile(listed, file)
125
+ argv.push(`--${fileFlag}=${file}`)
126
+ } else {
127
+ argv.push(`--${name}=${csvRow(listed)}`)
128
+ }
129
+ } else {
130
+ argv.push(`--${name}=${scalar(value as string | number | boolean)}`)
131
+ }
132
+ }
133
+
134
+ const { stderr } = await runFile(options.spmTrain, argv, { maxBuffer: 1 << 30, cwd: options.cwd })
135
+
136
+ await writeLocalTextFile(stderr, `${options.workDirectory}/spm_train.log`)
137
+ const base = resolvePath(options.cwd ?? ".", prefix)
138
+ const model = `${base}.model`
139
+ const { dropped_fields } = await editModel(model, model, { wheelFlags: Object.keys(flags) })
140
+
141
+ return { model, vocab: `${base}.vocab`, argv, dropped: dropped_fields }
142
+ }
@@ -0,0 +1,141 @@
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
+
29
+ import { makeDirectories } from "@mailwoman/core/fs/writers"
30
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments"
31
+ import { resolvePath } from "path-ts"
32
+
33
+ import { spmTrainBinary } from "./binary.ts"
34
+ import {
35
+ buildSlavicCorpus,
36
+ checkCodepointOverlap,
37
+ meanInitONNXEmbeddings,
38
+ spliceVocabulary,
39
+ trainDiacriticSentencePiece,
40
+ } from "./splice.ts"
41
+
42
+ const { values, positionals } = parseArguments({
43
+ allowPositionals: true,
44
+ options: {
45
+ "oa-root": { type: "string" },
46
+ locales: { type: "string", default: "cz,pl,sk,si" },
47
+ "base-tokenizer": { type: "string" },
48
+ "out-tokenizer": { type: "string" },
49
+ "vocab-size": { type: "string", default: "24000" },
50
+ "per-file-cap": { type: "string", default: "400000" },
51
+ "work-dir": { type: "string", default: "out/bsplice-work" },
52
+ "trained-samples": { type: "string", default: "" },
53
+ "extra-text": { type: "string" },
54
+ "extra-repeat": { type: "string", default: "10" },
55
+ "accept-overlap": { type: "string", default: "" },
56
+ "spm-train": { type: "string" },
57
+ "fp32-onnx": { type: "string" },
58
+ "spliced-tokenizer": { type: "string" },
59
+ "out-fp32": { type: "string" },
60
+ "int8-onnx": { type: "string" },
61
+ "out-int8": { type: "string" },
62
+ },
63
+ })
64
+
65
+ function list(value: string): string[] {
66
+ return value
67
+ .split(",")
68
+ .map((entry) => entry.trim())
69
+ .filter((entry) => entry.length > 0)
70
+ }
71
+
72
+ const command = positionals[0]
73
+
74
+ if (command === "build-tokenizer") {
75
+ const workDirectory = resolvePath(values["work-dir"])
76
+ const baseTokenizer = resolvePath(requiredArgument(command, "base-tokenizer", values["base-tokenizer"]))
77
+ const outTokenizer = resolvePath(requiredArgument(command, "out-tokenizer", values["out-tokenizer"]))
78
+ const corpus = `${workDirectory}/slavic-corpus.txt`
79
+
80
+ await makeDirectories(workDirectory)
81
+
82
+ const lines = await buildSlavicCorpus({
83
+ oaRoot: resolvePath(requiredArgument(command, "oa-root", values["oa-root"])),
84
+ locales: values.locales.split(","),
85
+ outPath: corpus,
86
+ perFileCap: Number(values["per-file-cap"]),
87
+ extraText: values["extra-text"] ?? null,
88
+ extraRepeat: Number(values["extra-repeat"]),
89
+ })
90
+
91
+ console.log(`corpus: ${lines} lines`)
92
+
93
+ const donor = await trainDiacriticSentencePiece(corpus, `${workDirectory}/slavic-sp`, {
94
+ spmTrain: await spmTrainBinary(values["spm-train"]),
95
+ vocabSize: Number(values["vocab-size"]),
96
+ })
97
+
98
+ const pieces = await spliceVocabulary(baseTokenizer, donor, outTokenizer)
99
+
100
+ console.log(`spliced ${pieces.length} diacritic pieces -> ${outTokenizer}`)
101
+ console.log("English tokenization verified identical (0 differences).")
102
+
103
+ if (values["trained-samples"]) {
104
+ const samples = Object.fromEntries(
105
+ list(values["trained-samples"]).map((pair) => {
106
+ const at = pair.indexOf("=")
107
+
108
+ return [pair.slice(0, at).trim(), pair.slice(at + 1).trim()]
109
+ })
110
+ )
111
+
112
+ const reportPath = outTokenizer.replace(/\.[^./]*$/, "") + ".overlap-report.json"
113
+ const report = await checkCodepointOverlap(pieces, samples, reportPath, new Set(list(values["accept-overlap"])))
114
+ const overlapping = Object.entries(report).flatMap(([locale, codepoints]) => (codepoints.length ? [locale] : []))
115
+
116
+ console.log(
117
+ `overlap check passed; report ${reportPath}; overlapping (accepted): ${overlapping.join(", ") || "none"}`
118
+ )
119
+ }
120
+ } else if (command === "onnx-mean-init") {
121
+ const outFp32 = resolvePath(requiredArgument(command, "out-fp32", values["out-fp32"]))
122
+
123
+ const [oldVocab, newVocab] = await meanInitONNXEmbeddings({
124
+ fp32ONNX: resolvePath(requiredArgument(command, "fp32-onnx", values["fp32-onnx"])),
125
+ baseTokenizer: resolvePath(requiredArgument(command, "base-tokenizer", values["base-tokenizer"])),
126
+ splicedTokenizer: resolvePath(requiredArgument(command, "spliced-tokenizer", values["spliced-tokenizer"])),
127
+ outFp32,
128
+ int8ONNX: values["int8-onnx"] ?? null,
129
+ outInt8: values["out-int8"] ?? null,
130
+ })
131
+
132
+ console.log(`expanded ONNX token_embeddings ${oldVocab} -> ${newVocab}; wrote ${outFp32}`)
133
+
134
+ if (values["out-int8"]) {
135
+ console.log(` int8 twin written ${values["out-int8"]}`)
136
+ }
137
+ } else {
138
+ console.error("usage: splice.run.ts build-tokenizer|onnx-mean-init [options]")
139
+
140
+ process.exitCode = 2
141
+ }