{"slug": "what-is-gradient-checkpointing-and-when-should-you-use-it", "title": "What is gradient checkpointing, and when should you use it?", "summary": "Nodus Compute detailed how gradient checkpointing (activation checkpointing) works in its `sft` fine-tuning runtime, where it is enabled by default, and estimated that it cuts activation memory more than 10x for Qwen3-8B at a cost of 20 to 36% more step time. Using per-layer formulas from Korthikanti et al., the company estimated activation memory for a single 8,192-token sequence falling from 41.1 GB without checkpointing to 7.2 GB with sqrt(36) segmentation and 3.6 GB with every layer checkpointed. The writeup distinguishes the memory technique from training checkpoints that save weights and optimizer state for resume, and advises enabling it only when activations are what overflow the GPU.", "body_md": "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.\n\nNo, 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.\n\nA 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](https://www.nodus-compute.ai/blog/automatic-checkpointing-and-resume-for-training/).\n\nThe two often sit side by side in one config. The Nodus [`sft` runtime](https://www.nodus-compute.ai/docs/reference/runtimes/sft/) 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.\n\nGradient checkpointing and activation checkpointing are the same technique. PyTorch's [`torch.utils.checkpoint` docs](https://docs.pytorch.org/docs/stable/checkpoint.html) call it activation checkpointing, and recent Hugging Face Transformers releases have renamed their methods to match.\n\nIt 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.\n\nThe idea comes from Chen et al.'s 2016 paper, [Training Deep Nets with Sublinear Memory Cost](https://arxiv.org/abs/1604.06174). 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.\n\nThe extra time has a simple ceiling. Korthikanti et al. at NVIDIA note in [Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198) 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.\n\nOn 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.\n\nThe inputs are from the [Qwen3-8B config](https://huggingface.co/Qwen/Qwen3-8B/blob/main/config.json): 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.\n\n| Setup | Units of s x b x h | Activation memory | \n|---|---|---|\n| No checkpointing (34 per layer) | 34 x 36 = 1,224 | 41.1 GB | \n| Checkpoint every 2nd layer | 18 x 2 + 18 x 34 + 34 = 682 | 22.9 GB | \n| 6 segments of 6 layers, the sqrt(36) rule | 6 x 2 + 6 x 34 = 216 | 7.2 GB | \n| Checkpoint every layer | 36 x 2 + 34 = 106 | 3.6 GB | \n\nKorthikanti 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.\n\n*Checkpointing every layer cuts this example's activations from 41.1 GB to 3.6 GB.*\n\nThe 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.\n\nThe 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.\n\nWrap each block's call in `torch.utils.checkpoint.checkpoint` and pass `use_reentrant=False`. The [PyTorch docs](https://docs.pytorch.org/docs/stable/checkpoint.html) recommend the non-reentrant variant and warn that a future release will raise an error when `use_reentrant` is not passed explicitly.\n\n``` python\nimport torch\nfrom torch.utils.checkpoint import checkpoint\n\nclass Stack(torch.nn.Module):\n    def __init__(self, layers, use_checkpointing=True):\n        super().__init__()\n        self.layers = torch.nn.ModuleList(layers)\n        self.use_checkpointing = use_checkpointing\n\n    def forward(self, x):\n        for layer in self.layers:\n            if self.use_checkpointing and self.training:\n                x = checkpoint(layer, x, use_reentrant=False)\n            else:\n                x = layer(x)\n        return x\n```\n\nFor 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()`.\n\nThe 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.\n\nKeep 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`.\n\nOne call on the model, or one flag on the trainer. In the [Transformers v5.24.1 model docs](https://huggingface.co/docs/transformers/main_classes/model), 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.\n\n``` python\nimport torch\nfrom transformers import AutoModelForCausalLM, TrainingArguments\n\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen3-8B\", dtype=torch.bfloat16)\n\n# Transformers v5.24 and later\nmodel.activation_checkpointing_enable(\n    activation_checkpointing_kwargs={\"use_reentrant\": False})\n\n# Older releases (alias until v6)\n# model.gradient_checkpointing_enable(\n#     gradient_checkpointing_kwargs={\"use_reentrant\": False})\n\n# Or let Trainer do it\nargs = TrainingArguments(output_dir=\"out\", bf16=True,\n                         activation_checkpointing=True)  # older: gradient_checkpointing=True\n```\n\nThe 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.\n\nOn Nodus, the `sft` runtime sets `gradientCheckpointing: true` for you. You only touch it to turn it off:\n\n```\nspec:\n  runtime: nodus/sft\n  parameters:\n    gradientCheckpointing: false\n```\n\nExpect 20 to 36% longer steps with every layer checkpointed. The [Hugging Face GPU training guide](https://huggingface.co/docs/transformers/perf_train_gpu_one) 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.\n\n*Most measurements land near the 33% ceiling that one extra forward pass implies.*\n\nMeasured 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.\n\nTurn it on when activations are the part that does not fit. Here is the order we use.\n\nLeave 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](https://www.nodus-compute.ai/blog/vram-needed-for-70b-model/) sizes.\n\nUsually yes, at current list prices. On the [Nodus pricing page](https://www.nodus-compute.ai/pricing/), 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.\n\n| Option | Hours | Cost | \n|---|---|---|\n| H100, no checkpointing (if it fit) | 10 | $26.00 | \n| H100 with checkpointing, +20% | 12 | $31.20 | \n| H100 with checkpointing, +36% | 13.6 | $35.36 | \n| H200, no checkpointing, same speed | 10 | $35.93 | \n\nPrices checked November 25, 2026.\n\n*At list prices, checkpointing on an H100 beats moving to an H200 unless the H200 also runs your step faster.*\n\nThe 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.\n\nNo. 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.\n\nYes. 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.\n\nIt 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](https://arxiv.org/abs/2205.14135) already avoid storing the attention score matrix, which gives a similar saving.\n\nStart 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.\n\n*Originally published on the [Nodus blog](https://www.nodus-compute.ai/blog/gradient-checkpointing-explained/).*", "url": "https://wpnews.pro/news/what-is-gradient-checkpointing-and-when-should-you-use-it", "canonical_source": "https://dev.to/viswaretas_kotra/what-is-gradient-checkpointing-and-when-should-you-use-it-5c6b", "published_at": "2026-11-25 16:38:33+00:00", "updated_at": "2026-11-25 16:43:40.246103+00:00", "lang": "en", "topics": ["machine-learning", "large-language-models", "ai-infrastructure", "mlops"], "entities": ["Nodus Compute", "Qwen3-8B", "PyTorch", "Hugging Face", "NVIDIA", "Korthikanti et al.", "Chen et al."], "also_reported_by": [], "takeaway": "For Qwen3-8B at an 8,192-token sequence, checkpointing every layer cuts estimated activation memory from 41.1 GB to 3.6 GB, while the sqrt(n) segmentation rule yields 7.2 GB, at a cost of 20 to 36% more step time.", "recommendation": {"advice": "Enable gradient checkpointing when activation memory, not weights, is what overflows your GPU; the source estimates over 10x memory savings for roughly 20-36% more step time.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/what-is-gradient-checkpointing-and-when-should-you-use-it", "markdown": "https://wpnews.pro/news/what-is-gradient-checkpointing-and-when-should-you-use-it.md", "text": "https://wpnews.pro/news/what-is-gradient-checkpointing-and-when-should-you-use-it.txt", "jsonld": "https://wpnews.pro/news/what-is-gradient-checkpointing-and-when-should-you-use-it.jsonld"}}