REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: build a pre-norm decoder block and audit its gradients

A decoder block composes normalization, projection layout, multiple attention heads, causal masking, residual connections and a feed-forward network.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Project: build a pre-norm decoder block and audit its gradients →

Your task

Implement one causal pre-norm block on nonempty x[B,T,D]. parameters has exactly n1/n2 [D], qkv [3D,D], out [D,D], ff1 [2D,D], ff2 [D,2D]. Use layer_norm eps=1e-5 with these weights and no biases; split contiguous Q/K/V projections into heads, scaled causal softmax attention, concatenate heads and add the output projection residual. Then add ff2(GELU(ff1(layer_norm(residual,n2)))). Dropout is zero; heads must divide D. Return the differentiable output and reject a wrong schema.

Starter

import torch


def decoder_block(x, parameters, heads):
    return None
Inspect the worked answer
import math
import torch
from torch.nn import functional as F


def decoder_block(x, parameters, heads):
    if x.ndim != 3 or min(x.shape) < 1 or type(heads) is not int or heads < 1 or x.shape[-1] % heads:
        raise ValueError('nonempty [B,T,D] input and a head count dividing D required')
    batch, length, width = x.shape
    shapes = {'n1': (width,), 'n2': (width,), 'qkv': (3 * width, width),
              'out': (width, width), 'ff1': (2 * width, width), 'ff2': (width, 2 * width)}
    if parameters.keys() != shapes.keys() or any(tuple(parameters[k].shape) != shape for k, shape in shapes.items()):
        raise ValueError('exact decoder parameter schema required')
    normalized = F.layer_norm(x, (width,), parameters['n1'])
    qkv = F.linear(normalized, parameters['qkv'])
    q, k, v = [part.reshape(batch, length, heads, width // heads).transpose(1, 2)
               for part in qkv.chunk(3, dim=-1)]
    scores = q @ k.transpose(-2, -1) / math.sqrt(width // heads)
    causal = torch.ones(length, length, dtype=torch.bool, device=x.device).tril()
    attention = torch.softmax(scores.masked_fill(~causal, float('-inf')), dim=-1) @ v
    joined = attention.transpose(1, 2).reshape(batch, length, width)
    residual = x + F.linear(joined, parameters['out'])
    hidden = F.layer_norm(residual, (width,), parameters['n2'])
    hidden = F.gelu(F.linear(hidden, parameters['ff1']))
    return residual + F.linear(hidden, parameters['ff2'])

About this algorithm

How Project: build a pre-norm decoder block and audit its gradients works

The idea

GPT-style models are one unit stacked many times, the decoder block. It has two sub-layers, causal self-attention and a feed-forward network, and each is wrapped the same way: normalise the input, compute an update, add the update back to the unnormalised input. That pre-norm residual layout keeps a direct path from input to output, which helps deep stacks train.

decoder_block(x, parameters, heads) builds it from six raw tensors. One qkv matrix produces queries, keys and values together. They are split into heads, scored with scaled dot products, and masked with a lower-triangular causal matrix so that a position attends only to itself and earlier positions. The heads are joined, projected by out and added to x; then ff1, GELU and ff2 form the second update.

How it works

  1. Check that x is a nonempty [B, T, D] tensor, that heads divides D, and that parameters has exactly the six expected names and shapes.
  2. Apply layer_norm with weight n1, project with qkv, split the result into three chunks and reshape each to [B, heads, T, D / heads].
  3. Compute scores = q @ k.transpose(-2, -1) / sqrt(D / heads).
  4. Fill positions above the diagonal with negative infinity using the causal mask, apply softmax, and multiply by v.
  5. Rejoin the heads to [B, T, D] and form residual = x + linear(joined, out).
  6. Normalise residual with n2, apply ff1, GELU and ff2, and return residual plus that result.

What it costs

Attention
O(T²·D)
Linear layers
O(T·D²)
Scores kept
heads × T × T

Every position scores every other position in each head, so attention grows with the square of the sequence length, while the linear layers grow in step with it.

Where it is used

  • GPT-2 moved layer normalisation to the input of each sub-block, which is the pre-norm layout built here.
  • Andrej Karpathy's nanoGPT produces queries, keys and values from a single linear layer and splits the result, like this Lab's qkv.
  • PyTorch's nn.MultiheadAttention stores a combined in_proj_weight of shape [3D, D], matching the qkv parameter.

Watch out for

  • Adding the attention update to the normalised tensor instead of the original x, which breaks the identity path through the block.
  • Masking after the softmax, or filling with zero instead of negative infinity, so future positions still receive attention weight.
  • Scaling the scores by sqrt(D) instead of the head width, sqrt(D / heads).