◆ AI All-in-One

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
↗ Plan a path here

Read first

The TransformerLanguage Modeling and Next-Token Prediction

This leads to

Build a GPT from ScratchDecoding: Temperature, Top-k and Top-pHallucinationsThe KV Cache and Fast InferenceEvaluating LLMs and BenchmarksPretraining Large Language ModelsSynthetic DataMultimodal LLMs
The full path from zero — 31 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. LSTMs and GRUs
  26. Residual Connections
  27. Sequence-to-Sequence Models
  28. Attention
  29. Self-Attention and Multi-Head Attention
  30. Positional Encodings
  31. The Transformer
  32. 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 tt only sees positions 11 to tt. 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 TT tokens gives TT 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:

  1. Feed in the prompt's token ids.
  2. Take the output distribution at the last position: P(next token∣everything so far)P(\text{next token} \mid \text{everything so far}).
  3. Choose a token from it: the most likely one, or a random draw (Decoding: Temperature, Top-k and Top-p).
  4. 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.

How a GPT generates: predict one token, append it, repeat The ␣capital ␣of ␣France ␣is ␣the prompt token ids in GPT-2: 464, 3139, 286, 4881, 318 new token (id 262) token + position embeddings decoder block 1 causal self-attention + MLP decoder block 2 causal self-attention + MLP decoder block 12 causal self-attention + MLP ⋮ vector at the last position → linear → softmax P(next token): real GPT-2 small output ␣the 0.085 ␣now 0.048 ␣a 0.046 ␣France 0.032 ␣Paris 0.032 … plus 50,252 other tokens pick one (here the most likely), append it and run the stack again
Fig. 1 A GPT generating text. The prompt runs through the stack; the vector at the last position becomes a probability for every token in the vocabulary (real numbers from GPT-2 small); one token is chosen, appended, and the loop runs again.

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

Published parameter counts of decoder-only language models (log scale) 100M 1B 10B 100B 1T 2018 2019 2020 2021 2022 2023 2024 2025 parameters GPT-1 OpenAI GPT-2 OpenAI GPT-3 OpenAI PaLM Google LLaMA Meta, open weights Llama 3.1 Meta, open weights DeepSeek-V3 mixture of experts, 37B active GPT-4 (2023): size not disclosed closed weights open weights Each grid line is 10× the one below.
Fig. 2 Published sizes of some landmark decoder-only models, on a log scale where each grid line is ten times the one below. Sizes grew about a thousandfold in two years, then the frontier shifted to more data, mixture-of-experts models and undisclosed sizes.
  • 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

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

  1. 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?
  2. Try the few-shot prompt with one, two and three examples. Print the probability of " Berlin" each time.
  3. 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 read p[id] instead of topk.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You ask a base model (not instruction-tuned) "What is the capital of France?" and it replies with three more quiz questions. Why?

  2. A model generates a 500-token answer. Why does it appear word by word rather than all at once?

  3. You prompt a model with "France: Paris / Japan: Tokyo / Italy: Rome / Germany:" and it answers with a German city. What is this called?

  4. A 2023 paper argued that many "emergent abilities" are partly an artefact. What was the argument?

  5. Your team needs a model it can download, run on its own servers and fine-tune. Which kind should you look for?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Intro to Large Language Models

Andrej Karpathy · 2023 · Beginner · Free

A one-hour talk for a general audience on what LLMs are, how they are trained and where they are going.

Video

Deep Dive into LLMs like ChatGPT

Andrej Karpathy · 2025 · Beginner · Free

A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.

Article

The Illustrated GPT-2

Jay Alammar · Beginner · Free

Visualises a decoder-only Transformer generating text one token at a time, including masked self-attention.

Paper

Emergent Abilities of Large Language Models

Wei et al. · 2022 · Intermediate · Free

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