gigatoken 0.1.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.
- checksums.yaml +7 -0
- data/Cargo.lock +3016 -0
- data/Cargo.toml +135 -0
- data/LICENSE +21 -0
- data/README.md +141 -0
- data/exe/gigatoken +9 -0
- data/ext/gigatoken/Cargo.toml +24 -0
- data/ext/gigatoken/extconf.rb +19 -0
- data/ext/gigatoken/src/error.rs +20 -0
- data/ext/gigatoken/src/gvl.rs +122 -0
- data/ext/gigatoken/src/lib.rs +50 -0
- data/ext/gigatoken/src/sentencepiece.rs +205 -0
- data/ext/gigatoken/src/sources.rs +207 -0
- data/ext/gigatoken/src/tokenizer.rs +571 -0
- data/lib/gigatoken/cli/bench.rb +64 -0
- data/lib/gigatoken/cli/support.rb +132 -0
- data/lib/gigatoken/cli/validate.rb +55 -0
- data/lib/gigatoken/cli.rb +18 -0
- data/lib/gigatoken/hub.rb +242 -0
- data/lib/gigatoken/packed_result.rb +48 -0
- data/lib/gigatoken/tokenizer.rb +117 -0
- data/lib/gigatoken/version.rb +5 -0
- data/lib/gigatoken.rb +29 -0
- data/rust-toolchain.toml +8 -0
- data/src/batch.rs +1808 -0
- data/src/bindings/bridge.rs +396 -0
- data/src/bindings/hub.rs +42 -0
- data/src/bindings/matcher.rs +114 -0
- data/src/bindings/mod.rs +14 -0
- data/src/bindings/padding.rs +177 -0
- data/src/bindings/pretokenize.rs +53 -0
- data/src/bindings/sources.rs +273 -0
- data/src/bindings/train.rs +125 -0
- data/src/bpe/mod.rs +1217 -0
- data/src/bpe/pretoken_cache.rs +495 -0
- data/src/bpe/sentencepiece.rs +1485 -0
- data/src/bpe/tiktoken.rs +2555 -0
- data/src/bpe_train.rs +351 -0
- data/src/input/decompress.rs +11 -0
- data/src/input/file_source.rs +514 -0
- data/src/input/jsonl.rs +94 -0
- data/src/input/mod.rs +333 -0
- data/src/input/parquet.rs +303 -0
- data/src/lib.rs +578 -0
- data/src/load_tokenizer/hf.rs +1036 -0
- data/src/load_tokenizer/hub.rs +344 -0
- data/src/load_tokenizer/mod.rs +3 -0
- data/src/load_tokenizer/tiktoken.rs +87 -0
- data/src/main.rs +95 -0
- data/src/pretokenize/fast/cl100k.rs +426 -0
- data/src/pretokenize/fast/cl100k_family.rs +891 -0
- data/src/pretokenize/fast/deepseek_v3.rs +605 -0
- data/src/pretokenize/fast/kimi.rs +281 -0
- data/src/pretokenize/fast/mask.rs +1486 -0
- data/src/pretokenize/fast/mod.rs +446 -0
- data/src/pretokenize/fast/nemotron.rs +138 -0
- data/src/pretokenize/fast/o200k.rs +347 -0
- data/src/pretokenize/fast/o200k_family.rs +1734 -0
- data/src/pretokenize/fast/olmo3.rs +505 -0
- data/src/pretokenize/fast/qwen2.rs +429 -0
- data/src/pretokenize/fast/qwen3_5.rs +541 -0
- data/src/pretokenize/fast/r50k.rs +1250 -0
- data/src/pretokenize/mod.rs +1079 -0
- data/src/pretokenize/options.rs +188 -0
- data/src/pretokenize/pretoken.rs +20 -0
- data/src/pretokenize/pretokenize_traits.rs +49 -0
- data/src/pretokenize/reference/avx512.rs +522 -0
- data/src/pretokenize/reference/combinator.rs +572 -0
- data/src/pretokenize/reference/mod.rs +28 -0
- data/src/pretokenize/reference/simd.rs +852 -0
- data/src/pretokenize/reference/state_machine.rs +365 -0
- data/src/pretokenize/unicode.rs +546 -0
- data/src/test_hub.rs +28 -0
- data/src/token.rs +42 -0
- metadata +161 -0
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
//! Fast scalar pretokenizers, one submodule per pretokenization scheme.
|
|
2
|
+
//!
|
|
3
|
+
//! Each scheme implements an advance function that consumes exactly one
|
|
4
|
+
//! pretoken, wrapped in a thin iterator struct. The byte predicates and
|
|
5
|
+
//! SWAR scans below are shared; a new scheme (e.g. o200k) should slot in
|
|
6
|
+
//! as another submodule reusing these primitives where its character
|
|
7
|
+
//! classes line up.
|
|
8
|
+
|
|
9
|
+
pub(crate) mod cl100k_family;
|
|
10
|
+
pub(crate) mod mask;
|
|
11
|
+
pub(crate) mod o200k_family;
|
|
12
|
+
|
|
13
|
+
pub mod cl100k;
|
|
14
|
+
pub mod deepseek_v3;
|
|
15
|
+
pub mod kimi;
|
|
16
|
+
pub mod nemotron;
|
|
17
|
+
pub mod o200k;
|
|
18
|
+
pub mod olmo3;
|
|
19
|
+
pub mod qwen2;
|
|
20
|
+
pub mod qwen3_5;
|
|
21
|
+
pub mod r50k;
|
|
22
|
+
|
|
23
|
+
pub use cl100k::FastCl100kPretokenizer;
|
|
24
|
+
pub use deepseek_v3::FastDeepSeekV3Pretokenizer;
|
|
25
|
+
pub use kimi::FastKimiPretokenizer;
|
|
26
|
+
pub use nemotron::FastNemotronPretokenizer;
|
|
27
|
+
pub use o200k::FastO200kPretokenizer;
|
|
28
|
+
pub use olmo3::FastOlmo3Pretokenizer;
|
|
29
|
+
pub use qwen2::FastQwen2Pretokenizer;
|
|
30
|
+
pub use qwen3_5::FastQwen35Pretokenizer;
|
|
31
|
+
pub use r50k::FastR50kPretokenizer;
|
|
32
|
+
|
|
33
|
+
use crate::pretokenize::SpanBatch;
|
|
34
|
+
use crate::pretokenize::unicode;
|
|
35
|
+
|
|
36
|
+
// -----------------------------------------------------------------------
|
|
37
|
+
// Shared chunked span pull for the mask-scanner pretokenizers
|
|
38
|
+
// -----------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
/// The `PretokenSpans::fill_spans_keyed` body shared by every mask-scanner
|
|
41
|
+
/// pretokenizer (all of them wrap a `(bytes, MaskState)` pair). With a SIMD
|
|
42
|
+
/// scanner this is the two-phase chunk walker
|
|
43
|
+
/// ([`mask::MaskState::fill_spans_two_phase`]): boundary harvest into a
|
|
44
|
+
/// flat buffer, then a branch-free emission loop — the per-span refill
|
|
45
|
+
/// ladder and pack branches of the fused pull loop were the largest single
|
|
46
|
+
/// source of encode's discarded issue bandwidth. Without SIMD support it
|
|
47
|
+
/// pulls spans one at a time over `next_span`, fusing its
|
|
48
|
+
/// `#[inline(always)]` walker body into one tight loop. `#[inline(never)]`:
|
|
49
|
+
/// each monomorphization is its own out-of-line loop, keeping its register
|
|
50
|
+
/// allocation away from the (register-hungry) encode loop that calls it.
|
|
51
|
+
/// Routing this through `Iterator::next` instead measured ~23% of warm
|
|
52
|
+
/// encode time in un-inlined call overhead.
|
|
53
|
+
#[inline(never)]
|
|
54
|
+
pub(crate) fn fill_spans_keyed_mask<'a, S: mask::MaskScheme>(
|
|
55
|
+
bytes: &'a [u8],
|
|
56
|
+
state: &mut mask::MaskState,
|
|
57
|
+
batch: &mut SpanBatch<'a>,
|
|
58
|
+
prefetch: &impl Fn(u64),
|
|
59
|
+
) -> usize {
|
|
60
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
61
|
+
if mask::simd_scanner_available() {
|
|
62
|
+
return state.fill_spans_two_phase::<S>(bytes, batch, prefetch);
|
|
63
|
+
}
|
|
64
|
+
crate::pretokenize::fill_spans_keyed_with_buf(
|
|
65
|
+
bytes,
|
|
66
|
+
// next_span returns in-bounds, nonempty span boundaries.
|
|
67
|
+
|| state.next_span::<S>(bytes),
|
|
68
|
+
batch,
|
|
69
|
+
prefetch,
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Implement [`crate::pretokenize::PretokenSpans`] for a mask-scanner
|
|
74
|
+
/// pretokenizer (any `{ bytes, state: MaskState }` struct) by delegating
|
|
75
|
+
/// to its scheme's [`fill_spans_keyed_mask`] monomorphization.
|
|
76
|
+
macro_rules! impl_mask_pretoken_spans {
|
|
77
|
+
($pretokenizer:ident, $scheme:ty) => {
|
|
78
|
+
// SAFETY: delegates to `fill_spans_keyed_mask`, whose bodies
|
|
79
|
+
// (`fill_spans_keyed_with_buf` / `fill_spans_two_phase`) write
|
|
80
|
+
// exactly the first `n` entries from live spans of `self.bytes`.
|
|
81
|
+
unsafe impl<'a> crate::pretokenize::PretokenSpans<'a> for $pretokenizer<'a> {
|
|
82
|
+
#[inline]
|
|
83
|
+
fn fill_spans_keyed(
|
|
84
|
+
&mut self,
|
|
85
|
+
batch: &mut crate::pretokenize::SpanBatch<'a>,
|
|
86
|
+
prefetch: &impl Fn(u64),
|
|
87
|
+
) -> usize {
|
|
88
|
+
crate::pretokenize::fast::fill_spans_keyed_mask::<$scheme>(
|
|
89
|
+
self.bytes,
|
|
90
|
+
&mut self.state,
|
|
91
|
+
batch,
|
|
92
|
+
prefetch,
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
pub(crate) use impl_mask_pretoken_spans;
|
|
99
|
+
|
|
100
|
+
// -----------------------------------------------------------------------
|
|
101
|
+
// Branchless byte predicates
|
|
102
|
+
// -----------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
#[inline(always)]
|
|
105
|
+
pub(crate) fn is_letter(b: u8) -> bool {
|
|
106
|
+
(b | 0x20).wrapping_sub(b'a') < 26
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
#[inline(always)]
|
|
110
|
+
pub(crate) fn is_digit(b: u8) -> bool {
|
|
111
|
+
b.wrapping_sub(b'0') < 10
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
#[inline(always)]
|
|
115
|
+
pub(crate) fn is_ascii_ws(b: u8) -> bool {
|
|
116
|
+
b == b' ' || b.wrapping_sub(9) < 5
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
#[inline(always)]
|
|
120
|
+
pub(crate) unsafe fn decode_non_ascii(bytes: &[u8]) -> char {
|
|
121
|
+
unsafe {
|
|
122
|
+
std::str::from_utf8_unchecked(bytes)
|
|
123
|
+
.chars()
|
|
124
|
+
.next()
|
|
125
|
+
.unwrap_unchecked()
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/// Decode one non-ASCII scalar. Requires only `pos < bytes.len()` and
|
|
130
|
+
/// `bytes[pos] >= 0x80`; arbitrary (invalid) bytes are tolerated and
|
|
131
|
+
/// decode deterministically. Returns the codepoint and the number of
|
|
132
|
+
/// bytes consumed.
|
|
133
|
+
///
|
|
134
|
+
/// Invalid input is garbage-in/defined-garbage-out, with two hard
|
|
135
|
+
/// guarantees the walkers rely on:
|
|
136
|
+
///
|
|
137
|
+
/// - Never reads past `bytes.len()`, and the returned length never
|
|
138
|
+
/// overruns it: a multi-byte lead whose sequence is cut off by the
|
|
139
|
+
/// buffer end (a truncated tail) consumes exactly the bytes that
|
|
140
|
+
/// remain and yields [`CP_INVALID`]. (Pre-fix this read up to 3 bytes
|
|
141
|
+
/// past the slice and returned an end past `len` — walker panic on the
|
|
142
|
+
/// Iterator path, out-of-bounds span on the SpanBatch path.)
|
|
143
|
+
/// - The codepoint is always `<= 0x10FFFF`, so the packed class-table
|
|
144
|
+
/// lookups (`unicode::class_of` / `ds_class_of`, indexed unchecked)
|
|
145
|
+
/// stay in bounds: invalid leads 0xF5..=0xFF take the 4-byte branch
|
|
146
|
+
/// and can assemble "codepoints" up to 0x1FFFFF, which are clamped to
|
|
147
|
+
/// [`CP_INVALID`]. (Pre-fix the table lookup read up to ~246 KB past
|
|
148
|
+
/// the table — heap memory whose contents depend on other threads'
|
|
149
|
+
/// allocations, which is what made >65 KB invalid-UTF-8 pretokens
|
|
150
|
+
/// split nondeterministically between the walker paths.)
|
|
151
|
+
///
|
|
152
|
+
/// The clamp target U+10FFFF is unassigned (a noncharacter) — class
|
|
153
|
+
/// `Other` in every scheme's classifier — so truncated or
|
|
154
|
+
/// beyond-Unicode garbage classifies like any other unassigned
|
|
155
|
+
/// codepoint, identically on every path.
|
|
156
|
+
#[inline(always)]
|
|
157
|
+
pub(crate) unsafe fn decode_cp(bytes: &[u8], pos: usize) -> (u32, usize) {
|
|
158
|
+
if pos + 4 > bytes.len() {
|
|
159
|
+
// Within 3 bytes of the buffer end: the only region where a
|
|
160
|
+
// sequence can be truncated. Cold: interior calls (the hot ones)
|
|
161
|
+
// never take it, and the branch predicts not-taken.
|
|
162
|
+
return decode_cp_near_end(bytes, pos);
|
|
163
|
+
}
|
|
164
|
+
// SAFETY: pos + 4 <= len just checked.
|
|
165
|
+
unsafe { decode_cp_inbounds(bytes, pos) }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/// [`decode_cp`] without the buffer-end guard, for callers that already
|
|
169
|
+
/// guarantee `pos + 4 <= bytes.len()` structurally (the mask-scanner
|
|
170
|
+
/// batch helpers, whose `scan + 70 <= len` batch guard covers every call
|
|
171
|
+
/// site's worst case) — keeps the tail check out of the batch
|
|
172
|
+
/// classification path. Identical results to [`decode_cp`] on any input
|
|
173
|
+
/// where both are callable, including the [`CP_INVALID`] clamp for
|
|
174
|
+
/// beyond-Unicode garbage from invalid 4-byte leads.
|
|
175
|
+
#[inline(always)]
|
|
176
|
+
pub(crate) unsafe fn decode_cp_inbounds(bytes: &[u8], pos: usize) -> (u32, usize) {
|
|
177
|
+
unsafe {
|
|
178
|
+
let b0 = *bytes.get_unchecked(pos) as u32;
|
|
179
|
+
let b1 = (*bytes.get_unchecked(pos + 1) & 0x3F) as u32;
|
|
180
|
+
if b0 < 0xE0 {
|
|
181
|
+
return (((b0 & 0x1F) << 6) | b1, 2);
|
|
182
|
+
}
|
|
183
|
+
let b2 = (*bytes.get_unchecked(pos + 2) & 0x3F) as u32;
|
|
184
|
+
if b0 < 0xF0 {
|
|
185
|
+
return (((b0 & 0x0F) << 12) | (b1 << 6) | b2, 3);
|
|
186
|
+
}
|
|
187
|
+
let b3 = (*bytes.get_unchecked(pos + 3) & 0x3F) as u32;
|
|
188
|
+
(
|
|
189
|
+
(((b0 & 0x07) << 18) | (b1 << 12) | (b2 << 6) | b3).min(CP_INVALID),
|
|
190
|
+
4,
|
|
191
|
+
)
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/// The codepoint reported for byte sequences that cannot be decoded
|
|
196
|
+
/// within bounds (truncated tails) or that assemble past the Unicode
|
|
197
|
+
/// range (invalid 4-byte-lead garbage). U+10FFFF: the largest scalar
|
|
198
|
+
/// value, an unassigned noncharacter, class `Other` in [`unicode::class_of`],
|
|
199
|
+
/// `class_of_marks_join`, and `ds_class_of` alike.
|
|
200
|
+
pub(crate) const CP_INVALID: u32 = 0x10FFFF;
|
|
201
|
+
|
|
202
|
+
/// [`decode_cp`]'s slow path for `pos + 4 > bytes.len()`: decodes with
|
|
203
|
+
/// per-byte bounds, identical results to the fast path for complete
|
|
204
|
+
/// sequences; a sequence truncated by the buffer end consumes exactly
|
|
205
|
+
/// the remaining bytes and yields [`CP_INVALID`].
|
|
206
|
+
#[cold]
|
|
207
|
+
#[inline(never)]
|
|
208
|
+
fn decode_cp_near_end(bytes: &[u8], pos: usize) -> (u32, usize) {
|
|
209
|
+
let len = bytes.len();
|
|
210
|
+
let b0 = bytes[pos] as u32;
|
|
211
|
+
let need = if b0 < 0xE0 {
|
|
212
|
+
2
|
|
213
|
+
} else if b0 < 0xF0 {
|
|
214
|
+
3
|
|
215
|
+
} else {
|
|
216
|
+
4
|
|
217
|
+
};
|
|
218
|
+
if pos + need > len {
|
|
219
|
+
// Truncated tail: consume the rest of the buffer as one
|
|
220
|
+
// unclassifiable char so every walker path terminates the final
|
|
221
|
+
// pretoken at `len` the same way.
|
|
222
|
+
return (CP_INVALID, len - pos);
|
|
223
|
+
}
|
|
224
|
+
let b1 = (bytes[pos + 1] & 0x3F) as u32;
|
|
225
|
+
if need == 2 {
|
|
226
|
+
return (((b0 & 0x1F) << 6) | b1, 2);
|
|
227
|
+
}
|
|
228
|
+
let b2 = (bytes[pos + 2] & 0x3F) as u32;
|
|
229
|
+
if need == 3 {
|
|
230
|
+
return (((b0 & 0x0F) << 12) | (b1 << 6) | b2, 3);
|
|
231
|
+
}
|
|
232
|
+
let b3 = (bytes[pos + 3] & 0x3F) as u32;
|
|
233
|
+
(
|
|
234
|
+
(((b0 & 0x07) << 18) | (b1 << 12) | (b2 << 6) | b3).min(CP_INVALID),
|
|
235
|
+
4,
|
|
236
|
+
)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/// `[\r\n]*`: advance past a run of CR/LF bytes (trailing newlines after a
|
|
240
|
+
/// punctuation run in the cl100k-family schemes).
|
|
241
|
+
#[inline(always)]
|
|
242
|
+
pub(crate) fn scan_newlines(bytes: &[u8], mut pos: usize) -> usize {
|
|
243
|
+
while pos < bytes.len() {
|
|
244
|
+
let b = unsafe { *bytes.get_unchecked(pos) };
|
|
245
|
+
if b == b'\r' || b == b'\n' {
|
|
246
|
+
pos += 1;
|
|
247
|
+
} else {
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
pos
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/// If the char at `pos` is a letter (`\p{L}` under the 4-way `CharClass`
|
|
255
|
+
/// classifier), return the offset just past it.
|
|
256
|
+
#[inline(always)]
|
|
257
|
+
pub(crate) fn letter_end_at(bytes: &[u8], pos: usize) -> Option<usize> {
|
|
258
|
+
let &b = bytes.get(pos)?;
|
|
259
|
+
if is_letter(b) {
|
|
260
|
+
return Some(pos + 1);
|
|
261
|
+
}
|
|
262
|
+
if b >= 0x80 {
|
|
263
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos) };
|
|
264
|
+
if unicode::class_of(cp) == unicode::CharClass::Letter {
|
|
265
|
+
return Some(pos + l);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
None
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// -----------------------------------------------------------------------
|
|
272
|
+
// SWAR
|
|
273
|
+
// -----------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
pub(crate) const HI: u64 = 0x8080_8080_8080_8080;
|
|
276
|
+
|
|
277
|
+
/// Returns the high bit set in each lane that is NOT an ASCII letter,
|
|
278
|
+
/// computed directly (rather than as the complement of a letter mask) so
|
|
279
|
+
/// the scan loop can branch on `!= 0` and reuse the value for `trailing_zeros`.
|
|
280
|
+
#[inline(always)]
|
|
281
|
+
pub(crate) fn swar64_letter_nonmask(word: u64) -> u64 {
|
|
282
|
+
let lowered = word | 0x2020_2020_2020_2020;
|
|
283
|
+
let ge_a = (lowered | HI).wrapping_sub(0x6161_6161_6161_6161);
|
|
284
|
+
let le_z = 0xFAFA_FAFA_FAFA_FAFA_u64.wrapping_sub(lowered);
|
|
285
|
+
!(ge_a & le_z) & HI
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/// SWAR letter scan: advances `pos` past ASCII letters.
|
|
289
|
+
/// Returns the updated pos.
|
|
290
|
+
#[inline(always)]
|
|
291
|
+
pub(crate) fn swar_scan_letters(bytes: &[u8], mut pos: usize) -> usize {
|
|
292
|
+
let len = bytes.len();
|
|
293
|
+
// SWAR: 8 bytes at a time
|
|
294
|
+
while pos + 8 <= len {
|
|
295
|
+
let word = unsafe { (bytes.as_ptr().add(pos) as *const u64).read_unaligned() };
|
|
296
|
+
if word & HI != 0 {
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
let nonletter = swar64_letter_nonmask(word);
|
|
300
|
+
if nonletter != 0 {
|
|
301
|
+
return pos + nonletter.to_le().trailing_zeros() as usize / 8;
|
|
302
|
+
}
|
|
303
|
+
pos += 8;
|
|
304
|
+
}
|
|
305
|
+
// Scalar tail
|
|
306
|
+
while pos < len {
|
|
307
|
+
let b = unsafe { *bytes.get_unchecked(pos) };
|
|
308
|
+
if is_letter(b) {
|
|
309
|
+
pos += 1;
|
|
310
|
+
} else {
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
pos
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/// NEON letter scan: 16 bytes per iteration. Non-ASCII bytes (>= 0x80) fail
|
|
318
|
+
/// the `<= 'z'` check after case-folding, so they stop the run exactly like
|
|
319
|
+
/// non-letters; the caller's unicode continuation handles them.
|
|
320
|
+
///
|
|
321
|
+
/// NOT used by `scan_letters_from`: measured 0.83x of the SWAR scan on OWT.
|
|
322
|
+
/// The `vshrn`-based movemask needs a vector→GPR transfer whose latency sits
|
|
323
|
+
/// on the serial per-token chain, and typical letter runs (~4-6 bytes) fit in
|
|
324
|
+
/// one SWAR iteration anyway. Kept as a reference / benchmark baseline.
|
|
325
|
+
#[cfg(target_arch = "aarch64")]
|
|
326
|
+
#[allow(dead_code)]
|
|
327
|
+
#[inline(always)]
|
|
328
|
+
pub(crate) fn neon_scan_letters(bytes: &[u8], mut pos: usize) -> usize {
|
|
329
|
+
use std::arch::aarch64::*;
|
|
330
|
+
let len = bytes.len();
|
|
331
|
+
while pos + 16 <= len {
|
|
332
|
+
unsafe {
|
|
333
|
+
let v = vld1q_u8(bytes.as_ptr().add(pos));
|
|
334
|
+
let lowered = vorrq_u8(v, vdupq_n_u8(0x20));
|
|
335
|
+
let ge_a = vcgeq_u8(lowered, vdupq_n_u8(b'a'));
|
|
336
|
+
let le_z = vcleq_u8(lowered, vdupq_n_u8(b'z'));
|
|
337
|
+
let nonletter = vmvnq_u8(vandq_u8(ge_a, le_z));
|
|
338
|
+
// Narrowing movemask: 4 bits per lane, first set nibble = first
|
|
339
|
+
// non-letter lane.
|
|
340
|
+
let mask = vget_lane_u64::<0>(vreinterpret_u64_u8(vshrn_n_u16::<4>(
|
|
341
|
+
vreinterpretq_u16_u8(nonletter),
|
|
342
|
+
)));
|
|
343
|
+
if mask != 0 {
|
|
344
|
+
return pos + (mask.trailing_zeros() >> 2) as usize;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
pos += 16;
|
|
348
|
+
}
|
|
349
|
+
while pos < len {
|
|
350
|
+
let b = unsafe { *bytes.get_unchecked(pos) };
|
|
351
|
+
if is_letter(b) {
|
|
352
|
+
pos += 1;
|
|
353
|
+
} else {
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
pos
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// -----------------------------------------------------------------------
|
|
361
|
+
// Shared run scans (`\p{L}+`, `\p{N}+`, `\p{N}{1,3}`, `[^\s\p{L}\p{N}]+`)
|
|
362
|
+
// -----------------------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
/// `\p{N}{1,3}`: extend a number run that already matched `consumed` chars
|
|
365
|
+
/// to at most 3 chars total. Shared by the cl100k and olmo3 schemes.
|
|
366
|
+
#[inline(always)]
|
|
367
|
+
pub(crate) fn scan_numbers_max3(bytes: &[u8], mut pos: usize, mut consumed: u32) -> usize {
|
|
368
|
+
let len = bytes.len();
|
|
369
|
+
while consumed < 3 && pos < len {
|
|
370
|
+
let b = unsafe { *bytes.get_unchecked(pos) };
|
|
371
|
+
if is_digit(b) {
|
|
372
|
+
pos += 1;
|
|
373
|
+
consumed += 1;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if b >= 0x80 {
|
|
377
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos) };
|
|
378
|
+
if unicode::class_of(cp) == unicode::CharClass::Number {
|
|
379
|
+
pos += l;
|
|
380
|
+
consumed += 1;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
pos
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
#[inline(always)]
|
|
390
|
+
pub(crate) fn scan_letters_from(bytes: &[u8], pos: usize) -> usize {
|
|
391
|
+
let len = bytes.len();
|
|
392
|
+
let mut p = pos;
|
|
393
|
+
loop {
|
|
394
|
+
p = swar_scan_letters(bytes, p);
|
|
395
|
+
if p < len && unsafe { *bytes.get_unchecked(p) } >= 0x80 {
|
|
396
|
+
let (cp, l) = unsafe { decode_cp(bytes, p) };
|
|
397
|
+
if unicode::class_of(cp) == unicode::CharClass::Letter {
|
|
398
|
+
p += l;
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return p;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
#[inline(always)]
|
|
407
|
+
pub(crate) fn scan_digits_from(bytes: &[u8], pos: usize) -> usize {
|
|
408
|
+
let len = bytes.len();
|
|
409
|
+
let mut p = pos;
|
|
410
|
+
loop {
|
|
411
|
+
while p < len && is_digit(unsafe { *bytes.get_unchecked(p) }) {
|
|
412
|
+
p += 1;
|
|
413
|
+
}
|
|
414
|
+
if p < len && unsafe { *bytes.get_unchecked(p) } >= 0x80 {
|
|
415
|
+
let (cp, l) = unsafe { decode_cp(bytes, p) };
|
|
416
|
+
if unicode::class_of(cp) == unicode::CharClass::Number {
|
|
417
|
+
p += l;
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return p;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
#[inline(always)]
|
|
426
|
+
pub(crate) fn scan_other_from(bytes: &[u8], pos: usize) -> usize {
|
|
427
|
+
let len = bytes.len();
|
|
428
|
+
let mut p = pos;
|
|
429
|
+
loop {
|
|
430
|
+
while p < len {
|
|
431
|
+
let b = unsafe { *bytes.get_unchecked(p) };
|
|
432
|
+
if b >= 0x80 { break; }
|
|
433
|
+
if is_letter(b) || is_digit(b) || is_ascii_ws(b) { return p; }
|
|
434
|
+
p += 1;
|
|
435
|
+
}
|
|
436
|
+
if p < len {
|
|
437
|
+
let (cp, l) = unsafe { decode_cp(bytes, p) };
|
|
438
|
+
if unicode::class_of(cp) == unicode::CharClass::Other {
|
|
439
|
+
p += l;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return p;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
//! Fast pretokenizer for the Nemotron-3 regex (nvidia Nemotron-3 family):
|
|
2
|
+
//! `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`
|
|
3
|
+
//!
|
|
4
|
+
//! The o200k scheme without contraction suffixes and with single-char
|
|
5
|
+
//! `\p{N}` digit tokens. See `o200k_family` (`CONTRACTIONS = false`,
|
|
6
|
+
//! `DIGITS3 = false`).
|
|
7
|
+
|
|
8
|
+
use super::mask::{MaskScheme, MaskState};
|
|
9
|
+
use super::o200k_family;
|
|
10
|
+
use crate::pretokenize::Pretoken;
|
|
11
|
+
|
|
12
|
+
pub(crate) struct NemotronScheme;
|
|
13
|
+
|
|
14
|
+
impl MaskScheme for NemotronScheme {
|
|
15
|
+
#[inline(always)]
|
|
16
|
+
fn advance(bytes: &[u8], pos: usize) -> usize {
|
|
17
|
+
o200k_family::advance_pos::<false, false, true, false>(bytes, pos)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
#[cfg(target_arch = "aarch64")]
|
|
21
|
+
#[inline(always)]
|
|
22
|
+
fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
|
|
23
|
+
o200k_family::batch_masks::<false, false, true, false>(bytes, scan)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
#[cfg(target_arch = "x86_64")]
|
|
27
|
+
#[inline(always)]
|
|
28
|
+
unsafe fn batch_masks_x86<const AVX512: bool>(bytes: &[u8], scan: usize) -> (u64, u64) {
|
|
29
|
+
// SAFETY: the caller detected the tier (trait contract).
|
|
30
|
+
unsafe { o200k_family::batch_masks_x86::<AVX512, false, false, true, false>(bytes, scan) }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// With SIMD support (aarch64 NEON, or x86_64 AVX-512/AVX2 detected at
|
|
35
|
+
/// runtime), iteration runs the shared o200k-family mask scanner (see
|
|
36
|
+
/// `o200k_family::batch_masks`); elsewhere every token takes the scalar
|
|
37
|
+
/// `advance_pos`.
|
|
38
|
+
pub struct FastNemotronPretokenizer<'a> {
|
|
39
|
+
bytes: &'a [u8],
|
|
40
|
+
state: MaskState,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
impl<'a> FastNemotronPretokenizer<'a> {
|
|
44
|
+
#[inline]
|
|
45
|
+
pub fn new(bytes: &'a [u8]) -> Self {
|
|
46
|
+
Self::with_pos(bytes, 0)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Resume iteration at a byte offset previously returned by [`Self::pos`].
|
|
50
|
+
#[inline]
|
|
51
|
+
pub fn with_pos(bytes: &'a [u8], pos: usize) -> Self {
|
|
52
|
+
Self { bytes, state: MaskState::new(pos) }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// Current position as a byte offset into the input.
|
|
56
|
+
#[inline]
|
|
57
|
+
pub fn pos(&self) -> usize {
|
|
58
|
+
self.state.pos
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
impl<'a> Iterator for FastNemotronPretokenizer<'a> {
|
|
63
|
+
type Item = Pretoken<'a>;
|
|
64
|
+
|
|
65
|
+
#[inline]
|
|
66
|
+
fn next(&mut self) -> Option<Pretoken<'a>> {
|
|
67
|
+
let (start, end) = self.state.next_span::<NemotronScheme>(self.bytes)?;
|
|
68
|
+
Some(Pretoken(&self.bytes[start..end]))
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
super::impl_mask_pretoken_spans!(FastNemotronPretokenizer, NemotronScheme);
|
|
73
|
+
|
|
74
|
+
#[cfg(test)]
|
|
75
|
+
mod tests {
|
|
76
|
+
use super::*;
|
|
77
|
+
|
|
78
|
+
/// The Nemotron pattern verbatim — no possessive quantifiers, so it
|
|
79
|
+
/// runs directly under fancy-regex.
|
|
80
|
+
const NEMOTRON_REF_REGEX: &str = r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+";
|
|
81
|
+
|
|
82
|
+
fn regex_tokens(s: &str) -> Vec<String> {
|
|
83
|
+
let re = fancy_regex::Regex::new(NEMOTRON_REF_REGEX).unwrap();
|
|
84
|
+
re.find_iter(s)
|
|
85
|
+
.map(|m| m.unwrap().as_str().to_string())
|
|
86
|
+
.collect()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
fn fast_tokens(s: &str) -> Vec<String> {
|
|
90
|
+
FastNemotronPretokenizer::new(s.as_bytes())
|
|
91
|
+
.map(|t| String::from_utf8_lossy(t.0).into_owned())
|
|
92
|
+
.collect()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// The o200k small-case list applies verbatim (contraction cases just
|
|
96
|
+
/// tokenize differently, which the reference regex reflects).
|
|
97
|
+
#[test]
|
|
98
|
+
fn nemotron_small_cases() {
|
|
99
|
+
for case in crate::pretokenize::fast::o200k::tests::SMALL_CASES {
|
|
100
|
+
assert_eq!(
|
|
101
|
+
fast_tokens(case),
|
|
102
|
+
regex_tokens(case),
|
|
103
|
+
"Mismatch on case {case:?}"
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// Random codepoint soup drawn from classes the scheme distinguishes,
|
|
109
|
+
/// compared against the reference regex.
|
|
110
|
+
#[test]
|
|
111
|
+
fn nemotron_matches_regex_random() {
|
|
112
|
+
use rand::prelude::*;
|
|
113
|
+
let pools: &[&[char]] = &[
|
|
114
|
+
&['a', 'z', 'é', 'ß', 'ж', 'ا', '한', '日'], // lower/caseless
|
|
115
|
+
&['A', 'Z', 'É', 'Ж', 'DŽ', 'Dž'], // upper/title
|
|
116
|
+
&['1', '9', '٢', '½', 'Ⅷ', '๕'], // numbers
|
|
117
|
+
&[' ', '\t', '\n', '\r', '\u{a0}', '\u{2028}'], // whitespace
|
|
118
|
+
&['\u{301}', '\u{5bf}', '\u{93b}', '\u{20dd}'], // marks
|
|
119
|
+
&['.', ',', '!', '$', '\'', '«', '¡', '€', '☃', '/'], // punct/symbols
|
|
120
|
+
&['\u{0}', '\u{ad}', '\u{200b}', '\u{e0001}'], // other (C*)
|
|
121
|
+
];
|
|
122
|
+
let mut rng = StdRng::seed_from_u64(0x93E3_5EEE);
|
|
123
|
+
for round in 0..3000 {
|
|
124
|
+
let len = rng.random_range(1..40);
|
|
125
|
+
let s: String = (0..len)
|
|
126
|
+
.map(|_| {
|
|
127
|
+
let pool = pools.choose(&mut rng).unwrap();
|
|
128
|
+
*pool.choose(&mut rng).unwrap()
|
|
129
|
+
})
|
|
130
|
+
.collect();
|
|
131
|
+
assert_eq!(
|
|
132
|
+
fast_tokens(&s),
|
|
133
|
+
regex_tokens(&s),
|
|
134
|
+
"Mismatch on round {round}, case {s:?}"
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|