14.1 Conv layers and pooling on autograd
Convolution as a linear map in Mathematics proved that a convolution is a matrix and built im2col and its adjoint col2im, but only as numpy functions. Nothing in the system can train a kernel yet. The autograd engine from the foundations chapter has Linear and no layer that shares weights across positions, so a model that reads an image must flatten it and learn every pixel position separately. This section turns those two functions into layers with hand-written backward passes on the Tensor from Tensor, broadcasting backward, and no_grad.
Concepts from other sections (16)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- patch embedding: a convolution with kernel equal to stride, equivalent to one linear map applied to each flattened patch. Read more: 14.3 Vision transformer encoder
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- receptive field: the region of the input that a given neuron depends on, which grows with depth. Read more: Chapter 3: Neural Architectures and Their History
- Cross-correlation: sliding a kernel over a signal and taking a dot product at each position, with no flip; what deep learning calls convolution. Read more: 18.1 Convolution as a linear map in Mathematics
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
- Jacobian: the matrix of partial derivatives of a function . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- registration order: the order layers are created in a
Module, which fixes both the state-dict keys and the order of random initialization draws. Read more: 8.2 Bengio’s neural probabilistic language model - Gradient check: a comparison of an analytic gradient against the numerical one that reports pass or fail and the element furthest past its allowance. Read more: 10.1 Partial derivatives, gradients, and gradcheck in Mathematics
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Residual stream: the running sum a Transformer block adds its attention and MLP outputs to. Read more: 13.4 Variance propagation and initialization in Mathematics
- Linear map: a function between vector spaces with ; once bases are chosen, every linear map is a matrix. Read more: Chapter 9: Linear Algebra in Mathematics
Everything visual or audible in the rest of the book starts here. A vision transformer’s patch embedding in Vision transformer encoder is a Conv2d whose kernel equals its stride, and Whisper’s stem in Whisper encoder is two Conv1d layers. A wrong backward pass here passes every shape check and shows up much later as a vision tower that does not learn, so the gradients are proven three ways: against PyTorch, against central differences, and by training LeNet-5 to read digits, which is the first end-to-end evidence that the vision layers train.
Besides the conv chapter of the mathematics book, you will use the reshapes and relu from The op library and gradcheck_all, Module and Linear from Module system and basic layers, normal_init from Variance propagation and initialization, and PCG32 from Modular arithmetic, hashing, and PCG32. Training LeNet also uses the cross-entropy of Losses with a fused backward and Adam and AdamW; for comparison, a plain-loop LeNet lives in ml/06-neural-architectures/code/lenet.rs. The full solution is conv.py and its contract is course/contracts/py/tinyllm/vision/conv.pyi.
Learning objectives
- Derive the backward pass of a convolution as , , , and extend it to grouped convolution.
- Implement
Conv1dasConv2don an image one row tall, with no new backward code.- Implement max and average pooling with deterministic gradients, including the tie rule and overlapping windows.
- Initialize a conv layer with the right fan-in and assemble LeNet-5 so a PyTorch checkpoint loads.
Notation
Section titled “Notation”The derivations below use a small set of symbols, summarized here with their shapes.
| Symbol | Meaning | Type / shape |
|---|---|---|
| input batch (NCHW) | float[N, C, H, W] | |
| kernel bank (KCRS), groups | float[K, C/γ, R, S] | |
| bias | float[K] | |
output height and width (conv_out_size) | int | |
im2col of image , rows ordered | float64[C·R·S, P·Q] | |
| upstream gradient | float[N, K, P, Q] |
Conv2d: one matmul forward, its transpose backward
Section titled “Conv2d: one matmul forward, its transpose backward”Take one group first (). Flatten the kernels to . Column of is the receptive field of output position , so the layer is
reshaped to . As in torch.nn.Conv2d, this is cross-correlation: no kernel flip.
For the backward pass, let be and perturb each input. The loss changes by with . Using :
The first and last terms read off and . For the middle term, im2col is linear, so , and the mathematics book proved . Hence
You can see why this is right without the algebra: col2im sums where windows overlap, which is exactly the chain rule for a pixel that feeds several outputs. Stride, padding, and dilation change only which pixels im2col copies; the three formulas do not change.
Groups are a small extension. With groups, output channels read only input channels . Because im2col’s rows are ordered , group owns the contiguous rows , and the layer is independent copies of the equations above on those row and channel slices: is block diagonal. must divide both and .
The remaining question for the layer is how to start its weights. One output is a sum of products . With independent zero-mean weights of variance , , so keeps the scale of the signal. The fan-in counts one group’s channels, not all . Biases start at zero, and weight then bias are drawn from one PCG32 stream. The forward and backward run in float64 and the output is cast back to ‘s dtype.
Conv1d: an image one row tall
Section titled “Conv1d: an image one row tall”With Conv2d in hand, the 1-D layer costs almost nothing. A sequence [N, C, L] is an image [N, C, 1, L], and a kernel [K, C/γ, k] is [K, C/γ, 1, k]. A 1-D conv with stride , padding , dilation is then the 2-D op with stride , padding , dilation , and the output [N, K, 1, Lout] drops its row axis. The reshapes are existing autograd ops, so gradients reach , , and with no new backward code. The row axis must get padding 0: padding it by would give output rows, all but one of them reading only zeros.
Pooling
Section titled “Pooling”Pooling reuses the same machinery with no parameters at all. It treats every channel independently. A window slides with stride (default ) and no padding, so by conv_out_size. Folding channels into the batch ([N·C, 1, H, W]) makes im2col return each window as a column of taps in row-major order.
Average pooling computes over the column . Every tap has derivative , so the backward writes into all taps and col2im adds the overlaps.
Max pooling computes with . Near a point with a unique maximum, is a copy of one input, so the Jacobian is a selection: the backward writes at tap and zero elsewhere, then col2im sums, so a pixel that is the maximum of two overlapping windows receives both gradients. At a tie the function is not differentiable and any split of among the tied taps is a valid subgradient. The contract fixes one, as PyTorch does: the first tied tap in row-major window order, which is the lowest flat index in . That makes gradients deterministic.
LeNet-5
Section titled “LeNet-5”The layers are only worth something if they learn together, and LeNet-5 is the classic test. The composition is same-padded so any in_hw that is a multiple of 4 works: conv1 = Conv2d(1, 6, 5, pad=2), ReLU, max_pool2d 2; conv2 = Conv2d(6, 16, 5, pad=2), ReLU, max_pool2d 2; flatten in order (as torch.flatten); fc1 = Linear(16 (in_hw/4)^2, 120), ReLU; fc2 = Linear(120, 84), ReLU; fc3 = Linear(84, n_classes). Parameters register in that order and all draw from one rng. For 8 x 8 digits the shapes are , with parameters. Trained with cross-entropy and Adam (batch 32, learning rate ), it reaches about 0.97 on held-out digits in 400 steps.
Working pooling by hand
Section titled “Working pooling by hand”Before writing code, it helps to pin the tie rule with numbers you can check. Pool this image with windows and stride 2 ():
The four windows reduce as follows.
| Window | Taps (row-major) | Max, at pixel | Mean |
|---|---|---|---|
| top-left | 1, 4, 3, 2 | 4 at | |
| top-right | 2, 2, 0, 1 | 2 at (tie with : the first wins) | |
| bottom-left | 0, 3, 1, 2 | 3 at | |
| bottom-right | 5, 1, 4, 1 | 5 at |
So max pooling gives and average pooling . Now backpropagate , so every . Max pooling puts ones at , , , and zeros elsewhere; pixel gets nothing although it also holds a 2. Average pooling puts at every pixel. These are the exact numbers a correct solution must produce, and they are the first test case listed later.
Designing the API
Section titled “Designing the API”The public surface is four layers and two functions:
class Conv2d(Module): # weight [c_out, c_in/groups, kh, kw], bias [c_out] or None def __init__(self, c_in, c_out, k, stride=1, pad=0, dilation=1, groups=1, bias=True, rng=None): ... def forward(self, x: Tensor) -> Tensor: ... # [N, C, H, W] -> [N, K, P, Q]class Conv1d(Module): # weight [c_out, c_in/groups, k] def __init__(self, c_in, c_out, k, stride=1, pad=0, dilation=1, groups=1, bias=True, rng=None): ... def forward(self, x: Tensor) -> Tensor: ... # [N, C, L] -> [N, K, Lout]def max_pool2d(x: Tensor, k: int, stride: Optional[int] = None) -> Tensor: ... # [N, C, H, W] -> [N, C, P, Q]def avg_pool2d(x: Tensor, k: int, stride: Optional[int] = None) -> Tensor: ...class LeNet5(Module): # conv1, conv2, fc1, fc2, fc3 def __init__(self, n_classes=10, in_hw=8, rng=None): ... def forward(self, x: Tensor) -> Tensor: ... # [N, 1, in_hw, in_hw] -> [N, n_classes]For Conv2d, k, stride, pad, and dilation are an int or a (row, column) pair; for Conv1d they are ints. rng=None means PCG32(0).substream("init"). Each layer is a single autograd node built with from_op. Everything invalid raises ValueError: a size, stride, or dilation below 1, negative padding, groups that do not divide both channel counts, an input of the wrong rank or channel count, a kernel or window larger than the (padded) input, and in_hw not a multiple of 4.
Building it step by step
Section titled “Building it step by step”The design follows from six observations, each of which removes code rather than adding it.
- Reuse the proven matrix. The mathematics book showed with , and that col2im is im2col’s adjoint. So a conv layer needs no new indexing code: one call to
im2colforward, one matmul per group, and the three formulas above backward. - One autograd node, not many. Building the conv out of
Tensorops (gathers, matmuls) would record thousands of nodes and be slow. A singlefrom_opnode with a hand-written VJP records one, and the VJP is exactly the derivation above. - Groups are slices, not a different algorithm. Because im2col’s rows are ordered , group ‘s input rows and output channels are contiguous ranges. The forward and the VJP loop over groups and apply the one-group formulas to those slices.
- Conv1d should not be a second implementation. A sequence is an image one row tall, so
Conv1dreshapes and calls the 2-D op with stride, padding, and dilation 1, 0, 1 on the row axis; the reshape carries the gradient. - Pooling is im2col with one channel. Folding channels into the batch makes each column one window of taps. The forward is a reduction over the column; the backward writes into the column and col2im adds the overlaps.
- Compute in float64, return the input’s dtype. Matching torch within needs float64 accumulation; casting back keeps a float32 model float32.
Start with the conv op. The forward builds the columns once and keeps them for the backward, because they are ‘s right-hand factor:
def _conv2d_op(x, w, b, stride, pad, dilation, groups) -> Tensor: xd, wd = x.data, w.data n, c, h, wid = xd.shape kout, cg, r, s = wd.shape # cg = C / groups input channels per group # ... raise if c != cg * groups p = conv_out_size(h, r, stride[0], pad[0], dilation[0]) q = conv_out_size(wid, s, stride[1], pad[1], dilation[1]) kg = kout // groups # output channels per group dt = xd.dtype cols = im2col(xd, r, s, stride, pad, dilation) # [N, C*R*S, P*Q], rows ordered (c, r, s) crs = cg * r * s # rows owned by one group wflat = wd.reshape(kout, crs).astype(np.float64) # W-bar, one row per output channel y = np.empty((n, kout, p * q)) for g in range(groups): # Y_g = W_g C_g: block-diagonal W, one block per group y[:, g * kg : (g + 1) * kg] = np.einsum( "kj,njl->nkl", wflat[g * kg : (g + 1) * kg], cols[:, g * crs : (g + 1) * crs] ) if b is not None: y += b.data.astype(np.float64)[None, :, None] # b 1^T, broadcast over positions out = y.reshape(n, kout, p, q).astype(dt)The VJP is the three formulas, applied per group:
def vjp(gout): gy = gout.reshape(n, kout, p * q).astype(np.float64) # G_n dcols = np.empty_like(cols) dw = np.empty((kout, crs)) for g in range(groups): gg = gy[:, g * kg : (g + 1) * kg] # this group's output gradient cg_ = cols[:, g * crs : (g + 1) * crs] # this group's columns dw[g * kg : (g + 1) * kg] = np.einsum("nkl,njl->kj", gg, cg_) # sum_n G_n C_n^T dcols[:, g * crs : (g + 1) * crs] = np.einsum( "kj,nkl->njl", wflat[g * kg : (g + 1) * kg], gg # W^T G_n ) dx = col2im(dcols, xd.shape, r, s, stride, pad, dilation) # the adjoint: sums overlapping windows grads = [dx.astype(dt), dw.reshape(wd.shape).astype(wd.dtype)] if b is not None: grads.append(gy.sum(axis=(0, 2)).astype(b.data.dtype)) # over the batch and every position return tuple(grads)
parents = (x, w) if b is None else (x, w, b) return from_op(out, parents, vjp, "conv2d")Conv2d.__init__ validates every argument and initializes with the group’s fan-in:
fan_in = (c_in // groups) * kh * kw # one group's channels: what one output actually sumsself.weight = Tensor( normal_init((c_out, c_in // groups, kh, kw), 1.0 / math.sqrt(fan_in), r), requires_grad=True,)self.bias = Tensor(np.zeros(c_out), requires_grad=True) if bias else NoneConv1d.forward is the one-row reshape:
n, c, length = x.shapex4 = F.reshape(x, (n, c, 1, length)) # an image one row tallk_out, cg, k = self.weight.shapew4 = F.reshape(self.weight, (k_out, cg, 1, k))# row axis: stride 1, padding 0 (padding it would add rows of zeros), dilation 1y = _conv2d_op(x4, w4, self.bias, (1, self.stride), (0, self.pad), (1, self.dilation), self.groups)return F.reshape(y, (n, k_out, y.shape[3]))The two pooling functions share _pool_cols, which defaults the stride to the window size and folds channels into the batch:
s = k if stride is None else stride # non-overlapping windows by default# ...cols = im2col(x.data.reshape(n * c, 1, h, w), k, k, (s, s)) # [N*C, k*k, P*Q]Max pooling keeps the argmax for the backward:
def max_pool2d(x, k, stride=None): cols, s, p, q = _pool_cols(x, k, stride, "max_pool2d") n, c, h, w = x.shape # argmax returns the first maximum: the lowest (r, s) in the window, # which is the lowest flat index of x arg = np.argmax(cols, axis=1) # [N*C, P*Q] y = np.take_along_axis(cols, arg[:, None, :], axis=1)[:, 0] out = y.reshape(n, c, p, q).astype(x.data.dtype)
def vjp(g): dcols = np.zeros_like(cols) # zero at every tap that was not the max np.put_along_axis(dcols, arg[:, None, :], g.reshape(n * c, 1, p * q).astype(np.float64), axis=1) dx = col2im(dcols, (n * c, 1, h, w), k, k, (s, s)) # overlapping windows add return (dx.reshape(n, c, h, w).astype(x.data.dtype),)
return from_op(out, (x,), vjp, "max_pool2d")Average pooling’s backward spreads to every tap:
def vjp(g): gg = g.reshape(n * c, 1, p * q).astype(np.float64) / (k * k) dcols = np.broadcast_to(gg, cols.shape).copy() # copy: col2im needs a writable, real array dx = col2im(dcols, (n * c, 1, h, w), k, k, (s, s)) return (dx.reshape(n, c, h, w).astype(x.data.dtype),)Finally, LeNet5 is the composition described earlier, with every layer drawing from the same rng in registration order, and a flatten that keeps NCHW’s order:
def forward(self, x): h = max_pool2d(F.relu(self.conv1(x)), 2) h = max_pool2d(F.relu(self.conv2(h)), 2) h = F.reshape(h, (h.shape[0], -1)) # (c, h, w) order, as torch.flatten h = F.relu(self.fc1(h)) h = F.relu(self.fc2(h)) return self.fc3(h)The full solution is conv.py.
Why this design
Section titled “Why this design”The forward and backward are each multiply-adds, the same as a direct convolution, done as dense matmuls. The price is memory: the columns hold every input pixel up to times ( per image), and they are kept until the backward pass. The alternative, six nested loops over in Python, would be orders of magnitude slower and need its own backward indexing; im2col turns the whole layer into einsum calls and reuses an adjoint that is already proven.
A hand-written VJP also beats composing autograd ops. Composition would be correct but would record a node per gather and keep many intermediates; one node keeps exactly cols and the weights. And the deterministic tie rule is a choice, not a mathematical necessity: any subgradient is valid at a tie, but fixing the first index matches PyTorch, so golden comparisons and checkpoints behave identically, and repeated runs give the same gradients.
What can go wrong
Section titled “What can go wrong”A correct solution is checked on the cases below. Several of them are golden comparisons against PyTorch, because later sections load pretrained conv weights into these layers.
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| hand example: pooling | unit, smoke | the hand-worked maxima, means, and both gradients, exactly | the tie rule is pinned |
| Conv2d matches torch | golden | forward, , , within of torch on three layers: LeNet’s (5 x 5, pad 2), a grouped, strided, dilated one, and a patch embedding (kernel 4, stride 4) | the vision transformer and the planned vision-language models load pretrained conv weights |
| Conv1d matches torch | golden | the same for the two Whisper stem shapes (k 3 pad 1; k 3 stride 2 pad 1) | Whisper’s stem halves the frames |
| pooling matches torch | golden | max and average, forward and within , including k 3 stride 2 (overlap) and integer inputs full of ties | gradients add where windows overlap |
| gradient check, Conv2d | gradcheck | the hand-written vjp for , , against central differences, with unequal strides, padding, dilation, and 2 groups | the backward is correct beyond the fixture cases |
| gradient check, Conv1d | gradcheck | gradients reach , , through the reshapes (stride 2, pad 1) | training Whisper’s stem |
| max-pool ties route to the lowest index | property | on a constant image each window’s gradient lands on its top-left pixel | deterministic gradients |
| shapes, init, and dtype | unit | names (weight, bias), KCRS shape with channels, std near , bias=False, float32 in gives float32 out | checkpoints load by name and shape |
| LeNet is the composition | unit | the ten parameter names in order, fc1 of width 64 (144 for 12 x 12), and the forward equal to the layers composed by hand | a torch LeNet checkpoint loads |
| bad arguments rejected | boundary | every ValueError listed in the API | wrong layouts fail at the line that is wrong |
| LeNet learns digits | learning | 400 Adam steps, held-out accuracy about 0.97 | the layers learn together |
The mistakes that most often slip past shape checks are subtle indexing errors. Routing max-pool ties to the last maximum makes gradients differ from torch on flat or integer images; np.argmax returns the first maximum in row-major window order, which avoids it. In grouped convolution, two related bugs are every group reading the first group’s columns (the loop must slice cols[:, g * crs : (g + 1) * crs]) and building from the first group’s weights only (dcols must use wflat[g * kg : (g + 1) * kg] for group g); either makes later groups compute on, or learn from, the wrong channels.
Warning: Summing the bias gradient over one image instead of the batch lets biases learn from only a fraction of the signal.
gy.sum(axis=(0, 2))sums the batch and the positions together.
Several pitfalls are off-by-a-factor errors. An average-pool backward divided by instead of makes gradients times too large; the VJP divides by k * k. A fan-in that counts every input channel instead of one group’s starts grouped layers times too small; the solution uses fan_in = (c_in // groups) * kh * kw. A pooling stride that defaults to 1 instead of gives outputs nearly as large as the input; _pool_cols uses s = k when stride is None.
The remaining ones are layout errors. If Conv1d pads the dummy row axis too, it produces extra rows of zeros and the final reshape fails or is wrong, so Conv1d.forward passes padding (0, self.pad). If LeNet flattens in order, it still trains, but a torch checkpoint no longer loads; F.reshape(h, (N, -1)) on NCHW keeps order. And if the constructors did not check that groups divide c_out, you could build a weight whose groups have unequal sizes; they raise unless groups divides both channel counts.
Where this leads
Section titled “Where this leads”These layers are used immediately. In Vision transformer encoder, PatchEmbed is Conv2d(3, d, p, stride=p): non-overlapping windows, one token per patch. In Whisper encoder, the stem is Conv1d(n_mels, d, 3, pad=1) followed by Conv1d(d, d, 3, stride=2, pad=1). The planned vision-language model section will load pretrained vision towers’ patch-embedding weights into Conv2d.
Production libraries go further in several directions. torch.nn.Conv2d on cuDNN selects an algorithm per shape (im2col plus GEMM, Winograd, FFT) and supports a channels-last memory format; see torch/nn/modules/conv.py and cuDNN’s cudnnConvolutionForward. On CPU, oneDNN and XNNPACK run direct convolutions with JIT-generated kernels and avoid im2col’s memory blow-up (oneapi-src/oneDNN). F.max_pool2d in torch/nn/functional.py adds padding, dilation, ceil_mode, and returned indices for unpooling. And modern architectures such as ConvNeXt and ViT add normalization, residual streams, and depthwise (groups equal to channels) convolutions; a ViT keeps only the first conv.
Further reading
Section titled “Further reading”- LeCun, Bottou, Bengio, Haffner, “Gradient-based learning applied to document recognition” (1998), section II.
- Chellapilla, Puri, Simard, “High performance convolutional neural networks for document processing” (2006), the im2col paper.
- Dumoulin and Visin, “A guide to convolution arithmetic for deep learning” (2016, free).
- Liu et al., “A ConvNet for the 2020s” (2022).
Key terms
Section titled “Key terms”- im2col: the linear map that copies each receptive field of an image into a column, so a convolution becomes a matmul.
- col2im: the adjoint of im2col; it adds columns back into image positions, summing where windows overlap.
- grouped convolution: a convolution whose channels split into independent groups, giving a block-diagonal weight matrix.
- fan-in: the number of products one output sums, for a conv, which sets the init scale .
- subgradient: a valid gradient choice at a non-differentiable point, such as a tie in max pooling.
Summary
Section titled “Summary”- A conv layer is one matmul per group on im2col’s columns, so its backward pass is three short formulas: , , .
Conv1disConv2don an image one row tall; stride, padding, and dilation apply to the time axis only.- Max pooling’s backward routes each output’s gradient to its window’s maximum; a tie goes to the lowest flat index, and overlapping windows add.
- Average pooling’s backward spreads over the window.
- The layers learn together: LeNet-5 on 8 x 8 digits reaches about 0.97 held-out accuracy in 400 Adam steps.
Review questions
Section titled “Review questions”-
Why is and not of something?
Answer
The forward reads through im2col, a linear map. The gradient through a linear map is its adjoint applied to the upstream gradient, and col2im is im2col’s adjoint. Concretely, col2im adds every copy of a pixel back together, which is the chain rule for a pixel that fed several outputs.
-
Why does
Conv1dpass padding(0, self.pad)and not(self.pad, self.pad)?Answer
The row axis has height 1 and a kernel of height 1. Padding it by would produce output rows, all but one reading only zeros, and the final reshape to
[N, K, Lout]would fail or mix rows into time steps. -
In the hand-worked pooling example, why does pixel get no gradient even though it equals the window’s maximum?
Answer
The window’s taps are in row-major order;
np.argmaxreturns the first maximum, tap 0, which is pixel . The VJP writes only at the argmax, so gets zero. Any split would be a valid subgradient, but only one choice matches PyTorch. -
Why is the fan-in and not ?
Answer
Each output of a grouped conv sums only its own group’s input channels. Its variance is , so keeps the scale. Using would start a grouped layer times too small.
-
Why does the max-pool VJP not need the input values, only
arg?Answer
Near a point with a unique maximum the output is a copy of one input, so the Jacobian is a selection matrix determined entirely by which tap won. Keeping the argmax indices is enough to route each gradient.