Module contents
Lesson 4 of 22Core 100 min

Deriving the attention backward pass by hand

Derive the row-wise softmax vector-Jacobian product and chain it through matrix products to obtain attention gradients. Implement and check the backward pass, study saturation, and analyze activation memory.

After this lesson you can

  • Derive the row-wise softmax vector-Jacobian product.
  • Obtain matrix expressions for dQ, dK, and dV and verify their shapes.
  • Implement masked attention backward and verify it using finite differences.
  • Calculate attention activation memory as a function of batch size, heads, and sequence length.
  • Explain how saturated attention attenuates gradients to queries and keys.

Before you start

Traversing attention backward

A GPT written in NumPy does not receive an automatic backward pass: the loss contribution must be returned to queries, keys, and values. The forward pass is a short sequence of operations, but an omitted scale factor or a misplaced transpose can produce apparently correct gradient shapes and faulty training. We will derive each step and then check it in two independent ways.

InteractiveThe gradient travels backward through attention

dO = Incoming gradient

1.0000.200-0.3000.7000.200-1.0000.5000.100
step 1 of 6
NodedO
Shape4 × 2
Play or advance step by step. Each panel contains values calculated for a particular four-position attention example; the shape and formula change with the node.

The matrices in this figure are an explicit example with two features, four positions, and a fixed output gradient. Colors show sign and relative magnitude within each matrix; do not compare intensity between steps as if they shared the same scale. The backward pass sums contributions that converge on the shared input, but first we study Q, K, and V as independent arguments.

Graph and shapes

For one head, Q∈RTq×dkQ\in\R^{T_q\times d_k}, K∈RTk×dkK\in\R^{T_k\times d_k}, and V∈RTk×dvV\in\R^{T_k\times d_v}. A fixed mask is expressed by bias BB, which is zero or −∞-\infty:

S=QK⊤dk+B,P=softmax⁡(S),O=PV.S=\frac{QK\T}{\sqrt{d_k}}+B,\qquad P=\softmax(S),\qquad O=PV.

Softmax acts row-wise, so S,P∈RTq×TkS,P\in\R^{T_q\times T_k} and O∈RTq×dvO\in\R^{T_q\times d_v}. We assume at least one valid key per query and do not use dropout. The causal mask is fixed and is not differentiated as a parameter. With batch and head dimensions, the same formulas act on the last two axes; in this lab Q, K, and V have exactly the same leading axes, while the mask may be broadcast. If a trainable input is broadcast, its gradient must sum over the broadcast dimensions.

We use Xˉ=∂L/∂X\bar X=\partial L/\partial X for a scalar loss LL. The vector-Jacobian product propagates an output perturbation without forming the full Jacobian. With the Frobenius convention  ⁣dL=⟨Xˉ, ⁣dX⟩\dd L=\langle\bar X,\dd X\rangle, differentiation means finding the coefficient of each differential.

Row-wise softmax VJP

For a row pi=esi/∑jesjp_i=e^{s_i}/\sum_j e^{s_j}, the previous lesson obtained Jij=pi(δij−pj)J_{ij}=p_i(\delta_{ij}-p_j). Multiplying by the incoming gradient pˉi\bar p_i and rearranging the sum,

sˉj=∑ipˉipi(δij−pj)=pj(pˉj−∑ipipˉi).\bar s_j=\sum_i\bar p_i p_i(\delta_{ij}-p_j) =p_j\left(\bar p_j-\sum_i p_i\bar p_i\right).

The row-wise softmax VJP is calculated in matrix form without constructing Jacobians:

Sˉ=P⊙(Pˉ−rowsum⁡(P⊙Pˉ)),\bar S=P\odot\left(\bar P-\operatorname{rowsum}(P\odot\bar P)\right),

where rowsum retains one column for broadcasting over that row’s keys. The cost is O(Tk)O(T_k) per row, compared with O(Tk2)O(T_k^2) if an explicit Jacobian is formed. Each row of Sˉ\bar S sums to zero because the probabilities sum to one. This checks a useful property, although it is insufficient to verify every component.

Matrix products

From O=PVO=PV it follows that  ⁣dO=( ⁣dP)V+P( ⁣dV)\dd O=(\dd P)V+P(\dd V). Applying the VJP of a contraction to each term,

Vˉ=P⊤Oˉ,Pˉ=OˉV⊤.\bar V=P\T\bar O,\qquad \bar P=\bar O V\T.

The shapes are Tk×dvT_k\times d_v and Tq×TkT_q\times T_k. After the softmax VJP, attention backpropagation continues through S=QK⊤/dk+BS=QK\T/\sqrt{d_k}+B:

Qˉ=SˉKdk,Kˉ=Sˉ⊤Qdk.\bar Q=\frac{\bar S K}{\sqrt{d_k}},\qquad \bar K=\frac{\bar S\T Q}{\sqrt{d_k}}.

Check the dimensions: Qˉ\bar Q is Tq×dkT_q\times d_k and Kˉ\bar K is Tk×dkT_k\times d_k. When Tq≠TkT_q\ne T_k, forgetting the transpose of Sˉ\bar S generally does not even fit. If Q, K, and V come from the same input XX, gradients through the three projections add toward XX; they are not three independent inputs to the final model. Broadcasting also requires reducing any broadcast axis when returning gradients to the original shape.

For a forbidden key, Pij=0P_{ij}=0, so the formula gives Sˉij=0\bar S_{ij}=0. There is no need to multiply by the mask again provided the weights were constructed correctly and every row has a valid key. A completely empty mask remains a separate case, as in the previous lesson: the formula does not repair a NaN softmax. If BB is a learnable finite bias rather than fixed, its gradient is Sˉ\bar S, summed over broadcast axes.

Saturation and memory

InteractiveWhen softmax saturates
00.20.40.60.8p10.705p20.259p30.035

The Jacobian rows and columns correspond to the three logits.

0.208−0.183−0.025−0.1830.192−0.009−0.025−0.0090.034
1.0
Norm of dS0.4013
Scale the logits of one row. The figure shows probabilities, the Jacobian, and its VJP norm for a fixed incoming gradient.

Gradient saturation occurs when a unique maximum dominates: PP approaches one-hot and diag⁡(p)−pp⊤\diag(p)-pp\T approaches zero. The path to scores, queries, and keys is then attenuated for a bounded incoming gradient. This does not imply that Vˉ=P⊤Oˉ\bar V=P\T\bar O is zero: the winning value can still receive a gradient. Nor does it imply that all gradients in a whole network vanish, since other paths may exist.

InteractiveHow much memory does attention save?
010203040Q2K2V2S32P32O2

The bars show MiB. The cache total excludes S and O because they can be recomputed.

1
8
10
64
T1024
Q, K, V, P cache38.0 MiB
Hypothetical reference8 GiB
Change batch, heads, length, dimension, and type. Compare the Q, K, V, and P cache with the hypothetical 8 GiB reference; S and O appear as additional costs if materialized.

Activation memory depends on the implementation. For square self-attention and dk=dv=dd_k=d_v=d, Q, K, and V together have 3BHTd3BHTd elements and P has BHT2BHT^2. Saving Q, K, V, and P suffices for the backward pass above; also saving S and O is an additional choice, not a universal requirement. Bars count tensors without parameters, gradients, workspace, or fragmentation. P exceeds Q, K, and V together when T>3dT>3d; against one alone the threshold is T>dT>d. The 8 GiB reference is hypothetical and does not identify the device used in the tests.

FlashAttention computes exact attention in blocks and avoids materializing the full quadratic matrix in high-capacity memory; its backward pass recomputes block information. Recomputation changes the compute-memory trade-off, not the definition of attention. Actual savings depend on implementation, precision, and shape.

Lab: VJP and finite differences

The following implementation stores only Q, K, V, and P. The file attention_core.py provides the same functions as a reusable module. Lesson 11 keeps its GPT self-contained: its attention_back function uses the same equations within projections and heads, without depending on that file.

[ ]Forward and backward from scratchBrowser
import numpy as np
def attention_forward(q, k, v, allowed):
    if q.shape[:-2] != k.shape[:-2] or k.shape[:-2] != v.shape[:-2]:
        raise ValueError('Q, K y V necesitan los mismos ejes de lote y cabeza')
    if q.shape[-1] != k.shape[-1] or k.shape[-2] != v.shape[-2]:
        raise ValueError('Dimensiones de clave o valor incompatibles')
    scores = q @ np.swapaxes(k, -1, -2) / np.sqrt(q.shape[-1])
    allowed = np.broadcast_to(np.asarray(allowed, dtype=bool), scores.shape)
    if not np.all(allowed.any(axis=-1)):
        raise ValueError('Cada consulta necesita al menos una clave válida')
    scores = np.where(allowed, scores, -np.inf)
    e = np.exp(scores - scores.max(axis=-1, keepdims=True))
    p = e / e.sum(axis=-1, keepdims=True)
    return p @ v, (q, k, v, p)
def attention_backward(dout, cache):
    q, k, v, p = cache
    dv = np.swapaxes(p, -1, -2) @ dout
    dp = dout @ np.swapaxes(v, -1, -2)
    ds = p * (dp - np.sum(dp * p, axis=-1, keepdims=True))
    scale = np.sqrt(q.shape[-1])
    return ds @ k / scale, np.swapaxes(ds, -1, -2) @ q / scale, dv
[ ]Central check in float64Browser
rng = np.random.default_rng(1804)
q = rng.normal(size=(2,3)); k = rng.normal(size=(3,3)); v = rng.normal(size=(3,2))
g = rng.normal(size=(2,2)); mask = np.arange(3)[None,:] <= np.arange(2)[:,None]
out, cache = attention_forward(q,k,v,mask)
analytic = attention_backward(g,cache)
def loss(): return np.sum(attention_forward(q,k,v,mask)[0] * g)
eps=1e-5
for name,arr,grad in zip(('Q','K','V'),(q,k,v),analytic):
    fd=np.zeros_like(arr)
    for idx in np.ndindex(arr.shape):
        old=arr[idx]; arr[idx]=old+eps; plus=loss(); arr[idx]=old-eps; minus=loss(); arr[idx]=old
        fd[idx]=(plus-minus)/(2*eps)
    error=np.max(np.abs(fd-grad))
    print(name,'error máximo:',error)
    assert error < 1e-8

The example has Tq=2T_q=2 and Tk=3T_k=3 to make the transpose of Sˉ\bar S visible. Gradient checking uses float64 and a scalar loss with fixed Oˉ\bar O. Repeat with several seeds, masks, and step sizes ε\eps: if ε\eps is too small, cancellation in subtraction can dominate; if large, truncation error is no longer negligible. One numerical case does not replace the derivation.

Autograd and GPU memory

The local cell redefines the VJP to be independent of Pyodide state. It compares Q, K, and V in float64 with PyTorch autograd, including rectangular attention and a mask; then it measures the increase in peak memory during forward and backward passes of dense float32 attention. The counter measures tensor memory allocated by the process, not all reserved memory or other processes’ load. The mask and inputs already exist before resetting the peak; subsequent temporaries, results, and gradients do count.

[ ]Autograd and peak memoryLocal GPU
import gc, numpy as np, torch
assert torch.cuda.is_available(), 'Este experimento necesita CUDA'
rng=np.random.default_rng(1804)
q=rng.normal(size=(2,2,3,4)); k=rng.normal(size=(2,2,5,4)); v=rng.normal(size=(2,2,5,3)); g=rng.normal(size=(2,2,3,3))
allowed=np.arange(5)[None,:] <= np.arange(3)[:,None]
s=q @ np.swapaxes(k,-1,-2)/np.sqrt(q.shape[-1]); s=np.where(allowed,s,-np.inf)
e=np.exp(s-s.max(axis=-1,keepdims=True)); p=e/e.sum(axis=-1,keepdims=True)
dp=g @ np.swapaxes(v,-1,-2); ds=p*(dp-(dp*p).sum(axis=-1,keepdims=True))
own=(ds@k/np.sqrt(4),np.swapaxes(ds,-1,-2)@q/np.sqrt(4),np.swapaxes(p,-1,-2)@g)
qt,kt,vt=[torch.tensor(a,device='cuda',requires_grad=True) for a in (q,k,v)]
mt=torch.tensor(allowed,device='cuda'); gt=torch.tensor(g,device='cuda')
st=(qt@kt.transpose(-1,-2))/np.sqrt(4); pt=torch.softmax(st.masked_fill(~mt,-torch.inf),dim=-1)
((pt@vt)*gt).sum().backward()
for name,a,b in zip(('dQ','dK','dV'),own,(qt.grad,kt.grad,vt.grad)):
    error=np.max(np.abs(a-b.cpu().numpy())); print(name,'error máximo:',error); assert error<1e-10
del qt,kt,vt,gt,st,pt; gc.collect(); torch.cuda.synchronize()
for T in [128,256,512,1024,2048]:
    q=torch.randn(1,4,T,32,device='cuda',requires_grad=True)
    k=torch.randn_like(q,requires_grad=True); v=torch.randn_like(q,requires_grad=True)
    mask=torch.ones(T,T,dtype=torch.bool,device='cuda').tril(); torch.cuda.synchronize()
    base=torch.cuda.memory_allocated(); torch.cuda.reset_peak_memory_stats()
    p=torch.softmax((q@k.transpose(-1,-2)/32**0.5).masked_fill(~mask,-torch.inf),dim=-1)
    out=p@v; out.square().mean().backward(); torch.cuda.synchronize()
    print('T:',T,'incremento pico MiB:',(torch.cuda.max_memory_allocated()-base)/2**20)
    del q,k,v,mask,p,out; gc.collect(); torch.cuda.synchronize()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Do not compare those peaks with the theoretical cache as if they were the same quantity: temporaries, gradients, and outputs overlap at the peak. The relationship with T2T^2 is a trend for this dense implementation; fused kernels can have a different memory curve. A shared GPU can vary measurements and available memory.

Exercises

Proof
Prove: The VJP of a softmax row can be evaluated in linear time.
0
Use J_ij = p_i (δ_ij - p_j) and an incoming gradient u.

Step 1 of 2. What is component j of the VJP?

Numeric
Calculate in MiB the memory for P with B=8, H=12, T=2048 and float32, materializing every entry.
Quiz
For the described backward pass, which cache computes derivatives without reconstructing P?
Code
Implement backward(dout, cache) with cache=(q,k,v,p). Inputs are not broadcast against each other and p already contains zeros in forbidden positions. Return dQ, dK, dV.
import numpy as np
def backward(dout, cache):
  pass
Shift+Enter to run
Key idea
Attention backward chains two product VJPs with the linear-time softmax VJP. Saving the probability matrix simplifies calculation but costs quadratic memory; recomputation can reduce that memory at the expense of additional work.