4 Implementing a GPT model from scratch to generate text

Language Models · v1.0.5

2026-11-03 01:40:26

Where we are

Where this fits

Step 3 of stage 1: the architecture, written after attention and before pretraining.

Already built

  • a BPE tokenizer and embedding layers
  • masked multi-head attention — one sub-layer of one block

Built here

  • everything that surrounds attention
  • the target is GPT-2 small, 124M parameters
  • no weight is trained; the output is gibberish, and that gap motivates the next unit

Outline of key topics

  • Configuration and skeleton — fixing every shape in one place, then sketching the model in placeholders.
  • Layer normalization — activations at zero mean and unit variance.
  • GELU and the feed-forward network — a smooth activation inside a fourfold expand-and-contract.
  • Shortcut connections — a short path for the gradient.
  • The transformer block — the unit repeated twelve times.
  • The assembled model — parameter count, memory, and the GPT-2 family.
  • Greedy decoding — calling the model on its own output.

Configuration and skeleton

The configuration

Embedding layers feed a stack of transformer blocks containing masked multi-head attention.

A single configuration object fixes every shape the model needs.

key GPT-2 124M
vocab_size 50,257
context_length 1,024
emb_dim 768
n_heads 12
n_layers 12
drop_rate 0.1

Nothing downstream hard-codes a dimension.

The skeleton

A placeholder model establishes the data path before any internal component is real.

# pseudo-code
def forward(token_ids):
    x = tok_emb(token_ids) + pos_emb(positions)
    x = drop_emb(x)
    x = trf_blocks(x)        # n_layers x TransformerBlock
    x = final_norm(x)
    return out_head(x)       # logits, no bias

Two sentences of four tokens give output shape \([2,\ 4,\ 50257]\) — one unnormalized score per vocabulary entry, at every position.

Components of a block

Layer normalization

Six activations rescaled to zero mean and unit variance.

Deep stacks suffer vanishing and exploding gradients. Normalization holds each layer’s outputs at a consistent scale.

\[\hat{x} = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta\]

  • \(\gamma\) and \(\beta\) are trainable vectors of length emb_dim
  • the statistic runs over the feature axis — per token, per example
  • never over the batch axis, so behaviour is independent of batch size

GELU and the feed-forward network

GELU (left) against ReLU (right): smooth, with non-zero gradient over almost all negative inputs.

\[\mathrm{GELU}(x) = x \cdot \Phi(x)\]

# pseudo-code
def feed_forward(x):
    x = linear(x, 768 -> 3072)
    x = GELU(x)
    return linear(x, 3072 -> 768)
  • attention mixes across positions; this sub-layer transforms each position alone
  • a fourfold expansion and contraction, shape preserved end to end

Shortcut connections

Five layers without shortcuts (left) and with them (right), annotated with the mean absolute gradient at each layer.

A shortcut adds a layer’s input to its output, creating a shorter path for the gradient.

  • without them, the mean gradient shrinks by about an order of magnitude per layer travelled backwards
  • with them, the first layer’s mean gradient rises from \(0.00020\) to \(0.2217\)
  • every sub-layer in the block that follows is wrapped in one

The transformer block

The repeating unit

# pseudo-code
def transformer_block(x):
    for op in (attention, feed_forward):
        shortcut = x
        x = layer_norm(x)
        x = op(x)
        x = dropout(x)
        x = x + shortcut
    return x

One pattern applied twice: norm, operate, drop, add.

  • the operation is masked multi-head attention, then the feed-forward network
  • only the layer-norm parameters differ between the two
  • normalization comes before each operation — Pre-LayerNorm

Shape preservation

Each row is one token’s 768-dimensional vector; outputs keep the dimension of the inputs.

\([B, T, \texttt{emb\_dim}]\) in, \([B, T, \texttt{emb\_dim}]\) out.

  • what changes is content, not shape: each output vector re-encodes context drawn from the whole sequence
  • shape preservation is what makes stacking twelve blocks require no dimension bookkeeping

The assembled model

GPTModel, end to end

Token and positional embeddings, twelve transformer blocks, a final layer norm, a linear output head.

Input — embedding layers map token indices to dense vectors and add learnable positional embeddings, followed by dropout.

Body — a sequential stack of identical transformer blocks.

Head — a final layer normalization, then a bias-free linear projection into vocabulary space.

Output shape is unchanged from the placeholder: \([2, 4, 50257]\).

Parameters, memory, scale

Parameter count

  • summing every tensor gives \(163{,}009{,}536\), not 124 million
  • weight tying, used in the original GPT-2, reuses the token embedding matrix as the output head — about \(38.6\)M entries, counted once instead of twice, giving \(124{,}412{,}160\)
  • untied layers train better, so the model here genuinely holds 163M

At 4 bytes per parameter: \(\approx 621.8\) MB of weights alone.

One architecture, four sizes

Model emb_dim n_layers n_heads
small 768 12 12
medium 1,024 24 16
large 1,280 36 20
XL 1,600 48 25

Only the configuration changes.

Generating text

Greedy decoding

One generation step: encode, run the model, keep the last position’s logits, softmax, pick the token ID, append.
# pseudo-code
for _ in range(max_new_tokens):
    ctx   = idx[-context_size:]
    logits = model(ctx)[last]
    probs  = softmax(logits)
    idx    = concat(idx, argmax(probs))
  • the context is cropped to the supported window
  • only the last position’s logits matter
  • argmax selects one token: greedy decoding

Architecture without training

Six iterations of the prediction cycle, each appending its own prediction to the input.

Six generation steps from the prompt Hello, I am:

Hello, I am Featureiman
Byeswickattribute argue
  • the weights are at random initialization
  • nothing in this unit measures how wrong an output is, and nothing changes a weight in response

Architecture alone does not produce language.

Summary

Summary

  • A GPT model is modular: embeddings, a stack of identical transformer blocks, a final norm, a linear head.
  • Layer normalization holds each layer’s outputs at a consistent mean and variance, over the feature axis.
  • GELU inside a fourfold expand-and-contract transforms each position independently; attention mixes across positions.
  • Shortcut connections keep gradients from vanishing across depth — measured, \(0.00020\) to \(0.2217\) at the first layer.
  • The block preserves \([B, T, \texttt{emb\_dim}]\), which is what makes stacking it twelve times trivial.
  • Parameter counts depend on weight tying: \(163{,}009{,}536\) untied against \(124{,}412{,}160\) tied.
  • Next: cross-entropy loss, a training loop, sampling, and OpenAI’s pretrained weights.