Module contents
Lesson 8 of 22Core 105 min

The transformer block: residual stream, normalization and feed-forward network

Assemble a transformer block from attention, position-wise feed-forward networks, residual connections, and normalization. Study gradients, rank collapse, parameter counts, and compute costs.

After this lesson you can

  • Assemble a pre-norm block with multi-head attention, MLP, layer normalization, residuals, and backward propagation.
  • Explain the residual stream as a communication channel to which each sublayer adds its contribution.
  • Compare post-norm and pre-norm initialization gradients and warmup behavior.
  • Explain rank collapse in pure attention and the role of residual connections.
  • Count parameters and FLOPs per token using the 12·L·d² approximation.

Before you start

A stream that is read and written

An attention layer mixes information across positions; a position-wise network transforms what reaches each one. The question is how to stack many such operations without erasing what came before. The residual stream is the sequence of width-dd vectors passing through the network. Each branch reads that stream and adds a write of the same shape. It is not a channel preserving all data intact: writes may reinforce, modify, or cancel components.

InteractiveOne stream and two writes
−0.500.51x10.3536x2−0.4144x30.741x40.8851Component
3
Readout logit1.139
Two-class predictionA
Advance through six blocks and disable one branch. The model is an explicit toy function: attention permutes and scales components; the MLP applies tanh. The readout logit is x1 − x2 + 0.5 x3.

For a differentiable map FF, the Jacobian of x+F(x)x+F(x) is I+JF(x)I+J_F(x). The identity offers a direct gradient path, but does not guarantee that the product of many Jacobians has singular values near one: if F(x)=−xF(x)=-x, the total Jacobian is zero. The size, direction, and correlation of writes still matter. This connects with vanishing gradients, exploding gradients, and the spectrum of the Jacobian product.

The sum has another useful interpretation: if a branch writes nothing, the state passes through unchanged. If the branch writes a vector opposite to a state feature, it can erase it; if it writes in another direction, it can add information. For a model with multiple tokens, a position’s attention branch depends on the other positions allowed by its mask, while the MLP receives each row separately. Both return T×dT\times d and share the same addition point, although their internal shapes and dependencies on other rows differ.

Multi-head attention uses an output projection to write the sum of head contributions into the same residual space. The position-wise feed-forward network uses the same matrices at each token without directly mixing positions:

F(x)=W2 ϕ(W1x+b1)+b2,W1∈Rdff×d,W2∈Rd×dff.F(x)=W_2\,\phi(W_1x+b_1)+b_2,\qquad W_1\in\mathbb R^{d_{ff}\times d},\quad W_2\in\mathbb R^{d\times d_{ff}}.

A common expansion is dff=4dd_{ff}=4d with GELU; another possible activation is ReLU. If kr⊤k_r\T is row rr of W1W_1 and vrv_r is column rr of W2W_2, then F(x)=∑rϕ(kr⊤x+b1r)vr+b2F(x)=\sum_r\phi(k_r\T x+b_{1r})v_r+b_2. The first projection determines how strongly each write activates; the second stores its directions. This is a key-value memory analogy, not a guaranteed discrete lookup. Geva et al. studied learned patterns in specific models.

Why mixing without a residual path can erase differences

Attention with a weight matrix whose rows sum to one replaces each token with a mixture of values. If the matrix rows are equal and values match input vectors, all positions receive the same vector and the resulting matrix has rank at most one. Even if rows are not initially equal, compositions of mixtures can bring them closer.

InteractiveAttention and loss of diversity
12
0.7
Relative rank-one error0.00000
Change depth and Q and K scale, and add residual or MLP. The relative Frobenius error of the best rank-one approximation is calculated by power iteration. The simulation has six tokens and four components.

Rank collapse in pure attention has a precise theoretical version: Dong et al. prove a doubly exponential convergence bound toward token uniformity in their model of pure attention networks without residuals or MLPs, under their analysis’s assumptions and bounds. The result does not mean any isolated attention layer has rank one after one layer, or that adding a residual guarantees prevention of collapse in every network. In the figure Q and K matrices are deterministic and values are the identity; relative norm can also fall with a residual. The lab calculates error exactly with singular values, in a different simulation with its own seed.

In a simplified form of the multi-head result, if products of matrix norms for each head are bounded by β\beta and γ\gamma bounds the attention term defined in the paper, distance rLr_L to a matrix with identical rows satisfies a bound of the form rL≤C(3L−1)/2r03Lr_L\le C^{(3^L-1)/2}r_0^{3^L}, with C=4γβH/dkC=4\gamma\beta H/\sqrt{d_k}. If C>0C>0 is uniform and C r0<1\sqrt C\,r_0<1, the right-hand side tends to zero doubly exponentially. The bound alone does not ensure convergence for every r0r_0 or every unbounded sequence of weights. Its norm and residual are not exactly the figure’s rank-one Frobenius error.

The plotted error is σ22+⋯/σ12+σ22+⋯\sqrt{\sigma_2^2+\cdots}/\sqrt{\sigma_1^2+\sigma_2^2+\cdots} when the matrix is nonzero. A matrix can have rank one without identical rows: the theoretical uniformity result is more specific, since rows converge to the same vector. Rank-one error detects loss of linear diversity, but alone does not prove rows coincide. The simulation also shows the explicit mixing that leads to that uniformity.

Ordering normalization

The transformer block combines attention AA, network FF, and layer normalization N1,N2N_1,N_2. In pre-norm, with each operation preserving shape T×dT\times d,

u=x+A(N1(x)),y=u+F(N2(u)).u=x+A(N_1(x)),\qquad y=u+F(N_2(u)).

In post-norm, u=N1(x+A(x))u=N_1(x+A(x)) and y=N2(u+F(u))y=N_2(u+F(u)). These are different functions: normalization cannot be moved through an arbitrary sum or sublayer. The pre-norm and post-norm distinction also affects backward propagation. In pre-norm, each sum’s gradient has an identity path; in post-norm both paths pass through the normalization Jacobian. LayerNorm’s scale invariance has conditions and epsilon, as seen in its analysis.

To write the pre-norm backward pass, let gy=∂L/∂yg_y=\partial L/\partial y and let JJ denote the Jacobian of a function evaluated at the corresponding input. First propagate backward through the second sum:

gu=gy+JN2(u)⊤JF(N2(u))⊤gy.g_u=g_y+J_{N_2}(u)\T J_F(N_2(u))\T g_y.

Then propagate backward through the first:

gx=gu+JN1(x)⊤JA(N1(x))⊤gu.g_x=g_u+J_{N_1}(x)\T J_A(N_1(x))\T g_u.

In both expressions the first term comes through the identity. For attention, the Jacobian includes the value path and the query and key paths, including the softmax derivative. There is no need to construct it as a huge matrix: apply its transpose to the gradient using attention backward. The lab code applies that rule per head, recombines width dd, and also propagates gradients to every weight.

The pre-norm residual stream is not completely normalized at every addition; its magnitude can grow with depth, depending on correlations and branch scale, so a final normalization is often used before the head. “Can” matters: a sum of opposing writes can also reduce the norm. In post-norm each output is normalized before the next layer, subject to learned parameters and epsilon.

Xiong et al. analyze an initialization regime and find larger gradients near the output in post-norm; in their experiments pre-norm could train without warmup on several tasks. This does not prove every post-norm configuration fails without warmup or that pre-norm never needs it. The next test preserves a useful negative result: in this short task all four runs remain finite.

InteractiveObserved gradients and losses
  • Pre-norm
  • Post-norm
  • Pre, with warmup
  • Pre, without warmup
  • Post, with warmup
  • Post, without warmup
12
150
Measured depth12
Compare QKV gradient norms at initialization for any depth from 2 to 48 and validation loss during 150 steps of four 12-layer models. Data are from one seed and a synthetic corpus, not a universal law; norms are rounded to four decimals.

Counting the cost

For attention with Q, K, V, and output width dd, there are 4d24d^2 weights. An FFN of width 4d4d has 2d(4d)=8d22d(4d)=8d^2 weights, so the block’s dominant term is 12d212d^2. With LL blocks it is 12Ld212Ld^2, excluding embeddings and linear terms. The parameter and FLOP count depends on biases, normalization, tying, and scope; do not confuse parameters with operations.

InteractiveDecoder budget
010.0 M20.0 M30.0 M40.0 M50.0 M60.0 MAttention28.3 MMLP56.7 MNorms38.4 kEmbeddings39.4 M
12
768
12
3072
50257
1024
Parameters124 M
Approximate forward FLOPs per token266 M
Headsd/H = 64
Adjust layers, widths, vocabulary, and context. The model counts tied token embeddings once, positions, biases, and norms. T fixes both positional table size and processed length. Cost uses an approximate causal pair count and excludes softmax and normalization.

Counting multiplication and addition as two FLOPs, a forward approximation per token is 2N+2LTd2N+2LTd, if NN approximately represents weights used in dense projections including the output head and a triangular count of causal pairs is used. Lookup embeddings are not a dense multiplication; using total parameters for NN is an approximation. An implementation that computes the full square matrix may pay approximately twice as much for the two attention multiplications. Softmax, normalizations, and hardware details are omitted. As TT grows, attention cost cannot be ignored.

The count follows directly from shapes. Four attention projections have d2d^2 weights each; the MLP has d dffd\,d_{ff} in each direction. For a matrix of TT tokens, calculating QK scores and mixing values each cost approximately 2T2d2T^2d FLOPs in a square multiplication. If a kernel exploits the causal half, the cost of both operations per sequence is approximately 2T2d2T^2d, or 2Td2Td per token, per layer. This approximation ignores the triangular-mask diagonal, relevant for short sequences. A kernel that computes and discards the upper triangle does not obtain that saving merely by applying a logical mask.

For GPT-2 small, L=12L=12, d=768d=768, dff=3072d_{ff}=3072, V=50257V=50257, and T=1024T=1024. The figure also offers GPT-2 medium with 24 layers and width 1024; configuration values can be checked in small and medium. With tied weights, biases, and LayerNorm, the count is L(12d2+13d)+Vd+Td+2dL(12d^2+13d)+Vd+Td+2d. Linear terms represent branch biases and scales and the final norm. Calculate the total and approximate cost in the exercises and compare with the rounded figure of 124 million. Actual cost depends on the kernel and what is counted.

NumPy lab: forward and backward

Build a bias-free block to isolate the calculation, with two heads, LayerNorm without learned scale, exact GELU, and residuals. The code saves values needed for backward; xx is stored as rows. Softmax and LayerNorm derivatives are applied per row, and matrix gradients sum over positions. The test checks every element of the input and six matrices using central differences.

[ ]Pre-norm block and backward passBrowser
import numpy as np
from scipy.special import erf

def ln(x,eps=1e-5):
    centered=x-x.mean(-1,keepdims=True)
    inv=1/np.sqrt((centered**2).mean(-1,keepdims=True)+eps)
    return centered*inv,inv

def ln_back(g,z,inv):
    return inv*(g-g.mean(-1,keepdims=True)-z*(g*z).mean(-1,keepdims=True))

def gelu(x): return 0.5*x*(1+erf(x/np.sqrt(2)))
def gelu_grad(x): return 0.5*(1+erf(x/np.sqrt(2)))+x*np.exp(-x*x/2)/np.sqrt(2*np.pi)

def attention(x,Wq,Wk,Wv,Wo,heads=2):
    t,d=x.shape;dh=d//heads
    q=(x@Wq).reshape(t,heads,dh).transpose(1,0,2)
    k=(x@Wk).reshape(t,heads,dh).transpose(1,0,2)
    v=(x@Wv).reshape(t,heads,dh).transpose(1,0,2)
    scores=q@k.transpose(0,2,1)/np.sqrt(dh)
    scores-=scores.max(-1,keepdims=True); p=np.exp(scores);p/=p.sum(-1,keepdims=True)
    concat=(p@v).transpose(1,0,2).reshape(t,d)
    return concat@Wo,(x,q,k,v,p,concat,Wq,Wk,Wv,Wo)

def attention_back(g,cache):
    x,q,k,v,p,concat,Wq,Wk,Wv,Wo=cache;t,d=x.shape;heads,_,dh=q.shape
    dWo=concat.T@g;dc=(g@Wo.T).reshape(t,heads,dh).transpose(1,0,2)
    dp=dc@v.transpose(0,2,1);dv=p.transpose(0,2,1)@dc
    ds=p*(dp-(dp*p).sum(-1,keepdims=True))
    dq=ds@k/np.sqrt(dh);dk=ds.transpose(0,2,1)@q/np.sqrt(dh)
    dq=dq.transpose(1,0,2).reshape(t,d);dk=dk.transpose(1,0,2).reshape(t,d);dv=dv.transpose(1,0,2).reshape(t,d)
    return dq@Wq.T+dk@Wk.T+dv@Wv.T,(x.T@dq,x.T@dk,x.T@dv,dWo)

def block_forward(x,weights):
    Wq,Wk,Wv,Wo,W1,W2=weights
    z,iv1=ln(x);a,ac=attention(z,Wq,Wk,Wv,Wo)
    u=x+a;v,iv2=ln(u);hidden=v@W1;g=gelu(hidden);y=u+g@W2
    return y,(z,iv1,ac,u,v,iv2,hidden,g,W1,W2)

def block_backward(dy,cache):
    z,iv1,ac,u,v,iv2,hidden,g,W1,W2=cache
    dW2=g.T@dy;dh=(dy@W2.T)*gelu_grad(hidden);dW1=v.T@dh
    du=dy+ln_back(dh@W1.T,v,iv2)
    dz,attn_grads=attention_back(du,ac)
    dx=du+ln_back(dz,z,iv1)
    return dx,(*attn_grads,dW1,dW2)

def demo():
    rng=np.random.default_rng(11);x=rng.normal(size=(3,4)); weights=[rng.normal(0,.2,s) for s in [(4,4)]*4+[(4,8),(8,4)]]
    up=rng.normal(size=x.shape);y,cache=block_forward(x,weights);dx,dw=block_backward(up,cache)
    eps=1e-5
    def loss(): return float((block_forward(x,weights)[0]*up).sum())
    checks=[]
    for arr,grad in [(x,dx)]+list(zip(weights,dw)):
        worst=0.0
        for index in np.ndindex(arr.shape):
            old=arr[index];arr[index]=old+eps;lp=loss();arr[index]=old-eps;lm=loss();arr[index]=old
            worst=max(worst,abs((lp-lm)/(2*eps)-grad[index]))
        checks.append(worst)
    print('error máximo para x, Wq, Wk, Wv, Wo, W1, W2:',checks)
    assert max(checks)<1e-7
    return checks
[ ]Finite differencesBrowser
demo()

The next simulation computes the best rank-one approximation with SVD. It is independent of the widget’s generator: the figure uses the kit generator and the cell uses NumPy. Concrete values therefore need not match. Compare trends without turning a finite simulation into a proof of the theoretical bound.

[ ]Pure attention and residual: rank-one errorBrowser
import numpy as np

def collapse(residual=False,mlp=False,depth=12,scale=.7):
    rng=np.random.default_rng(43);x=rng.normal(size=(6,4));curve=[]
    for layer in range(depth+1):
        s=np.linalg.svd(x,compute_uv=False)
        curve.append(float(np.sqrt(np.sum(s[1:]**2))/np.linalg.norm(s)))
        if layer==depth: break
        Wq=rng.normal(0,scale/2,(4,4));Wk=rng.normal(0,scale/2,(4,4))
        logits=(x@Wq)@(x@Wk).T/2
        a=np.exp(logits-logits.max(axis=-1,keepdims=True));a/=a.sum(axis=-1,keepdims=True)
        y=a@x
        if residual:y=x+y
        if mlp:y=y+0.2*np.tanh(y)
        x=y
    return curve
for residual,mlp in [(False,False),(True,False),(True,True)]:
    values=collapse(residual,mlp)
    print('residual:',residual,'MLP:',mlp,'inicio:',values[0],'final:',values[-1])

Local lab: four training runs

Generate two corpora of synthetic sentences with different seeds, separating training and validation. They are independent samples from the same small grammar and can repeat sentences, so this validation does not measure generalization to a new grammar. The causal model uses 12 layers, width 32, four heads, and context 32. All four arms start with the same initialization seed per variant, use the same batches, and AdamW with maximum rate 0.001; warmup increases the rate linearly over 30 of 150 steps. Pre-norm adds final LayerNorm and therefore has 64 more parameters. Parameter counts are not exactly equalized. Validation uses a fixed batch that is not updated.

In the reference run on RTX 3060 with PyTorch 2.11.0+cu128, final validation losses were approximately 1.326 and 1.181 for pre-norm with and without warmup, and 1.290 and 1.146 for post-norm with and without warmup. None of the four diverges in this short experiment. Warmup delays learning at this rate and horizon: one cannot infer that it is harmful or unnecessary at another scale. The figure retains those data and initialization gradients, measured with another fixed batch seed. The depth sweep is not a training curve for deep models.

[ ]Prepare models and dataLocal GPU
import json, math, random
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F

assert torch.cuda.is_available(), 'Este experimento necesita CUDA'
device='cuda'; chars='abcdefghijklmnopqrstuvwxyz 0123456789.,\n'; V=len(chars)

def corpus(seed,n):
    rng=random.Random(seed)
    subjects=['ana','luis','marta','pablo','eva']
    verbs=['suma','lee','mira','copia','busca']
    nouns=['libros','datos','notas','numeros','mapas']
    text=''.join(f'{rng.choice(subjects)} {rng.choice(verbs)} {rng.choice(nouns)} {rng.randrange(100):02d}.\n' for _ in range(n))
    return torch.tensor([chars.index(c) for c in text],dtype=torch.long)
train=corpus(5,5000); valid=corpus(6,1000)

class Block(nn.Module):
    def __init__(self,d,h,pre):
        super().__init__(); self.h=h; self.pre=pre
        self.n1=nn.LayerNorm(d);self.n2=nn.LayerNorm(d)
        self.qkv=nn.Linear(d,3*d); self.out=nn.Linear(d,d)
        self.fc=nn.Linear(d,4*d);self.proj=nn.Linear(4*d,d)
    def attention(self,x):
        b,t,d=x.shape; q,k,v=self.qkv(x).chunk(3,dim=-1)
        q,k,v=[a.reshape(b,t,self.h,d//self.h).transpose(1,2) for a in (q,k,v)]
        a=F.scaled_dot_product_attention(q,k,v,is_causal=True)
        return self.out(a.transpose(1,2).reshape(b,t,d))
    def forward(self,x):
        if self.pre:
            x=x+self.attention(self.n1(x)); return x+self.proj(F.gelu(self.fc(self.n2(x))))
        x=self.n1(x+self.attention(x)); return self.n2(x+self.proj(F.gelu(self.fc(x))))

class Model(nn.Module):
    def __init__(self,L=12,d=32,h=4,pre=True,T=32):
        super().__init__(); self.token=nn.Embedding(V,d);self.pos=nn.Embedding(T,d)
        self.blocks=nn.ModuleList([Block(d,h,pre) for _ in range(L)])
        self.final=nn.LayerNorm(d) if pre else nn.Identity();self.head=nn.Linear(d,V,bias=False)
    def forward(self,x,y):
        T=x.shape[1]; z=self.token(x)+self.pos(torch.arange(T,device=x.device))[None,:,:]
        for block in self.blocks: z=block(z)
        logits=self.head(self.final(z))
        return F.cross_entropy(logits.reshape(-1,V),y.reshape(-1))

def batch(data,generator,b=16,T=32):
    starts=torch.randint(len(data)-T-1,(b,),generator=generator).tolist()
    x=torch.stack([data[i:i+T] for i in starts]).to(device)
    y=torch.stack([data[i+1:i+T+1] for i in starts]).to(device)
    return x,y

def run(pre,warm,steps=150,seed=10):
    torch.manual_seed(seed);torch.cuda.manual_seed_all(seed)
    model=Model(pre=pre).to(device); opt=torch.optim.AdamW(model.parameters(),lr=0.001)
    gen=torch.Generator().manual_seed(seed); vg=torch.Generator().manual_seed(123)
    vx,vy=batch(valid,vg,b=64)
    history=[]; initial_grad=[]
    for step in range(steps):
        x,y=batch(train,gen);opt.zero_grad(set_to_none=True);loss=model(x,y)
        if not torch.isfinite(loss): raise RuntimeError('Pérdida no finita')
        loss.backward()
        if step==0: initial_grad=[float(block.qkv.weight.grad.norm()) for block in model.blocks]
        lr=0.001*min(1,(step+1)/30) if warm else 0.001
        for group in opt.param_groups: group['lr']=lr
        opt.step()
        if step%10==0 or step==steps-1:
            with torch.no_grad(): val=float(model(vx,vy))
            history.append([step+1,float(loss.detach()),val])
    return {'pre':pre,'warm':warm,'steps':steps,'params':sum(p.numel() for p in model.parameters()),'initial_grad':initial_grad,'history':history}
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Train pre-norm with warmupLocal GPU
result = run(True,True)
print('pre-con-warmup', 'parámetros:',result['params'],'historial:',result['history'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Train pre-norm without warmupLocal GPU
result = run(True,False)
print('pre-sin-warmup', 'parámetros:',result['params'],'historial:',result['history'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Train post-norm with warmupLocal GPU
result = run(False,True)
print('post-con-warmup', 'parámetros:',result['params'],'historial:',result['history'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Train post-norm without warmupLocal GPU
result = run(False,False)
print('post-sin-warmup', 'parámetros:',result['params'],'historial:',result['history'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Prepare the gradient profileLocal GPU
def gradient_profile(depth):
    for pre in (True,False):
        torch.manual_seed(10); torch.cuda.manual_seed_all(10)
        net=Model(L=depth,pre=pre).cuda()
        x,y=batch(valid,torch.Generator().manual_seed(123),b=16)
        net(x,y).backward()
        vals=[float(block.qkv.weight.grad.norm()) for block in net.blocks]
        print('capas:',depth,'pre:',pre,'normas:',[round(v,4) for v in vals])
        del net
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 2 to 4 layersLocal GPU
for depth in range(2,5):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 5 to 7 layersLocal GPU
for depth in range(5,8):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 8 to 10 layersLocal GPU
for depth in range(8,11):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 11 to 13 layersLocal GPU
for depth in range(11,14):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 14 to 16 layersLocal GPU
for depth in range(14,17):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 17 to 19 layersLocal GPU
for depth in range(17,20):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 20 to 22 layersLocal GPU
for depth in range(20,23):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 23 to 25 layersLocal GPU
for depth in range(23,26):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 26 to 28 layersLocal GPU
for depth in range(26,29):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 29 to 31 layersLocal GPU
for depth in range(29,32):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 32 to 34 layersLocal GPU
for depth in range(32,35):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 35 to 37 layersLocal GPU
for depth in range(35,38):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 38 to 40 layersLocal GPU
for depth in range(38,41):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 41 to 43 layersLocal GPU
for depth in range(41,44):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 44 to 46 layersLocal GPU
for depth in range(44,47):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Gradients for 47 to 48 layersLocal GPU
for depth in range(47,49):
    gradient_profile(depth)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Code
Implement block_forward(x, attention, ffn) and block_backward(dy, cache) for a pre-norm block. Each branch function receives a matrix and returns (output, backward), where backward accepts the output gradient and returns the input gradient. Return (y, cache) in forward and the gradient with respect to x in backward. LayerNorm and its backward pass are supplied; branches can represent multi-head attention or an FFN and preserve shape. Tests use differentiable branches and compare with central differences.
import numpy as np
def ln(x):
  c=x-x.mean(axis=-1,keepdims=True)
  inv=1/np.sqrt((c*c).mean(axis=-1,keepdims=True)+1e-5)
  return c*inv,inv
def ln_back(g,z,inv):
  return inv*(g-g.mean(axis=-1,keepdims=True)-z*(g*z).mean(axis=-1,keepdims=True))
def block_forward(x, attention, ffn):
  pass
def block_backward(dy, cache):
  pass
Shift+Enter to run
Numeric
For GPT-2 small, calculate the total using the formula in the text, including tied embeddings, positions, biases, and norms.
Numeric
With N = 124439808, L = 12, T = 1024, and d = 768, calculate 2N + 2LTd FLOPs per token.
Quiz
Which expression implements the first branch of a pre-norm block?
Quiz
In which variant can the residual stream grow through successive additions without normalization applied to the entire sum after each branch?
Proof
Prove: Derive the Jacobian of G(x) = x + F(x), with differentiable F.
0
Derivative matrices have the same dimensions because F returns a vector of x's width.

Step 1 of 3. What is the derivative of the identity?

Key idea
Attention and the MLP write to a residual stream; normalization placement changes both the function and its gradient. The dominant budget is 12Ld² weights, but for long contexts the cost of mixing positions must be added.