pub struct BpeTokenizer { /* private fields */ }Expand description
A Byte-Pair Encoding tokenizer built from a vocabulary and an ordered list of merge rules.
The merge list is applied greedily: at each step the adjacent symbol pair with the lowest rank (earliest in the list) is merged, until no ranked pair remains.
§Byte-level mode
Enable with_byte_level for GPT-2 / RoBERTa /
Llama style tokenizers. In this mode the input is pre-tokenized with a
GPT-2 word-splitting pass and each piece’s raw bytes are mapped into the
reversible byte-level unicode alphabet before BPE is applied, so encoding
never fails on arbitrary UTF-8 and decode(encode(s)) == s.
§Special tokens
Register atomic markers (e.g. <|endoftext|>, <s>) with
with_special_tokens. They are matched
verbatim (longest-match-wins) before pre-tokenization and never split.
Implementations§
Source§impl BpeTokenizer
impl BpeTokenizer
Sourcepub fn from_vocab_merges(
vocab: BTreeMap<String, TokenId>,
merges: Vec<(String, String)>,
) -> Self
pub fn from_vocab_merges( vocab: BTreeMap<String, TokenId>, merges: Vec<(String, String)>, ) -> Self
Builds a tokenizer from a vocabulary (token string → id) and an ordered
list of merge rules. The index of a rule in merges is its rank, so
earlier rules win ties.
Examples found in repository?
13fn main() {
14 // --- BPE (GPT-2 style) ---
15 let mut bpe_vocab = BTreeMap::new();
16 for (i, t) in ["l", "o", "w", "lo", "low", "e", "r", "er", "<unk>"]
17 .into_iter()
18 .enumerate()
19 {
20 bpe_vocab.insert(t.to_string(), i as u32);
21 }
22 let bpe_merges = vec![
23 ("l".to_string(), "o".to_string()),
24 ("lo".to_string(), "w".to_string()),
25 ("e".to_string(), "r".to_string()),
26 ];
27 let bpe = BpeTokenizer::from_vocab_merges(bpe_vocab, bpe_merges);
28
29 let text = "low lower";
30 let bpe_ids = bpe.encode(text).unwrap();
31 println!("BPE encode({text:?}) = {bpe_ids:?}");
32 println!(
33 "BPE decode({bpe_ids:?}) = {:?}",
34 bpe.decode(&bpe_ids).unwrap()
35 );
36
37 // --- WordPiece (BERT style) ---
38 let mut wp_vocab = BTreeMap::new();
39 for (i, t) in ["[UNK]", "un", "##aff", "##able", "play", "##ing"]
40 .into_iter()
41 .enumerate()
42 {
43 wp_vocab.insert(t.to_string(), i as u32);
44 }
45 let wp = WordPieceTokenizer::from_vocab(wp_vocab, "[UNK]").unwrap();
46
47 let text2 = "unaffable playing";
48 let wp_ids = wp.encode(text2).unwrap();
49 println!("WP encode({text2:?}) = {wp_ids:?}");
50 println!(
51 "WP decode({wp_ids:?}) = {:?}",
52 wp.decode(&wp_ids).unwrap()
53 );
54}Sourcepub fn with_byte_level(self) -> Self
pub fn with_byte_level(self) -> Self
Enables GPT-2 byte-level pre-tokenization and byte-fallback encoding.
Sourcepub fn with_special_tokens(self, specials: BTreeMap<String, TokenId>) -> Self
pub fn with_special_tokens(self, specials: BTreeMap<String, TokenId>) -> Self
Registers special tokens (token string → id) that are matched atomically before pre-tokenization and never split by BPE.
Sourcepub fn vocab_size(&self) -> usize
pub fn vocab_size(&self) -> usize
Number of tokens in the vocabulary (excluding special tokens that are not also present in the base vocabulary).
Sourcepub fn from_files(
vocab_path: &str,
merges_path: &str,
) -> Result<Self, TokenizerError>
pub fn from_files( vocab_path: &str, merges_path: &str, ) -> Result<Self, TokenizerError>
Loads a GPT-2 style tokenizer from disk: vocab_path is one token per
line (line number = id), merges_path is one A B pair per line
(optionally prefixed by a single count header line).
§Errors
Returns TokenizerError::Io on a read failure, or
TokenizerError::MalformedFile if a line cannot be parsed.
Trait Implementations§
Source§impl Clone for BpeTokenizer
impl Clone for BpeTokenizer
Source§fn clone(&self) -> BpeTokenizer
fn clone(&self) -> BpeTokenizer
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for BpeTokenizer
impl Debug for BpeTokenizer
Auto Trait Implementations§
impl Freeze for BpeTokenizer
impl RefUnwindSafe for BpeTokenizer
impl Send for BpeTokenizer
impl Sync for BpeTokenizer
impl Unpin for BpeTokenizer
impl UnsafeUnpin for BpeTokenizer
impl UnwindSafe for BpeTokenizer
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> TokenizerExt for T
impl<T> TokenizerExt for T
Source§fn encode_with(
&self,
text: &str,
cfg: &EncodeConfig,
) -> Result<Encoding, TokenizerError>
fn encode_with( &self, text: &str, cfg: &EncodeConfig, ) -> Result<Encoding, TokenizerError>
cfg. Read more