ffbpe 0.1.8

Unicode-aware, streaming BPE training and tiktoken-compatible encoding
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
use std::{collections::BTreeMap, hash::Hash, io::{Read, Write}};

use ahash::AHashMap;
use hashbrown::HashMap;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};

use crate::{
  MyError, MyResult,
  bpe::Freq,
  pretokenizer::{
    PreTokenPiece, PreTokenizer, UnicodeBigramSelection, count_unicode_bigrams,
    for_each_regular_chunk, is_unicode_bigram_script, select_unicode_bigrams,
  },
};

type WordCounts = HashMap<String, Freq, ahash::RandomState>;
type BorrowedWordCounts<'a> = HashMap<&'a str, Freq, ahash::RandomState>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SourceBatchOptions {
  pub max_records: usize,
  pub max_bytes: usize,
}

impl Default for SourceBatchOptions {
  fn default() -> Self {
    Self {
      max_records: 4096,
      max_bytes: 64 * 1024 * 1024,
    }
  }
}

impl SourceBatchOptions {
  pub fn validate(self) -> MyResult<Self> {
    if self.max_records == 0 {
      return Err(MyError::SourceBatch("max_records must be at least 1"));
    }
    if self.max_bytes == 0 {
      return Err(MyError::SourceBatch("max_bytes must be at least 1"));
    }
    Ok(self)
  }
}

fn checked_add<K: Eq + Hash>(counts: &mut AHashMap<K, Freq>, key: K, value: Freq) -> MyResult<()> {
  let current = counts.entry(key).or_default();
  *current = current.checked_add(value).ok_or(MyError::FrequencyOverflow)?;
  Ok(())
}

fn merge_counts<K: Eq + Hash>(target: &mut AHashMap<K, Freq>, source: AHashMap<K, Freq>) -> MyResult<()> {
  for (key, value) in source {
    checked_add(target, key, value)?;
  }
  Ok(())
}

fn count_bigrams_into(
  pre_tokenizer: &PreTokenizer,
  text: &str,
  counts: &mut AHashMap<(char, char), Freq>,
) -> MyResult<()> {
  if text.is_empty() {
    return Ok(());
  }
  if pre_tokenizer.re_special_tokens.as_str() == "$^" {
    return count_unicode_bigrams(text, counts, is_unicode_bigram_script);
  }
  for_each_regular_chunk(text, &pre_tokenizer.re_special_tokens, |chunk| {
    count_unicode_bigrams(chunk, counts, is_unicode_bigram_script)
  })
}

fn count_words_borrowed<'a>(
  pre_tokenizer: &PreTokenizer,
  text: &'a str,
  counts: &mut BorrowedWordCounts<'a>,
) -> MyResult<()> {
  pre_tokenizer.for_each_piece(text, |piece| {
    if let PreTokenPiece::Word(word) = piece {
      let frequency = counts.entry(word).or_insert(0);
      *frequency = frequency.checked_add(1).ok_or(MyError::FrequencyOverflow)?;
    }
    Ok(())
  })
}

fn merge_borrowed_word_counts<'a>(
  mut left: BorrowedWordCounts<'a>,
  mut right: BorrowedWordCounts<'a>,
) -> MyResult<BorrowedWordCounts<'a>> {
  if left.len() < right.len() {
    std::mem::swap(&mut left, &mut right);
  }
  for (word, frequency) in right {
    let current = left.entry(word).or_default();
    *current = current.checked_add(frequency).ok_or(MyError::FrequencyOverflow)?;
  }
  Ok(left)
}

fn merge_borrowed_into_word_counts(
  target: &mut WordCounts,
  source: BorrowedWordCounts<'_>,
) -> MyResult<()> {
  target.reserve(source.len());
  for (word, frequency) in source {
    let current = target.entry_ref(word).or_insert(0);
    *current = current.checked_add(frequency).ok_or(MyError::FrequencyOverflow)?;
  }
  Ok(())
}

fn merge_word_counts(target: &mut WordCounts, source: WordCounts) -> MyResult<()> {
  for (word, frequency) in source {
    let current = target.entry(word).or_default();
    *current = current.checked_add(frequency).ok_or(MyError::FrequencyOverflow)?;
  }
  Ok(())
}

#[derive(Clone)]
#[cfg_attr(feature = "py", pyo3::pyclass(from_py_object))]
pub struct BigramCounter {
  pre_tokenizer: PreTokenizer,
  counts: AHashMap<(char, char), Freq>,
}

impl BigramCounter {
  pub fn new(pre_tokenizer: PreTokenizer) -> Self {
    Self {
      pre_tokenizer,
      counts: AHashMap::new(),
    }
  }

  pub fn add_text(&mut self, text: &str) -> MyResult<()> {
    count_bigrams_into(&self.pre_tokenizer, text, &mut self.counts)
  }

  pub fn add_batch<S: AsRef<str> + Sync>(&mut self, texts: &[S]) -> MyResult<()> {
    let batch_counts = texts
      .par_iter()
      .try_fold(AHashMap::new, |mut counts, text| {
        count_bigrams_into(&self.pre_tokenizer, text.as_ref(), &mut counts)?;
        Ok::<_, MyError>(counts)
      })
      .try_reduce(AHashMap::new, |mut left, right| {
        merge_counts(&mut left, right)?;
        Ok::<_, MyError>(left)
      })?;
    merge_counts(&mut self.counts, batch_counts)
  }

  pub fn add_source<I, S>(&mut self, source: I, options: SourceBatchOptions) -> MyResult<()>
  where
    I: IntoIterator<Item = S>,
    S: AsRef<str> + Sync,
  {
    let options = options.validate()?;
    let mut batch = Vec::new();
    let mut bytes: usize = 0;
    for text in source {
      let text_bytes = text.as_ref().len();
      if !batch.is_empty()
        && (batch.len() >= options.max_records
          || bytes.saturating_add(text_bytes) > options.max_bytes)
      {
        self.add_batch(&batch)?;
        batch.clear();
        bytes = 0;
      }
      bytes = bytes.checked_add(text_bytes).ok_or(MyError::SourceBatch("batch byte size overflow"))?;
      batch.push(text);
    }
    if !batch.is_empty() {
      self.add_batch(&batch)?;
    }
    Ok(())
  }

  pub fn merge(&mut self, other: Self) -> MyResult<()> {
    merge_counts(&mut self.counts, other.counts)
  }

  pub fn selected(&self, top_k: usize, min_freq: Freq) -> Vec<(char, char)> {
    let mut selected = self
      .selection(top_k, min_freq)
      .bigrams
      .into_iter()
      .collect::<Vec<_>>();
    selected.sort_unstable();
    selected
  }

  /// Select Unicode bigrams and preserve their effective frequency boundary.
  pub fn selection(&self, top_k: usize, min_freq: Freq) -> UnicodeBigramSelection {
    select_unicode_bigrams(self.counts.clone(), top_k, min_freq)
  }

  pub fn counts(&self) -> &AHashMap<(char, char), Freq> {
    &self.counts
  }
}

#[derive(Clone)]
#[cfg_attr(feature = "py", pyo3::pyclass(from_py_object))]
pub struct WordCounter {
  pre_tokenizer: PreTokenizer,
  counts: WordCounts,
}

impl WordCounter {
  pub fn new(pre_tokenizer: PreTokenizer) -> Self {
    Self {
      pre_tokenizer,
      counts: WordCounts::default(),
    }
  }

  pub fn add_text(&mut self, text: &str) -> MyResult<()> {
    let mut counts = BorrowedWordCounts::default();
    count_words_borrowed(&self.pre_tokenizer, text, &mut counts)?;
    merge_borrowed_into_word_counts(&mut self.counts, counts)
  }

  pub fn add_batch<'a, S: AsRef<str> + Sync>(&mut self, texts: &'a [S]) -> MyResult<()> {
    let batch_counts = texts
      .par_iter()
      .try_fold(BorrowedWordCounts::default, |mut counts, text| {
        count_words_borrowed(&self.pre_tokenizer, text.as_ref(), &mut counts)?;
        Ok::<_, MyError>(counts)
      })
      .try_reduce(BorrowedWordCounts::default, merge_borrowed_word_counts)?;
    merge_borrowed_into_word_counts(&mut self.counts, batch_counts)
  }

  pub fn add_source<I, S>(&mut self, source: I, options: SourceBatchOptions) -> MyResult<()>
  where
    I: IntoIterator<Item = S>,
    S: AsRef<str> + Sync,
  {
    let options = options.validate()?;
    let mut batch = Vec::new();
    let mut bytes: usize = 0;
    for text in source {
      let text_bytes = text.as_ref().len();
      if !batch.is_empty()
        && (batch.len() >= options.max_records
          || bytes.saturating_add(text_bytes) > options.max_bytes)
      {
        self.add_batch(&batch)?;
        batch.clear();
        bytes = 0;
      }
      bytes = bytes.checked_add(text_bytes).ok_or(MyError::SourceBatch("batch byte size overflow"))?;
      batch.push(text);
    }
    if !batch.is_empty() {
      self.add_batch(&batch)?;
    }
    Ok(())
  }

  pub fn merge(&mut self, other: Self) -> MyResult<()> {
    merge_word_counts(&mut self.counts, other.counts)
  }

  pub fn words(&self) -> BTreeMap<String, Freq> {
    self.counts.iter().map(|(word, frequency)| (word.clone(), *frequency)).collect()
  }

  pub fn len(&self) -> usize {
    self.counts.len()
  }

  pub fn is_empty(&self) -> bool {
    self.counts.is_empty()
  }

  pub fn clear(&mut self) {
    self.counts.clear();
  }

  pub fn take_counts(&mut self) -> WordCounts {
    std::mem::take(&mut self.counts)
  }

  pub fn save<W: Write>(&self, writer: W) -> MyResult<()> {
    serde_json::to_writer(writer, &self.counts)?;
    Ok(())
  }

  pub fn load<R: Read>(pre_tokenizer: PreTokenizer, reader: R) -> MyResult<Self> {
    let counts = serde_json::from_reader(reader)?;
    Ok(Self { pre_tokenizer, counts })
  }

  pub fn counts(&self) -> &WordCounts {
    &self.counts
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::bigram::{Bigram, VocabBigramIndex};
  use crate::pretokenizer::parse_unicode_bigrams;

  #[test]
  fn bigram_counter_batches_and_merges() {
    let pre_tokenizer = PreTokenizer::new(&[], None);
    let mut left = BigramCounter::new(pre_tokenizer.clone());
    left.add_source(
      ["你好世界", "你好"],
      SourceBatchOptions { max_records: 1, max_bytes: 8 },
    ).unwrap();
    let mut right = BigramCounter::new(pre_tokenizer);
    right.add_text("世界").unwrap();
    left.merge(right).unwrap();

    assert_eq!(left.counts().get(&('', '')), Some(&2));
    assert_eq!(left.counts().get(&('', '')), Some(&2));
    let selection = left.selection(1, 1);
    assert_eq!(selection.cutoff_freq, Some(2));
    assert_eq!(selection.max_excluded_freq, Some(1));
    assert_eq!(selection.bigrams.len(), 2);
  }

  #[test]
  fn bigram_counter_ignores_vocab_bigram_word_boundaries() {
    let pre_tokenizer = PreTokenizer::new(&[], None)
      .with_vocab_bigram_index(VocabBigramIndex::unicode(ahash::AHashSet::new()));
    let mut counter = BigramCounter::new(pre_tokenizer);

    counter.add_text("你好").unwrap();

    assert_eq!(counter.counts().get(&('', '')), Some(&1));
  }

  #[test]
  fn word_counter_uses_frozen_bigrams_and_skips_special_tokens() {
    let bigrams = parse_unicode_bigrams(&["你好".to_string()]).unwrap();
    let pre_tokenizer = PreTokenizer::new(&["<eot>".to_string()], Some("<eot>"))
      .with_unicode_bigrams(bigrams);
    let mut counter = WordCounter::new(pre_tokenizer);
    counter.add_batch(&["你好世界<eot>", "你好"]).unwrap();

    let words = counter.words();
    assert_eq!(words.get("你好"), Some(&2));
    assert_eq!(words.get(""), Some(&1));
    assert_eq!(words.get(""), Some(&1));
    assert!(!words.contains_key("<eot>"));
  }

  #[test]
  fn word_counter_uses_vocab_bigram_pretokenization() {
    let vocab_bigrams = [Bigram::new('a', 'b'), Bigram::new('b', 'c')]
      .into_iter()
      .collect();
    let pre_tokenizer = PreTokenizer::try_new(
      &["<eot>".to_string()],
      Some("<eot>"),
      Some(r"\p{L}+"),
    )
    .unwrap()
    .with_vocab_bigram_index(VocabBigramIndex::unicode(vocab_bigrams));
    let mut counter = WordCounter::new(pre_tokenizer);

    counter.add_batch(&["abcz<eot>", "abcx"]).unwrap();

    assert_eq!(
      counter.words(),
      [
        ("abc".to_string(), 2),
        ("x".to_string(), 1),
        ("z".to_string(), 1),
      ]
      .into_iter()
      .collect(),
    );
  }

  #[test]
  fn word_counter_borrowed_batch_matches_owned_pretokenization() {
    let bigrams = parse_unicode_bigrams(&["世界".to_string(), "你好".to_string()]).unwrap();
    let pre_tokenizer = PreTokenizer::new(&[], None).with_unicode_bigrams(bigrams);
    let texts = ["Hello 世界你好 world", "世界你好", "Hello"];
    let mut expected = BTreeMap::new();
    for text in texts {
      for (word, frequency) in pre_tokenizer.get_words_owned(text).unwrap() {
        *expected.entry(word).or_default() += frequency;
      }
    }

    let mut counter = WordCounter::new(pre_tokenizer);
    counter.add_batch(&texts).unwrap();

    assert_eq!(counter.words(), expected);
  }

  #[test]
  fn word_counter_streams_around_adjacent_special_tokens() {
    let pre_tokenizer = PreTokenizer::new(&["<eot>".to_string()], Some("<eot>"));
    let mut counter = WordCounter::new(pre_tokenizer);
    counter.add_text("<eot>Hello<eot><eot> world<eot>").unwrap();

    assert_eq!(
      counter.words(),
      [("Hello".to_string(), 1), (" world".to_string(), 1)].into_iter().collect(),
    );
  }

  #[test]
  fn word_counter_preserves_empty_custom_pattern_matches() {
    let pre_tokenizer = PreTokenizer::try_new(&[], None, Some("")).unwrap()
      .with_unicode_bigrams(ahash::AHashSet::new());
    let expected = pre_tokenizer.get_words_owned("ab").unwrap();
    let mut counter = WordCounter::new(pre_tokenizer);
    counter.add_text("ab").unwrap();

    assert_eq!(counter.words(), expected);
  }
}