MLCrack

    DEEP LEARNING Β· INTERVIEW QUESTION

    What is gradient accumulation and why is it used for large batch training?

    🟑 intermediate · Training & Optimization

    Hint: Accumulate gradients over multiple mini-batches before updating weights.

    Answer

    Gradient accumulation adds gradients from several microbatches before one optimizer update. For equal-size microbatches, divide each mean loss by the number of accumulation steps; for unequal sizes or padded tokens, normalize by the total number of valid examples/tokens.

    Effective batch size = microbatch size Γ— accumulation steps Γ— data-parallel workers, when their gradients are combined correctly. For example, microbatch 4 and eight accumulation steps on one worker use 32 examples per update.

    This matches a physical large-batch gradient only when the objective decomposes across examples and the computation is otherwise equivalent. BatchNorm still computes statistics on each microbatch. Ordinary accumulation does not supply contrastive negatives across microbatches. Dropout, stochastic transforms, precision and optimizer/scheduler timing can also affect equivalence.

    python
    # Equal-size microbatches; model, optimizer and loss_fn are supplied. optimizer.zero_grad() for batch in microbatches: loss = loss_fn(model(batch.x), batch.y) / len(microbatches) loss.backward() optimizer.step()

    Clip gradients and advance an update-based scheduler once per optimizer step. Accumulation reduces activation-memory demand but usually cannot match the parallel efficiency of processing the large batch at once. Validate quality rather than assuming identical convergence.