Lecture 18: GPT Architectures
How a stack of Transformer decoder blocks plus a next-token likelihood becomes GPT, and what has (and has not) changed from GPT-1 to today's open-weight models.
Scope. These notes follow the November 10 lecture slides and the in-class discussion. The lecture stopped at the “modern decoder recipe” slide; grouped-query attention and Mixture of Experts were finished at the start of the November 12 lecture and are summarized briefly in Section 9 for completeness.
1. Recap: from RNNs to a decoder block
The last few lectures built up to this one in three steps.
- RNNs. A vanilla RNN moves from hidden state
h_t toh_{t+1} with a single shared weight matrix. Backpropagation through time is just the chain rule, but repeatedly multiplying by the same matrix makes gradients vanish or explode, so vanilla RNNs struggle beyond roughly 20 time steps. Gated cells (LSTM, GRU) help. - Attention. The first attention mechanisms let the recurrent model look back at the source sequence at every step instead of squeezing everything into a single hidden state.
- Transformers. If every output can look back at all inputs anyway, the recurrence is unnecessary. “Attention Is All You Need” removes it and stacks attention layers instead.
A single (masked) attention layer computes
The output is simply a reweighting of the values, which are themselves a linear projection of the inputs. Queries are matched against keys by similarity; the softmax turns these scores into non-negative weights that sum to one; and the weights select (“unlock”) the corresponding values.
A decoder block wraps this in familiar pieces:
- LayerNorm → multi-head masked self-attention → residual add,
- LayerNorm → position-wise MLP → residual add.
Attention mixes information across tokens; the MLP processes each token on its own. The residual (skip) connections carry simple updates straight through, while more complicated updates go through attention and the MLP. Residuals plus LayerNorm are what make it possible to stack
Nothing in a decoder block is new on its own: fully connected layers, residual additions, LayerNorm, and attention. A GPT is “just” these pieces stacked many times.
2. From Transformer to GPT
GPT stands for Generative Pre-trained Transformer:
- Transformer: it is a stack of Transformer (decoder) blocks;
- Pre-trained: it is trained once on a very large corpus and then reused for other tasks;
- Generative: it models and samples text, rather than only mapping an
X to aY .
2.1 Sequence transduction vs. sequence modeling
The original Transformer was built for sequence transduction such as machine translation. It is a conditional model of an output sequence
GPT instead models the text itself, an unconditional generative model:
The key observation is that a sequence already contains its own supervision. Each conditional
This mirrors the discriminative/generative contrast from earlier in the course. Logistic regression models
Why this matters: data. Paired
Architectural consequence. Once there is no distinction between an “input” and an “output” sequence, the encoder and the cross-attention that feeds encoder states into the middle of the decoder are no longer needed. A GPT is a decoder-only stack with causal self-attention, which is why diagrams of GPT go straight through one tower instead of two.
2.2 GPT as a probabilistic model
As a directed probabilistic graphical model, GPT has an edge from every earlier token to every later token, and no edges backwards:
where
As everywhere else in this course, we fit the model by maximum likelihood, in practice maximizing the log-likelihood because logs turn the product into a sum:
GPT-1 is essentially this equation implemented with a 12-layer masked self-attention decoder.
3. Anatomy of a GPT
3.1 End to end
| Stage | Operation | Output shape |
|---|---|---|
| Token ids | integers in |
|
| Embedding | token embedding + position embedding | |
| Decoder blocks | ||
| Final LayerNorm | normalize each position | |
| LM head | linear map |
|
| Softmax | over the vocabulary |
Here
- The token embedding is a lookup table mapping each token id to a vector. The position embedding adds information about where in the sequence the token sits, since the same word can play different roles at the beginning and end of a sentence.
- The LM head projects back from embedding space to vocabulary space; it is the reverse of the token embedding.
- The softmax turns the logits into a distribution over the vocabulary, i.e.
P_\theta(x_{t+1} \mid x_{\le t}) at every position.
Because of the causal mask, one forward pass gives a next-token distribution at every position. During training every position is scored against its true next token. During generation only the last position is used.
“It’s all matrix multiplication.” The forward pass multiplies by an embedding matrix, runs blocks made of
3.2 The output layer and the loss
- Targets are the inputs shifted by one token. For the input
The cat sat on, the targets arecat sat on the. - Weight tying. One
V \times d matrix both embeds tokens and, transposed, scores them in the LM head. This savesVd parameters. - Cross-entropy is the MLE objective. Averaging
-\log P_\theta(\text{true next token}) over positions is exactly the (negated, averaged) log-likelihood from Section 2.2. - Sanity check. At initialization the model should be close to uniform over the vocabulary, so the initial loss should be about
\ln V . For a 65-character vocabulary,\ln 65 \approx 4.17 ; the in-class run started at 4.3 (Section 6).
3.3 Where do the parameters live?
Each decoder block has
- attention: four
d \times d matrices (W_Q, W_K, W_V , and the output projectionW_O ), i.e.4d^2 ; - MLP:
d \to 4d \to d , i.e.2 \cdot 4d^2 = 8d^2 .
Ignoring biases and LayerNorm parameters,
| Model | Total | Usually quoted | ||||
|---|---|---|---|---|---|---|
| GPT-0 (ours) | 4 | 64 | 0.20M | 0.004M | 0.21M | 208,961 |
| GPT-1 | 12 | 768 | 84.9M | 31.1M | 116M | 117M |
| GPT-2 small | 12 | 768 | 84.9M | 38.6M | 124M | 124M |
| GPT-2 XL | 48 | 1600 | 1.47B | 0.08B | 1.56B | 1.5B |
| GPT-3 | 96 | 12,288 | 173.9B | 0.6B | 174.6B | 175B |
Two takeaways:
- In small models, the embeddings are a big share of the parameters. In large models, more than 99% of parameters are in the blocks, and about two-thirds of those are in the MLPs. Although attention is the conceptual breakthrough, most of the weights sit in plain feed-forward layers. This makes the MLP an obvious target for optimization, and Mixture of Experts (Section 9) is the first widely adopted step in that direction.
- A forward pass costs roughly
2N FLOPs per token for a model withN parameters, and training costs roughly6N (discussed in the next lecture).
4. Generating text, one token at a time
for _ in range(max_new_tokens):
logits = model(idx[:, -T:])[:, -1] # last position only
probs = softmax(logits / tau)
nxt = sample(probs) # or argmax
idx = cat(idx, nxt)
The model only outputs a distribution. How to pick the next token from it is a separate design choice, the sampling procedure:
- Greedy decoding always takes the argmax (the limit
\tau \to 0 ). It tends to give bland text and can get stuck in loops, e.g. repeatedly emitting a very common word. - Temperature
\tau divides the logits before the softmax.\tau < 1 sharpens the distribution;\tau > 1 flattens it, producing more varied text and helping escape loops. Chat products set this for you, but they still have to choose it. - Top-
k keeps only thek most likely tokens, renormalizes, and samples among them. Top-p (nucleus) sampling keeps the smallest set of tokens whose total probability is at leastp .
Why one token at a time? Each step’s input includes the token just sampled, which does not exist until the previous step finishes. Training is parallel across positions (teacher forcing), but generation is inherently sequential. Getting around this requires a different model altogether; for example, diffusion language models try to generate all positions jointly, borrowing ideas from the diffusion lecture. Today’s dominant LLMs are still autoregressive.
5. The KV cache: don’t recompute the past
Without a cache, step
The cost is memory. For GPT-3, caching one token needs
or about 9.7 GB for a single 2,048-token context. Generation is therefore limited by memory, not arithmetic, which motivates the KV-shrinking attention variants GQA and MLA (Section 9).
In industry, the cache is also an important cost lever: when many requests share the same prefix, providers can reuse cached keys and values, and cache hit rates are tracked as a way to lower inference costs.
6. Let’s write a GPT: EasyGPT
The course’s EasyGPT repository, adapted from Andrej Karpathy’s nanoGPT, contains:
gpt0.ipynb: a character-level GPT trained on Tiny Shakespeare (≈1 MB of text);gpt_zero.py: the whole model in about 90 lines, embeddings → blocks → LayerNorm → LM head;transformer.py: the causal self-attention + MLP block from last lecture.
“GPT-0” is a teaching version of GPT-1: same ideas, smaller and simpler.
6.1 The model
The model class from gpt_zero.py, with docstrings shortened:
class GPT(nn.Module):
def __init__(self, config: GPTConfig):
super().__init__()
self.block_size = config.block_size
self.device = config.device
# Token and positional embeddings
self.token_embedding = nn.Embedding(config.vocab_size, config.n_embd)
self.position_embedding = nn.Embedding(config.block_size, config.n_embd)
# Transformer blocks
self.transformer = nn.Sequential(*[Block(config) for _ in range(config.n_layer)])
# Final normalization and output projection
self.ln_f = nn.LayerNorm(config.n_embd)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
def forward(self, idx, targets=None):
B, T = idx.shape
assert T <= self.block_size, "Sequence length exceeds block size"
token_embeddings = self.token_embedding(idx) # (B, T, C)
position_embeddings = self.position_embedding(torch.arange(T, device=self.device)) # (T, C)
x = token_embeddings + position_embeddings # (B, T, C)
x = self.transformer(x) # (B, T, C)
x = self.ln_f(x) # (B, T, C)
logits = self.lm_head(x) # (B, T, vocab_size)
loss = None
if targets is not None:
logits_flat = logits.view(B * T, -1) # (B*T, vocab_size)
targets_flat = targets.view(B * T) # (B*T,)
loss = F.cross_entropy(logits_flat, targets_flat)
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -self.block_size:] # crop to the last block_size tokens
logits, _ = self(idx_cond)
last_logits = logits[:, -1, :] # (B, vocab_size)
probs = F.softmax(last_logits, dim=-1) # (B, vocab_size)
next_token = torch.multinomial(probs, num_samples=1) # (B, 1)
idx = torch.cat((idx, next_token), dim=1) # (B, T+1)
return idx
Here C is the embedding dimension (Block is the causal self-attention + MLP block from transformer.py.
Two hyperparameters are baked into the architecture:
vocab_sizefixes the size of the token embedding table. The model can never represent more distinct tokens than this.block_sizefixes the size of the position embedding table, so the model can never accept more tokens per sequence than this. This is the maximum context length, which is why LLM providers advertise it: it is fixed when the model is trained.
The GPTConfig dataclass in gpt_config.py also sets n_layer (how many blocks to stack), n_head, n_embd, dropout (none for GPT-0), bias, and device. Note that this teaching model does not tie weights: lm_head is a separate nn.Linear with a bias. Tying it to the token embedding (Section 3.2) would be one extra line, self.lm_head.weight = self.token_embedding.weight.
6.2 Training on Tiny Shakespeare
- Data. Tiny Shakespeare has about one million characters and 65 unique characters (52 upper- and lowercase letters plus 13 punctuation and whitespace symbols).
- Tokenization. Character-level: each character maps to an integer (e.g.
h → 46,e → 43,l → 50), and the whole corpus becomes one long integer sequence. - Examples. Fixed-length blocks are cut from the sequence; within a block the model predicts the 2nd token from the 1st, the 3rd from the first two, and so on, all in one pass.
- Config. 4 layers, 4 heads,
d = 64 , context 8, vocabulary 65, giving 208,961 parameters. - Optimization. Adam with default settings; loss estimation runs under
torch.no_grad().
In the run shown in class, the training loss starts at 4.3 (close to
The repository also implements the GPT-2 architecture. Swapping in the GPT-2 config on an A100 GPU takes about an hour to train and produces noticeably more Shakespeare-like text.
7. From GPT-0 to GPT-3
7.1 GPT-0 → GPT-1 (2018)
GPT-1 is the same idea about 500 times larger (117M parameters).
| GPT-0 | GPT-1 | |
|---|---|---|
| Tokenizer | characters | byte-pair encoding (40,000 merges) |
| Normalization | pre-norm | post-norm (like the original Transformer) |
| Layers / heads | 4 / 4 | 12 / 12 |
| Context (block size) | 8 | 512 |
| Vocabulary | 65 characters | ~40K BPE tokens |
| Embedding dim | 64 | 768 |
| Data | Tiny Shakespeare (1 MB) | BooksCorpus (~7,000 unpublished books) |
| Learning rate | constant | 2,000-step warmup + cosine decay |
GPT-1 also uses weight tying.
7.2 Tokenization: byte-pair encoding
Tokenization involves a trade-off:
- Characters give a tiny vocabulary but very long sequences, and the model must learn to spell.
- Words give short sequences but a huge vocabulary across all words and languages, plus the problem of unknown words.
Byte-pair encoding (BPE) sits in between. Start from characters (GPT-2: raw bytes) and repeatedly merge the most frequent adjacent pair into a new token:
| Step | Merge | Sequence | Length |
|---|---|---|---|
| 0 | aaabdaaabac |
11 | |
| 1 | aa → Z |
ZabdZabac |
9 |
| 2 | ab → Y |
ZYdZYac |
7 |
| 3 | ZY → X |
XdXac |
5 |
Vocabulary sizes have grown over time: GPT-1 ~40K, GPT-2/3 50,257, Llama 3 128K, gpt-oss 201K.
Tokenization has visible side effects:
- Spaces are part of tokens (e.g.
·learning). - Cost, speed, and context length are all counted in tokens, not characters or words.
- The model never sees the letters inside a word like
strawberry, which is a single token, so letter-level questions are hard. - Digits are chunked somewhat arbitrarily. For example, the GPT-2 tokenizer splits
453as45+3and1234567as123+45+67, which complicates arithmetic.
7.3 GPT-1 → GPT-2 (2019)
- Pre-norm: LayerNorm moves to the input of each sub-block, plus a final LayerNorm after the last block.
- Byte-level BPE: any string can be encoded, so there are no unknown tokens.
- Scale: four sizes from 124M to 1.5B parameters. The largest has 48 layers, 25 heads,
d = 1600 , context 1,024, and a vocabulary of 50,257. - Data: WebText, about 40 GB of text from roughly 8M web pages linked from Reddit.
- No fine-tuning: tasks are posed as text (“zero-shot”), so one model handles many tasks.
GPT-2 (124M) can be reproduced with nanoGPT in about 4 days on an 8×A100 machine.
7.4 GPT-2 → GPT-3 (2020)
- Architecture: the same design as GPT-2, plus alternating dense and locally banded sparse attention layers.
- Scale: 175B parameters, 96 layers,
d = 12{,}288 , 96 heads of dimension 128, context 2,048. - Data: filtered Common Crawl (~570 GB) plus WebText2, books, and Wikipedia, for about 300B training tokens.
- Headline result: few-shot in-context learning, i.e. performing a task from examples in the prompt with no weight updates (next lecture).
7.5 GPT-4 (2023): the curtain closes
The GPT-4 technical report discloses only that it is Transformer-based, pretrained to predict the next token, fine-tuned with RLHF, and accepts image and text input. It explicitly withholds architecture, model size, hardware, compute, data, and training details.
An interesting pattern across the models with published details: even though deep learning seems to break the classical rule of having fewer parameters than data points, these models are trained on more tokens than they have parameters (for GPT-3, 300B tokens vs. 175B parameters).
8. Open-weight models and the modern recipe
With open-weight models we can see inside again.
| GPT-2 XL (2019) | GPT-3 (2020) | Llama 3.1 405B (2024) | DeepSeek-V3 (2024) | gpt-oss-120b (2025) | |
|---|---|---|---|---|---|
| Params (total / active) | 1.5B / 1.5B | 175B / 175B | 405B / 405B | 671B / 37B | 117B / 5.1B |
| Layers × width | 48 × 1,600 | 96 × 12,288 | 126 × 16,384 | 61 × 7,168 | 36 × 2,880 |
| Attention | MHA, 25 heads | MHA + banded sparse | GQA: 128 q / 8 kv | MLA (compressed KV) | GQA: 64 q / 8 kv; alternating 128-token window / full |
| Position | learned | learned | RoPE | RoPE | RoPE + YaRN |
| Norm · MLP | LayerNorm · GELU | LayerNorm · GELU | RMSNorm · SwiGLU | RMSNorm · SwiGLU MoE | RMSNorm · SwiGLU MoE |
| Experts | – | – | – (dense) | 1 shared + 256 routed, top-8 | 128, top-4 |
| Context | 1K | 2K | 128K | 128K | 128K |
| Vocab | 50K | 50K | 128K | 129K | 201K |
| Training tokens | 40 GB of text | 300B | 15.6T | 14.8T | not disclosed |
The skeleton is still GPT-2’s; the rows show what changed. Note the gap between total and active parameters in the MoE models. For example, gpt-oss-120b has 117B parameters, but only 5.1B are used for any given token.
| Part | GPT-2 (2019) | Typical in 2025–26 | Why |
|---|---|---|---|
| Normalization | LayerNorm | RMSNorm | cheaper, just as stable |
| MLP | GELU | SwiGLU (gated) | better quality per parameter |
| Positions | learned absolute | RoPE | a learned table ends at the training length; RoPE encodes relative position by rotating query/key vectors |
| KV heads | one per query head | GQA / MLA | smaller KV cache, faster generation |
| FFN | dense | Mixture of Experts | more parameters at the same compute per token |
| Context | 1K | 128K+ | RoPE scaling, sliding windows |
| Vocab | 50K | 128K–200K | fewer tokens per text, more languages |
What has not changed since 2018: decoder-only, causal self-attention + MLP + residual stream, and next-token cross-entropy pretraining. Since about 2020 the architecture has mostly followed a scale-up recipe with few surprising tricks. The bigger differences between models are in training: building the corpus, and post-training (e.g. reinforcement learning) so that the model does something useful rather than just producing plausible text. These are the topics of the next two lectures.
9. Two parts in more detail (finished on November 12)
9.1 Grouped-query attention: shrinking the KV cache
In standard multi-head attention (MHA), every query head has its own key/value head. Multi-query attention (MQA) shares a single K/V head across all query heads. Grouped-query attention (GQA) sits in between: query heads are split into groups, and each group shares one K/V head (e.g. 8 query heads with 2 KV heads).
Because the KV cache scales with the number of KV heads, the savings are large. For Llama 3 70B at a 128K-token context in bf16, a single sequence needs about 344 GB with 64 KV heads (MHA) vs. about 43 GB with 8 (GQA). The quality cost is small, and generation is much faster because each step reads far less memory. DeepSeek’s multi-head latent attention (MLA) goes further: it caches one small latent vector per token and reconstructs K and V from it.
9.2 Mixture of Experts: a 1991 probabilistic idea
A mixture of experts models the conditional distribution as a gated mixture
Its parameters can be estimated with EM.
- MoE:
g_m(X) is a learned gating function of the input; - bagging:
g_m(X) = 1/M , a constant uniform weight; - boosting:
g_m(X) = \alpha_m , a constant per-expert weight.
Ensemble analysis suggests that diverse experts help. Their errors are wrong in individualized ways and partly cancel out through consensus, so slight “overfitting” of individual experts can help the ensemble.
In today’s LLMs, the MLP in each block is replaced by many expert MLPs with a learned router. The gate is the same as in 1991 but sparse: only the top-
| Model | Experts / layer | Used per token | Total | Active |
|---|---|---|---|---|
| Mixtral 8x7B (2024) | 8 | 2 | 47B | 13B |
| DeepSeek-V3 (2024) | 256 + 1 shared | 8 + 1 shared | 671B | 37B |
| gpt-oss-120b (2025) | 128 | 4 | 117B | 5.1B |
- Capacity grows with total parameters, while cost per token grows only with active parameters.
- Training: the router must be kept balanced, or a few experts end up receiving every token and over-specialize.
- Serving: every expert must sit in GPU memory, even though only a few run per token.
10. Summary
| Component | Transformer | GPT |
|---|---|---|
| Architecture | encoder–decoder | decoder-only |
| Attention | full self-attention (+ cross-attention) | masked (causal) self-attention |
| Positional encoding | sinusoidal (original) | learned (GPT-1 to 3); RoPE in most models today |
| Output | task-specific | next-token prediction |
| Training objective | flexible (e.g. translation) | next-token maximum likelihood (cross-entropy) |
| Inference | depends on task | one token at a time (greedy, temperature, top-k/top-p) with a KV cache |
From GPT-1 to today, the skeleton has stayed the same: decoder-only, causal self-attention + MLP + residuals, trained by next-token prediction. What changed:
- Scale: 117M (GPT-1) → 175B dense (GPT-3) → hundreds of billions of total parameters with MoE; context 512 → 128K+; vocabulary ~40K → 128K–200K.
- Swapped-in parts: RMSNorm, SwiGLU, RoPE, GQA/MLA, and Mixture of Experts.
- Training: BooksCorpus → ~15 trillion tokens, followed by post-training with SFT and RL from human feedback (upcoming lectures).