Skip to main content

Tokenizers

Tokenizers map text to integer ids (and back). Transformers prefers fast tokenizers from the πŸ€— Tokenizers library when available.

Adapted for this playbook from the πŸ€— Transformers documentation by Hugging Face. Official page: https://huggingface.co/docs/transformers/fast_tokenizers. Images Β© Hugging Face (documentation-images) unless noted. This is not a substitute for the upstream docs β€” verify against the current version.

Covers Hugging Face pages: fast_tokenizers, custom_tokenizers, tokenizer_summary

Load a tokenizer​

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
encoded = tokenizer(
"Hugging Face Transformers",
padding=True,
truncation=True,
return_tensors="pt",
)
print(encoded.keys()) # input_ids, attention_mask, ...

Algorithms (summary)​

AlgorithmTypical modelsIdea
WordPieceBERTMerge frequent pieces; uses ## continuation
BPEGPT-2, many LLMsByte-pair merges on frequency
UnigramT5 / SentencePieceProbabilistic subword set
Byte-level BPEGPT-2 / RoBERTa lineageOperates on bytes for full coverage

Official detail: Tokenization algorithms.

Fast vs slow​

  • Fast β€” Rust implementation; batching, offsets, alignment helpers
  • Slow β€” pure Python fallback for some models
tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=True)

Chat templates​

Instruction models expect messages rendered through a chat template (Jinja). See Chat and tools.

Pitfalls​

  • Different tokenizers β‡’ different ids for the β€œsame” text β€” never mix across models.
  • Left vs right padding matters for decoder-only generation.
  • add_eos_token / pad_token may need explicit setup for GPT-style models.

Discussion

Comments​

Share feedback or questions about this page. No account required.

Loading comments…