AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
✎Large Language Models
  1. Tokenization: how text becomes numbers
  2. How LLMs work: next-token prediction at scale
  3. Decoding: greedy, beam search, temperature, top-k, top-p
  4. Scaling laws: parameters, data and compute
  5. Fine-tuning & alignment: SFT, RLHF, DPO, LoRA/QLoRA
  6. Prompting: zero-shot, few-shot, chain-of-thought, structured output
  7. Retrieval-Augmented Generation (RAG)
  8. Agents & tool use: ReAct, function calling, MCP
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Large Language Models

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.

Intermediate~22 min·6 references
Key terms
Large language model (LLM)Language modelNext-token predictionPretrainingLogitsPerplexityGPT (Generative Pre-trained Transformer)BERTContext windowKV cache

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.

≈
Analogy: the ultimate “continue the sentence” game
Imagine a student who has read a whole library and plays one game all day: cover the next word, guess it, check, adjust. To get good at guessing the next word of a physics textbook, a court ruling, or Python code, the student is forced to absorb grammar, facts, style, and patterns of reasoning. Nobody teaches those skills explicitly — they are side effects of becoming an excellent guesser.

The training objective

P(x₁, …, x_T) = Π_t P(x_t | x₁, …, x_{t−1}) L(θ) = −(1/T) Σ_t log P_θ(x_t | x_<t)
The chain rule turns a sequence probability into a product of next-token probabilities; training minimizes the average cross-entropy.
In words: The probability of a whole text is the product of the probabilities of each token given the tokens before it. Training maximizes that, which is the same as minimizing the average negative log-probability of each true next token — the Cross-entropy (log loss) loss.
Symbols(hover a symbol in the formula)
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
3 tokens; the model gives the true tokens probabilities 0.5, 0.2, 0.8 P(sequence) = 0.5 · 0.2 · 0.8 = 0.08 −log of each: 0.6931, 1.6094, 0.2231 L = (0.6931 + 1.6094 + 0.2231) / 3 = 0.8419 nats per token The unlikely middle token (0.2) contributes most of the loss.

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 = exp(L) = exp(−(1/T) Σ_t log P_θ(x_t | x_<t))
In words: Perplexity undoes the log of the average loss. It reads as “the model is as unsure as if it had to choose uniformly among this many tokens at every step”. Lower is better; 1 would be perfect certainty.
Symbols(hover a symbol in the formula)
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
Using the previous example, L = 0.8419 perplexity = exp(0.8419) = 2.32 Same result directly: 0.08^(−1/3) = 2.32 → like choosing among ~2.3 equally likely tokens. A model that always guesses uniformly over 50,000 tokens has perplexity 50,000.

One forward pass, from ids to probabilities

  1. Tokenize the text into ids, e.g. [464, 3139, 286, …].
  2. 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).
  3. 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].
  4. 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.
  5. 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 = h_T · W_out ∈ ℝ^V p_i = e^(z_i) / Σ_j e^(z_j)
Logits z and the softmax over a vocabulary of size V.
In words: The last position's hidden vector is multiplied by the output matrix to give one raw score per vocabulary token. Softmax exponentiates the scores (making them positive) and divides by their sum (making them add up to 1).
Symbols(hover a symbol in the formula)
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
Tiny vocabulary V = 3, logits z = [2, 1, 0] e^2 = 7.389, e^1 = 2.718, e^0 = 1 → sum = 11.107 p = [7.389, 2.718, 1] / 11.107 = [0.665, 0.245, 0.090] GPT-2: h_T has 768 numbers, W_out is 768 × 50,257 → 50,257 logits.
Loading interactive…
The same forward pass as a diagram, with real GPT-2 small numbers. Press Walk through to follow the token ids up through 12 Pre-LN blocks to the next-token probabilities, then around the loop. Tap the KV cache and the LM head, and notice that every block only adds to the residual stream.

Three transformer families

FamilyAttentionPretraining taskTypical use
Encoder-only (BERT, RoBERTa)Bidirectional — every token sees left and rightMasked language modeling: hide ~15% of tokens, predict themClassification, NER, embeddings for search
Decoder-only (GPT, Llama, Mistral, Qwen)Causal — each token sees only the pastNext-token predictionChat, generation, code, agents
Encoder-decoder (original Transformer, T5, BART)Encoder bidirectional + decoder causal with cross-attentionSpan corruption / denoising, translationTranslation, 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].

Loading interactive…
BERT-base for comparison with the GPT diagram above. Walk through it and notice the differences: three embeddings (token, segment, position) instead of two, no causal mask in self-attention, LayerNorm after each residual (Post-LN), and two pretraining heads — MLM fills in [MASK] tokens, NSP reads the [CLS] vector — instead of a next-token loop.

From base model to assistant

  1. 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.
  2. Supervised fine-tuning / [[instruction-tuning]]: tens of thousands to millions of (instruction, good answer) pairs teach the format of being helpful.
  3. 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 = 2 × n_layers × n_kv_heads × d_head × seq_len × batch × bytes_per_value
Example (Llama-2-7B-like: 32 layers, 32 KV heads, d_head 128, fp16): 2×32×32×128×2 B ≈ 0.5 MB per token → ~2 GB for one 4,096-token sequence. Grouped-query attention (fewer KV heads) shrinks this several-fold.
In words: For every token in every sequence, each layer stores one key and one value vector per KV head. Multiply all the counts together and by the size of one number to get the memory the cache needs.
Symbols(hover a symbol in the formula)
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
Llama-2-7B-like, fp16: 2 × 32 × 32 × 128 × 2 B = 524,288 B ≈ 0.5 MB per token × 4,096 tokens × batch 1 = 2,147,483,648 B ≈ 2 GB Batch 16 → ≈ 32 GB: more than the 14 GB the weights need. With 8 KV heads instead of 32 (grouped-query attention): ÷ 4 → ≈ 0.5 GB per sequence.
knobContext window (max sequence length)
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).
knobModel size (number of parameters)
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).
python
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))
Look inside: next-token probabilities, loss and perplexity with GPT-2.
python
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]))
A greedy generation loop that reuses the KV cache (what model.generate does for you).
!
Common misconceptions
(1) Base vs chat model: a base model continues your text — ask it a question and it may answer with more questions. Use an instruction/chat model (and its chat template) for assistant behaviour. (2) It is not a database: the model produces *plausible* continuations; when knowledge is missing it still produces fluent text, which is the root of Hallucination. (3) Knowledge cutoff: nothing after the training data exists for the model unless you put it in the context. (4) Silent truncation: input beyond the context window is cut off by your client or framework, often without an error.
▸Go deeper: the causal mask and training compute
Attention(Q, K, V) = softmax(QKᵀ/√d_k + M) V, M_ij = 0 if j ≤ i, −∞ if j > i
The mask M sets future positions to −∞ so softmax gives them zero weight.
In words: Ordinary scaled dot-product attention, plus a mask matrix added to the scores before the softmax. Adding −∞ to a score makes e^(score) = 0, so a token gets exactly zero weight on every later token — it can only look at itself and the past.
Symbols(hover a symbol in the formula)
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
Token 2 of 3, raw scaled scores [1.0, 2.0, 0.5] Mask row: [0, 0, −∞] → [1.0, 2.0, −∞] e^1 = 2.718, e^2 = 7.389, e^(−∞) = 0 → sum 10.107 Weights = [0.269, 0.731, 0] → token 3 (the future) is invisible.

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

1.
What is the pretraining objective of a GPT-style (decoder-only) model?
2.
A model’s average loss on a test set is ln(20) ≈ 3.0 nats per token. What is its perplexity?
3.
What does the KV cache store, and why does it help?
4.
You double the sequence length served by a model. What happens to the KV-cache memory per sequence?
5.
For which task is an encoder-only model like BERT the most natural fit?
Score: 0/5

References

  1. [1]
    Attention Is All You Need
    PaperVaswani et al.2017arxiv.org
  2. [2]
    Language Models are Few-Shot Learners (GPT-3)
    PaperBrown et al.2020arxiv.org
  3. [3]
    BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
    PaperDevlin et al.2019arxiv.org
  4. [4]
    nanoGPT — the simplest, fastest repository for training/finetuning medium-sized GPTs
    CourseAndrej Karpathy2023github.com
  5. [5]
    Efficiently Scaling Transformer Inference
    PaperPope et al.2022arxiv.org
    Prefill vs decode, KV-cache memory and inference trade-offs.
  6. [6]
    Transformers documentation — Generation with LLMs
    DocsHugging Facehuggingface.co
← Previous
Tokenization: how text becomes numbers
Next →
Decoding: greedy, beam search, temperature, top-k, top-p