@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,313 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The two checks a pruned tokenizer and model pass before release.
7
+ *
8
+ * B1, segmentation identity: the original and pruned tokenizers produce the same piece sequence, modulo the id
9
+ * renumbering, on every evaluation text and on a random sample of the training rows.
10
+ *
11
+ * B2, logit identity: the original and pruned int8 models answer the evaluation inputs with the same output bits.
12
+ * The graphs differ only in the embedding table and the kept rows are the same bytes, so any difference is a defect
13
+ * of the surgery. Every channel input is fed zeros, because the identity must hold for any channel values. The
14
+ * release battery covers realistic inputs.
15
+ */
16
+
17
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
18
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
19
+ import { writeLocalJSONFile, writeLocalTextFile } from "@mailwoman/core/fs/writers"
20
+ import { prettyJSON, stringifyJSON } from "@mailwoman/core/json"
21
+
22
+ import { runMTFTokenizer } from "./binary.ts"
23
+ import { loadEncoder } from "./model.ts"
24
+ import type { PruneIDMap } from "./prune.ts"
25
+
26
+ /**
27
+ * The number of differing texts each check prints in full.
28
+ * The rest are only counted.
29
+ */
30
+ const SEGMENTATION_DIFFERENCES_SHOWN = 5
31
+ const LOGIT_DIFFERENCES_SHOWN = 3
32
+
33
+ /**
34
+ * An encoder's `encode`, as the checks call it.
35
+ */
36
+ export interface PieceEncoder {
37
+ encode(text: string): { ids: number[]; pieces: string[] }
38
+ }
39
+
40
+ /**
41
+ * B1: the number of `texts` the two tokenizers segment differently, modulo the renumbering.
42
+ *
43
+ * An id that maps to -1 counts as a difference on its own: the pruned vocabulary
44
+ * dropped a piece the text needs.
45
+ */
46
+ export function checkSegmentationIdentity(
47
+ original: PieceEncoder,
48
+ pruned: PieceEncoder,
49
+ oldToNew: readonly number[],
50
+ texts: readonly string[],
51
+ label: string
52
+ ): number {
53
+ let differing = 0
54
+
55
+ for (const text of texts) {
56
+ const before = original.encode(text)
57
+ const after = pruned.encode(text)
58
+ const mapped = before.ids.map((id) => oldToNew[id] ?? -1)
59
+
60
+ if (mapped.includes(-1) || mapped.length !== after.ids.length || mapped.some((id, i) => id !== after.ids[i])) {
61
+ differing++
62
+
63
+ if (differing <= SEGMENTATION_DIFFERENCES_SHOWN) {
64
+ console.info(`[B1 DIFF] ${label}: ${stringifyJSON(text)}`)
65
+ console.info(` orig : ${stringifyJSON(before.pieces)}`)
66
+ console.info(` pruned: ${stringifyJSON(after.pieces)}`)
67
+ }
68
+ }
69
+ }
70
+
71
+ console.info(`[B1] ${label}: ${texts.length.toLocaleString("en-US")} texts, ${differing} diffs`)
72
+
73
+ return differing
74
+ }
75
+
76
+ /**
77
+ * The input description B2 builds feeds from: a name, an element type, and a shape whose
78
+ * entries are sizes or the symbolic dimensions `batch` and `sequence`.
79
+ */
80
+ export interface InputMeta {
81
+ name: string
82
+ type: string
83
+ shape: readonly (number | string)[]
84
+ }
85
+
86
+ /**
87
+ * A feed's element type, values and shape.
88
+ */
89
+ export interface Feed {
90
+ type: "int64" | "float32"
91
+ data: BigInt64Array | Float32Array
92
+ dims: number[]
93
+ }
94
+
95
+ /**
96
+ * One input's feed for `ids`: the ids for `input_ids`, ones for `attention_mask`,
97
+ * zeros for every other input.
98
+ */
99
+ export function feedsFor(metas: readonly InputMeta[], ids: readonly number[]): Record<string, Feed> {
100
+ const feeds: Record<string, Feed> = {}
101
+
102
+ for (const meta of metas) {
103
+ const type = meta.type.includes("int64") ? "int64" : "float32"
104
+
105
+ const dims = meta.shape.map((dim) => {
106
+ if (dim === "batch") return 1
107
+
108
+ if (dim === "sequence") return ids.length
109
+ const size = Number(dim)
110
+
111
+ if (!Number.isInteger(size)) throw new Error(`input ${meta.name} has the unresolved dimension ${dim}`)
112
+
113
+ return size
114
+ })
115
+
116
+ const size = dims.reduce((product, d) => product * d, 1)
117
+ let data: BigInt64Array | Float32Array
118
+
119
+ if (meta.name === "input_ids") {
120
+ data = BigInt64Array.from(ids, (id) => BigInt(id))
121
+ } else if (type === "int64") {
122
+ data = new BigInt64Array(size).fill(meta.name === "attention_mask" ? 1n : 0n)
123
+ } else {
124
+ data = new Float32Array(size).fill(meta.name === "attention_mask" ? 1 : 0)
125
+ }
126
+
127
+ feeds[meta.name] = { type, data, dims }
128
+ }
129
+
130
+ return feeds
131
+ }
132
+
133
+ /**
134
+ * A session's metadata and a call that answers its outputs, in output order, for one set of feeds.
135
+ */
136
+ export interface LogitSession {
137
+ inputs: readonly InputMeta[]
138
+ run(feeds: Record<string, Feed>): Promise<Float32Array[]>
139
+ }
140
+
141
+ function bytesOf(values: ArrayBufferView): Buffer {
142
+ return Buffer.from(values.buffer, values.byteOffset, values.byteLength)
143
+ }
144
+
145
+ /**
146
+ * B2: the number of `texts` the two models answer differently, bit for bit.
147
+ *
148
+ * An unmapped id is refused, because the comparison would score a graph against inputs it cannot represent.
149
+ */
150
+ export async function checkLogitParity(
151
+ original: PieceEncoder,
152
+ oldToNew: readonly number[],
153
+ originalSession: LogitSession,
154
+ prunedSession: LogitSession,
155
+ texts: readonly string[]
156
+ ): Promise<number> {
157
+ let differing = 0
158
+
159
+ for (const text of texts) {
160
+ const ids = original.encode(text).ids
161
+ const mapped = ids.map((id) => oldToNew[id] ?? -1)
162
+
163
+ if (mapped.includes(-1)) throw new Error(`unmapped id in B2 input: ${stringifyJSON(text)}`)
164
+ const before = await originalSession.run(feedsFor(originalSession.inputs, ids))
165
+ const after = await prunedSession.run(feedsFor(prunedSession.inputs, mapped))
166
+
167
+ for (let k = 0; k < before.length; k++) {
168
+ if (!bytesOf(before[k]!).equals(bytesOf(after[k]!))) {
169
+ differing++
170
+
171
+ if (differing <= LOGIT_DIFFERENCES_SHOWN) {
172
+ let largest = 0
173
+
174
+ before[k]!.forEach((v, i) => (largest = Math.max(largest, Math.abs(v - after[k]![i]!))))
175
+
176
+ console.info(`[B2 DIFF] ${stringifyJSON(text)}: max |Δ| ${largest}`)
177
+ }
178
+
179
+ break
180
+ }
181
+ }
182
+ }
183
+
184
+ console.info(`[B2] ${texts.length} inputs, ${differing} non-bit-equal`)
185
+
186
+ return differing
187
+ }
188
+
189
+ /**
190
+ * An onnxruntime-node session over `path`, with four intra-op threads on the CPU.
191
+ */
192
+ async function openLogitSession(path: string): Promise<LogitSession & AsyncDisposable> {
193
+ const ort = await import("onnxruntime-node")
194
+
195
+ const session = await ort.InferenceSession.create(path, {
196
+ intraOpNumThreads: 4,
197
+ executionProviders: ["cpu"],
198
+ })
199
+
200
+ const inputs = session.inputMetadata.flatMap((meta) =>
201
+ meta.isTensor ? [{ name: meta.name, type: meta.type, shape: meta.shape }] : []
202
+ )
203
+
204
+ return {
205
+ inputs,
206
+ async run(feeds) {
207
+ const tensors = Object.fromEntries(
208
+ Object.entries(feeds).map(([name, feed]) => [name, new ort.Tensor(feed.type, feed.data, feed.dims)])
209
+ )
210
+
211
+ const outputs = await session.run(tensors)
212
+
213
+ return session.outputNames.map((name) => outputs[name]!.data as Float32Array)
214
+ },
215
+ [Symbol.asyncDispose]: () => session.release(),
216
+ }
217
+ }
218
+
219
+ export interface VerifyPruneOptions {
220
+ originalTokenizer: string
221
+ originalONNX: string
222
+ prunedDirectory: string
223
+ manifest: string
224
+ evalTexts: string
225
+ sampleRows?: number
226
+ logitInputs?: number
227
+ seed?: number
228
+ /**
229
+ * Rewrites the manifest's build-machine prefix onto this host: each train path
230
+ * starting with `from` is read under `to`.
231
+ */
232
+ remap: readonly [from: string, to: string]
233
+ }
234
+
235
+ export interface VerifyReport {
236
+ b1_eval_texts: number
237
+ b1_train_sample: number
238
+ b1_diffs: number
239
+ b2_inputs: number
240
+ b2_diffs: number
241
+ verdict: "PASS" | "FAIL"
242
+ }
243
+
244
+ /**
245
+ * Run B1 and B2 over a pruned directory and write `verify-report.json` into it.
246
+ */
247
+ export async function verifyPrune(options: VerifyPruneOptions): Promise<VerifyReport> {
248
+ const seed = options.seed ?? 42
249
+ const { old_to_new: oldToNew } = await readLocalJSONFile<PruneIDMap>(`${options.prunedDirectory}/id-map.json`)
250
+ const { texts: evalTexts } = await readLocalJSONFile<{ texts: string[] }>(options.evalTexts)
251
+
252
+ await using scratch = await temporaryDirectory("mtf-verify-")
253
+ const listed = await runMTFTokenizer<string[]>(["manifest-train-files", "--manifest", options.manifest])
254
+ const [from, to] = options.remap
255
+ const files = listed.map((path) => (path.startsWith(from) ? to + path.slice(from.length) : path))
256
+ const filesPath = scratch.path("files.json").toString()
257
+ const rowsPath = scratch.path("rows.json").toString()
258
+
259
+ await writeLocalJSONFile(files, filesPath)
260
+
261
+ await runMTFTokenizer([
262
+ "sample-rows",
263
+ "--files",
264
+ filesPath,
265
+ "--rows",
266
+ String(options.sampleRows ?? 1_000_000),
267
+ "--seed",
268
+ String(seed),
269
+ "--out",
270
+ rowsPath,
271
+ ])
272
+
273
+ const trainSample = await readLocalJSONFile<string[]>(rowsPath)
274
+
275
+ using original = await loadEncoder(options.originalTokenizer)
276
+ using pruned = await loadEncoder(`${options.prunedDirectory}/tokenizer.model`)
277
+ let b1 = checkSegmentationIdentity(original, pruned, oldToNew, evalTexts, "eval-surface")
278
+
279
+ b1 += checkSegmentationIdentity(original, pruned, oldToNew, trainSample, "train-sample")
280
+
281
+ const picked = await runMTFTokenizer<number[]>([
282
+ "sample-indices",
283
+ "--population",
284
+ String(evalTexts.length),
285
+ "--count",
286
+ String(Math.min(options.logitInputs ?? 256, evalTexts.length)),
287
+ "--seed",
288
+ String(seed),
289
+ ])
290
+
291
+ const logitTexts = picked.map((i) => evalTexts[i]!)
292
+
293
+ await using originalSession = await openLogitSession(options.originalONNX)
294
+ await using prunedSession = await openLogitSession(`${options.prunedDirectory}/model.onnx`)
295
+ const b2 = await checkLogitParity(original, oldToNew, originalSession, prunedSession, logitTexts)
296
+
297
+ const verdict = b1 === 0 && b2 === 0 ? "PASS" : "FAIL"
298
+
299
+ console.info(`VERDICT: ${verdict} (B1 diffs ${b1}, B2 diffs ${b2})`)
300
+
301
+ const report: VerifyReport = {
302
+ b1_eval_texts: evalTexts.length,
303
+ b1_train_sample: trainSample.length,
304
+ b1_diffs: b1,
305
+ b2_inputs: logitTexts.length,
306
+ b2_diffs: b2,
307
+ verdict,
308
+ }
309
+
310
+ await writeLocalTextFile(prettyJSON(report, true, 1), `${options.prunedDirectory}/verify-report.json`)
311
+
312
+ return report
313
+ }