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.

  1. RNNs. A vanilla RNN moves from hidden state h_t to h_{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.
  2. 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.
  3. 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

\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V, \qquad Q = XW_Q,\; K = XW_K,\; V = XW_V .

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. \sqrt{d_k} is only a normalizing constant. The mask M sets entry (t, s) to -\infty whenever s > t, so position t can never attend to the future. This is the causal mask.

A decoder block wraps this in familiar pieces:

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 N such blocks, and N is just an architectural hyperparameter. Because of the causal mask, one forward pass trains next-token prediction at all T positions in parallel.

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:

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 Y given an input sequence X:

P(Y \mid X) = \prod_t P(Y_t \mid Y_{<t}, X).

GPT instead models the text itself, an unconditional generative model:

P(X) = \prod_t P(X_t \mid X_{<t}).

The key observation is that a sequence already contains its own supervision. Each conditional P(X_t \mid X_{<t}) is a supervised problem: the input is everything before position t, and the target is the token at t. So GPT keeps the same building blocks and simply maps X to X shifted by one position.

This mirrors the discriminative/generative contrast from earlier in the course. Logistic regression models P(Y \mid X) directly. Naive Bayes models P(X \mid Y) and P(Y), which lets it say something about P(X) and generate data. GPT does not change the parameterization of the Transformer. It changes what is being predicted.

Why this matters: data. Paired (X, Y) data such as translations requires human annotation and is limited. Raw text needs no labels: anything humans have already written can be used. Reframing the task as next-token prediction dramatically increases the amount of usable training data.

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:

P_\theta(X) = \prod_i \prod_t P_\theta(X_{i,t} \mid X_{i,<t}),

where i indexes training sequences. Compare this with a hidden Markov model, which assumes the past can be compressed into a hidden state passed along a chain. GPT makes no such compression assumption. Every earlier token can directly influence every later one; only “reverse causality” is ruled out.

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:

\max_\theta \; \sum_i \sum_t \log P_\theta(X_{i,t} \mid X_{i,<t}).

GPT-1 is essentially this equation implemented with a 12-layer masked self-attention decoder. Everything later in the lecture (tokenizers, scale, architectural tweaks) is built around this one objective.

3. Anatomy of a GPT

3.1 End to end

Stage Operation Output shape
Token ids integers in \{0,\dots,V-1\} B \times T
Embedding token embedding + position embedding B \times T \times d
Decoder blocks N stacked blocks B \times T \times d
Final LayerNorm normalize each position B \times T \times d
LM head linear map d \to V B \times T \times V (logits)
Softmax over the vocabulary B \times T \times V (probabilities)

Here B is the batch size, T the context length, d the embedding dimension, and V the vocabulary size.

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 QK^\top products, softmaxes and value products, and applies linear layers. The backward pass of a linear layer is again matrix multiplication (with transposed weights). This is why GPUs and TPUs, which excel at repeated matrix multiplication, are the hardware for LLMs.

3.2 The output layer and the loss

3.3 Where do the parameters live?

Each decoder block has

Ignoring biases and LayerNorm parameters, L blocks therefore contain about 12 L d^2 parameters, and the (tied) embedding adds Vd.

Model L d 12Ld^2 Vd 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:

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:

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 t of generation re-runs all t tokens through every layer, even though the keys and values of earlier tokens have not changed (the causal mask guarantees that earlier positions never see later ones). With a KV cache, each layer stores the keys and values of past tokens; step t processes only the new token, whose query reads the stored keys and values.

The cost is memory. For GPT-3, caching one token needs

\underbrace{2}_{K,V} \times \underbrace{96}_{\text{layers}} \times \underbrace{12{,}288}_{d} \times \underbrace{2\ \text{bytes}}_{\text{fp16}} \approx 4.7\ \text{MB},

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:

“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 (d above), and Block is the causal self-attention + MLP block from transformer.py.

Two hyperparameters are baked into the architecture:

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

In the run shown in class, the training loss starts at 4.3 (close to \ln 65 \approx 4.17) and quickly drops to about 2.6, with validation loss following. After about 5,000 steps the model produces text that looks like Shakespeare in layout and spelling style but is mostly nonsense. At the character level, even spelling a word requires learning dependencies between characters. The upside is that a 65-symbol vocabulary keeps the model small enough to train on a laptop CPU.

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:

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:

7.3 GPT-1 → GPT-2 (2019)

GPT-2 (124M) can be reproduced with nanoGPT in about 4 days on an 8×A100 machine.

7.4 GPT-2 → GPT-3 (2020)

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. Parameter counts and “mixture of experts” claims found online are rumors, not published facts.

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

P(Y \mid X) = \sum_m g_m(X)\, P_m(Y \mid X), \qquad \sum_m g_m(X) = 1,\; g_m(X) \ge 0 .

Its parameters can be estimated with EM. The form also unifies familiar ensembles:

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-k experts run for each token.

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

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: