File size: 12,538 Bytes
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPF Smart Gateway - BPE Tokenizer
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Byte-Pair Encoding tokenizer for SPF Transformer.
// Trains on SPF corpus (brain data, source code, rules).
// Pure Rust. No external tokenizer dependencies.
//
// Depends on: nothing (Layer 0)

use std::collections::HashMap;

// ============================================================================
// SPECIAL TOKENS
// ============================================================================

pub const PAD_TOKEN: &str = "[PAD]";
pub const BOS_TOKEN: &str = "[BOS]";
pub const EOS_TOKEN: &str = "[EOS]";
pub const UNK_TOKEN: &str = "[UNK]";
pub const TOOL_TOKEN: &str = "[TOOL]";
pub const GATE_TOKEN: &str = "[GATE]";
pub const USER_TOKEN: &str = "[USER]";
pub const SPF_TOKEN: &str = "[SPF]";
pub const ALLOWED_TOKEN: &str = "[ALLOWED]";
pub const BLOCKED_TOKEN: &str = "[BLOCKED]";

pub const PAD_ID: u32 = 0;
pub const BOS_ID: u32 = 1;
pub const EOS_ID: u32 = 2;
pub const UNK_ID: u32 = 3;
pub const TOOL_ID: u32 = 4;
pub const GATE_ID: u32 = 5;
pub const USER_ID: u32 = 6;
pub const SPF_ID: u32 = 7;
pub const ALLOWED_ID: u32 = 8;
pub const BLOCKED_ID: u32 = 9;

const NUM_SPECIAL: u32 = 10;

// ============================================================================
// BPE TOKENIZER
// ============================================================================

/// Byte-Pair Encoding tokenizer with SPF-specific special tokens
#[derive(Clone)]
pub struct Tokenizer {
    /// Token string → ID
    token_to_id: HashMap<String, u32>,
    /// ID → token string
    id_to_token: HashMap<u32, String>,
    /// Merge rules: (pair) → merged token, ordered by priority
    merges: Vec<(String, String)>,
    /// Vocabulary size
    pub vocab_size: u32,
}

impl Tokenizer {
    /// Create a new tokenizer with only special tokens (untrained)
    pub fn new() -> Self {
        let mut tok = Self {
            token_to_id: HashMap::new(),
            id_to_token: HashMap::new(),
            merges: Vec::new(),
            vocab_size: NUM_SPECIAL,
        };
        // Register special tokens
        let specials = [
            PAD_TOKEN, BOS_TOKEN, EOS_TOKEN, UNK_TOKEN, TOOL_TOKEN,
            GATE_TOKEN, USER_TOKEN, SPF_TOKEN, ALLOWED_TOKEN, BLOCKED_TOKEN,
        ];
        for (i, &s) in specials.iter().enumerate() {
            tok.token_to_id.insert(s.to_string(), i as u32);
            tok.id_to_token.insert(i as u32, s.to_string());
        }
        tok
    }

    /// Load tokenizer vocabulary from JSON file.
    /// Falls back to untrained tokenizer if file doesn't exist.
    pub fn load(path: &str) -> Result<Self, String> {
        let file_path = std::path::Path::new(path);
        if !file_path.exists() {
            // No trained tokenizer yet — use untrained (special tokens + byte fallback)
            return Ok(Self::new());
        }
        let content = std::fs::read_to_string(file_path)
            .map_err(|e| format!("Read error: {}", e))?;
        Self::from_json(&content)
    }

    /// Save tokenizer vocabulary to JSON file.
    pub fn save(&self, path: &str) -> Result<(), String> {
        let json = self.to_json();
        std::fs::write(path, json)
            .map_err(|e| format!("Write error: {}", e))
    }

    /// Train BPE on a corpus of text. Learns `num_merges` merge rules.
    /// `target_vocab` is the desired vocabulary size (including special tokens).
    pub fn train(&mut self, corpus: &str, target_vocab: u32) {
        let num_merges = target_vocab.saturating_sub(NUM_SPECIAL + 256); // 256 byte-level tokens

        // Step 1: Initialize vocabulary with all byte values
        for b in 0u8..=255 {
            let token = format!("{}", b as char);
            let id = NUM_SPECIAL + b as u32;
            self.token_to_id.insert(token.clone(), id);
            self.id_to_token.insert(id, token);
        }
        self.vocab_size = NUM_SPECIAL + 256;

        // Step 2: Tokenize corpus into byte-level tokens
        let mut words: Vec<Vec<String>> = corpus
            .split_whitespace()
            .map(|w| w.chars().map(|c| c.to_string()).collect())
            .collect();

        // Step 3: Iteratively merge most frequent pairs
        for _ in 0..num_merges {
            // Count all adjacent pairs
            let mut pair_counts: HashMap<(String, String), u64> = HashMap::new();
            for word in &words {
                for pair in word.windows(2) {
                    *pair_counts
                        .entry((pair[0].clone(), pair[1].clone()))
                        .or_insert(0) += 1;
                }
            }

            if pair_counts.is_empty() {
                break;
            }

            // Find most frequent pair
            let best_pair = pair_counts
                .iter()
                .max_by_key(|(_, &count)| count)
                .map(|(pair, _)| pair.clone());

            let (left, right) = match best_pair {
                Some(p) => p,
                None => break,
            };

            // Create merged token
            let merged = format!("{}{}", left, right);

            // Register in vocabulary
            let id = self.vocab_size;
            self.token_to_id.insert(merged.clone(), id);
            self.id_to_token.insert(id, merged.clone());
            self.merges.push((left.clone(), right.clone()));
            self.vocab_size += 1;

            // Apply merge to all words
            for word in &mut words {
                let mut i = 0;
                while i + 1 < word.len() {
                    if word[i] == left && word[i + 1] == right {
                        word[i] = merged.clone();
                        word.remove(i + 1);
                    } else {
                        i += 1;
                    }
                }
            }
        }
    }

    /// Encode text to token IDs
    pub fn encode(&self, text: &str) -> Vec<u32> {
        let mut tokens = Vec::new();

        for word in text.split_whitespace() {
            // Check if it's a special token
            if let Some(&id) = self.token_to_id.get(word) {
                tokens.push(id);
                continue;
            }

            // Byte-level tokenization
            let mut chars: Vec<String> = word.chars().map(|c| c.to_string()).collect();

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

            // Convert to IDs
            for ch in &chars {
                match self.token_to_id.get(ch) {
                    Some(&id) => tokens.push(id),
                    None => tokens.push(UNK_ID),
                }
            }
        }

        tokens
    }

    /// Decode token IDs back to text
    pub fn decode(&self, ids: &[u32]) -> String {
        let mut parts = Vec::new();
        for &id in ids {
            match self.id_to_token.get(&id) {
                Some(token) => {
                    // Skip special tokens in output (except content ones)
                    match id {
                        PAD_ID | BOS_ID | EOS_ID => continue,
                        _ => parts.push(token.clone()),
                    }
                }
                None => parts.push(UNK_TOKEN.to_string()),
            }
        }
        parts.join("")
    }

    /// Encode with BOS/EOS wrapping
    pub fn encode_with_special(&self, text: &str) -> Vec<u32> {
        let mut ids = vec![BOS_ID];
        ids.extend(self.encode(text));
        ids.push(EOS_ID);
        ids
    }

    /// Get token string for an ID
    pub fn get_token(&self, id: u32) -> Option<&str> {
        self.id_to_token.get(&id).map(|s| s.as_str())
    }

    /// Get ID for a token string
    pub fn get_id(&self, token: &str) -> Option<u32> {
        self.token_to_id.get(token).copied()
    }

    /// Serialize tokenizer state to JSON
    pub fn to_json(&self) -> String {
        let merges_json: Vec<String> = self.merges
            .iter()
            .map(|(l, r)| format!("[\"{}\",\"{}\"]", l.replace('"', "\\\""), r.replace('"', "\\\"")))
            .collect();

        let vocab_json: Vec<String> = self.token_to_id
            .iter()
            .map(|(k, v)| format!("\"{}\":{}", k.replace('"', "\\\""), v))
            .collect();

        format!(
            "{{\"vocab_size\":{},\"merges\":[{}],\"vocab\":{{{}}}}}",
            self.vocab_size,
            merges_json.join(","),
            vocab_json.join(",")
        )
    }

    /// Deserialize tokenizer from JSON string
    pub fn from_json(json: &str) -> Result<Self, String> {
        let parsed: serde_json::Value = serde_json::from_str(json)
            .map_err(|e| format!("Tokenizer JSON parse error: {}", e))?;

        let mut tok = Self::new();

        // Load vocab
        if let Some(vocab) = parsed.get("vocab").and_then(|v| v.as_object()) {
            for (token, id) in vocab {
                if let Some(id_num) = id.as_u64() {
                    let id32 = id_num as u32;
                    tok.token_to_id.insert(token.clone(), id32);
                    tok.id_to_token.insert(id32, token.clone());
                }
            }
        }

        // Load merges
        if let Some(merges) = parsed.get("merges").and_then(|m| m.as_array()) {
            for pair in merges {
                if let Some(arr) = pair.as_array() {
                    if arr.len() == 2 {
                        if let (Some(l), Some(r)) = (arr[0].as_str(), arr[1].as_str()) {
                            tok.merges.push((l.to_string(), r.to_string()));
                        }
                    }
                }
            }
        }

        // Load vocab size
        if let Some(vs) = parsed.get("vocab_size").and_then(|v| v.as_u64()) {
            tok.vocab_size = vs as u32;
        } else {
            tok.vocab_size = tok.token_to_id.len() as u32;
        }

        Ok(tok)
    }
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_special_tokens() {
        let tok = Tokenizer::new();
        assert_eq!(tok.get_id(PAD_TOKEN), Some(PAD_ID));
        assert_eq!(tok.get_id(BOS_TOKEN), Some(BOS_ID));
        assert_eq!(tok.get_id(TOOL_TOKEN), Some(TOOL_ID));
        assert_eq!(tok.get_id(GATE_TOKEN), Some(GATE_ID));
        assert_eq!(tok.get_token(SPF_ID), Some(SPF_TOKEN));
    }

    #[test]
    fn test_train_and_encode() {
        let mut tok = Tokenizer::new();
        let corpus = "the cat sat on the mat the cat the mat";
        tok.train(corpus, 300);

        let ids = tok.encode("the cat");
        assert!(!ids.is_empty());
        assert!(ids.iter().all(|&id| id != UNK_ID));
    }

    #[test]
    fn test_roundtrip() {
        let mut tok = Tokenizer::new();
        tok.train("hello world hello world", 300);

        let text = "hello";
        let ids = tok.encode(text);
        let decoded = tok.decode(&ids);
        assert_eq!(decoded, text);
    }

    #[test]
    fn test_encode_with_special() {
        let mut tok = Tokenizer::new();
        tok.train("test data", 300);

        let ids = tok.encode_with_special("test");
        assert_eq!(ids[0], BOS_ID);
        assert_eq!(*ids.last().unwrap(), EOS_ID);
    }

    #[test]
    fn test_unknown_token() {
        let tok = Tokenizer::new(); // untrained — only specials + no bytes
        // With an untrained tokenizer, byte-level chars might not exist
        // This tests the UNK fallback path
        assert_eq!(tok.vocab_size, NUM_SPECIAL);
    }

    #[test]
    fn test_json_roundtrip() {
        let mut tok = Tokenizer::new();
        tok.train("the cat sat on the mat", 300);

        let json = tok.to_json();
        let tok2 = Tokenizer::from_json(&json).unwrap();

        assert_eq!(tok.vocab_size, tok2.vocab_size);
        assert_eq!(tok.merges.len(), tok2.merges.len());

        let ids1 = tok.encode("the cat");
        let ids2 = tok2.encode("the cat");
        assert_eq!(ids1, ids2);
    }
}