@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,80 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Train the first-generation tokenizer recipe on a text file of raw addresses, one per line.
7
+ *
8
+ * The recipe is fixed: a 16,000-piece unigram vocabulary, 0.9995 character coverage, byte fallback, the four special
9
+ * ids, and no user-defined symbols. It writes `tokenizer.model`, `tokenizer.vocab` and `META.json` under `--output`.
10
+ * `--version` must match the corpus version the tokenizer ships with.
11
+ *
12
+ * Usage: `node packages/mtf/tools/tokenizer/train/text.run.ts --input <txt> --output <dir> --version <v>
13
+ * [--spm-train <path>]`
14
+ */
15
+
16
+ import { readLocalTextFile } from "@mailwoman/core/fs/readers"
17
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
18
+ import { makeDirectories, writeLocalJSONFile } from "@mailwoman/core/fs/writers"
19
+ import { gitHead } from "@mailwoman/core/git"
20
+ import { sha256File } from "@mailwoman/core/hash"
21
+ import { prettyJSON } from "@mailwoman/core/json"
22
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments"
23
+ import { resolvePath } from "path-ts"
24
+
25
+ import { spmTrainBinary } from "../binary.ts"
26
+ import { trainSentencePiece } from "../sentencepiece.ts"
27
+
28
+ const RECIPE = {
29
+ vocab_size: 16_000,
30
+ character_coverage: 0.9995,
31
+ model_type: "unigram",
32
+ byte_fallback: true,
33
+ } as const
34
+
35
+ const { values } = parseArguments({
36
+ options: {
37
+ input: { type: "string" },
38
+ output: { type: "string" },
39
+ version: { type: "string" },
40
+ "spm-train": { type: "string" },
41
+ },
42
+ })
43
+
44
+ const input = resolvePath(requiredArgument("train-text", "input", values.input))
45
+ const output = resolvePath(requiredArgument("train-text", "output", values.output))
46
+ const version = requiredArgument("train-text", "version", values.version)
47
+
48
+ await makeDirectories(output)
49
+ await using scratch = await temporaryDirectory("mtf-train-text-")
50
+
51
+ const trained = await trainSentencePiece(
52
+ {
53
+ input,
54
+ model_prefix: `${output}/tokenizer`,
55
+ ...RECIPE,
56
+ pad_id: 0,
57
+ unk_id: 1,
58
+ bos_id: 2,
59
+ eos_id: 3,
60
+ user_defined_symbols: [],
61
+ },
62
+ { spmTrain: await spmTrainBinary(values["spm-train"]), workDirectory: scratch.path.toString() }
63
+ )
64
+
65
+ const text = await readLocalTextFile(input)
66
+
67
+ const meta = {
68
+ tokenizer_version: version,
69
+ ...RECIPE,
70
+ // Every line break ends a line, and a final line without one still counts.
71
+ training_lines: (text.match(/\n/g)?.length ?? 0) + (text && !text.endsWith("\n") ? 1 : 0),
72
+ git_commit: await gitHead().catch(() => null),
73
+ model_sha256: await sha256File(trained.model),
74
+ model_path: trained.model,
75
+ vocab_path: trained.vocab,
76
+ }
77
+
78
+ await writeLocalJSONFile(meta, `${output}/META.json`)
79
+
80
+ console.log(prettyJSON(meta, false, 2))
@@ -0,0 +1,151 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Train a versioned SentencePiece tokenizer from a corpus's train split.
7
+ *
8
+ * The tool writes `tokenizer.model`, `tokenizer.vocab`, `model_card.json` and `META.json` under `--output`. The card
9
+ * records the byte-fallback rate on `--eval-fixture`, so a tokenizer's coverage is a measured number. The training
10
+ * runs native `spm_train` from SentencePiece v0.2.2 and writes the model the Python wheel writes for the same call.
11
+ *
12
+ * `--corpus` takes a corpus tree (the parent of `train/`), a directory holding exactly one `corpus-v*` tree, or a
13
+ * version (`v0.3.0` or `0.3.0`), which resolves to `corpus/versioned/vX/corpus-vX` under the data root.
14
+ *
15
+ * Usage:
16
+ *
17
+ * node packages/mtf/tools/tokenizer/train.run.ts --corpus v0.3.0 --output <dir> [--vocab 48000]
18
+ * [--character-coverage 0.9999] [--model-type unigram] [--no-byte-fallback] [--split-digits]
19
+ * [--countries US,FR] [--per-country-sample 500000] [--mine-postcode-literals 0]
20
+ * [--user-defined-symbols-file <txt>] [--no-default-user-defined-symbols] [--eval-fixture <jsonl>]
21
+ * [--seed 42] [--corpus-version <v>] [--flag name=value ...] [--spm-train <path>]
22
+ */
23
+
24
+ import { dataRootPath } from "@mailwoman/core/data-root"
25
+ import { isDirectory } from "@mailwoman/core/fs/readers/stat"
26
+ import { prettyJSON } from "@mailwoman/core/json"
27
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments"
28
+ import { resolvePath } from "path-ts"
29
+ import { Globerator } from "spliterator/node/fs"
30
+
31
+ import { spmTrainBinary } from "./binary.ts"
32
+ import type { TrainerFlagValue } from "./sentencepiece.ts"
33
+ import { DEFAULT_USER_DEFINED_SYMBOLS, readUserDefinedSymbolsFile } from "./symbols.ts"
34
+ import { TOKENIZER_TRAINING_DEFAULTS, trainTokenizer } from "./train.ts"
35
+
36
+ const { values } = parseArguments({
37
+ options: {
38
+ corpus: { type: "string" },
39
+ "corpus-version": { type: "string" },
40
+ output: { type: "string" },
41
+ vocab: { type: "string", default: String(TOKENIZER_TRAINING_DEFAULTS.vocabSize) },
42
+ "character-coverage": { type: "string", default: String(TOKENIZER_TRAINING_DEFAULTS.characterCoverage) },
43
+ "model-type": { type: "string", default: TOKENIZER_TRAINING_DEFAULTS.modelType },
44
+ "no-byte-fallback": { type: "boolean", default: false },
45
+ "split-digits": { type: "boolean", default: false },
46
+ countries: { type: "string", default: TOKENIZER_TRAINING_DEFAULTS.countries.join(",") },
47
+ "per-country-sample": { type: "string", default: String(TOKENIZER_TRAINING_DEFAULTS.perCountrySample) },
48
+ "mine-postcode-literals": { type: "string", default: "0" },
49
+ "user-defined-symbols-file": { type: "string" },
50
+ "no-default-user-defined-symbols": { type: "boolean", default: false },
51
+ "eval-fixture": { type: "string" },
52
+ seed: { type: "string", default: String(TOKENIZER_TRAINING_DEFAULTS.seed) },
53
+ flag: { type: "string", multiple: true, default: [] },
54
+ "spm-train": { type: "string" },
55
+ },
56
+ })
57
+
58
+ const MODEL_TYPES = new Set(["unigram", "bpe", "char", "word"])
59
+
60
+ function integer(name: string, value: string): number {
61
+ const parsed = Number(value)
62
+
63
+ if (!Number.isInteger(parsed)) throw new Error(`--${name} is not an integer: ${value}`)
64
+
65
+ return parsed
66
+ }
67
+
68
+ /**
69
+ * The corpus tree a `--corpus` value names.
70
+ */
71
+ async function resolveCorpusDirectory(spec: string): Promise<string> {
72
+ const path = resolvePath(spec)
73
+
74
+ if (await isDirectory(`${path}/train`)) return path
75
+
76
+ if (await isDirectory(path)) {
77
+ const candidates = await Globerator.from("corpus-v*", { cwd: path, absolute: false }).toSorted()
78
+
79
+ if (candidates.length === 1 && (await isDirectory(`${path}/${candidates[0]}/train`))) {
80
+ return `${path}/${candidates[0]}`
81
+ }
82
+ }
83
+
84
+ const version = spec.replace(/^v+/, "")
85
+ const candidate = dataRootPath("corpus", "versioned", `v${version}`, `corpus-v${version}`).toString()
86
+
87
+ if (await isDirectory(`${candidate}/train`)) return candidate
88
+
89
+ throw new Error(`could not resolve --corpus=${spec}; tried ${candidate}/train and the direct path forms`)
90
+ }
91
+
92
+ /**
93
+ * `v0.3.0` from a `.../v0.3.0/corpus-v0.3.0` path, or the directory name.
94
+ */
95
+ function inferCorpusVersion(corpusDirectory: string): string {
96
+ const name = corpusDirectory.split("/").at(-1)!
97
+
98
+ return name.startsWith("corpus-") ? name.slice("corpus-".length) : name
99
+ }
100
+
101
+ /**
102
+ * A `--flag name=value` trainer argument: `true` and `false` as booleans,
103
+ * a number as a number, else the text.
104
+ */
105
+ function extraFlag(spec: string): [string, TrainerFlagValue] {
106
+ const at = spec.indexOf("=")
107
+
108
+ if (at <= 0) throw new Error(`--flag ${spec} is not name=value`)
109
+ const name = spec.slice(0, at)
110
+ const text = spec.slice(at + 1)
111
+
112
+ if (text === "true" || text === "false") return [name, text === "true"]
113
+
114
+ return [name, text !== "" && Number.isFinite(Number(text)) ? Number(text) : text]
115
+ }
116
+
117
+ const modelType = values["model-type"]
118
+
119
+ if (!MODEL_TYPES.has(modelType)) throw new Error(`--model-type must be one of ${[...MODEL_TYPES].join(", ")}`)
120
+
121
+ const corpusDirectory = await resolveCorpusDirectory(requiredArgument("train", "corpus", values.corpus))
122
+ const symbols: string[] = values["no-default-user-defined-symbols"] ? [] : [...DEFAULT_USER_DEFINED_SYMBOLS]
123
+
124
+ if (values["user-defined-symbols-file"]) {
125
+ symbols.push(...(await readUserDefinedSymbolsFile(values["user-defined-symbols-file"])))
126
+ }
127
+
128
+ const card = await trainTokenizer({
129
+ corpusDirectory,
130
+ outputDirectory: resolvePath(requiredArgument("train", "output", values.output)),
131
+ corpusVersion: values["corpus-version"] ?? inferCorpusVersion(corpusDirectory),
132
+ vocabSize: integer("vocab", values.vocab),
133
+ characterCoverage: Number(values["character-coverage"]),
134
+ modelType,
135
+ byteFallback: !values["no-byte-fallback"],
136
+ splitDigits: values["split-digits"],
137
+ allowWhitespaceOnlyPieces: false,
138
+ perCountrySample: integer("per-country-sample", values["per-country-sample"]),
139
+ countries: values.countries
140
+ .split(",")
141
+ .map((code) => code.trim())
142
+ .filter((code) => code.length > 0),
143
+ minePostcodeLiterals: integer("mine-postcode-literals", values["mine-postcode-literals"]),
144
+ userDefinedSymbols: symbols,
145
+ evalFixture: values["eval-fixture"] ?? null,
146
+ seed: integer("seed", values.seed),
147
+ extraFlags: Object.fromEntries(values.flag.map(extraFlag)),
148
+ spmTrain: await spmTrainBinary(values["spm-train"]),
149
+ })
150
+
151
+ console.log(prettyJSON(card, false, 2))
@@ -0,0 +1,266 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Train a versioned SentencePiece tokenizer from a corpus's train split, and write its model card.
7
+ *
8
+ * The training lines are a balanced sample: a reservoir of `perCountrySample` raws per country, drawn with CPython's
9
+ * generator in the order `tokenizer/train.py` drew, then shuffled. The card records what reproduces the model: the
10
+ * corpus files read and their order, the SHA-256 of the training input and of the symbol list, the SentencePiece
11
+ * release, every flag, and the model's SHA-256.
12
+ */
13
+
14
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
15
+ import { makeDirectories, writeLocalJSONFile } from "@mailwoman/core/fs/writers"
16
+ import { gitHead } from "@mailwoman/core/git"
17
+ import { sha256File, sha256Hex } from "@mailwoman/core/hash"
18
+ import { isoSeconds } from "@mailwoman/core/utils"
19
+
20
+ import { runMTFTokenizer, SENTENCEPIECE } from "./binary.ts"
21
+ import { type ByteFallbackReport, measureByteFallback, readFixtureLines } from "./byte-fallback.ts"
22
+ import { readModelPieces } from "./model.ts"
23
+ import { type TrainerFlags, type TrainerFlagValue, trainSentencePiece } from "./sentencepiece.ts"
24
+ import { dedupeKeepOrder, sentencePieceSymbol } from "./symbols.ts"
25
+
26
+ export interface TokenizerTrainingConfig {
27
+ corpusDirectory: string
28
+ outputDirectory: string
29
+ corpusVersion: string
30
+ vocabSize: number
31
+ characterCoverage: number
32
+ modelType: string
33
+ byteFallback: boolean
34
+ splitDigits: boolean
35
+ allowWhitespaceOnlyPieces: boolean
36
+ perCountrySample: number
37
+ countries: readonly string[]
38
+ minePostcodeLiterals: number
39
+ userDefinedSymbols: readonly string[]
40
+ evalFixture: string | null
41
+ seed: number
42
+ /**
43
+ * Further trainer arguments, appended after the standard ones in this order.
44
+ */
45
+ extraFlags: Readonly<Record<string, TrainerFlagValue>>
46
+ /**
47
+ * The `spm_train` binary.
48
+ */
49
+ spmTrain: string
50
+ }
51
+
52
+ /**
53
+ * The defaults the Python tokenizer trainer used.
54
+ */
55
+ export const TOKENIZER_TRAINING_DEFAULTS = {
56
+ vocabSize: 48_000,
57
+ characterCoverage: 0.9999,
58
+ modelType: "unigram",
59
+ byteFallback: true,
60
+ splitDigits: false,
61
+ allowWhitespaceOnlyPieces: false,
62
+ perCountrySample: 500_000,
63
+ countries: ["US", "FR"],
64
+ minePostcodeLiterals: 0,
65
+ seed: 42,
66
+ } as const
67
+
68
+ /**
69
+ * The symbols to keep whole, as written and as passed to SentencePiece: the configured list,
70
+ * then any mined postcode literals, first occurrences only, truncated to a quarter of the vocabulary.
71
+ */
72
+ export async function resolveUserDefinedSymbols(
73
+ config: Pick<
74
+ TokenizerTrainingConfig,
75
+ "userDefinedSymbols" | "minePostcodeLiterals" | "corpusDirectory" | "countries" | "vocabSize"
76
+ >
77
+ ): Promise<{ symbols: string[]; passed: string[] }> {
78
+ const listed = [...config.userDefinedSymbols]
79
+
80
+ if (config.minePostcodeLiterals > 0) {
81
+ listed.push(
82
+ ...(await runMTFTokenizer<string[]>([
83
+ "mine-postcodes",
84
+ "--corpus",
85
+ config.corpusDirectory,
86
+ "--top-k",
87
+ String(config.minePostcodeLiterals),
88
+ "--countries",
89
+ config.countries.join(","),
90
+ ]))
91
+ )
92
+ }
93
+
94
+ let symbols = dedupeKeepOrder(listed)
95
+ const cap = Math.max(0, Math.floor(config.vocabSize / 4))
96
+
97
+ if (symbols.length > cap) {
98
+ console.warn(`user_defined_symbols (${symbols.length}) exceeds the vocab_size/4 cap (${cap}); truncating`)
99
+
100
+ symbols = symbols.slice(0, cap)
101
+ }
102
+
103
+ return { symbols, passed: symbols.map(sentencePieceSymbol) }
104
+ }
105
+
106
+ /**
107
+ * The trainer flags of a configuration, in the order the Python trainer passed them.
108
+ */
109
+ export function trainerFlags(
110
+ config: TokenizerTrainingConfig,
111
+ input: string,
112
+ modelPrefix: string,
113
+ symbols: readonly string[]
114
+ ): TrainerFlags {
115
+ return {
116
+ input,
117
+ model_prefix: modelPrefix,
118
+ vocab_size: config.vocabSize,
119
+ character_coverage: config.characterCoverage,
120
+ model_type: config.modelType,
121
+ byte_fallback: config.byteFallback,
122
+ split_digits: config.splitDigits,
123
+ allow_whitespace_only_pieces: config.allowWhitespaceOnlyPieces,
124
+ pad_id: 0,
125
+ unk_id: 1,
126
+ bos_id: 2,
127
+ eos_id: 3,
128
+ user_defined_symbols: symbols,
129
+ ...config.extraFlags,
130
+ }
131
+ }
132
+
133
+ /**
134
+ * A train file read, in read order, and the SHA-256 its corpus manifest records, when it records one.
135
+ */
136
+ interface CorpusFileRecord {
137
+ path: string
138
+ sha256: string | null
139
+ }
140
+
141
+ /**
142
+ * The card `trainTokenizer` writes as `model_card.json` and `META.json`.
143
+ */
144
+ export interface TokenizerModelCard {
145
+ tokenizer_version: string
146
+ corpus_version: string
147
+ vocab_size: number
148
+ training_lines: number
149
+ training_duration_seconds: number
150
+ generated_at: string
151
+ git_commit: string | null
152
+ model_sha256: string
153
+ model_path: string
154
+ vocab_path: string
155
+ sentencepiece: typeof SENTENCEPIECE & { trainer: "spm_train" }
156
+ sentencepiece_flags: Record<string, unknown>
157
+ training_input: {
158
+ sha256: string
159
+ lines: number
160
+ corpus_files: CorpusFileRecord[]
161
+ user_defined_symbols_sha256: string
162
+ }
163
+ sampling: { countries: string[]; per_country: number; seed: number; per_country_lines: Record<string, number> }
164
+ byte_fallback_eval: ByteFallbackReport | null
165
+ }
166
+
167
+ function directoryName(path: string): string {
168
+ return path.replace(/\/+$/, "").split("/").at(-1)!
169
+ }
170
+
171
+ /**
172
+ * Sample, train and write `tokenizer.model`, `tokenizer.vocab`, `model_card.json`
173
+ * and `META.json` under the output directory.
174
+ */
175
+ export async function trainTokenizer(config: TokenizerTrainingConfig): Promise<TokenizerModelCard> {
176
+ const started = performance.now()
177
+
178
+ await makeDirectories(config.outputDirectory)
179
+ const modelPrefix = `${config.outputDirectory}/tokenizer`
180
+
181
+ await using scratch = await temporaryDirectory("mtf-train-")
182
+ const input = scratch.path("input.txt").toString()
183
+ const corpusFiles = await runMTFTokenizer<CorpusFileRecord[]>(["train-files", "--corpus", config.corpusDirectory])
184
+
185
+ const sampled = await runMTFTokenizer<{ lines: number; per_country: [string, number][] }>([
186
+ "sample-raws",
187
+ "--corpus",
188
+ config.corpusDirectory,
189
+ "--countries",
190
+ config.countries.join(","),
191
+ "--per-country",
192
+ String(config.perCountrySample),
193
+ "--seed",
194
+ String(config.seed),
195
+ "--out",
196
+ input,
197
+ ])
198
+
199
+ for (const [country, lines] of sampled.per_country) {
200
+ console.info(`sampled ${lines} lines for country=${country}`)
201
+ }
202
+
203
+ if (sampled.lines === 0) {
204
+ throw new Error(`sampled zero lines from ${config.corpusDirectory} for countries ${config.countries.join(",")}`)
205
+ }
206
+
207
+ const { symbols, passed } = await resolveUserDefinedSymbols(config)
208
+ const flags = trainerFlags(config, input, modelPrefix, passed)
209
+ const inputSHA256 = await sha256File(input)
210
+
211
+ console.info(
212
+ `training sentencepiece: vocab=${config.vocabSize}, type=${config.modelType}, char_cov=${config.characterCoverage}, ` +
213
+ `byte_fb=${config.byteFallback}, lines=${sampled.lines}, uds=${symbols.length}`
214
+ )
215
+
216
+ const trained = await trainSentencePiece(flags, { spmTrain: config.spmTrain, workDirectory: scratch.path.toString() })
217
+ const elapsed = (performance.now() - started) / 1000
218
+
219
+ const byteFallback = config.evalFixture
220
+ ? await measureByteFallback(trained.model, await readFixtureLines(config.evalFixture))
221
+ : null
222
+
223
+ const portableFlags: Record<string, unknown> = Object.fromEntries(
224
+ Object.entries(flags).filter(([name]) => name !== "input" && name !== "user_defined_symbols")
225
+ )
226
+
227
+ portableFlags["user_defined_symbols_count"] = symbols.length
228
+ portableFlags["user_defined_symbols_preview"] = symbols.slice(0, 64)
229
+
230
+ const card: TokenizerModelCard = {
231
+ tokenizer_version: directoryName(config.outputDirectory),
232
+ corpus_version: config.corpusVersion,
233
+ vocab_size: (await readModelPieces(trained.model)).length,
234
+ training_lines: sampled.lines,
235
+ training_duration_seconds: Math.round(elapsed * 1000) / 1000,
236
+ generated_at: isoSeconds(),
237
+ git_commit: await gitHead().catch(() => null),
238
+ model_sha256: await sha256File(trained.model),
239
+ model_path: trained.model,
240
+ vocab_path: trained.vocab,
241
+ sentencepiece: { ...SENTENCEPIECE, trainer: "spm_train" },
242
+ sentencepiece_flags: portableFlags,
243
+ training_input: {
244
+ sha256: inputSHA256,
245
+ lines: sampled.lines,
246
+ corpus_files: corpusFiles,
247
+ user_defined_symbols_sha256: sha256Hex(passed.map((symbol) => `${symbol}\n`).join("")),
248
+ },
249
+ sampling: {
250
+ countries: [...config.countries],
251
+ per_country: config.perCountrySample,
252
+ seed: config.seed,
253
+ per_country_lines: Object.fromEntries(sampled.per_country),
254
+ },
255
+ byte_fallback_eval: byteFallback,
256
+ }
257
+
258
+ await writeLocalJSONFile(card, `${config.outputDirectory}/model_card.json`)
259
+ await writeLocalJSONFile(card, `${config.outputDirectory}/META.json`)
260
+
261
+ console.info(
262
+ `wrote ${trained.model} (vocab=${card.vocab_size}, byte_fb_overall=${byteFallback ? byteFallback.overall.rate.toFixed(4) : "n/a"})`
263
+ )
264
+
265
+ return card
266
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Count each tokenizer piece's occurrences in the corpus train split that `prune.run.ts` reads.
7
+ *
8
+ * The manifest's train paths are listed as built, so a path under the training volume (`/data/...`) is rewritten
9
+ * onto this host by `--data-root-remap <from>:<to>`, which defaults to `/data` onto the data root. Every file must
10
+ * exist after the rewrite. The tool writes `{counts, ...}` to `--out`, with the run's sidecar fields beside the
11
+ * counts.
12
+ *
13
+ * Usage: `node packages/mtf/tools/tokenizer/utilization.run.ts --manifest <MANIFEST.json> --tokenizer <model>
14
+ * --out <json> [--workers <n>] [--data-root-remap <from>:<to>]`
15
+ */
16
+
17
+ import { dataRootPath } from "@mailwoman/core/data-root"
18
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
19
+ import { isFile } from "@mailwoman/core/fs/readers/stat"
20
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
21
+ import { writeLocalJSONFile } from "@mailwoman/core/fs/writers"
22
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments"
23
+ import { availableParallelism } from "@mailwoman/core/utils/system"
24
+ import { resolvePath } from "path-ts"
25
+
26
+ import { runMTFTokenizer } from "./binary.ts"
27
+
28
+ const { values } = parseArguments({
29
+ options: {
30
+ manifest: { type: "string" },
31
+ tokenizer: { type: "string" },
32
+ out: { type: "string" },
33
+ workers: { type: "string", default: String(Math.max(2, availableParallelism() - 2)) },
34
+ "data-root-remap": { type: "string" },
35
+ },
36
+ })
37
+
38
+ const manifestPath = resolvePath(requiredArgument("utilization", "manifest", values.manifest))
39
+ const tokenizer = resolvePath(requiredArgument("utilization", "tokenizer", values.tokenizer))
40
+ const out = resolvePath(requiredArgument("utilization", "out", values.out))
41
+ const remap = values["data-root-remap"] ?? `/data:${dataRootPath()}`
42
+ const at = remap.indexOf(":")
43
+ const [from, to] = [remap.slice(0, at), remap.slice(at + 1)]
44
+ const listed = await runMTFTokenizer<string[]>(["manifest-train-files", "--manifest", manifestPath])
45
+ const files = listed.map((path) => (path.startsWith(from) ? to + path.slice(from.length) : path))
46
+ const missing: string[] = []
47
+
48
+ for (const file of files)
49
+ if (!(await isFile(file))) {
50
+ missing.push(file)
51
+ }
52
+
53
+ if (missing.length) throw new Error(`${missing.length} parquet paths missing locally, first: ${missing[0]}`)
54
+
55
+ const manifest = await readLocalJSONFile<{ corpus_version?: string; total_rows?: number }>(manifestPath)
56
+
57
+ console.info(`[utilization] ${files.length} train files, ${manifest.total_rows ?? "?"} rows, workers ${values.workers}`)
58
+
59
+ const started = performance.now()
60
+
61
+ await using scratch = await temporaryDirectory("mtf-utilization-")
62
+ const filesPath = scratch.path("files.json").toString()
63
+ const countsPath = scratch.path("counts.json").toString()
64
+
65
+ await writeLocalJSONFile(files, filesPath)
66
+
67
+ const { vocab_size: vocabSize, fired } = await runMTFTokenizer<{ vocab_size: number; fired: number }>([
68
+ "count-pieces",
69
+ "--model",
70
+ tokenizer,
71
+ "--files",
72
+ filesPath,
73
+ "--threads",
74
+ values.workers,
75
+ "--out",
76
+ countsPath,
77
+ ])
78
+
79
+ const { counts } = await readLocalJSONFile<{ counts: number[] }>(countsPath)
80
+
81
+ await writeLocalJSONFile(
82
+ {
83
+ manifest: manifestPath,
84
+ corpus_version: manifest.corpus_version ?? null,
85
+ tokenizer,
86
+ vocab_size: vocabSize,
87
+ train_files: files.length,
88
+ total_rows: manifest.total_rows ?? null,
89
+ fired,
90
+ elapsed_s: Math.round((performance.now() - started) / 100) / 10,
91
+ counts,
92
+ },
93
+ out
94
+ )
95
+
96
+ console.info(`[utilization] wrote ${out}; fired ${fired}/${vocabSize} (${((100 * fired) / vocabSize).toFixed(2)}%)`)
@@ -0,0 +1,77 @@
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
+
22
+ import { dataRootPath } from "@mailwoman/core/data-root"
23
+ import { prettyJSON } from "@mailwoman/core/json"
24
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments"
25
+ import { resolvePath } from "path-ts"
26
+
27
+ import { measureByteFallback, readFixtureLines } from "./byte-fallback.ts"
28
+ import { verifyPrune } from "./verify.ts"
29
+
30
+ const { values, positionals } = parseArguments({
31
+ allowPositionals: true,
32
+ options: {
33
+ tokenizer: { type: "string" },
34
+ fixture: { type: "string" },
35
+ "orig-tokenizer": { type: "string" },
36
+ "orig-onnx": { type: "string" },
37
+ "pruned-dir": { type: "string" },
38
+ manifest: { type: "string" },
39
+ "eval-texts": { type: "string" },
40
+ "sample-rows": { type: "string", default: "1000000" },
41
+ "logit-inputs": { type: "string", default: "256" },
42
+ seed: { type: "string", default: "42" },
43
+ "data-root-remap": { type: "string" },
44
+ },
45
+ })
46
+
47
+ const command = positionals[0]
48
+
49
+ if (command === "byte-fallback") {
50
+ const tokenizer = resolvePath(requiredArgument(command, "tokenizer", values.tokenizer))
51
+ const fixture = resolvePath(requiredArgument(command, "fixture", values.fixture))
52
+
53
+ console.log(prettyJSON(await measureByteFallback(tokenizer, await readFixtureLines(fixture)), false, 2))
54
+ } else if (command === "prune") {
55
+ const remap = values["data-root-remap"] ?? `/data:${dataRootPath()}`
56
+ const at = remap.indexOf(":")
57
+
58
+ const report = await verifyPrune({
59
+ originalTokenizer: resolvePath(requiredArgument(command, "orig-tokenizer", values["orig-tokenizer"])),
60
+ originalONNX: resolvePath(requiredArgument(command, "orig-onnx", values["orig-onnx"])),
61
+ prunedDirectory: resolvePath(requiredArgument(command, "pruned-dir", values["pruned-dir"])),
62
+ manifest: resolvePath(requiredArgument(command, "manifest", values.manifest)),
63
+ evalTexts: resolvePath(requiredArgument(command, "eval-texts", values["eval-texts"])),
64
+ sampleRows: Number(values["sample-rows"]),
65
+ logitInputs: Number(values["logit-inputs"]),
66
+ seed: Number(values.seed),
67
+ remap: [remap.slice(0, at), remap.slice(at + 1)],
68
+ })
69
+
70
+ if (report.verdict !== "PASS") {
71
+ process.exitCode = 1
72
+ }
73
+ } else {
74
+ console.error("usage: verify.run.ts byte-fallback|prune [options]")
75
+
76
+ process.exitCode = 2
77
+ }