Phase 01/Tensors and tokens/Tokenization and embeddings
PHASE 01 · Tensors and tokens

Tokenization and embeddings

0%
5 h5 subtopics2 lessons · 1 required
In plain English

A model cannot read letters. Before any text reaches it, a tokenizer chops the text into pieces called tokens, which are often whole common words but can also be fragments like "ing" or single characters. Each piece has a number, like an entry in a dictionary. The embedding table then turns each number into a long list of learned numbers that captures something about its meaning. Think of it as translating a sentence into barcode IDs, then looking up each barcode in a catalogue to get a detailed description card. The number of tokens, not the number of words, is what the model's cost and speed depend on, which is why inference engineers care about it.

Why it matters

Every latency, throughput and memory number in inference is quoted per token, so you must know what a token is and how many your input becomes. The embedding table is also the single largest tensor in small models, and the unembedding matmul is a real cost at every decode step.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, Hugging Face, Liquid AI, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain how byte-pair encoding builds a vocabulary and tokenizes new text.
  • Compare token counts of the same text under GPT-2 and Llama tokenizers.
  • Locate the embedding matrix in a model and compute its parameter share.
  • Train a tiny BPE tokenizer and inspect its merges.
  • Describe what weight tying between embedding and unembedding means.

Key concepts

Token
The unit a model reads; a short string of bytes mapped to an integer id in the vocabulary.
Byte-pair encoding (BPE)
Build a vocabulary by repeatedly merging the most frequent adjacent pair of symbols in a training corpus.
Vocabulary size
Number of distinct tokens (50,257 for GPT-2, 32,000 for Llama 2); sets the width of the embedding and unembedding matrices.
Embedding matrix
A (vocab, d_model) lookup table; token id i selects row i as the model's input vector.
Unembedding / LM head
The final (d_model, vocab) projection that turns the last hidden state into one logit per token.
Weight tying
Sharing one matrix for embedding and unembedding, as GPT-2 does, saving vocab*d_model parameters.
Special tokens
Reserved ids such as BOS, EOS and padding that control sequence boundaries and chat formatting.

Subtopics

  1. 1. From bytes to tokens

    Byte-level BPE, pre-tokenization regexes, why whitespace and leading spaces matter in GPT-2.

  2. 2. Vocabulary trade-offs

    Larger vocabularies mean fewer tokens per text but bigger embedding and LM-head matrices; effects on code and non-English text.

  3. 3. Embedding lookup

    nn.Embedding as a gather over a (vocab, d_model) matrix; token plus position embeddings in GPT-2.

  4. 4. Unembedding and logits

    The LM head produces a (T, vocab) logit tensor; softmax and sampling turn it into a next token.

  5. 5. Chat templates and special tokens

    How instruction-tuned models like TinyLlama-Chat wrap turns in special tokens via tokenizer.apply_chat_template.

Resources

Hands-on lessons

L1

Count tokens and find the embedding table

CPU · your Macnotebook75 minrequired

Goal · Produce a token-count comparison across tokenizers and compute the embedding matrix's share of GPT-2 parameters.

  1. 1Load AutoTokenizer for gpt2 and TinyLlama/TinyLlama-1.1B-Chat-v1.0.
  2. 2Tokenize five texts (an English paragraph, Python code, a JSON blob, a non-English paragraph, a string of digits) with both; tabulate token counts and tokens per word.
  3. 3Print tokenizer.convert_ids_to_tokens for the code sample and note how indentation and leading spaces are encoded.
  4. 4Load gpt2 with AutoModelForCausalLM; find model.transformer.wte.weight and print its shape.
  5. 5Compute wte.numel() / total parameters and check whether model.lm_head.weight shares data_ptr() with wte.
  6. 6Pick the token for ' king' and list the 10 nearest tokens by cosine similarity of embedding rows.
Deliverable
A notebook with the token-count table, the parameter-share number and the nearest-neighbour list.
Check
GPT-2 wte has shape (50257, 768) and is 38,597,376 parameters, about 31 percent of 124,439,808; lm_head shares storage with wte.
L2

Train a 1k-vocab BPE tokenizer on Tiny Shakespeare

CPU · your Macscript60 minoptional

Goal · Train your own byte-level BPE tokenizer and show how vocabulary size changes compression.

  1. 1Download input.txt from the nanoGPT shakespeare_char data folder.
  2. 2Use the tokenizers library (ByteLevel pre-tokenizer, BpeTrainer) to train with vocab_size 256, 1000 and 5000.
  3. 3For each vocabulary, encode the full text and record total tokens and bytes per token.
  4. 4Print the first 30 merges of the 1000 vocab and explain three of them.
  5. 5Encode a sentence not in Shakespeare (a Python line) and compare with the gpt2 tokenizer count.
Deliverable
A script plus a short table of vocab size vs total tokens.
Check
Token count decreases monotonically with vocabulary size, and the 256 vocab gives exactly one token per byte.

Build your own

Build your own BPE tokenizer

PythonCPU · your Mac~6 h

A byte-level BPE tokenizer with training, encoding, decoding and special tokens, written from scratch and checked token-for-token against tiktoken's GPT-2 vocabulary.

The real thing: github.com/openai/tiktoken ↗

How you know a stage passes

Write tests/test_bpe.py first. Early stages assert round-trip equality (decode(encode(s)) == s) on a fixed set of strings including emoji and CJK text, and compare merge tables against minbpe's reference output on Tiny Shakespeare. Later stages load the GPT-2 vocab and merges files and compare your ids with `tiktoken.get_encoding("gpt2")` on 1,000 lines of text. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01bytes in, bytes out
    A Tokenizer with vocab size 256 where encode maps text to its UTF-8 bytes and decode reverses it.
    test · decode(encode(s)) == s for every string in the fixture, and encode("hello") == [104, 101, 108, 108, 111].
  2. 02train merges
    `train(text, vocab_size)` repeatedly merges the most frequent adjacent pair and records the merge order; encode applies merges in that order.
    test · Training to 512 on Tiny Shakespeare produces the same first 50 merges as minbpe's BasicTokenizer; token count on the training text drops below 60 percent of the byte count.
  3. 03regex pre-tokenization
    Text is split with the GPT-2 regex pattern before merging so that merges never cross word or category boundaries.
    test · encode("hello world") never contains a token spanning the space and the following letters; training produces no merge whose bytes contain a space followed by a letter.
  4. 04load GPT-2's vocabulary
    Your tokenizer loads the published GPT-2 encoder.json and vocab.bpe files, including the byte-to-unicode mapping, and encodes with them.
    test · Your ids equal tiktoken gpt2 ids on all 1,000 fixture lines; "Hello, world!" encodes to [15496, 11, 995, 0].
  5. 05special tokens and chat templates
    Special tokens such as <|endoftext|> are matched before BPE and never split; a tiny chat template renders role markers into those tokens.
    test · encode("<|endoftext|>") returns [50256]; a two-turn chat renders to the exact id list in the fixture; a user message containing the literal string "<|endoftext|>" is not treated as special when allowed_special is empty.
  6. 06make it fast enough
    Encoding uses a priority queue or rank-lookup merge loop instead of rescanning the whole sequence per merge.
    test · Encoding 1 MB of text takes under 5 seconds on your Mac and the ids are unchanged; the README reports tokens per second next to tiktoken's.

Knowledge check

QWhy does ' the' (with a leading space) have a different GPT-2 token id than 'the'?

GPT-2 is byte-level and treats the space as part of the token, so word-initial and word-internal occurrences get different ids.

QWhat is the cost of growing the vocabulary from 32k to 128k tokens for a d_model 4096 model?

Embedding and LM head each grow by 96k*4096 = about 393M parameters, and the final logit matmul does 4x more work per token, in exchange for fewer tokens per text.

QIs an embedding lookup a matmul?

Mathematically it equals a one-hot matmul, but it is implemented as a gather of rows, which is a memory read rather than arithmetic.

QWhat does weight tying save in GPT-2 small?

One copy of the (50257, 768) matrix, about 38.6M parameters, roughly 31 percent of the model.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 check passes with the exact parameter numbers.
  • Can explain BPE training in under two minutes with an example merge.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →