Skip to content
MAMasterAI Now
5 / 11قراءة 14 دقيقةالمستوى: Beginner5 بطاقات

تقطيع BPE

كيف يتحوّل النص الخام إلى الأعداد الصحيحة التي يقرأها المحوّل فعلًا.

⚠ هذه المرحلة مترجمة بنسبة 3% إلى العربية؛ وتُعرض البطاقات المتبقية بالإنجليزية. لاحظت خطأ؟ تصحيحات الترجمة مرحّب بها.

تقدّم القراءة0%
Card 1 — the interfaceالبطاقة 1 من 5

Models cannot read text. They read integers.

The tokenizer is the only component that ever sees characters.

A transformer is a stack of matrix multiplications. It has no idea what a letter is. So every string must first be chopped into tokens, and each token mapped to an integer id from a fixed vocabulary. Feed in "Hello world" and the model actually receives something like [15496, 995].

Analogy
The library catalogue

A tokenizer is a librarian who breaks every incoming book into index cards from a fixed card deck. The model only ever handles card numbers. If the deck lacks a card for a word, the librarian spells it out over several cards.

The full pipeline is: text → tokens → token ids → embeddings → transformer → token ids → text. Notice that the tokenizer sits at both ends: the model's raw output is a probability distribution over token ids, and the detokenizer stitches those ids back into a string.

Watch outWhy this matters financially

API pricing, context-window limits and generation speed are all measured in TOKENS, not characters or words. A badly tokenized language can cost several times more per sentence than English for the identical meaning.

تحقّق سريع قبل البطاقة التالية

What does a transformer model receive as input?

5 اختبارات

🔒

المختبر مغلق

أكمل بطاقات المرحلة (5) واختباراتها لفتح هذه المحاكاة.

Read the full stage transcript (all 5 cards, no JavaScript required)
Card 1 — the interface

1. Models cannot read text. They read integers.

The tokenizer is the only component that ever sees characters.

A transformer is a stack of matrix multiplications. It has no idea what a letter is. So every string must first be chopped into tokens, and each token mapped to an integer id from a fixed vocabulary. Feed in "Hello world" and the model actually receives something like [15496, 995].

Analogy
The library catalogue

A tokenizer is a librarian who breaks every incoming book into index cards from a fixed card deck. The model only ever handles card numbers. If the deck lacks a card for a word, the librarian spells it out over several cards.

The full pipeline is: text → tokens → token ids → embeddings → transformer → token ids → text. Notice that the tokenizer sits at both ends: the model's raw output is a probability distribution over token ids, and the detokenizer stitches those ids back into a string.

Watch outWhy this matters financially

API pricing, context-window limits and generation speed are all measured in TOKENS, not characters or words. A badly tokenized language can cost several times more per sentence than English for the identical meaning.

Knowledge check: What does a transformer model receive as input?

  • a. Raw Unicode characters
  • b. Integer token ids drawn from a fixed vocabulary← correct
  • c. Word frequencies

Everything between characters and ids — normalisation, splitting, merging — is tokenizer business, not model business.

Card 2 — the dilemma

2. Characters are too fine, words are too coarse

Pick your poison: a huge vocabulary or an endless sequence.

GranularityVocabularySequence lengthProblem
Characters~100Very longSequences explode; the model must relearn spelling
Whole words1,000,000+ShortUnknown words are unrepresentable; rare words starve
Sub-words (BPE)~50,000MediumNeeds a training pass to build — the accepted trade-off

Whole-word vocabularies break the moment the model meets "unfriendliest" or a new product name, because the id simply does not exist. Character-level vocabularies never break but turn every sentence into a marathon of steps — and attention cost grows with the square of sequence length.

Analogy
LEGO bricks, not atoms

Characters are atoms; whole words are prefabricated walls that only fit one building. Sub-word tokens are LEGO bricks: a small set of reusable pieces that can spell anything, including words nobody has invented yet.

Byte-Pair Encoding finds that middle ground automatically. Start from raw bytes, then repeatedly glue together whichever pair of symbols occurs most often. Frequent strings like "the " become single tokens; rare ones stay spelled out.

Knowledge check: Why is a pure whole-word vocabulary a bad idea for an LLM?

  • a. It is impossible to store
  • b. Any word not in the vocabulary cannot be represented at all← correct
  • c. It makes sequences longer

Open vocabularies need a fallback. Sub-word schemes always have byte-level pieces to spell anything, including typos and new words.

Card 3 — the algorithm

3. BPE in four steps

Count pairs, merge the winner, repeat. That is the whole algorithm.

  1. 1Start with every word split into characters, plus an end-of-word marker (commonly the leading space or a special </w>).
  2. 2Count how often each adjacent pair of symbols occurs across the whole corpus.
  3. 3Merge the single most frequent pair into one new symbol and record the merge rule.
  4. 4Repeat until you hit the target vocabulary size (e.g. 50,000 merges).
py
corpus = {'l o w </w>': 5, 'l o w e r </w>': 2, 'n e w e s t </w>': 6}

# pass 1: the most frequent pair is ('e', 's') with count 6
# merge it -> 'e s' becomes the new symbol 'es'
corpus = {'l o w </w>': 5, 'l o w e r </w>': 2, 'n e w es t </w>': 6}

# pass 2: now ('es', 't') occurs 6 times -> merge into 'est'
# pass 3: ('l', 'o') occurs 7 times -> merge into 'lo'
# ... continue until vocab_size merges are learned

Merges are applied greedily in the order they were learned. At encode time the tokenizer replays the recorded merge list on the new text — no counting, no statistics, just a deterministic list of rules applied in sequence.

NoteByte-level BPE

Modern LLMs (GPT-2 onward) run BPE over raw BYTES rather than Unicode characters. Every possible input — emoji, Japanese, Maldivian Thaana, malformed UTF-8 — is representable, with zero out-of-vocabulary tokens. A single emoji may still cost 2–4 tokens.

Knowledge check: At encode time, how does a BPE tokenizer decide how to split new text?

  • a. It re-counts the most frequent pairs in the new text
  • b. It replays the ordered list of merge rules learned during training← correct
  • c. It looks the whole word up in a dictionary

Training learns the rule list; encoding applies it greedily. That is why tokenization is fast and perfectly reproducible, and why different model families tokenize the same string differently.

Card 4 — the trade-off

4. Vocabulary size is a dial with real consequences

Bigger vocabulary, shorter sequences — and a bigger embedding table.

VocabularySequence lengthEmbedding parametersTrade-off
32kLongestSmallestCheap table, expensive attention
50kBalancedModerateCommon default for multilingual models
128kShortestLargestFaster generation, heavy embedding/output layers

The embedding matrix and the final output projection both scale linearly with vocabulary size: vocab × hidden_dim, twice. For a 128k vocabulary and 4096-width hidden state that is over a billion parameters spent purely on lookup tables.

  • Sequence length costs quadratically in attention, so merging frequent strings pays off fast.
  • Rare tokens get weak gradients — a token seen 50 times in pretraining never learns a good vector.
  • Multilingual fairness: languages poorly covered by the vocabulary produce 3–5× more tokens per sentence, meaning higher cost, slower output and shorter effective context.
  • Special tokens (<|endoftext|>, <|im_start|>, chat roles) are reserved ids inserted deliberately, never produced by merges.

Knowledge check: A language is under-represented in your BPE vocabulary. What is the practical consequence?

  • a. Its sentences cost more tokens, so they hit the context limit sooner and generate slower← correct
  • b. The model cannot represent that language at all
  • c. Nothing, tokenization is language-neutral

Because bytes still cover it, everything is representable — but at a much higher token cost, which is a real latency, pricing and context-window penalty.

Card 5 — gotchas

5. Five tokenization surprises that break production apps

Count tokens, never characters. Especially not for the word "strawberry".

  • Counting characters is impossible. A model cannot reliably say how many letters are in a word, because it never sees letters — it sees whole chunks. "strawberry" may be two tokens, so "count the r's" is a question about pieces it cannot decompose.
  • Numbers tokenize irregularly. "1000" may be a single token while "1001" splits into two, which is why arithmetic is unstable and why chunking digits before feeding a calculator helps.
  • Leading spaces matter. "hello" and " hello" are different tokens. Stray whitespace changes the id sequence and can shift output quality.
  • Glitch tokens exist. Some rare merge artefacts (famously SolidGoldMagikarp in early GPT-2-era tokenizers) received almost no training signal and produce bizarre model behaviour.
  • Prompt length is counted in tokens. A "200-character" prompt can be 30 tokens or 200 depending on language and symbols. Always measure, then budget.
Analogy
Cutting a mosaic

Ask someone to cut a mosaic into tiles. Give them tiny tiles and you get a beautiful picture needing thousands of pieces (characters). Give them tiles the size of the whole sky and the picture is useless (whole words). BPE chooses the tile size that keeps the picture recognisable with the fewest pieces.

Good to knowRule of thumb

For English prose, expect roughly 4 characters per token, so 1,000 words ≈ 1,300 tokens. For code, emoji-heavy text, or languages like Turkish and Finnish with long agglutinative words, budget 2–3× more.

NoteNext up

Every token now has an id — and every id will get an embedding vector. Stage 6 takes those vectors into three dimensions so you can finally see what "similar meaning" looks like.

Knowledge check: Why can an LLM fail at "how many r letters are in strawberry?"

  • a. It never sees individual letters — the word arrives as whole sub-word tokens← correct
  • b. The letter r is not in its vocabulary
  • c. Because it is not connected to the internet

Character-level reasoning has to be reconstructed from token representations. Modern frontier models have largely patched this with specialised training, but the underlying representation limit still explains the pattern.