Blazingly fast tokenizer — 50x faster, 10x smaller, 100% accurate
Actively maintained. Last release 3 weeks ago, commits in 7 of the last 26 weeks. A safe choice.
pip install tokie
Python bindings for the tokie Rust tokenizer. The tokie Python package is 0.3.0 and wraps the Rust tokie 0.2.0 crate. encode, encode_plus, and batch release the GIL and return NumPy arrays. There is no Encoding object and no .ids attribute; use .tolist() only to print or assert.
decode and decode_bytes take the array returned by encode, encode_plus, or a slice of batch's flat uint32 ids. Pass it directly; do not call .tolist() first. The array must be one-dimensional, native-endian, C-contiguous, and aligned uint32. Lists, tuples, and arrays of another dtype are rejected; 0.2.0 also accepted lists.
Installation
pip install -U tokie
Pin a floor with pip install "tokie>=0.3.0" when a resolver needs one.
Quick start
import tokie
tokenizer = tokie.Tokenizer.from_pretrained("openai-community/gpt2")
# from_json(path) and from_file(path) are aliases for open(path).
ids = tokenizer.encode("Hello world") # uint32 array, template off
print(ids.tolist())
print(tokenizer.decode(ids))
print(tokenizer.decode_bytes(ids)) # raw bytes
# The single-sequence template. GPT-2 has none, so this matches encode.
print(tokenizer.encode_plus("Hello world").tolist())
flat, ends = tokenizer.batch(["Hello world", "a12b"]) # ends are cumulative
print(tokenizer.count_tokens("Hello world")) # template off
print(tokenizer.count_tokens_batch(["Hello world", "a12b"]))
print(tokenizer.vocab_size) # highest id + 1
print(tokenizer.pad_token_id) # [PAD] then <pad>
print(tokenizer.num_special_tokens_to_add(is_pair=False))
tokenizer.save("gpt2.tokie")
encode leaves the template off. encode_plus applies it and accepts pair, truncate, and pad; truncation is from the right, longest sequence first, and padding is fixed on the right. One max_len covers both and counts the template ids.
opens exactly one file from the repo, whatever its name. A repo with no file is parsed from ; several files is an error. There is no runtime fallback: a genuine legacy image is refused by magic, not by extension, while a JSON file merely named is parsed as JSON. reads either file from disk by its magic, and are path aliases for , and parses JSON text.