@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.
- package/README.md +37 -7
- package/crates/mtf-channels/tests/fixtures/README.md +13 -0
- package/crates/mtf-sampler/tests/fixtures/README.md +120 -0
- package/lib/code-units.ts +45 -0
- package/lib/index.ts +6 -2
- package/out/code-units.d.ts +24 -0
- package/out/code-units.d.ts.map +1 -0
- package/out/code-units.js +36 -0
- package/out/code-units.js.map +1 -0
- package/out/index.d.ts +4 -2
- package/out/index.d.ts.map +1 -1
- package/out/index.js +6 -2
- package/out/index.js.map +1 -1
- package/out/tools/build-wasm.run.js +2 -2
- package/out/tools/build-wasm.run.js.map +1 -1
- package/out/tools/sampler/native.d.ts +314 -0
- package/out/tools/sampler/native.d.ts.map +1 -0
- package/out/tools/sampler/native.js +114 -0
- package/out/tools/sampler/native.js.map +1 -0
- package/out/tools/tokenizer/binary.d.ts +38 -0
- package/out/tools/tokenizer/binary.d.ts.map +1 -0
- package/out/tools/tokenizer/binary.js +94 -0
- package/out/tools/tokenizer/binary.js.map +1 -0
- package/out/tools/tokenizer/byte-fallback.d.ts +39 -0
- package/out/tools/tokenizer/byte-fallback.d.ts.map +1 -0
- package/out/tools/tokenizer/byte-fallback.js +49 -0
- package/out/tools/tokenizer/byte-fallback.js.map +1 -0
- package/out/tools/tokenizer/model.d.ts +70 -0
- package/out/tools/tokenizer/model.d.ts.map +1 -0
- package/out/tools/tokenizer/model.js +56 -0
- package/out/tools/tokenizer/model.js.map +1 -0
- package/out/tools/tokenizer/prune.d.ts +69 -0
- package/out/tools/tokenizer/prune.d.ts.map +1 -0
- package/out/tools/tokenizer/prune.js +126 -0
- package/out/tools/tokenizer/prune.js.map +1 -0
- package/out/tools/tokenizer/prune.run.d.ts +16 -0
- package/out/tools/tokenizer/prune.run.d.ts.map +1 -0
- package/out/tools/tokenizer/prune.run.js +34 -0
- package/out/tools/tokenizer/prune.run.js.map +1 -0
- package/out/tools/tokenizer/sentencepiece.d.ts +63 -0
- package/out/tools/tokenizer/sentencepiece.d.ts.map +1 -0
- package/out/tools/tokenizer/sentencepiece.js +90 -0
- package/out/tools/tokenizer/sentencepiece.js.map +1 -0
- package/out/tools/tokenizer/splice.d.ts +117 -0
- package/out/tools/tokenizer/splice.d.ts.map +1 -0
- package/out/tools/tokenizer/splice.js +398 -0
- package/out/tools/tokenizer/splice.js.map +1 -0
- package/out/tools/tokenizer/splice.run.d.ts +29 -0
- package/out/tools/tokenizer/splice.run.d.ts.map +1 -0
- package/out/tools/tokenizer/splice.run.js +114 -0
- package/out/tools/tokenizer/splice.run.js.map +1 -0
- package/out/tools/tokenizer/symbols.d.ts +42 -0
- package/out/tools/tokenizer/symbols.d.ts.map +1 -0
- package/out/tools/tokenizer/symbols.js +113 -0
- package/out/tools/tokenizer/symbols.js.map +1 -0
- package/out/tools/tokenizer/train/text.run.d.ts +16 -0
- package/out/tools/tokenizer/train/text.run.d.ts.map +1 -0
- package/out/tools/tokenizer/train/text.run.js +67 -0
- package/out/tools/tokenizer/train/text.run.js.map +1 -0
- package/out/tools/tokenizer/train.d.ts +113 -0
- package/out/tools/tokenizer/train.d.ts.map +1 -0
- package/out/tools/tokenizer/train.js +162 -0
- package/out/tools/tokenizer/train.js.map +1 -0
- package/out/tools/tokenizer/train.run.d.ts +24 -0
- package/out/tools/tokenizer/train.run.d.ts.map +1 -0
- package/out/tools/tokenizer/train.run.js +131 -0
- package/out/tools/tokenizer/train.run.js.map +1 -0
- package/out/tools/tokenizer/utilization.run.d.ts +17 -0
- package/out/tools/tokenizer/utilization.run.d.ts.map +1 -0
- package/out/tools/tokenizer/utilization.run.js +80 -0
- package/out/tools/tokenizer/utilization.run.js.map +1 -0
- package/out/tools/tokenizer/verify.d.ts +94 -0
- package/out/tools/tokenizer/verify.d.ts.map +1 -0
- package/out/tools/tokenizer/verify.js +193 -0
- package/out/tools/tokenizer/verify.js.map +1 -0
- package/out/tools/tokenizer/verify.run.d.ts +22 -0
- package/out/tools/tokenizer/verify.run.d.ts.map +1 -0
- package/out/tools/tokenizer/verify.run.js +71 -0
- package/out/tools/tokenizer/verify.run.js.map +1 -0
- package/package.json +15 -3
- package/tools/build-wasm.run.ts +2 -2
- package/tools/sampler/native.ts +433 -0
- package/tools/tokenizer/binary.ts +118 -0
- package/tools/tokenizer/byte-fallback.ts +80 -0
- package/tools/tokenizer/model.ts +110 -0
- package/tools/tokenizer/prune.run.ts +37 -0
- package/tools/tokenizer/prune.ts +195 -0
- package/tools/tokenizer/sentencepiece.ts +142 -0
- package/tools/tokenizer/splice.run.ts +141 -0
- package/tools/tokenizer/splice.ts +592 -0
- package/tools/tokenizer/symbols.ts +119 -0
- package/tools/tokenizer/train/text.run.ts +80 -0
- package/tools/tokenizer/train.run.ts +151 -0
- package/tools/tokenizer/train.ts +266 -0
- package/tools/tokenizer/utilization.run.ts +96 -0
- package/tools/tokenizer/verify.run.ts +77 -0
- package/tools/tokenizer/verify.ts +313 -0
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Splice the diacritic pieces of a locale tokenizer into a frozen unigram vocabulary, and grow an exported model's
|
|
7
|
+
* embedding table to match.
|
|
8
|
+
*
|
|
9
|
+
* An appended piece contains a code point outside ASCII, so it cannot match any span of an ASCII string, and ASCII
|
|
10
|
+
* text tokenizes exactly as before. `verifySourceIdentical` checks that on a probe rather than assuming it. A
|
|
11
|
+
* trained locale that shares a code point with the new pieces can re-tokenize. `checkCodepointOverlap`
|
|
12
|
+
* reports and refuses unless the locale is accepted. The method does not scale to CJK.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readFileRange, readLocalBuffer, readLocalJSONFile, readLocalTextFile } from "@mailwoman/core/fs/readers"
|
|
16
|
+
import { isDirectory, isFile } from "@mailwoman/core/fs/readers/stat"
|
|
17
|
+
import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
|
|
18
|
+
import { makeDirectories, writeLocalBuffer, writeLocalJSONFile, writeLocalTextFile } from "@mailwoman/core/fs/writers"
|
|
19
|
+
import { prettyJSON, stringifyJSON } from "@mailwoman/core/json"
|
|
20
|
+
import { codePointLength } from "@mailwoman/core/strings/code-points"
|
|
21
|
+
import { splitLines } from "@mailwoman/core/strings/unicode"
|
|
22
|
+
import { CSVSpliterator } from "spliterator"
|
|
23
|
+
import { Globerator } from "spliterator/node/fs"
|
|
24
|
+
|
|
25
|
+
import { runMTFTokenizer } from "./binary.ts"
|
|
26
|
+
import { editModel, loadEncoder, PieceType, readModelPieces, type VocabularyPiece } from "./model.ts"
|
|
27
|
+
import { trainSentencePiece } from "./sentencepiece.ts"
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The corpus sample size and the seed of its shuffle.
|
|
31
|
+
*/
|
|
32
|
+
const CORPUS_SAMPLE = 350_000
|
|
33
|
+
const CORPUS_SEED = 42
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* ASCII address lines, the default probe of the English-identity check.
|
|
37
|
+
*/
|
|
38
|
+
export const ENGLISH_PROBE: readonly string[] = [
|
|
39
|
+
"109 Seminary Dr, Mill Valley, CA 94941",
|
|
40
|
+
"5210 South Ingleside Avenue, Chicago, IL 60615",
|
|
41
|
+
"1600 Pennsylvania Ave NW, Washington, DC 20500",
|
|
42
|
+
"350 Fifth Avenue, New York, NY 10118",
|
|
43
|
+
"1 Infinite Loop, Cupertino, CA 95014",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The piece text without SentencePiece's word-boundary marker.
|
|
48
|
+
*/
|
|
49
|
+
function core(piece: string): string {
|
|
50
|
+
return piece.replaceAll("▁", "")
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The first code point outside ASCII.
|
|
55
|
+
*/
|
|
56
|
+
const NON_ASCII = 0x80
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Corpus lines this long or longer, in code points, are left out: they are run-on records rather than names.
|
|
60
|
+
*/
|
|
61
|
+
const MAX_LINE_CODE_POINTS = 80
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The int8 check accepts at most one mismatched value for each configured group
|
|
65
|
+
* of values in the reconstructed row.
|
|
66
|
+
*/
|
|
67
|
+
const QUANTIZE_MISMATCH_DIVISOR = 20
|
|
68
|
+
|
|
69
|
+
function isNonASCII(c: string): boolean {
|
|
70
|
+
return c.codePointAt(0)! >= NON_ASCII
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isASCII(text: string): boolean {
|
|
74
|
+
return ![...text].some(isNonASCII)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface SlavicCorpusOptions {
|
|
78
|
+
oaRoot: string
|
|
79
|
+
locales: readonly string[]
|
|
80
|
+
outPath: string
|
|
81
|
+
/**
|
|
82
|
+
* Rows read per OpenAddresses CSV.
|
|
83
|
+
*
|
|
84
|
+
* The read admits two rows past the cap, as the Python reader did.
|
|
85
|
+
*/
|
|
86
|
+
perFileCap?: number
|
|
87
|
+
/**
|
|
88
|
+
* Extra corpus lines, such as gazetteer alias names, appended after the sample.
|
|
89
|
+
*/
|
|
90
|
+
extraText?: string | null
|
|
91
|
+
/**
|
|
92
|
+
* The repetition count for the extra lines.
|
|
93
|
+
*
|
|
94
|
+
* A list of single names needs enough unigram mass to win vocabulary slots.
|
|
95
|
+
*/
|
|
96
|
+
extraRepeat?: number
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The distinct `STREET`, `CITY` and `STREET CITY` lines of each locale's OpenAddresses CSVs,
|
|
101
|
+
* under 80 code points, shuffled and capped at 350,000, then the extra lines.
|
|
102
|
+
* Returns the number of lines written.
|
|
103
|
+
*
|
|
104
|
+
* The files of a locale are read in name order and the lines kept in first-seen order,
|
|
105
|
+
* so the corpus is the same on every run.
|
|
106
|
+
*/
|
|
107
|
+
export async function buildSlavicCorpus(options: SlavicCorpusOptions): Promise<number> {
|
|
108
|
+
const perFileCap = options.perFileCap ?? 400_000
|
|
109
|
+
const lines = new Set<string>()
|
|
110
|
+
|
|
111
|
+
for (const locale of options.locales) {
|
|
112
|
+
const directory = `${options.oaRoot}/${locale}`
|
|
113
|
+
|
|
114
|
+
if (!(await isDirectory(directory))) continue
|
|
115
|
+
const names = await Globerator.from("*.csv", { cwd: directory, absolute: false }).toSorted()
|
|
116
|
+
|
|
117
|
+
for (const name of names) {
|
|
118
|
+
try {
|
|
119
|
+
const rows = CSVSpliterator.fromAsync<Record<string, string>>(`${directory}/${name}`, {
|
|
120
|
+
normalizeKeys: false,
|
|
121
|
+
take: perFileCap + 2,
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
for await (const row of rows) {
|
|
125
|
+
const street = row["STREET"] || ""
|
|
126
|
+
const city = row["CITY"] || ""
|
|
127
|
+
|
|
128
|
+
if (street) {
|
|
129
|
+
lines.add(street)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (city) {
|
|
133
|
+
lines.add(city)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (street && city) {
|
|
137
|
+
lines.add(`${street} ${city}`)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
} catch (error) {
|
|
141
|
+
console.warn(`skipped the rest of ${directory}/${name}: ${(error as Error).message}`)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
await using scratch = await temporaryDirectory("mtf-slavic-")
|
|
147
|
+
const unshuffled = scratch.path("lines.json").toString()
|
|
148
|
+
const shuffled = scratch.path("shuffled.json").toString()
|
|
149
|
+
|
|
150
|
+
await writeLocalJSONFile(
|
|
151
|
+
[...lines].filter((line) => line && codePointLength(line) < MAX_LINE_CODE_POINTS),
|
|
152
|
+
unshuffled
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
await runMTFTokenizer(["shuffle", "--seed", String(CORPUS_SEED), "--input", unshuffled, "--out", shuffled])
|
|
156
|
+
const corpus = (await readLocalJSONFile<string[]>(shuffled)).slice(0, CORPUS_SAMPLE)
|
|
157
|
+
|
|
158
|
+
if (options.extraText && (await isFile(options.extraText))) {
|
|
159
|
+
const extra = splitLines(await readLocalTextFile(options.extraText))
|
|
160
|
+
.map((line) => line.trim())
|
|
161
|
+
.filter((line) => line && codePointLength(line) < MAX_LINE_CODE_POINTS)
|
|
162
|
+
|
|
163
|
+
for (let i = 0; i < Math.max(1, options.extraRepeat ?? 10); i++) {
|
|
164
|
+
corpus.push(...extra)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
await writeLocalTextFile(corpus.join("\n"), options.outPath)
|
|
169
|
+
|
|
170
|
+
return corpus.length
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Train the locale unigram model the splice draws its pieces from, and return its `.model` path.
|
|
175
|
+
*/
|
|
176
|
+
export async function trainDiacriticSentencePiece(
|
|
177
|
+
corpusPath: string,
|
|
178
|
+
outPrefix: string,
|
|
179
|
+
options: { spmTrain: string; vocabSize?: number }
|
|
180
|
+
): Promise<string> {
|
|
181
|
+
await using scratch = await temporaryDirectory("mtf-diacritic-")
|
|
182
|
+
|
|
183
|
+
const trained = await trainSentencePiece(
|
|
184
|
+
{
|
|
185
|
+
input: corpusPath,
|
|
186
|
+
model_prefix: outPrefix,
|
|
187
|
+
vocab_size: options.vocabSize ?? 24_000,
|
|
188
|
+
model_type: "unigram",
|
|
189
|
+
character_coverage: 1,
|
|
190
|
+
normalization_rule_name: "identity",
|
|
191
|
+
num_threads: 8,
|
|
192
|
+
},
|
|
193
|
+
{ spmTrain: options.spmTrain, workDirectory: scratch.path.toString() }
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
return trained.model
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Raise when `probe` tokenizes differently under the spliced vocabulary than under the base one.
|
|
201
|
+
*/
|
|
202
|
+
export async function verifySourceIdentical(
|
|
203
|
+
baseTokenizer: string,
|
|
204
|
+
splicedTokenizer: string,
|
|
205
|
+
probe: readonly string[] = ENGLISH_PROBE
|
|
206
|
+
): Promise<void> {
|
|
207
|
+
using base = await loadEncoder(baseTokenizer)
|
|
208
|
+
using spliced = await loadEncoder(splicedTokenizer)
|
|
209
|
+
|
|
210
|
+
const differing = probe.filter(
|
|
211
|
+
(text) => base.encode(text).pieces.join("\0") !== spliced.encode(text).pieces.join("\0")
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
if (differing.length) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`source tokenization changed on ${differing.length}/${probe.length} probe strings: a piece containing ASCII ` +
|
|
217
|
+
`was spliced in. First: ${stringifyJSON(differing[0])}`
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Append the pieces of `donor` whose core holds a code point outside ASCII and that `base`
|
|
224
|
+
* lacks, with their scores, as normal pieces, then check the English identity.
|
|
225
|
+
* Returns the appended pieces.
|
|
226
|
+
*/
|
|
227
|
+
export async function spliceVocabulary(base: string, donor: string, out: string): Promise<string[]> {
|
|
228
|
+
const basePieces = new Set((await readModelPieces(base)).map(([piece]) => piece))
|
|
229
|
+
|
|
230
|
+
const appended: VocabularyPiece[] = (await readModelPieces(donor))
|
|
231
|
+
.filter(([piece]) => {
|
|
232
|
+
const text = core(piece)
|
|
233
|
+
|
|
234
|
+
return text && !isASCII(text) && !basePieces.has(piece)
|
|
235
|
+
})
|
|
236
|
+
.map(([piece, score]) => [piece, score, PieceType.Normal] as const)
|
|
237
|
+
|
|
238
|
+
await makeDirectories(out.slice(0, out.lastIndexOf("/")) || ".")
|
|
239
|
+
await editModel(base, out, { append: appended })
|
|
240
|
+
await verifySourceIdentical(base, out)
|
|
241
|
+
|
|
242
|
+
return appended.map(([piece]) => piece)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function byCodePoint(a: string, b: string): number {
|
|
246
|
+
return a.codePointAt(0)! - b.codePointAt(0)!
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const REPLACEMENT_CHARACTER = "�"
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The code points outside ASCII in the first `capBytes` of a locale sample,
|
|
253
|
+
* read as UTF-8 with undecodable bytes ignored.
|
|
254
|
+
* A character split by the byte cap is left out.
|
|
255
|
+
*
|
|
256
|
+
* The sample is read as raw text rather than parsed, because the check needs a locale's
|
|
257
|
+
* character inventory and not its records, and any sample format then works.
|
|
258
|
+
*/
|
|
259
|
+
export async function collectSampleCodepoints(samplePath: string, capBytes = 4_000_000): Promise<Set<string>> {
|
|
260
|
+
const bytes = await readFileRange(samplePath, 0, capBytes)
|
|
261
|
+
// A streaming decode holds back an incomplete final sequence instead of replacing it.
|
|
262
|
+
const text = new TextDecoder("utf-8").decode(bytes, { stream: true })
|
|
263
|
+
const out = new Set<string>()
|
|
264
|
+
|
|
265
|
+
for (const c of text) {
|
|
266
|
+
if (isNonASCII(c)) {
|
|
267
|
+
out.add(c)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The decoder replaces an invalid byte with U+FFFD, where Python's `errors="ignore"` drops it.
|
|
272
|
+
if (!bytes.includes(Buffer.from(REPLACEMENT_CHARACTER))) {
|
|
273
|
+
out.delete(REPLACEMENT_CHARACTER)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return out
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export interface OverlapReport {
|
|
280
|
+
new_piece_codepoints: string[]
|
|
281
|
+
per_locale_overlap: Record<string, string[]>
|
|
282
|
+
accepted_overlap: string[]
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Report the code points outside ASCII that the new pieces share with each trained locale's
|
|
287
|
+
* sample, write the report, and raise when an overlapping locale is not in `acceptedOverlap`.
|
|
288
|
+
*
|
|
289
|
+
* The evaluation for an accepted locale must meet a registered per-locale non-inferiority
|
|
290
|
+
* comparison for it before the first measurement.
|
|
291
|
+
*/
|
|
292
|
+
export async function checkCodepointOverlap(
|
|
293
|
+
newPieces: readonly string[],
|
|
294
|
+
localeSamples: Readonly<Record<string, string>>,
|
|
295
|
+
reportPath: string,
|
|
296
|
+
acceptedOverlap: ReadonlySet<string> = new Set()
|
|
297
|
+
): Promise<Record<string, string[]>> {
|
|
298
|
+
const newCodepoints = new Set<string>()
|
|
299
|
+
|
|
300
|
+
for (const piece of newPieces) {
|
|
301
|
+
for (const c of core(piece)) {
|
|
302
|
+
if (isNonASCII(c)) {
|
|
303
|
+
newCodepoints.add(c)
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const report: Record<string, string[]> = {}
|
|
309
|
+
|
|
310
|
+
for (const locale of Object.keys(localeSamples).toSorted()) {
|
|
311
|
+
const sample = await collectSampleCodepoints(localeSamples[locale]!)
|
|
312
|
+
|
|
313
|
+
report[locale] = [...newCodepoints].filter((c) => sample.has(c)).toSorted(byCodePoint)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const written: OverlapReport = {
|
|
317
|
+
new_piece_codepoints: [...newCodepoints].toSorted(byCodePoint),
|
|
318
|
+
per_locale_overlap: report,
|
|
319
|
+
accepted_overlap: [...acceptedOverlap].toSorted(),
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
await writeLocalTextFile(prettyJSON(written, true, 2), reportPath)
|
|
323
|
+
|
|
324
|
+
const offending = Object.entries(report)
|
|
325
|
+
.filter(([locale, codepoints]) => codepoints.length > 0 && !acceptedOverlap.has(locale))
|
|
326
|
+
.map(([locale]) => locale)
|
|
327
|
+
|
|
328
|
+
if (offending.length) {
|
|
329
|
+
const detail = offending.map((locale) => `${locale}: ${report[locale]!.slice(0, 12).join("")}`).join("; ")
|
|
330
|
+
|
|
331
|
+
throw new Error(
|
|
332
|
+
`splice check: code point overlap with trained locale(s) ${offending.join(", ")} (${detail}). Either the ` +
|
|
333
|
+
`overlap is a defect, or register a per-locale non-inferiority comparison for each and pass ` +
|
|
334
|
+
`--accept-overlap ${offending.join(",")}. Report: ${reportPath}`
|
|
335
|
+
)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return report
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The ONNX element type codes this module reads.
|
|
343
|
+
*/
|
|
344
|
+
const ONNX_FLOAT = 1
|
|
345
|
+
const ONNX_UINT8 = 2
|
|
346
|
+
|
|
347
|
+
interface Initializer {
|
|
348
|
+
dims: number[]
|
|
349
|
+
data_type: number
|
|
350
|
+
bytes: Buffer
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Refuses a table initializer whose dims or byte length differ from `[rows, columns]` at `bytesPerValue`.
|
|
355
|
+
*
|
|
356
|
+
* @throws Naming the initializer, its dims and byte length, and the shape it was expected to have.
|
|
357
|
+
*/
|
|
358
|
+
export function assertTableShape(
|
|
359
|
+
label: string,
|
|
360
|
+
tensor: { dims: readonly number[]; bytes: Uint8Array },
|
|
361
|
+
[rows, columns]: readonly [number, number],
|
|
362
|
+
bytesPerValue: number
|
|
363
|
+
): void {
|
|
364
|
+
const expectedBytes = rows * columns * bytesPerValue
|
|
365
|
+
|
|
366
|
+
if (
|
|
367
|
+
tensor.dims.length !== 2 ||
|
|
368
|
+
tensor.dims[0] !== rows ||
|
|
369
|
+
tensor.dims[1] !== columns ||
|
|
370
|
+
tensor.bytes.length !== expectedBytes
|
|
371
|
+
) {
|
|
372
|
+
throw new Error(
|
|
373
|
+
`${label} has dims [${tensor.dims.join(", ")}] and ${tensor.bytes.length} bytes; ` +
|
|
374
|
+
`expected [${rows}, ${columns}] in ${expectedBytes} bytes`
|
|
375
|
+
)
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function readInitializer(model: string, name: string, directory: string): Promise<Initializer> {
|
|
380
|
+
const raw = `${directory}/${name.replaceAll("/", "_")}.bin`
|
|
381
|
+
|
|
382
|
+
const meta = await runMTFTokenizer<{ dims: number[]; data_type: number }>([
|
|
383
|
+
"onnx-read",
|
|
384
|
+
"--model",
|
|
385
|
+
model,
|
|
386
|
+
"--name",
|
|
387
|
+
name,
|
|
388
|
+
"--raw-out",
|
|
389
|
+
raw,
|
|
390
|
+
])
|
|
391
|
+
|
|
392
|
+
return { ...meta, bytes: await readLocalBuffer(raw) }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function writeInitializer(
|
|
396
|
+
model: string,
|
|
397
|
+
out: string,
|
|
398
|
+
name: string,
|
|
399
|
+
tensor: { dims: readonly number[]; data_type: number; bytes: Uint8Array },
|
|
400
|
+
directory: string
|
|
401
|
+
): Promise<void> {
|
|
402
|
+
const raw = `${directory}/${name.replaceAll("/", "_")}.out.bin`
|
|
403
|
+
|
|
404
|
+
await writeLocalBuffer(tensor.bytes, raw)
|
|
405
|
+
await makeDirectories(out.slice(0, out.lastIndexOf("/")) || ".")
|
|
406
|
+
|
|
407
|
+
await runMTFTokenizer([
|
|
408
|
+
"onnx-write",
|
|
409
|
+
"--model",
|
|
410
|
+
model,
|
|
411
|
+
"--name",
|
|
412
|
+
name,
|
|
413
|
+
"--dims",
|
|
414
|
+
tensor.dims.join(","),
|
|
415
|
+
"--data-type",
|
|
416
|
+
String(tensor.data_type),
|
|
417
|
+
"--raw",
|
|
418
|
+
raw,
|
|
419
|
+
"--out",
|
|
420
|
+
out,
|
|
421
|
+
])
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* The mean, in `float32`, of the rows of `table` at `rows`: each column summed row
|
|
426
|
+
* by row in `float32`, then divided by the row count.
|
|
427
|
+
* NumPy reduces `table[rows].mean(0)` the same way.
|
|
428
|
+
*/
|
|
429
|
+
function meanRow(table: Float32Array, hidden: number, rows: readonly number[]): Float32Array {
|
|
430
|
+
const out = new Float32Array(hidden)
|
|
431
|
+
|
|
432
|
+
for (let j = 0; j < hidden; j++) {
|
|
433
|
+
let sum = table[rows[0]! * hidden + j]!
|
|
434
|
+
|
|
435
|
+
for (let r = 1; r < rows.length; r++) {
|
|
436
|
+
sum = Math.fround(sum + table[rows[r]! * hidden + j]!)
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
out[j] = Math.fround(sum / rows.length)
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return out
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* NumPy's `np.round` for one value: to the nearest integer, ties to even.
|
|
447
|
+
*/
|
|
448
|
+
function roundHalfEven(value: number): number {
|
|
449
|
+
const floor = Math.floor(value)
|
|
450
|
+
const fraction = value - floor
|
|
451
|
+
|
|
452
|
+
if (fraction > 0.5) return floor + 1
|
|
453
|
+
|
|
454
|
+
if (fraction < 0.5) return floor
|
|
455
|
+
|
|
456
|
+
return floor % 2 === 0 ? floor : floor + 1
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function quantize(value: number, scale: number, zeroPoint: number): number {
|
|
460
|
+
const scaled = Math.fround(value / scale)
|
|
461
|
+
|
|
462
|
+
return Math.min(255, Math.max(0, Math.fround(roundHalfEven(scaled) + zeroPoint)))
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export interface ONNXMeanInitOptions {
|
|
466
|
+
fp32ONNX: string
|
|
467
|
+
baseTokenizer: string
|
|
468
|
+
splicedTokenizer: string
|
|
469
|
+
outFp32: string
|
|
470
|
+
int8ONNX?: string | null
|
|
471
|
+
outInt8?: string | null
|
|
472
|
+
embeddingName?: string
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Grow an exported model's token embedding table to the spliced vocabulary.
|
|
477
|
+
*
|
|
478
|
+
* Each new row is the mean of the base tokenizer's pieces for the new piece's surface (FVT),
|
|
479
|
+
* or the mean of every row when the surface has no piece inside the old vocabulary.
|
|
480
|
+
* The embedding is the only vocabulary-sized tensor of the token classifier,
|
|
481
|
+
* so the rest of the graph is unchanged.
|
|
482
|
+
*
|
|
483
|
+
* For an int8 twin the new rows are quantized with the table's own scale and zero point,
|
|
484
|
+
* after checking that those parameters reproduce the table's last row.
|
|
485
|
+
*/
|
|
486
|
+
export async function meanInitONNXEmbeddings(options: ONNXMeanInitOptions): Promise<[number, number]> {
|
|
487
|
+
const name = options.embeddingName ?? "inner.token_embeddings.weight"
|
|
488
|
+
|
|
489
|
+
await using scratch = await temporaryDirectory("mtf-mean-init-")
|
|
490
|
+
const directory = scratch.path.toString()
|
|
491
|
+
const embedding = await readInitializer(options.fp32ONNX, name, directory)
|
|
492
|
+
|
|
493
|
+
if (embedding.data_type !== ONNX_FLOAT || embedding.dims.length !== 2) {
|
|
494
|
+
throw new Error(`${name} in ${options.fp32ONNX} is not a float32 matrix`)
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const [oldVocab, hidden] = embedding.dims as [number, number]
|
|
498
|
+
|
|
499
|
+
// A short `raw_data` would read as a table of zeros past its end, and every spliced row would average them in.
|
|
500
|
+
assertTableShape(`${name} in ${options.fp32ONNX}`, embedding, [oldVocab, hidden], Float32Array.BYTES_PER_ELEMENT)
|
|
501
|
+
|
|
502
|
+
// A copy, because a `Float32Array` view needs a 4-byte-aligned offset that a read buffer need not have.
|
|
503
|
+
const table = new Float32Array(new Uint8Array(embedding.bytes).buffer, 0, oldVocab * hidden)
|
|
504
|
+
const spliced = await readModelPieces(options.splicedTokenizer)
|
|
505
|
+
const newVocab = spliced.length
|
|
506
|
+
|
|
507
|
+
if (newVocab < oldVocab) {
|
|
508
|
+
throw new Error(`spliced vocab ${newVocab} < embedding vocab ${oldVocab}: wrong tokenizer?`)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const globalMean = meanRow(
|
|
512
|
+
table,
|
|
513
|
+
hidden,
|
|
514
|
+
Array.from({ length: oldVocab }, (_, i) => i)
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
const newRows = new Float32Array((newVocab - oldVocab) * hidden)
|
|
518
|
+
|
|
519
|
+
{
|
|
520
|
+
using base = await loadEncoder(options.baseTokenizer)
|
|
521
|
+
|
|
522
|
+
for (let id = oldVocab; id < newVocab; id++) {
|
|
523
|
+
const surface = spliced[id]![0].replaceAll("▁", " ")
|
|
524
|
+
const constituents = base.encode(surface).ids.filter((i) => i < oldVocab)
|
|
525
|
+
|
|
526
|
+
newRows.set(constituents.length ? meanRow(table, hidden, constituents) : globalMean, (id - oldVocab) * hidden)
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const grown = new Float32Array(newVocab * hidden)
|
|
531
|
+
|
|
532
|
+
grown.set(table)
|
|
533
|
+
grown.set(newRows, oldVocab * hidden)
|
|
534
|
+
|
|
535
|
+
await writeInitializer(
|
|
536
|
+
options.fp32ONNX,
|
|
537
|
+
options.outFp32,
|
|
538
|
+
name,
|
|
539
|
+
{ dims: [newVocab, hidden], data_type: ONNX_FLOAT, bytes: new Uint8Array(grown.buffer) },
|
|
540
|
+
directory
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
if (options.int8ONNX && options.outInt8) {
|
|
544
|
+
const quantized = await readInitializer(options.int8ONNX, `${name}_quantized`, directory)
|
|
545
|
+
const scaleTensor = await readInitializer(options.int8ONNX, `${name}_scale`, directory)
|
|
546
|
+
const zeroTensor = await readInitializer(options.int8ONNX, `${name}_zero_point`, directory)
|
|
547
|
+
|
|
548
|
+
if (quantized.data_type !== ONNX_UINT8) throw new Error(`${name}_quantized is not a uint8 table`)
|
|
549
|
+
|
|
550
|
+
// The int8 table must describe the same vocabulary and width as the fp32 one, or the grown table mixes rows.
|
|
551
|
+
assertTableShape(`${name}_quantized in ${options.int8ONNX}`, quantized, [oldVocab, hidden], 1)
|
|
552
|
+
|
|
553
|
+
if (scaleTensor.bytes.length < Float32Array.BYTES_PER_ELEMENT || !zeroTensor.bytes.length) {
|
|
554
|
+
throw new Error(`${name}_scale or ${name}_zero_point in ${options.int8ONNX} holds no value`)
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const scale = scaleTensor.bytes.readFloatLE(0)
|
|
558
|
+
const zeroPoint = zeroTensor.bytes[0]!
|
|
559
|
+
const lastRow = oldVocab - 1
|
|
560
|
+
let mismatched = 0
|
|
561
|
+
|
|
562
|
+
for (let j = 0; j < hidden; j++) {
|
|
563
|
+
if (quantize(table[lastRow * hidden + j]!, scale, zeroPoint) !== quantized.bytes[lastRow * hidden + j]) {
|
|
564
|
+
mismatched++
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// Up to one value in twenty may sit on the other side of a rounding boundary.
|
|
569
|
+
// More means the wrong scale or zero point.
|
|
570
|
+
if (mismatched > Math.floor(hidden / QUANTIZE_MISMATCH_DIVISOR)) {
|
|
571
|
+
throw new Error(`int8 inverse mismatch on row ${lastRow}: ${mismatched}/${hidden}; scale or zero point wrong?`)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const grownQuantized = new Uint8Array(newVocab * hidden)
|
|
575
|
+
|
|
576
|
+
grownQuantized.set(quantized.bytes.subarray(0, oldVocab * hidden))
|
|
577
|
+
|
|
578
|
+
for (let i = 0; i < newRows.length; i++) {
|
|
579
|
+
grownQuantized[oldVocab * hidden + i] = quantize(newRows[i]!, scale, zeroPoint)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
await writeInitializer(
|
|
583
|
+
options.int8ONNX,
|
|
584
|
+
options.outInt8,
|
|
585
|
+
`${name}_quantized`,
|
|
586
|
+
{ dims: [newVocab, hidden], data_type: quantized.data_type, bytes: grownQuantized },
|
|
587
|
+
directory
|
|
588
|
+
)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
return [oldVocab, newVocab]
|
|
592
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The strings a trained tokenizer keeps whole, and how they reach SentencePiece.
|
|
7
|
+
*
|
|
8
|
+
* A user-defined symbol bypasses unigram inference and is always emitted as one piece. The literal a caller writes
|
|
9
|
+
* is not the literal SentencePiece matches: it turns whitespace into `▁` before matching, so `PO Box` is passed as
|
|
10
|
+
* `PO▁Box`. The symbols also compete with the vocabulary budget, so a list longer than a quarter of the vocabulary
|
|
11
|
+
* is truncated.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readLocalTextFile } from "@mailwoman/core/fs/readers"
|
|
15
|
+
import { splitLines } from "@mailwoman/core/strings/unicode"
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The default symbols: US state and territory codes, country abbreviations
|
|
19
|
+
* and names, and postal-form anchors.
|
|
20
|
+
*
|
|
21
|
+
* A state code beside a postcode (`NY 10001`) stays one piece, so the region and postcode stay adjacent.
|
|
22
|
+
* Postal markers (`PO Box`, `Cedex`, `BP`) are fixed surface forms that are
|
|
23
|
+
* cheaper to add once than to learn.
|
|
24
|
+
*
|
|
25
|
+
* A hyphen is not listed because it already tokenizes as one piece.
|
|
26
|
+
* Whole Japanese postcodes come from mined postcode literals.
|
|
27
|
+
*
|
|
28
|
+
* The list keeps its duplicates (`CA`, `DE`), which the trainer removes.
|
|
29
|
+
*/
|
|
30
|
+
export const DEFAULT_USER_DEFINED_SYMBOLS: readonly string[] = [
|
|
31
|
+
// US states and territories.
|
|
32
|
+
..."AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY DC PR VI GU AS MP".split(
|
|
33
|
+
" "
|
|
34
|
+
),
|
|
35
|
+
// Country abbreviations and names.
|
|
36
|
+
"USA",
|
|
37
|
+
"US",
|
|
38
|
+
"U.S.",
|
|
39
|
+
"U.S.A.",
|
|
40
|
+
"FR",
|
|
41
|
+
"FRA",
|
|
42
|
+
"France",
|
|
43
|
+
"JP",
|
|
44
|
+
"JPN",
|
|
45
|
+
"Japan",
|
|
46
|
+
"GB",
|
|
47
|
+
"UK",
|
|
48
|
+
"U.K.",
|
|
49
|
+
"DE",
|
|
50
|
+
"DEU",
|
|
51
|
+
"Germany",
|
|
52
|
+
"IT",
|
|
53
|
+
"ITA",
|
|
54
|
+
"Italy",
|
|
55
|
+
"ES",
|
|
56
|
+
"ESP",
|
|
57
|
+
"Spain",
|
|
58
|
+
"NL",
|
|
59
|
+
"NLD",
|
|
60
|
+
"Netherlands",
|
|
61
|
+
"CA",
|
|
62
|
+
"CAN",
|
|
63
|
+
"Canada",
|
|
64
|
+
"AU",
|
|
65
|
+
"AUS",
|
|
66
|
+
"Australia",
|
|
67
|
+
"CH",
|
|
68
|
+
"CHE",
|
|
69
|
+
"Switzerland",
|
|
70
|
+
"BE",
|
|
71
|
+
"BEL",
|
|
72
|
+
"Belgium",
|
|
73
|
+
"AT",
|
|
74
|
+
"AUT",
|
|
75
|
+
"Austria",
|
|
76
|
+
"SE",
|
|
77
|
+
"SWE",
|
|
78
|
+
"Sweden",
|
|
79
|
+
"RU",
|
|
80
|
+
"RUS",
|
|
81
|
+
// Postal-form anchors.
|
|
82
|
+
"PO Box",
|
|
83
|
+
"P.O. Box",
|
|
84
|
+
"P.O.Box",
|
|
85
|
+
"POB",
|
|
86
|
+
"Apt",
|
|
87
|
+
"Apt.",
|
|
88
|
+
"Suite",
|
|
89
|
+
"Ste",
|
|
90
|
+
"Cedex",
|
|
91
|
+
"CEDEX",
|
|
92
|
+
"BP",
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* One literal per line.
|
|
97
|
+
*
|
|
98
|
+
* A blank line or a `#` comment is skipped, and only line ends are trimmed,
|
|
99
|
+
* because a symbol may hold a space (`PO Box`).
|
|
100
|
+
*/
|
|
101
|
+
export async function readUserDefinedSymbolsFile(path: string): Promise<string[]> {
|
|
102
|
+
return splitLines(await readLocalTextFile(path))
|
|
103
|
+
.map((line) => line.trimEnd())
|
|
104
|
+
.filter((line) => line && !line.trim().startsWith("#"))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A symbol with each ASCII space replaced by SentencePiece's whitespace placeholder, `▁`.
|
|
109
|
+
*/
|
|
110
|
+
export function sentencePieceSymbol(symbol: string): string {
|
|
111
|
+
return symbol.replaceAll(" ", "▁")
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The non-empty entries, first occurrences only, in order.
|
|
116
|
+
*/
|
|
117
|
+
export function dedupeKeepOrder(items: Iterable<string>): string[] {
|
|
118
|
+
return [...new Set([...items].filter((item) => item.length > 0))]
|
|
119
|
+
}
|