Practice / Minibatches
Batched backprop: dense layers on a minibatch
Before you start
Every earlier page did its derivations one example at a time and then stacked the results. Real training runs a whole minibatch through each layer as one matrix, and the backward pass is written the same way. These ten problems take a dense layer in the layout most array code uses, , derive its three gradients from index form, show where the sum over the batch hides inside a matrix product, and then follow the batch dimension through a mean loss, an activation, a masked loss, gradient accumulation and sequences. The five mistakes at the end are the ones that pass a quick look: a weight gradient in the other layout, a applied twice, where belongs, an elementwise derivative used as a matrix, and micro-batch gradients summed instead of averaged.
- The conventions are those of the previous pages: a gradient has the shape of the variable it is taken with respect to, is the elementwise product, is the all-ones vector, and rows are examples.
- The dense layer: input with row equal to , weights , bias , and output , with row written . This is the layout of most array code, which stores as inputs by outputs; the one-hidden-layer page used the other layout, with outputs by inputs.
- is a scalar loss computed from by the layers above. For any array in the network, is the code-style name for : the array of , with the shape of . Row of is written .
- The backward pass of a layer receives from above and returns , , and for the layer below.
- A mean loss over the batch is , where depends only on example . Targets are written to keep for the layer's output.
Builds on: Jacobians and the chain rule, One-hidden-layer backprop, the whole backward pass
Problems
- ·
Give the shapes of , , , and of , , , . Show that row of is the layer applied to example alone.
- ··
Compute from index form.
- ··
Compute .
- ··
Compute . Does it involve a sum over the batch?
- ···
Write as a sum of single-example gradients and show it is . How many entries does the Jacobian of with respect to have, and how many are nonzero?
- ··
Mean loss: with targets . Compute , and . Where does the enter?
- ··
Let elementwise, with . Given , compute without forming any Jacobian.
- ···
Masked softmax cross-entropy: logits , row-wise softmax , one-hot target rows , and marking the real rows (padding has ; at least one ). With , the loss is . Compute , and check the case where every .
- ···
Gradient accumulation: split rows into micro-batches of rows, with the mean loss over micro-batch . Show that the full-batch mean loss is and give . What changes if the sizes differ?
- ···
Sequences: holds sequences of positions, and the layer acts at every position: , with position of sequence . Compute and as matrix products.
Answers
- , , , , and each has the shape of ; row of is
- ()
- ()
- ()
- ; the Jacobian of with respect to has entries, only of them nonzero, and the matrix product never forms it
- ; ;
- ()
- ; with every it is
- , so
- and , where () and () stack every position of every sequence as a row
Worked solutions
Problem 1
Give the shapes of , , , and of , , , . Show that row of is the layer applied to example alone.
- is .A product needs the inner dimensions to agree, so has rows, one per input feature, and its columns are the output features.
- is , and every row of it is .. This is the matrix form of adding to every row, which array code does by broadcasting.
- Row of is .Row of a product is row of the left factor times the right factor.
- has the shape of for every .It has one entry per entry of , so that is defined.
- , , , , and each has the shape of ; row of is Row uses only row of and the shared and : the batch is copies of the single-example layer , one per row, sharing the parameters.
Problem 2
Compute from index form.
- .Index form of .
- appears in for every , with coefficient , and in no entry outside column .Column of builds only column of , and every example uses the same .
- .The chain rule sums over every entry of that contains ; by step 2 that is one entry per example.
- ., and a sum over the shared index is the definition of the matrix product.
- (), the shape of . The batch index is the one summed over, which is why is the inner dimension of the product.
Problem 3
Compute .
- appears in for every , with coefficient . copies into every row (Problem 1, step 2).
- .The chain rule sums over the entries that contain , each with derivative .
- (), the shape of ; multiplying by sums each column of , which array code writes as a sum over axis . A bias added to every row has its gradient summed over every row.
Problem 4
Compute . Does it involve a sum over the batch?
- appears in for every , with coefficient , and in no other row of .Example feeds only row : in a dense layer the examples do not interact.
- .The chain rule sums over the entries of row that contain , one per output feature; .
- (), the shape of . The sum is over output features, not over the batch: each example gets its own input gradient, and row is , the single-example rule for .
Problem 5
Write as a sum of single-example gradients and show it is . How many entries does the Jacobian of with respect to have, and how many are nonzero?
- For one example, has , so its gradient with respect to has entries : it is , . appears only in , with coefficient ; an outer product has entries .
- .Every example uses the same , so the loss reaches through all rows and the contributions add.
- For matrices and with rows and , ., the entry of the sum of outer products.
- Flatten to entries and to ; the Jacobian is , and entry is if and otherwise. depends only on column of (Problem 2, step 2), so for each of the outputs only of the weights give a nonzero entry: in total.
- ; the Jacobian of with respect to has entries, only of them nonzero, and the matrix product never forms itStep 3 with , . costs multiply-adds, the same as the forward product , while the full Jacobian has entries: at and , about . The matrix product is the vector-Jacobian product of the Jacobians page, done for the whole batch at once.
Problem 6
Mean loss: with targets . Compute , and . Where does the enter?
- with , where is row of .The squared Frobenius norm is the sum of the squared entries, which is the sum of the squared row norms.
- .Only contains row of , it carries the factor , and differentiates to .
- , .Step 2 for every entry.
- and .Problems 2 and 3 hold for any ; they never used where it came from.
- ; ; The enters once, in , and every later gradient is linear in , so it carries the factor without applying it again. is the average of the single-example gradients; with a summed loss it would be times larger.
Problem 7
Let elementwise, with . Given , compute without forming any Jacobian.
- depends only on . is applied to each entry on its own, in every row.
- . reaches only through , so the chain rule has one term.
- , so .Differentiate with the quotient rule and use ; the forward pass already saved .
- () means minus each entry of . The Jacobian of with respect to is and diagonal, with these entries on the diagonal, so multiplying by it is an elementwise product: the batch changes the shape, not the rule.
Problem 8
Masked softmax cross-entropy: logits , row-wise softmax , one-hot target rows , and marking the real rows (padding has ; at least one ). With , the loss is . Compute , and check the case where every .
- Let , the number of real rows, so . by assumption, and it does not depend on , so it is a constant for the derivative.
- Row of feeds only , and , with , , row of , , .The softmax is taken row by row; the gradient is the softmax page's Problem 5 for example .
- Row of is . enters with coefficient .
- Multiplying row of a matrix by , for every , is multiplying it on the left by ..
- ; with every it is With every row real, and : the softmax page's batched result. Padding rows get a zero gradient whatever their logits, and dividing by the number of real rows, not by , keeps the loss on the same scale however much padding a batch carries. In code is never built: the mask multiplies each row.
Problem 9
Gradient accumulation: split rows into micro-batches of rows, with the mean loss over micro-batch . Show that the full-batch mean loss is and give . What changes if the sizes differ?
- .Group the sum by micro-batch; each example is in exactly one.
- . is the mean of the losses in micro-batch .
- ..
- .The gradient of a sum is the sum of the gradients, and is a constant.
- , so Accumulating the micro-batch gradients and dividing once by reproduces the full-batch gradient, up to rounding. This needs the examples not to interact, which holds for every layer on this page; batch normalisation, which mixes examples, is the exception. With sizes the same steps give weights in place of .
Problem 10
Sequences: holds sequences of positions, and the layer acts at every position: , with position of sequence . Compute and as matrix products.
- and .Every position of every sequence uses the same and , so each is an example in the sense of Problems 3 and 5, and their contributions add.
- Let have one row per pair , and the rows in the same order.Stacking the pairs as rows turns the double sum into a single sum over the rows; any order works if both use the same one.
- and , where () and () stack every position of every sequence as a rowProblem 5, step 3 and Problem 3 applied to the rows: . A position-wise layer treats positions exactly like examples, so a transformer's feed-forward and projection layers see a batch of rows. If the loss is a mean over all positions, the factor in is , not .
Where this goes wrong
1. Weight gradient in the outputs-by-inputs layout
The one-hidden-layer page computed , a product with the transposed delta on the left, and that pattern is easy to carry from one layer to the next.
- , is , is Right so far: the layer and shapes of Problem 1.
- “The weight gradient is the upstream gradient, transposed, times the input.”The habit that causes the mistake: the rule for , where is outputs by inputs, applied to a layer stored inputs by outputs.
- It is , the transpose of 's shape. In , multiplies into , so (Problem 2). When the update runs and silently applies the transpose.
2. Dividing by N twice
The bias gradient is often described as “the average of the deltas over the batch”, and with a mean loss that description is true of the result, not of the formula.
- Right so far: Problem 6, step 3. The of the mean loss is already inside .
- “The bias gradient is the average of the upstream gradient over the batch.”The shortcut that causes the mistake: averaging rows of a that already carries the .
- That is , times too small. The rule is , a plain sum (Problem 3), because the factor was applied once at the loss (Problem 6). The bias then learns times more slowly than the weights, and the gap grows with the batch size.
3. Multiplying the upstream gradient by W instead of Wᵀ
The forward pass multiplies by , and it is tempting to think the backward pass simply multiplies by it again.
- , and should have the shape of , Right so far: Problem 1.
- “Backward goes through the same weights, so multiply by .”The analogy that causes the mistake: the backward pass uses the same weights, but it runs the map in the opposite direction, from output features back to input features, which is what does.
- is undefined unless . The rule is (Problem 4): sums over 's second index. For a square the product runs and sends every gradient back along the wrong weights.
4. Elementwise derivative applied as a matrix product
The chain rule is a product of Jacobians, and in a batch every factor looks like a matrix.
- , and is Right so far: Problem 7, step 3 gives the derivative at every entry.
- “The chain rule multiplies the upstream gradient by the local derivative, so multiply the matrices.”The analogy that causes the mistake: the rule for vectors, applied to two arrays as if the derivative array were the Jacobian.
- It is , a matrix over pairs of examples. The Jacobian of an elementwise map is diagonal, so multiplying by it is an elementwise product: (Problem 7).
5. Summing micro-batch means without dividing by K
Gradient accumulation is usually written as a running sum of gradients, and the division at the end is easy to leave out.
- with the mean over micro-batch Right so far: Problem 9, step 3.
- “Accumulate the gradients of the micro-batches; the result is the gradient of the full batch.”The shortcut that causes the mistake: true when each is a sum, or already divided by the full , but here each one is a mean over rows.
- It is times the full-batch gradient: each is already a mean, so the sum of of them must be divided by (Problem 9). Switching from one batch of to micro-batches then multiplies the effective learning rate by , which looks like a training instability rather than an arithmetic slip.
Print this set: batched-backprop.pdf (problems, answers, and worked solutions on separate pages).