Skip to main content

BpeTokenizer

Struct BpeTokenizer 

Source
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

Source

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?
examples/tokenize_text.rs (line 27)
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}
Source

pub fn with_byte_level(self) -> Self

Enables GPT-2 byte-level pre-tokenization and byte-fallback encoding.

Source

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.

Source

pub fn vocab_size(&self) -> usize

Number of tokens in the vocabulary (excluding special tokens that are not also present in the base vocabulary).

Source

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

Source§

fn clone(&self) -> BpeTokenizer

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BpeTokenizer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Tokenizer for BpeTokenizer

Source§

fn decode(&self, ids: &[TokenId]) -> Result<String, TokenizerError>

Decode ids back into a string.

In byte-level mode this is exact: decode(encode(s)) == s. In plain mode encode discards whitespace, so decoding is lossy for multi-word input.

Source§

fn encode(&self, text: &str) -> Result<Vec<TokenId>, TokenizerError>

Encode text into a sequence of token ids. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TokenizerExt for T
where T: Tokenizer + ?Sized,

Source§

fn encode_with( &self, text: &str, cfg: &EncodeConfig, ) -> Result<Encoding, TokenizerError>

Encode a single sequence, applying special-token insertion, truncation and (fixed) padding from cfg. Read more
Source§

fn encode_batch( &self, texts: &[&str], cfg: &EncodeConfig, ) -> Result<Vec<Encoding>, TokenizerError>

Encode a batch of sequences, applying special tokens and truncation to each and then the batch-level Padding strategy across all of them. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.