trustformers-tokenizers 0.1.1

Tokenizers for TrustformeRS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;
use trustformers_core::errors::{Result, TrustformersError};

/// SIMD-optimized tokenization utilities for improved performance
pub struct SimdTokenizer {
    /// Lookup table for ASCII character classification
    ascii_lookup: [u8; 256],
}

impl SimdTokenizer {
    /// Create a new SIMD tokenizer
    pub fn new() -> Self {
        let mut ascii_lookup = [0u8; 256];

        // Set up character classification flags
        // Bit 0: alphabetic, Bit 1: numeric, Bit 2: whitespace, Bit 3: punctuation
        for (i, flags_ref) in ascii_lookup.iter_mut().enumerate() {
            let ch = i as u8 as char;
            let mut flags = 0u8;

            if ch.is_alphabetic() {
                flags |= 1;
            }
            if ch.is_numeric() {
                flags |= 2;
            }
            if ch.is_whitespace() {
                flags |= 4;
            }
            if ch.is_ascii_punctuation() {
                flags |= 8;
            }

            *flags_ref = flags;
        }

        Self { ascii_lookup }
    }

    /// Fast ASCII character classification using SIMD
    #[cfg(target_arch = "x86_64")]
    pub fn classify_ascii_chars(&self, text: &[u8]) -> Vec<u8> {
        if !is_x86_feature_detected!("avx2") {
            return self.classify_ascii_chars_scalar(text);
        }

        unsafe { self.classify_ascii_chars_avx2(text) }
    }

    /// Fast ASCII character classification - fallback for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn classify_ascii_chars(&self, text: &[u8]) -> Vec<u8> {
        self.classify_ascii_chars_scalar(text)
    }

    /// Fallback scalar implementation for character classification
    fn classify_ascii_chars_scalar(&self, text: &[u8]) -> Vec<u8> {
        text.iter().map(|&byte| self.ascii_lookup[byte as usize]).collect()
    }

    /// AVX2-optimized character classification
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx2")]
    unsafe fn classify_ascii_chars_avx2(&self, text: &[u8]) -> Vec<u8> {
        let mut result = Vec::with_capacity(text.len());
        let chunks = text.chunks_exact(32);
        let remainder = chunks.remainder();

        // Process 32 bytes at a time using AVX2
        for chunk in chunks {
            let _input = _mm256_loadu_si256(chunk.as_ptr() as *const __m256i);

            // Character classification using parallel lookups
            let mut output = [0u8; 32];
            for i in 0..32 {
                output[i] = self.ascii_lookup[chunk[i] as usize];
            }

            result.extend_from_slice(&output);
        }

        // Process remaining bytes
        for &byte in remainder {
            result.push(self.ascii_lookup[byte as usize]);
        }

        result
    }

    /// Fast whitespace detection using SIMD
    #[cfg(target_arch = "x86_64")]
    pub fn find_whitespace_boundaries(&self, text: &[u8]) -> Vec<usize> {
        if !is_x86_feature_detected!("avx2") {
            return self.find_whitespace_boundaries_scalar(text);
        }

        unsafe { self.find_whitespace_boundaries_avx2(text) }
    }

    /// Fast whitespace detection - fallback for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn find_whitespace_boundaries(&self, text: &[u8]) -> Vec<usize> {
        self.find_whitespace_boundaries_scalar(text)
    }

    /// Scalar implementation for whitespace boundary detection
    fn find_whitespace_boundaries_scalar(&self, text: &[u8]) -> Vec<usize> {
        let mut boundaries = Vec::new();
        let mut in_whitespace = false;

        for (i, &byte) in text.iter().enumerate() {
            let is_whitespace = (self.ascii_lookup[byte as usize] & 4) != 0;

            if is_whitespace != in_whitespace {
                boundaries.push(i);
                in_whitespace = is_whitespace;
            }
        }

        boundaries
    }

    /// AVX2-optimized whitespace boundary detection
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx2")]
    unsafe fn find_whitespace_boundaries_avx2(&self, text: &[u8]) -> Vec<usize> {
        let mut boundaries = Vec::new();
        let mut prev_whitespace_mask = 0u32;

        // Define whitespace characters
        let space = _mm256_set1_epi8(b' ' as i8);
        let tab = _mm256_set1_epi8(b'\t' as i8);
        let newline = _mm256_set1_epi8(b'\n' as i8);
        let carriage_return = _mm256_set1_epi8(b'\r' as i8);

        let chunks = text.chunks_exact(32);
        let mut offset = 0;

        for chunk in chunks {
            let input = _mm256_loadu_si256(chunk.as_ptr() as *const __m256i);

            // Compare with whitespace characters
            let space_mask = _mm256_cmpeq_epi8(input, space);
            let tab_mask = _mm256_cmpeq_epi8(input, tab);
            let newline_mask = _mm256_cmpeq_epi8(input, newline);
            let cr_mask = _mm256_cmpeq_epi8(input, carriage_return);

            // Combine all whitespace masks
            let whitespace_mask = _mm256_or_si256(
                _mm256_or_si256(space_mask, tab_mask),
                _mm256_or_si256(newline_mask, cr_mask),
            );

            let mask_bits = _mm256_movemask_epi8(whitespace_mask) as u32;

            // Find transitions between whitespace and non-whitespace
            let transitions = mask_bits ^ (mask_bits << 1) ^ prev_whitespace_mask;

            // Extract boundary positions
            for i in 0..32 {
                if (transitions & (1 << i)) != 0 {
                    boundaries.push(offset + i);
                }
            }

            prev_whitespace_mask = if (mask_bits & (1 << 31)) != 0 { 1 } else { 0 };
            offset += 32;
        }

        // Process remainder with scalar code
        let remainder = &text[offset..];
        for (i, &byte) in remainder.iter().enumerate() {
            let is_whitespace = matches!(byte, b' ' | b'\t' | b'\n' | b'\r');
            let current_mask = if is_whitespace { 1 } else { 0 };

            if current_mask != prev_whitespace_mask {
                boundaries.push(offset + i);
                prev_whitespace_mask = current_mask;
            }
        }

        boundaries
    }

    /// Fast byte-to-UTF8 validation using SIMD
    #[cfg(target_arch = "x86_64")]
    pub fn validate_utf8_fast(&self, bytes: &[u8]) -> Result<()> {
        if !is_x86_feature_detected!("avx2") {
            return self.validate_utf8_scalar(bytes);
        }

        unsafe { self.validate_utf8_avx2(bytes) }
    }

    /// Fast byte-to-UTF8 validation - fallback for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn validate_utf8_fast(&self, bytes: &[u8]) -> Result<()> {
        self.validate_utf8_scalar(bytes)
    }

    /// Scalar UTF-8 validation
    fn validate_utf8_scalar(&self, bytes: &[u8]) -> Result<()> {
        std::str::from_utf8(bytes)
            .map_err(|e| TrustformersError::invalid_input(format!("Invalid UTF-8: {}", e)))?;
        Ok(())
    }

    /// AVX2-optimized UTF-8 validation
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx2")]
    unsafe fn validate_utf8_avx2(&self, bytes: &[u8]) -> Result<()> {
        // Simplified fast path for ASCII-only text
        let chunks = bytes.chunks_exact(32);
        let remainder = chunks.remainder();

        for chunk in chunks {
            let input = _mm256_loadu_si256(chunk.as_ptr() as *const __m256i);
            let ascii_mask = _mm256_cmpgt_epi8(_mm256_setzero_si256(), input);

            if _mm256_movemask_epi8(ascii_mask) != 0 {
                // Contains non-ASCII, fall back to scalar validation
                return self.validate_utf8_scalar(bytes);
            }
        }

        // Check remainder
        for &byte in remainder {
            if byte >= 128 {
                return self.validate_utf8_scalar(bytes);
            }
        }

        Ok(())
    }

    /// Fast case conversion using SIMD
    #[cfg(target_arch = "x86_64")]
    pub fn to_lowercase_ascii(&self, text: &[u8]) -> Vec<u8> {
        if !is_x86_feature_detected!("avx2") {
            return self.to_lowercase_ascii_scalar(text);
        }

        unsafe { self.to_lowercase_ascii_avx2(text) }
    }

    /// Fast case conversion - fallback for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn to_lowercase_ascii(&self, text: &[u8]) -> Vec<u8> {
        self.to_lowercase_ascii_scalar(text)
    }

    /// Scalar lowercase conversion
    fn to_lowercase_ascii_scalar(&self, text: &[u8]) -> Vec<u8> {
        text.iter()
            .map(|&byte| {
                if byte.is_ascii_uppercase() {
                    byte + 32 // Convert to lowercase
                } else {
                    byte
                }
            })
            .collect()
    }

    /// AVX2-optimized lowercase conversion
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx2")]
    unsafe fn to_lowercase_ascii_avx2(&self, text: &[u8]) -> Vec<u8> {
        let mut result = Vec::with_capacity(text.len());
        let chunks = text.chunks_exact(32);
        let remainder = chunks.remainder();

        let a_upper = _mm256_set1_epi8(b'A' as i8);
        let z_upper = _mm256_set1_epi8(b'Z' as i8);
        let to_lower_offset = _mm256_set1_epi8(32);

        for chunk in chunks {
            let input = _mm256_loadu_si256(chunk.as_ptr() as *const __m256i);

            // Create mask for uppercase letters
            let ge_a = _mm256_cmpgt_epi8(input, _mm256_sub_epi8(a_upper, _mm256_set1_epi8(1)));
            let le_z = _mm256_cmpgt_epi8(_mm256_add_epi8(z_upper, _mm256_set1_epi8(1)), input);
            let is_upper = _mm256_and_si256(ge_a, le_z);

            // Apply lowercase conversion
            let lowercase_offset = _mm256_and_si256(is_upper, to_lower_offset);
            let output = _mm256_add_epi8(input, lowercase_offset);

            let mut temp = [0u8; 32];
            _mm256_storeu_si256(temp.as_mut_ptr() as *mut __m256i, output);
            result.extend_from_slice(&temp);
        }

        // Process remainder
        for &byte in remainder {
            let converted = if byte.is_ascii_uppercase() { byte + 32 } else { byte };
            result.push(converted);
        }

        result
    }

    /// High-performance text preprocessing pipeline
    pub fn preprocess_text(&self, text: &str) -> Result<Vec<String>> {
        let bytes = text.as_bytes();

        // Step 1: Validate UTF-8
        self.validate_utf8_fast(bytes)?;

        // Step 2: Find word boundaries using whitespace detection
        let boundaries = self.find_whitespace_boundaries(bytes);

        // Step 3: Extract tokens
        let mut tokens = Vec::new();
        let mut start = 0;

        for &boundary in &boundaries {
            if start < boundary {
                let token_bytes = &bytes[start..boundary];
                let token = String::from_utf8_lossy(token_bytes).into_owned();
                if !token.trim().is_empty() {
                    tokens.push(token);
                }
            }
            start = boundary;
        }

        // Add final token if any
        if start < bytes.len() {
            let token_bytes = &bytes[start..];
            let token = String::from_utf8_lossy(token_bytes).into_owned();
            if !token.trim().is_empty() {
                tokens.push(token);
            }
        }

        Ok(tokens)
    }
}

impl Default for SimdTokenizer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simd_character_classification() {
        let tokenizer = SimdTokenizer::new();
        let text = b"Hello, World! 123";

        let classifications = tokenizer.classify_ascii_chars(text);

        // 'H' should be alphabetic (bit 0 set)
        assert_eq!(classifications[0] & 1, 1);

        // ',' should be punctuation (bit 3 set)
        assert_eq!(classifications[5] & 8, 8);

        // ' ' should be whitespace (bit 2 set)
        assert_eq!(classifications[6] & 4, 4);

        // '1' should be numeric (bit 1 set)
        assert_eq!(classifications[14] & 2, 2);
    }

    #[test]
    fn test_simd_whitespace_boundaries() {
        let tokenizer = SimdTokenizer::new();
        let text = b"Hello World Test";

        let boundaries = tokenizer.find_whitespace_boundaries(text);

        // Should find boundaries at positions 5 and 11 (before/after spaces)
        assert!(boundaries.contains(&5));
        assert!(boundaries.contains(&6));
        assert!(boundaries.contains(&11));
        assert!(boundaries.contains(&12));
    }

    #[test]
    fn test_simd_utf8_validation() {
        let tokenizer = SimdTokenizer::new();

        // Valid ASCII
        assert!(tokenizer.validate_utf8_fast(b"Hello World").is_ok());

        // Valid UTF-8
        assert!(tokenizer.validate_utf8_fast("Hello 世界".as_bytes()).is_ok());

        // Invalid UTF-8
        assert!(tokenizer.validate_utf8_fast(&[0xFF, 0xFE]).is_err());
    }

    #[test]
    fn test_simd_lowercase() {
        let tokenizer = SimdTokenizer::new();
        let text = b"Hello WORLD Test";

        let lowercase = tokenizer.to_lowercase_ascii(text);
        let expected = b"hello world test";

        assert_eq!(lowercase, expected);
    }

    #[test]
    fn test_simd_preprocess_pipeline() {
        let tokenizer = SimdTokenizer::new();
        let text = "Hello, World! How are you?";

        let tokens = tokenizer.preprocess_text(text).expect("Operation failed in test");

        assert!(tokens.len() > 0);
        assert!(tokens.contains(&"Hello,".to_string()));
        assert!(tokens.contains(&"World!".to_string()));
        assert!(tokens.contains(&"How".to_string()));
    }

    #[test]
    fn test_simd_empty_input() {
        let tokenizer = SimdTokenizer::new();

        assert_eq!(tokenizer.classify_ascii_chars(b"").len(), 0);
        assert_eq!(tokenizer.find_whitespace_boundaries(b"").len(), 0);
        assert!(tokenizer.validate_utf8_fast(b"").is_ok());
        assert_eq!(tokenizer.to_lowercase_ascii(b"").len(), 0);
    }

    #[test]
    fn test_simd_long_input() {
        let tokenizer = SimdTokenizer::new();
        let text = "A".repeat(1000);

        let lowercase = tokenizer.to_lowercase_ascii(text.as_bytes());
        let expected = "a".repeat(1000);

        assert_eq!(lowercase, expected.as_bytes());
    }
}