scirs2-text 0.4.3

Text processing module for SciRS2 (scirs2-text)
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
445
446
447
448
//! Language-agnostic BPE tokenizer with Unicode/NFC normalization.
//!
//! Implements the standard BPE merge algorithm operating on Unicode characters
//! (with optional byte-fallback for unknown characters) rather than on raw
//! bytes alone, so it works across scripts.

use crate::error::{Result, TextError};
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for the Unicode-aware BPE tokenizer.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct UnicodeBpeConfig {
    /// Target vocabulary size (base chars + merge operations).
    pub vocab_size: usize,
    /// Minimum pair frequency for a merge operation to be kept.
    pub min_frequency: usize,
    /// Apply NFC-style normalization (simplified: recompose via canonical form).
    pub normalize: bool,
    /// Represent characters absent from the training vocabulary as `<0xHH>` byte tokens.
    pub byte_fallback: bool,
}

impl Default for UnicodeBpeConfig {
    fn default() -> Self {
        Self {
            vocab_size: 32_000,
            min_frequency: 2,
            normalize: true,
            byte_fallback: true,
        }
    }
}

// ---------------------------------------------------------------------------
// Helper: simplified NFC normalization
// ---------------------------------------------------------------------------

/// Simplified NFC: collect chars, re-emit them — Rust's `char` is Unicode scalar,
/// so collecting into a `String` already yields a well-formed Unicode string.
/// Full NFC would require unicode-normalization; here we at minimum remove
/// ASCII control characters and canonicalize whitespace.
fn nfc_normalize(s: &str) -> String {
    s.chars()
        .filter(|c| !c.is_control() || c.is_whitespace())
        .collect()
}

// ---------------------------------------------------------------------------
// BPE implementation
// ---------------------------------------------------------------------------

/// Unicode-normalized BPE tokenizer that trains on a raw text corpus.
pub struct UnicodeBpeTokenizer {
    config: UnicodeBpeConfig,
    /// token → id mapping (populated after training).
    vocab: HashMap<String, u32>,
    /// id → token reverse mapping.
    id_to_token: Vec<String>,
    /// Ordered list of merge operations (pair → merged token).
    merges: Vec<(String, String)>,
    /// Special tokens always added to the vocabulary.
    special_tokens: Vec<String>,
}

/// Result of a single merge step.
struct MergeResult {
    pair: (String, String),
    freq: usize,
    new_token: String,
}

impl UnicodeBpeTokenizer {
    /// Create an untrained tokenizer with the given configuration.
    pub fn new(config: UnicodeBpeConfig) -> Self {
        Self {
            config,
            vocab: HashMap::new(),
            id_to_token: Vec::new(),
            merges: Vec::new(),
            special_tokens: vec!["<unk>".into(), "<s>".into(), "</s>".into(), "<pad>".into()],
        }
    }

    // -----------------------------------------------------------------------
    // Training
    // -----------------------------------------------------------------------

    /// Train the BPE vocabulary on a corpus of strings.
    pub fn train(&mut self, corpus: &[&str]) -> Result<()> {
        if corpus.is_empty() {
            return Err(TextError::InvalidInput(
                "BPE training corpus must not be empty".into(),
            ));
        }

        // ---- 1. Pre-tokenize corpus into words, normalize ----
        let words: Vec<String> = corpus
            .iter()
            .flat_map(|doc| {
                let normalized = if self.config.normalize {
                    nfc_normalize(doc)
                } else {
                    doc.to_string()
                };
                normalized
                    .split_whitespace()
                    .map(|w| w.to_owned())
                    .collect::<Vec<_>>()
            })
            .filter(|w| !w.is_empty())
            .collect();

        if words.is_empty() {
            return Err(TextError::InvalidInput(
                "corpus has no words after split".into(),
            ));
        }

        // ---- 2. Count word frequencies ----
        let mut word_freq: HashMap<String, usize> = HashMap::new();
        for word in &words {
            *word_freq.entry(word.clone()).or_insert(0) += 1;
        }

        // ---- 3. Represent each word as a sequence of chars (+ </w> end marker) ----
        // word_splits: word → Vec<String> of character tokens
        let mut word_splits: HashMap<String, Vec<String>> = word_freq
            .keys()
            .map(|w| {
                let chars: Vec<String> = w.chars().map(|c| c.to_string()).collect();
                (w.clone(), chars)
            })
            .collect();

        // ---- 4. Collect base character vocabulary ----
        let mut base_chars: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        for chars in word_splits.values() {
            for c in chars {
                base_chars.insert(c.clone());
            }
        }

        // ---- 5. Initialise vocabulary with special tokens + base chars ----
        self.vocab.clear();
        self.id_to_token.clear();
        self.merges.clear();

        for sp in &self.special_tokens {
            let id = self.id_to_token.len() as u32;
            self.vocab.insert(sp.clone(), id);
            self.id_to_token.push(sp.clone());
        }
        for c in &base_chars {
            if !self.vocab.contains_key(c) {
                let id = self.id_to_token.len() as u32;
                self.vocab.insert(c.clone(), id);
                self.id_to_token.push(c.clone());
            }
        }

        // ---- 6. BPE merge loop ----
        let max_merges = self.config.vocab_size.saturating_sub(self.vocab.len());

        for _ in 0..max_merges {
            // Count bigram frequencies
            let mut pair_freq: HashMap<(String, String), usize> = HashMap::new();
            for (word, freq) in &word_freq {
                let chars = match word_splits.get(word) {
                    Some(c) => c,
                    None => continue,
                };
                for window in chars.windows(2) {
                    *pair_freq
                        .entry((window[0].clone(), window[1].clone()))
                        .or_insert(0) += freq;
                }
            }

            // Find best merge (highest frequency, tie-break by lexicographic order)
            let best = pair_freq
                .iter()
                .filter(|(_, &freq)| freq >= self.config.min_frequency)
                .max_by_key(|((a, b), &freq)| (freq, std::cmp::Reverse((a.clone(), b.clone()))));

            let merge = match best {
                Some(((a, b), &freq)) => MergeResult {
                    pair: (a.clone(), b.clone()),
                    freq,
                    new_token: format!("{}{}", a, b),
                },
                None => break, // no more eligible merges
            };

            if merge.freq < self.config.min_frequency {
                break;
            }

            // Register new token
            if !self.vocab.contains_key(&merge.new_token) {
                let id = self.id_to_token.len() as u32;
                self.vocab.insert(merge.new_token.clone(), id);
                self.id_to_token.push(merge.new_token.clone());
            }
            self.merges.push(merge.pair.clone());

            // Apply merge to all word splits
            let (ref left, ref right) = merge.pair;
            for chars in word_splits.values_mut() {
                let mut i = 0;
                while i + 1 < chars.len() {
                    if chars[i] == *left && chars[i + 1] == *right {
                        let merged = format!("{}{}", chars[i], chars[i + 1]);
                        chars.splice(i..=i + 1, std::iter::once(merged));
                        // Don't advance i — the newly merged token might pair again
                    } else {
                        i += 1;
                    }
                }
            }
        }

        Ok(())
    }

    // -----------------------------------------------------------------------
    // Encoding
    // -----------------------------------------------------------------------

    /// Tokenize a string to token IDs.
    pub fn encode(&self, text: &str) -> Result<Vec<u32>> {
        if self.vocab.is_empty() {
            return Err(TextError::ModelNotFitted(
                "BPE tokenizer has not been trained".into(),
            ));
        }

        let normalized = if self.config.normalize {
            nfc_normalize(text)
        } else {
            text.to_string()
        };

        let unk_id = self.vocab.get("<unk>").copied().unwrap_or(0);

        let mut ids = Vec::new();

        for word in normalized.split_whitespace() {
            // Split word into individual characters
            let mut chars: Vec<String> = word.chars().map(|c| c.to_string()).collect();

            // Apply merges in training order
            for (left, right) in &self.merges {
                let mut i = 0;
                while i + 1 < chars.len() {
                    if chars[i] == *left && chars[i + 1] == *right {
                        let merged = format!("{}{}", chars[i], chars[i + 1]);
                        chars.splice(i..=i + 1, std::iter::once(merged));
                    } else {
                        i += 1;
                    }
                }
            }

            for tok in chars {
                if let Some(&id) = self.vocab.get(&tok) {
                    ids.push(id);
                } else if self.config.byte_fallback {
                    // Encode as individual UTF-8 bytes: <0xHH>
                    for byte in tok.as_bytes() {
                        let byte_tok = format!("<0x{:02X}>", byte);
                        let id = self.vocab.get(&byte_tok).copied().unwrap_or(unk_id);
                        ids.push(id);
                    }
                } else {
                    ids.push(unk_id);
                }
            }
        }

        Ok(ids)
    }

    // -----------------------------------------------------------------------
    // Decoding
    // -----------------------------------------------------------------------

    /// Decode token IDs back to a string.
    pub fn decode(&self, ids: &[u32]) -> Result<String> {
        if self.id_to_token.is_empty() {
            return Err(TextError::ModelNotFitted(
                "BPE tokenizer has not been trained".into(),
            ));
        }
        let mut parts = Vec::new();
        for &id in ids {
            let idx = id as usize;
            if idx >= self.id_to_token.len() {
                return Err(TextError::InvalidInput(format!(
                    "token id {} out of vocabulary range {}",
                    id,
                    self.id_to_token.len()
                )));
            }
            parts.push(self.id_to_token[idx].clone());
        }
        Ok(parts.join(" "))
    }

    /// Current vocabulary size (number of entries in the token → id mapping).
    pub fn vocab_size(&self) -> usize {
        self.vocab.len()
    }

    /// Number of merge operations learned during training.
    pub fn n_merges(&self) -> usize {
        self.merges.len()
    }

    /// Access the raw vocabulary map.
    pub fn vocab(&self) -> &HashMap<String, u32> {
        &self.vocab
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn small_corpus() -> Vec<&'static str> {
        vec![
            "low lower lowest",
            "new newer newest",
            "low new lower newest",
            "the lowest number",
        ]
    }

    #[test]
    fn test_default_config() {
        let cfg = UnicodeBpeConfig::default();
        assert_eq!(cfg.vocab_size, 32_000);
        assert_eq!(cfg.min_frequency, 2);
        assert!(cfg.normalize);
        assert!(cfg.byte_fallback);
    }

    #[test]
    fn test_train_empty_corpus_error() {
        let mut tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig::default());
        let result = tok.train(&[]);
        assert!(result.is_err(), "empty corpus must return error");
    }

    #[test]
    fn test_train_succeeds() {
        let mut tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig::default());
        tok.train(&small_corpus()).expect("train failed");
        assert!(
            tok.vocab_size() > 0,
            "vocab should be non-empty after training"
        );
    }

    #[test]
    fn test_vocab_size_bounded() {
        let config = UnicodeBpeConfig {
            vocab_size: 20,
            min_frequency: 1,
            ..Default::default()
        };
        let mut tok = UnicodeBpeTokenizer::new(config);
        tok.train(&small_corpus()).expect("train failed");
        assert!(
            tok.vocab_size() <= 20,
            "vocab size {} must be <= 20",
            tok.vocab_size()
        );
    }

    #[test]
    fn test_encode_returns_ids() {
        let mut tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig {
            min_frequency: 1,
            ..Default::default()
        });
        tok.train(&small_corpus()).expect("train failed");
        let ids = tok.encode("low").expect("encode failed");
        assert!(
            !ids.is_empty(),
            "encoding 'low' should produce at least one id"
        );
    }

    #[test]
    fn test_encode_before_train_error() {
        let tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig::default());
        let result = tok.encode("hello");
        assert!(result.is_err(), "encode before train must return error");
    }

    #[test]
    fn test_decode_before_train_error() {
        let tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig::default());
        let result = tok.decode(&[0, 1]);
        assert!(result.is_err(), "decode before train must return error");
    }

    #[test]
    fn test_n_merges_increases_with_training() {
        let mut tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig {
            vocab_size: 50,
            min_frequency: 1,
            ..Default::default()
        });
        tok.train(&small_corpus()).expect("train failed");
        assert!(tok.n_merges() > 0, "should have at least one merge");
    }

    #[test]
    fn test_special_tokens_in_vocab() {
        let mut tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig::default());
        tok.train(&small_corpus()).expect("train failed");
        assert!(tok.vocab().contains_key("<unk>"));
        assert!(tok.vocab().contains_key("<s>"));
        assert!(tok.vocab().contains_key("</s>"));
    }

    #[test]
    fn test_decode_special_token() {
        let mut tok = UnicodeBpeTokenizer::new(UnicodeBpeConfig {
            min_frequency: 1,
            ..Default::default()
        });
        tok.train(&small_corpus()).expect("train failed");
        let unk_id = tok.vocab()["<unk>"];
        let decoded = tok.decode(&[unk_id]).expect("decode failed");
        assert_eq!(decoded, "<unk>");
    }
}