What is gradient checkpointing, and when should you use it?
DEV Community

What is gradient checkpointing, and when should you use it?

Gradient checkpointing, also called activation checkpointing, saves GPU memory in training by keeping only a few activations from the forward pass and recomputing the rest during the backward pass.

Nodus turns it on by default in its sft fine-tuning runtime: in our Qwen3-8B estimate it cuts activation memory more than 10x, and published measurements put the cost at 20 to 36% more step time. Use it when activations are what overflow your GPU, and leave it off when the model already fits with a batch size that keeps the GPU busy.

Is gradient checkpointing the same as saving a training checkpoint?

No, and the shared word causes real confusion. Gradient checkpointing is a memory trick inside one training step. Nothing is written to disk, and nothing survives a crash.

A training checkpoint is a saved copy of the weights, optimizer state and data position, written every few hundred steps so a run can resume after a failure. If that is what you are looking for, read our guide to automatic checkpointing and resume.

The two often sit side by side in one config. The Nodus sft runtime has gradientCheckpointing, default true, described as "recompute activations to save GPU memory". It also has saveSteps, default 200, the number of steps between recovery checkpoints. One saves memory, the other saves progress.

Gradient checkpointing and activation checkpointing are the same technique. PyTorch's torch.utils.checkpoint docs call it activation checkpointing, and recent Hugging Face Transformers releases have renamed their methods to match.

How does gradient checkpointing work?

It throws away most of what the forward pass would normally keep. In ordinary training, every intermediate tensor a layer produces stays in memory until the backward pass uses it to compute gradients. With checkpointing, only the input to each checkpointed block is kept. When the backward pass reaches that block, it runs the block's forward again to rebuild what it needs.

The idea comes from Chen et al.'s 2016 paper, Training Deep Nets with Sublinear Memory Cost. Split an n-layer network into about sqrt(n) segments and keep only the segment boundaries. Memory then grows with sqrt(n) instead of n, for "the computational cost of an extra forward pass per mini-batch". The paper reports a 1,000-layer residual network going from 48 GB to 7 GB with 30% more running time.

The extra time has a simple ceiling. Korthikanti et al. at NVIDIA note in Reducing Activation Recomputation in Large Transformer Models that the backward pass needs about twice the FLOPs of the forward pass. A normal step is therefore 1 forward plus 2 forward-equivalents of backward, or 3 units. Recomputing everything adds 1 more, so 4 / 3 = 1.33, at most about 33% more compute.

How much memory does gradient checkpointing save?

On a transformer, often 90% or more of the activation memory. We worked it out for Qwen3-8B, using the per-layer formulas from Korthikanti et al. Their formulas are for GPT-style layers, so treat the results as estimates for Qwen3's gated MLP and grouped-query attention.

The inputs are from the Qwen3-8B config: hidden size h = 4,096 and L = 36 layers. We assume one 8,192-token sequence (s = 8,192, b = 1) in 16-bit precision, with a fused attention kernel. One unit of s x b x h bytes is then 8,192 x 4,096 = 33,554,432 bytes, about 33.6 MB.

Setup Units of s x b x h Activation memory No checkpointing (34 per layer) 34 x 36 = 1,224 41.1 GB Checkpoint every 2nd layer 18 x 2 + 18 x 34 + 34 = 682 22.9 GB 6 segments of 6 layers, the sqrt(36) rule 6 x 2 + 6 x 34 = 216 7.2 GB Checkpoint every layer 36 x 2 + 34 = 106 3.6 GB Korthikanti et al. put the stored input of a checkpointed layer at 2 x s x b x h bytes, against 34 x s x b x h for a full layer. When we count peak memory, we add the activations of the block being recomputed: 34 units for one layer, 6 x 34 for a 6-layer segment.

Every layer works out to 2.4 GB of stored inputs plus 1.1 GB for the layer being rebuilt. Checkpointing every layer cuts this example's activations from 41.1 GB to 3.6 GB.

The table holds a detail the sqrt(n) rule hides. Chen's rule assumes the cost of storing a segment boundary is about the same as the cost inside a layer. In a transformer, a layer's input is 2 units and its insides are 34, about 17x more. The best number of segments is then near sqrt(17 x 36), about 25, not 6. In practice, checkpointing every layer (3.6 GB) or segments of 2 layers (18 segments, about 3.5 GB) is close to the minimum. That is why Hugging Face checkpoints every decoder layer by default rather than using sqrt(n) segments.

How do you use gradient checkpointing in PyTorch?

Wrap each block's call in torch.utils.checkpoint.checkpoint and pass use_reentrant=False. The PyTorch docs recommend the non-reentrant variant and warn that a future release will raise an error when use_reentrant is not passed explicitly.

import torch
from torch.utils.checkpoint import checkpoint

class Stack(torch.nn.Module):
    def __init__(self, layers, use_checkpointing=True):
        super().__init__()
        self.layers = torch.nn.ModuleList(layers)
        self.use_checkpointing = use_checkpointing
    def forward(self, x):
        for layer in self.layers:
            if self.use_checkpointing and self.training:
                x = checkpoint(layer, x, use_reentrant=False)
            else:
                x = layer(x)
        return x

For an nn.Sequential model, checkpoint_sequential(model, segments, x, use_reentrant=False) splits it into segments for you.

We ran both forms on PyTorch 2.15 on CPU with a 12-block MLP stack. The gradients matched the plain version exactly, with a maximum difference of 0.0. That checks correctness, not speed or memory, which you should measure on your own GPU with torch.cuda.max_memory_allocated().

The non-reentrant variant also avoids an old trap. The docs say the reentrant variant needs at least one input and output with requires_grad=True, or the checkpointed part gets no gradients. That bites LoRA runs, where the frozen base model's inputs do not require gradients. The non-reentrant version has no such requirement.

Keep the recomputed forward identical to the first one. The docs warn that if a global variable or other state changes between the two calls, you can get an error or silently wrong gradients. Dropout is handled for you, because preserve_rng_state defaults to True.

How do you turn it on in Hugging Face Transformers and Nodus?

One call on the model, or one flag on the trainer. In the Transformers v5.24.1 model docs, the method is activation_checkpointing_enable(). The old gradient_checkpointing_enable() still works as a deprecated alias until v6, and older releases only have the old name.

import torch
from transformers import AutoModelForCausalLM, TrainingArguments

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-8B", dtype=torch.bfloat16)

# Transformers v5.24 and later
model.activation_checkpointing_enable(activation_checkpointing_kwargs={"use_reentrant": False})

# Older releases (alias until v6)
# model.gradient_checkpointing_enable(
#     gradient_checkpointing_kwargs={"use_reentrant": False})

# Or let Trainer do it
args = TrainingArguments(output_dir="out", bf16=True, activation_checkpointing=True)
# older: gradient_checkpointing=True

The new method takes every_n_layers, which checkpoints only every n-th decoder layer and lets the rest keep their activations. That is the 22.9 GB row in our table, with roughly half the recompute cost. It also takes offload, which holds the saved inputs in pinned CPU memory and makes each step slower.

On Nodus, the sft runtime sets gradientCheckpointing: true for you. You only touch it to turn it off:

spec:
  runtime: nodus/sft
  parameters:
    gradientCheckpointing: false

How much slower is training with gradient checkpointing?

Expect 20 to 36% longer steps with every layer checkpointed. The Hugging Face GPU training guide quotes about 20%. Chen et al. measured 30% on their residual network. Korthikanti et al. write that full recomputation can add as much as 30 to 40% to compute time, and they measured 36% on their largest models. Most measurements land near the 33% ceiling that one extra forward pass implies.

Measured overheads can sit below 33% because the non-reentrant variant stops recomputing once it has what it needs, and because some step time is not compute.

When should you turn on gradient checkpointing?

Turn it on when activations are the part that does not fit. Here is the order we use.

  1. Find the biggest consumer first. If weights, gradients and optimizer state already overflow the GPU, checkpointing cannot help. Our CUDA out of memory guide shows how to split the total.
  2. Try a smaller micro-batch with gradient accumulation. It adds no compute. If micro-batch 1 still runs out of memory, or leaves the GPU underused, move on.
  3. Turn on gradient checkpointing. This is the usual fix for long sequences and for full fine-tuning on one GPU.
  4. Use LoRA or QLoRA when model state is the problem. They shrink gradients and optimizer state, not activations, which is why most LoRA recipes keep checkpointing on. Our LoRA vs full fine-tuning post covers the quality trade.
  5. Pick a bigger GPU when checkpointing costs more than the extra memory would.
  6. Leave it off for inference. There is no backward pass, so there is nothing to recompute. Serving memory goes to the KV cache instead, which our 70B VRAM guide sizes.

Is gradient checkpointing cheaper than a bigger GPU?

Usually yes, at current list prices. On the Nodus pricing page, the H100 SXM 80 GB is listed at $2.60/hr and the H200 SXM 141 GB at $3.593/hr. Take a fine-tuning job that would need 10 GPU-hours on an H100 if it fit without checkpointing.

Option Hours Cost H100, no checkpointing (if it fit) 10 $26.00 H100 with checkpointing, +20% 12 $31.20 H100 with checkpointing, +36% 13.6 $35.36 H200, no checkpointing, same speed 10 $35.93 Prices checked November 25, 2026.

At list prices, checkpointing on an H100 beats moving to an H200 unless the H200 also runs your step faster. The break-even is the price ratio: $3.593 / $2.60 = 1.38. If checkpointing slows your step by less than 38%, it is cheaper than the larger GPU at the same speed. In practice the H200 is often faster per step too, which lowers that break-even, so measure one step on each before committing a long run.

FAQ

Does gradient checkpointing change model accuracy? No. It recomputes the same values, so gradients match up to normal GPU floating-point nondeterminism, and our CPU test matched exactly. That is why Nodus can leave it on by default in the sft runtime without changing what you train.

Can I combine gradient checkpointing with FSDP or DeepSpeed? Yes. Sharding splits weights, gradients and optimizer state across GPUs, while checkpointing shrinks activations on each GPU, so the two stack. Use sharding when model state is too big and checkpointing when activations are.

What is selective activation recomputation? It is the middle ground from Korthikanti et al.: recompute only the attention parts that are cheap to rebuild but large to store. With sequence parallelism, they cut recomputation overhead by over 90%. Fused attention kernels such as FlashAttention already avoid storing the attention score matrix, which gives a similar saving.

Should I checkpoint the whole model or only some layers? Start with every layer, then back off if you have memory to spare. Checkpointing every 2nd layer roughly halves the recompute cost and still saves memory, as the 22.9 GB row shows.

Originally published on the Nodus blog.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.