871. Fix gradient accumulation that never resets
Why it matters Gradient accumulation is how you train with a big effective batch on a small GPU. Forgetting to zero gradients is the PyTorch bug everyone hits once (missing optimizer.zero_grad()).
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
train_accum(w, micro_grads, accum, lr) should run SGD with gradient accumulation. Walk through micro_grads in order, adding each to an accumulator. After every accum micro-batches, update w = w - lr * (accumulator / accum) and reset the accumulator to zero. A leftover group with fewer than accum micro-batches at the end is ignored (no update).
Inputs: w is a list or ndarray of shape (d,). micro_grads is a list of gradients of shape (d,). accum is an int >= 1. lr is a float.
Return an ndarray of floats with shape (d,). No rounding.
def train_accum(w, micro_grads, accum, lr)Example 1
Input: train_accum([0.0], [[1.0], [3.0], [2.0], [2.0]], 2, 0.5)
Output: [-2.0]
Example 2
Input: w = [1.0, 1.0], micro_grads = [[1.0, 0.0], [0.0, 1.0]], accum = 1, lr = 1.0
Output: [0.0, 0.0]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Trace the accumulator after the first update.
Hint 2
What should acc be right after w changes?
Hint 3
Set acc back to zeros after each update.
Common mistakes
- Resetting before the update.
- Dividing by the total number of micro-batches.
- Updating on the leftover partial group.
Understand the idea
Each update should use only the micro-batches since the last update. Without the reset, the second update also includes the first group's gradients, so updates grow over time and training diverges. In the example the correct second update uses (2 + 2) / 2 = 2, but the buggy one uses (1 + 3 + 2 + 2) / 2 = 4.
Shapes and data flow
w, acc, g: (d,).