AI Hints
Home›Fine-Tuning LLMs Tutorial›Fitting Training into Memory
Fine-Tuning LLMs · Lesson 62 of 120

Gradient Accumulation

Big batches, small memory.

⏱ 2 min read▶ Video at 1:36:42🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Big batches give smoother, steadier training. But big batches need lots of memory for activations. Gradient accumulation gives us the best of both.

  • Big batches: steadier
  • But need more memory
  • Accumulation: both

How it works

Instead of one big batch, we run several small batches. After each one, we compute gradients, but we don't update the weights yet. The gradients add up. After, say, four small batches, we take one update step. The result is almost the same as one batch, four times bigger. But only one small batch is in memory at a time.

keyvalue
Runa small batch, compute gradients
Don't updatejust add up the gradients
After N batchesone weight update
Effective batchbatch size × N

Same effective batch

Let's compare three setups for our data. Each multiplies the batch size by the accumulation steps. Run it. All three give an effective batch of eight, and sixty six weight updates per epoch. The last one needs only one example in memory at a time. It's slower, but it fits on a much smaller GPU.

app.pypython
import math

examples = 527
for batch, accum in [(8, 1), (2, 4), (1, 8)]:
    effective = batch * accum
    updates = math.ceil(examples / effective)
    print(f"batch {batch} x accumulate {accum} = effective batch {effective},"
          f" {updates} weight updates per epoch")
Output
batch 8 x accumulate 1 = effective batch 8, 66 weight updates per epoch
batch 2 x accumulate 4 = effective batch 8, 66 weight updates per epoch
batch 1 x accumulate 8 = effective batch 8, 66 weight updates per epoch

In SFTConfig

In SFT config, set per device train batch size to the small batch, and gradient accumulation steps to N. For example, a batch of two, and four accumulation steps. Keep the learning rate you'd use for the effective batch size.

keyvalue
per_device_train_batch_size2
gradient_accumulation_steps4
Effective batch8
Learning rateas for batch 8

Summary

Let's recap. Gradient accumulation adds up gradients over several small batches, then updates once. The effective batch is batch size times steps. And it trades speed for memory. Next, another way to save activation memory.

Key takeaways
  • Add up gradients
  • batch × steps
  • Slower, but fits
Next up: Gradient Checkpointing — trade time for memory