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.
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, , , and . A fixed mask is expressed by bias , which is zero or :
Softmax acts row-wise, so and . 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 for a scalar loss . The vector-Jacobian product propagates an output perturbation without forming the full Jacobian. With the Frobenius convention , differentiation means finding the coefficient of each differential.
Row-wise softmax VJP
For a row , the previous lesson obtained . Multiplying by the incoming gradient and rearranging the sum,
The row-wise softmax VJP is calculated in matrix form without constructing Jacobians:
where rowsum retains one column for broadcasting over that row’s keys. The cost is per row, compared with if an explicit Jacobian is formed. Each row of 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 it follows that . Applying the VJP of a contraction to each term,
The shapes are and . After the softmax VJP, attention backpropagation continues through :
Check the dimensions: is and is . When , forgetting the transpose of generally does not even fit. If Q, K, and V come from the same input , gradients through the three projections add toward ; 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, , so the formula gives . 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 is a learnable finite bias rather than fixed, its gradient is , summed over broadcast axes.
Saturation and memory
Gradient saturation occurs when a unique maximum dominates: approaches one-hot and approaches zero. The path to scores, queries, and keys is then attenuated for a bounded incoming gradient. This does not imply that 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.
Activation memory depends on the implementation. For square self-attention and , Q, K, and V together have elements and P has . 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 ; against one alone the threshold is . 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.
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, dvrng = 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-8The example has and to make the transpose of visible. Gradient checking uses float64 and a scalar loss with fixed . Repeat with several seeds, masks, and step sizes : if 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.
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=([email protected](-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(([email protected](-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()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 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
Step 1 of 2. What is component j of the VJP?
import numpy as np
def backward(dout, cache):
pass