1use crate::merge::{apply_merges, train_merges, Pair};
10use kute_core::{check_sequence, sequence_for, CorpusFingerprint, CorpusSource, Tokenizer};
11use kute_types::{
12 CanonicalInput, KuteError, Manifest, MergeRule, Modality, Payload, PayloadKind, Provenance, Result,
13 TestVector, TokenEntry, TokenKind, TokenPayload, TokenSequence, TokenizerCapabilities, TrainingConfig,
14 Vocabulary, KUTE_VERSION, KVF_VERSION,
15};
16use rustc_hash::FxHashMap;
17use std::collections::{BTreeMap, BTreeSet};
18
19pub const ALGORITHM: &str = "sequence-bpe";
20
21struct Loaded {
22 vocabulary: Vocabulary,
23 alphabet: FxHashMap<String, u32>,
24 ranks: FxHashMap<Pair, u32>,
25}
26
27#[derive(Default)]
28pub struct SequenceBpeTokenizer {
29 loaded: Option<Loaded>,
30}
31
32impl SequenceBpeTokenizer {
33 pub fn new() -> Self {
34 Self::default()
35 }
36
37 pub fn boxed() -> Box<dyn Tokenizer> {
38 Box::new(Self::new())
39 }
40
41 fn loaded(&self) -> Result<&Loaded> {
42 self.loaded.as_ref().ok_or_else(|| KuteError::NotTrained("train or load a vocabulary first".into()))
43 }
44}
45
46fn encode_symbols(loaded: &Loaded, symbols: &[String]) -> Result<Vec<u32>> {
47 let mut ids = Vec::with_capacity(symbols.len());
48 for s in symbols {
49 ids.push(*loaded.alphabet.get(s).ok_or_else(|| KuteError::UnknownSymbol(s.clone()))?);
50 }
51 apply_merges(&mut ids, &loaded.ranks);
52 Ok(ids)
53}
54
55impl Tokenizer for SequenceBpeTokenizer {
56 fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary> {
57 config.validate()?;
58 let mut fingerprint = CorpusFingerprint::new();
59 let mut records: Vec<Vec<String>> = Vec::new();
60 let mut modality = Modality::Events;
61 while let Some(record) = corpus.next_record()? {
62 fingerprint.update(&record);
63 if let Some(limit) = config.max_corpus_units {
64 if fingerprint.units() > limit {
65 return Err(KuteError::LimitExceeded(format!("corpus is larger than the max_corpus_units limit of {limit}")));
66 }
67 }
68 modality = record.modality;
69 match record.payload {
70 Payload::Symbols(s) => records.push(s),
71 Payload::Bytes(_) => {
72 return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads; use bpe for bytes".into()))
73 }
74 }
75 }
76 let alphabet_set: BTreeSet<&str> = records.iter().flatten().map(String::as_str).collect();
77 if alphabet_set.is_empty() {
78 return Err(KuteError::InvalidInput("the corpus contains no symbols".into()));
79 }
80 for s in &alphabet_set {
81 if s.is_empty() || s.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
82 return Err(KuteError::InvalidInput("symbols must be 1 to 1024 bytes".into()));
83 }
84 }
85 let base = alphabet_set.len() as u32;
86 let reserved = config.reserved_tokens.len() as u32;
87 if config.vocab_size < base + reserved {
88 return Err(KuteError::InvalidConfig(format!(
89 "the corpus has {base} distinct symbols; vocab_size must be at least {}",
90 base + reserved
91 )));
92 }
93 let index: FxHashMap<&str, u32> = alphabet_set.iter().enumerate().map(|(i, s)| (*s, i as u32)).collect();
94
95 let mut window_counts: FxHashMap<Vec<u32>, u64> = FxHashMap::default();
96 for record in &records {
97 let ids: Vec<u32> = record.iter().map(|s| index[s.as_str()]).collect();
98 for window in ids.chunks(config.train_window) {
99 *window_counts.entry(window.to_vec()).or_insert(0) += 1;
100 }
101 }
102 let mut windows: Vec<(Vec<u32>, u64)> = window_counts.into_iter().collect();
103 windows.sort_unstable();
104 let counts: Vec<u64> = windows.iter().map(|(_, c)| *c).collect();
105 let words: Vec<Vec<u32>> = windows.into_iter().map(|(w, _)| w).collect();
106 let unique_windows = words.len() as u64;
107
108 let mut lengths: Vec<usize> = vec![1; base as usize];
109 let limit = config.max_token_length;
110 let learned = train_merges(words, &counts, base, config.vocab_size - base - reserved, config.min_frequency, |l, r| {
111 let len = lengths[l as usize] + lengths[r as usize];
112 if limit.map_or(true, |m| len <= m) && len <= kute_types::vocab::MAX_TOKEN_SYMBOLS {
113 lengths.push(len);
114 true
115 } else {
116 false
117 }
118 });
119
120 let mut tokens: Vec<TokenEntry> = alphabet_set
121 .iter()
122 .enumerate()
123 .map(|(i, s)| TokenEntry { id: i as u32, kind: TokenKind::Symbol, payload: TokenPayload::Symbols(vec![s.to_string()]), frequency: None })
124 .collect();
125 let mut rules = Vec::with_capacity(learned.len());
126 for m in &learned {
127 let mut seq = match &tokens[m.left as usize].payload {
128 TokenPayload::Symbols(s) => s.clone(),
129 TokenPayload::Bytes(_) => unreachable!("sequence vocabularies hold symbols only"),
130 };
131 if let TokenPayload::Symbols(s) = &tokens[m.right as usize].payload {
132 seq.extend(s.iter().cloned());
133 }
134 tokens.push(TokenEntry { id: m.id, kind: TokenKind::Merge, payload: TokenPayload::Symbols(seq), frequency: Some(m.count) });
135 rules.push(MergeRule { left: m.left, right: m.right, id: m.id });
136 }
137 for name in &config.reserved_tokens {
138 let id = tokens.len() as u32;
139 tokens.push(TokenEntry { id, kind: TokenKind::Special, payload: TokenPayload::Symbols(vec![name.clone()]), frequency: None });
140 }
141
142 let mut statistics = BTreeMap::new();
143 statistics.insert("corpus_records".to_string(), fingerprint.records());
144 statistics.insert("corpus_symbols".to_string(), fingerprint.units());
145 statistics.insert("alphabet_size".to_string(), base as u64);
146 statistics.insert("unique_windows".to_string(), unique_windows);
147 statistics.insert("merges_learned".to_string(), learned.len() as u64);
148 statistics.insert("requested_vocab_size".to_string(), config.vocab_size as u64);
149
150 let vocabulary = Vocabulary {
151 manifest: Manifest {
152 kvf_version: KVF_VERSION.to_string(),
153 id: config.vocabulary_id.clone(),
154 version: config.vocabulary_version.clone(),
155 algorithm: ALGORITHM.to_string(),
156 modality,
157 payload_kind: PayloadKind::Symbols,
158 lossless: true,
159 description: config.description.clone(),
160 created: None,
161 generator: format!("kute {KUTE_VERSION}"),
162 },
163 pretokenizer: None,
164 adapter: None,
165 tokens,
166 merges: rules,
167 statistics,
168 provenance: Provenance {
169 corpus_fingerprints: vec![fingerprint.finish()],
170 license: config.license.clone(),
171 training: Some(serde_json::to_value(config)?),
172 },
173 test_vectors: Vec::new(),
174 representations: Vec::new(),
175 integrity: None,
176 };
177 self.load(vocabulary)?;
178 let loaded = self.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
179 let mut vectors = Vec::new();
180 for record in records.iter().filter(|r| !r.is_empty()).take(4) {
181 let sample: Vec<String> = record.iter().take(32).cloned().collect();
182 let ids = encode_symbols(loaded, &sample)?;
183 vectors.push(TestVector { input: TokenPayload::Symbols(sample), ids });
184 }
185 loaded.vocabulary.test_vectors = vectors;
186 loaded.vocabulary.seal()?;
187 Ok(loaded.vocabulary.clone())
188 }
189
190 fn load(&mut self, mut vocabulary: Vocabulary) -> Result<()> {
191 vocabulary.validate()?;
192 if vocabulary.manifest.algorithm != ALGORITHM {
193 return Err(KuteError::VocabularyMismatch(format!(
194 "the sequence-bpe tokenizer cannot interpret a {:?} vocabulary",
195 vocabulary.manifest.algorithm
196 )));
197 }
198 let mut alphabet: FxHashMap<String, u32> = FxHashMap::default();
199 for t in &vocabulary.tokens {
200 if t.kind == TokenKind::Symbol {
201 let TokenPayload::Symbols(s) = &t.payload else {
202 return Err(KuteError::InvalidVocabulary(format!("symbol token {} has a byte payload", t.id)));
203 };
204 if s.len() != 1 || alphabet.insert(s[0].clone(), t.id).is_some() {
205 return Err(KuteError::InvalidVocabulary(format!("symbol token {} is not a single, unique symbol", t.id)));
206 }
207 }
208 }
209 let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
210 for m in &vocabulary.merges {
211 if ranks.insert((m.left, m.right), m.id).is_some() {
212 return Err(KuteError::InvalidVocabulary(format!("pair ({}, {}) has two merge rules", m.left, m.right)));
213 }
214 }
215 if vocabulary.integrity.is_none() {
216 vocabulary.seal()?;
217 }
218 self.loaded = Some(Loaded { vocabulary, alphabet, ranks });
219 Ok(())
220 }
221
222 fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
223 let loaded = self.loaded()?;
224 let Payload::Symbols(symbols) = &input.payload else {
225 return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads".into()));
226 };
227 sequence_for(&loaded.vocabulary, input.modality, encode_symbols(loaded, symbols)?)
228 }
229
230 fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
231 let loaded = self.loaded()?;
232 check_sequence(&loaded.vocabulary, tokens)?;
233 let mut out = Vec::with_capacity(tokens.ids.len() * 2);
234 for &id in &tokens.ids {
235 match &loaded.vocabulary.token(id)?.payload {
236 TokenPayload::Symbols(s) => out.extend(s.iter().cloned()),
237 TokenPayload::Bytes(_) => return Err(KuteError::InvalidVocabulary("byte token in a symbol vocabulary".into())),
238 }
239 }
240 Ok(CanonicalInput { modality: tokens.modality, payload: Payload::Symbols(out) })
241 }
242
243 fn vocabulary(&self) -> Option<&Vocabulary> {
244 self.loaded.as_ref().map(|l| &l.vocabulary)
245 }
246
247 fn capabilities(&self) -> TokenizerCapabilities {
248 TokenizerCapabilities {
249 algorithm: ALGORITHM.to_string(),
250 lossless: true,
251 trainable: true,
252 deterministic: true,
253 accepts: vec![PayloadKind::Symbols],
254 rejects_unknown: true,
255 notes: "BPE over named symbols. Lossless for sequences drawn from the trained alphabet; any other symbol is refused.".to_string(),
256 }
257 }
258}