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

Gradient Checkpointing

Trade time for memory.

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

Activations can take more memory than the model itself. Gradient checkpointing is a clever trick. Throw most of them away, and recompute them when they're needed.

  • Activations can be huge
  • Throw most away
  • Recompute when needed

With and without

Without checkpointing, every layer's activations are kept, until the backward pass. That's fast, but uses lots of memory. With checkpointing, only a few are kept, at checkpoints. During backward, the missing ones are recomputed from the nearest checkpoint. That saves a lot of memory, but costs about twenty to thirty percent more time.

Without

  • Keep every activation
  • Fast
  • Lots of memory

With checkpointing

  • Keep only a few
  • ~20–30% slower
  • Much less memory

Turning it on

In SFT config, set gradient checkpointing to true. Or call gradient checkpointing enable on the model. It's switched on in most QLoRA recipes, because memory is almost always the limit. On a small model, with plenty of memory, leave it off, and train faster.

keyvalue
SFTConfiggradient_checkpointing=True
Ormodel.gradient_checkpointing_enable()
QLoRA recipesusually on
Plenty of memoryleave it off

Quick check

Let's check. Your training runs out of memory. Which change does not help? Pause, and think about it. The answer is D. More epochs only make training longer. They don't change memory.

Quick check
Training runs out of memory. Which change does NOT help?

Summary

Let's recap. Gradient checkpointing keeps fewer activations, and recomputes the rest. It saves memory, and costs some time. And it's standard in QLoRA. Next, mixed precision, and sequence length.

Key takeaways
  • Keep a few activations
  • Recompute the rest
  • Memory for time
Next up: Mixed Precision — fast maths, safe updates