Check my levelCoursesProgramsFor teamsPricing
UKSign inSign up
Check my levelCoursesProgramsFor teamsPricingClaude quizPromptsBlogFAQSearchSign upUK
AcademlCoursesHugging Face LLM Course: Practical TransformersTokenization: BPE, WordPiece, SentencePiece
LoRA tuning: a large weight matrix plus two thin onesThe ollama run command and a VRAM gauge the model fits intoA shelf of open-weight models: DeepSeek, Qwen, Mistral, Llama
Get started free
Course

Hugging Face LLM Course: Practical Transformers

Module 1 · Transformers and Tokenization
01Pipeline API: Run Models in Three Lines02Tokenization: BPE, WordPiece, SentencePiece03Hugging Face Hub: Finding and Downloading Models
Module 2 · Fine-Tuning
04Dataset Preparation: load_dataset and Tokenization05Trainer API: Fine-Tuning a Classifier06PEFT and LoRA: Fine-Tuning Without Full Training
Module 3 · Advanced Capabilities
07Hugging Face Inference Providers: Serverless Inference08Gradio + Spaces: Deploy an ML Demo in 10 Minutes09vLLM + smolagents: Inference Server and Tool-Using Agents
Hugging Face LLM Course: Practical Transformers · Lesson 2

Tokenization: BPE vs WordPiece vs SentencePiece (and Unigram)

A tokenizer splits text into subwords and converts them to numbers the model understands. For chat models it also holds the dialogue format (chat template).

40 min readUpdated Dec 2, 20262 questions in quizReady prompt included

What is the difference between BPE, WordPiece and SentencePiece?

BPE and WordPiece both build a vocabulary by merging symbol pairs: BPE takes the most frequent pair, WordPiece the pair that occurs most often relative to its parts. SentencePiece is a library: it runs BPE or Unigram directly on raw text and stores the space as ▁, so it also works for languages without spaces.

Start free: 7 days of full access →
Lesson 2 of 9free after sign-up

Hugging Face LLM Course: Practical Transformers

9 practical lessons with Transformers: pipeline(), tokenizers, the Hub, Trainer, LoRA and a Gradio demo on Spaces. Each lesson has a task checked by AI and a short quiz.

Course program →

The rest of this lesson opens after a free sign-up

Sign up with email or Google: the first two lessons of every course stay open for good, and the whole catalog is open for 7 days. No card needed.

Sign up freeOr a trial lesson, no sign-up →

Which algorithm, which models

The four names you meet in the Hugging Face docs, side by side. Three are algorithms; SentencePiece is the library that runs two of them on raw text.

NameHow it builds tokensModels (per Hugging Face docs)What you see in the output
BPEStarts from characters and merges the most frequent adjacent pair until the vocabulary reaches its target sizeLlama, Gemma, Qwen2; GPT (40,478 tokens). GPT-2 uses byte-level BPE: 256 bytes + 50,000 merges + end-of-text = 50,257Any text maps to tokens; byte-level BPE needs no <unk>
WordPieceMerges the pair with the highest score: freq(pair) ÷ (freq(a) × freq(b))BERT, DistilBERT, ElectraWord-internal pieces start with ##, e.g. play ##ing
UnigramStarts from a large vocabulary and drops the tokens whose removal raises the loss least (10–20% per round); picks the most probable splitT5, BigBird, PegasusCan sample several splits of one word during training
SentencePieceA library: applies BPE or Unigram to the raw character stream, with the space as a symbolCheckpoints that ship a SentencePiece model file (for example spiece.model in T5)▁ marks a space; decoding turns ▁ back into spaces
Source: Hugging Face Transformers docs, “Tokenization algorithms”, checked 9 Nov 2026.
In this lesson
AlgorithmsChat templates for LLMsSpecial TokensPracticeReady promptQuiz
CoursesLLM coursesFor teamsPricingFAQBlogAboutPrivacy
© 2026 AcademlDevelopment & promotion —MMIX — Marketing Mix

From text to input_ids: the tokenizer pipeline

  1. NormalizationUnicode cleanup, lowercasing for uncased models
    →
  2. Pre-tokenizationSplit on spaces and punctuation; SentencePiece works on the raw stream
    →
  3. ModelBPE, WordPiece or Unigram splits words into subwords
    →
  4. Post-processingAdds [CLS]/[SEP] or <s>, builds attention_mask
    →
The four stages of the 🤗 Tokenizers pipeline. AutoTokenizer.from_pretrained(...) runs all four with the settings saved in the checkpoint.

Errors and version notes

Checked on 9 Nov 2026 against the Transformers docs, the v5.0.0 release notes and the Hugging Face blog.

  • “LlamaTokenizer requires the SentencePiece library”: in Transformers 4.x the slow tokenizers built on a SentencePiece model (LlamaTokenizer, T5Tokenizer, DebertaV2Tokenizer and others) import the sentencepiece package. Run pip install sentencepiece and restart the kernel, or load AutoTokenizer.from_pretrained(model_id), which picks the fast tokenizer when the checkpoint has tokenizer.json.
  • Transformers v5 has been the stable release since 26 Jan 2026. Per the Hugging Face blog (18 Dec 2025), one tokenizer file per model replaces the slow/fast pair, LlamaTokenizer now inherits from the Rust tokenizers backend, which is the default, and a SentencePiece backend stays for the models that need it.
  • Keep one tokenizer per model family: the same sentence gets different input_ids from BERT, GPT-2 and T5 tokenizers, and a model reads foreign ids as different tokens.
  • When you pad a batch, pass attention_mask (1 = real token, 0 = padding), otherwise the model attends to padding as if it were text.

Sources we checked

  • Hugging Face Transformers: Tokenization algorithms
  • Hugging Face Tokenizers: The tokenization pipeline
  • Hugging Face LLM Course, chapter 6: Tokenizers
  • Hugging Face blog: Tokenization in Transformers v5
  • Transformers v5.0.0 release notes
  • Kudo & Richardson (2018): SentencePiece

FAQ

Does BERT use WordPiece and GPT-2 use BPE?+

Yes. BERT and its family (DistilBERT, Electra) use WordPiece, and pieces inside a word start with ##. GPT-2 uses byte-level BPE with 50,257 tokens: 256 byte tokens, 50,000 merges and an end-of-text token, so any text can be encoded without an unknown token.

Is SentencePiece an algorithm or a library?+

A library. SentencePiece runs BPE or Unigram on raw text and treats the space as an ordinary symbol (▁). That is why it suits languages written without spaces, such as Chinese and Japanese. Hugging Face lists T5 among the Unigram models.

What is Unigram tokenization?+

Unigram starts with a large candidate vocabulary and removes, round by round, the tokens whose removal increases the loss least (usually the bottom 10–20%), keeping base characters. At inference it picks the most probable split; during training it can sample several splits of the same word.

How do I fix “LlamaTokenizer requires the SentencePiece library”?+

In Transformers 4.x, install the package with pip install sentencepiece and restart the Python kernel, or load the tokenizer through AutoTokenizer.from_pretrained(model_id), which uses the fast tokenizer when the checkpoint has a tokenizer.json; the same fix applies to T5Tokenizer and DebertaV2Tokenizer. In Transformers v5, stable since January 2026, LlamaTokenizer runs on the Rust tokenizers backend, and the SentencePiece backend stays for the models that need it.

Which tokenizer should I use for my model?+

The one the checkpoint was trained with: load it by model id with AutoTokenizer. Choosing between BPE, WordPiece and Unigram matters when you train a new tokenizer, which chapter 6 of the free Hugging Face LLM Course covers.

Where is the official documentation on BPE, WordPiece and SentencePiece?+

The Transformers page “Tokenization algorithms”, the 🤗 Tokenizers docs on the pipeline, and chapter 6 of the Hugging Face LLM Course. This lesson belongs to Academl's own course and is independent of Hugging Face.

Is this lesson free?+

Yes. It is lesson 2 of 9 in “Hugging Face LLM Course: Practical Transformers”, and a free account keeps the first two lessons of every Academl course open for good. A free account opens all lessons for 7 days with no card; after that Pro costs $9 a month or $79 a year.

Related lessons and courses

Lesson 1: pipeline() in three lines →Tokenizing a dataset with load_dataset →Hugging Face LLM course →OpenAI embeddings in Python →LLM engineer roadmap →Open-source LLMs course →OpenAI embeddings guide →

Continue the course: from tokenizers to LoRA

The next lessons cover the Hub, dataset preparation, the Trainer API, PEFT and LoRA, Inference Providers and a Gradio demo on Spaces. A free account opens all 9 lessons for 7 days.

Create a free account →

Algorithms

  • BPE (GPT-2, RoBERTa) — iteratively merges the most frequent symbol pairs. Its byte-level variant works on bytes, so any text, including Cyrillic and emoji, splits without unknown tokens. Most current LLMs use it: Llama 3 and Llama 4, Qwen, GPT models.
  • WordPiece (BERT) — merges that maximise corpus likelihood.
  • SentencePiece (T5, Llama 1 and 2) — trains BPE or Unigram directly on raw text and encodes the space as an ordinary symbol ▁, so it is whitespace-agnostic.

The examples target transformers 5. Version 5 has one tokenizer per model: the split into slow (Python) and fast (Rust) implementations is gone, and AutoTokenizer picks the backend for you.

from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
print(tok.tokenize("Hugging Face!"))  # ['hugging', 'face', '!']
enc = tok("Hugging Face!", return_tensors="pt")
print(enc.input_ids)           # tensor([[101, ..., 102]])

batch_enc = tok(["Short.", "Much longer."], padding=True, truncation=True,
                max_length=16, return_tensors="pt")
print(batch_enc.attention_mask)  # 1=real, 0=pad

print(tok.decode([101, 7592, 2088, 102], skip_special_tokens=True))  # hello world
print(tok.decode(batch_enc.input_ids.tolist(), skip_special_tokens=True))  # list of strings

enc = tok("Hello world", return_offsets_mapping=True)
print(enc.offset_mapping)  # character span of each token