Skip to content
class

WordPieceTokenizer

extends_WordPieceCommonMixinTokenizer
WordPieceTokenizer(vocab: dict[str, int], unk_token: str = '[UNK]', continuing_prefix: str = '##', max_chars_per_word: int = 100, normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Reference (pure-Python) WordPiece tokenizer.

Implements BERT's WordPiece algorithm in pure Python. Each pre-tokenized word is split via greedy longest-match: the longest vocab prefix is emitted, then the algorithm recurses on the remainder with the continuation prefix ("##" by default) prepended. If no prefix matches at any position, the whole word becomes a single UNK token.

Easy to read, easy to step through, no C++ build required. For production / latency-sensitive use, prefer WordPieceTokenizerFast — same algorithm, same vocab format, bit-identical encode outputs, but the hot loop runs in C++.

Parameters

vocabdict[str, int]
BERT-style vocab — token-string → id map. Continuation tokens are prefixed with ##; id = line index when loaded from vocab.txt.
unk_tokenstr= "[UNK]"
Token emitted when no valid longest-match prefix can be found. Must be present in vocab for it to actually emit an id (otherwise nothing is emitted for that word).
continuing_prefixstr= "##"
Prefix used to distinguish non-initial subwords from initial ones. Almost never overridden outside of WordPiece variants.
max_chars_per_wordint= 100
Words longer than this are short-circuited to UNK without running longest-match (matches BERT's BasicTokenizer cap and bounds worst-case encode cost).
normalizerNormalizer= None
Pre-encode normalisation chain. Default lucid.utils.tokenizer._normalizers.BERTNormalizer.
pre_tokenizerPreTokenizer= None
Chunk-splitter run before WordPiece. Default lucid.utils.tokenizer._pre_tokenizers.WhitespacePunctuationSplit.
special_tokensSpecialTokens= None
Special-token registry. Defaults to SpecialTokens(unk=unk_token) so the tokenizer behaves correctly out of the box.

Notes

The greedy longest-match is O(W^2) per word in the worst case (where W = word length), but typical English words have W < 20, so the Python interpreter overhead dominates. WordPieceTokenizerFast recovers an order of magnitude on long-document encoding.

Examples

>>> import pathlib, tempfile
>>> with tempfile.TemporaryDirectory() as vocab_dir:   # holds a vocab.txt
...     _ = pathlib.Path(vocab_dir, "vocab.txt").write_text("[UNK]\nhello\nworld\n")
...     tok = WordPieceTokenizer.from_pretrained(vocab_dir)
>>> ids = tok.encode("hello world")
>>> ids
[1, 2]
>>> tok.decode(ids)
'hello world'

See Also

  • WordPieceTokenizerFast—C++-backed equivalent with the same API.

Used by 3

Constructors

1
dunder

__init__

→None
__init__(vocab: dict[str, int], unk_token: str = '[UNK]', continuing_prefix: str = '##', max_chars_per_word: int = 100, normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Construct a pure-Python WordPiece tokenizer.

Parameters

vocabdict[str, int]
BERT-style token → id map; continuation pieces are prefixed with continuing_prefix.
unk_tokenstr= "[UNK]"
Emitted when no longest-match prefix is found.
continuing_prefixstr= "##"
Marker prepended to non-initial subword lookups.
max_chars_per_wordint= 100
Words longer than this are short-circuited to UNK.
normalizer(Normalizer or None, optional, keyword - only)= None
Pre-encode normaliser. Defaults to BERTNormalizer.
pre_tokenizer(PreTokenizer or None, optional, keyword - only)= None
Chunk splitter. Defaults to WhitespacePunctuationSplit.
special_tokens(SpecialTokens or None, optional, keyword - only)= None
Special-token registry. Defaults to SpecialTokens(unk=unk_token).

Properties

2
prop

algo

→strfrom _WordPieceCommonMixin
algo: str

Algorithm identifier (always "wordpiece").

prop

vocab_size

→int
vocab_size: int

Number of WordPiece tokens currently registered.

Returns

int

len(self._vocab).

Class methods

1
cls

from_file

→Selffrom _WordPieceCommonMixin
from_file(directory: str, unk_token: str = '[UNK]', continuing_prefix: str = '##', max_chars_per_word: int = 100, normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Load from a BERT-style directory containing vocab.txt.

Instance methods

4
fn

get_vocab

→dict[str, int]from _WordPieceCommonMixin
get_vocab()

Return a shallow copy of the token → id map.

fn

id_to_token

→str | Nonefrom _WordPieceCommonMixin
id_to_token(token_id: int)

Look up the surface string for a token id.

fn

save

→Nonefrom _WordPieceCommonMixin
save(directory: str)

Persist as a BERT-style directory (vocab.txt + unified tokenizer.json + special_tokens_map.json).

fn

train

→None
train(corpus: Iterable[str], vocab_size: int = 30000)

Re-train this tokenizer from scratch on corpus.

Greedy frequency-based WordPiece training (matches Hugging Face's WordPieceTrainer semantics; faster than the full log-likelihood training in the original paper). For each iteration, counts adjacent symbol-pair frequencies across all words and merges the most frequent pair, growing the vocab by 1 each step until vocab_size is reached or no pair appears more than once.

Replaces _vocab in place; previous contents are discarded. The result is a BERT-compatible vocab with ## continuation markers and the configured UNK token reserved at id 0. Tie-break is lexicographic key order for determinism (same convention as BPE).

Parameters

corpusiterable of str
Each item is one document (or chunk thereof). Generators are consumed exactly once.
vocab_sizeint= 30 000
Target total vocab size (chars + merges). Stops early if no more pair-merges occur.