Gradient Accumulation Over Steps
Problem Statement
Implement gradient accumulation, where you accumulate gradients over multiple mini-batches before taking an optimizer step.
Background
When GPU memory is limited, you can simulate a larger batch size by accumulating gradients over N forward/backward passes before calling optimizer.step(). Only zero gradients every N steps.
Your Task
The starter code provides 4 mini-batches, a model, and an optimizer. Accumulate gradients over all 4 mini-batches before taking a single optimizer step. This simulates a larger effective batch size of 4x.
Output Format
Returns a dictionary with "initial_weight", "final_weight", and "weight_changed".
Example
None
{'initial_weight': [0.7645, -0.8049], 'final_weight': [19.8107, 22.0265], 'weight_changed': True}- We start by initializing the model with
torch.manual_seed(42)and creating annn.Linear(2, 1)model, resulting in initial weights of approximately . - We then accumulate gradients over 4 mini-batches, computing the MSE loss for each batch and calling
backward()without zeroing the gradients between batches. The losses are calculated as for each batch. - After all 4 batches, we call
optimizer.step()to update the model weights, and thenoptimizer.zero_grad()to reset the gradients. This results in final weights of approximately . - Since the final weights are different from the initial weights, we return a dictionary with
"weight_changed"set toTrue, along with the initial and final weight values.
Constraints
- Accumulate over 4 batches before stepping
- Use SGD with lr=0.1
- Use MSE loss