Unit 2 of 7 · about 6 hours · derive, implement

Byte-level BPE: training, merges and tie-breaking

Every later count in this stage, from sequence lengths to KV-cache bytes, is measured in tokens, and BPE decides what a token is. The merge list is part of the model's identity: change one tie-break and every token ID downstream shifts.

You'll be able to

  • Run BPE training by hand on a small corpus, apply the tie-breaking rule, and predict the merge list.
  • Implement byte-level BPE training from a blank file, with regex pre-tokenization and special tokens as hard boundaries.
  • Explain why a byte-level vocabulary encodes any input without an unknown token.

Covers

Byte-level tokenization and complete input coverageBPE pair counts, merges and deterministic tie breaking
1

Read

In this order, only the parts listed

0 of 2 done

  1. BPE tokenizer from scratch (notebook)LLMs from Scratch companion - tokenization and data loading

    Sections 1.1 to 1.4 for bytes, the vocabulary and a worked example, then 3.1 for training, encoding and decoding

    Skim section 2, the simple implementation. Skip 3.3, loading OpenAI's GPT-2 files, until the identity unit.

  2. CS336 Assignment 1 handoutStanford CS336 Assignment 1 - tokenizer contract

    Section 2.4, BPE Tokenizer Training, with Example (bpe_example) (pp. 5 to 7), then Section 2.5 on removing special tokens before pre-tokenization and optimizing the merge step (pp. 8 to 9)

2

Focus on

  • The base vocabulary is all 256 byte values, so coverage is complete before the first merge. Merges only shorten sequences.
  • Pairs are counted inside pre-tokens, weighted by how often each pre-token occurs. No pair crosses a pre-token or special-token boundary.
  • Ties go to the lexicographically greater pair. Without a fixed rule, two correct trainers produce different merge lists.
  • After a merge, only the counts of pairs that overlap the merged occurrences change. Updating just those makes training fast.
Common mistakes · 3
  • Decoding token bytes to str to compare or print them. A merged token can be a partial UTF-8 sequence, so decoding fails or maps distinct tokens to the same replacement character.
  • Pre-tokenizing before splitting on special tokens. Their text then enters the pair counts as ordinary pieces such as <| and endoftext, and steals merges.
  • Treating vocab_size as the number of merges. It includes the 256 byte values, the merges and the special tokens.
3

Try it yourself

Closed-book, before checking anything

By hand, train on the CS336 example corpus (low x5, lower x2, widest x3, newest x6) for six merges and get s t, e st, o w, l ow, w est, n e. Then tokenize newest as [ne, west].
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why can byte-level BPE encode any string, while a character vocabulary built from a corpus cannot?Answer

    Its base vocabulary holds all 256 byte values, and every string has a UTF-8 encoding. A character vocabulary covers only the characters seen in training, so an unseen character needs an unknown token.

  2. 2.The pairs (A, B), (A, C), (B, ZZ) and (BA, A) tie for the highest count. Which one merges under the CS336 rule?Answer

    (BA, A). The rule takes the lexicographically greatest pair, and BA sorts after A and B.

  3. 3.After (s, t) merges into st, which pair counts can change?Answer

    Only counts next to the merged occurrences. Each neighbouring pair (x, s) or (t, y) loses those occurrences, the new pairs (x, st) and (st, y) gain them, and (s, t) loses every occurrence that merged. All other counts stay the same.

  4. 4.A training file contains [Doc 1]<|endoftext|>[Doc 2]. What goes wrong if you pre-tokenize it without splitting on the special token first?Answer

    The special token's text is pre-tokenized like ordinary text, so its pieces enter the pair counts and can earn merges. The trainer should split on special tokens so that they act as hard boundaries and contribute nothing to the counts.

5

Practice

  • CS336 Assignment 1: train_bpe

    Problem (train_bpe) in Section 2.4; connect your trainer to run_train_bpe in tests/adapters.py and pass tests/test_train_bpe.py

    The public tests compare your merges and vocabulary with a reference, check special-token handling, and require training on the small fixture in under 1.5 seconds. Implement it in your own repository.

You're done when

You reproduce the six example merges by hand, and your own trainer passes all three tests in tests/test_train_bpe.py.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 5 more in the section
  • LLMs from Scratch companion - tokenization and data loadingSebastian Raschka · primary

    Work through the ch02 main notebook, 05_bpe-from-scratch and 04_bonus_dataloader-intuition. Rebuild byte-level BPE, serialization and packed windows in blank files, then add multilingual, control, whitespace and chunk-boundary properties.

  • Stanford CS336 Assignment 1 - tokenizer contractStanford University · required

    Read the Assignment 1 tokenizer handout and use the named unicode1, unicode2, train_bpe, tokenizer and tokenizer_experiments specifications plus public tests as an acceptance contract. Implement independently in your own repository and do not copy or modify course solutions.

Also in this section

  • Modern LLM Notebook - tokenization and data experimentsWalking Labs · support

    Run English notebooks 01-tokenizer-basics and 02-bpe-tokenizer. Use only the quality, deduplication and mixture examples from 15-data-engineering. Change the corpus and tie cases, then verify every quantitative claim independently.

  • Tokenizer and Corpus Pipeline - reduced foundation sliceRoadmap-Final · support

    Use the byte, identity, split, deduplication, contamination, packing, manifest and restart correctness requirements. Keep the corpus small and stop before distributed processing or internet-scale filtering.

  • Hugging Face LLM Course - tokenizer translationHugging Face · optional

    After the blank-file tokenizer passes, use the tokenizer chapters to map vocabulary, special tokens, fast tokenizers and batching into library APIs. Do not replace the deterministic implementation gate with a pretrained tokenizer call.

  • Python unicodedata - normalization formsPython Software Foundation · reference

    Read unicodedata.normalize for canonical and compatibility equivalence, and unidata_version for recording the normalization database version.

  • Hugging Face Datasets - streaming, sharding and resumeHugging Face · reference

    Read Shard, Interleave, Save a dataset checkpoint and resume iteration, and Export. Use tiny local data and inspect the warning that shuffle buffers are lost on resume; do not download web-scale corpora or upload to the Hub.