@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.
Files changed (97) hide show
  1. package/README.md +37 -7
  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/lib/index.ts +6 -2
  6. package/out/code-units.d.ts +24 -0
  7. package/out/code-units.d.ts.map +1 -0
  8. package/out/code-units.js +36 -0
  9. package/out/code-units.js.map +1 -0
  10. package/out/index.d.ts +4 -2
  11. package/out/index.d.ts.map +1 -1
  12. package/out/index.js +6 -2
  13. package/out/index.js.map +1 -1
  14. package/out/tools/build-wasm.run.js +2 -2
  15. package/out/tools/build-wasm.run.js.map +1 -1
  16. package/out/tools/sampler/native.d.ts +314 -0
  17. package/out/tools/sampler/native.d.ts.map +1 -0
  18. package/out/tools/sampler/native.js +114 -0
  19. package/out/tools/sampler/native.js.map +1 -0
  20. package/out/tools/tokenizer/binary.d.ts +38 -0
  21. package/out/tools/tokenizer/binary.d.ts.map +1 -0
  22. package/out/tools/tokenizer/binary.js +94 -0
  23. package/out/tools/tokenizer/binary.js.map +1 -0
  24. package/out/tools/tokenizer/byte-fallback.d.ts +39 -0
  25. package/out/tools/tokenizer/byte-fallback.d.ts.map +1 -0
  26. package/out/tools/tokenizer/byte-fallback.js +49 -0
  27. package/out/tools/tokenizer/byte-fallback.js.map +1 -0
  28. package/out/tools/tokenizer/model.d.ts +70 -0
  29. package/out/tools/tokenizer/model.d.ts.map +1 -0
  30. package/out/tools/tokenizer/model.js +56 -0
  31. package/out/tools/tokenizer/model.js.map +1 -0
  32. package/out/tools/tokenizer/prune.d.ts +69 -0
  33. package/out/tools/tokenizer/prune.d.ts.map +1 -0
  34. package/out/tools/tokenizer/prune.js +126 -0
  35. package/out/tools/tokenizer/prune.js.map +1 -0
  36. package/out/tools/tokenizer/prune.run.d.ts +16 -0
  37. package/out/tools/tokenizer/prune.run.d.ts.map +1 -0
  38. package/out/tools/tokenizer/prune.run.js +34 -0
  39. package/out/tools/tokenizer/prune.run.js.map +1 -0
  40. package/out/tools/tokenizer/sentencepiece.d.ts +63 -0
  41. package/out/tools/tokenizer/sentencepiece.d.ts.map +1 -0
  42. package/out/tools/tokenizer/sentencepiece.js +90 -0
  43. package/out/tools/tokenizer/sentencepiece.js.map +1 -0
  44. package/out/tools/tokenizer/splice.d.ts +117 -0
  45. package/out/tools/tokenizer/splice.d.ts.map +1 -0
  46. package/out/tools/tokenizer/splice.js +398 -0
  47. package/out/tools/tokenizer/splice.js.map +1 -0
  48. package/out/tools/tokenizer/splice.run.d.ts +29 -0
  49. package/out/tools/tokenizer/splice.run.d.ts.map +1 -0
  50. package/out/tools/tokenizer/splice.run.js +114 -0
  51. package/out/tools/tokenizer/splice.run.js.map +1 -0
  52. package/out/tools/tokenizer/symbols.d.ts +42 -0
  53. package/out/tools/tokenizer/symbols.d.ts.map +1 -0
  54. package/out/tools/tokenizer/symbols.js +113 -0
  55. package/out/tools/tokenizer/symbols.js.map +1 -0
  56. package/out/tools/tokenizer/train/text.run.d.ts +16 -0
  57. package/out/tools/tokenizer/train/text.run.d.ts.map +1 -0
  58. package/out/tools/tokenizer/train/text.run.js +67 -0
  59. package/out/tools/tokenizer/train/text.run.js.map +1 -0
  60. package/out/tools/tokenizer/train.d.ts +113 -0
  61. package/out/tools/tokenizer/train.d.ts.map +1 -0
  62. package/out/tools/tokenizer/train.js +162 -0
  63. package/out/tools/tokenizer/train.js.map +1 -0
  64. package/out/tools/tokenizer/train.run.d.ts +24 -0
  65. package/out/tools/tokenizer/train.run.d.ts.map +1 -0
  66. package/out/tools/tokenizer/train.run.js +131 -0
  67. package/out/tools/tokenizer/train.run.js.map +1 -0
  68. package/out/tools/tokenizer/utilization.run.d.ts +17 -0
  69. package/out/tools/tokenizer/utilization.run.d.ts.map +1 -0
  70. package/out/tools/tokenizer/utilization.run.js +80 -0
  71. package/out/tools/tokenizer/utilization.run.js.map +1 -0
  72. package/out/tools/tokenizer/verify.d.ts +94 -0
  73. package/out/tools/tokenizer/verify.d.ts.map +1 -0
  74. package/out/tools/tokenizer/verify.js +193 -0
  75. package/out/tools/tokenizer/verify.js.map +1 -0
  76. package/out/tools/tokenizer/verify.run.d.ts +22 -0
  77. package/out/tools/tokenizer/verify.run.d.ts.map +1 -0
  78. package/out/tools/tokenizer/verify.run.js +71 -0
  79. package/out/tools/tokenizer/verify.run.js.map +1 -0
  80. package/package.json +15 -3
  81. package/tools/build-wasm.run.ts +2 -2
  82. package/tools/sampler/native.ts +433 -0
  83. package/tools/tokenizer/binary.ts +118 -0
  84. package/tools/tokenizer/byte-fallback.ts +80 -0
  85. package/tools/tokenizer/model.ts +110 -0
  86. package/tools/tokenizer/prune.run.ts +37 -0
  87. package/tools/tokenizer/prune.ts +195 -0
  88. package/tools/tokenizer/sentencepiece.ts +142 -0
  89. package/tools/tokenizer/splice.run.ts +141 -0
  90. package/tools/tokenizer/splice.ts +592 -0
  91. package/tools/tokenizer/symbols.ts +119 -0
  92. package/tools/tokenizer/train/text.run.ts +80 -0
  93. package/tools/tokenizer/train.run.ts +151 -0
  94. package/tools/tokenizer/train.ts +266 -0
  95. package/tools/tokenizer/utilization.run.ts +96 -0
  96. package/tools/tokenizer/verify.run.ts +77 -0
  97. package/tools/tokenizer/verify.ts +313 -0
@@ -0,0 +1,49 @@
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
+ import { readLocalTextFile } from "@mailwoman/core/fs/readers";
12
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary";
13
+ import { writeLocalJSONFile } from "@mailwoman/core/fs/writers";
14
+ import { parseJSONStrict } from "@mailwoman/core/json";
15
+ import { runMTFTokenizer } from "./binary.js";
16
+ /**
17
+ * Encode each non-blank line of `lines`, stripped, and tally its byte-fallback pieces.
18
+ */
19
+ export async function measureByteFallback(model, lines) {
20
+ await using scratch = await temporaryDirectory("mtf-byte-fallback-");
21
+ const input = scratch.path("lines.json").toString();
22
+ await writeLocalJSONFile(lines, input);
23
+ const report = await runMTFTokenizer(["byte-fallback", "--model", model, "--lines", input]);
24
+ return { overall: report.overall, per_script: Object.fromEntries(report.per_script) };
25
+ }
26
+ /**
27
+ * The texts of a held-out fixture: a JSONL file's `raw`, `text` or `input` field
28
+ * per object line, or each line of a plain-text file.
29
+ * Empty lines are skipped.
30
+ */
31
+ export async function readFixtureLines(path) {
32
+ const lines = [];
33
+ for (const line of (await readLocalTextFile(path)).split(/\r\n|\r|\n/)) {
34
+ if (!line)
35
+ continue;
36
+ if (line.trimStart().startsWith("{")) {
37
+ const record = parseJSONStrict(line);
38
+ const value = record["raw"] || record["text"] || record["input"];
39
+ if (value) {
40
+ lines.push(String(value));
41
+ }
42
+ }
43
+ else {
44
+ lines.push(line);
45
+ }
46
+ }
47
+ return lines;
48
+ }
49
+ //# sourceMappingURL=byte-fallback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"byte-fallback.js","sourceRoot":"","sources":["../../../tools/tokenizer/byte-fallback.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAA;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAA;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAEtD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAsB7C;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,KAAa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 -0,0 +1,70 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * A SentencePiece model's vocabulary, read and edited through `mtf-tokenizer`, and an encoder over it through the
7
+ * `@mailwoman/mtf` runtime.
8
+ */
9
+ import { type MTFModel } from "#index";
10
+ /**
11
+ * `ModelProto.SentencePiece.Type`, by wire value.
12
+ */
13
+ export declare const PieceType: {
14
+ readonly Normal: 1;
15
+ readonly Unknown: 2;
16
+ readonly Control: 3;
17
+ readonly UserDefined: 4;
18
+ readonly Unused: 5;
19
+ readonly Byte: 6;
20
+ };
21
+ export type PieceType = (typeof PieceType)[keyof typeof PieceType];
22
+ /**
23
+ * One vocabulary entry.
24
+ * `score` is the stored `float32`, widened exactly.
25
+ */
26
+ export type VocabularyPiece = readonly [piece: string, score: number, type: PieceType];
27
+ /**
28
+ * Every piece of the model at `path`, in id order.
29
+ */
30
+ export declare function readModelPieces(path: string): Promise<VocabularyPiece[]>;
31
+ /**
32
+ * The edits `mtf-tokenizer edit` applies, in this order.
33
+ */
34
+ export interface ModelEdit {
35
+ /**
36
+ * The piece ids to keep, in the order to keep them.
37
+ */
38
+ keep?: readonly number[];
39
+ /**
40
+ * Pieces to append after the kept ones.
41
+ */
42
+ append?: readonly VocabularyPiece[];
43
+ /**
44
+ * The flag names of the training call that wrote the model.
45
+ *
46
+ * The trainer and normalizer spec fields without a corresponding flag are dropped.
47
+ * This turns a native `spm_train` model into the bytes the Python wheel writes.
48
+ */
49
+ wheelFlags?: readonly string[];
50
+ }
51
+ /**
52
+ * What an edit dropped from each spec, by field number.
53
+ */
54
+ export interface ModelEditSummary {
55
+ pieces: number;
56
+ dropped_fields: {
57
+ trainer?: number[];
58
+ normalizer?: number[];
59
+ };
60
+ }
61
+ /**
62
+ * Write `source` with `edit` applied to `destination`, which may be `source` itself.
63
+ */
64
+ export declare function editModel(source: string, destination: string, edit: ModelEdit): Promise<ModelEditSummary>;
65
+ /**
66
+ * The model at `path`, loaded into the WebAssembly runtime.
67
+ * Dispose it after use.
68
+ */
69
+ export declare function loadEncoder(path: string): Promise<MTFModel>;
70
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../tools/tokenizer/model.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,EAAE,KAAK,QAAQ,EAA0B,MAAM,QAAQ,CAAA;AAI9D;;GAEG;AACH,eAAO,MAAM,SAAS;aACrB,MAAM,EAAE,CAAC;aACT,OAAO,EAAE,CAAC;aACV,OAAO,EAAE,CAAC;aACV,WAAW,EAAE,CAAC;aACd,MAAM,EAAE,CAAC;aACT,IAAI,EAAE,CAAC;CACE,CAAA;AAEV,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,CAAA;AAElE;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;AAEtF;;GAEG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC,CAQ9E;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB;;OAEG;IACH,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IACxB;;OAEG;IACH,MAAM,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;IACnC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAC9B;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAA;CAC7D;AAED;;GAEG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAe/G;AAID;;;GAGG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAIjE"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * A SentencePiece model's vocabulary, read and edited through `mtf-tokenizer`, and an encoder over it through the
7
+ * `@mailwoman/mtf` runtime.
8
+ */
9
+ import { readLocalBuffer, readLocalJSONFile } from "@mailwoman/core/fs/readers";
10
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary";
11
+ import { replaceFileAtomically, writeLocalJSONFile } from "@mailwoman/core/fs/writers";
12
+ import { MTFRuntime, mtfWASMURL } from "#index";
13
+ import { runMTFTokenizer } from "./binary.js";
14
+ /**
15
+ * `ModelProto.SentencePiece.Type`, by wire value.
16
+ */
17
+ export const PieceType = {
18
+ Normal: 1,
19
+ Unknown: 2,
20
+ Control: 3,
21
+ UserDefined: 4,
22
+ Unused: 5,
23
+ Byte: 6,
24
+ };
25
+ /**
26
+ * Every piece of the model at `path`, in id order.
27
+ */
28
+ export async function readModelPieces(path) {
29
+ await using scratch = await temporaryDirectory("mtf-inspect-");
30
+ const out = scratch.path("pieces.json").toString();
31
+ await runMTFTokenizer(["inspect", path, "--out", out]);
32
+ const { pieces } = await readLocalJSONFile(out);
33
+ return pieces;
34
+ }
35
+ /**
36
+ * Write `source` with `edit` applied to `destination`, which may be `source` itself.
37
+ */
38
+ export async function editModel(source, destination, edit) {
39
+ await using scratch = await temporaryDirectory("mtf-edit-");
40
+ const plan = scratch.path("plan.json").toString();
41
+ const staged = scratch.path("model").toString();
42
+ await writeLocalJSONFile({ keep: edit.keep ?? null, append: edit.append ?? null, wheel_flags: edit.wheelFlags ?? null }, plan);
43
+ const summary = await runMTFTokenizer(["edit", source, "--plan", plan, "--out", staged]);
44
+ await replaceFileAtomically(staged, destination);
45
+ return summary;
46
+ }
47
+ let runtime = null;
48
+ /**
49
+ * The model at `path`, loaded into the WebAssembly runtime.
50
+ * Dispose it after use.
51
+ */
52
+ export async function loadEncoder(path) {
53
+ runtime ??= readLocalBuffer(mtfWASMURL()).then((bytes) => MTFRuntime.instantiate(new Uint8Array(bytes)));
54
+ return (await runtime).loadModel(await readLocalBuffer(path));
55
+ }
56
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../../tools/tokenizer/model.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAA;AACjE,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAA;AAEtF,OAAO,EAAiB,UAAU,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAA;AAE9D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7C;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IACxB,MAAM,EAAE,CAAC;IACT,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,CAAC;IACV,WAAW,EAAE,CAAC;IACd,MAAM,EAAE,CAAC;IACT,IAAI,EAAE,CAAC;CACE,CAAA;AAUV;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAY;IACjD,YAAY,OAAO,GAAG,MAAM,kBAAkB,CAAC,cAAc,CAAC,CAAA;IAC9D,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,QAAQ,EAAE,CAAA;IAElD,MAAM,eAAe,CAAS,CAAC,SAAS,EAAE,IAAI,EAAE,OAAO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AAC,IAAI,CAAC,CAAC,CAAA;AAC9D,CAAC"}
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Prune a tokenizer's unused pieces and the matching rows of an int8 model's embedding table.
7
+ *
8
+ * A piece that never won a Viterbi path contributes no score to any other path, so segmentation is unchanged for
9
+ * every input whose best path avoided the pruned pieces. The kept pieces stay in their order. The embedding rows
10
+ * are gathered by the old-to-new id map with the scale and zero point untouched, so each kept row stays the same
11
+ * bytes.
12
+ */
13
+ /**
14
+ * The quantized embedding table of the BIO token classifier.
15
+ */
16
+ export declare const QUANTIZED_EMBEDDING = "inner.token_embeddings.weight_quantized";
17
+ /**
18
+ * The id map `prunePieces` writes as `id-map.json`: the kept old ids in order,
19
+ * and each old id's new id or -1.
20
+ */
21
+ export interface PruneIDMap {
22
+ kept_ids: number[];
23
+ old_to_new: number[];
24
+ }
25
+ export interface PruneReport {
26
+ vocab_before: number;
27
+ vocab_after: number;
28
+ train_fired: number;
29
+ eval_fired: number;
30
+ single_codepoint_kept: number;
31
+ tokenizer_bytes: {
32
+ before: number;
33
+ after: number;
34
+ };
35
+ onnx_bytes: {
36
+ before: number;
37
+ after: number;
38
+ };
39
+ }
40
+ export interface PruneOptions {
41
+ tokenizer: string;
42
+ onnx: string;
43
+ /**
44
+ * A JSON file whose `counts` is each piece's use count over the training corpus,
45
+ * as `utilization.run.ts` writes.
46
+ */
47
+ trainCounts: string;
48
+ /**
49
+ * A JSON file whose `fired_ids` lists the pieces the evaluation surface uses.
50
+ */
51
+ evalFired: string;
52
+ outDirectory: string;
53
+ }
54
+ /**
55
+ * The pieces to keep: every piece the training corpus or the evaluation surface used, every
56
+ * piece that is not a normal piece (control, unknown, user-defined, unused and byte pieces),
57
+ * and every piece of at most one code point once a leading `▁` is removed.
58
+ * This keeps every character reachable.
59
+ */
60
+ export declare function keepSet(vocabulary: readonly (readonly [string, number, number])[], counts: readonly number[], evalFired: readonly number[]): {
61
+ keep: boolean[];
62
+ singleCodepoint: number;
63
+ };
64
+ /**
65
+ * Write the pruned `tokenizer.model`, `model.onnx`, `id-map.json`
66
+ * and `prune-report.json` under the output directory.
67
+ */
68
+ export declare function prunePieces(options: PruneOptions): Promise<PruneReport>;
69
+ //# sourceMappingURL=prune.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prune.d.ts","sourceRoot":"","sources":["../../../tools/tokenizer/prune.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAWH;;GAEG;AACH,eAAO,MAAM,mBAAmB,4CAA4C,CAAA;AAE5E;;;GAGG;AACH,MAAM,WAAW,UAAU;IAC1B,QAAQ,EAAE,MAAM,EAAE,CAAA;IAClB,UAAU,EAAE,MAAM,EAAE,CAAA;CACpB;AAED,MAAM,WAAW,WAAW;IAC3B,YAAY,EAAE,MAAM,CAAA;IACpB,WAAW,EAAE,MAAM,CAAA;IACnB,WAAW,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,MAAM,CAAA;IAC7B,eAAe,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;IAClD,UAAU,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;CAC7C;AAED,MAAM,WAAW,YAAY;IAC5B,SAAS,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,MAAM,CAAA;IACZ;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,CAAA;CACpB;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CACtB,UAAU,EAAE,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,EAC1D,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,SAAS,EAAE,SAAS,MAAM,EAAE,GAC1B;IAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAAC,eAAe,EAAE,MAAM,CAAA;CAAE,CA+B9C;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAsF7E"}
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Prune a tokenizer's unused pieces and the matching rows of an int8 model's embedding table.
7
+ *
8
+ * A piece that never won a Viterbi path contributes no score to any other path, so segmentation is unchanged for
9
+ * every input whose best path avoided the pruned pieces. The kept pieces stay in their order. The embedding rows
10
+ * are gathered by the old-to-new id map with the scale and zero point untouched, so each kept row stays the same
11
+ * bytes.
12
+ */
13
+ import { readLocalBuffer, readLocalJSONFile } from "@mailwoman/core/fs/readers";
14
+ import { readFileSize } from "@mailwoman/core/fs/readers/stat";
15
+ import { temporaryDirectory } from "@mailwoman/core/fs/temporary";
16
+ import { makeDirectories, writeLocalBuffer, writeLocalJSONFile, writeLocalTextFile } from "@mailwoman/core/fs/writers";
17
+ import { prettyJSON } from "@mailwoman/core/json";
18
+ import { runMTFTokenizer } from "./binary.js";
19
+ import { editModel, PieceType, readModelPieces } from "./model.js";
20
+ /**
21
+ * The quantized embedding table of the BIO token classifier.
22
+ */
23
+ export const QUANTIZED_EMBEDDING = "inner.token_embeddings.weight_quantized";
24
+ /**
25
+ * The pieces to keep: every piece the training corpus or the evaluation surface used, every
26
+ * piece that is not a normal piece (control, unknown, user-defined, unused and byte pieces),
27
+ * and every piece of at most one code point once a leading `▁` is removed.
28
+ * This keeps every character reachable.
29
+ */
30
+ export function keepSet(vocabulary, counts, evalFired) {
31
+ if (counts.length !== vocabulary.length) {
32
+ throw new Error(`the counts cover ${counts.length} pieces and the tokenizer has ${vocabulary.length}`);
33
+ }
34
+ const keep = counts.map((n) => n > 0);
35
+ for (const id of evalFired) {
36
+ if (id < 0 || id >= keep.length)
37
+ throw new Error(`eval-fired id ${id} is outside the vocabulary`);
38
+ keep[id] = true;
39
+ }
40
+ let singleCodepoint = 0;
41
+ vocabulary.forEach(([piece, , type], id) => {
42
+ if (type !== PieceType.Normal) {
43
+ keep[id] = true;
44
+ return;
45
+ }
46
+ const literal = piece.startsWith("▁") ? piece.slice(1) : piece;
47
+ if ([...literal].length <= 1) {
48
+ keep[id] = true;
49
+ singleCodepoint++;
50
+ }
51
+ });
52
+ return { keep, singleCodepoint };
53
+ }
54
+ /**
55
+ * Write the pruned `tokenizer.model`, `model.onnx`, `id-map.json`
56
+ * and `prune-report.json` under the output directory.
57
+ */
58
+ export async function prunePieces(options) {
59
+ const vocabulary = await readModelPieces(options.tokenizer);
60
+ const { counts } = await readLocalJSONFile(options.trainCounts);
61
+ const { fired_ids: evalFired } = await readLocalJSONFile(options.evalFired);
62
+ const { keep, singleCodepoint } = keepSet(vocabulary, counts, evalFired);
63
+ const keptIDs = keep.flatMap((kept, id) => (kept ? [id] : []));
64
+ const oldToNew = new Array(vocabulary.length).fill(-1);
65
+ keptIDs.forEach((id, i) => {
66
+ oldToNew[id] = i;
67
+ });
68
+ const trainFired = counts.filter((n) => n > 0).length;
69
+ const evalCount = new Set(evalFired).size;
70
+ console.info(`[prune] vocab ${vocabulary.length} → keep ${keptIDs.length} (${((100 * keptIDs.length) / vocabulary.length).toFixed(1)}%)`);
71
+ console.info(`[prune] train-fired ${trainFired}, eval-fired ${evalCount}, single-codepoint kept ${singleCodepoint}`);
72
+ await makeDirectories(options.outDirectory);
73
+ const tokenizerOut = `${options.outDirectory}/tokenizer.model`;
74
+ await editModel(options.tokenizer, tokenizerOut, { keep: keptIDs });
75
+ await using scratch = await temporaryDirectory("mtf-prune-");
76
+ const table = scratch.path("table.bin").toString();
77
+ const gathered = scratch.path("gathered.bin").toString();
78
+ const onnxOut = `${options.outDirectory}/model.onnx`;
79
+ const meta = await runMTFTokenizer([
80
+ "onnx-read",
81
+ "--model",
82
+ options.onnx,
83
+ "--name",
84
+ QUANTIZED_EMBEDDING,
85
+ "--raw-out",
86
+ table,
87
+ ]);
88
+ if (meta.dims[0] !== vocabulary.length) {
89
+ throw new Error(`embedding rows ${meta.dims[0]} != vocab ${vocabulary.length}`);
90
+ }
91
+ const rowBytes = (await readFileSize(table)) / vocabulary.length;
92
+ const rows = await readLocalBuffer(table);
93
+ const out = Buffer.alloc(keptIDs.length * rowBytes);
94
+ keptIDs.forEach((id, i) => rows.copy(out, i * rowBytes, id * rowBytes, (id + 1) * rowBytes));
95
+ await writeLocalBuffer(out, gathered);
96
+ await runMTFTokenizer([
97
+ "onnx-write",
98
+ "--model",
99
+ options.onnx,
100
+ "--name",
101
+ QUANTIZED_EMBEDDING,
102
+ "--dims",
103
+ [keptIDs.length, ...meta.dims.slice(1)].join(","),
104
+ "--data-type",
105
+ String(meta.data_type),
106
+ "--raw",
107
+ gathered,
108
+ "--out",
109
+ onnxOut,
110
+ ]);
111
+ const idMap = { kept_ids: keptIDs, old_to_new: oldToNew };
112
+ await writeLocalJSONFile(idMap, `${options.outDirectory}/id-map.json`);
113
+ const report = {
114
+ vocab_before: vocabulary.length,
115
+ vocab_after: keptIDs.length,
116
+ train_fired: trainFired,
117
+ eval_fired: evalCount,
118
+ single_codepoint_kept: singleCodepoint,
119
+ tokenizer_bytes: { before: await readFileSize(options.tokenizer), after: await readFileSize(tokenizerOut) },
120
+ onnx_bytes: { before: await readFileSize(options.onnx), after: await readFileSize(onnxOut) },
121
+ };
122
+ await writeLocalTextFile(prettyJSON(report, true, 1), `${options.outDirectory}/prune-report.json`);
123
+ console.info(prettyJSON(report, false, 1));
124
+ return report;
125
+ }
126
+ //# sourceMappingURL=prune.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prune.js","sourceRoot":"","sources":["../../../tools/tokenizer/prune.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,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O,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAA;IAErE,MAAM,kBAAkB,CAAC,KAAK,EAAE,GAAG,OAAO,CAAC,YAAY,cAAc,CAAC,CAAA;IAEtE,MAAM,MAAM,GAAgB;QAC3B,YAAY,EAAE,UAAU,CAAC,MAAM;QAC/B,WAAW,EAAE,OAAO,CAAC,MAAM;QAC3B,WAAW,EAAE,UAAU;QACvB,UAAU,EAAE,SAAS;QACrB,qBAAqB,EAAE,eAAe;QACtC,eAAe,EAAE,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC,YAAY,CAAC,EAAE;QAC3G,UAAU,EAAE,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC,OAAO,CAAC,EAAE;KAC5F,CAAA;IAED,MAAM,kBAAkB,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,YAAY,oBAAoB,CAAC,CAAA;IAElG,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAA;IAE1C,OAAO,MAAM,CAAA;AACd,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Prune a tokenizer's unused pieces and the int8 model's matching embedding rows.
7
+ *
8
+ * `--train-counts` is the per-piece count `utilization.run.ts` writes; `--eval-fired` is a JSON file whose
9
+ * `fired_ids` lists the pieces the evaluation surface uses. The tool writes `tokenizer.model`, `model.onnx`,
10
+ * `id-map.json` and `prune-report.json` under `--out-dir`. `verify.run.ts prune` then checks the result.
11
+ *
12
+ * Usage: `node packages/mtf/tools/tokenizer/prune.run.ts --tokenizer <model> --onnx <int8 onnx>
13
+ * --train-counts <json> --eval-fired <json> --out-dir <dir>`
14
+ */
15
+ export {};
16
+ //# sourceMappingURL=prune.run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prune.run.d.ts","sourceRoot":"","sources":["../../../tools/tokenizer/prune.run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Prune a tokenizer's unused pieces and the int8 model's matching embedding rows.
7
+ *
8
+ * `--train-counts` is the per-piece count `utilization.run.ts` writes; `--eval-fired` is a JSON file whose
9
+ * `fired_ids` lists the pieces the evaluation surface uses. The tool writes `tokenizer.model`, `model.onnx`,
10
+ * `id-map.json` and `prune-report.json` under `--out-dir`. `verify.run.ts prune` then checks the result.
11
+ *
12
+ * Usage: `node packages/mtf/tools/tokenizer/prune.run.ts --tokenizer <model> --onnx <int8 onnx>
13
+ * --train-counts <json> --eval-fired <json> --out-dir <dir>`
14
+ */
15
+ import { parseArguments, requiredArgument } from "@mailwoman/core/scripting/arguments";
16
+ import { resolvePath } from "path-ts";
17
+ import { prunePieces } from "./prune.js";
18
+ const { values } = parseArguments({
19
+ options: {
20
+ tokenizer: { type: "string" },
21
+ onnx: { type: "string" },
22
+ "train-counts": { type: "string" },
23
+ "eval-fired": { type: "string" },
24
+ "out-dir": { type: "string" },
25
+ },
26
+ });
27
+ await prunePieces({
28
+ tokenizer: resolvePath(requiredArgument("prune", "tokenizer", values.tokenizer)),
29
+ onnx: resolvePath(requiredArgument("prune", "onnx", values.onnx)),
30
+ trainCounts: resolvePath(requiredArgument("prune", "train-counts", values["train-counts"])),
31
+ evalFired: resolvePath(requiredArgument("prune", "eval-fired", values["eval-fired"])),
32
+ outDirectory: resolvePath(requiredArgument("prune", "out-dir", values["out-dir"])),
33
+ });
34
+ //# sourceMappingURL=prune.run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prune.run.js","sourceRoot":"","sources":["../../../tools/tokenizer/prune.run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAA;AACtF,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAExC,MAAM,EAAE,MAAM,EAAE,GAAG,cAAc,CAAC;IACjC,OAAO,EAAE;QACR,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QAC7B,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QACxB,cAAc,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QAClC,YAAY,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QAChC,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC7B;CACD,CAAC,CAAA;AAEF,MAAM,WAAW,CAAC;IACjB,SAAS,EAAE,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;IAChF,IAAI,EAAE,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IACjE,WAAW,EAAE,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC;IAC3F,SAAS,EAAE,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,YAAY,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC;IACrF,YAAY,EAAE,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;CAClF,CAAC,CAAA"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * One SentencePiece training call, made with native `spm_train` and written in the Python wheel's model form.
7
+ *
8
+ * The flags are the keyword arguments a `SentencePieceTrainer.train(**flags)` call took, in the same order and with
9
+ * the same values. Two lists go through files rather than the command line, because the CLI splits an inline list
10
+ * on commas and a user-defined symbol may itself be a comma. `minloglevel` sets only the wheel's log level and has
11
+ * no CLI flag, so it is left off the command line.
12
+ *
13
+ * `spm_train` sets every trainer flag on its spec, so the model records defaults the caller did not supply.
14
+ * The wheel's spec holds only fields supplied in the call. After training, the rewrite drops trainer and normalizer
15
+ * fields absent from the flags. This produces the same bytes the wheel produces for that call.
16
+ */
17
+ import { type ModelEditSummary } from "./model.ts";
18
+ /**
19
+ * One training argument's value.
20
+ */
21
+ export type TrainerFlagValue = string | number | boolean | readonly string[];
22
+ /**
23
+ * The keyword arguments of one training call, in call order.
24
+ */
25
+ export type TrainerFlags = Readonly<Record<string, TrainerFlagValue>>;
26
+ /**
27
+ * This function serializes a list as one CSV row, matching the format Python's
28
+ * `csv.writer` produces for a list flag.
29
+ */
30
+ export declare function csvRow(values: readonly string[]): string;
31
+ export interface TrainedModel {
32
+ model: string;
33
+ vocab: string;
34
+ /**
35
+ * The command line `spm_train` ran with.
36
+ */
37
+ argv: string[];
38
+ /**
39
+ * The spec fields the wheel's form dropped.
40
+ */
41
+ dropped: ModelEditSummary["dropped_fields"];
42
+ }
43
+ export interface TrainOptions {
44
+ spmTrain: string;
45
+ /**
46
+ * Where the list files and the trainer's log go.
47
+ */
48
+ workDirectory: string;
49
+ /**
50
+ * The directory where `spm_train` runs.
51
+ *
52
+ * Relative `input` and `model_prefix` values resolve from this directory.
53
+ *
54
+ * The model records both paths as given, so a recipe written with relative paths
55
+ * trains to the same bytes in any directory.
56
+ */
57
+ cwd?: string;
58
+ }
59
+ /**
60
+ * Train with `flags` containing `model_prefix`, then rewrite `<model_prefix>.model` in the wheel's form.
61
+ */
62
+ export declare function trainSentencePiece(flags: TrainerFlags, options: TrainOptions): Promise<TrainedModel>;
63
+ //# sourceMappingURL=sentencepiece.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sentencepiece.d.ts","sourceRoot":"","sources":["../../../tools/tokenizer/sentencepiece.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAOH,OAAO,EAAa,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAE7D;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,MAAM,EAAE,CAAA;AAE5E;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAA;AAerE;;;GAGG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAMxD;AAWD,MAAM,WAAW,YAAY;IAC5B,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb;;OAEG;IACH,IAAI,EAAE,MAAM,EAAE,CAAA;IACd;;OAEG;IACH,OAAO,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,CAAA;CAC3C;AAED,MAAM,WAAW,YAAY;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB;;OAEG;IACH,aAAa,EAAE,MAAM,CAAA;IACrB;;;;;;;OAOG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;CACZ;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CAAC,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CAwC1G"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * One SentencePiece training call, made with native `spm_train` and written in the Python wheel's model form.
7
+ *
8
+ * The flags are the keyword arguments a `SentencePieceTrainer.train(**flags)` call took, in the same order and with
9
+ * the same values. Two lists go through files rather than the command line, because the CLI splits an inline list
10
+ * on commas and a user-defined symbol may itself be a comma. `minloglevel` sets only the wheel's log level and has
11
+ * no CLI flag, so it is left off the command line.
12
+ *
13
+ * `spm_train` sets every trainer flag on its spec, so the model records defaults the caller did not supply.
14
+ * The wheel's spec holds only fields supplied in the call. After training, the rewrite drops trainer and normalizer
15
+ * fields absent from the flags. This produces the same bytes the wheel produces for that call.
16
+ */
17
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers";
18
+ import { stringifyJSON } from "@mailwoman/core/json";
19
+ import { runFile } from "@mailwoman/core/process";
20
+ import { resolvePath } from "path-ts";
21
+ import { editModel } from "./model.js";
22
+ /**
23
+ * The list flags `spm_train` reads one entry per line from a file.
24
+ */
25
+ const FILE_LIST_FLAGS = {
26
+ user_defined_symbols: "user_defined_symbols_file",
27
+ control_symbols: "control_symbols_file",
28
+ };
29
+ /**
30
+ * The flags only the wheel reads.
31
+ */
32
+ const WHEEL_ONLY_FLAGS = new Set(["minloglevel"]);
33
+ /**
34
+ * This function serializes a list as one CSV row, matching the format Python's
35
+ * `csv.writer` produces for a list flag.
36
+ */
37
+ export function csvRow(values) {
38
+ return values
39
+ .map((value) => /[",\r\n]/.test(value) || (values.length === 1 && value === "") ? `"${value.replaceAll('"', '""')}"` : value)
40
+ .join(",");
41
+ }
42
+ /**
43
+ * A scalar flag as the wheel's `str(value)` renders it.
44
+ */
45
+ function scalar(value) {
46
+ if (typeof value === "boolean")
47
+ return value ? "true" : "false";
48
+ return String(value);
49
+ }
50
+ /**
51
+ * Train with `flags` containing `model_prefix`, then rewrite `<model_prefix>.model` in the wheel's form.
52
+ */
53
+ export async function trainSentencePiece(flags, options) {
54
+ const prefix = flags["model_prefix"];
55
+ if (typeof prefix !== "string")
56
+ throw new Error("a training call needs a model_prefix");
57
+ const argv = [];
58
+ for (const [name, value] of Object.entries(flags)) {
59
+ if (WHEEL_ONLY_FLAGS.has(name))
60
+ continue;
61
+ if (Array.isArray(value)) {
62
+ const listed = value;
63
+ const fileFlag = FILE_LIST_FLAGS[name];
64
+ if (fileFlag) {
65
+ if (!listed.length)
66
+ continue;
67
+ for (const entry of listed) {
68
+ if (/[\r\n]/.test(entry))
69
+ throw new Error(`${name} entry ${stringifyJSON(entry)} holds a line break`);
70
+ }
71
+ const file = `${options.workDirectory}/${fileFlag}.txt`;
72
+ await writeLocalTextFile(listed, file);
73
+ argv.push(`--${fileFlag}=${file}`);
74
+ }
75
+ else {
76
+ argv.push(`--${name}=${csvRow(listed)}`);
77
+ }
78
+ }
79
+ else {
80
+ argv.push(`--${name}=${scalar(value)}`);
81
+ }
82
+ }
83
+ const { stderr } = await runFile(options.spmTrain, argv, { maxBuffer: 1 << 30, cwd: options.cwd });
84
+ await writeLocalTextFile(stderr, `${options.workDirectory}/spm_train.log`);
85
+ const base = resolvePath(options.cwd ?? ".", prefix);
86
+ const model = `${base}.model`;
87
+ const { dropped_fields } = await editModel(model, model, { wheelFlags: Object.keys(flags) });
88
+ return { model, vocab: `${base}.vocab`, argv, dropped: dropped_fields };
89
+ }
90
+ //# sourceMappingURL=sentencepiece.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sentencepiece.js","sourceRoot":"","sources":["../../../tools/tokenizer/sentencepiece.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAA;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAA;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,EAAE,SAAS,EAAyB,MAAM,YAAY,CAAA;AAY7D;;GAEG;AACH,MAAM,eAAe,GAAqC;IACzD,oBAAoB,EAAE,2BAA2B;IACjD,eAAe,EAAE,sBAAsB;CACvC,CAAA;AAED;;GAEG;AACH,MAAM,gBAAgB,GAAG,I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