Tokens In, Tokens Out: Tokenizers, Decoding Controls and the KV Cache
How text becomes subword tokens with byte-pair encoding, how a model turns next-token scores into text with greedy decoding, temperature, top-k and top-p sampling, repetition, frequency and presence penalties and stop sequences, and why the KV cache makes generation fast while its memory grows with context length and batch size.
Contentsand lesson path
On this page
- Why it matters
- Subword tokenization with byte-pair encoding
- From scores to text: decoding controls
- The KV cache and the cost of context
- Check your understanding
- Apply it
- Review prompt
Lessons of Transformer Architecture
- Attention as Soft Lookup: Queries, Keys and Values Concept · 20 min
- Lab: Build Multi-Head Causal Self-Attention from Scratch Lab · 30 min
- Anatomy of a Transformer Block and the Three Model Families Concept · 25 min
- Tokens In, Tokens Out: Tokenizers, Decoding Controls and the KV Cache Concept · 25 min
- Lab: Fine-Tune a Pretrained Encoder for Classification Lab · 30 min
- Check: Inside the Transformer Knowledge check · 8 questions
What you will learn
- Explain subword tokenization, autoregressive decoding and its controls (greedy, temperature, top-k and top-p sampling, repetition, frequency and presence penalties, stop sequences) and how the KV cache and context length drive inference cost.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
A language model never sees text. A tokenizer turns text into a list of integer ids, the model turns the ids so far into a score for every possible next id, and a decoding procedure picks one, appends it and repeats. Each of these steps has settings you will meet in every model API and serving framework: why a word costs three tokens, what temperature and top-p do, why a summary repeats itself, where an answer stops, and why long prompts and many parallel users run a GPU out of memory.
This lesson builds each step in a few lines of Python 3.12 and PyTorch 2, small enough to read in full: a byte-pair-encoding tokenizer, a word-level model whose scores come from counting word pairs, and one attention layer with and without a cache.
02. Subword tokenization with byte-pair encoding
Splitting text into whole words gives a huge vocabulary and no way to handle a word that was not in the training data. Splitting into characters handles everything but makes sequences very long. Subword tokenization sits in between: frequent words become one token, rare words are built from a few pieces. Byte-pair encoding (BPE), used by the GPT and Llama families, learns its pieces from data. It starts from single characters and repeatedly merges the most frequent adjacent pair into a new symbol, recording each merge. To encode new text, it applies the merges in the same order. The marker </w> marks the end of a word, so that "ing" at the end of a word can become a different token from "ing" in the middle.
"""Learn byte-pair-encoding merges from a tiny corpus, then encode unseen words."""
from collections import Counter
corpus = ("train trains trained training trainer rain rains rained raining "
"brain brains drain drained draining plain explain explained").split()
words = Counter(tuple(w) + ("</w>",) for w in corpus) # characters + end-of-word
def pair_counts(words):
pairs = Counter()
for symbols, n in words.items():
for a, b in zip(symbols, symbols[1:]):
pairs[a, b] += n
return pairs
def merge(symbols, pair):
out, i = [], 0
while i < len(symbols):
if symbols[i:i + 2] == pair:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
return tuple(out)
merges = []
for _ in range(12): # each round: merge the most frequent adjacent pair
best = max(pair_counts(words).items(), key=lambda kv: (kv[1], kv[0]))[0]
merges.append(best)
words = Counter({merge(s, best): n for s, n in words.items()})
print("merges in order:")
print(" ", " ".join("+".join(p) for p in merges))
def encode(word):
symbols = tuple(word) + ("</w>",)
for pair in merges: # apply the merges in the order they were learned
symbols = merge(symbols, pair)
return list(symbols)
for word in ("training", "retrained", "brainy", "zebra"):
print(f"{word:10} -> {encode(word)}")python bpe.pymerges in order:
i+n a+in r+ain t+rain e+d ed+</w> s+</w> rain+</w> p+l pl+ain in+g ing+</w>
training -> ['train', 'ing</w>']
retrained -> ['r', 'e', 'train', 'ed</w>']
brainy -> ['b', 'rain', 'y', '</w>']
zebra -> ['z', 'e', 'b', 'r', 'a', '</w>']The first merges build the pieces that this corpus repeats most: "in", "ain", "rain", "train", the endings "ed" and "ing". "training" then needs only two tokens. "retrained" never appeared, yet it is encoded from known pieces, and even "zebra", whose letters barely occur, falls back to single characters. Byte-level BPE tokenizers (GPT-2 and later, Llama 3) work on bytes rather than characters, so any text in any script can be encoded without an "unknown" token; WordPiece tokenizers such as BERT's, used in the fine-tuning lab, still have an [UNK] token. Real tokenizers learn tens of thousands of merges from large corpora. Two consequences are worth remembering. Token counts, not word counts, set the cost and the context limit of a request, so measure them with the model's own tokenizer. And a model must always be used with the tokenizer it was trained with, because a token id is a row number in its embedding table. SentencePiece (T5) is another related method that differs in how it chooses pieces.
03. From scores to text: decoding controls
At each step the model outputs logits, one raw score per vocabulary entry; a softmax turns them into probabilities. lm.py is a deliberately tiny language model: its logits for the next word are log-probabilities counted from word pairs in a 50-word corpus. It is too simple to be clever, which makes the effect of each decoding control easy to see.
"""A word-level bigram language model: next-word logits from counts in a tiny corpus."""
from collections import Counter
import torch
text = ("the cat sat on the mat . the dog sat on the rug . the cat saw the dog . "
"a dog ran to the park . the cat ran to a tree . a bird sat on a tree . "
"the dog saw a bird on the mat .")
tokens = text.split()
vocab = sorted(set(tokens))
idx = {w: i for i, w in enumerate(vocab)}
counts = torch.full((len(vocab), len(vocab)), 0.02) # small smoothing count
for a, b in zip(tokens, tokens[1:]):
counts[idx[a], idx[b]] += 1
LOGITS = counts.log() # row = previous word, column = next word
def next_logits(prev_word):
return LOGITS[idx[prev_word]].clone()- Greedy decoding always takes the most likely token. It is repeatable, but it tends to repeat itself.
- Temperature divides the logits by T before the softmax. Below 1 it sharpens the distribution towards the top token; above 1 it flattens it, giving rare tokens more chance.
- Top-k keeps only the k most likely tokens; top-p (nucleus sampling) keeps the smallest set of most likely tokens whose probabilities add up to at least p, so the number kept adapts to how confident the model is. Both cut off the long tail of unlikely tokens before sampling.
- Penalties lower the scores of tokens that already appear in the output. The repetition penalty (as in Hugging Face Transformers) divides a positive logit, or multiplies a negative one, by a factor. The frequency penalty (as in OpenAI-style APIs) subtracts an amount for every earlier occurrence, so it grows with the count; the presence penalty subtracts a fixed amount once a token has appeared at all.
- A stop sequence ends generation as soon as the output produces it, and is usually left out of the returned text. A maximum token count is the other way generation ends.
"""Greedy decoding, temperature, top-k, top-p and penalties on the bigram model."""
import torch
from lm import next_logits, vocab
def top_k_filter(logits, k):
cutoff = logits.topk(k).values[-1]
return logits.masked_fill(logits < cutoff, float("-inf"))
def top_p_filter(logits, p):
probs, order = torch.softmax(logits, -1).sort(descending=True)
keep = probs.cumsum(-1) - probs < p # smallest set whose mass reaches p
out = torch.full_like(logits, float("-inf"))
out[order[keep]] = logits[order[keep]]
return out
def generate(start, steps=12, temperature=0.0, top_k=None, top_p=None,
repetition_penalty=1.0, frequency_penalty=0.0, presence_penalty=0.0,
stop=None, seed=0):
g = torch.Generator().manual_seed(seed)
words = [start]
for _ in range(steps):
logits = next_logits(words[-1])
counts = torch.zeros(len(vocab))
for w in words:
counts[vocab.index(w)] += 1
seen = counts > 0
# repetition penalty (Hugging Face style): divide positive, multiply negative
logits[seen] = torch.where(logits[seen] > 0, logits[seen] / repetition_penalty,
logits[seen] * repetition_penalty)
# frequency and presence penalties (OpenAI style): subtract from the logits
logits -= frequency_penalty * counts + presence_penalty * seen
if temperature == 0: # greedy: always the single most likely word
nxt = int(logits.argmax())
else:
logits = logits / temperature
if top_k:
logits = top_k_filter(logits, top_k)
if top_p:
logits = top_p_filter(logits, top_p)
nxt = int(torch.multinomial(torch.softmax(logits, -1), 1, generator=g))
words.append(vocab[nxt])
if stop and vocab[nxt] == stop: # stop sequence: end and drop it
words.pop()
break
return " ".join(words)
if __name__ == "__main__":
probs = torch.softmax(next_logits("the"), -1)
top = probs.topk(4)
print("after 'the':", ", ".join(f"{vocab[i]} {p:.2f}" for p, i in zip(*top)))
for t in (0.5, 1.0, 2.0):
p = torch.softmax(next_logits("the") / t, -1)
print(f" temperature {t}: top word {p.max():.2f}, kept by top-p 0.9: "
f"{int((top_p_filter(next_logits('the') / t, 0.9) > -1e9).sum())} words")
print("greedy: ", generate("the"))
print("temperature 1.0: ", generate("the", temperature=1.0))
print("temperature 1.0, k=3:", generate("the", temperature=1.0, top_k=3))
print("greedy, repetition 2:", generate("the", repetition_penalty=2.0))
print("greedy, frequency 1: ", generate("the", frequency_penalty=1.0))
print("greedy, presence 1: ", generate("the", presence_penalty=1.0))
print("top-p 0.9, stop '.': ", generate("a", steps=20, temperature=1.0, top_p=0.9,
stop=".", seed=2))python decoding.pyafter 'the': dog 0.29, cat 0.29, mat 0.20, rug 0.10
temperature 0.5: top word 0.37, kept by top-p 0.9: 3 words
temperature 1.0: top word 0.29, kept by top-p 0.9: 5 words
temperature 2.0: top word 0.21, kept by top-p 0.9: 10 words
greedy: the cat ran to a bird on the cat ran to a bird
temperature 1.0: the rug . the park tree . the dog ran to the cat
temperature 1.0, k=3: the dog . the dog ran to the dog ran to the cat
greedy, repetition 2: the cat ran to a bird on the dog . the mat .
greedy, frequency 1: the cat ran to a bird on the dog . a tree .
greedy, presence 1: the cat ran to a bird on the dog . the mat .
top-p 0.9, stop '.': a bird sat on the dog saw the dogAfter "the", the model splits most of its probability between "dog" and "cat". Temperature 0.5 sharpens this (top word 0.37) and top-p 0.9 then needs only 3 words; at temperature 2.0 the distribution is so flat that 10 words are needed to reach 0.9. Greedy decoding falls into a loop: "the cat ran to a bird on the cat ran to a bird". In this bigram model each word fixes the next, so once a word comes back, the whole cycle comes back. A real model looks at the whole context, not just the last word, but once a repeated phrase dominates that context, greedy decoding tends to fall into the same kind of loop. Plain sampling at temperature 1.0 escapes the loop but sometimes picks a word from the tail that makes no sense, such as "the park tree"; top-k removes those choices. All three penalties break the loop by making "cat" less attractive the second time. The last line samples with top-p until the model produces ".", which is then cut. Real APIs differ in which controls they offer and in the exact formulas, so read the documentation of the one you use.
04. The KV cache and the cost of context
In a causal transformer, the keys and values of earlier tokens do not change when a new token is added, because each earlier position only ever looked backwards. Recomputing them at every step is therefore wasted work. The KV cache stores the keys and values of every layer as they are produced, so each new step computes the query, key and value of the new token only, and attends over the stored ones. Processing the prompt and filling the cache is called prefill; producing one token at a time afterwards is decoding. The script generates 20 tokens from one attention layer both ways.
"""Greedy generation with one causal attention layer, with and without a KV cache."""
import torch
import torch.nn.functional as F
from torch import nn
torch.manual_seed(0)
V, D = 50, 32
emb, pos = nn.Embedding(V, D), nn.Embedding(64, D)
Wq, Wk, Wv = nn.Linear(D, D), nn.Linear(D, D), nn.Linear(D, D)
head = nn.Linear(D, V)
computed = {"no cache": 0, "cache": 0} # how many key/value pairs were computed
def logits_full(ids): # recompute every position's keys and values each step
x = emb(ids) + pos(torch.arange(len(ids)))
computed["no cache"] += len(ids)
q, k, v = Wq(x), Wk(x), Wv(x)
return head(F.scaled_dot_product_attention(q[None], k[None], v[None],
is_causal=True)[0, -1])
def logits_cached(new_id, t, cache): # only the new token's q, k and v
x = emb(new_id) + pos(torch.tensor(t))
computed["cache"] += 1
cache["k"].append(Wk(x))
cache["v"].append(Wv(x))
k, v = torch.stack(cache["k"]), torch.stack(cache["v"])
weights = torch.softmax(k @ Wq(x) / D ** 0.5, dim=0) # this query sees all past
return head(weights @ v)
with torch.no_grad():
prompt = [7, 3, 12]
a = list(prompt)
for _ in range(20):
a.append(int(logits_full(torch.tensor(a)).argmax()))
cache = {"k": [], "v": []}
b = list(prompt)
for t, tok in enumerate(prompt[:-1]): # prefill: cache the prompt's keys and values
logits_cached(torch.tensor(tok), t, cache)
for t in range(len(prompt) - 1, len(prompt) + 19):
b.append(int(logits_cached(torch.tensor(b[t]), t, cache).argmax()))
print("same tokens with and without the cache:", a == b)
print("key/value pairs computed:", computed)python kv_cache.pysame tokens with and without the cache: True
key/value pairs computed: {'no cache': 250, 'cache': 22}Both versions produce the same tokens. Without the cache, the loop computed 250 key/value pairs, 3 + 4 + … + 22, a number that grows with the square of the output length; with it, 22, one per token. The attention for each new token still reads every cached key, so the cost of one step grows with the length of the context. What the cache costs is memory, and the next script does the arithmetic for two published model shapes.
"""KV-cache bytes per token: 2 (K and V) x layers x KV heads x head size x 2 bytes."""
configs = { # published shapes of two open models, cache stored in 16-bit numbers
"Llama-2-7B (32 KV heads)": dict(layers=32, kv_heads=32, head_dim=128),
"Llama-3-8B (8 KV heads) ": dict(layers=32, kv_heads=8, head_dim=128),
}
for name, c in configs.items():
per_token = 2 * c["layers"] * c["kv_heads"] * c["head_dim"] * 2 # bytes
print(f"{name}: {per_token / 2**10:5.0f} KiB per token")
for context, batch in ((2_048, 1), (4_096, 1), (4_096, 16)):
gib = per_token * context * batch / 2**30
print(f" {context:6,} tokens x {batch:2d} sequences: {gib:6.1f} GiB")python cache_memory.pyLlama-2-7B (32 KV heads): 512 KiB per token
2,048 tokens x 1 sequences: 1.0 GiB
4,096 tokens x 1 sequences: 2.0 GiB
4,096 tokens x 16 sequences: 32.0 GiB
Llama-3-8B (8 KV heads) : 128 KiB per token
2,048 tokens x 1 sequences: 0.2 GiB
4,096 tokens x 1 sequences: 0.5 GiB
4,096 tokens x 16 sequences: 8.0 GiBA model with Llama 2 7B's shape stores 512 KiB of keys and values per token, so one 4,096-token conversation needs 2 GiB and sixteen of them 32 GiB, on top of the model weights. The cache grows linearly with context length and with the number of sequences served at once, which is why long contexts and many concurrent users are what limit a serving GPU. Grouped-query attention (GQA), used by Llama 3 8B, lets several query heads share one key/value head: with 8 instead of 32 KV heads, the cache is four times smaller for the same number of query heads. Serving systems add further tricks, such as storing the cache in fixed-size pages and quantising it, but the arithmetic above is the starting point for sizing any deployment.
05. Check your understanding
06. Apply it
For the character-level decoder in your practice project:
- Write a
generatefunction with temperature, top-k, top-p and a stop string, reusing the filters fromdecoding.py. - Add a KV cache to your attention layers and check, as in
kv_cache.py, that greedy outputs are identical with and without it. - Measure tokens per second with and without the cache for 50, 200 and 800 generated tokens, and compute the cache size per token of your model from its shape.
07. Review prompt
Without looking back, explain how BPE learns its merges and how it encodes a new word; describe what temperature, top-k and top-p do to the next-token distribution; distinguish the repetition, frequency and presence penalties; explain how a stop sequence ends generation; and describe what the KV cache stores, what it saves, what it costs and how context length, batch size and grouped-query attention change that cost.
References
- Sennrich et al. (2016): Neural Machine Translation of Rare Words with Subword Units
- Holtzman et al. (2020): The Curious Case of Neural Text Degeneration
- Hugging Face Transformers docs: GenerationConfig (top_k, top_p, repetition_penalty, stop_strings)
- Ainslie et al. (2023): GQA, Training Generalized Multi-Query Transformer Models
- Hugging Face LLM Course: Tokenizers
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.