Slide, then Match: Backpropagation by Hand Without Chasing Indices

Autograd lets you train a network without ever deriving a gradient, but it cannot tell you what a custom backward pass should look like, or why yours is wrong. We distill matrix differential calculus into a procedure that lets a student, with only single-variable calculus and a first course in linear algebra, derive gradients by hand without the index tracking that modern layers make unmanageable. The procedure covers every layer of seven modern open-weight LLMs, including Llama, Gemma 3, and DeepSeek-V3, and we propose it as the way to teach backpropagation.

Why we still teach backpropagation the hard way

If we ask a room of ML students to derive the backpropagation gradient of a layer they have never seen before, most of them will reach for one of two tools.

First is index tracking, which is the method used by most deep learning classes whenever a mathematically rigorous derivation is needed. Write out every matrix product as an indexed sum, push a partial derivative through each sum and somehow line up the indices at the end. It does work, but it also buries the intuition and logic behind gradients under index bookkeeping across matrix operations. The error rate also climbs with every extra dimension.

Second is the “Gradient Recipe”. You look up the layer gradient in a table of known gradients, and copy the answer. This is fast, as long as the layer doesn’t deviate too far from the table, but tells you nothing about how matrix derivatives and backpropagation work.

These were adequate when “Neural Networks” meant stacks of fully connected layers, but are strained by the layers inside modern architectures, such as convolution, multi-head attention and mixture-of-experts. Some of these backward passes are written out in the literature, such as the attention backward in FlashAttention , but deriving them yourself with the above tools is miserable.

A third approach, becoming increasingly common in good courses and blog posts over the years, is to teach backpropagation as a chain of vector-Jacobian products (VJPs) . This is the right picture to think of, as autodiff engines really work this way. But this only tells you what gets computed and stops short of a procedure for working out a new layer’s backwards pass.

This post is about that procedure, which lets you derive the backward pass of a new layer yourself. We build a set of five rules, which will enable you to derive the gradients for the aforementioned layers without ever handling anything more complex than the 2D matrix. After that we check the rest of every popular open-sourced modern LLM, layer by layer, against the same rules. We will show that backpropagation through the entirety of gpt-oss, Llama, Gemma 3, DeepSeek, and Kimi needs nothing new beyond our five rules.

Why derive backpropagation gradients by hand though?

When autograd can calculate the gradients without you ever knowing how it works, and LLMs can produce the formula for you, what values does hand-derived gradients have? Because producing a formula is not the same as understanding it. Fused kernels, quantization tricks and new architectures all come with hand-written backward functions, as checking requires knowing what the answer should be and why. The formulas also explain things that are otherwise memorized as facts. Once you have the layers’ backward passes in front of you, you know why a training step costs about three times a forward pass, why activations dominate training memory, why attention divides its scores by the square root of the query-key dimension, why residual connections keep gradients alive, and why MoE models need load balancing. And in the case where gradients come out wrong, knowing what each block’s backward should be is how you find the broken block. We provide more details in What the derivations tell you.

The toolkit already exists

What’s ironic is that the right tools have been around for decades. Magnus & Neudecker’s Matrix Differential Calculus , originally written for statistics and econometrics, reduces most matrix gradient derivations to a few lines. You write out the differential of the loss, massage it into the Frobenius inner product \(\mathrm{tr}\{A^\top dX\}\), and read off \(A\) as the gradient.

The procedure has also been applied to deep learning directly. The MIT course Matrix Calculus (for Machine Learning and Beyond) teaches the coordinate-free view to undergraduates, treats the derivative as a linear operator on general vector spaces. Boué’s Deep learning for pedestrians works through convolutional networks and, more recently, transformers exactly in this style. Write the loss’s differential as a Frobenius inner product, expand it, apply a few product identities, and read off the gradient.

Our contributions

Building on these tools, we present the Slide-and-Match procedure, which contributes to machine learning pedagogy by:

We present the whole method in an interactive figure below. If every move already looks obvious, skip ahead to the boss battles, where we take on the harder layers. If not, the next few sections build each move one at a time, and we will come back to this figure once you have them.

Interactive. Pick a module and a target, then step through write out, slide, and match.

What you need to follow along

This is the complete set of mathematics the post requires, with nothing beyond first-year maths.

What you need Usually taught in
Matrix products, transposes, \((AB)^\top = B^\top A^\top\) Linear algebra I
The inner product, extended to arrays of any shape as a multiply-then-add of matching entries Linear algebra I
Properties of the inner product: (i) linear in each slot, (ii) symmetric, and (iii) \(\langle M, X\rangle = \langle N, X\rangle\) for every \(X\) forces \(M = N\) Linear algebra I
The trace and its cyclic property \(\mathrm{tr}\{ABC\} = \mathrm{tr}\{CAB\}\) Linear algebra I
The tangent line of a one-variable function, \(f(x + dx) \approx f(x) + f'(x)\,dx\) Calculus I

Nudges, drifts, and sensitivities

The Nudge-Drift framework

Popular teaching materials on backpropagation pass scalars to show how backpropagation works. In practice, layers pass vectors and matrices, often with millions of entries at once, and tracking each becomes impractical as the numbers grow. So we need a way to talk about a whole matrix’s worth of change at once. For this, we define two terms for any function \(Y = F(X)\).

The nudge \(dX\) is a small change to \(X\), in any direction. It has the same shape as \(X\).

The drift \(d_X Y\) is the change in \(Y\) that the nudge in \(X\) causes, to first order. It has the same shape as \(Y\). (If you know the formalism, the drift is the differential of \(F\) at \(X\), which is the Jacobian applied to the nudge. We never build the Jacobian. We only use what it does to \(dX\).)

As layers can have multiple inputs, we distinguish them using a subscript on the drift. When \(Y\) depends on several inputs, we nudge them one at a time, with its total drift being the sum of the drifts from each one

\[dY = d_{X_1} Y + d_{X_2} Y + \cdots.\]

When there is only one input, \(d_X Y\) is simply \(dY\).

For a linear map, the drift is easy and exact. If \(Y = AX\), then

\[F(X + dX) - F(X) = AX + A\,dX - AX = A\,dX,\]

so \(d_X Y = A\,dX\). A linear map’s drift is simply the map itself, applied to the nudge.

Sensitivities

In deep learning, the objective of training is to minimize a single number, the loss \(\mathcal L\). Every quantity in a network eventually feeds into it. Therefore, what we want to know is how a nudge in some quantity \(Z\) drifts a scalar. In the linear case, there is only one way that can look, whatever shape \(Z\) has:

Shape of \(Z\) How the loss drifts As an inner product
scalar \(z\) \(d_z \mathcal L = \delta_z\, dz\) \(\langle \delta_z, dz\rangle\)
vector \(\mathbf z\) \(d_{\mathbf z} \mathcal L = \delta_{\mathbf z}^\top d\mathbf z\) \(\langle \delta_{\mathbf z}, d\mathbf z\rangle\)
matrix \(Z\) \(d_Z \mathcal L = \operatorname{sum}(\delta_Z \odot dZ)\) \(\langle \delta_Z, dZ\rangle\)

In every row the loss’s response to a nudge is pinned down by a single object, \(\delta_Z\), with the same shape as \(Z\). We call it the sensitivity of the loss to \(Z\). We will sometimes call it blame, since each entry tells us how much that entry of \(Z\) is responsible for moving the loss.

The fact that the sensitivity always has the same shape as the thing it measures is the idea this whole post leans on. A weight matrix gets a sensitivity shaped like a weight matrix. A batch of activations gets a sensitivity shaped like a batch of activations. Whatever layout or dimension you are working in, the object you are hunting for looks like the thing you nudged.

Linearity is all you need

So far we only talked about linear maps. Then what about nonlinearities?

The idea is the oldest one in calculus. Zoom in far enough on a smooth function and it looks like a straight line. That is what a derivative is, whether you learned it from a tangent line in high school, from 3Blue1Brown’s Essence of Calculus , or in an analysis course. The drift \(d_X Y\) is therefore the difference \(F(X + dX) - F(X)\) linearized in \(dX\), as anything involving a product of two nudges is too small to matter when you zoom in.

A neural network is built from two kinds of operations, Linear and Elementwise-nonlinear. Linear operations include matrix multiplications, convolutions, adding bias terms, and their drift is exactly linear in the nudge. The nonlinearity lives entirely within activations, such as ReLU, tanh, or GELU, which apply a scalar function \(f: x \mapsto y\) to each entry independently. Therefore, the scalar tangent is all we need:

\[f(x + dx) \approx f(x) + f'(x)\,dx \quad\Rightarrow\quad dy = f'(x)\,dx.\]

Chain the two kinds of operations together and the loss’s drift is linear in any nudge, which means the sensitivity with respect to the loss exists for every layer.

The two linearization rules

We define two rules for deriving the linearized nudge-drift relation for neural network functions:

Rule Statement Why it holds
Linear \(F\) \(Y = F(X) \;\Rightarrow\; dY = F(dX)\) \(F(X + dX) - F(X) = F(dX)\) exactly
Elementwise-Nonlinear \(F\) (applies \(f\) to every entry) \(Y = F(X) \;\Rightarrow\; dY = F'(X)\odot dX\) The tangent line, entry by entry

Which way to turn the dials

Now that we have the sensitivity, which tells you how the nudge affects the drift, how can we use it to drift the loss in the direction of maximum decrease?

Recall that a dot product is large when two vectors point the same way and negative when they point opposite ways. This means that if you can only afford a nudge of a fixed size, the loss drops fastest when \(dX\) points directly against \(\delta_X\). So the best possible nudge is

\[dX = -\eta\, \delta_X\]

for some small step size \(\eta\). That is gradient descent, derived with nothing but the dot product.

Interactive. Drag the nudge around the sensitivity. The loss drops fastest when the nudge points straight against it.

Gradient descent is usually pictured as a ball rolling down a hilly landscape . The problem is that nobody can see that landscape when the weights have more than 3 numbers, so the intuition has nothing to hold on to. We enable a dimension-agnostic intuition of “Knobs and Dials” straight from the geometry of the dot product. A wall of a hundred million dials is no harder to picture than a wall of three.

Think of the parameters as a wall of dials, one per entry of \(W\), each marked in tiny ticks. The matching entry of \(\delta_W\) is a label on that dial stating how much and in which direction the loss moves per tick. Turn many dials at once and the loss moves by the sum of label times ticks, which is all \(\langle \delta_W, dW\rangle\) says. We therefore turn each dial against its label, in proportion to it. For example, if a label of \(0.1\) earns one tick down, a label of \(-0.4\) earns four ticks up and a label of \(0.05\) earns half a tick down. That exchange rate between label and ticks is the step size \(\eta\).

Backpropagation: Stacking sensitivities

So far we only have looked at how nudges, drifts and sensitivities work in functions with single outputs. We define such a function as a component. To understand how backpropagation happens in complex real-world neural networks, where components build modules and modules build the whole network, we need to understand how they work across components. In this section, we first see how components interact, either in series or in parallel, in the nudge-drift framework. Then, we formalize the backward pass of a module as the calculation of two sensitivities. One to update the module weights, and one to pass on to the previous module.

In series

Let \(Y = f(X)\). Suppose the loss depends on \(Y\), we know the sensitivity of the loss with respect to \(Y\) which is \(\delta_Y\), and we want to know what \(\delta_X\) is.

What we know is that if we nudge \(X\), that nudge drifts \(Y\) by \(d_X Y\). From the loss’s point of view, that drift is just a nudge in \(Y\) (A nudge does not specify a direction, any direction is allowed!), allowing us to reuse \(Y\)’s sensitivity:

\[d_X \mathcal L = \langle \delta_Y,\; d_X Y \rangle .\]

A drift becomes the next nudge. As \(d_X Y\) is some linear function of \(dX\), call it \(J(dX)\), all we have to do is rewrite the expression so the linear map acts on \(\delta_Y\) instead of on \(dX\):

\[\langle \delta_Y,\; J(dX) \rangle = \langle J^{*}(\delta_Y),\; dX \rangle ,\]

where \(J^{*}\) is defined as whatever function that makes the equality work. As the right-hand side has the defining form \(\langle \delta_X, dX\rangle\), \(\delta_X = J^{*}(\delta_Y)\). This allows us to evaluate a component series of any length: Start from the sensitivity we currently know, ask “which nudge caused this drift?”, substitute one layer, slide, and ask again.

In parallel

Suppose \(X\) feeds two quantities \(A = f(X)\) and \(B = g(X)\), and both feed the loss. Nudging \(X\) nudges both, and the loss moves to \(\mathcal L(A + dA,\, B + dB)\). To first order,

\[\mathcal L(A + dA, B + dB) \approx \mathcal L(A, B) + \langle \delta_A, dA\rangle + \langle \delta_B, dB\rangle + (\text{cross terms}).\]

The cross terms describe how a change in \(A\) alters the effect of a change in \(B\), and every one of them contains a factor of \(dA\) and a factor of \(dB\). A product of two small nudges is second order, so it drops out exactly like the leftover terms in the tangent line.

When a variable fans out, its sensitivity is the sum of the sensitivities carried back along each path. Carry each one back to \(X\) along its own path with the series rule, giving

\[d_X\mathcal{L}= \langle \delta_A, dA\rangle + \langle \delta_B, dB\rangle=\langle \delta_X^{A}, dX\rangle + \langle \delta_X^{B}, dX\rangle,\]

and use the fact that the inner product is linear in each slot:

\[\langle \delta_X^{A}, dX\rangle + \langle \delta_X^{B}, dX\rangle = \langle \delta_X^{A} + \delta_X^{B},\; dX\rangle \quad\Rightarrow\quad \delta_X = \delta_X^{A} + \delta_X^{B}.\]

This handles a fan-out of any width. Simply add up the sensitivities of parallel layers to get the total sensitivity.

In modules and whole networks

To see how this ultimately gives us the update rule for training neural networks, we need to formalize neural networks in the language that we have been using throughout this article.

We define a Module \(M\) as the unit building block of neural networks. It can be comprised of multiple components \(\mathcal{F}=\{f_1, \dots, f_n\}\), should take in Inputs \(\mathcal{X}=\{X_1, \dots, X_p\}\), spit out Outputs \(\mathcal{Y}=\{Y_1, \dots, Y_q\}\), and optionally have an updatable set of component Weights \(\mathcal{W}=\{W_1, W_2 \dots W_n\}\), which influences the input-output relation:

\[\mathcal{Y}=M(\mathcal{X}; \mathcal{W}).\]

For a module to update \(\mathcal{W}\) with \(\delta_{\mathcal{W}}=\{\delta_{W_1}, \dots, \delta_{W_n}\}\), all it needs is the sensitivity of the outputs with respect to the loss, \(\delta_{\mathcal{Y}}=\{\delta_{Y_1}\dots\delta_{Y_q}\}\). The series and parallel rules assemble everything else, from simple linear modules to attention and MoE modules.

A Neural Network is the complete composition of modules, stacked in series, in parallel, or both. It ends in a loss \(\mathcal L\), which turns the final outputs into a single number.

Consider a module somewhere in the middle of the network. The loss depends on its outputs only through the modules that come after it, so the only place it can get the output sensitivity \(\delta_{\mathcal Y}\) from is the modules it feeds. And the output of one module is the input of the next. If \(M^{(k)}\) feeds \(M^{(k+1)}\), then \(\mathcal Y^{(k)}\) and \(\mathcal X^{(k+1)}\) are the same quantities, so

\[\delta_{\mathcal Y^{(k)}} = \delta_{\mathcal X^{(k+1)}} .\]

This is the series rule applied to whole modules. If a module’s output feeds several later modules, each of them hands back an input sensitivity, and by the parallel rule the module adds them up.

This means a module has two things to compute in the backward pass. Given \(\delta_{\mathcal Y}\), it computes

\[\delta_{\mathcal Y} \;\longmapsto\; \big(\delta_{\mathcal W},\; \delta_{\mathcal X}\big),\]

where the weight sensitivity \(\delta_{\mathcal W}\) is what it keeps for its own update, and the input sensitivity \(\delta_{\mathcal X}=\{\delta_{X_1}, \dots, \delta_{X_p}\}\) is what it hands to the modules that produced its inputs. Both come from the routine we have been using. Nudge one weight, or one input, and write the loss’s drift through every output it reaches:

\[d_{W_i}\mathcal L = \sum_{j=1}^{q} \langle \delta_{Y_j},\; d_{W_i} Y_j\rangle = \langle \delta_{W_i},\; dW_i\rangle, \qquad d_{X_l}\mathcal L = \sum_{j=1}^{q} \langle \delta_{Y_j},\; d_{X_l} Y_j\rangle = \langle \delta_{X_l},\; dX_l\rangle .\]

The sum over outputs is the parallel rule. Getting from the middle expression to the right-hand one is the series rule, applied through the module’s components. To do this the module uses \(\delta_{\mathcal Y}\), its own weights, and the values it saw on the forward pass. It does not need to know what comes before it or after it.

Sensitivity calculation is then a single sweep of the modules in the reverse of the order they ran. Each module collects its output sensitivity from the ones it fed, computes its weight sensitivity and its input sensitivity, keeps the first, and passes the second back. When the sweep reaches the front of the network, every weight \(W_i\) in every module has its own \(\delta_{W_i}\). This sweep is backpropagation, also known as reverse-mode automatic differentiation.

Notice that the only things that cross a module’s boundary in the backward pass are an output sensitivity going in and an input sensitivity coming out. Therefore, if we derive the sensitivities of a module once, we can reuse the module without opening it ever again.

Slide-and-Match

The only thing missing now is how to compute the transition \(\langle \delta_Y,\; J(dX) \rangle = \langle J^{*}(\delta_Y),\; dX \rangle.\) Finding \(J^*\) for an arbitrary linear map is real work. Fortunately, neural networks do not use arbitrary linear maps. It either (i) multiplies by a matrix on the left or the right, (ii) multiplies entry by entry, or (iii) rearranges its entries. We show that for each of these, \(J^{*}\) can be written down by a simple rule that looks like a slide to the other side.

Trace and the inner product

The inner product we use everywhere is the dot product, extended to arrays of any shape, which multiplies matching entries and adds everything up by \(\langle A, B\rangle = \operatorname{sum}(A \odot B).\) Although this is the more efficient definition, we need a second one to establish the rules for \(J^*\):

\[\langle A, B\rangle = \mathrm{tr}\{A^\top B\}.\]

Proof. The \(j\)-th diagonal entry of \(A^\top B\) is the dot product of column \(j\) of \(A\) with column \(j\) of \(B\), so adding up the diagonal adds up every entrywise product.

A property of the trace makes this useful. The cyclic property, \(\mathrm{tr}\{ABC\} = \mathrm{tr}\{CAB\}\), states that components can be “merry-go-rounded” inside the trace.

Proof. \(\mathrm{tr}\{MN\} = \sum_i \sum_j M_{ij} N_{ji}\) does not change when the two sums are swapped, giving \(\mathrm{tr}\{MN\} = \mathrm{tr}\{NM\}\). Setting \(M = AB\) and \(N = C\) gives the cyclic property.

The three sliding rules

We define three rules for sliding a factor from one slot of the inner product to the other:

Rule Statement Why it holds
Sandwich \(\langle A, BXC\rangle = \langle B^\top A C^\top, X\rangle\) \(\langle A, BXC\rangle = \mathrm{tr}\{A^\top BXC\}\)
\(= \mathrm{tr}\{CA^\top BX\} = \mathrm{tr}\{(B^\top A C^\top)^\top X\}\)
\(= \langle B^\top A C^\top, X\rangle\) by the cyclic property
Hadamard \(\langle A, B\odot X\rangle = \langle B\odot A, X\rangle\) Entrywise, \(\sum a\,(b\,x) = \sum (b\,a)\,x\)
Permutation \(\langle A, \pi(X)\rangle = \langle \pi^{-1}(A), X\rangle\) for any fixed rearrangement \(\pi\) of entries, such as \(\langle A, X^\top\rangle = \langle A^\top, X\rangle\) Entrywise, rearranging both arrays the same way pairs up the same entries

Sandwich and Permutation cover the linear operations in a neural network (matrix products, rearrangements, selections), and Hadamard covers the elementwise ones. Every layer we checked needed nothing beyond these three. Below are notes on the cases you will meet most often.

Notes

Factor on only one side of the nudge. This can be handled by Sandwich with \(C = I\) or \(B = I\), where each case can be written as \(\langle A, BX\rangle = \langle B^\top A, X\rangle\) and \(\langle A, XC\rangle = \langle A C^\top, X\rangle\).

Transpose. The transpose is the rearrangement you will meet most, and the Permutation rule turns it into its own inverse, another transpose. The same rule handles a reshape, the split of a vector into attention heads, and their merge afterwards. Whatever rearrangement the forward pass applied, the backward pass undoes.

Scalars. A scalar has no side and is its own transpose, so it can sit anywhere, in front, behind, or in either slot.

Selection, deletion and duplication. Selecting some rows (an embedding lookup, or sending tokens to an expert), dropping a column, and copying a vector to several places (broadcasting a bias, or sharing one key among several query heads) move entries around without being rearrangements, but each is a multiplication by a 0/1 matrix, so Sandwich slides it like any other matrix. Their transpose does the opposite job. Where the forward pass selected, the backward pass puts the blame back in place and fills zeros elsewhere. Where the forward pass copied, the backward pass adds the copies’ blames. Copy forward, sum backward is the parallel rule again.

Concatenation. Concatenation follows the same idea. It is two 0/1 matrices side by side, so the sensitivity simply splits into column blocks \(A_1\) and \(A_2\) of \(A\) that line up with \(X\) and \(Y\), \(\langle A, [X \mid Y]\rangle = \langle A_1, X\rangle + \langle A_2, Y\rangle\).

Convolution. Convolution is multiplication by a large structured matrix (a Toeplitz matrix), and its shortcut, proved in its boss battle, is Sandwich for that matrix without ever building it.

Backpropagation by hand

The procedure: write out, slide, and match

Every derivation in the rest of the post only takes three steps. We write them for a weight \(W\) in a layer with output \(Z\). The same steps work for any input.

  1. Write out. Express \(d_W \mathcal L\) as one inner product whose only nudge is \(dW\).
    1. Forward. Write the layer’s forward pass with one named intermediate per operation, ending at the output \(Z\), whose sensitivity \(\delta_Z\) arrives from the next layer.
    2. Linearize. Nudge only \(W\) and rewrite each line as its drift, using the Linear and Elementwise rules. Lines that do not depend on \(W\) drop out.
    3. Substitute. Start from \(d_W \mathcal L = \langle \delta_Z,\, d_W Z\rangle\), which is the defining form of \(\delta_Z\) with \(Z\)’s drift as the nudge. Replace the drifts one line at a time, starting from the line nearest \(Z\), until the only nudge left is \(dW\).
  2. Slide. Use the sliding rules until \(dW\) stands alone in the right slot. The expression now reads \(\langle M, dW\rangle\).
  3. Match. This is the defining form \(\langle \delta_W, dW\rangle\), so \(\delta_W = M\).

Example 1: Linear layer

Take \(\mathbf z = W\mathbf x\), with the loss depending on \(\mathbf z\) and \(\delta_{\mathbf z}\) known.

Write-Out. As the forward rule is \(\mathbf z = W\mathbf x\), Nudging \(W\) results in \(d_W \mathbf z = dW\mathbf x\). Starting from the loss relation \(d_W \mathcal L = \langle \delta_{\mathbf z},\; d_W \mathbf z\rangle\), we replace the drift to get the nudge-drift relation between \(W\) and \(\mathcal{L}\):

\[d_W \mathcal L = \langle \delta_{\mathbf z},\; dW\, \mathbf x\rangle.\]

Slide. The vector \(\mathbf x\) sits to the right of the nudge, so Sandwich moves it across:

\[d_W \mathcal L = \langle \delta_{\mathbf z},\; dW\, \mathbf x\rangle = \langle \delta_{\mathbf z} \mathbf x^\top,\; dW\rangle \quad\Rightarrow\quad \delta_W = \delta_{\mathbf z} \mathbf x^\top .\]

Nudging \(\mathbf x\) instead drifts \(\mathbf z\) by \(W\,d\mathbf x\), and Sandwich gives:

\[d_{\mathbf x} \mathcal L= \langle \delta_{\mathbf z}, W\, d\mathbf x\rangle = \langle W^\top \delta_{\mathbf z}, d\mathbf x\rangle.\]

Match. Read off the left side of the inner product to get \(\delta_{\mathbf W} = \delta_{\mathbf z}\mathbf x^\top\) and \(\delta_{\mathbf x} = W^\top \delta_{\mathbf z}\).

With batched data

Classrooms usually write data as single columns, so data passes through a layer as \(Z=W\mathbf{x}\). Frameworks store data as batched rows for memory reasons, so the same layer appears in code as \(Z=XW\) where each row of \(X\) is data. Students who memorized “\(\delta_W=\delta_Z X^\top\)” now find every formula obsolete, and they end up re-deriving which side the transpose goes on by trial and error.

We need no additional rules. Take \(Z = XW\), with the loss depending on \(Z\) and \(\delta_Z\) known.

Write-Out. As the forward rule is \(Z=XW\), nudging \(W\) results in \(d_W Z = X\,dW\). Starting from the loss relation \(d_W\mathcal{L} = \langle \delta_Z, d_W Z \rangle\), we replace the drift to get the nudge-drift relation between \(W\) and \(\mathcal{L}\):

\[d_W \mathcal L = \langle \delta_Z,\; XdW\rangle.\]

Slide. The matrix \(X\) sits to the left of the nudge, so Sandwich moves it across:

\[d_W \mathcal L = \langle \delta_Z,\; XdW\rangle = \langle X^\top\delta_Z,\; dW\rangle\]

Nudging \(X\) instead drifts \(Z\) by \(dX\,W\), and Sandwich gives:

\[d_X\mathcal{L} = \langle \delta_Z, dXW \rangle = \langle \delta_Z W^\top, dX \rangle\]

Match. Reading off the left slots gives both sensitivities:

\[\delta_W=X^\top\delta_Z \ \text{and} \ \delta_X=\delta_ZW^\top.\]
A note on einsum.

If you write layers with einsum , you may already know a shortcut for its backward pass: the sensitivity of one operand is an einsum of the upstream sensitivity with the other operands, labeled with that operand’s indices. For C = einsum('ij,jk->ik', A, B), that gives sens_A = einsum('ik,jk->ij', sens_C, B), where sens_A holds \(\delta_A\). This is Sandwich written in indices, and its proof is the same single swap of a finite sum:

\[\langle \delta_C, dC\rangle = \sum_{ik} (\delta_C)_{ik} \sum_j dA_{ij} B_{jk} = \sum_{ij} dA_{ij} \Big(\sum_k(\delta_C)_{ik}B_{jk}\Big),\]

where the bracket is einsum('ik,jk->ij', sens_C, B). For contractions over many axes, einsum is often the cleaner notation. What the relabeling shortcut does not cover is everything that is not a contraction (activations, softmax, convolution, concatenation), the cases where an index disappears or repeats (a row sum, a trace), and fan-outs, where it has to be applied once per occurrence and then summed. The rest of this post covers those.

Example 2: Elementwise Activations

Take \(H = \Phi(Z)\), where \(\Phi\) applies a scalar function \(\phi\) to every entry of \(Z\) separately, \(H_{ij} = \phi(Z_{ij})\). Examples include ReLU, sigmoid, tanh, GELU, Swish. We write \(\Phi'\) for the same thing done with the derivative \(\phi'\). The loss depends on \(H\), and \(\delta_H\) is known.

Write-Out. As the forward rule is \(H = \Phi(Z)\), each entry of \(H\) depends only on the matching entry of \(Z\), so nudging \(Z\) results in \(d_Z H = \Phi'(Z) \odot dZ\). This is the single-variable derivative \(d\phi = \phi'(z)\,dz\), applied entry by entry. Starting from the loss relation \(d_Z \mathcal L = \langle \delta_H,\; d_Z H\rangle\), we replace the drift to get the nudge-drift relation between \(Z\) and \(\mathcal L\):

\[d_Z \mathcal L = \langle \delta_H,\; \Phi'(Z) \odot dZ\rangle.\]

Slide. The factor \(\Phi'(Z)\) multiplies the nudge elementwise, so Hadamard moves it across unchanged:

\[d_Z \mathcal L = \langle \delta_H,\; \Phi'(Z) \odot dZ\rangle = \langle \Phi'(Z) \odot \delta_H,\; dZ\rangle.\]

Match. Reading off the left slot gives the sensitivity

\[\delta_Z = \delta_H \odot \Phi'(Z).\]
A note on SwiGLU.

The feed-forward blocks of recent language models use SwiGLU, which looks more complicated than a single activation. It runs the input through two linear layers and multiplies the results elementwise, with Swish applied to one of them:

\[G = XW_g, \qquad U = XW_u, \qquad H = \Phi(G) \odot U, \qquad \phi(z) = \frac{z}{1 + e^{-z}} .\]

Everything except Swish is linear, and Swish is an elementwise activation, so we need no additional rules.

Write-Out. \(H\) is a product of two inputs, so nudging both gives one term per input:

\[d\mathcal L = \langle \delta_H,\; (\Phi'(G) \odot dG) \odot U\rangle + \langle \delta_H,\; \Phi(G) \odot dU\rangle.\]

Slide. Every factor is elementwise, so Hadamard moves each one across unchanged:

\[d\mathcal L = \langle \delta_H \odot U \odot \Phi'(G),\; dG\rangle + \langle \delta_H \odot \Phi(G),\; dU\rangle.\]

Match. Reading off the left slots gives both sensitivities:

\[\delta_G = \delta_H \odot U \odot \Phi'(G) \ \text{and} \ \delta_U = \delta_H \odot \Phi(G).\]

From here, \(G\) and \(U\) are batched linear layers, so Example 1 gives \(\delta_{W_g} = X^\top \delta_G\) and \(\delta_{W_u} = X^\top \delta_U\). The input \(X\) feeds both layers, so its two sensitivities add: \(\delta_X = \delta_G W_g^\top + \delta_U W_u^\top\).

Example 3: LoRA

Low-Rank Adaptation freezes a weight matrix \(W\) and learns a low-rank correction \(BA\). Take the paper’s column convention, \(Z = WX + BAX\), with the loss depending on \(Z\) and \(\delta_Z\) known. Since \(W\) is frozen, we only need \(\delta_A\) and \(\delta_B\).

Write-Out. As the forward rule is \(Z = WX + BAX\), nudging \(A\) leaves \(WX\) alone and results in \(d_A Z = B\,dA\,X\). Nudging \(B\) instead results in \(d_B Z = dB\,AX\). Starting from the loss relations \(d_A \mathcal{L} = \langle \delta_Z,\; d_A Z \rangle\) and \(d_B \mathcal{L} = \langle \delta_Z,\; d_B Z \rangle\), we replace the drifts to get the nudge-drift relations:

\[d_A \mathcal{L} = \langle \delta_Z,\; B\,dA\,X\rangle \quad \text{and} \quad d_B \mathcal{L} = \langle \delta_Z,\; dB\,AX\rangle.\]

Slide. For \(dA\), the matrix \(B\) sits to the left of the nudge and \(X\) sits to the right, so Sandwich moves both across:

\[d_A \mathcal{L} = \langle \delta_Z,\; B\,dA\,X\rangle = \langle B^\top \delta_Z X^\top,\; dA\rangle.\]

For \(dB\), the product \(AX\) sits to the right of the nudge, and Sandwich gives:

\[d_B \mathcal{L} = \langle \delta_Z,\; dB\,AX\rangle = \langle \delta_Z (AX)^\top,\; dB\rangle = \langle \delta_Z X^\top A^\top,\; dB\rangle.\]

Match. Reading off the left slots gives both sensitivities:

\[\delta_A = B^\top \delta_Z X^\top \ \text{and} \ \delta_B = \delta_Z X^\top A^\top.\]

A three-matrix chain took one line per sensitivity. In the batched row convention of Example 1 the layer reads \(Z = XW + XAB\), and the same two steps give \(\delta_A = X^\top \delta_Z B^\top\) and \(\delta_B = A^\top X^\top \delta_Z\). The same chain reappears inside DeepSeek’s attention, which compresses its keys and values through a low-rank bottleneck.

Boss battles

To test the procedure we need opponents that defeat the recipe table. Here are three, in rising order of difficulty, and one more for you to try.

Boss battle 1: Convolution

Take an image \(I\) convolved with a filter \(K\) of odd width, zero-padded so the output has the same size, \(Z = K * I\), with the loss depending on \(Z\) and \(\delta_Z\) known. Treat any out-of-range index as zero, which is what padding does, and write \(\tilde B\) for an array flipped through its center, \(\tilde B_a = B_{-a}\) (in 2D, a 180° rotation).

Lemma (Convolution rule). A convolution factor crosses the inner product flipped:

\[\langle A * B,\; C \rangle = \langle A,\; C * \tilde B \rangle .\]

This is Sandwich for the convolution’s matrix, written so that the matrix never has to be built.

Proof

In 1D:

\[\begin{aligned} \langle A * B,\, C\rangle &= \sum_p \Big(\textstyle\sum_a A_a B_{p-a}\Big) C_p &&\text{expand the definition of } A * B \\ &= \sum_a A_a \Big(\textstyle\sum_p C_p\, B_{p-a}\Big) &&\text{swap the order of a finite sum} \\ &= \sum_a A_a\, (C * \tilde B)_a = \langle A,\, C * \tilde B\rangle &&\text{since } B_{p-a} = \tilde B_{a-p} . \end{aligned}\]

Expand once, reorder once, recognize the flip. In 2D the filter carries a second spatial index through identical steps, and the 1D flip becomes the 180° rotation.

Write-Out. As the forward rule is \(Z = K * I\) and convolution is linear in each input, nudging \(K\) results in \(d_K Z = dK * I\). Nudging \(I\) instead results in \(d_I Z = K * dI = dI * K\), since convolution commutes. Starting from the loss relations, we replace the drifts to get:

\[d_K \mathcal L = \langle \delta_Z,\; dK * I\rangle \quad \text{and} \quad d_I \mathcal L = \langle \delta_Z,\; dI * K\rangle.\]

Slide. Symmetry puts the convolution in the left slot, and the Convolution rule moves the fixed factor across, flipped:

\[d_K \mathcal L = \langle dK * I,\; \delta_Z\rangle = \langle dK,\; \delta_Z * \tilde I\rangle \quad \text{and} \quad d_I \mathcal L = \langle dI * K,\; \delta_Z\rangle = \langle dI,\; \delta_Z * \tilde K\rangle.\]

Match. Symmetry once more, and reading off the left slots gives both sensitivities:

\[\delta_K = \delta_Z * \tilde I \ \text{and} \ \delta_I = \delta_Z * \tilde K,\]

with \(\delta_K\) evaluated at the filter’s offsets only.

Deep learning frameworks actually compute cross-correlation, \(Z = K \star I\) with \(Z_p = \sum_a K_a I_{p+a}\), which is convolution with the flipped kernel, \(K \star I = \tilde K * I\). Putting \(\tilde K\) in place of \(K\) above gives \(\delta_I = \delta_Z * K\), a convolution with the unflipped kernel (often called a full convolution), and \(\delta_K = \delta_Z \star I\), a cross-correlation with the input. Either way, the backward pass does the opposite of what the forward pass did, and that is the flip.

Intuition: why the kernel flips

Both results are the fan-out rule at scale. A single kernel weight \(K_a\) is reused at every output position, so its sensitivity is the sum of the blame collected at every position it touched, each weighted by the input pixel it multiplied there. That sum is a correlation of \(\delta_Z\) with \(I\), which is a convolution with the flipped image.

Each input pixel \(I_j\) also fans out: it feeds every output whose window covers it. On the forward pass, output \(p\) reads from input \(p - a\) with weight \(K_a\), an offset of \(-a\). On the backward pass, input \(j\) sends blame to output \(j + a\) along the same wire with the same weight, an offset of \(+a\). Running the wires backward flips the sign of every offset, which is the rotated kernel that tutorials usually state as a fact to remember.

Boss battle 2: Multi-head attention

Attention is where hand derivations usually stop. To see why, we first look at how a careful paper does it. Noci et al. differentiate a single attention layer, and getting there takes vectorized matrices, Kronecker products, an \(n^2 \times n^2\) softmax Jacobian and a commutation matrix, none of which appears in the final gradients.

We never build them, as the backward pass turns out to be a relay of the same slide-and-match moves we have used throughout. We start with one head, then extend to multiple heads and a batch.

Setup (one head, rows are tokens). For a single attention head, the forward pass computes:

\[\begin{aligned} Q &= XW_Q, & K &= XW_K, & V &= XW_V, \\ S &= \tau QK^\top, & P &= \text{softmax}(S), & O &= PV, \end{aligned}\]

with \(\tau = 1/\sqrt{d_k}\) and softmax applied row-wise to \(S\).

The matrix dimensions are:

\[X \in \mathbb{R}^{N \times d_{\text{model}}}, \qquad Q, K \in \mathbb{R}^{N \times d_k}, \qquad V, O \in \mathbb{R}^{N \times d_v}, \qquad S, P \in \mathbb{R}^{N \times N}.\]

Given \(\delta_O\), our goal is to find \(\delta_{W_Q}\), \(\delta_{W_K}\), \(\delta_{W_V}\), and \(\delta_X\) by walking the computation graph \(X \to (Q, K, V) \to S \to P \to O\) backward, one operation at a time.

Step 1: Through \(O = PV\). Since \(O = PV\) has two inputs, \(P\) and \(V\), we apply two quick rounds of Write-Out, Slide, and Match:

\[\begin{aligned} \underbrace{d_V \mathcal{L} = \langle \delta_O,\; P\,dV \rangle}_{\text{Write-Out}} &= \underbrace{\langle P^\top \delta_O,\; dV \rangle}_{\text{Slide}} \quad \Rightarrow \quad \underbrace{\delta_V = P^\top \delta_O}_{\text{Match}}, \\[6pt] \underbrace{d_P \mathcal{L} = \langle \delta_O,\; dP\,V \rangle}_{\text{Write-Out}} &= \underbrace{\langle \delta_O V^\top,\; dP \rangle}_{\text{Slide}} \quad \Rightarrow \quad \underbrace{\delta_P = \delta_O V^\top}_{\text{Match}}. \end{aligned}\]

Step 2: Through \(P = \text{softmax}(S)\). This is the only nonlinear step in attention. Rather than reaching for a memorized backward rule or a Jacobian table, we derive it directly using the exact same Write-Out, Slide, and Match steps we have used so far. Because softmax acts independently on each row of \(S\), we first work through a single row \(p = \text{softmax}(s)\) and then stack the result back into matrix form.

Write-Out. Write \(e = \exp(s)\) and \(c = \langle \mathbf 1, e \rangle= \sum_k e^{s_k}\) for the normalizer, so that

\[p = \frac{1}{c}e.\]

This makes softmax look like the building blocks we already have: \(e\) is elementwise, \(c\) is a sum (linear) of its entries, and \(p\) is the vector \(e\) times the single number \(1/c\). So we need nothing beyond the one-variable rules \(d(e^u) = e^u\,du\) and \(d(1/u) = -du/u^2\), and the product rule, where we nudge each factor on its own and add the two drifts.

Nudging \(s\) by \(ds\) gives:

\[de = e \odot ds \text{ (by the elementwise rule) and } dc = \langle \mathbf 1, e \odot ds \rangle = \langle e, ds \rangle.\]

Applying the product rule to \(p = \frac{1}{c}e\) yields the drift:

\[dp = \frac{1}{c}de - \frac{dc}{c^2}e = p \odot ds - \Big\langle \frac{e}{c},\; ds\Big\rangle\, \frac{e}{c} = p \odot ds - \langle p, ds \rangle p.\]

or, collecting both terms,

\[p \odot (ds - \langle p, ds \rangle \mathbf 1).\]

Adding a constant to every entry of \(s\) does not change \(p\), so only the part of \(ds\) that differs from the weighted average \(\langle p, ds \rangle\) moves the output. Substituting this drift into the loss relation \(d_s \mathcal{L} = \langle \delta_p, dp \rangle\) gives:

\[d_s \mathcal{L} = \langle \delta_p,\; p \odot (ds - \langle p, ds \rangle \mathbf 1) \rangle.\]

Slide. Using linearity of the inner product, we first split \(d_s \mathcal{L} = \langle \delta_p,\; p \odot (ds - \langle p, ds \rangle \mathbf{1}) \rangle\) into two terms:

\[d_s \mathcal{L} = \langle \delta_p,\; p \odot ds \rangle - \langle \delta_p,\; \langle p, ds \rangle p \rangle.\]

For the first term, the Hadamard rule slides \(p\) across to give \(\langle p \odot \delta_p,\; ds \rangle\). For the second term, pulling out the scalar \(\langle p, ds \rangle\) and moving the scalar \(\langle p, \delta_p \rangle\) inside yields \(\langle \delta_p,\; \langle p, ds \rangle p \rangle = \langle p, ds \rangle \langle p, \delta_p \rangle = \langle \langle p, \delta_p \rangle p,\; ds \rangle\). Recombining both terms isolates \(ds\) on the right:

\[d_s \mathcal{L} = \langle p \odot \delta_p - \langle p, \delta_p \rangle p,\; ds \rangle = \langle p \odot (\delta_p - \langle p, \delta_p \rangle \mathbf{1}),\; ds \rangle.\]

Match. Reading off the left slot gives the single-row sensitivity:

\[\delta_s = p \odot (\delta_p - \langle p, \delta_p \rangle \mathbf{1}).\]

Expand the right-hand side and you get \(\mathrm{diag}(p)\,\delta_p - p\,(p^\top \delta_p) = \big(\mathrm{diag}(p) - pp^\top\big)\delta_p\), the diagonal-minus-rank-one Jacobian from the tables. We never built it. It is what three lines of algebra look like if you insist on writing a matrix.

Compare the forward and backward rules. The drift subtracts the average nudge. The sensitivity subtracts the average blame, \(\langle p, \delta_p\rangle\), so each score’s sensitivity is its probability times how far its blame sits above average. Softmax’s backward rule is its drift rule with \(\delta_p\) fed in where \(ds\) was. (In Jacobian language, the softmax Jacobian is symmetric.)

A quick check against something familiar: with cross-entropy, \(\mathcal L = -\langle y, \log p\rangle\), we get \(\delta_p = -y/p\) entrywise and \(\langle p, \delta_p\rangle = -1\), so \(\delta_s = p \odot (\mathbf 1 - y/p) = p - y\). That is the usual “prediction minus target.”

The inner product of two matrices is the sum of the inner products of their rows, so the rows can be handled one at a time. Applied to every row of \(P\) at once, with each row’s average blame \(m_i = \langle P_{i,:},\, (\delta_P)_{i,:}\rangle\) collected into a column \(m\):

\[\delta_S = P \odot \big(\delta_P - m\, \mathbf 1^\top\big).\]

We will call this the softmax rule. It is not a fourth sliding rule, just a result we derived with the five rules, and we will reuse it twice more.

Step 3: Through \(S = \tau QK^\top\). For \(Q\), nudging gives \(d_Q S = \tau\, dQ\, K^\top\); the scalar \(\tau\) moves freely and Sandwich slides \(K^\top\) across:

\[\underbrace{d_Q \mathcal{L} = \langle \delta_S,\; \tau\, dQ\, K^\top \rangle}_{\text{Write-Out}} = \underbrace{\langle \tau\,\delta_S K,\; dQ \rangle}_{\text{Slide}} \quad \Rightarrow \quad \underbrace{\delta_Q = \tau\,\delta_S K}_{\text{Match}}.\]

For \(K\), nudging gives \(d_K S = \tau Q\, dK^\top\); Sandwich slides \(Q\) across, and the permutation rule for transpose flips both slots so \(dK\) stands alone:

\[\underbrace{d_K \mathcal{L} = \langle \delta_S,\; \tau Q\, dK^\top \rangle}_{\text{Write-Out}} = \underbrace{\langle \tau Q^\top \delta_S,\; dK^\top \rangle = \langle \tau\,\delta_S^\top Q,\; dK \rangle}_{\text{Slide}} \quad \Rightarrow \quad \underbrace{\delta_K = \tau\,\delta_S^\top Q}_{\text{Match}}.\]

Step 4: through the projections, adding at the fan-out. Each of \(Q = XW_Q\), \(K = XW_K\), \(V = XW_V\) is a row-convention linear layer, which we already solved:

\[\delta_{W_Q} = X^\top \delta_Q, \qquad \delta_{W_K} = X^\top \delta_K, \qquad \delta_{W_V} = X^\top \delta_V .\]

Nudging \(X\) instead, Sandwich gives each path’s share; for the query path, \(\langle \delta_Q, dX\, W_Q\rangle = \langle \delta_Q W_Q^\top, dX\rangle\). The input \(X\) feeds all three projections, so it fans out three ways. By the parallel rule, its sensitivity is the sum of the three blames:

\[\delta_X = \delta_Q W_Q^\top + \delta_K W_K^\top + \delta_V W_V^\top .\]

That finishes a single head: four rounds of slide-and-match, one softmax step, and one fan-out.

More heads. Multi-head attention runs \(h\) independent copies of this computation side by side, with parameters \(W_Q^{(i)}, W_K^{(i)}, W_V^{(i)}\) for head \(i\), concatenates their outputs, and mixes them with one more linear layer:

\[O_{\text{cat}} = [\, O_1 \mid O_2 \mid \cdots \mid O_h \,], \qquad Y = O_{\text{cat}} W_O .\]

The backward pass adds two moves, both linear. The output projection is one more row-convention linear layer, giving \(\delta_{W_O} = O_{\text{cat}}^\top \delta_Y\) and \(\delta_{O_{\text{cat}}} = \delta_Y W_O^\top\). Concatenation places blocks side by side, and its shortcut cuts the sensitivity apart again: head \(i\) receives the columns of \(\delta_{O_{\text{cat}}}\) that belong to it. Run steps 1 to 4 for each head separately, and add up the input sensitivities, since \(X\) fans out to every head:

\[\delta_X = \sum_{i=1}^{h} \Big( \delta_{Q_i} W_Q^{(i)\top} + \delta_{K_i} W_K^{(i)\top} + \delta_{V_i} W_V^{(i)\top} \Big).\]

A batch. A batch of \(B\) sequences adds one more leading axis. Each sequence goes through the same per-head computation independently. The weights are shared across the batch, which is another fan-out, so each weight’s sensitivity is a sum over examples:

\[\delta_{W_Q^{(i)}} = \sum_{b=1}^{B} X_b^\top\, \delta_{Q_i, b} ,\]

and the same for the other weights.

Why the boss falls. Every object we touched (\(\delta_O\), \(\delta_P\), \(\delta_S\), \(\delta_Q\), \(\delta_K\), \(\delta_V\), every \(\delta_W\), and \(\delta_X\)) is two-dimensional and shaped like the thing it measures. Head and batch indices do appear, but they only label independent copies of one computation, and the parallel rule settles them by adding.

Final boss: A mixture-of-experts block

Modern LLMs such as gpt-oss and DeepSeek-V3 replace each feed-forward layer with a mixture of experts. A small router scores every expert for every token, keeps the top few, and sends the token only to those. No gradient table has an entry for this block, and it contains something none of our earlier opponents did, a discrete choice. We derive the gradients for a gpt-oss mixture of experts block as implemented in HuggingFace Transformers.

Setup (rows are tokens). The input is \(X \in \mathbb{R}^{N \times d}\). The router computes logits \(L = XW_r + \mathbf 1 b_r^\top\) (\(N \times E\), one column per expert). For each token \(i\), let \(T_i\) be the \(k\) experts with the largest logits. The router weights \(R\) are a softmax over \(T_i\) in row \(i\) and zero elsewhere.

For expert \(e\), let \(D_e\) be the 0/1 matrix whose rows pick out the tokens routed to \(e\), one row per token with a single 1 in that token’s column. The expert runs a gated MLP on its tokens, and the outputs are weighted and put back:

\[\begin{aligned} X_e &= D_e X, & H_e &= X_e W_e + \mathbf 1 b_e^\top, \\ G &= H_e \Pi_g, & U &= H_e \Pi_u, \\ \hat G &= \min(G, \ell), & \hat U &= \mathrm{clip}(U, -\ell, \ell), \\ M &= (\hat U + 1) \odot \varphi(\hat G), & Y_e &= M W'_e + \mathbf 1 b'^\top_e, \\ r_e &= D_e R_{:,e}, & \mathrm{Out} &= \textstyle\sum_e D_e^\top \big( (r_e \mathbf 1^\top) \odot Y_e \big), \end{aligned}\]

Where \(\varphi(g) = g\,\sigma(\alpha g)\) is applied entrywise, \(\alpha\) is the swish steepness parameter, and \(\ell\) is the clamp bound. \(\Pi_g\) and \(\Pi_u\) are 0/1 matrices that pick the even and odd columns of \(H_e\), because gpt-oss interleaves its gate and up projections. Given \(\delta_{\mathrm{Out}}\), we want every parameter’s sensitivity and \(\delta_X\).

Two observations before the fight. First, \(D_e\), \(\Pi_g\), and \(\Pi_u\) are the 0/1 matrices from the slide-and-match section, so the sliding rules apply to them unchanged. Sliding \(D_e\) across turns it into \(D_e^\top\), which does the opposite job: \(D_e\) gathers rows out of the batch, and \(D_e^\top\) puts them back, adding wherever two contributions land in the same row. Gather in the forward pass, scatter-add in the backward pass, and no new rule.

Second, the top-\(k\) choice. Nudge \(L\) slightly and, unless two logits are tied, the same \(k\) experts still win. So in the backward pass \(T_i\) is a fixed mask, exactly like the set of active units of a ReLU, with the same convention at ties. A softmax over \(T_i\) with zeros elsewhere is also the full softmax with the logits outside \(T_i\) set to \(-\infty\). That is attention’s causal mask, chosen by the router instead of by position.

Step 1: through the combine. Nudging \(Y_e\) results in \(d_{Y_e}\mathrm{Out} = D_e^\top\big((r_e\mathbf 1^\top) \odot dY_e\big)\). Starting from the loss relation \(d_{Y_e}\mathcal L = \langle \delta_{\mathrm{Out}},\, d_{Y_e}\mathrm{Out}\rangle\), we replace the drift to get the nudge-drift relation between \(Y_e\) and \(\mathcal L\):

\[\begin{aligned} &\underbrace{d_{Y_e}\mathcal L = \big\langle \delta_{\mathrm{Out}},\; D_e^\top\big((r_e\mathbf 1^\top) \odot dY_e\big)\big\rangle}_{\text{Write-Out}} = \underbrace{\big\langle D_e\delta_{\mathrm{Out}},\; (r_e\mathbf 1^\top) \odot dY_e\big\rangle}_{\text{Slide (Sandwich)}} \\[6pt] &\qquad = \underbrace{\big\langle (r_e\mathbf 1^\top) \odot D_e\delta_{\mathrm{Out}},\; dY_e\big\rangle}_{\text{Slide (Hadamard rule)}} \quad\Rightarrow\quad \underbrace{\delta_{Y_e} = (r_e\mathbf 1^\top) \odot D_e\delta_{\mathrm{Out}}}_{\text{Match}} . \end{aligned}\]

Each expert collects the sensitivity of the tokens it served, scaled by how much the router trusted it. Nudging \(r_e\) results in \(d_{r_e}\mathrm{Out} = D_e^\top\big((dr_e\mathbf 1^\top) \odot Y_e\big)\). Starting from the loss relation \(d_{r_e}\mathcal L = \langle \delta_{\mathrm{Out}},\, d_{r_e}\mathrm{Out}\rangle\), we replace the drift to get the nudge-drift relation between \(r_e\) and \(\mathcal L\):

\[\begin{aligned} &\underbrace{d_{r_e}\mathcal L = \big\langle \delta_{\mathrm{Out}},\; D_e^\top\big((dr_e\mathbf 1^\top) \odot Y_e\big)\big\rangle}_{\text{Write-Out}} = \underbrace{\big\langle D_e\delta_{\mathrm{Out}},\; (dr_e\mathbf 1^\top) \odot Y_e\big\rangle}_{\text{Slide (Sandwich)}} \\[6pt] &\qquad = \underbrace{\big\langle D_e\delta_{\mathrm{Out}} \odot Y_e,\; dr_e\mathbf 1^\top\big\rangle}_{\text{Slide (Hadamard rule)}} = \underbrace{\big\langle (D_e\delta_{\mathrm{Out}} \odot Y_e)\,\mathbf 1,\; dr_e\big\rangle}_{\text{Slide (Sandwich)}} \quad\Rightarrow\quad \underbrace{\delta_{r_e} = (D_e\delta_{\mathrm{Out}} \odot Y_e)\,\mathbf 1}_{\text{Match}} . \end{aligned}\]

Row by row, a router weight’s sensitivity is the inner product of what the expert produced for that token with the sensitivity of that token. Since \(r_e = D_e R_{:,e}\), Sandwich puts each entry back in its token’s row by \((\delta_R)_{:,e} = D_e^\top \delta_{r_e}\), which is zero for tokens that did not use expert \(e\).

Step 2: Through one expert. The down projection (\(Y_e = M W'_e + \mathbf 1 b'^\top_e\)) is a row-convention linear layer with a bias:

\[\delta_{W'_e} = M^\top \delta_{Y_e}, \qquad \delta_{b'_e} = \delta_{Y_e}^\top \mathbf 1, \qquad \delta_M = \delta_{Y_e} W'^\top_e .\]

The bias drifts the output by \(\mathbf 1\, db'^\top_e\), so Sandwich and then the Permutation rule isolate \(db'_e\):

\[\underbrace{d_{b'_e}\mathcal L = \langle \delta_{Y_e},\; \mathbf 1\, db'^\top_e \rangle}_{\text{Write-Out}} = \underbrace{\langle \mathbf 1^\top \delta_{Y_e},\; db'^\top_e \rangle = \langle \delta_{Y_e}^\top \mathbf 1,\; db'_e \rangle}_{\text{Slide}} \quad\Rightarrow\quad \underbrace{\delta_{b'_e} = \delta_{Y_e}^\top \mathbf 1}_{\text{Match}}.\]

Every token adds its sensitivity to the shared bias, which is copy forward, sum backward again. The gate \(M = \varphi(\hat G) \odot (\hat U + 1)\) is a product of two elementwise pieces. Nudging \(\hat U\) and \(\hat G\) separately and starting from the loss relations \(d_{\hat U}\mathcal L = \langle \delta_M,\, d_{\hat U}M\rangle\) and \(d_{\hat G}\mathcal L = \langle \delta_M,\, d_{\hat G}M\rangle\), the Hadamard rule slides each factor across:

\[\begin{aligned} &\underbrace{d_{\hat U}\mathcal L = \big\langle \delta_M,\; \varphi(\hat G) \odot d\hat U \big\rangle}_{\text{Write-Out}} = \underbrace{\big\langle \varphi(\hat G) \odot \delta_M,\; d\hat U \big\rangle}_{\text{Slide (Hadamard rule)}} \quad\Rightarrow\quad \underbrace{\delta_{\hat U} = \varphi(\hat G) \odot \delta_M}_{\text{Match}}, \\[6pt] &\underbrace{d_{\hat G}\mathcal L = \big\langle \delta_M,\; \varphi'(\hat G) \odot (\hat U + 1) \odot d\hat G \big\rangle}_{\text{Write-Out}} = \underbrace{\big\langle \varphi'(\hat G) \odot (\hat U + 1) \odot \delta_M,\; d\hat G \big\rangle}_{\text{Slide (Hadamard rule)}} \\[6pt] &\qquad\Rightarrow\quad \underbrace{\delta_{\hat G} = \varphi'(\hat G) \odot (\hat U + 1) \odot \delta_M}_{\text{Match}}. \end{aligned}\]

where \(\varphi'(g) = \sigma(\alpha g) + \alpha g\, \sigma(\alpha g)\big(1 - \sigma(\alpha g)\big)\) is the single-variable derivative. The clamps are elementwise too, with slope 1 inside the limits and 0 outside:

\[\delta_G = \mathbf 1[G < \ell] \odot \delta_{\hat G}, \qquad \delta_U = \mathbf 1[\,|U| < \ell\,] \odot \delta_{\hat U}.\]

A clamped entry, like a dead ReLU unit, receives no blame. The split \(G = H_e\Pi_g\), \(U = H_e\Pi_u\) is Sandwich twice, and \(H_e\) feeds both, so the parallel rule adds the two:

\[\delta_{H_e} = \delta_G \Pi_g^\top + \delta_U \Pi_u^\top .\]

\(\Pi_g^\top\) puts each gate column back in its even slot, and \(\Pi_u^\top\) puts each up column back in its odd slot; in code, these are two strided assignments. The up projection is one more linear layer, \(\delta_{W_e} = X_e^\top \delta_{H_e}\), \(\delta_{b_e} = \delta_{H_e}^\top \mathbf 1\), \(\delta_{X_e} = \delta_{H_e} W_e^\top\), and the dispatch \(X_e = D_e X\) slides by Sandwich, so expert \(e\) hands \(D_e^\top \delta_{X_e}\) back to the tokens it served.

Step 3: through the router. Each row of \(R\) is a softmax with a mask, so the softmax rule from attention applies without change:

\[\delta_L = R \odot \big(\delta_R - m\,\mathbf 1^\top\big), \qquad m_i = \langle R_{i,:},\, (\delta_R)_{i,:}\rangle .\]

Wherever \(R\) is zero, so is \(\delta_L\): an expert the router did not choose for a token gets no blame from that token. The router itself is a linear layer, so \(\delta_{W_r} = X^\top \delta_L\) and \(\delta_{b_r} = \delta_L^\top \mathbf 1\).

Step 4: add up at the fan-out. \(X\) feeds the router and every expert, so

\[\delta_X = \delta_L W_r^\top + \sum_e D_e^\top \delta_{X_e} .\]

(The residual connection around the block adds \(\delta_{\mathrm{Out}}\) on top, by the parallel rule once more.)

Why the boss falls. A discrete choice looked like it would need a rule of its own. It did not: the top-\(k\) choice became a fixed mask, the routing became 0/1 matrices that slide like any other matrix, and the clamps became elementwise slopes. The three sliding rules, the softmax rule from attention, and the parallel rule did everything. The derivation also explains a design decision. An expert outside \(T_i\) gets exactly zero router blame from token \(i\), so an expert that falls out of favor receives no signal to win tokens back. That is one reason mixture-of-experts training adds a load-balancing term to the loss, or, in DeepSeek-V3, a bias that steers the choice without passing through the gradient at all .

Try it yourself: Attention sinks

gpt-oss gives each attention head one learned number \(\sigma\), its sink . Each row of scores gets \(\sigma\) appended as an extra logit, the softmax runs over \(N + 1\) entries, and the sink’s column is dropped before multiplying by \(V\):

\[q_i = \mathrm{softmax}\big([\,S_{i,:},\ \sigma\,]\big), \qquad P_{i,:} = \text{the first } N \text{ entries of } q_i, \qquad O = PV .\]

The sink soaks up probability, which lets a head attend to nothing. Given \(\delta_P\), find \(\delta_S\) and \(\delta_\sigma\). Hint: what is the sensitivity of a column nobody uses?

Solution.

Dropping a column is the concatenation shortcut read backward, \(\langle \delta_P, dP\rangle = \langle [\,\delta_P \mid 0\,], dq\rangle\), so the full softmax output has sensitivity \([\,\delta_P \mid 0\,]\). The softmax rule needs each row’s average blame, \(m_i = \langle q_i, [\,(\delta_P)_{i,:},\ 0\,]\rangle = \langle P_{i,:}, (\delta_P)_{i,:}\rangle\), the same number as without a sink. The first \(N\) entries of the softmax rule give

\[\delta_S = P \odot \big(\delta_P - m\,\mathbf 1^\top\big),\]

the same formula as plain attention. Only the values of \(P\) have changed, and its rows now sum to less than one. The last entry gives row \(i\)’s share of the sink’s blame, \(q_{i,\sigma}(0 - m_i)\), where \(q_{i,\sigma} = 1 - \sum_j P_{ij}\) is the mass the sink took. One \(\sigma\) serves every row of every sequence, so the parallel rule adds the shares:

\[\delta_\sigma = -\sum_{b}\sum_{i} m_{b,i}\, q_{b,i,\sigma} .\]

When scaling up a row’s attention would raise the loss (\(m_i > 0\)), gradient descent raises the sink and the head attends less.

The rest of a modern LLM

The examples and the three boss battles cover only part of the open-weight models people actually train. We provide a layer by layer check against the Hugging Face implementations of gpt-oss , Llama 3 , Gemma 3 , DeepSeek-V3 and V3.2 , Kimi K2 , and Kimi Linear .

Interactive. Seven open-weight LLMs, module by module. Point at a module to see which rule carries its sensitivity backward.

From the page to backward()

The sensitivities we derived are also, almost line for line, what you would write when giving a layer a custom backward pass. PyTorch’s documentation describes a custom backward as a vector-Jacobian product , which is what we have been calling an input sensitivity. It takes \(\delta_Y\) and returns \(J^{*}(\delta_Y)\). JAX makes the split even more explicit . A forward function returns the output plus saved “residuals,” and a backward function receives the upstream sensitivity and returns the weight and input sensitivities. A hand derivation turns into code line by line.

We numerically verify every gradient derived in this post against both finite differences and autodiff. The code and results are shown below.

Interactive. Every hand-derived backward pass in PyTorch and JAX, checked against finite differences and autodiff.

What the derivations tell you

Once a backward pass is on the page, it starts explaining things that are usually learned as facts. Here are a few, each read straight off a formula derived above.

Residual connections keep the blame flowing.

A residual block computes \(Y = X + f(X)\), so \(X\) fans out twice: once into the identity path and once into the branch \(f\). By the parallel rule,

\[\delta_X = \delta_Y + J^*(\delta_Y).\]

The first term reaches \(X\) untouched, however small the second term becomes. Stack many such blocks and the blame from the loss still has a direct path to every early layer, which is the standard explanation for why very deep residual networks keep training .

Attention divides by \(\sqrt{d_k}\) to keep softmax learning.

The softmax rule says \(\delta_s = p \odot (\delta_p - \langle p, \delta_p\rangle \mathbf 1)\). When one probability is close to 1 and the rest are close to 0, every entry of this is close to 0: the large probability multiplies a blame almost equal to the average blame, and every other entry is multiplied by a probability near zero. A saturated softmax passes almost no blame back to its scores. Dot products of \(d_k\)-dimensional vectors grow with \(d_k\) (with independent unit-variance entries, their variance is exactly \(d_k\)), which pushes softmax toward saturation, and dividing by \(\sqrt{d_k}\) brings the variance back to 1. The transformer paper gives this variance argument ; the softmax rule shows why saturation is the thing to avoid.

A training step costs about three forward passes.

A linear layer’s forward pass is one matrix product, \(Z = XW\). Its backward pass is two products of the same size, \(\delta_X = \delta_Z W^\top\) and \(\delta_W = X^\top \delta_Z\). Networks spend most of their compute in products like these, so the backward pass costs about twice the forward pass, and a full training step about three times. This is where the familiar estimate of roughly six floating-point operations per parameter per token for training, against two for inference, comes from .

Activations dominate training memory.

\(\delta_W = X^\top \delta_Z\) needs the layer’s input \(X\), so every layer has to keep its input until the backward pass reaches it. A custom PyTorch backward does this with ctx.save_for_backward, and it is why stored activations, more often than weights, fill a GPU during training. Gradient checkpointing trades this memory for compute, discarding some activations and recomputing them during the backward pass . FlashAttention makes the same trade inside attention: \(\delta_V = P^\top \delta_O\) and the softmax rule both need \(P\), and FlashAttention recomputes it in tiles instead of storing the full \(N \times N\) matrix .

Weight gradients have low rank built in.

\(\delta_W = X^\top \delta_Z\) is a sum of one outer product per token (row \(t\) of \(X\) times row \(t\) of \(\delta_Z\)), so its rank is at most the number of tokens in the batch. The bound bites when a batch holds fewer tokens than a layer is wide, as in small-batch fine-tuning. More generally, gradient-compression methods such as GaLore rely on gradients being close to low-rank , and this formula is one place that structure comes from.

Conclusion

Deep learning pedagogy has carried an odd split for a long time. Students are asked to picture optimization with low-dimensional hills and valleys, and to compute gradients with index tracking that breaks apart as soon as the layers get interesting.

The tools to do better have existed since 1988, and they have been applied to deep learning before. On top of this, we add a distilled version that fits in first-year math. With these ideas we derived convolution, multi-head attention, and a gpt-oss mixture-of-experts block by hand. In doing so, we never built anything larger than the matrices the network already stores, and found nothing in today’s open-source LLMs that needs additional rules. And the result of each derivation is already code. Type that into a custom layer’s backward in PyTorch or JAX, and the framework runs your formula as its own.

We believe that this is how backpropagation should be taught from the start. When a student meets an unfamiliar layer, they should be able to write it out, slide, then match, instead of getting lost in the indices. After all, a teacher’s job ends when the students can work “as if I did not exist” .

AI usage disclosure

Anthropic Claude was used to assist with code implementation, English language editing, interactive figure generation, and organization of the post. All ideas, derivations, and conclusions were developed and verified by the authors.

Enjoy Reading This Article?

Here are some more articles you might like to read next: