Skip to content
class

BPETokenizer

extends_BPECommonMixinTokenizer
BPETokenizer(vocab: dict[str, int], merges: list[tuple[str, str]], normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Reference (pure-Python) BPE tokenizer.

Implements the classical Sennrich-2016 BPE encode loop directly in Python. Easy to read, easy to step through with a debugger, works on every platform (no C++ build needed).

For production / latency-sensitive use, prefer the matching BPETokenizerFast — same algorithm, same vocab format, bit-identical encode outputs, but the hot loop is in C++.

Parameters

vocabdict[str, int]
Token-string → id map. Must include every single character that any merge could produce (so the algorithm has a valid starting symbol sequence).
mergeslist[tuple[str, str]]
Ordered BPE merge pairs — index = rank (lower = higher priority, applied first during encoding).
normalizerNormalizer= None
Pre-encode text normalisation chain. Default lucid.utils.tokenizer._normalizers.NFC.
pre_tokenizerPreTokenizer= None
Chunk-splitter that turns the normalised text into the sequence of strings the BPE algorithm processes one at a time. Default lucid.utils.tokenizer._pre_tokenizers.WhitespaceSplit.
special_tokensSpecialTokens= None
Special-token registry — see lucid.utils.tokenizer.SpecialTokens.

Examples

Trained in place from an empty vocabulary and no merges:
>>> from lucid.utils.tokenizer import BPETokenizer
>>> tok = BPETokenizer(vocab={}, merges=[])
>>> tok.train(["the quick brown fox", "the lazy dog sleeps"],
...           vocab_size=80)
>>> tok.decode(tok.encode("the quick dog"))
'thequickdog'
The whitespace is gone, and that is the algorithm rather than a
defect: raw BPE has no notion of a word boundary. Use
ByteLevelBPETokenizer where the round trip has to be exact.

Used by 4

Constructors

1
dunder

__init__

→None
__init__(vocab: dict[str, int], merges: list[tuple[str, str]], normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Construct a pure-Python BPE tokenizer.

Parameters

vocabdict[str, int]
Token-string → id map; must cover every starting symbol referenced by merges.
mergeslist of (str, str)
Ordered merge pairs; index = rank (lower wins).
normalizer(Normalizer or None, optional, keyword - only)= None
Pre-encode normalisation chain. Defaults to NFC.
pre_tokenizer(PreTokenizer or None, optional, keyword - only)= None
Chunk splitter. Defaults to WhitespaceSplit.
special_tokens(SpecialTokens or None, optional, keyword - only)= None
Special-token registry.

Notes

Mutates internal state: copies vocab / merges, builds the _pair_to_merge compiled lookup, and registers special tokens via the base Tokenizer constructor.

Properties

2
prop

algo

→strfrom _BPECommonMixin
algo: str

Algorithm identifier ("bpe").

prop

vocab_size

→int
vocab_size: int

Number of tokens currently registered in the vocab.

Returns

int

len(self._vocab) — includes special tokens that were registered into the main vocab.

Class methods

1
cls

from_file

→BPETokenizer
from_file(directory: str, normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Load a pure-Python BPE tokenizer from directory.

Parameters

directorystr
Folder with tokenizer.json or vocab.json + merges.txt.
normalizerNormalizer | None= None
Optional pre-encode normaliser override.
pre_tokenizerPreTokenizer | None= None
Optional pre-tokenizer splitter override.
special_tokensSpecialTokens | None= None
Optional special-token registry override.

Instance methods

4
fn

get_vocab

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

Return a shallow copy of the token → id map.

fn

id_to_token

→str | Nonefrom _BPECommonMixin
id_to_token(token_id: int)

Look up the surface string for a token id.

fn

save

→Nonefrom _BPECommonMixin
save(directory: str)

Persist as both legacy (vocab.json + merges.txt) AND unified (tokenizer.json) formats.

fn

train

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

Re-train this tokenizer from scratch on corpus.

Implements the classical Sennrich-2016 training loop:

  1. Pre-tokenize each document (using the configured pre-tokenizer chain) into a frequency-counted set of words.
  2. Seed the vocab with every distinct codepoint appearing in any word.
  3. Iteratively count adjacent symbol-pair frequencies + merge 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 + _merges in place; previous contents are discarded.

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 merges occur.