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)β
| Algorithm | Typical models | Idea |
|---|---|---|
| WordPiece | BERT | Merge frequent pieces; uses ## continuation |
| BPE | GPT-2, many LLMs | Byte-pair merges on frequency |
| Unigram | T5 / SentencePiece | Probabilistic subword set |
| Byte-level BPE | GPT-2 / RoBERTa lineage | Operates 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_tokenmay need explicit setup for GPT-style models.
Discussion
Commentsβ
Share feedback or questions about this page. No account required.
Loading commentsβ¦