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 NoneInspect 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'])