Skip to main content

WordPieceTokenizer

Struct WordPieceTokenizer 

Source
pub struct WordPieceTokenizer { /* private fields */ }
Expand description

A WordPiece tokenizer built from a vocabulary.

Words are split greedily into the longest matching sub-words; a word that cannot be split at all is replaced by the [UNK] token.

Input is pre-tokenized with a BERT-style basic tokenizer that splits on whitespace and punctuation and isolates CJK characters. Enable with_lowercase to match *-uncased models.

Implementations§

Source§

impl WordPieceTokenizer

Source

pub fn from_vocab( vocab: BTreeMap<String, TokenId>, unk_token: &str, ) -> Result<Self, TokenizerError>

Builds a tokenizer from a vocabulary (token string → id). unk_token names the fallback token (typically "[UNK]"); it must be present in vocab.

§Errors

Returns TokenizerError::UnknownToken if unk_token is missing.

Examples found in repository?
examples/tokenize_text.rs (line 45)
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_lowercase(self) -> Self

Enables lowercasing during pre-tokenization, matching *-uncased BERT models.

Source

pub fn vocab_size(&self) -> usize

Number of tokens in the vocabulary.

Source

pub fn from_file( vocab_path: &str, unk_token: &str, ) -> Result<Self, TokenizerError>

Loads a BERT style vocabulary from disk: one token per line (line number = id).

§Errors

Returns TokenizerError::Io on a read failure or TokenizerError::UnknownToken if unk_token is absent.

Trait Implementations§

Source§

impl Clone for WordPieceTokenizer

Source§

fn clone(&self) -> WordPieceTokenizer

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 WordPieceTokenizer

Source§

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

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

impl Tokenizer for WordPieceTokenizer

Source§

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

Decode ids back into a string, mirroring BERT’s convert_tokens_to_string: continuation tokens (those prefixed with ##) are concatenated directly, while each new word is preceded by a space. This preserves inter-word spacing that encode discards.

§Errors

Returns a TokenizerError if an id is missing from the inverse vocabulary.

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.