PIXELBANKv9.1.0
Menu

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:

Input:
None
Output:
{'initial_weight': [0.7645, -0.8049], 'final_weight': [19.8107, 22.0265], 'weight_changed': True}
Reasoning:
  • We start by initializing the model with torch.manual_seed(42) and creating an nn.Linear(2, 1) model, resulting in initial weights of approximately [0.7645,−0.8049][0.7645, -0.8049].
  • 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 ((prediction−target)2)((prediction - target)^2) for each batch.
  • After all 4 batches, we call optimizer.step() to update the model weights, and then optimizer.zero_grad() to reset the gradients. This results in final weights of approximately [19.8107,22.0265][19.8107, 22.0265].
  • Since the final weights are different from the initial weights, we return a dictionary with "weight_changed" set to True, along with the initial and final weight values.

Constraints:

  • Accumulate over 4 batches before stepping
  • Use SGD with lr=0.1
  • Use MSE loss
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Gradient Accumulation Over Steps - Medium | PixelBank