Deep Learning
GPT Architecture - How Large Language Models Generate Text
Explore the GPT architecture and understand how large language models generate coherent text.
- Autoregressive generation - predict next token sequentially
- Decoder-only architecture - simple but powerful design
- Scaling laws - performance improves with more parameters
Language is the house of being.
GPT Architecture — Complete Guide
GPT (Generative Pre-trained Transformer) is a decoder-only transformer trained to predict the next token. It powers ChatGPT, GPT-4, and modern LLMs.
Decoder-Only Architecture
GPT Decoder Block Architecture
How the GPT decoder block works: This is the fundamental unit repeated N times in every GPT model. Input embeddings (token + positional) enter from the top and flow through two sub-layers. First, Masked Multi-Head Self-Attention (blue) computes context-aware representations — the "masked" part means each token can only attend to previous tokens, preventing information leakage from future tokens. The golden dashed line on the left is a residual connection that adds the original input to the attention output, then Layer Normalization stabilizes training. Second, the Feed-Forward Network (purple) processes each position independently through two linear layers with GELU activation, expanding to 4× d_model dimensions then projecting back. This FFN acts as a "knowledge store" — the attention layer gathers context, and the FFN makes decisions based on that context. The pattern (Attention → Add+Norm → FFN → Add+Norm) repeats for every block, with each layer learning increasingly abstract language patterns.
Autoregressive Generation
Autoregressive Text Generation Process
How autoregressive generation works: This diagram shows the step-by-step process of text generation. At each step, the model receives ALL previously generated tokens as input and predicts the next token. Step 1: given "The", the model predicts "cat" with P=0.82. Step 2: given "The, cat", it predicts "sat" with P=0.91 — notice the probability increased because the model now has more context. Step 3: given "The, cat, sat", it predicts "on" with P=0.76. The key insight: each prediction conditions on the ENTIRE history, not just the previous token. The model builds up the sentence one token at a time, with each new token becoming part of the input for the next prediction. This sequential process continues until an end-of-sequence token is generated or a maximum length is reached. The probabilities reflect the model's confidence — higher probability means the model is more certain about that token choice.
Choosing the Next Token
The probabilities in the diagram are only the raw material. Turning them into the token that actually gets appended is a separate decision, and the two knobs you will meet everywhere are temperature and top-k. Temperature divides the logits before the softmax: below one it sharpens the distribution toward the most likely continuations, above one it flattens the distribution so that unlikely words get a share of the probability mass. Top-k discards everything outside the k most likely candidates first, which stops a long tail of near-impossible tokens from collecting the mass the softmax still assigns them.
import torch
@torch.no_grad()
def generate(model, idx, max_new_tokens, temperature=1.0, top_k=None):
model.eval()
for _ in range(max_new_tokens):
logits = model(idx)[:, -1, :] / max(temperature, 1e-6)
if top_k is not None:
cutoff = torch.topk(logits, top_k).values[:, -1, None]
logits = logits.masked_fill(logits < cutoff, float("-inf"))
probs = torch.softmax(logits, dim=-1)
next_id = torch.multinomial(probs, num_samples=1)
idx = torch.cat([idx, next_id], dim=1) # feed it straight back in
return idx
Greedy decoding is the special case where temperature is driven to zero and only the argmax survives: it is deterministic and often repetitive, which is why sampling with a modest temperature is preferred for open-ended writing while greedy or beam search remains common for tasks where a single correct string exists.
Causal Attention Mask
The causal mask ensures autoregressive behavior by preventing tokens from attending to future positions:
Where the mask matrix is:
Building the mask is a single call to an upper-triangular helper, and it is worth doing explicitly once so the arithmetic in the formula stops being abstract. The mask is added to the scaled scores rather than multiplied, because the masked entries hold negative infinity and an addition sends them to zero after the softmax — a multiplication would leave them as NaN.
import torch
def causal_mask(n, device="cpu"):
return torch.triu(torch.full((n, n), float("-inf")), diagonal=1)
print(causal_mask(4))
# tensor([[ 0., -inf, -inf, -inf],
# [ 0., 0., -inf, -inf],
# [ 0., 0., 0., -inf],
# [ 0., 0., 0., 0.]])
q, k = torch.randn(2, 4, 8), torch.randn(2, 4, 8) # (batch, seq, d_k)
scores = q @ k.transpose(-2, -1) / q.size(-1) ** 0.5
scores = scores + causal_mask(4)
weights = torch.softmax(scores, dim=-1)
print(weights[0].round(2))
# each row sums to 1.0 and everything right of the diagonal is 0.0
Causal Attention Mask Visualization
How the causal mask enforces autoregression: This lower-triangular matrix visualizes which tokens can attend to which other tokens. Green cells (✓) mean the token CAN attend to that position; red cells (✗) mean attention is BLOCKED. Row 1 (x₁) can only attend to itself — it has no previous context. Row 2 (x₂) can attend to x₁ and itself, but not x₃ or x₄. Row 3 attends to x₁, x₂, x₃. Row 4 attends to all four. This creates the autoregressive property: when predicting token 4, the model can only use information from tokens 1, 2, 3 — never from token 5 or later. The mask is implemented by adding -∞ to blocked positions before softmax, making their attention weights effectively zero. This is what makes GPT a "decoder-only" model — it can only look left, never right.
Scaling Laws
GPT Model Evolution and Scaling
How GPT models scale with resources: The timeline shows the explosive growth of GPT models. GPT-1 (2018) had 117M parameters trained on 5GB of book text using 8 GPUs for 5 days. GPT-2 (2019) jumped to 1.5B parameters on 40GB of web text. GPT-3 (2020) reached 175B parameters trained on 300B tokens — requiring ~3.14×10²³ FLOPs (equivalent to running a supercomputer for months). GPT-4 (2023) is estimated at ~1.8T parameters using a Mixture of Experts architecture. The scaling curve at the bottom shows the key insight: loss decreases as a power law with compute (Loss ∝ C^(-γ)). This means performance improves predictably with more parameters, data, and compute — you can forecast how much resources you need for a target performance level. The formula at the top (Loss ∝ N^(-α) + D^(-β) + C^(-γ)) shows that scaling any one factor alone has diminishing returns — you need to scale all three together.
Training Pipeline
GPT Training Pipeline
How GPT is trained end-to-end: This four-stage pipeline shows how a raw language model becomes ChatGPT. Stage 1 (Data Collection): Gather massive text corpora — Common Crawl (web pages), Wikipedia, books, and code from GitHub — totaling 13+ trillion tokens. Stage 2 (Pre-training): Train the model to predict the next token using cross-entropy loss with the AdamW optimizer. This takes 3-6 months on thousands of GPUs and teaches the model language structure, facts, and reasoning. Stage 3 (Supervised Fine-tuning): Train on ~100K human-written instruction-response pairs to teach the model to follow instructions. Stage 4 (RLHF): Use human feedback to train a reward model, then optimize the policy using PPO (Proximal Policy Optimization) with a KL-divergence penalty to stay close to the pre-trained model. The formulas at the bottom show the mathematical objectives: pre-training minimizes negative log-likelihood, while RLHF maximizes reward minus a penalty for deviating too far from the original model.
Common Mistakes & How to Avoid Them
Common Mistakes
Running generation with the model still in training mode, so dropout noise is sampled at inference and identical prompts give different answers
Fix: Call model.eval and wrap generation in no_grad, then check that repeating the same prompt twice produces the same first token
Applying temperature after the softmax instead of to the logits, which distorts rather than sharpens the distribution
Fix: Divide the logits by temperature first and only then run softmax; verify that a temperature below one makes the top token more likely
Forgetting the causal mask during training so the model learns to copy the next token and appears brilliant until the first real generation
Fix: Add the upper-triangular mask to the scores in every layer and unit-test that all attention weight above the diagonal is exactly zero
Key Takeaways
What to Learn Next
-> BERT Compare with bidirectional models.
-> Transformers Master the underlying architecture.
-> What are LLMs Learn the basics of large language models.
-> LLM Architecture Deep Dive Explore LLM internals in detail.
-> Pre-training Language Models Understand how models learn from text.
-> RLHF and Alignment Learn how to align models with human values.