@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,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
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The rate at which a tokenizer falls back to raw bytes, overall and per script.
|
|
7
|
+
*
|
|
8
|
+
* `mtf-tokenizer byte-fallback` encodes each line with the model and assigns it a script from the Unicode name of
|
|
9
|
+
* its letters, through the tables `mtf-channels` generates from CPython's Unicode database.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readLocalTextFile } from "@mailwoman/core/fs/readers"
|
|
13
|
+
import { temporaryDirectory } from "@mailwoman/core/fs/temporary"
|
|
14
|
+
import { writeLocalJSONFile } from "@mailwoman/core/fs/writers"
|
|
15
|
+
import { parseJSONStrict } from "@mailwoman/core/json"
|
|
16
|
+
|
|
17
|
+
import { runMTFTokenizer } from "./binary.ts"
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One bucket's counts.
|
|
21
|
+
*
|
|
22
|
+
* `rate` is `byte_fallback_pieces / pieces`, or 0 for a bucket with no pieces.
|
|
23
|
+
*/
|
|
24
|
+
export interface ByteFallbackTally {
|
|
25
|
+
lines: number
|
|
26
|
+
pieces: number
|
|
27
|
+
byte_fallback_pieces: number
|
|
28
|
+
rate: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The overall tally and one per script, keyed in the order each script first appeared.
|
|
33
|
+
*/
|
|
34
|
+
export interface ByteFallbackReport {
|
|
35
|
+
overall: ByteFallbackTally
|
|
36
|
+
per_script: Record<string, ByteFallbackTally>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Encode each non-blank line of `lines`, stripped, and tally its byte-fallback pieces.
|
|
41
|
+
*/
|
|
42
|
+
export async function measureByteFallback(model: string, lines: readonly string[]): Promise<ByteFallbackReport> {
|
|
43
|
+
await using scratch = await temporaryDirectory("mtf-byte-fallback-")
|
|
44
|
+
const input = scratch.path("lines.json").toString()
|
|
45
|
+
|
|
46
|
+
await writeLocalJSONFile(lines, input)
|
|
47
|
+
|
|
48
|
+
const report = await runMTFTokenizer<{
|
|
49
|
+
overall: ByteFallbackTally
|
|
50
|
+
per_script: [string, ByteFallbackTally][]
|
|
51
|
+
}>(["byte-fallback", "--model", model, "--lines", input])
|
|
52
|
+
|
|
53
|
+
return { overall: report.overall, per_script: Object.fromEntries(report.per_script) }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The texts of a held-out fixture: a JSONL file's `raw`, `text` or `input` field
|
|
58
|
+
* per object line, or each line of a plain-text file.
|
|
59
|
+
* Empty lines are skipped.
|
|
60
|
+
*/
|
|
61
|
+
export async function readFixtureLines(path: string): Promise<string[]> {
|
|
62
|
+
const lines: string[] = []
|
|
63
|
+
|
|
64
|
+
for (const line of (await readLocalTextFile(path)).split(/\r\n|\r|\n/)) {
|
|
65
|
+
if (!line) continue
|
|
66
|
+
|
|
67
|
+
if (line.trimStart().startsWith("{")) {
|
|
68
|
+
const record = parseJSONStrict<Record<string, unknown>>(line)
|
|
69
|
+
const value = record["raw"] || record["text"] || record["input"]
|
|
70
|
+
|
|
71
|
+
if (value) {
|
|
72
|
+
lines.push(String(value))
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
lines.push(line)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return lines
|
|
80
|
+
}
|