Matrix calculus II: the matrix chain rule and backpropagation by hand
Understand exactly what loss.backward() computes: the chain rule between matrix spaces, why full Jacobians are never formed, and how vector-Jacobian products yield gradients for linear layers, nonlinearities, softmax and arbitrary contractions. Derive a complete batch-vectorized MLP by hand and write a PyTorch layer with custom backward.
After this lesson you can
- Apply the chain rule with differentials to compositions between matrix and tensor spaces.
- Compute VJPs and JVPs without forming Jacobians and estimate their cost versus the full Jacobian.
- Derive gradients of Y = XW + b, elementwise nonlinearities and softmax with cross-entropy.
- Obtain VJPs for arbitrary einsum contractions and broadcasting.
- Implement and check a full batch MLP backward pass and a custom PyTorch layer.
Before you start
- 02Matrix differentialGradient with respect to a matrixTrace trickLayout conventionsKronecker productVec operator and the vec trickEinstein notation and einsumTensor contractionBroadcastingOrthogonal projectionPositive definite matrixTransposeRank-one matrix and CR factorization
- 03Multivariable chain ruleJacobian matrix
- 07Softmax cross-entropy lossCross-entropy
Motivation: what loss.backward() computes
Training a network repeats three lines: loss = model(X, y), loss.backward() and optimizer.step(). The middle line leaves the gradient of the loss with respect to each set of weights in W.grad, as a matrix shaped like W. While it works, nobody looks inside. But in three situations, trust is not enough:
- Debugging. The loss does not fall, or falls then explodes, or a gradient becomes
NaN. To tell whether the problem is in the data, architecture or a numerically fragile operation, you need to know what each node computes in the backward pass. A bias gradient shaped(B, D)instead of(D,), orlogapplied to a probability that was already zero, is easy to spot when you know what should be there. - Writing custom layers. Attention with an unusual mask, a low-rank layer, a fused Triton kernel: once the forward pass is no longer a composition of standard operations, you must write the backward pass yourself. Much of FlashAttention consists of hand-written forward and backward passes that never store the attention matrix.
- Reasoning about cost. Why does backward cost roughly twice as much as forward? Why does training memory grow with batch size even though the weights stay the same? Why does nobody compute a network’s Jacobians? The answers are linear algebra, and that is what this lesson covers.
In the previous lesson you learned to differentiate a scalar function of a matrix using the differential: write , rotate with the trace trick, and read off the gradient. Now we chain functions between matrix spaces. The chain rule written with Jacobians produces absurdly large objects; backpropagation avoids forming them and instead applies the adjoint of each differential from output to input. By the end you will have derived every gradient of a batch-vectorized multilayer perceptron (MLP), trained it with your own backward pass and written a layer with a custom backward pass in PyTorch.
The chain rule between matrix spaces
Recall the starting point. A function is differentiable at if there is a linear map such that
and the differential is that linear part applied to a perturbation, . What matters now is that is a linear map between matrix spaces, not a table of numbers. Composing functions composes their linear parts.
Proof
Write and and use the Frobenius norm in every space. Since these are linear maps between finite-dimensional spaces, they are bounded: and likewise for . By assumption,
with and , where as its argument tends to (and ). Take , so . Then
The first remainder term is bounded by . For the second, if is small enough, , so ; in particular and . Both terms are , and is linear: it is the derivative of at .
∎This is the matrix chain rule, and in practice you use it without naming it: write in terms of , then in terms of , and substitute. It is the familiar multivariable chain rule without choosing coordinates.
In coordinates: giant Jacobians
If you choose coordinates, each linear map becomes a matrix. Flatten inputs and outputs with the vec operator, which stacks columns: the Jacobian matrix of is the matrix satisfying
and because composition of linear maps is multiplication of their matrices, the chain rule reads . To compute these matrices, use the Kronecker product identity
Apply it to the most important deep learning function, , with (a batch of examples in rows) and . As a function of , , so
and as a function of , gives . The Jacobian has one row for each output entry and one column for each variable entry: its size is the product of the two sizes. With respect to the weights, has times as many entries as .
That factor is the number of entries in and is enormous in a real network. Calculate how much space it takes with realistic dimensions.
Three observations you will use throughout the lesson:
- The Jacobian is almost all zeros. is block diagonal: copies of along the diagonal and zeros elsewhere. The fraction of zeros is . But storing only the nonzeros does not save you: that would be copies of when all the information is already in one.
- Nobody needs the Jacobian. The optimizer needs , a matrix shaped like . The Jacobian is a tool for going from to , and can be applied without constructing it.
- Time also explodes. Multiplying a vector by a dense Jacobian of costs about operations, times more than the product replacing it, without counting the cost of reading tens of terabytes from memory.
JVP and VJP: the adjoint of the differential
There are two ways to use a linear map without writing its matrix: apply it, or apply its adjoint. Defining the adjoint requires the Frobenius inner product, , the same one used to define the gradient.
Existence and uniqueness follow from the same argument as for the gradient: is a linear form on , and every linear form is represented by a unique matrix under the Frobenius product. The coordinate formula comes from writing both sides with vec: . In the calculus module you saw these two operations with vectors, as JVP and VJP; with matrices nothing changes except that each object’s shape is preserved.
Notice the shapes: the JVP goes from input space to output space, like the forward pass; the VJP goes from output to input, backward. And that is exactly what the gradient needs.
Proof
By the chain rule, for every , and the gradient is the unique matrix with that property. For the chain, observe that the adjoint of a composition is the composition of the adjoints in reverse order: if and are composable linear maps, , hence . Applied to this yields the formula. In coordinates it is .
∎The recipe for the VJP of any operation is the trace trick with an incoming gradient instead of a scalar: write in terms of , form , rotate until is on the right, , and read off . This yields every rule in the lesson.
The cost of each mode
Suppose (inputs and outputs flattened) and evaluating costs . A JVP gives one column of (the derivative in one direction); a VJP gives one row. Both cost a small multiple of , as you will see layer by layer. Thus:
- Forward mode, which propagates JVPs, needs passes for the full Jacobian.
- Reverse mode, which propagates VJPs, needs passes.
A loss has and equal to the number of parameters, which may be . Reverse mode obtains the full gradient in one backward pass, at a cost bounded by a small multiple of the forward pass and independent of : the cheap gradient principle. Forward mode would need a billion passes. Conversely, for a function with few inputs and many outputs (for example, the trajectory of a dynamical system as a function of three parameters), forward mode wins. The general algorithms for both modes are studied in reverse-mode automatic differentiation in the numerical methods module.
Reverse mode has a cost: each node’s VJP needs forward values ( depends on ), which were calculated in the opposite direction. They must be stored during the forward pass. This activation memory grows with batch size and motivates techniques such as gradient checkpointing, which stores only some activations and recomputes the rest. You will see exactly what must be stored for each operation.
The linear layer
Every network consists of linear layers interleaved with elementwise operations, so this is the rule you will use most often. With the batch in rows, as in PyTorch,
where is the matrix with in every row: bias broadcasting written as a product.
These are the linear layer gradients. You prove the first two formulas with differentials in the exercise below. The bias formula takes one line: , so (the trace of a number is the number itself, and can be transposed), that is, .
Step 1 of 4. What is ?
The same formula follows from the Jacobian without forming it. With and the rule ,
and with , . Read from right to left, the Kronecker identity turns the giant product into an ordinary-sized matrix product.
There are four readings of these formulas that specialists keep in mind:
- Shapes almost decide the formula. must have shape , and with () and () only one product has that shape: the one contracting the batch index, . Likewise for . But only almost: if , also has the correct shape and is wrong. Shapes rule out mistakes; they do not prove correctness.
- The weight gradient is a sum of rank-one matrices. : each example contributes a rank-one matrix, the outer product of the input and the output gradient. Thus the rank of is at most . The norm of each example’s gradient comes for free, , without forming a matrix: this is Goodfellow’s (2015) trick for per-example gradient clipping, needed for training with differential privacy.
- Propagating backward means multiplying by . The input gradient, , is the transposed linear layer applied to the gradient. A deep network multiplies the gradient by once per layer (and by the diagonal of each activation’s derivatives); the singular values of these products determine whether the gradient vanishes or explodes (vanishing gradients).
- The backward pass costs twice as much. The forward pass performs one product costing operations; the backward pass performs two of the same size, and . It needs for the second and for the first: each layer’s input is what must be stored.
Structured Jacobians
The linear layer has a giant but highly structured Jacobian (). So do the other pieces of a network: their Jacobians are diagonal, or diagonal plus a rank-one matrix. These are structured Jacobians, and their structure makes the VJP cost the same as the forward pass, instead of .
Elementwise nonlinearities
If is applied elementwise, . The Jacobian is the diagonal matrix , with side length equal to the number of entries, and the VJP is
because elementwise multiplication by a fixed matrix is self-adjoint: . What matters is what must be saved in the forward pass:
- ReLU: (at PyTorch takes ). It suffices to save the mask, one bit per entry. A neuron whose mask is always zero never receives a gradient: it is a dead ReLU.
- Sigmoid and tanh: and can be written using the output , so saving is enough; the next layer already needed it anyway.
- GELU: its derivative needs . Each activation determines what gets saved, and that takes memory.
Softmax
Softmax does not act elementwise: each probability depends on all logits, . Its Jacobian is dense but highly structured. Differentiate by taking logarithms, turning the quotient into a subtraction:
Proof
You prove point 1 in the exercise below. For 2, and , so ; moreover . Thus is the orthogonal projection onto , symmetric and idempotent.
For 3, . Since is positive semidefinite, if and only if , that is, if is a multiple of . All are positive, so is invertible and that is equivalent to . The rank follows from the rank theorem.
For 4, is the variance of when index is chosen with probabilities . For any constant , the variance is at most . Take , so for every . With the midpoint between the largest and smallest , each . With , where , the term vanishes and remains. The Rayleigh quotient of is bounded by both quantities.
∎Step 1 of 4. Where does symmetry come from?
Before looking at the consequences, experiment with it.
What you should have seen:
- One eigenvalue is always , with eigenvector : logits are defined only up to an additive constant. The other two are positive while no is zero.
- With two tied classes and the third negligible, the largest eigenvalue approaches , the universal bound. This is maximum sensitivity: a change in the difference between the two tied logits moves the probabilities substantially.
- When one logit dominates, the entire Jacobian fades, with . This is saturation: the gradient reaching barely passes to the logits. In transformer attention this occurs when a row of the attention matrix concentrates on one position, and is why dot products are divided by , as you will see in attention backpropagation.
- Temperature scales the Jacobian by , because has Jacobian with respect to . As falls that factor grows, but saturation wins: if the difference between the two largest logits is , decays like , much faster than grows.
The softmax VJP does not need the Jacobian. If ,
which costs : center with the mean weighted by , then multiply by . Forming would cost , and with the GPT-2 vocabulary, , that is about numbers, 10 GB in float32, per token. Batched, with one row per example, with : the rowwise softmax VJP rule used by attention’s backward pass.
Softmax with cross-entropy
In the last layer, softmax is rarely alone: it is followed by cross-entropy with a target distribution (one-hot or smoothed, with ). The composition simplifies spectacularly:
using . The gradient of the first term is and that of log-sum-exp is :
This is the gradient of softmax cross-entropy: prediction minus target. It also follows by chaining VJPs: the gradient of with respect to is (elementwise), and the softmax VJP turns it into . The two routes agree exactly, but not in floating point: the second divides by , and if a probability rounds to zero the quotient becomes infinity and the product NaN. The first divides by nothing and its entries lie in . That is why libraries fuse the operations (F.cross_entropy takes logits, not probabilities) and compute log-sum-exp by subtracting the maximum, using the log-sum-exp trick. With the mean loss of a batch of examples, the gradient with respect to the logits matrix is .
Contractions and broadcasting
Every multilinear tensor operation can be written in einsum notation: matrix multiplication, batched products, attention dot products and multi-head projections. Its backward pass has a rule that fits in one sentence.
Proof
By definition, , where the sum runs over indices not in . is linear in , so is the same expression with in place of , and
where each letter is summed only once over its range. Group terms by the values of the indices of :
The expression in parentheses is a function of the indices of , and is exactly the stated einsum. If a letter of does not appear in the parentheses, the expression does not depend on it: the gradient is constant along that axis. Since , the expression in parentheses is the gradient.
∎Remember this VJP of a contraction as follows: for the gradient of an operand, exchange its role with the output’s. Indices contracted by the forward pass become free, and the other operand’s free indices become contracted; indices everywhere (batch, heads) remain everywhere because each batch element is independent.
| Forward | Gradient of first | Gradient of second |
|---|---|---|
ik,kj->ij () | ij,kj->ik () | ik,ij->kj () |
bik,bkj->bij (batched) | bij,bkj->bik | bik,bij->bkj |
bhqd,bhkd->bhqk (scores ) | bhqk,bhkd->bhqd () | bhqk,bhqd->bhkd () |
i,j->ij () | ij,j->i () | ij,i->j () |
ij->i (sum rows) | extended along j |
The first row is the linear layer again, now without thinking. The last shows the solitary-index case: forward sums over j, and backward copies the gradient along j. The assumption that indices do not repeat within an operand matters: trace ii-> has gradient , with only on the diagonal, and that is not an einsum of the theorem’s form.
Forward broadcasting becomes a backward sum
The opposite of copying is summing, and this duality explains the bias gradient. Adding bias to a tensor of shape first applies the copy , , which is linear.
Proof
. The general case is identical: each entry of the smaller tensor appears in the inner product multiplied by every entry of to which it was copied. This is also a case of the previous theorem in a broad sense: the copy is d->btd, with indices only in the output (NumPy does not permit that einsum, but the proof’s formula still holds), and its VJP is btd->d.
This appears everywhere in a network. A linear layer’s bias is copied into the batch rows, and its gradient is , the sum over the batch. Positional embeddings, of shape , are added to each sequence in a batch , and their gradient sums over . Normalization scale parameters of shape sum over batch and positions. Libraries do this automatically (in PyTorch, with sum_to_size), but it is the most common mistake in a hand-written backward pass: if you forget the sum, the bias “gradient” has the shape of the output.
Complete example: a two-layer MLP by hand
You now have the three rules: linear layer, elementwise nonlinearity and softmax with cross-entropy. A classification MLP with one hidden layer, for a batch with one-hot labels , computes
with and . Backward applies the VJPs in reverse order, with rowwise:
Six lines, each a local rule knowing nothing about the rest of the network. That modularity makes automatic differentiation possible: each operation records in the forward pass what its VJP will need, and the backward pass traverses the graph in reverse applying them. That is backpropagation, and nothing more is needed.
Two calculations the interactive performs live deserve a look:
- Cost. Forward products total operations. Backward computes and (each the size of ) and : in total, somewhat less than twice as much because the first layer does not need . An intermediate layer in a deep network does need it, and the count is exactly twice as much. This is why a training step costs roughly three forward passes.
- Memory. Backward needs (for ), the mask of , (for ) and : about numbers, proportional to batch size. With a many-layer transformer and long sequences, this activation memory easily exceeds weight memory; checkpointing and kernels such as FlashAttention that recompute instead of storing target it.
Implementation from scratch
First, just once, form the full Jacobian of a tiny layer to see that Kronecker theory is literal and the VJP agrees. In NumPy, the column-major flattening used in the text is reshape(-1, order="F").
import numpy as np
rng = np.random.default_rng(0)
n, d, p = 4, 3, 2
X = rng.standard_normal((n, d))
W = rng.standard_normal((d, p))
G = rng.standard_normal((n, p)) # gradiente que llega a Y
V = rng.standard_normal((d, p)) # una dirección para el JVP
vec = lambda M: M.reshape(-1, order="F") # vec por columnas, como en el texto
J_W = np.kron(np.eye(p), X) # ∂vec(Y)/∂vec(W) = I ⊗ X
J_X = np.kron(W.T, np.eye(n)) # ∂vec(Y)/∂vec(X) = Wᵀ ⊗ I
print("forma de J_W:", J_W.shape, " no nulos:", np.count_nonzero(J_W), "de", J_W.size)
print("JVP: J_W vec(V) = vec(X V) ", np.allclose(J_W @ vec(V), vec(X @ V)))
print("VJP: J_Wᵀ vec(G) = vec(Xᵀ G) ", np.allclose(J_W.T @ vec(G), vec(X.T @ G)))
print("VJP: J_Xᵀ vec(G) = vec(G Wᵀ) ", np.allclose(J_X.T @ vec(G), vec(G @ W.T)))Now the MLP pieces. Each is a pair of functions: forward returns the output and a cache of what the VJP will need; the VJP receives the cache and output gradient and returns input gradients. To check a VJP without writing the full loss, use a trick: if with random , then , so the VJP with must match the gradient of that , compared with a centered difference in random directions in float64 (the previous lesson’s gradient checking).
def linear_fwd(X, W, b):
return X @ W + b, (X, W)
def linear_vjp(cache, G):
X, W = cache
return G @ W.T, X.T @ G, G.sum(axis=0) # ∇X, ∇W, ∇b
def relu_fwd(Z):
mask = Z > 0
return Z * mask, mask # solo se guarda la máscara
def relu_vjp(mask, G):
return G * mask
def softmax_ce_fwd(Z, y):
"""Entropía cruzada media con etiquetas enteras y, vía log-sum-exp estable."""
Zs = Z - Z.max(axis=1, keepdims=True)
logP = Zs - np.log(np.exp(Zs).sum(axis=1, keepdims=True))
B = Z.shape[0]
return -logP[np.arange(B), y].mean(), (np.exp(logP), y)
def softmax_ce_vjp(cache):
P, y = cache
B = P.shape[0]
G = P.copy()
G[np.arange(B), y] -= 1.0 # P − Y sin formar Y
return G / B
def dir_check(f, x, grad, h=1e-6, n_dirs=4, seed=1):
"""Peor error relativo entre <grad, V> y la diferencia centrada de f en direcciones aleatorias V."""
r = np.random.default_rng(seed)
worst = 0.0
for _ in range(n_dirs):
V = r.standard_normal(np.shape(x))
fd = (f(x + h * V) - f(x - h * V)) / (2 * h)
an = np.sum(grad * V)
worst = max(worst, abs(fd - an) / max(1e-15, abs(fd) + abs(an)))
return worst
B, Din, Dout = 8, 5, 4
X = rng.standard_normal((B, Din)); W = rng.standard_normal((Din, Dout)); b = rng.standard_normal(Dout)
C = rng.standard_normal((B, Dout)) # L = <C, salida>, así que ∇_salida L = C
gX, gW, gb = linear_vjp((X, W), C)
print("lineal ∇X ", f"{dir_check(lambda X_: np.sum(C * linear_fwd(X_, W, b)[0]), X, gX):.1e}")
print("lineal ∇W ", f"{dir_check(lambda W_: np.sum(C * linear_fwd(X, W_, b)[0]), W, gW):.1e}")
print("lineal ∇b ", f"{dir_check(lambda b_: np.sum(C * linear_fwd(X, W, b_)[0]), b, gb):.1e}")
Z = rng.standard_normal((B, Dout))
_, mask = relu_fwd(Z)
print("relu ", f"{dir_check(lambda Z_: np.sum(C * relu_fwd(Z_)[0]), Z, relu_vjp(mask, C)):.1e}")
y = rng.integers(0, Dout, B)
_, cache = softmax_ce_fwd(Z, y)
print("softmax-CE", f"{dir_check(lambda Z_: softmax_ce_fwd(Z_, y)[0], Z, softmax_ce_vjp(cache)):.1e}")All relative errors are of order or smaller: finite-difference rounding, not a bug. With the pieces verified, the MLP chains them in the order of the six equations.
def mlp_loss_grads(params, X, y):
W1, b1, W2, b2 = params
Z1, c1 = linear_fwd(X, W1, b1)
A1, m1 = relu_fwd(Z1)
Z2, c2 = linear_fwd(A1, W2, b2)
L, c3 = softmax_ce_fwd(Z2, y)
G2 = softmax_ce_vjp(c3) # (P − Y) / B
GA1, gW2, gb2 = linear_vjp(c2, G2)
GZ1 = relu_vjp(m1, GA1)
_, gW1, gb1 = linear_vjp(c1, GZ1) # ∇X no hace falta en la primera capa
return L, [gW1, gb1, gW2, gb2]
def init(D, H, K, seed=0):
r = np.random.default_rng(seed)
return [r.standard_normal((D, H)) * np.sqrt(2 / D), np.zeros(H),
r.standard_normal((H, K)) * np.sqrt(1 / H), np.zeros(K)]
Xs = rng.standard_normal((16, 6)); ys = rng.integers(0, 3, 16)
params = init(6, 7, 3, seed=1)
L, grads = mlp_loss_grads(params, Xs, ys)
for i, name in enumerate(["W1", "b1", "W2", "b2"]):
def f(P_, i=i):
ps = list(params); ps[i] = P_
return mlp_loss_grads(ps, Xs, ys)[0]
print(f"{name}: forma {grads[i].shape} = {params[i].shape} error relativo {dir_check(f, params[i], grads[i]):.1e}")Now what really matters: training with your own backward pass. Scikit-learn’s handwritten digits are 1797 images of ; with 64 hidden neurons and stochastic gradient descent with momentum, a few passes suffice.
from sklearn.datasets import load_digits
dig = load_digits()
Xd, yd = dig.data / 16.0, dig.target
perm = np.random.default_rng(0).permutation(len(yd))
tr, te = perm[:1347], perm[1347:]
mu, sd = Xd[tr].mean(axis=0), Xd[tr].std(axis=0) + 1e-6
Xtr, Xte = (Xd[tr] - mu) / sd, (Xd[te] - mu) / sd
ytr, yte = yd[tr], yd[te]
print("entrenamiento:", Xtr.shape, " test:", Xte.shape)params = init(64, 64, 10, seed=0)
vel = [np.zeros_like(p) for p in params]
lr, mom, bs = 0.05, 0.9, 32
for epoch in range(6):
order = np.random.default_rng(epoch).permutation(len(ytr))
for s in range(0, len(ytr), bs):
idx = order[s:s + bs]
L, g = mlp_loss_grads(params, Xtr[idx], ytr[idx])
for p, v, gp in zip(params, vel, g):
v *= mom
v -= lr * gp
p += v # actualización en el sitio
W1, b1, W2, b2 = params
acc = np.mean((np.maximum(Xte @ W1 + b1, 0) @ W2 + b2).argmax(axis=1) == yte)
if epoch % 2 == 0 or epoch == 5:
print(f"época {epoch:2d} acierto en test {acc:.3f}")
assert acc > 0.95Accuracy on the 450 test images exceeds 95% in the first epochs and ends above 97%. No line in that loop knows what a Jacobian is.
The second lab turns the contraction theorem into code. einsum_vjp receives the specification, operands and output gradient, then builds the einsum with exchanged roles for each operand; indices present only in that operand are recovered by broadcasting.
def einsum_vjp(spec, operands, grad_out):
"""Gradientes de L respecto a cada operando de C = einsum(spec, *operands), dado grad_out = ∇_C L."""
ins, out = spec.replace(" ", "").split("->")
terms = ins.split(",")
grads = []
for k, term in enumerate(terms):
assert len(set(term)) == len(term), "índices repetidos dentro de un operando: fuera del teorema"
others = [t for j, t in enumerate(terms) if j != k]
rest = [op for j, op in enumerate(operands) if j != k]
visible = set(out).union(*others)
kept = "".join(c for c in term if c in visible) # índices que el einsum puede producir
g = np.einsum(",".join([out] + others) + "->" + kept, grad_out, *rest)
# índices solo de este operando: el forward los sumaba; el gradiente es constante a lo largo de ellos
g = g.reshape([g.shape[kept.index(c)] if c in visible else 1 for c in term])
grads.append(np.broadcast_to(g, operands[k].shape).copy())
return grads
casos = {
"bij,bjk->bik": [(3, 4, 5), (3, 5, 2)], # producto por lotes
"bhqd,bhkd->bhqk": [(2, 3, 4, 5), (2, 3, 6, 5)], # puntuaciones de atención Q Kᵀ
"bhqk,bhkd->bhqd": [(2, 3, 4, 6), (2, 3, 6, 5)], # pesos de atención por valores
"bthd,hde->bte": [(2, 4, 3, 5), (3, 5, 7)], # proyección de salida que suma las cabezas
"i,j->ij": [(3,), (4,)], # producto exterior
"ijk,k->j": [(2, 3, 4), (4,)], # i solo en el primer operando
}
for spec, shapes in casos.items():
ops = [rng.standard_normal(s) for s in shapes]
C = rng.standard_normal(np.einsum(spec, *ops).shape)
gs = einsum_vjp(spec, ops, C)
errs = []
for k in range(len(ops)):
def f(x, k=k):
o = list(ops); o[k] = x
return np.sum(C * np.einsum(spec, *o))
errs.append(dir_check(f, ops[k], gs[k]))
print(f"{spec:17s}", " ".join(f"{e:.1e}" for e in errs))And the adjoint of broadcasting, the piece libraries use internally to return a gradient of the right shape to each tensor:
def sum_to_shape(G, shape):
"""VJP del broadcasting de un tensor de forma `shape` a la forma de G."""
G = G.sum(axis=tuple(range(G.ndim - len(shape)))) # ejes añadidos por la izquierda
stretched = tuple(i for i, s in enumerate(shape) if s == 1 and G.shape[i] != 1)
return G.sum(axis=stretched, keepdims=True) # ejes estirados desde 1
for xs, bs in [((2, 3, 4), (4,)), ((2, 3, 4), (3, 1)), ((2, 3, 4), (2, 1, 1)), ((5, 4), (1, 4))]:
x, bias = rng.standard_normal(xs), rng.standard_normal(bs)
C = rng.standard_normal(np.broadcast_shapes(xs, bs))
g = sum_to_shape(C, bs)
err = dir_check(lambda b_: np.sum(C * (x + b_)), bias, g)
print(f"x {str(xs):10s} + b {str(bs):10s} -> ∇b de forma {str(g.shape):10s} error {err:.1e}")The professional version: PyTorch
PyTorch exposes the lesson’s two operations as functions: torch.autograd.functional.jvp and vjp, plus jacobian, which forms the full Jacobian (one VJP per output or one JVP per input, depending on mode). First verify the theory. PyTorch flattens by rows, not columns, and with that ordering the identity changes sides: , so the Jacobian of with respect to is . The cell requires PyTorch and runs in the local lab.
import time
import torch
from torch.autograd.functional import jacobian, vjp, jvp
torch.manual_seed(0)
dev = "cuda" if torch.cuda.is_available() else "cpu"
n, d, p = 4, 3, 2
X = torch.randn(n, d, dtype=torch.float64, device=dev)
W = torch.randn(d, p, dtype=torch.float64, device=dev)
f = lambda W_: X @ W_
J = jacobian(f, W) # forma (n, p, d, p): ∂Y[i, j] / ∂W[k, l]
print("forma del jacobiano:", tuple(J.shape))
I = torch.eye(p, dtype=X.dtype, device=dev)
print("por filas: J = X ⊗ I ", torch.allclose(J.reshape(n * p, d * p), torch.kron(X, I)))
Jc = J.permute(1, 0, 3, 2).reshape(n * p, d * p) # aplanado por columnas, el vec del texto
print("por columnas: J = I ⊗ X ", torch.allclose(Jc, torch.kron(I, X)))
G = torch.randn(n, p, dtype=torch.float64, device=dev)
_, gW = vjp(f, W, G)
print("vjp = Xᵀ G ", torch.allclose(gW, X.T @ G))
V = torch.randn(d, p, dtype=torch.float64, device=dev)
_, jv = jvp(f, W, V)
print("jvp = X V ", torch.allclose(jv, X @ V))
# una capa todavía pequeña: jacobiano completo frente a un VJP
n, d, p = 64, 128, 128
X = torch.randn(n, d, device=dev); W = torch.randn(d, p, device=dev); G = torch.randn(n, p, device=dev)
f = lambda W_: X @ W_
for name, fn in [("jacobiano completo", lambda: jacobian(f, W, vectorize=True)), ("un VJP", lambda: vjp(f, W, G)[1])]:
fn() # calentamiento
if dev == "cuda": torch.cuda.synchronize()
t = time.perf_counter()
out = fn()
if dev == "cuda": torch.cuda.synchronize()
print(f"{name:20s} {(time.perf_counter() - t) * 1e3:8.2f} ms {out.numel() * out.element_size() / 1e6:8.2f} MB")npm run lab and open the connection link.Even for a toy layer ( by ) the Jacobian occupies 537 MB in float32, versus 0.07 MB for the VJP, and takes several times longer (around ten times on a consumer GPU), although at this size VJP time is almost entirely fixed operation-launch overhead. With torch.func you get the same in functional style (vjp, jvp, jacrev, jacfwd): jacrev constructs the Jacobian with one VJP per output, and jacfwd with one JVP per input, the mode choice from the cost section.
Next write a layer with a custom backward pass. A torch.autograd.Function has two static methods: forward computes output and saves in ctx what backward needs, and backward receives and returns one gradient per forward input (or None). We write the text’s linear layer and a low-rank layer , with and , the structure of LoRA. Its gradients follow from the trace trick: with , , and . The backward pass never forms , which would be an matrix.
import warnings
import torch
from torch.autograd import gradcheck
warnings.filterwarnings("ignore", message=".*no current CUDA context.*")
class LinearFn(torch.autograd.Function):
"""Y = X W + b con W de forma (d_in, d_out), como en el texto."""
@staticmethod
def forward(ctx, X, W, b):
ctx.save_for_backward(X, W)
return X @ W + b
@staticmethod
def backward(ctx, G):
X, W = ctx.saved_tensors
gX = G @ W.T if ctx.needs_input_grad[0] else None
gW = X.T @ G if ctx.needs_input_grad[1] else None
gb = G.sum(dim=0) if ctx.needs_input_grad[2] else None
return gX, gW, gb
class LowRankFn(torch.autograd.Function):
"""Y = X U Vᵀ + b sin formar nunca U Vᵀ: solo productos de rango r."""
@staticmethod
def forward(ctx, X, U, V, b):
T = X @ U # (B, r)
ctx.save_for_backward(X, U, V, T)
return T @ V.T + b
@staticmethod
def backward(ctx, G):
X, U, V, T = ctx.saved_tensors
GV = G @ V # (B, r): se reutiliza dos veces
gX = GV @ U.T if ctx.needs_input_grad[0] else None # como nn.Linear, solo si hace falta
return gX, X.T @ GV, G.T @ T, G.sum(dim=0) # ∇X, ∇U, ∇V, ∇b
dev = "cuda"
torch.manual_seed(0)
kw = dict(dtype=torch.float64, device=dev, requires_grad=True)
X, W, b = torch.randn(6, 5, **kw), torch.randn(5, 4, **kw), torch.randn(4, **kw)
U, V = torch.randn(5, 2, **kw), torch.randn(4, 2, **kw)
print("gradcheck LinearFn (float64, GPU):", gradcheck(LinearFn.apply, (X, W, b)))
print("gradcheck LowRankFn (float64, GPU):", gradcheck(LowRankFn.apply, (X, U, V, b)))
import time
def bench(make, steps=30):
torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
params, layer = make()
Xb = torch.randn(4096, 4096, device=dev)
for _ in range(3):
layer(Xb).sum().backward()
torch.cuda.synchronize(); t = time.perf_counter()
for _ in range(steps):
layer(Xb).sum().backward()
torch.cuda.synchronize()
ms = (time.perf_counter() - t) / steps * 1e3
return ms, sum(p.numel() for p in params), (torch.cuda.max_memory_allocated() - base) / 1e6
def make_linear():
lin = torch.nn.Linear(4096, 4096, device=dev)
return list(lin.parameters()), lin
def make_lowrank(r=64):
U = (torch.randn(4096, r, device=dev) / 64).requires_grad_()
V = (torch.randn(4096, r, device=dev) / 8).requires_grad_()
b = torch.zeros(4096, device=dev, requires_grad=True)
return [U, V, b], lambda X_: LowRankFn.apply(X_, U, V, b)
for name, mk in [("nn.Linear 4096→4096", make_linear), ("LowRankFn, r = 64", make_lowrank)]:
ms, n_par, peak = bench(mk)
print(f"{name:22s} {ms:7.2f} ms por paso {n_par / 1e6:6.2f} M parámetros pico {peak:7.1f} MB")npm run lab and open the connection link.gradcheck compares your backward pass with elementwise finite differences and passes in float64. The speed comparison follows from operation counts: with and , the low-rank layer forward performs of the dense layer’s operations and has 32 times fewer parameters (0.53 M versus 16.78 M). The full step, in which neither computes because the input does not request it (hence needs_input_grad), performs five skinny products versus two dense ones, of the operations, and time per step falls by a similar ratio. Peak memory drops less, because it is dominated by input and output, the same for both layers.
Common mistakes
Exercises
nn.Linear(d_in, d_out) stores weight with shape (d_out, d_in) and computes Y = X @ weight.T + bias for a batch X of shape (B, d_in). If G is the loss gradient with respect to Y, what does backward() leave in weight.grad?softmax_vjp(p, dy): given probabilities p = softmax(z) and gradient dy with respect to p, both shaped (..., K) (softmax along the last axis), return the gradient with respect to z with the same shape, rowwise. Do not form the Jacobian: tests include a case with . Hidden tests compare with the explicit Jacobian at small sizes.import numpy as np
def softmax_vjp(p, dy):
# p, dy: forma (..., K). Devuelve dx con la misma forma, sin formar matrices K x K.
passmlp_grads(X, Y, W1, b1, W2, b2) for the MLP , , with loss . X is (B, D), Y is (B, K) with rows summing to 1 (one-hot or smoothed), W1 is (D, H), b1 is (H,), W2 is (H, K) and b2 is (K,). Return the tuple (dW1, db1, dW2, db2) with parameter shapes. Hidden tests compare with float64 finite differences.import numpy as np
def mlp_grads(X, Y, W1, b1, W2, b2):
# forward: guarda lo que necesitará el backward
# backward: aplica los VJP en orden inverso
passSummary
- Chain rule: . In coordinates, , and with the Jacobian of with respect to is : times the size of the weights.
- VJP: . The gradient is the VJP of the output gradient, and in a chain VJPs are applied in reverse order. One reverse pass gives a scalar loss’s gradient with respect to all parameters, at the cost of storing activations.
- Linear layer: , , . Two products the size of the forward pass.
- Structured Jacobians: elementwise activations have diagonal Jacobians and VJP ; softmax has , symmetric positive semidefinite, with null space and VJP ; with cross-entropy, .
- Contractions and broadcasting: an einsum’s VJP is another einsum with operand and output roles exchanged; forward broadcasting becomes a sum over stretched axes in the backward pass.