6. The GPT Architecture

Decoder-only transformers and next-token prediction

The original Transformer paper from 2017 described a model with two halves: an encoder that reads the full input sequence, and a decoder that generates the output one token at a time. Machine translation needs both — the encoder digests the French sentence, the decoder produces the English one.

GPT made a deliberate choice to throw away the encoder entirely. The result is a decoder-only model that does one thing obsessively well: predict what comes next.

Encoder-decoder vs decoder-only

An encoder can look at the entire input sequence at once. Token 3 can attend to token 10 just as easily as token 2. This bidirectionality is great when you need to understand a fixed input (BERT is an encoder-only model built for exactly this).

A decoder generates output one token at a time and can only look backward. Token 3 can attend to tokens 1 and 2, but not to tokens 4, 5, or anything that hasn't been generated yet. This constraint is called causal masking, and it's not a limitation so much as a design choice — it's what makes autoregressive generation possible.

Why decoder-only works for generation

If the model could see future tokens during training, it would just copy them instead of learning to predict them. Causal masking enforces the discipline: at every position, the model must commit to a prediction using only what came before. This is the same constraint that applies at inference time, so training and generation stay perfectly aligned.

GPT-style models skip the cross-attention layers that let the decoder communicate with an encoder. Every transformer block is self-attention only, attending to the sequence the model itself has produced so far.

Causal masking

During attention, each token computes a score against every other token. Normally you'd softmax over all of those scores. Causal masking zeroes out the future positions before the softmax by replacing them with −∞ — so they become exactly 0 after the exponential.

The mask is a lower-triangular matrix. Position i can see positions 0 through i, and nothing else.

Diagram

Causal attention mask

Causal Attention Mask (5×5) t1 t2 t3 t4 t5 ← queries t1 t2 t3 t4 t5 keys → ✓ −∞ −∞ −∞ −∞ ✓ ✓ −∞ −∞ −∞ ✓ ✓ ✓ −∞ −∞ ✓ ✓ ✓ ✓ −∞ ✓ ✓ ✓ ✓ ✓ can attend masked (−∞)
Each row is a query token. Teal cells are positions it can attend to; red cells are set to −∞ before softmax.

The result is that token t5 can see all five positions, but token t1 can only see itself. After softmax, those −∞ entries become 0 — the token pays exactly zero attention to the future.

The full GPT stack

Starting from raw text, GPT processes it through a fixed pipeline. Here it is from bottom to top:

Diagram

The GPT stack

Token Probabilities Softmax Linear (d_model → vocab) Layer Norm Transformer Block ⋮ Transformer Block Transformer Block × N blocks Token Embedding + Positional Embedding
The GPT stack. Data flows upward — from token IDs at the bottom to a probability distribution at the top.

Token embedding. The model maintains a lookup table of shape [vocab_size × d_model]. Each token ID indexes into this table to produce a dense vector of size d_model (768 for GPT-2 small, up to 12288 for GPT-3). This is just an embedding matrix — it gets trained like everything else.

Positional embedding. Unlike RNNs, transformers have no built-in sense of order. GPT adds a second learned embedding for the position of each token in the sequence, then sums it with the token embedding. After this step, each token is represented as a d_model-dimensional vector that encodes both what the token is and where it sits in the sequence.

N transformer blocks. This is where the actual computation happens. Each block is identical in structure: multi-head causal self-attention followed by a feed-forward network, both wrapped with residual connections and layer norm. GPT-2 small uses 12 blocks; GPT-3 uses 96. Depth is how these models build up compositional understanding.

Final layer norm. After the last transformer block, a single layer normalization stabilizes the representation before the output projection.

Linear projection. A weight matrix of shape [d_model × vocab_size] projects the final hidden state back up to vocabulary size. No bias, no activation — just a matrix multiply. This is often tied (shared weights) with the token embedding matrix, which halves memory and tends to help performance.

Softmax. The raw scores (logits) become a proper probability distribution. The entry at position k tells you how likely the next token is the k-th word in the vocabulary.

Next-token prediction

The entire training objective fits in one sentence: given tokens 1 through n, predict token n+1.

Training signal on a single sequence

Consider the training text: the cat sat on the mat

GPT processes all 6 tokens in parallel, and the loss is computed at every position:

  • Position 1: given [the], predict cat
  • Position 2: given [the, cat], predict sat
  • Position 3: given [the, cat, sat], predict on
  • Position 4: given [the, cat, sat, on], predict the
  • Position 5: given [the, cat, sat, on, the], predict mat

One forward pass, six training signals. This efficiency is part of why transformers train so well on large corpora — every token in every sequence contributes gradient.

The loss function is cross-entropy: maximize the log-probability assigned to the correct next token. Equivalently, minimize the surprise. After billions of tokens of training, the model internalizes a rich model of language — syntax, facts, reasoning patterns — all learned as a side effect of getting good at predicting the next word.

How generation works

Inference is an autoregressive loop:

  1. Start with a prompt. Tokenize it and run the full GPT stack. You now have a probability distribution over the vocabulary for position n+1.
  2. Sample or take the argmax. Greedy decoding picks the highest-probability token. Sampling draws from the distribution (optionally with temperature scaling, top-k filtering, or nucleus sampling for more varied output).
  3. Append and repeat. Add the chosen token to the sequence and run the model again. The new token is now part of the context — the model attends to it just like the original prompt tokens.
  4. Stop when done. Generation ends when the model produces a special end-of-sequence token, or when a maximum length is reached.

Each generated token is fed back in as input. This is why it's called autoregressive — the model's own outputs become its next inputs.

Temperature controls randomness

Before softmax, divide the logits by a temperature parameter T. At T=1.0 you get the model's unmodified distribution. At T→0 you get greedy decoding (all probability mass on the top token). At T>1 the distribution flattens and output becomes more random. Most production systems use something like T=0.7 to balance coherence and variety.

Vocabulary size and the output projection

The vocabulary defines the set of tokens the model can produce. GPT-2 uses a 50,257-token BPE vocabulary. GPT-3 uses the same. The final linear layer maps from d_model to vocab_size, so GPT-2 small's output projection is a 768×50,257 matrix — about 38M parameters on its own, out of 117M total.

This is also why temperature scaling and sampling strategies matter so much at 50k+ tokens: the raw logit distribution is very peaked. The top few tokens typically capture the vast majority of probability mass; everything else is noise.

Scale: GPT-2 to GPT-3

GPT model sizes

Model Parameters Layers d_model Heads Context
GPT-2 Small117M12768121024
GPT-2 Medium345M241024161024
GPT-2 Large762M361280201024
GPT-2 XL1.5B481600251024
GPT-3175B9612288962048

Every dimension grows together: more layers, wider hidden states, more attention heads. The parameter count scales roughly as 12 × layers × d_model² — dominated by the feed-forward and attention weight matrices inside each block.

The jump from GPT-2 XL to GPT-3 is roughly 100× more parameters. That scale shift, combined with the same simple next-token objective on vastly more data, produced qualitatively different capabilities — including in-context learning (following instructions in the prompt) that smaller models barely exhibited.

Key takeaways

  • GPT is decoder-only: causal self-attention, no encoder, no cross-attention.
  • Causal masking sets future positions to −∞ before softmax, enforcing left-to-right attention.
  • The stack is: token embedding + positional embedding → N transformer blocks → layer norm → linear → softmax.
  • Training objective: cross-entropy loss on next-token prediction at every position.
  • Generation is an autoregressive loop — predict, append, repeat.
  • Scale (layers, width, data) is the primary driver of capability improvements.

The architecture is now clear, but we've said almost nothing about how you actually train one of these models — what data to use, how long to train, what the loss curve looks like, and what goes wrong. That's what the next article covers.

Try It — Next-Token Predictor

Type a prompt below and click Predict Next to see a probability distribution over the most likely next tokens. Click Sample to randomly draw one (weighted by the distribution) and append it to your text. Keep sampling to generate text one token at a time.