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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Enhanced BPE tokenizer with LLM-compatible features.
//!
//! Supports special tokens, chat templates, and byte-level fallback.
//! Designed for compatibility with GPT-2, LLaMA, Mistral, and ChatML-style models.

use std::collections::HashMap;

/// Errors produced by the enhanced BPE tokenizer.
#[derive(Debug, thiserror::Error)]
pub enum BpeError {
    /// A token was not found in the vocabulary.
    #[error("Unknown token: {0}")]
    UnknownToken(String),
    /// The vocabulary is structurally invalid.
    #[error("Invalid vocabulary")]
    InvalidVocab,
    /// A chat template formatting error.
    #[error("Template error: {0}")]
    TemplateError(String),
}

// ─── Special tokens ──────────────────────────────────────────────────────────

/// Special tokens used by LLM tokenizers.
///
/// Each field is optional; `None` means the model does not use that token type.
/// The `custom` map holds additional model-specific tokens (e.g., `<|im_start|>`).
#[derive(Debug, Clone)]
pub struct SpecialTokens {
    /// Beginning-of-sequence token.
    pub bos: Option<String>,
    /// End-of-sequence token.
    pub eos: Option<String>,
    /// Unknown-word fallback token.
    pub unk: Option<String>,
    /// Padding token.
    pub pad: Option<String>,
    /// Separator token (multi-sequence models).
    pub sep: Option<String>,
    /// Classification token (BERT-style).
    pub cls: Option<String>,
    /// Mask token (for masked LM).
    pub mask: Option<String>,
    /// Additional model-specific special tokens mapped to preferred IDs.
    /// The preferred IDs are treated as hints; `BpeVocab::new` skips tokens
    /// already registered via the standard fields.
    pub custom: HashMap<String, u32>,
}

impl Default for SpecialTokens {
    fn default() -> Self {
        Self {
            bos: None,
            eos: None,
            unk: Some("<unk>".into()),
            pad: Some("<pad>".into()),
            sep: None,
            cls: None,
            mask: None,
            custom: HashMap::new(),
        }
    }
}

impl SpecialTokens {
    /// GPT-2 style special tokens (`<|endoftext|>` for both BOS and EOS).
    pub fn gpt2() -> Self {
        Self {
            bos: Some("<|endoftext|>".into()),
            eos: Some("<|endoftext|>".into()),
            ..Default::default()
        }
    }

    /// LLaMA / Mistral style special tokens (`<s>` / `</s>`).
    pub fn llama() -> Self {
        Self {
            bos: Some("<s>".into()),
            eos: Some("</s>".into()),
            unk: Some("<unk>".into()),
            ..Default::default()
        }
    }

    /// ChatML style special tokens (`<|im_start|>` / `<|im_end|>`).
    ///
    /// The custom map is left empty here because `BpeVocab::new` will assign
    /// IDs to bos/eos during the standard loop; the `<|im_start|>` and
    /// `<|im_end|>` entries in `custom` would conflict with those IDs.
    /// If callers need a specific custom token not covered by bos/eos/unk/pad,
    /// they can insert into `custom` after construction.
    pub fn chatml() -> Self {
        Self {
            bos: Some("<|im_start|>".into()),
            eos: Some("<|im_end|>".into()),
            custom: HashMap::new(),
            ..Default::default()
        }
    }
}

// ─── BPE vocabulary ───────────────────────────────────────────────────────────

/// BPE vocabulary with ordered merge rules and special-token awareness.
#[derive(Debug, Clone)]
pub struct BpeVocab {
    /// Token string → integer ID.
    pub token_to_id: HashMap<String, u32>,
    /// Integer ID → token string.
    pub id_to_token: HashMap<u32, String>,
    /// Ordered merge rules learned during training (earlier = higher priority).
    pub merges: Vec<(String, String)>,
    /// The special-token configuration used to build this vocab.
    pub special_tokens: SpecialTokens,
}

impl BpeVocab {
    /// Create a new vocabulary, pre-registering all special tokens.
    ///
    /// Standard special tokens (bos, eos, unk, pad, sep, cls, mask) are
    /// assigned IDs 0, 1, 2, … in declaration order, skipping duplicates.
    /// Custom tokens from `special_tokens.custom` are registered next,
    /// but only if the token string has not already been added by the
    /// standard loop (prevents ID collisions).
    pub fn new(special_tokens: SpecialTokens) -> Self {
        let mut vocab = Self {
            token_to_id: HashMap::new(),
            id_to_token: HashMap::new(),
            merges: Vec::new(),
            special_tokens: special_tokens.clone(),
        };

        // Register standard special tokens in declaration order.
        let standard_slots: &[Option<&str>] = &[
            special_tokens.bos.as_deref(),
            special_tokens.eos.as_deref(),
            special_tokens.unk.as_deref(),
            special_tokens.pad.as_deref(),
            special_tokens.sep.as_deref(),
            special_tokens.cls.as_deref(),
            special_tokens.mask.as_deref(),
        ];
        for slot in standard_slots.iter().flatten() {
            vocab.ensure_token(slot);
        }

        // Register custom tokens; skip any that already have an ID.
        // We sort by preferred ID for deterministic ordering.
        let mut custom_sorted: Vec<(&String, u32)> =
            special_tokens.custom.iter().map(|(k, &v)| (k, v)).collect();
        custom_sorted.sort_by_key(|&(_, id)| id);
        for (tok, _preferred_id) in custom_sorted {
            vocab.ensure_token(tok);
        }

        vocab
    }

    /// Register a token if not yet present and return its ID.
    fn ensure_token(&mut self, token: &str) -> u32 {
        if let Some(&id) = self.token_to_id.get(token) {
            return id;
        }
        let id = self.token_to_id.len() as u32;
        self.token_to_id.insert(token.to_string(), id);
        self.id_to_token.insert(id, token.to_string());
        id
    }

    /// Add a token, returning its ID.  If the token already exists the
    /// existing ID is returned without modification.
    pub fn add_token(&mut self, token: String) -> u32 {
        self.ensure_token(&token)
    }

    /// Number of tokens in the vocabulary.
    pub fn vocab_size(&self) -> usize {
        self.token_to_id.len()
    }

    /// Look up the ID for a token string, returning `None` if not found.
    pub fn get_id(&self, token: &str) -> Option<u32> {
        self.token_to_id.get(token).copied()
    }

    /// Look up the token string for an ID, returning `None` if not found.
    pub fn get_token(&self, id: u32) -> Option<&str> {
        self.id_to_token.get(&id).map(String::as_str)
    }

    /// Returns `true` if `token` is registered as any kind of special token.
    pub fn is_special(&self, token: &str) -> bool {
        let s = &self.special_tokens;
        s.bos.as_deref() == Some(token)
            || s.eos.as_deref() == Some(token)
            || s.unk.as_deref() == Some(token)
            || s.pad.as_deref() == Some(token)
            || s.sep.as_deref() == Some(token)
            || s.cls.as_deref() == Some(token)
            || s.mask.as_deref() == Some(token)
            || s.custom.contains_key(token)
    }
}

// ─── Byte-level BPE tokenizer ────────────────────────────────────────────────

/// Byte-level BPE tokenizer (GPT-2 style).
///
/// The vocabulary is seeded with 256 byte tokens using a `Ġ`-prefixed encoding
/// (`Ġ\x00` … `Ġÿ`), then additional merge rules are applied during training.
/// This implementation handles encoding and decoding; actual merge-rule training
/// is left to external tooling (HuggingFace `tokenizers`, etc.).
pub struct ByteLevelBpe {
    /// The underlying vocabulary.
    pub vocab: BpeVocab,
}

impl ByteLevelBpe {
    /// Create a new byte-level BPE tokenizer seeded with byte tokens and
    /// the provided special tokens.
    pub fn new(special_tokens: SpecialTokens) -> Self {
        let mut vocab = BpeVocab::new(special_tokens);
        // Add all 256 byte tokens as the base vocabulary.
        // GPT-2 uses a `Ġ` prefix so each byte maps to a distinct, displayable
        // token string (`Ġa`, `Ġb`, …, `Ġ\x00`, …).
        for b in 0u8..=255 {
            let token = format!("Ġ{}", b as char);
            vocab.ensure_token(&token);
        }
        Self { vocab }
    }

    /// Total number of tokens in the vocabulary.
    pub fn vocab_size(&self) -> usize {
        self.vocab.vocab_size()
    }

    /// Encode `text` into token IDs.
    ///
    /// When `add_special_tokens` is `true`, the BOS token is prepended and the
    /// EOS token is appended (if either is configured).
    ///
    /// This implementation performs character-level byte encoding.  A production
    /// tokenizer would additionally apply ordered BPE merge rules; this is
    /// intentionally omitted to keep the implementation self-contained.
    pub fn encode(&self, text: &str, add_special_tokens: bool) -> Vec<u32> {
        let mut ids = Vec::new();

        if add_special_tokens {
            if let Some(bos_id) = self
                .vocab
                .special_tokens
                .bos
                .as_deref()
                .and_then(|t| self.vocab.get_id(t))
            {
                ids.push(bos_id);
            }
        }

        // Encode each character via the Ġ-prefixed byte-token representation.
        let unk_id = self
            .vocab
            .special_tokens
            .unk
            .as_deref()
            .and_then(|t| self.vocab.get_id(t))
            .unwrap_or(0);

        for ch in text.chars() {
            let token = format!("Ġ{ch}");
            let id = self.vocab.get_id(&token).unwrap_or(unk_id);
            ids.push(id);
        }

        if add_special_tokens {
            if let Some(eos_id) = self
                .vocab
                .special_tokens
                .eos
                .as_deref()
                .and_then(|t| self.vocab.get_id(t))
            {
                ids.push(eos_id);
            }
        }

        ids
    }

    /// Decode a sequence of token IDs back to a string.
    ///
    /// When `skip_special_tokens` is `true`, any token registered as a special
    /// token (BOS, EOS, UNK, PAD, etc.) is omitted from the output.
    pub fn decode(&self, ids: &[u32], skip_special_tokens: bool) -> String {
        ids.iter()
            .filter_map(|&id| {
                let tok = self.vocab.get_token(id)?;
                if skip_special_tokens && self.vocab.is_special(tok) {
                    return None;
                }
                // Strip the leading Ġ prefix added during encoding.
                Some(tok.trim_start_matches('Ġ').to_string())
            })
            .collect()
    }
}

// ─── Chat templates ───────────────────────────────────────────────────────────

/// A single message in a multi-turn conversation.
#[derive(Debug, Clone)]
pub struct Message {
    /// The role of the author: `"user"`, `"assistant"`, or `"system"`.
    pub role: String,
    /// The text content of the message.
    pub content: String,
}

/// The formatting style used by a [`ChatTemplate`].
#[derive(Debug, Clone)]
pub enum ChatStyle {
    /// ChatML format: `<|im_start|>role\ncontent<|im_end|>\n`.
    ChatML,
    /// LLaMA-2 format: `[INST] user [/INST] assistant </s>`.
    Llama2,
    /// Alpaca format: `### Instruction:\n… ### Response:\n`.
    Alpaca,
    /// Simple human-readable format: `role: content\n`.
    Simple,
}

/// Formats a list of [`Message`]s into a model-ready prompt string.
///
/// Each LLM family expects a distinct conversation format.  `ChatTemplate`
/// encodes these conventions so that callers need not hard-code format strings.
#[derive(Debug, Clone)]
pub struct ChatTemplate {
    /// The formatting style to apply.
    pub style: ChatStyle,
}

impl ChatTemplate {
    /// Create a new template with the given style.
    pub fn new(style: ChatStyle) -> Self {
        Self { style }
    }

    /// Format `messages` into a prompt string.
    ///
    /// When `add_generation_prompt` is `true`, the template appends a partial
    /// assistant turn header so that the model can begin generating immediately
    /// (e.g., `<|im_start|>assistant\n` for ChatML).
    pub fn apply(&self, messages: &[Message], add_generation_prompt: bool) -> String {
        match &self.style {
            ChatStyle::ChatML => {
                let mut s = String::new();
                for msg in messages {
                    s.push_str(&format!(
                        "<|im_start|>{}\n{}<|im_end|>\n",
                        msg.role, msg.content
                    ));
                }
                if add_generation_prompt {
                    s.push_str("<|im_start|>assistant\n");
                }
                s
            }

            ChatStyle::Llama2 => {
                let mut s = String::new();
                for msg in messages {
                    match msg.role.as_str() {
                        "system" => {
                            s.push_str(&format!("<<SYS>>\n{}\n<</SYS>>\n", msg.content));
                        }
                        "user" => {
                            s.push_str(&format!("[INST] {} [/INST]", msg.content));
                        }
                        "assistant" => {
                            s.push_str(&format!(" {} </s>", msg.content));
                        }
                        _ => {
                            s.push_str(&msg.content);
                        }
                    }
                }
                s
            }

            ChatStyle::Alpaca => {
                let mut s = String::new();
                for msg in messages {
                    match msg.role.as_str() {
                        "user" => {
                            s.push_str(&format!("### Instruction:\n{}\n\n", msg.content));
                        }
                        "assistant" => {
                            s.push_str(&format!("### Response:\n{}\n\n", msg.content));
                        }
                        _ => {}
                    }
                }
                if add_generation_prompt {
                    s.push_str("### Response:\n");
                }
                s
            }

            ChatStyle::Simple => messages
                .iter()
                .map(|m| format!("{}: {}\n", m.role, m.content))
                .collect(),
        }
    }

    /// Approximate token count for `messages` using whitespace splitting.
    ///
    /// This is a fast heuristic; for precise counts, encode the formatted
    /// prompt with a full BPE tokenizer.
    pub fn count_tokens(&self, messages: &[Message]) -> usize {
        let prompt = self.apply(messages, false);
        prompt.split_whitespace().count()
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_special_tokens_gpt2() {
        let st = SpecialTokens::gpt2();
        assert_eq!(st.bos.as_deref(), Some("<|endoftext|>"));
        assert_eq!(st.eos.as_deref(), Some("<|endoftext|>"));
    }

    #[test]
    fn test_special_tokens_llama() {
        let st = SpecialTokens::llama();
        assert_eq!(st.bos.as_deref(), Some("<s>"));
        assert_eq!(st.eos.as_deref(), Some("</s>"));
    }

    #[test]
    fn test_bpe_vocab_add_token() {
        let mut vocab = BpeVocab::new(SpecialTokens::default());
        let id = vocab.add_token("hello".to_string());
        assert_eq!(vocab.get_id("hello"), Some(id));
        assert_eq!(vocab.get_token(id), Some("hello"));
    }

    #[test]
    fn test_bpe_vocab_special_tokens() {
        let vocab = BpeVocab::new(SpecialTokens::llama());
        assert!(vocab.is_special("<s>"));
        assert!(vocab.is_special("</s>"));
        assert!(!vocab.is_special("hello"));
    }

    #[test]
    fn test_byte_level_bpe_encode_decode() {
        let bpe = ByteLevelBpe::new(SpecialTokens::gpt2());
        let ids = bpe.encode("abc", false);
        assert_eq!(ids.len(), 3);
        let decoded = bpe.decode(&ids, false);
        assert_eq!(decoded, "abc");
    }

    #[test]
    fn test_byte_level_bpe_with_special_tokens() {
        let bpe = ByteLevelBpe::new(SpecialTokens::gpt2());
        let ids = bpe.encode("hi", true);
        // BOS + 'h' + 'i' + EOS = 4 tokens
        assert_eq!(ids.len(), 4);
        let decoded = bpe.decode(&ids, true);
        assert_eq!(decoded, "hi");
    }

    #[test]
    fn test_chat_template_chatml() {
        let tmpl = ChatTemplate::new(ChatStyle::ChatML);
        let msgs = vec![
            Message {
                role: "user".to_string(),
                content: "Hello".to_string(),
            },
            Message {
                role: "assistant".to_string(),
                content: "Hi!".to_string(),
            },
        ];
        let prompt = tmpl.apply(&msgs, false);
        assert!(prompt.contains("<|im_start|>user"));
        assert!(prompt.contains("<|im_end|>"));
        assert!(prompt.contains("Hello"));
    }

    #[test]
    fn test_chat_template_generation_prompt() {
        let tmpl = ChatTemplate::new(ChatStyle::ChatML);
        let msgs = vec![Message {
            role: "user".to_string(),
            content: "Hello".to_string(),
        }];
        let prompt = tmpl.apply(&msgs, true);
        assert!(
            prompt.ends_with("<|im_start|>assistant\n"),
            "Expected generation prompt at end: {prompt}"
        );
    }

    #[test]
    fn test_chat_template_llama2() {
        let tmpl = ChatTemplate::new(ChatStyle::Llama2);
        let msgs = vec![Message {
            role: "user".to_string(),
            content: "Tell me a joke".to_string(),
        }];
        let prompt = tmpl.apply(&msgs, false);
        assert!(prompt.contains("[INST]") && prompt.contains("[/INST]"));
    }

    #[test]
    fn test_chat_template_token_count() {
        let tmpl = ChatTemplate::new(ChatStyle::Simple);
        let msgs = vec![Message {
            role: "user".to_string(),
            content: "Hello world how are you".to_string(),
        }];
        let count = tmpl.count_tokens(&msgs);
        assert!(count >= 5, "Expected >= 5 tokens, got {count}");
    }

    #[test]
    fn test_vocab_size() {
        let bpe = ByteLevelBpe::new(SpecialTokens::default());
        // 256 byte tokens + at least 2 standard special tokens (unk, pad)
        assert!(bpe.vocab_size() >= 256);
    }

    #[test]
    fn test_chatml_no_id_collision() {
        // Ensure BpeVocab correctly handles ChatML tokens without ID conflicts.
        let vocab = BpeVocab::new(SpecialTokens::chatml());
        let bos_id = vocab.get_id("<|im_start|>");
        let eos_id = vocab.get_id("<|im_end|>");
        assert!(bos_id.is_some());
        assert!(eos_id.is_some());
        // IDs must be distinct.
        assert_ne!(bos_id, eos_id);
        // Reverse lookup must be consistent.
        assert_eq!(vocab.get_token(bos_id.unwrap()), Some("<|im_start|>"));
        assert_eq!(vocab.get_token(eos_id.unwrap()), Some("<|im_end|>"));
    }

    #[test]
    fn test_alpaca_template() {
        let tmpl = ChatTemplate::new(ChatStyle::Alpaca);
        let msgs = vec![
            Message {
                role: "user".to_string(),
                content: "What is Rust?".to_string(),
            },
            Message {
                role: "assistant".to_string(),
                content: "A systems language.".to_string(),
            },
        ];
        let prompt = tmpl.apply(&msgs, true);
        assert!(prompt.contains("### Instruction:"));
        assert!(prompt.contains("### Response:"));
        assert!(prompt.ends_with("### Response:\n"));
    }

    #[test]
    fn test_llama_special_token_is_special() {
        let bpe = ByteLevelBpe::new(SpecialTokens::llama());
        // Check that <s> and </s> are recognized as special.
        assert!(bpe.vocab.is_special("<s>"));
        assert!(bpe.vocab.is_special("</s>"));
        // A normal byte token should not be special.
        assert!(!bpe.vocab.is_special("Ġa"));
    }
}