Level 3 In-Depth AI · Transformers and Language Models
GPT and Decoder-Only Models
GPT-style models are stacks of causal Transformer blocks trained on one task, predicting the next token, at enormous scale. From GPT-1 to today's open and closed models, scaling this recipe produced in-context learning and the general-purpose assistants we use now.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1 hour to read, an hour to play with a model
- Builds on
- 31 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 31 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
Read them roughly in this order. See it on the concept map →
Why it matters
GPT stands for Generative Pre-trained Transformer. It names OpenAI's series of models, but the design it describes, a decoder-only model, is now the architecture of almost every large language model: ChatGPT, Claude, Gemini, Llama, Mistral, Qwen and DeepSeek. When people say "LLM" they nearly always mean one of these.
The recipe fits in a sentence: take a stack of The Transformer blocks with causal Self-Attention and Multi-Head Attention, and train it to predict the next token on as much text as you can find. Nothing in that recipe mentions translation, arithmetic, coding or answering questions. Yet as these models grew from 117 million parameters in 2018 to hundreds of billions a few years later, they started doing all of those things, often from nothing more than a few examples in the prompt.
This chapter explains what a decoder-only model is, how it generates text, how the GPT line evolved, and the two ideas that made it famous: in-context learning and emergent abilities. It sets up Build a GPT from Scratch, where you train one yourself.
The intuition
Imagine the world's most well-read autocomplete. It has read a large fraction of the public internet, millions of books, all of Wikipedia and most public code, and it has one skill: given some text, guess what comes next.
Now give it the start of a document:
Q: What is the capital of Japan? A:
What text usually follows that, across everything it has read? "Tokyo". Give it the start of a Python function with a docstring, and the likely continuation is the function's body. Give it "English: cheese, French:" and the likely continuation is "fromage". The model isn't switching between a translation mode and a coding mode. It is always doing the same thing, continuing the document, and the prompt decides what kind of document it is in.
That is both the power and the strangeness of GPT-style models. Every task has to be phrased as "the beginning of a text whose natural continuation is the answer".
Key idea A GPT is a causal Transformer trained only to predict the next token. It generates text by repeatedly predicting a token, appending it and predicting again. Any task that can be written as "continue this text" is, in principle, within reach.
How it works
The architecture
A decoder-only model is the The Transformer block stack from the previous chapters, with every attention layer causally masked so that position only sees positions to . There is no encoder and no cross-attention. Token and position information go in at the bottom; at the top, a linear layer and softmax produce a probability for every token in the vocabulary, at every position.
During training, a sequence of tokens gives predictions in one forward pass: token 2 from token 1, token 3 from tokens 1 and 2, and so on. The loss is the average cross-entropy of all of them (Language Modeling and Next-Token Prediction). The causal mask is what makes this honest: no position can see the answer it is asked to predict.
Generation, one token at a time
During generation (also called inference or sampling), the model runs in a loop:
- Feed in the prompt's token ids.
- Take the output distribution at the last position: .
- Choose a token from it: the most likely one, or a random draw (Decoding: Temperature, Top-k and Top-p).
- Append it to the input and go back to step 2, until an end-of-text token or a length limit.
This is autoregressive generation: each output becomes part of the next input.
Two consequences follow. First, generation is sequential: 500 tokens of output means 500 passes through the network, which is why long answers stream out word by word. Caching the keys and values of earlier tokens means each pass only has to process the newest token (The KV Cache and Fast Inference). Second, the model can't go back. Once it has committed to a token, everything after must be consistent with it, which is one route to confident errors (Hallucinations).
Base models and assistants
A model trained only on next-token prediction is called a base model (or pretrained model). It continues documents; it doesn't follow instructions. Ask a base model "What is the capital of France?" and it may answer, or it may continue with three more quiz questions, because that's what often follows such a line on the web. The GPT-2 example in the code section below shows this clearly.
The assistants people use are base models with further training: instruction tuning on example conversations (Instruction Tuning and Chat Models) and preference training such as RLHF and Preference Optimization. The architecture doesn't change; the behaviour does. GPT-style models are also called foundation models because one pretrained base can be adapted to many uses.
The GPT line
- GPT-1 (2018): 117 million parameters, 12 blocks, trained on about 7,000 unpublished books. Its point: pretrain a Transformer decoder on unlabelled text, then fine-tune it separately for each task. It beat specialised models on most of the benchmarks it was tested on.
- GPT-2 (2019): 1.5 billion parameters, trained on WebText, about 40 GB of text from web pages linked from Reddit. Without any fine-tuning, it could do some reading comprehension, summarisation and translation when prompted the right way (zero-shot). OpenAI initially withheld the full model over misuse concerns and released it in stages through 2019.
- GPT-3 (2020): 175 billion parameters, 96 blocks, trained on about 300 billion tokens. Its paper, Language Models are Few-Shot Learners, showed in-context learning at scale.
- InstructGPT and ChatGPT (2022): GPT-3-class models tuned to follow instructions with human feedback. ChatGPT, released on 30 November 2022, made LLMs a mass-market product.
- GPT-4 (2023): much more capable, accepts images as input. Its technical report deliberately gives no details of size, architecture or training data. Most frontier labs now publish little about their models.
Open-weights models
Alongside the closed models, a fast-moving ecosystem of open-weights models, whose trained parameters anyone can download, grew from 2023. Meta's LLaMA (February 2023, 7 to 65 billion parameters) showed that smaller models trained on more data (1 to 1.4 trillion tokens) could match much bigger ones. Its successors went up to Llama 3.1's 405 billion parameters trained on about 15 trillion tokens (2024). Mistral, Qwen (Alibaba), Gemma (Google) and DeepSeek followed. DeepSeek-V3 (December 2024) is a Mixture of Experts model with 671 billion parameters, of which 37 billion are used per token. Open models can be run on your own hardware (Running Models Locally) and fine-tuned (Fine-Tuning, LoRA and Parameter-Efficient Fine-Tuning).
Architecturally, these are all GPT-style decoders with the modern refinements described in The Transformer: pre-norm RMSNorm, SwiGLU feed-forward layers, RoPE positions and grouped-query attention.
In-context learning
GPT-3's headline result was that a large enough model can learn a task from examples in the prompt, with no change to its weights. This is in-context learning, and prompting a model with a handful of worked examples is few-shot prompting:
France: Paris
Japan: Tokyo
Italy: Rome
Germany:
The model infers the pattern ("country, then its capital") and continues it. Zero examples is zero-shot, one is one-shot. Larger models get much more out of the examples than small ones. The code below shows GPT-2 small, with only 124 million parameters, picking up the format (it predicts city names) but not reliably the right fact (it prefers Frankfurt to Berlin).
How a fixed network "learns" inside a single forward pass is still being researched. One concrete mechanism is the induction head, a pair of attention heads that finds an earlier place in the context where the current token appeared and copies what followed it. In-context learning is the foundation of Prompt Engineering and Chain-of-Thought and Reasoning Prompts prompting.
Emergent abilities, and a caveat
As models grew, some capabilities seemed to switch on suddenly. Multi-digit arithmetic or certain reasoning benchmarks stayed near chance for small models and then jumped at a certain scale. A 2022 paper catalogued many such emergent abilities. A 2023 paper by Schaeffer, Miranda and Koyejo argued that much of this suddenness comes from the measurement: with all-or-nothing metrics such as exact match, steady underlying improvement can look like a jump, while smoother metrics show gradual gains. Both things seem true. The overall loss improves smoothly and predictably with scale (Scaling Laws), but some specific skills that people care about can appear fairly abruptly. Nobody can yet predict reliably which skills a model twice as large will have.
In code
GPT-2 small is a real GPT, small enough for a laptop. With Hugging Face transformers (The Hugging Face Ecosystem; the first run downloads about 500 MB), we can look at its next-token distribution and run the generation loop by hand:
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2").eval() # 124M parameters
print(sum(p.numel() for p in model.parameters()))
ids = tok("The capital of France is", return_tensors="pt").input_ids
with torch.no_grad():
logits = model(ids).logits # (1, T, 50257): a prediction at every position
probs = logits[0, -1].softmax(-1) # distribution for the NEXT token
top = probs.topk(5)
for p, i in zip(top.values, top.indices):
print(f"{p:.3f} {tok.decode(i)!r}")
# the generation loop, by hand: pick the most likely token, append, repeat
for _ in range(12):
with torch.no_grad():
next_id = model(ids).logits[0, -1].argmax()
ids = torch.cat([ids, next_id.view(1, 1)], dim=1)
print(tok.decode(ids[0]))
# 124439808
# 0.085 ' the'
# 0.048 ' now'
# 0.046 ' a'
# 0.032 ' France'
# 0.032 ' Paris'
# The capital of France is the capital of the French Republic, and the capital of the
This is a base model at work. "Paris" is only joint fourth, at 3%: in web text, "The capital of France is" is often followed by something other than the bare answer. Always picking the most likely token then produces a fluent but circular sentence, a classic weakness of greedy decoding (Decoding: Temperature, Top-k and Top-p).
Now in-context learning, zero-shot versus three examples:
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2").eval()
def top3(prompt):
ids = tok(prompt, return_tensors="pt").input_ids
with torch.no_grad():
p = model(ids).logits[0, -1].softmax(-1)
v, i = p.topk(3)
return [(round(x.item(), 3), tok.decode(j)) for x, j in zip(v, i)]
print(top3("Germany:")) # zero-shot
print(top3("France: Paris\nJapan: Tokyo\nItaly: Rome\nGermany:")) # three examples in the prompt
# [(0.127, '\n'), (0.034, ' The'), (0.011, ' A')]
# [(0.378, ' Frankfurt'), (0.1, ' Berlin'), (0.087, ' Hamburg')]
With no examples, GPT-2 has no idea what "Germany:" is asking for. With three examples, all its top guesses are German cities: it has learned the task from the prompt alone. It still gets the fact wrong, which a larger model would not. That gap between "understands the task" and "knows the answer" closes with scale.
Common pitfalls
- Treating a base model like an assistant. Base models continue text; they don't obey. Use an instruction-tuned ("chat" or "instruct") version for questions and commands, with its chat template (Instruction Tuning and Chat Models).
- Believing fluent output. The model produces likely text, not verified truth. Fluency is not evidence of accuracy (Hallucinations).
- Forgetting the context limit. Everything the model knows about your task must fit in its context window, measured in tokens (Tokenization). Text beyond it is simply not seen.
- Expecting determinism. With sampling, the same prompt gives different answers. Even with greedy decoding, tiny numerical differences on different hardware can change outputs.
- Assuming knowledge is current. A model knows only what was in its training data up to a cutoff date. Use retrieval (Retrieval-Augmented Generation) or tools (Tool Use and Function Calling) for anything newer.
Watch out Few-shot examples are powerful, and they bias the model too. If all your examples share a label, a format quirk or an ordering, the model will copy it. Vary the examples, and check outputs on cases unlike them.
Where it leads
- Build a GPT from Scratch trains a small GPT in about 200 lines of PyTorch.
- Decoding: Temperature, Top-k and Top-p covers how to choose each token: greedy, temperature, top-k, top-p.
- Pretraining Large Language Models and Scaling Laws explain how the big ones are trained and how big to make them.
- Instruction Tuning and Chat Models, RLHF and Preference Optimization and Reasoning Models and Test-Time Compute turn a base model into a helpful assistant and a careful reasoner.
- The KV Cache and Fast Inference, Quantization and Serving LLMs at Scale make generation fast and cheap.
- Evaluating LLMs and Benchmarks covers how to measure what these models can actually do.
- Using LLM APIs, Prompt Engineering and AI Agents are about building with them.
A bit of history
In June 2018 Alec Radford and colleagues at OpenAI published Improving Language Understanding by Generative Pre-Training, the first GPT. GPT-2 followed in February 2019, and its staged release started a public debate about publishing powerful models. In May 2020 Tom Brown and 30 co-authors described GPT-3 and few-shot learning. In January 2022 OpenAI published InstructGPT, and on 30 November 2022 it released ChatGPT, which reached an estimated 100 million users within about two months. GPT-4 arrived in March 2023, the same year as Anthropic's Claude, Google's Gemini, and Meta's LLaMA, whose weights, shared with researchers, leaked within weeks; with Llama 2's openly licensed release that July, the open-model ecosystem took off. Since 2024 the frontier has moved towards multimodal input, mixture-of-experts designs, much longer context windows and models trained to reason before answering, but all of them are still, underneath, decoder-only Transformers predicting the next token.
Try it
- In the first code example, change the prompt to "Q: What is the capital of France?\nA:". Does "Paris" become more likely? Why would the question-and-answer format help a base model?
- Try the few-shot prompt with one, two and three examples. Print the probability of " Berlin" each time.
- Replace
"gpt2"with"gpt2-medium"(355M parameters) in the in-context learning example. Does the larger model get Germany's capital right?Hint for 2: find the token id with
tok.encode(" Berlin")and readp[id]instead oftopk.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Intro to Large Language Models
A one-hour talk for a general audience on what LLMs are, how they are trained and where they are going.
Deep Dive into LLMs like ChatGPT
A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.
The Illustrated GPT-2
Visualises a decoder-only Transformer generating text one token at a time, including masked self-attention.
Language Models are Few-Shot Learners
GPT-3: a 175B-parameter model that could do new tasks from a few examples in the prompt.
Language Models are Unsupervised Multitask Learners
GPT-2: a 1.5-billion-parameter language model that performs tasks zero-shot, with no fine-tuning.
LLaMA: Open and Efficient Foundation Language Models
Meta's 7B to 65B models trained only on public data. Its recipe (pre-norm, RMSNorm, SwiGLU, RoPE) became the template for open models.
Emergent Abilities of Large Language Models
Catalogues abilities that appear only above some model scale. Read alongside the critiques arguing they are partly a measurement effect.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/gpt.md