Skip to content
class

CharTokenizer

extends_VocabTokenizer
CharTokenizer(vocab: dict[str, int] | None = None, special_tokens: SpecialTokens | None = None)

Reference (pure-Python) character-level tokenizer.

Parameters

vocabdict[str, int]= None
Pre-built vocab; if omitted, an empty tokenizer is constructed (call train before encoding).
special_tokensSpecialTokens= None
Special-token registry. Configuring unk enables OOV fallback (otherwise unknown codepoints are dropped).

Examples

>>> from lucid.utils.tokenizer import CharTokenizer
>>> tok = CharTokenizer()
>>> tok.train(["the quick brown fox", "the lazy dog sleeps"],
...           vocab_size=64)
>>> tok.encode("the quick dog")[:5]
[0, 1, 2, 3, 4]
>>> tok.decode(tok.encode("the quick dog"))
'the quick dog'

Used by 1

Constructors

1
dunder

__init__

→None
__init__(vocab: dict[str, int] | None = None, special_tokens: SpecialTokens | None = None)

Construct a pure-Python character tokenizer.

Parameters

vocabdict[str, int] or None= None
Pre-built codepoint → id map; None or empty means empty tokenizer (call train to populate).
special_tokens(SpecialTokens or None, optional, keyword - only)= None
Special-token registry; configure unk for OOV fallback during encode.

Properties

2
prop

algo

→strfrom _VocabTokenizer
algo: str

Algorithm identifier.

prop

vocab_size

→intfrom _VocabTokenizer
vocab_size: int

Total number of tokens currently registered in the vocab.

Class methods

1
cls

from_file

→Selffrom _VocabTokenizer
from_file(directory: str, special_tokens: SpecialTokens | None = None)

Load from a directory containing vocab.txt.

Instance methods

4
fn

get_vocab

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

Return a shallow copy of the token → id map.

fn

id_to_token

→str | Nonefrom _VocabTokenizer
id_to_token(token_id: int)

Return the surface string for token_id or None.

fn

save

→Nonefrom _VocabTokenizer
save(directory: str)

Persist as vocab.txt + unified tokenizer.json.

fn

train

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

Build vocab by collecting unique codepoints in insertion order.

Stops when vocab_size distinct codepoints have been observed.

Parameters

corpusiterable of str
Each item is one document. Generators are consumed once.
vocab_sizeint= 1000
Maximum number of distinct codepoints to retain.