Skip to content
class

UnigramTokenizer

extends_UnigramCommonMixinTokenizer
UnigramTokenizer(pieces: list[tuple[str, float]], unk_token: str = '<unk>', unk_log_prob: float = -100.0, normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Reference (pure-Python) Unigram tokenizer.

Encodes via Viterbi over the lattice of all candidate sub-piece segmentations: for each chunk we build a DP table dp[i] = best (highest log-prob) path ending at byte offset i, with single-codepoint UNK fallback when no piece spans a region. Decode is a trivial "".join(pieces).replace("▁", " ").

Training is delegated to C++ (see train for the rationale) — even this "pure-Python" flavour does not implement EM in Python because the runtime would be unusable on any real corpus.

For production / latency-sensitive use, prefer UnigramTokenizerFast — same vocab format, bit-identical encode output, but the Viterbi hot loop runs in C++.

Parameters

pieceslist of (str, float)
Ordered (piece_str, log_prob) list; index = token id. Larger (less-negative) log-probs are preferred during Viterbi decode.
unk_tokenstr= "<unk>"
Fallback piece string used when no entry in pieces spans a region of the input. Must appear in pieces for the UNK id to be defined; otherwise encode silently drops unmatchable codepoints.
unk_log_probfloat= -100.0
Log probability assigned to UNK substitutions in the Viterbi recurrence. Very negative so any non-UNK path dominates when available.
normalizerNormalizer= None
Pre-encode text normalisation chain. Defaults to lucid.utils.tokenizer._normalizers.NFKC (matches LLaMA / Mistral / T5).
pre_tokenizerPreTokenizer= None
Chunk-splitter applied after normalisation. Defaults to SentencePiecePreTokenizer for canonical SentencePiece behaviour with ▁ word-start markers.
special_tokensSpecialTokens= None
Special-token registry — see lucid.utils.tokenizer.SpecialTokens. Defaults to SpecialTokens(unk=unk_token).

Notes

The Viterbi DP runs in O(N⋅M)O(N \cdot M) per chunk, where N is the chunk byte length and M is the max piece byte length. UTF-8 boundary masking ensures sub-piece offsets only land on codepoint boundaries (no mid-codepoint cuts), which matches the C++ flavour bit-for-bit.

Examples

>>> from lucid.utils.tokenizer import UnigramTokenizer
>>> tok = UnigramTokenizer(pieces=[])
>>> tok.train(["the quick brown fox", "the lazy dog sleeps"],
...           vocab_size=48)
>>> tok.decode(tok.encode("the quick dog"))
' the quick dog'
The leading space is the SentencePiece convention this follows — a
piece carries the boundary before it — and it survives the round
trip rather than being trimmed away.

See Also

  • UnigramTokenizerFast—C++-backed flavour with identical
  • encode output and a much faster—meth:~UnigramTokenizerFast.encode.

Used by 1

Constructors

1
dunder

__init__

→None
__init__(pieces: list[tuple[str, float]], unk_token: str = '<unk>', unk_log_prob: float = -100.0, normalizer: Normalizer | None = None, pre_tokenizer: PreTokenizer | None = None, special_tokens: SpecialTokens | None = None)

Construct a pure-Python Unigram tokenizer.

Parameters

pieceslist of (str, float)
Ordered (piece, log_prob) list; index = token id.
unk_tokenstr= "<unk>"
Fallback piece string for unmatchable input regions.
unk_log_probfloat= -100.0
Log probability assigned to UNK substitutions.
normalizer(Normalizer or None, optional, keyword - only)= None
Pre-encode normalisation. Defaults to NFKC.
pre_tokenizer(PreTokenizer or None, optional, keyword - only)= None
Chunk splitter. Defaults to SentencePiecePreTokenizer.
special_tokens(SpecialTokens or None, optional, keyword - only)= None
Special-token registry. Defaults to SpecialTokens(unk=unk_token).

Notes

Builds piece-id maps and caches the longest piece in bytes for the Viterbi DP via _rebuild_tables.

Properties

3
prop

algo

→strfrom _UnigramCommonMixin
algo: str

Algorithm identifier (always "unigram").

prop

pieces

→list[tuple[str, float]]from _UnigramCommonMixin
pieces: list[tuple[str, float]]

Raw (piece, log_prob) list.

prop

vocab_size

→int
vocab_size: int

Number of pieces in the Unigram vocabulary.

Returns

int

len(self._pieces).

Class methods

1
cls

from_file

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

Load from a directory containing tokenizer.json.

Instance methods

4
fn

get_vocab

→dict[str, int]
get_vocab()

Return a copy of the piece → id map.

Returns

dict[str, int]

Shallow copy; mutating it does not affect the tokenizer. Added tokens a tokenizer.json declares outside the piece list are included.

fn

id_to_token

→str | Nonefrom _UnigramCommonMixin
id_to_token(token_id: int)

Look up the piece string for a token id.

fn

save

→Nonefrom _UnigramCommonMixin
save(directory: str)

Persist as 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.