ArthurZ HF Staff commited on
Commit
f387af4
·
verified ·
1 Parent(s): bff358e
Files changed (1) hide show
  1. TAG_CLASSIFY_SPEC.md +171 -0
TAG_CLASSIFY_SPEC.md ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tag-classify pretokenization — design spec
2
+
3
+ **Principle (simdjson move):** compute a per-char **tag** stream in *one* SIMD pass, then every
4
+ pretokenizer is a cheap consumer over that stream. Two orthogonal tag alphabets (**atoms** for
5
+ category-based pretokenizers, **scripts** for `UnicodeScripts`) are produced by the *same* generic
6
+ range-classify engine — only the tables differ. 0-dep at runtime (tables bake to `const`;
7
+ `unicode_categories` is a dev-only *generator* dep, like `bitmap_gen`).
8
+
9
+ ```
10
+ ┌── classify<Lanes, Table> ──► tag[] (one SIMD pass, char-start aligned)
11
+ text (UTF-8 bytes) ───┤
12
+ └── char-start bitplane (for multibyte / char-count)
13
+
14
+ tag = ATOM (u4) │ tag = SCRIPT (u8)
15
+ │ │ │
16
+ ├ remap(vqtbl1) → class-view ───┤ └ FSM: split on script change
17
+ │ │ (Common/Any/Inherited transparent)
18
+ ├ RunSplit FSM (SIMD boundary + extract) ← WhitespaceSplit, Whitespace, Punctuation, Digits, Bert
19
+ └ Cl100k/ByteLevel FSM (scalar, segmented) ← cl100k, GPT-2
20
+ ```
21
+
22
+ ---
23
+
24
+ ## 1. The atom alphabet (12 tags, fits `u4`)
25
+
26
+ Derived by enumerating all 1.1M codepoints against the exact predicates in the pretokenizer code
27
+ (`scratchpad/atomgen`). 10 base atoms + the two ASCII specials promoted (Space, Apostrophe).
28
+
29
+ | # | atom | definition | example |
30
+ |---|---|---|---|
31
+ | 0 | `Letter` | `\p{L}` | `a 中 é` |
32
+ | 1 | `NumWord` | `Nd ∪ Nl` (numeric **and** `\w`) | `0-9 Ⅷ ٠` |
33
+ | 2 | `NumOther` | `No` (numeric, not `\w`) | `½ ² ¼` |
34
+ | 3 | `Newline` | `\r \n` | |
35
+ | 4 | `Space` | `0x20` only | ` ` |
36
+ | 5 | `WsOther` | `\s ∖ {\r\n, 0x20}` | `\t` NBSP U+2028 |
37
+ | 6 | `Mark` | `\p{M} ∪ {ZWJ,ZWNJ} ∪ (Other_Alphabetic∖L)` | combining marks |
38
+ | 7 | `Connector` | `\p{Pc}` | `_ ‿` |
39
+ | 8 | `Punct` | `(\p{P}∖Pc) ∪ ASCII-sym`, minus `0x27` | `! . , + = < $` |
40
+ | 9 | `Apostrophe` | `0x27` only | `'` |
41
+ | 10 | `SymOther` | non-ASCII `\p{S}` ∪ control ∪ unassigned | `× ©` U+0000 |
42
+ | 11 | `NumericOther` | `is_numeric ∖ \p{N}` | numeric-typed non-numbers |
43
+
44
+ `Cont` (continuation byte) is the 13th value or, equivalently, tag `0xFF` + `char_start=0`; it's
45
+ transparent to every FSM. Base predicates that forced the split (proven, not guessed):
46
+ `is_alphabetic ≠ \p{L}` (27043 cps), `is_numeric ≠ \p{N}` (478 cps → atom 11), ASCII-vs-Unicode
47
+ symbol asymmetry (ASCII sym → 8, non-ASCII sym → 10).
48
+
49
+ ## 2. The generic classify engine (composable lanes)
50
+
51
+ `classify` walks 16-byte chunks. Per chunk it runs **lanes**, each gated by a cheap
52
+ `vmaxvq` range test so ASCII-only chunks skip the multibyte lanes entirely. Every lane maps its
53
+ byte-region to a tag; the *structure* is shared across tag alphabets, only the per-lane **table**
54
+ changes. A `Classifier` = an ordered set of lanes + their tables.
55
+
56
+ | lane | byte range | mechanism | shared? |
57
+ |---|---|---|---|
58
+ | **ASCII** | `< 0x80` | `LUT128[byte] → tag` (nibble-shuffle / range) | structure shared; table per-alphabet |
59
+ | **2-byte** | `C2–DF` | codepoint bitmap (`vqtbl` `LETTER2`…) *or* range | per-alphabet |
60
+ | **CJK** | `E3–EC` | lead-byte range → tag (atoms: `Letter`; scripts: `Han`) | structure shared |
61
+ | **3-byte-other** | `E0–E2, ED–EF` | **SIMD range-search** (Thai/Devanagari; the must-fix) | structure shared |
62
+ | **4-byte** | `F0+` | SIMD range-search (rare) | structure shared |
63
+ | **cont** | `80–BF` | tag = `Cont`, `char_start=0` | shared |
64
+
65
+ **SIMD range-search kernel** (used by the 3-byte/4-byte lanes, and the whole script classifier):
66
+ a sorted threshold list classifies branchlessly by *counting thresholds cleared* —
67
+ `range_id = Σᵢ (cp ≥ tᵢ)` via broadcast `vcgeq` + accumulate, then `tag = TAG_LUT[range_id]`
68
+ (a `vqtbl1`). No binary search, no data-dependent branches, 16 lanes at a time. This is why the
69
+ 3-byte-non-CJK marks/letters gap has **no scalar slow path**.
70
+
71
+ Output: `tag[]` (one byte per input byte; continuation bytes = `Cont`) + a `char_start` bitplane.
72
+
73
+ ## 3. Composition: atoms and scripts are the same engine
74
+
75
+ ```
76
+ AtomClassifier = { ASCII: ATOM_ASCII_LUT, 2byte: ATOM_BITMAPS, CJK: →Letter,
77
+ 3byte: ATOM_GC_RANGES, 4byte: ATOM_GC_RANGES }
78
+ ScriptClassifier = { ASCII: SCRIPT_ASCII_LUT (mostly Common/Latin), 2byte: SCRIPT_RANGES,
79
+ CJK: →Han, 3byte: SCRIPT_RANGES, 4byte: SCRIPT_RANGES }
80
+ ```
81
+
82
+ Same lane code, same gating, same SIMD range kernel — swap the tables. `UnicodeScripts`'
83
+ `fixed_script` (Hira/Kata→Han, space→Any) is a post-remap, the same slot atoms use. So
84
+ `UnicodeScripts` reuses the entire classify + FSM framework; it is *not* a second system, it's a
85
+ second instantiation. (Script ⊥ atom at the *value* level — `'a'`/`'а'`/`'中'` are one atom, three
86
+ scripts — so they remain separate streams; you run whichever the configured pretokenizer needs.)
87
+
88
+ ## 4. Pretokenizer interface
89
+
90
+ ```
91
+ PreTokenizer = {
92
+ classifier: &Classifier, // Atoms (almost always) or Scripts
93
+ remap: Remap, // tag → consumer class
94
+ fsm: Fsm, // class-view → spans
95
+ }
96
+ ```
97
+
98
+ - **`Remap`**: for `≤16` tags (atoms) it's a **16-byte `vqtbl1`** table — 16 chars remapped in one
99
+ instruction. For scripts (`>16` tags) there is no small remap; the FSM compares script-ids directly.
100
+ - **`Fsm`** kinds (all local over the remapped tag view; the boundary stream is `tag ∈ mask`):
101
+ - `Split { delim_mask, behavior }` — the HF delimiter split. A char is a *match* iff `tag ∈
102
+ delim_mask`; matches are per-char, non-matches are runs; then `behavior ∈ {Removed, Isolated,
103
+ Contiguous, MergedWithPrevious, MergedWithNext}` places boundaries / drops the match segments
104
+ exactly as `SplitDelimiterBehavior` (normalizer.rs). Covers WhitespaceSplit (`WS`,Removed),
105
+ Punctuation (`Punct∪Pc∪Apostrophe`,Isolated), Digits (`numeric`,Contiguous),
106
+ Metaspace (`Space→▁`,MergedWithNext), CharDelimiterSplit (byte), Split-literal.
107
+ → SIMD class-change → movemask → `extract`; `Contiguous`/`Removed`/`Isolated` are pure boundary
108
+ masks (bitmask *wins* here), `MergedWith*` a one-lane shift.
109
+ - `ClassRuns { drop_mask, isolate_mask }` — cut at *every* class change; drop `drop_mask` runs,
110
+ isolate `isolate_mask` per-char. Covers Whitespace (drop `WS`, keep Word+Symbol runs) and Bert
111
+ (drop `WS`, isolate `Punct`). This is the case that keeps *two* run types, so it isn't a single
112
+ `Split`.
113
+ - `Cl100k` / `ByteLevel` — the 7-rule (GPT-2) **scalar** FSM (segmented `{1,3}` / ws-tail — measured
114
+ to beat the bitmask here). Peeks original bytes for the contraction suffix literals (ASCII).
115
+ - `ScriptRun` — run-split on script change, transparent set `{Common, Inherited, Any}` sticks to the
116
+ neighbouring run.
117
+
118
+ FSMs read the **tag stream** as primary input and may peek the **original bytes** for literal matches
119
+ that tags can't encode (cl100k contraction suffixes `'s`/`'re`, Metaspace marker, delimiter char).
120
+
121
+ ## 5. Remap tables (atoms → consumer class), all `[u8;16]`
122
+
123
+ Atom index: `0 Letter · 1 NumWord · 2 NumOther · 3 Newline · 4 Space · 5 WsOther · 6 Mark · 7 Connector · 8 Punct · 9 Apostrophe · 10 SymOther · 11 NumericOther`
124
+
125
+ ```
126
+ 0 1 2 3 4 5 6 7 8 9 10 11
127
+ cl100k [ L, N, N, NL, SP, WS, O, O, O, AP, O, O ] // AP triggers rule 1; SP is rule-4 ` ?`
128
+ ByteLevel [ L, N, N, WS, SP, WS, O, O, O, O, O, O ] // no \r\n split
129
+ Whitespace [Wrd, Wrd, Sym, ws, ws, ws, Wrd, Wrd, Sym, Sym, Sym, Sym ]
130
+ WhitespaceSpl [ ·, ·, ·, WS, WS, WS, ·, ·, ·, ·, ·, · ]
131
+ Punctuation [ ·, ·, ·, ·, ·, ·, ·, P, P, P, ·, · ]
132
+ Digits [ ·, N, N, ·, ·, ·, ·, ·, ·, ·, ·, N ]
133
+ Bert [ O, O, O, WS, WS, WS, O, P, P, P, O, O ] // ws-split + isolate punct
134
+ ```
135
+
136
+ ## 6. Outside the tag substrate
137
+
138
+ - `Split(regex)` — runtime pattern; **feature-gated**, rarely used. Escape hatch, not designed for.
139
+ - `CharDelimiterSplit` — arbitrary single byte; a byte compare, touches no tag.
140
+ - `FixedLength` — positional char count; rides the `char_start` bitplane only.
141
+ - Metaspace / cl100k-apostrophe — literal-byte matches; FSM peeks original bytes (§4).
142
+
143
+ ## 7. Portability (SIMD and non-SIMD share one table set)
144
+
145
+ Every table (`LETTER2/3`, `NUMBER2/3`, and the new `MARK2/3`/`PUNCT2/3`/`SYM2/3`/`CONNECTOR` +
146
+ 3-byte range tables) is arch-independent **data**, baked `const` by `bitmap_gen` (dev-only generator).
147
+ Each lane has two readers producing the *identical* tag:
148
+
149
+ | lane | SIMD reader (aarch64) | scalar reader (portable) |
150
+ |---|---|---|
151
+ | ASCII | nibble-shuffle | `LUT128[byte]` |
152
+ | 2/3-byte bitmap | `vqtbl` gather | `(TABLE[idx] >> bit) & 1` — **this is `FastLetter/FastNumber::step`** |
153
+ | CJK / range | branchless `Σ(cp ≥ tᵢ)` | plain range loop / binary search |
154
+
155
+ So `classify_cats` = `#[cfg(aarch64)] classify_neon` else `classify_scalar`, both emitting the same
156
+ `tag[]` (one byte-exact gate covers both). The **matchers already built are the scalar 2/3-byte
157
+ reader**, reused as-is. Downstream is already portable: `remap` is a table index; the FSMs are scalar
158
+ even on NEON (the shipped split *is* scalar). The only aarch64-only piece is the SIMD boundary-extract
159
+ optimisation for `Split`/`ClassRuns`; its scalar fallback is a run-scan (the measured winner for short
160
+ runs regardless).
161
+
162
+ ## 8. Speed contract
163
+
164
+ - **classify** is the one hot pass; keep the ASCII/2-byte/CJK fast lanes, SIMD range for the rest.
165
+ No scalar slow path (range kernel is branchless SIMD).
166
+ - **remap** is 1 `vqtbl1` / 16 chars.
167
+ - **RunSplit** pretokenizers extract via SIMD boundary bitmask (this is where the bitmask *wins* —
168
+ no segmented rules).
169
+ - **cl100k/ByteLevel** stay scalar-FSM (segmented rules; measured winner vs onig 5–45×, byte-exact).
170
+ - byte-exactness gate: every FSM's output must equal its reference (regex / current impl) over a
171
+ multi-script corpus. That single assert has caught every bug in this line of work.