@try-works/extension-laya 0.0.0-stage → 1.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 +38 -2
- package/lib/index.d.ts +18 -0
- package/lib/index.js +172 -0
- package/lib/index.js.map +1 -0
- package/lib/pure.d.ts +35 -0
- package/lib/pure.js +71 -0
- package/lib/pure.js.map +1 -0
- package/models.lock.json +63 -0
- package/package.json +39 -4
- package/schema/decision-choose.input.json +22 -0
- package/schema/decision-choose.output.json +20 -0
- package/schema/decision-score.input.json +18 -0
- package/schema/decision-score.output.json +18 -0
- package/schema/decision-test.input.json +10 -0
- package/schema/decision-test.output.json +18 -0
- package/tool-mode.extension.json +87 -0
- package/vendor/LICENSE.laya-ts +176 -0
- package/vendor/laya-ts/agent.d.ts +216 -0
- package/vendor/laya-ts/agent.js +631 -0
- package/vendor/laya-ts/common.d.ts +167 -0
- package/vendor/laya-ts/common.js +478 -0
- package/vendor/laya-ts/dx.d.ts +17 -0
- package/vendor/laya-ts/dx.js +46 -0
- package/vendor/laya-ts/email.d.ts +2 -0
- package/vendor/laya-ts/email.js +184 -0
- package/vendor/laya-ts/hooks.d.ts +134 -0
- package/vendor/laya-ts/hooks.js +379 -0
- package/vendor/laya-ts/index.d.ts +22 -0
- package/vendor/laya-ts/index.js +13 -0
- package/vendor/laya-ts/lang.d.ts +24 -0
- package/vendor/laya-ts/lang.js +590 -0
- package/vendor/laya-ts/presets.d.ts +5 -0
- package/vendor/laya-ts/presets.js +175 -0
- package/vendor/laya-ts/providers.d.ts +67 -0
- package/vendor/laya-ts/providers.js +668 -0
- package/vendor/laya-ts/router.d.ts +186 -0
- package/vendor/laya-ts/router.js +757 -0
- package/vendor/laya-ts/shortlist.d.ts +65 -0
- package/vendor/laya-ts/shortlist.js +407 -0
- package/vendor/laya-ts/structured.d.ts +89 -0
- package/vendor/laya-ts/structured.js +256 -0
- package/vendor/laya-ts/tokenizer.d.ts +66 -0
- package/vendor/laya-ts/tokenizer.js +482 -0
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
/** Special ids of the laya ModernBERT checkpoint (HF added_tokens). */
|
|
2
|
+
export const CHECKPOINT_IDS = { cls: 50281, sep: 50282, mask: 50284, pad: 50283, unk: 50280 };
|
|
3
|
+
/** Alias lookup order per special: ModernBERT `[X]` names first, Gemma `<x>` names after. */
|
|
4
|
+
export const SPECIAL_ALIASES = {
|
|
5
|
+
cls: ["[CLS]", "<bos>", "<s>"],
|
|
6
|
+
sep: ["[SEP]", "<eos>", "</s>"],
|
|
7
|
+
pad: ["[PAD]", "<pad>"],
|
|
8
|
+
mask: ["[MASK]", "<mask>"],
|
|
9
|
+
unk: ["[UNK]", "<unk>"],
|
|
10
|
+
};
|
|
11
|
+
/** Metaspace word-boundary marker (HF SentencePiece-style replacement for ' '). */
|
|
12
|
+
export const METASPACE_REPLACEMENT = "▁";
|
|
13
|
+
/** GPT-2 byte<->unicode table (same mapping as HF ByteLevel pre-tokenizer). */
|
|
14
|
+
function byteUnicodeMaps() {
|
|
15
|
+
const b2u = new Map();
|
|
16
|
+
const u2b = new Map();
|
|
17
|
+
const extra = (n) => (n < 0x100 ? n + 0x100 : n);
|
|
18
|
+
const ranges = [[0x21, 0x7e], [0xa1, 0xac], [0xae, 0xff]];
|
|
19
|
+
let k = 0;
|
|
20
|
+
const inRange = (b) => ranges.some(([lo, hi]) => b >= lo && b <= hi);
|
|
21
|
+
for (let b = 0; b < 256; b++) {
|
|
22
|
+
const cp = inRange(b) ? b : extra(k++);
|
|
23
|
+
b2u.set(b, String.fromCodePoint(cp));
|
|
24
|
+
u2b.set(String.fromCodePoint(cp), b);
|
|
25
|
+
}
|
|
26
|
+
return { b2u, u2b };
|
|
27
|
+
}
|
|
28
|
+
let cached = null;
|
|
29
|
+
function maps() {
|
|
30
|
+
if (!cached)
|
|
31
|
+
cached = byteUnicodeMaps();
|
|
32
|
+
return cached;
|
|
33
|
+
}
|
|
34
|
+
/** GPT-2 pre-tokenizer split (HF ByteLevel use_regex=true). */
|
|
35
|
+
const GPT2_SPLIT = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
|
|
36
|
+
/** Piece length at or above which `bpeWord` uses the heap.
|
|
37
|
+
*
|
|
38
|
+
* Its job is to leave the pieces prose is made of on code that did not change. English prose
|
|
39
|
+
* pieces measure a five-byte median with the checkpoint tokenizer (p90 eight, longest eleven),
|
|
40
|
+
* so essentially all of them take the inline rescan below -- byte for byte the loop that
|
|
41
|
+
* shipped before this change, reached in exactly one call as before. That is a regression-proofing choice, not a tuned one.
|
|
42
|
+
*
|
|
43
|
+
* It is deliberately not the break-even point. Per call the two forms cross over nearer six to
|
|
44
|
+
* eight bytes, and swept end to end at 0, 4, 6, 8, 12, 16, 24 and 32 the difference on 8 000
|
|
45
|
+
* characters of English stayed inside +/-5% at every setting -- below what the measurement can
|
|
46
|
+
* resolve. With the threshold in place English provably cannot regress, because it does not
|
|
47
|
+
* reach the new code at all; without it the cost was under 1% and indistinguishable from noise
|
|
48
|
+
* in 200 interleaved rounds. Both are defensible; this one needs no benchmark to believe.
|
|
49
|
+
*
|
|
50
|
+
* What is not noise is what happens past this line, where the rescan is quadratic and the heap
|
|
51
|
+
* is the only form that stays usable.
|
|
52
|
+
*/
|
|
53
|
+
const HEAP_MIN_LEN = 32;
|
|
54
|
+
/** Merge one word's chars greedily by merge rank: lowest rank wins, leftmost breaks a tie.
|
|
55
|
+
*
|
|
56
|
+
* Short pieces take the rescan inlined below, the loop that shipped before this change; long
|
|
57
|
+
* ones take the heap, which is the only form that stays usable when a piece is an entire state.
|
|
58
|
+
* Both forms follow the same rule and return the same tokens -- the tests assert that at every
|
|
59
|
+
* length from 0 to 200 across the boundary.
|
|
60
|
+
*
|
|
61
|
+
* This has to stay near-linear, because the piece reaching it can be an entire state. Both
|
|
62
|
+
* encoders that call it cut only at spaces: `metaspaceEncode` at the metaspace marker and at
|
|
63
|
+
* newline runs, `bpeEncode` on GPT2_SPLIT, whose ` ?\p{L}+` takes a maximal run of letters. A
|
|
64
|
+
* Chinese or Japanese state has no spaces, so it arrives here as one piece -- and this used to
|
|
65
|
+
* rescan the whole word for its best pair and rebuild the array once per merge, which is
|
|
66
|
+
* O(n^2). 8000 unspaced characters cost 1.41 s (Chinese) and 1.60 s (Japanese) through
|
|
67
|
+
* `metaspaceEncode` with mmBERT's tokenizer, against 1.9 ms for English prose of the same
|
|
68
|
+
* length, growing 4x per doubling. Both encoders are synchronous, so that was the whole event
|
|
69
|
+
* loop rather than one slow request.
|
|
70
|
+
*
|
|
71
|
+
* The word is a doubly linked list over the original slots, so merging is a relink rather than
|
|
72
|
+
* an array rebuild, and the candidate pairs live in a binary min-heap keyed on (rank, slot). A
|
|
73
|
+
* slot only ever absorbs the neighbour to its right, so slot indices stay in text order and
|
|
74
|
+
* ordering heap ties by slot index is exactly the leftmost tie-break a left-to-right rescan
|
|
75
|
+
* gets for free.
|
|
76
|
+
*
|
|
77
|
+
* One merge invalidates at most two pairs: the merged slot's own, and the one starting at its
|
|
78
|
+
* left neighbour. Deleting from a heap costs more than re-pushing, so each slot carries a
|
|
79
|
+
* version counter and a popped entry whose version has moved on is skipped -- standard lazy
|
|
80
|
+
* deletion. A matching version is itself proof the pair still has the rank it was pushed with,
|
|
81
|
+
* because `version` moves whenever the slot's text, its right neighbour, or that neighbour's
|
|
82
|
+
* text changes; there is no need to look the rank up again on the way out.
|
|
83
|
+
*
|
|
84
|
+
* Three details are what make this pay rather than merely scale, and together they are worth
|
|
85
|
+
* 1.2-1.3x over the same algorithm written the obvious way. The heap lives in three
|
|
86
|
+
* `Int32Array`s instead of a JS array of tuples, so pushing costs no allocation. Its capacity
|
|
87
|
+
* is derived rather than guessed, so it never grows in practice -- see the note on it below.
|
|
88
|
+
* And both sifts move the hole instead of swapping, one write per level rather than three.
|
|
89
|
+
*
|
|
90
|
+
* Merge *selection* is O(log n), so the call is O(n log n) for the token lengths a learned
|
|
91
|
+
* table produces. `offer` still builds the key `tok[slot] + " " + tok[j]`, which costs the
|
|
92
|
+
* length of those tokens, so a contrived table that grows a single token to O(n) stays
|
|
93
|
+
* quadratic in key construction alone -- measured on such a table it grows 4x or worse per
|
|
94
|
+
* doubling and is only 2.8-3.9x faster than the rescan. Real tables cap token length far below
|
|
95
|
+
* n, which is why the checkpoint tokenizers measure linear here.
|
|
96
|
+
*/
|
|
97
|
+
function bpeWord(chars, rank) {
|
|
98
|
+
if (chars.length >= HEAP_MIN_LEN)
|
|
99
|
+
return bpeWordHeap(chars, rank);
|
|
100
|
+
// The rescan stays inline rather than in its own function, so a short piece costs exactly one
|
|
101
|
+
// call as it did before -- routing it through a helper added a second call frame, and at ~10 ns
|
|
102
|
+
// over the 2 824 pieces in 8 000 characters of English prose that measured as a real 0.8%.
|
|
103
|
+
let word = chars.slice();
|
|
104
|
+
if (word.length <= 1)
|
|
105
|
+
return word;
|
|
106
|
+
for (;;) {
|
|
107
|
+
let best = Infinity, idx = -1;
|
|
108
|
+
for (let i = 0; i < word.length - 1; i++) {
|
|
109
|
+
const r = rank.get(word[i] + " " + word[i + 1]);
|
|
110
|
+
if (r !== undefined && r < best) {
|
|
111
|
+
best = r;
|
|
112
|
+
idx = i;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (idx < 0)
|
|
116
|
+
return word;
|
|
117
|
+
word = [...word.slice(0, idx), word[idx] + word[idx + 1], ...word.slice(idx + 2)];
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** The same rule in O(n log n): pairs chosen from a min-heap over a linked list of the slots. */
|
|
121
|
+
function bpeWordHeap(chars, rank) {
|
|
122
|
+
const n = chars.length;
|
|
123
|
+
const tok = chars.slice();
|
|
124
|
+
if (n <= 1)
|
|
125
|
+
return tok;
|
|
126
|
+
const next = new Int32Array(n), prev = new Int32Array(n);
|
|
127
|
+
const version = new Int32Array(n);
|
|
128
|
+
const dead = new Uint8Array(n);
|
|
129
|
+
for (let i = 0; i < n; i++) {
|
|
130
|
+
prev[i] = i - 1;
|
|
131
|
+
next[i] = i + 1 < n ? i + 1 : -1;
|
|
132
|
+
}
|
|
133
|
+
// 3n is a bound, not a hope: at most n-1 pairs are offered up front, every merge kills exactly
|
|
134
|
+
// one slot so there are at most n-1 merges, and each offers at most two pairs -- 3n-3 pushes
|
|
135
|
+
// worst case. Measured over 120 000 inputs, including tables built to maximise pushes, the
|
|
136
|
+
// high-water mark is 2n. The grow below still exists because an out-of-bounds typed-array
|
|
137
|
+
// write is silently dropped in JS, which would cost a merge and emit wrong tokens with no
|
|
138
|
+
// error at all: too quiet a failure to leave resting on a proof. It costs under 1%.
|
|
139
|
+
let heapCap = 3 * n;
|
|
140
|
+
let heapRank = new Int32Array(heapCap), heapSlot = new Int32Array(heapCap), heapVer = new Int32Array(heapCap);
|
|
141
|
+
let heapLen = 0;
|
|
142
|
+
/** Offer the pair starting at `slot`, when it has a right neighbour and a rank. Sifts up by
|
|
143
|
+
* moving the hole down toward the root, writing the new entry once at the end. */
|
|
144
|
+
const offer = (slot) => {
|
|
145
|
+
const j = next[slot];
|
|
146
|
+
if (j < 0)
|
|
147
|
+
return;
|
|
148
|
+
const r = rank.get(tok[slot] + " " + tok[j]);
|
|
149
|
+
if (r === undefined)
|
|
150
|
+
return;
|
|
151
|
+
if (heapLen === heapCap) {
|
|
152
|
+
heapCap *= 2;
|
|
153
|
+
const r2 = new Int32Array(heapCap);
|
|
154
|
+
r2.set(heapRank);
|
|
155
|
+
heapRank = r2;
|
|
156
|
+
const s2 = new Int32Array(heapCap);
|
|
157
|
+
s2.set(heapSlot);
|
|
158
|
+
heapSlot = s2;
|
|
159
|
+
const v2 = new Int32Array(heapCap);
|
|
160
|
+
v2.set(heapVer);
|
|
161
|
+
heapVer = v2;
|
|
162
|
+
}
|
|
163
|
+
const ver = version[slot];
|
|
164
|
+
let c = heapLen++;
|
|
165
|
+
while (c > 0) {
|
|
166
|
+
const p = (c - 1) >> 1;
|
|
167
|
+
if (heapRank[p] < r || (heapRank[p] === r && heapSlot[p] < slot))
|
|
168
|
+
break;
|
|
169
|
+
heapRank[c] = heapRank[p];
|
|
170
|
+
heapSlot[c] = heapSlot[p];
|
|
171
|
+
heapVer[c] = heapVer[p];
|
|
172
|
+
c = p;
|
|
173
|
+
}
|
|
174
|
+
heapRank[c] = r;
|
|
175
|
+
heapSlot[c] = slot;
|
|
176
|
+
heapVer[c] = ver;
|
|
177
|
+
};
|
|
178
|
+
for (let i = 0; i < n - 1; i++)
|
|
179
|
+
offer(i);
|
|
180
|
+
while (heapLen > 0) {
|
|
181
|
+
const slot = heapSlot[0], ver = heapVer[0];
|
|
182
|
+
// Pop: take the last entry and sift it down through the hole left at the root.
|
|
183
|
+
const lastRank = heapRank[--heapLen], lastSlot = heapSlot[heapLen], lastVer = heapVer[heapLen];
|
|
184
|
+
if (heapLen > 0) {
|
|
185
|
+
let c = 0;
|
|
186
|
+
for (;;) {
|
|
187
|
+
const l = 2 * c + 1;
|
|
188
|
+
if (l >= heapLen)
|
|
189
|
+
break;
|
|
190
|
+
const r = l + 1;
|
|
191
|
+
let m = l;
|
|
192
|
+
if (r < heapLen && (heapRank[r] < heapRank[l]
|
|
193
|
+
|| (heapRank[r] === heapRank[l] && heapSlot[r] < heapSlot[l])))
|
|
194
|
+
m = r;
|
|
195
|
+
if (heapRank[m] > lastRank || (heapRank[m] === lastRank && heapSlot[m] > lastSlot))
|
|
196
|
+
break;
|
|
197
|
+
heapRank[c] = heapRank[m];
|
|
198
|
+
heapSlot[c] = heapSlot[m];
|
|
199
|
+
heapVer[c] = heapVer[m];
|
|
200
|
+
c = m;
|
|
201
|
+
}
|
|
202
|
+
heapRank[c] = lastRank;
|
|
203
|
+
heapSlot[c] = lastSlot;
|
|
204
|
+
heapVer[c] = lastVer;
|
|
205
|
+
}
|
|
206
|
+
if (dead[slot] || version[slot] !== ver)
|
|
207
|
+
continue; // superseded by a later merge
|
|
208
|
+
const j = next[slot];
|
|
209
|
+
if (j < 0 || dead[j])
|
|
210
|
+
continue;
|
|
211
|
+
tok[slot] = tok[slot] + tok[j];
|
|
212
|
+
dead[j] = 1;
|
|
213
|
+
const k = next[j];
|
|
214
|
+
next[slot] = k;
|
|
215
|
+
if (k >= 0)
|
|
216
|
+
prev[k] = slot;
|
|
217
|
+
version[slot]++;
|
|
218
|
+
offer(slot);
|
|
219
|
+
const p = prev[slot];
|
|
220
|
+
if (p >= 0) {
|
|
221
|
+
version[p]++;
|
|
222
|
+
offer(p);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const out = [];
|
|
226
|
+
for (let i = 0; i >= 0; i = next[i])
|
|
227
|
+
out.push(tok[i]);
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
/** Byte-level BPE encode: NFC-normalize, NO lowercasing, GPT-2 byte map + rank-order merges. */
|
|
231
|
+
let sharedEncoder = null;
|
|
232
|
+
export function bpeEncode(vocab, merges, text) {
|
|
233
|
+
const { b2u } = maps();
|
|
234
|
+
const unkId = vocab.get("[UNK]") ?? CHECKPOINT_IDS.unk;
|
|
235
|
+
const out = [];
|
|
236
|
+
const enc = (sharedEncoder ??= new TextEncoder());
|
|
237
|
+
const parts = text.normalize("NFC").match(GPT2_SPLIT);
|
|
238
|
+
if (!parts)
|
|
239
|
+
return out;
|
|
240
|
+
for (const piece of parts) {
|
|
241
|
+
const chars = [];
|
|
242
|
+
for (const b of enc.encode(piece))
|
|
243
|
+
chars.push(b2u.get(b) ?? "");
|
|
244
|
+
for (const tok of bpeWord(chars, merges))
|
|
245
|
+
out.push(vocab.get(tok) ?? unkId);
|
|
246
|
+
}
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
/** Metaspace (SentencePiece-style) BPE encode: unicode chars, NO byte map, NO lowercasing.
|
|
250
|
+
* Normalizer replaces run first, then one marker is ensured at text start, then the text
|
|
251
|
+
* is cut into words at each marker (marker kept as word prefix) with maximal `\n` runs
|
|
252
|
+
* as their own pieces. Each piece is BPE-merged; leftover unknown pieces map to unk. */
|
|
253
|
+
export function metaspaceEncode(vocab, merges, text, unkId, replaces = [[" ", METASPACE_REPLACEMENT]], byteFallback = false) {
|
|
254
|
+
const unk = unkId ?? vocab.get("<unk>") ?? vocab.get("[UNK]") ?? CHECKPOINT_IDS.unk;
|
|
255
|
+
if (!text)
|
|
256
|
+
return [];
|
|
257
|
+
let t = text;
|
|
258
|
+
for (const [from, to] of replaces)
|
|
259
|
+
t = t.split(from).join(to);
|
|
260
|
+
const out = [];
|
|
261
|
+
const push = (piece) => {
|
|
262
|
+
for (const tok of bpeWord(Array.from(piece), merges)) {
|
|
263
|
+
const id = vocab.get(tok);
|
|
264
|
+
if (id !== undefined) {
|
|
265
|
+
out.push(id);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const bytes = byteFallback
|
|
269
|
+
? Array.from((sharedEncoder ??= new TextEncoder()).encode(tok), (b) => vocab.get(`<0x${b.toString(16).toUpperCase().padStart(2, "0")}>`))
|
|
270
|
+
: [];
|
|
271
|
+
if (bytes.length > 0 && bytes.every((b) => b !== undefined))
|
|
272
|
+
out.push(...bytes);
|
|
273
|
+
else
|
|
274
|
+
out.push(unk);
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
for (const seg of t.split(/(\n+)/)) {
|
|
278
|
+
if (!seg)
|
|
279
|
+
continue;
|
|
280
|
+
if (seg[0] === "\n") {
|
|
281
|
+
push(seg);
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
const w = seg.startsWith(METASPACE_REPLACEMENT) ? seg : METASPACE_REPLACEMENT + seg;
|
|
285
|
+
for (const chunk of w.split(METASPACE_REPLACEMENT).slice(1)) {
|
|
286
|
+
push(chunk ? METASPACE_REPLACEMENT + chunk : METASPACE_REPLACEMENT);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
function encodeSegment(data, text) {
|
|
293
|
+
return data.kind === "metaspace"
|
|
294
|
+
? metaspaceEncode(data.vocab, data.merges, text, data.ids.unk, data.replaces, data.byteFallback)
|
|
295
|
+
: bpeEncode(data.vocab, data.merges, text);
|
|
296
|
+
}
|
|
297
|
+
/** Regex source for `words`, longest match first, as a prefix tree: one branch per next character
|
|
298
|
+
* rather than one alternative per token, so a scan does not try every token at every position. */
|
|
299
|
+
function trieSource(words) {
|
|
300
|
+
const root = { kids: new Map(), end: false };
|
|
301
|
+
for (const w of words) {
|
|
302
|
+
let n = root;
|
|
303
|
+
for (const ch of w) {
|
|
304
|
+
let k = n.kids.get(ch);
|
|
305
|
+
if (!k)
|
|
306
|
+
n.kids.set(ch, (k = { kids: new Map(), end: false }));
|
|
307
|
+
n = k;
|
|
308
|
+
}
|
|
309
|
+
n.end = true;
|
|
310
|
+
}
|
|
311
|
+
const walk = (n) => {
|
|
312
|
+
const alts = [...n.kids].map(([c, k]) => c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + walk(k));
|
|
313
|
+
if (!alts.length)
|
|
314
|
+
return "";
|
|
315
|
+
const body = alts.length === 1 ? alts[0] : "(?:" + alts.join("|") + ")";
|
|
316
|
+
return n.end ? "(?:" + body + ")?" : body;
|
|
317
|
+
};
|
|
318
|
+
return walk(root);
|
|
319
|
+
}
|
|
320
|
+
const addedPhases = new WeakMap();
|
|
321
|
+
/** HF matches added tokens that are not `normalized` on the raw text first, then the `normalized` ones
|
|
322
|
+
* on what is left. */
|
|
323
|
+
function phasesOf(data) {
|
|
324
|
+
let phases = addedPhases.get(data);
|
|
325
|
+
if (!phases) {
|
|
326
|
+
phases = [false, true].flatMap((normalized) => {
|
|
327
|
+
const toks = (data.added ?? []).filter((t) => t.normalized === normalized && t.content);
|
|
328
|
+
if (!toks.length)
|
|
329
|
+
return [];
|
|
330
|
+
const re = new RegExp(trieSource(toks.map((t) => t.content)), "gu");
|
|
331
|
+
return [{ re, byContent: new Map(toks.map((t) => [t.content, t])), normalized }];
|
|
332
|
+
});
|
|
333
|
+
addedPhases.set(data, phases);
|
|
334
|
+
}
|
|
335
|
+
return phases;
|
|
336
|
+
}
|
|
337
|
+
function splitOnAdded(text, { re, byContent }) {
|
|
338
|
+
const out = [];
|
|
339
|
+
let last = 0;
|
|
340
|
+
for (const m of text.matchAll(re)) {
|
|
341
|
+
const tok = byContent.get(m[0]);
|
|
342
|
+
let before = text.slice(last, m.index);
|
|
343
|
+
if (tok.lstrip)
|
|
344
|
+
before = before.trimEnd();
|
|
345
|
+
if (before)
|
|
346
|
+
out.push(before);
|
|
347
|
+
out.push(tok);
|
|
348
|
+
last = m.index + m[0].length;
|
|
349
|
+
if (tok.rstrip)
|
|
350
|
+
while (last < text.length && /\s/u.test(text[last]))
|
|
351
|
+
last++;
|
|
352
|
+
}
|
|
353
|
+
if (last < text.length)
|
|
354
|
+
out.push(text.slice(last));
|
|
355
|
+
return out;
|
|
356
|
+
}
|
|
357
|
+
/** Dispatch to the Metaspace or GPT-2/ByteLevel encoder, after cutting out added tokens as HF does. */
|
|
358
|
+
export function encodeWithData(data, text) {
|
|
359
|
+
let pieces = [text];
|
|
360
|
+
for (const phase of phasesOf(data)) {
|
|
361
|
+
pieces = pieces.flatMap((p) => {
|
|
362
|
+
if (typeof p !== "string")
|
|
363
|
+
return [p];
|
|
364
|
+
return splitOnAdded(phase.normalized && data.kind === "bytelevel" ? p.normalize("NFC") : p, phase);
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
const out = [];
|
|
368
|
+
for (const p of pieces) {
|
|
369
|
+
if (typeof p === "string")
|
|
370
|
+
out.push(...encodeSegment(data, p));
|
|
371
|
+
else
|
|
372
|
+
out.push(p.id);
|
|
373
|
+
}
|
|
374
|
+
return out;
|
|
375
|
+
}
|
|
376
|
+
function childNodes(node) {
|
|
377
|
+
if (!node || typeof node !== "object")
|
|
378
|
+
return [];
|
|
379
|
+
const o = node;
|
|
380
|
+
const out = [];
|
|
381
|
+
for (const k of ["normalizers", "pre_tokenizers", "decoders"]) {
|
|
382
|
+
const v = o[k];
|
|
383
|
+
if (Array.isArray(v))
|
|
384
|
+
out.push(...v);
|
|
385
|
+
}
|
|
386
|
+
return out;
|
|
387
|
+
}
|
|
388
|
+
/** True when a normalizer/pre-tokenizer/decoder node (or nested Sequence member) has a type. */
|
|
389
|
+
function hasNodeType(node, want) {
|
|
390
|
+
if (!node || typeof node !== "object")
|
|
391
|
+
return false;
|
|
392
|
+
if (node["type"] === want)
|
|
393
|
+
return true;
|
|
394
|
+
return childNodes(node).some((c) => hasNodeType(c, want));
|
|
395
|
+
}
|
|
396
|
+
/** Collect normalizer Replace rules ({pattern: {String}, content}) in order. */
|
|
397
|
+
function collectReplaces(node, out) {
|
|
398
|
+
if (!node || typeof node !== "object")
|
|
399
|
+
return;
|
|
400
|
+
const o = node;
|
|
401
|
+
if (o["type"] === "Replace") {
|
|
402
|
+
const pat = o["pattern"];
|
|
403
|
+
const from = pat?.["String"];
|
|
404
|
+
const to = o["content"];
|
|
405
|
+
if (typeof from === "string" && typeof to === "string")
|
|
406
|
+
out.push([from, to]);
|
|
407
|
+
}
|
|
408
|
+
for (const c of childNodes(node))
|
|
409
|
+
collectReplaces(c, out);
|
|
410
|
+
}
|
|
411
|
+
/** Parse an HF tokenizer.json ({model vocab/merges, normalizer, pre_tokenizer, added_tokens}). */
|
|
412
|
+
export function parseTokenizerJson(raw) {
|
|
413
|
+
try {
|
|
414
|
+
const r = raw;
|
|
415
|
+
const vocabObj = r?.model?.vocab;
|
|
416
|
+
if (!vocabObj || typeof vocabObj !== "object")
|
|
417
|
+
return null;
|
|
418
|
+
const vocab = new Map(Object.entries(vocabObj));
|
|
419
|
+
const merges = new Map();
|
|
420
|
+
for (const [i, m] of (r.model?.merges ?? []).entries()) {
|
|
421
|
+
const pair = typeof m === "string" ? m.split(" ") : m;
|
|
422
|
+
if (pair.length >= 2)
|
|
423
|
+
merges.set(pair[0] + " " + pair[1], i);
|
|
424
|
+
}
|
|
425
|
+
const added = new Map();
|
|
426
|
+
const addedTokens = [];
|
|
427
|
+
for (const t of r.added_tokens ?? []) {
|
|
428
|
+
if (typeof t?.content === "string" && typeof t?.id === "number") {
|
|
429
|
+
added.set(t.content, t.id);
|
|
430
|
+
addedTokens.push({
|
|
431
|
+
content: t.content, id: t.id,
|
|
432
|
+
normalized: t.normalized === true, lstrip: t.lstrip === true, rstrip: t.rstrip === true,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const pick = (aliases, fb) => {
|
|
437
|
+
for (const a of aliases) {
|
|
438
|
+
const v = added.get(a) ?? vocab.get(a);
|
|
439
|
+
if (v !== undefined)
|
|
440
|
+
return { id: v, token: a };
|
|
441
|
+
}
|
|
442
|
+
return { id: fb, token: aliases[0] };
|
|
443
|
+
};
|
|
444
|
+
const cls = pick(SPECIAL_ALIASES.cls, CHECKPOINT_IDS.cls);
|
|
445
|
+
const sep = pick(SPECIAL_ALIASES.sep, CHECKPOINT_IDS.sep);
|
|
446
|
+
const mask = pick(SPECIAL_ALIASES.mask, CHECKPOINT_IDS.mask);
|
|
447
|
+
const pad = pick(SPECIAL_ALIASES.pad, CHECKPOINT_IDS.pad);
|
|
448
|
+
const unk = pick(SPECIAL_ALIASES.unk, CHECKPOINT_IDS.unk);
|
|
449
|
+
const kind = hasNodeType(r?.pre_tokenizer, "Metaspace") ? "metaspace" : "bytelevel";
|
|
450
|
+
const replaces = [];
|
|
451
|
+
collectReplaces(r?.normalizer, replaces);
|
|
452
|
+
if (kind === "metaspace" && replaces.length === 0)
|
|
453
|
+
replaces.push([" ", METASPACE_REPLACEMENT]);
|
|
454
|
+
return {
|
|
455
|
+
vocab, merges,
|
|
456
|
+
ids: { cls: cls.id, sep: sep.id, mask: mask.id, pad: pad.id, unk: unk.id },
|
|
457
|
+
kind,
|
|
458
|
+
maskToken: mask.token,
|
|
459
|
+
replaces,
|
|
460
|
+
byteFallback: r.model?.byte_fallback === true,
|
|
461
|
+
added: addedTokens,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
/** Load an HF tokenizer.json from a local path (node) or URL into vocab/merges/ids. */
|
|
469
|
+
export async function loadTokenizerJson(pathOrUrl) {
|
|
470
|
+
let raw;
|
|
471
|
+
if (/^https?:\/\//.test(pathOrUrl)) {
|
|
472
|
+
const res = await fetch(pathOrUrl);
|
|
473
|
+
if (!res.ok)
|
|
474
|
+
return null;
|
|
475
|
+
raw = await res.json();
|
|
476
|
+
}
|
|
477
|
+
else {
|
|
478
|
+
const fs = await import("node:fs/promises");
|
|
479
|
+
raw = JSON.parse(await fs.readFile(pathOrUrl, "utf8"));
|
|
480
|
+
}
|
|
481
|
+
return parseTokenizerJson(raw);
|
|
482
|
+
}
|