BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix16 of 16 in topic

871. Fix gradient accumulation that never resets

MediumDebug and fix Pro

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.

Functiondef 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,).
Topics
Debug and fix
Similar questions
  • Fix the causal mask off-by-oneMedium
  • Fix Adam missing bias correctionMedium
  • Fix attention scores without the transposeMedium
  • Fix the scaler that leaks test dataMedium
All Debug and fix problems
Report
871 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
import numpy as np
​
def train_accum(w, micro_grads, accum, lr):
w = np.asarray(w, dtype=float).copy()
acc = np.zeros_like(w)
for i, g in enumerate(micro_grads, start=1):
acc += np.asarray(g, dtype=float)
if i % accum == 0:
w -= lr * acc / accum
return w
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS