How LLMs work: next-token prediction at scale
Pretraining on trillions of tokens with one simple objective, the forward pass from token ids to probabilities, decoder-only GPT vs encoder-only BERT, the context window, and the KV cache that makes generation fast.
A Language model assigns probabilities to sequences of tokens. A large language model is the same idea scaled up: a Transformer with billions of parameters, trained on trillions of tokens. Chatbots, code assistants, translators and agents are all built on top of one deceptively simple task: predict the next token.
The training objective
- P(x₁, …, x_T)
- probability of the whole sequence of T tokens
- Π_t
- product over all positions t = 1 … T
- P(x_t | x₁, …, x_{t−1})
- probability of token t given all earlier tokens (“|” reads “given”)
- L(θ)
- the loss as a function of the model parameters θ
- −(1/T) Σ_t
- minus the average over all T positions
- log
- natural logarithm
- P_θ(x_t | x_<t)
- the model's predicted probability of the true token x_t; x_<t is shorthand for all tokens before t
▸Worked example
This is self-supervised: the labels are the text itself, so no human annotation is needed. A single 4,096-token document gives 4,095 training examples at once, because a causal mask lets every position predict its successor in parallel. This stage is called Pretraining, and its output is a base model — a powerful text continuer, not yet a helpful assistant. The loss is the Cross-entropy (log loss) you met earlier; its exponent is the Perplexity: a perplexity of 10 means the model is, on average, as uncertain as if it were choosing uniformly among 10 tokens.
- perplexity
- Perplexity: the effective number of choices per token
- exp
- exponential function e^(·), the inverse of the natural log
- L
- average cross-entropy loss per token (in nats)
- P_θ(x_t | x_<t)
- the model's probability for the true token at position t
- −(1/T) Σ_t
- minus the average over the T positions
▸Worked example
One forward pass, from ids to probabilities
- Tokenize the text into ids, e.g.
[464, 3139, 286, …]. - Embed: look up a vector (dimension d, e.g. 4,096) for each id and add position information (learned positions, or rotary embeddings RoPE in most modern LLMs).
- N transformer blocks (e.g. 32–128): masked Multi-head attention lets each token read earlier tokens; an MLP transforms each position; residual connections and Layer normalization keep training stable[1].
- LM head: the final hidden vector of the last position is multiplied by a d × V matrix, giving one score — a logit — per vocabulary entry.
- Softmax turns logits into a probability distribution over the next token. A decoding strategy then picks one token (next lesson), it is appended, and the loop repeats.
- z
- Logits: vector of V raw scores
- h_T
- final hidden vector at the last position T (size d)
- W_out
- output (LM head) matrix, d × V; often tied to the embedding matrix
- ℝ^V
- a vector of V real numbers (V = Vocabulary size)
- p_i
- probability that the next token is token i
- e^(z_i)
- e ≈ 2.718 raised to the logit of token i
- Σ_j e^(z_j)
- sum of e^(logit) over all V tokens (the normalizer)
▸Worked example
Three transformer families
| Family | Attention | Pretraining task | Typical use |
|---|---|---|---|
| Encoder-only (BERT, RoBERTa) | Bidirectional — every token sees left and right | Masked language modeling: hide ~15% of tokens, predict them | Classification, NER, embeddings for search |
| Decoder-only (GPT, Llama, Mistral, Qwen) | Causal — each token sees only the past | Next-token prediction | Chat, generation, code, agents |
| Encoder-decoder (original Transformer, T5, BART) | Encoder bidirectional + decoder causal with cross-attention | Span corruption / denoising, translation | Translation, summarization |
BERT’s bidirectional view makes excellent representations for understanding tasks, but it cannot naturally generate text left-to-right[3]. Decoder-only models won the generation race because the objective is simple, every token is a training signal, generation is native, and the approach keeps improving with scale. GPT-3 showed that a big enough decoder can even learn new tasks from examples placed in the prompt — In-context learning — with no weight updates[2].
From base model to assistant
- Pretraining: trillions of tokens of web pages, books, code and papers; weeks to months on thousands of GPUs. Result: a base model that continues text.
- Supervised fine-tuning / [[instruction-tuning]]: tens of thousands to millions of (instruction, good answer) pairs teach the format of being helpful.
- Preference tuning (RLHF, DPO): humans or AI judges compare answers, and the model is pushed toward the preferred ones. Covered in the fine-tuning lesson.
The context window
The Context window is the maximum number of tokens the model can process at once — prompt plus generated output. It grew from 512 tokens (BERT) and 1,024 (GPT-2) to 2,048 (GPT-3) and now 128k to over a million tokens in frontier models. Longer windows are expensive: plain self-attention compares every token with every other token (O(n²) compute), the KV cache grows linearly with length, and models often use information in the middle of a long context less reliably than at the beginning or end.
Generation and the KV cache
Generation is a loop: run the model, pick a token, append it, run again. Naively, step t recomputes keys and values for all t previous tokens in every layer — wasteful, because those never change (the causal mask means the past never looks at the future). The KV cache stores each layer’s keys and values; each new step computes q, k, v only for the newest token and attends over the cache. Inference therefore has two phases: prefill (the whole prompt processed in parallel, compute-bound) and decode (one token at a time, usually limited by memory bandwidth because the weights and cache must be read for every token)[5].
- KV bytes
- memory used by the KV cache
- 2
- one key and one value
- n_layers
- number of transformer layers
- n_kv_heads
- number of key/value heads (fewer than query heads with grouped-query attention)
- d_head
- dimension of one head (e.g. 128)
- seq_len
- number of tokens cached (prompt + generated so far)
- batch
- number of sequences processed together
- bytes_per_value
- 2 for fp16/bf16, 1 for 8-bit, 4 for fp32
▸Worked example
- What it is
- The maximum number of tokens (input + output) the model can attend to. Fixed by the model’s training, though you choose how much of it to use.
- ↑ If you increase it
- More documents, history and examples fit; but cost and latency grow (prefill compute, KV-cache memory), and recall of details buried in the middle may degrade.
- ↓ If you decrease it
- Faster and cheaper, but older conversation turns or document parts must be dropped or summarized — the model simply never sees them.
- Typical values
- 512 (BERT), 2k–8k (older open models), 128k (many current models), up to ~1M+ (some frontier models).
- What it is
- How many weights the network has. Determines memory (≈ 2 bytes per parameter in fp16/bf16) and compute per token (≈ 2 FLOPs per parameter for a forward pass).
- ↑ If you increase it
- Lower loss and better knowledge/reasoning (see scaling laws), but a 70B model needs ~140 GB in bf16 and is much slower per token.
- ↓ If you decrease it
- Runs on a laptop or phone (a 1–3B model, especially quantized), much cheaper, but less knowledge and weaker multi-step reasoning.
- Typical values
- 0.5–3B (on-device), 7–14B (single GPU), 70B+ (multi-GPU servers).
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2").eval()
ids = tok("The capital of France is", return_tensors="pt").input_ids
with torch.no_grad():
out = model(ids, labels=ids) # labels -> shifted next-token cross-entropy
print("loss", out.loss.item(), "perplexity", torch.exp(out.loss).item())
logits = out.logits[0, -1] # scores for the NEXT token, shape [50257]
probs = logits.softmax(-1)
top = torch.topk(probs, 5)
for p, i in zip(top.values, top.indices):
print(repr(tok.decode(int(i))), round(p.item(), 3))generated = ids
x, past = ids, None
for _ in range(10):
with torch.no_grad():
out = model(x, past_key_values=past, use_cache=True)
past = out.past_key_values # cached keys/values of all layers
next_id = out.logits[:, -1].argmax(-1, keepdim=True)
generated = torch.cat([generated, next_id], dim=-1)
x = next_id # feed ONLY the new token
print(tok.decode(generated[0]))model.generate does for you).▸Go deeper: the causal mask and training compute
- Q
- queries, one row per token
- K
- keys
- V
- values
- QKᵀ/√d_k
- scaled query–key scores (n × n)
- M
- the causal mask matrix (n × n)
- M_ij
- mask entry for query position i looking at key position j
- −∞
- minus infinity (in practice a very large negative number); softmax turns it into 0
- softmax
- Softmax over each row
▸Worked example
Training a decoder costs roughly 6 FLOPs per parameter per token (2 for the forward pass, 4 for the backward pass). GPT-3 (175B parameters, ~300B tokens) therefore needed about 6 × 1.75·10¹¹ × 3·10¹¹ ≈ 3·10²³ FLOPs. To see every piece of this pipeline in a few hundred lines of PyTorch, follow Karpathy’s nanoGPT and his “Let’s build GPT” walkthrough[4]; for production usage, the Hugging Face generation guide is the reference[6].
Quiz
References
- [1]Attention Is All You NeedPaperVaswani et al.2017arxiv.org
- [2]Language Models are Few-Shot Learners (GPT-3)PaperBrown et al.2020arxiv.org
- [3]BERT: Pre-training of Deep Bidirectional Transformers for Language UnderstandingPaperDevlin et al.2019arxiv.org
- [4]nanoGPT — the simplest, fastest repository for training/finetuning medium-sized GPTsCourseAndrej Karpathy2023github.com
- [5]Efficiently Scaling Transformer InferencePaperPope et al.2022arxiv.orgPrefill vs decode, KV-cache memory and inference trade-offs.
- [6]Transformers documentation — Generation with LLMsDocsHugging Facehuggingface.co