@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,71 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Check a tokenizer.
7
+ *
8
+ * `byte-fallback` encodes a held-out fixture (JSONL with `raw`, `text` or `input`, or plain text) and prints the
9
+ * byte-fallback rate overall and per script.
10
+ *
11
+ * `prune` runs the two release checks of a pruned tokenizer and model, segmentation identity (B1) and bit-equal
12
+ * logits (B2), writes `verify-report.json` into the pruned directory, and exits non-zero unless both pass.
13
+ *
14
+ * Usage:
15
+ *
16
+ * node packages/mtf/tools/tokenizer/verify.run.ts byte-fallback --tokenizer <model> --fixture <jsonl>
17
+ * node packages/mtf/tools/tokenizer/verify.run.ts prune --orig-tokenizer <model> --orig-onnx <onnx>
18
+ * --pruned-dir <dir> --manifest <MANIFEST.json> --eval-texts <json> [--sample-rows 1000000]
19
+ * [--logit-inputs 256] [--seed 42] [--data-root-remap <from>:<to>]
20
+ */
21
+ import { dataRootPath } from "@mailwoman/core/data-root";
22
+ import { prettyJSON } from "@mailwoman/core/json";
23
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments";
24
+ import { resolvePath } from "path-ts";
25
+ import { measureByteFallback, readFixtureLines } from "./byte-fallback.js";
26
+ import { verifyPrune } from "./verify.js";
27
+ const { values, positionals } = parseArguments({
28
+ allowPositionals: true,
29
+ options: {
30
+ tokenizer: { type: "string" },
31
+ fixture: { type: "string" },
32
+ "orig-tokenizer": { type: "string" },
33
+ "orig-onnx": { type: "string" },
34
+ "pruned-dir": { type: "string" },
35
+ manifest: { type: "string" },
36
+ "eval-texts": { type: "string" },
37
+ "sample-rows": { type: "string", default: "1000000" },
38
+ "logit-inputs": { type: "string", default: "256" },
39
+ seed: { type: "string", default: "42" },
40
+ "data-root-remap": { type: "string" },
41
+ },
42
+ });
43
+ const command = positionals[0];
44
+ if (command === "byte-fallback") {
45
+ const tokenizer = resolvePath(requiredArgument(command, "tokenizer", values.tokenizer));
46
+ const fixture = resolvePath(requiredArgument(command, "fixture", values.fixture));
47
+ console.log(prettyJSON(await measureByteFallback(tokenizer, await readFixtureLines(fixture)), false, 2));
48
+ }
49
+ else if (command === "prune") {
50
+ const remap = values["data-root-remap"] ?? `/data:${dataRootPath()}`;
51
+ const at = remap.indexOf(":");
52
+ const report = await verifyPrune({
53
+ originalTokenizer: resolvePath(requiredArgument(command, "orig-tokenizer", values["orig-tokenizer"])),
54
+ originalONNX: resolvePath(requiredArgument(command, "orig-onnx", values["orig-onnx"])),
55
+ prunedDirectory: resolvePath(requiredArgument(command, "pruned-dir", values["pruned-dir"])),
56
+ manifest: resolvePath(requiredArgument(command, "manifest", values.manifest)),
57
+ evalTexts: resolvePath(requiredArgument(command, "eval-texts", values["eval-texts"])),
58
+ sampleRows: Number(values["sample-rows"]),
59
+ logitInputs: Number(values["logit-inputs"]),
60
+ seed: Number(values.seed),
61
+ remap: [remap.slice(0, at), remap.slice(at + 1)],
62
+ });
63
+ if (report.verdict !== "PASS") {
64
+ process.exitCode = 1;
65
+ }
66
+ }
67
+ else {
68
+ console.error("usage: verify.run.ts byte-fallback|prune [options]");
69
+ process.exitCode = 2;
70
+ }
71
+ //# sourceMappingURL=verify.run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.run.js","sourceRoot":"","sources":["../../../tools/tokenizer/verify.run.ts"],"names":[],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/mtf",
3
- "version": "10.7.0",
3
+ "version": "10.8.0",
4
4
  "description": "Multilingual Token Framework: Mailwoman's subword tokenizer, a Rust core compiled to WASM with a TypeScript loader. It reproduces SentencePiece v0.2.2's pieces and offsets on the shipped unigram model and is the tokenizer runtime for @mailwoman/neural.",
5
5
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
6
  "repository": {
@@ -90,9 +90,21 @@
90
90
  }
91
91
  },
92
92
  "dependencies": {
93
- "@mailwoman/core": "10.7.0"
93
+ "@mailwoman/core": "10.8.0",
94
+ "@mailwoman/query-shape": "10.8.0",
95
+ "path-ts": "^2.5.0",
96
+ "spliterator": "^10.1.1"
94
97
  },
95
98
  "devDependencies": {
96
- "@types/node": "^26.6.5"
99
+ "@types/node": "^26.6.6",
100
+ "onnxruntime-node": "^1.31.1"
101
+ },
102
+ "peerDependencies": {
103
+ "onnxruntime-node": "^1.26.0"
104
+ },
105
+ "peerDependenciesMeta": {
106
+ "onnxruntime-node": {
107
+ "optional": true
108
+ }
97
109
  }
98
110
  }
@@ -14,14 +14,14 @@
14
14
  import { statPath } from "@mailwoman/core/fs/readers/stat"
15
15
  import { replaceFileAtomically } from "@mailwoman/core/fs/writers"
16
16
  import { sha256File } from "@mailwoman/core/hash"
17
- import { workspacePath } from "@mailwoman/core/paths"
17
+ import { repoRootPath, workspacePath } from "@mailwoman/core/paths"
18
18
  import { runFile } from "@mailwoman/core/process"
19
19
  import { parseArguments } from "@mailwoman/core/scripting/arguments"
20
20
 
21
21
  const { values } = parseArguments({ options: { check: { type: "boolean", default: false } } })
22
22
 
23
23
  const workspace = workspacePath("mtf")
24
- const built = workspacePath("mtf", "target", "wasm32-unknown-unknown", "release", "mtf_wasm.wasm")
24
+ const built = repoRootPath("target", "wasm32-unknown-unknown", "release", "mtf_wasm.wasm")
25
25
  const committed = workspacePath("mtf", "wasm", "mtf.wasm")
26
26
 
27
27
  await runFile("cargo", ["build", "--release", "--locked", "--target", "wasm32-unknown-unknown", "-p", "mtf-wasm"], {
@@ -0,0 +1,433 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The `mtf-node` addon: the training-row sampler and the row encoders of `crates/mtf-node`, loaded into Node.
7
+ *
8
+ * Cargo builds the addon from source the first time a process asks for it, under the root workspace's `node`
9
+ * profile and the toolchain the root `rust-toolchain.toml` pins, into the root `target/node/`. The build
10
+ * reads `mtf-sampler` with its parquet reader, so it stays out of the browser `wasm/mtf.wasm`, whose one dependency is
11
+ * `mtf-core`. The addon is built for the host it runs on: Linux and macOS, where Cargo writes the library to
12
+ * `libmtf_node.so` and `libmtf_node.dylib`.
13
+ */
14
+
15
+ import { repoRootPath, workspacePath } from "@mailwoman/core/paths"
16
+ import { runFile } from "@mailwoman/core/process"
17
+ import { platformName as platform } from "@mailwoman/core/utils/system"
18
+
19
+ /**
20
+ * One sampled row.
21
+ * The span triple is present when the row's file stores one.
22
+ */
23
+ export interface SampledRow {
24
+ raw: string
25
+ tokens: string[]
26
+ labels: string[]
27
+ country: string | null
28
+ source: string
29
+ spanStarts?: number[] | null
30
+ spanEnds?: number[] | null
31
+ spanTags?: string[] | null
32
+ }
33
+
34
+ /**
35
+ * A count per source.
36
+ */
37
+ export interface SourceCount {
38
+ source: string
39
+ count: number
40
+ }
41
+
42
+ /**
43
+ * A count per postcode-move outcome.
44
+ */
45
+ export interface OutcomeCount {
46
+ outcome: string
47
+ count: number
48
+ }
49
+
50
+ /**
51
+ * The kinds of event the sampler reports.
52
+ */
53
+ export const SamplerEventKind = {
54
+ RowEmitted: "row_emitted",
55
+ RowSkipped: "row_skipped",
56
+ SourceRestarted: "source_restarted",
57
+ EpochComplete: "epoch_complete",
58
+ } as const
59
+
60
+ export type SamplerEventKind = (typeof SamplerEventKind)[keyof typeof SamplerEventKind]
61
+
62
+ /**
63
+ * One sampler event, with the fields its kind sets.
64
+ */
65
+ export interface SamplerEvent {
66
+ kind: SamplerEventKind
67
+ index?: number | null
68
+ source?: string | null
69
+ country?: string | null
70
+ reason?: string | null
71
+ raw?: string | null
72
+ passes?: number | null
73
+ realized?: SourceCount[] | null
74
+ }
75
+
76
+ /**
77
+ * What opening a stream takes beyond the config, split and seed.
78
+ */
79
+ export interface NativeStreamOptions {
80
+ /**
81
+ * Caps the rows the stream emits, counted before the astral skip.
82
+ */
83
+ rowLimit?: number | null
84
+ /**
85
+ * The event kinds to collect for `takeEvents`.
86
+ */
87
+ events?: SamplerEventKind[] | null
88
+ }
89
+
90
+ export interface NativeSampler {
91
+ nextRows(count: number): SampledRow[]
92
+ takeEvents(): SamplerEvent[]
93
+ cancel(): void
94
+ readonly yielded: number
95
+ readonly astralSkipped: number
96
+ readonly postcodeMoveOutcomes: OutcomeCount[]
97
+ }
98
+
99
+ export interface NativeTrainingBatches {
100
+ nextBatch(): SampledRow[]
101
+ cancel(): void
102
+ readonly epoch: number
103
+ }
104
+
105
+ /**
106
+ * One upstream row and the rows the emit step made of it.
107
+ */
108
+ export interface EmittedDraw {
109
+ drawn: SampledRow
110
+ emitted: SampledRow[]
111
+ }
112
+
113
+ export interface NativeRawRows {
114
+ nextRaw(count: number): SampledRow[]
115
+ nextEmitted(count: number): EmittedDraw[]
116
+ takeEvents(): SamplerEvent[]
117
+ cancel(): void
118
+ readonly drawn: number
119
+ readonly postcodeMoveOutcomes: OutcomeCount[]
120
+ }
121
+
122
+ /**
123
+ * One row group's admitted rows over the requested columns.
124
+ */
125
+ export interface SplitColumnChunk {
126
+ rows: number
127
+ strings: Record<string, Array<string | null>>
128
+ lists: Record<string, Array<string[] | null>>
129
+ /**
130
+ * Each list-of-integers column, such as `span_starts`.
131
+ */
132
+ intLists: Record<string, Array<number[] | null>>
133
+ }
134
+
135
+ /**
136
+ * The rows a split read keeps: those whose string column `column`, uppercased, is one of `values`.
137
+ * A row whose value is null is not kept.
138
+ */
139
+ export interface SplitKeep {
140
+ column: string
141
+ values: string[]
142
+ }
143
+
144
+ /**
145
+ * Every row a split holds over a few columns, in file and row order.
146
+ */
147
+ export interface NativeSplitColumns {
148
+ readonly files: number
149
+ nextChunk(): SplitColumnChunk | null
150
+ }
151
+
152
+ /**
153
+ * What a row encoder reads.
154
+ * Every lexicon path left unset leaves its channel off.
155
+ */
156
+ export interface RowEncoderOptions {
157
+ tokenizerModelPath: string
158
+ labelSchemaPath: string
159
+ labelSet?: string | null
160
+ maxLength: number
161
+ padID?: number | null
162
+ postcodeShapesPath: string
163
+ postcodeSyntaxPath: string
164
+ anchorLookupPath?: string | null
165
+ anchorPaintMode?: "gold" | "shaped" | null
166
+ gazetteerLexiconPath?: string | null
167
+ gazetteerChoreography?: boolean | null
168
+ countryLexiconPath?: string | null
169
+ streetTypeLexiconPath?: string | null
170
+ localitySurfaceLexiconPath?: string | null
171
+ codeUnits?: boolean | null
172
+ }
173
+
174
+ /**
175
+ * One configured channel of an encoded batch: `features` `[B, L, dim]` and `confidence` `[B, L]`.
176
+ */
177
+ export interface EncodedChannel {
178
+ name: string
179
+ dim: number
180
+ features: Float32Array
181
+ confidence: Float32Array
182
+ }
183
+
184
+ /**
185
+ * An encoded batch: `inputIDs`, `attentionMask` and `labels` int64 `[B, L]` in row-major order.
186
+ */
187
+ export interface EncodedRows {
188
+ rows: number
189
+ maxLength: number
190
+ inputIDs: BigInt64Array
191
+ attentionMask: BigInt64Array
192
+ labels: BigInt64Array
193
+ channels: EncodedChannel[]
194
+ }
195
+
196
+ export interface NativeRowEncoder {
197
+ encodeBatch(rows: SampledRow[]): EncodedRows
198
+ readonly channelDims: Array<{ name: string; dim: number }>
199
+ }
200
+
201
+ /**
202
+ * The character path's settings.
203
+ */
204
+ export interface CharEncoderOptions {
205
+ mode: "word" | "char"
206
+ vocabPath: string
207
+ maxUnits: number
208
+ maxUnitWidth: number
209
+ charCtx?: number | null
210
+ labelSet: string
211
+ labelSchemaPath: string
212
+ }
213
+
214
+ /**
215
+ * A char-path batch: `charIDs` int64 `[B, S, W]`, `attentionMask` and `labels` int64 `[B, S]`.
216
+ */
217
+ export interface EncodedChars {
218
+ rows: number
219
+ maxUnits: number
220
+ maxUnitWidth: number
221
+ charIDs: BigInt64Array
222
+ attentionMask: BigInt64Array
223
+ labels: BigInt64Array
224
+ }
225
+
226
+ export interface NativeCharEncoder {
227
+ encodeBatch(rows: SampledRow[]): EncodedChars
228
+ }
229
+
230
+ export interface SourceWeight {
231
+ source: string
232
+ weight: number
233
+ }
234
+
235
+ export interface DerivedSourceReps {
236
+ source: string
237
+ targetRepsPerRow: number
238
+ rows: number
239
+ weight: number
240
+ }
241
+
242
+ /**
243
+ * The addon's exports, as `crates/mtf-node/src/lib.rs` declares them.
244
+ */
245
+ interface NativeModule {
246
+ Sampler: new (config: string, split: string, seed: number, options?: NativeStreamOptions | null) => NativeSampler
247
+ TrainingBatches: new (
248
+ config: string,
249
+ batchSize: number,
250
+ seed: number,
251
+ rowLimit?: number | null,
252
+ skipBatches?: number | null
253
+ ) => NativeTrainingBatches
254
+ RawRows: new (config: string, split: string, seed: number, options?: NativeStreamOptions | null) => NativeRawRows
255
+ SplitColumns: new (config: string, split: string, columns: string[], keep?: SplitKeep | null) => NativeSplitColumns
256
+ RowEncoder: new (options: NativeRowEncoderOptions) => {
257
+ encodeBatch(rows: SampledRow[]): RawEncodedRows
258
+ readonly channelDims: Array<{ name: string; dim: number }>
259
+ }
260
+ CharEncoder: new (options: CharEncoderOptions) => { encodeBatch(rows: SampledRow[]): RawEncodedChars }
261
+ sourceRowCounts(config: string, split: string): SourceCount[]
262
+ deriveSourceWeights(
263
+ fixed: SourceWeight[] | null,
264
+ sourceReps: SourceWeight[],
265
+ rowsBySource: SourceCount[],
266
+ samples: number
267
+ ): { merged: SourceWeight[]; derived: DerivedSourceReps[] }
268
+ channelNames(): string[]
269
+ pythonCasefold(text: string): string
270
+ pythonScriptRuns(text: string): string[]
271
+ pythonDetectScript(text: string): string
272
+ pythonIsLatinText(text: string): boolean
273
+ }
274
+
275
+ /**
276
+ * Python 3.12's string semantics for the training tools, read from the CPython
277
+ * Unicode tables in `mtf-channels/src/python_text/tables.rs`.
278
+ *
279
+ * Node's ICU follows another Unicode version and has no character-name table.
280
+ */
281
+ export interface PythonText {
282
+ /**
283
+ * `str.casefold`.
284
+ */
285
+ casefold(text: string): string
286
+ /**
287
+ * The consecutive runs of letter scripts, every character that is not a letter skipped,
288
+ * as the mixed-script audit's `script_runs` names them.
289
+ */
290
+ scriptRuns(text: string): string[]
291
+ /**
292
+ * The exposure phenomena's coarse script tag: a script block, `mixed` or `other`.
293
+ */
294
+ detectScript(text: string): string
295
+ /**
296
+ * Whether the text holds a letter and every letter is Latin script by Unicode name.
297
+ */
298
+ isLatinText(text: string): boolean
299
+ }
300
+
301
+ /**
302
+ * napi-rs camel-cases each Rust field name, so `pad_id` arrives as `padId`.
303
+ */
304
+ type NativeRowEncoderOptions = Omit<RowEncoderOptions, "padID"> & { padId?: number | null }
305
+
306
+ interface RawEncodedRows extends Omit<EncodedRows, "inputIDs"> {
307
+ inputIds: BigInt64Array
308
+ }
309
+
310
+ interface RawEncodedChars extends Omit<EncodedChars, "charIDs"> {
311
+ charIds: BigInt64Array
312
+ }
313
+
314
+ /**
315
+ * The file Cargo writes the addon to on each platform the addon builds for.
316
+ */
317
+ const LIBRARY_NAMES: Partial<Record<string, string>> = {
318
+ linux: "libmtf_node.so",
319
+ darwin: "libmtf_node.dylib",
320
+ }
321
+
322
+ /**
323
+ * Cargo's output for one build can run long, so the buffer is far above Node's 1 MB default.
324
+ */
325
+ const OUTPUT_LIMIT = 1 << 30
326
+
327
+ let addon: Promise<NativeModule> | null = null
328
+
329
+ /**
330
+ * The path of a current `mtf-node` build, building it first.
331
+ *
332
+ * Cargo rebuilds only when a crate source, a manifest or the lockfile changed,
333
+ * so a current build costs a second.
334
+ */
335
+ export async function buildMTFNode(): Promise<string> {
336
+ const name = LIBRARY_NAMES[platform()]
337
+
338
+ if (!name) {
339
+ throw new Error(`mtf-node builds on Linux and macOS; this host is ${platform()}`)
340
+ }
341
+
342
+ await runFile("cargo", ["build", "--profile", "node", "--locked", "-p", "mtf-node"], {
343
+ cwd: workspacePath("mtf"),
344
+ maxBuffer: OUTPUT_LIMIT,
345
+ })
346
+
347
+ return repoRootPath("target", "node", name)
348
+ }
349
+
350
+ /**
351
+ * The loaded addon, built the first time a process asks.
352
+ */
353
+ export function loadMTFNode(): Promise<NativeModule> {
354
+ addon ??= (async () => {
355
+ const path = await buildMTFNode()
356
+ const module = { exports: {} as NativeModule }
357
+
358
+ // `require` loads an addon only from a `.node` file, and Cargo gives the library the
359
+ // platform's extension, so the addon is opened the way `require` opens one.
360
+ process.dlopen(module, path)
361
+
362
+ return module.exports
363
+ })()
364
+
365
+ return addon
366
+ }
367
+
368
+ /**
369
+ * The addon's classes and functions under the repository's identifier spelling.
370
+ */
371
+ export interface MTFNode {
372
+ Sampler: NativeModule["Sampler"]
373
+ TrainingBatches: NativeModule["TrainingBatches"]
374
+ RawRows: NativeModule["RawRows"]
375
+ SplitColumns: NativeModule["SplitColumns"]
376
+ createRowEncoder(options: RowEncoderOptions): NativeRowEncoder
377
+ createCharEncoder(options: CharEncoderOptions): NativeCharEncoder
378
+ sourceRowCounts: NativeModule["sourceRowCounts"]
379
+ deriveSourceWeights: NativeModule["deriveSourceWeights"]
380
+ channelNames: NativeModule["channelNames"]
381
+ pythonText: PythonText
382
+ }
383
+
384
+ /**
385
+ * The addon, with the encoders' outputs renamed to the repository's acronym spelling.
386
+ */
387
+ export async function mtfNode(): Promise<MTFNode> {
388
+ const native = await loadMTFNode()
389
+
390
+ return {
391
+ Sampler: native.Sampler,
392
+ TrainingBatches: native.TrainingBatches,
393
+ RawRows: native.RawRows,
394
+ SplitColumns: native.SplitColumns,
395
+ createRowEncoder(options) {
396
+ const { padID, ...rest } = options
397
+ // napi-rs reads an `Option` from `undefined` and refuses `null`, which an unset config path holds.
398
+ const present = Object.fromEntries(Object.entries(rest).filter(([, value]) => value != null))
399
+ const encoder = new native.RowEncoder({ ...(present as typeof rest), padId: padID })
400
+
401
+ return {
402
+ get channelDims() {
403
+ return encoder.channelDims
404
+ },
405
+ encodeBatch(rows) {
406
+ const { inputIds, ...batch } = encoder.encodeBatch(rows)
407
+
408
+ return { ...batch, inputIDs: inputIds }
409
+ },
410
+ }
411
+ },
412
+ createCharEncoder(options) {
413
+ const encoder = new native.CharEncoder(options)
414
+
415
+ return {
416
+ encodeBatch(rows) {
417
+ const { charIds, ...batch } = encoder.encodeBatch(rows)
418
+
419
+ return { ...batch, charIDs: charIds }
420
+ },
421
+ }
422
+ },
423
+ sourceRowCounts: native.sourceRowCounts,
424
+ deriveSourceWeights: native.deriveSourceWeights,
425
+ channelNames: native.channelNames,
426
+ pythonText: {
427
+ casefold: native.pythonCasefold,
428
+ scriptRuns: native.pythonScriptRuns,
429
+ detectScript: native.pythonDetectScript,
430
+ isLatinText: native.pythonIsLatinText,
431
+ },
432
+ }
433
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The two native programs the tokenizer tools run: `mtf-tokenizer`, built from `crates/mtf-tools`, and
7
+ * SentencePiece v0.2.2's `spm_train`.
8
+ *
9
+ * `mtf-tokenizer` is a binary rather than a Node addon. Each tool calls it a handful of times over files, so a
10
+ * process per call costs milliseconds. A binary also builds without an addon toolchain, a per-platform artifact or ABI
11
+ * matching against Node. Cargo builds it on first use under the `tools` profile.
12
+ *
13
+ * `spm_train` is built from the google/sentencepiece tag the runtime and the Python wheel were built from, with the
14
+ * CMake recipe of `packages/sentencepiece-wasm/build.sh` minus emscripten. The checkout and build live under the
15
+ * cache root, outside the repository.
16
+ */
17
+
18
+ import { cacheRootPath } from "@mailwoman/core/data-root"
19
+ import { isFile } from "@mailwoman/core/fs/readers/stat"
20
+ import { makeDirectories } from "@mailwoman/core/fs/writers"
21
+ import { git, gitHead } from "@mailwoman/core/git"
22
+ import { parseJSONStrict } from "@mailwoman/core/json"
23
+ import { repoRootPath, workspacePath } from "@mailwoman/core/paths"
24
+ import { runFile } from "@mailwoman/core/process"
25
+
26
+ /**
27
+ * The SentencePiece release every tokenizer is trained with, and the commit its tag names.
28
+ */
29
+ export const SENTENCEPIECE = {
30
+ version: "0.2.2",
31
+ tag: "v0.2.2",
32
+ commit: "e0cce7d37b065b5140349dbe12c6bcf6192fdd78",
33
+ } as const
34
+
35
+ /**
36
+ * Child output can be a full model inspection, so the buffer is far above Node's 1 MB default.
37
+ */
38
+ const OUTPUT_LIMIT = 1 << 30
39
+
40
+ let mtfTokenizerBuild: Promise<string> | null = null
41
+
42
+ /**
43
+ * The path of a current `mtf-tokenizer` build, building it the first time a process asks.
44
+ */
45
+ export function mtfTokenizerBinary(): Promise<string> {
46
+ mtfTokenizerBuild ??= (async () => {
47
+ await runFile("cargo", ["build", "--profile", "tools", "--locked", "-p", "mtf-tools"], {
48
+ cwd: workspacePath("mtf"),
49
+ maxBuffer: OUTPUT_LIMIT,
50
+ })
51
+
52
+ return repoRootPath("target", "tools", "mtf-tokenizer")
53
+ })()
54
+
55
+ return mtfTokenizerBuild
56
+ }
57
+
58
+ /**
59
+ * Run one `mtf-tokenizer` command and parse the JSON it prints.
60
+ */
61
+ export async function runMTFTokenizer<T>(args: readonly string[]): Promise<T> {
62
+ const { stdout } = await runFile(await mtfTokenizerBinary(), args, { maxBuffer: OUTPUT_LIMIT })
63
+
64
+ return parseJSONStrict<T>(stdout)
65
+ }
66
+
67
+ /**
68
+ * The `spm_train` to run: `explicit` when given, otherwise a build of {@linkcode SENTENCEPIECE}
69
+ * under the cache root, cloned and compiled the first time.
70
+ */
71
+ export async function spmTrainBinary(explicit?: string | null): Promise<string> {
72
+ if (explicit) {
73
+ if (!(await isFile(explicit))) throw new Error(`--spm-train ${explicit} is not a file`)
74
+
75
+ return explicit
76
+ }
77
+
78
+ const root = cacheRootPath(`sentencepiece-${SENTENCEPIECE.tag}`)
79
+ const source = `${root}/src`
80
+ const build = `${root}/build`
81
+ const binary = `${build}/src/spm_train`
82
+
83
+ if (await isFile(binary)) return binary
84
+
85
+ await makeDirectories(root)
86
+
87
+ if (!(await isFile(`${source}/CMakeLists.txt`))) {
88
+ await git(
89
+ [
90
+ "clone",
91
+ "--quiet",
92
+ "--depth",
93
+ "1",
94
+ "--branch",
95
+ SENTENCEPIECE.tag,
96
+ "https://github.com/google/sentencepiece.git",
97
+ source,
98
+ ],
99
+ root
100
+ )
101
+ }
102
+
103
+ const head = await gitHead(source)
104
+
105
+ if (head !== SENTENCEPIECE.commit) {
106
+ throw new Error(`${source} is at ${head}, not ${SENTENCEPIECE.tag} (${SENTENCEPIECE.commit})`)
107
+ }
108
+
109
+ await runFile(
110
+ "cmake",
111
+ ["-S", source, "-B", build, "-DCMAKE_BUILD_TYPE=Release", "-DSPM_ENABLE_SHARED=OFF", "-DSPM_ENABLE_TCMALLOC=OFF"],
112
+ { maxBuffer: OUTPUT_LIMIT }
113
+ )
114
+
115
+ await runFile("cmake", ["--build", build, "-j", "4", "--target", "spm_train"], { maxBuffer: OUTPUT_LIMIT })
116
+
117
+ return binary
118
+ }