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
impl WordPieceTokenizer
Sourcepub fn from_vocab(
vocab: BTreeMap<String, TokenId>,
unk_token: &str,
) -> Result<Self, TokenizerError>
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?
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_lowercase(self) -> Self
pub fn with_lowercase(self) -> Self
Enables lowercasing during pre-tokenization, matching *-uncased
BERT models.
Sourcepub fn vocab_size(&self) -> usize
pub fn vocab_size(&self) -> usize
Number of tokens in the vocabulary.
Sourcepub fn from_file(
vocab_path: &str,
unk_token: &str,
) -> Result<Self, TokenizerError>
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
impl Clone for WordPieceTokenizer
Source§fn clone(&self) -> WordPieceTokenizer
fn clone(&self) -> WordPieceTokenizer
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 WordPieceTokenizer
impl Debug for WordPieceTokenizer
Source§impl Tokenizer for WordPieceTokenizer
impl Tokenizer for WordPieceTokenizer
Source§fn decode(&self, ids: &[TokenId]) -> Result<String, TokenizerError>
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.
Auto Trait Implementations§
impl Freeze for WordPieceTokenizer
impl RefUnwindSafe for WordPieceTokenizer
impl Send for WordPieceTokenizer
impl Sync for WordPieceTokenizer
impl Unpin for WordPieceTokenizer
impl UnsafeUnpin for WordPieceTokenizer
impl UnwindSafe for WordPieceTokenizer
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