Inferensys

Glossary

Gradient Checkpointing

Gradient checkpointing is a memory optimization technique for training deep neural networks that trades computational overhead for reduced memory consumption by selectively saving only a subset of layer activations during the forward pass and recomputing the unsaved ones during backpropagation.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
MODEL COMPRESSION TECHNIQUE

What is Gradient Checkpointing?

Gradient checkpointing is a memory optimization technique that trades compute for memory by selectively saving only a subset of layer activations during the forward pass and recomputing the others during the backward pass, enabling the training of larger models.

Gradient checkpointing is a memory-for-compute trade-off technique used during neural network training. It reduces peak memory consumption by strategically saving only a subset of intermediate layer activations from the forward pass. The unsaved activations are recomputed on-demand during the backward pass when needed for gradient calculation. This selective checkpointing allows for the training of models that would otherwise exceed available GPU or accelerator memory, albeit at the cost of increased computational overhead.

The technique is governed by a checkpointing schedule that determines which activations to store. Common strategies include storing every n-th layer or using dynamic programming to find an optimal schedule. It is a form of recomputation and is fundamentally different from pruning or quantization, which alter the model itself. Gradient checkpointing is essential for training massive models, such as large language models (LLMs), and is often combined with other memory-saving techniques like mixed-precision training and model parallelism.

MEMORY OPTIMIZATION TECHNIQUE

Key Characteristics of Gradient Checkpointing

Gradient checkpointing is a memory-for-compute trade-off technique that enables the training of neural networks that would otherwise exceed available GPU memory. It strategically manages which intermediate activations are stored during the forward pass.

01

The Core Trade-Off: Compute for Memory

Gradient checkpointing's fundamental principle is a time-memory trade-off. During the standard backpropagation algorithm, all intermediate activations from the forward pass must be stored to compute gradients, leading to memory usage that scales linearly with model depth. Checkpointing reduces peak memory consumption by selectively saving only a subset of these activations (the checkpoints). The unsaved activations are recomputed on-demand during the backward pass from the nearest checkpoint. This reduces memory usage from O(n) to O(√n) in a naive implementation, at the cost of approximately one additional forward pass per checkpoint segment.

02

Strategic Checkpoint Placement

The efficiency of gradient checkpointing is highly dependent on where checkpoints are placed. Common strategies include:

  • Uniform Placement: Dividing the network into equal segments (e.g., place a checkpoint every 5 layers). Simple but often suboptimal.
  • Memory-Budget-Aware Placement: Using a cost model to place checkpoints where recomputation cost is lowest relative to memory saved. Tools like PyTorch's torch.utils.checkpoint allow manual or automated placement.
  • Layer-Specific Strategies: Treating expensive, memory-intensive layers (e.g., attention blocks in Transformers) as natural checkpoints. The goal is to minimize the total wall-clock time penalty of recomputation while staying within a fixed memory budget.
03

Implementation in Modern Frameworks

Gradient checkpointing is natively supported in major deep learning frameworks with simple APIs:

  • PyTorch: torch.utils.checkpoint.checkpoint(function, *args) wraps a segment of the model. It accepts a recomputation function and its inputs.
  • TensorFlow: tf.recompute_grad decorator or the tf.contrib.layers.recompute_grad function (in older versions).
  • JAX: The jax.checkpoint (formerly jax.remat) transformation, which is composable with other JAX transformations. A critical implementation detail is handling non-deterministic operations (e.g., dropout). Frameworks typically use a RNG state checkpointing mechanism to ensure identical recomputation.
04

Critical Use Case: Large Model Training

This technique is indispensable for training models whose memory footprint exceeds GPU VRAM. Key applications include:

  • Training Very Deep Networks: Enabling research on architectures with hundreds or thousands of layers.
  • Large Batch Sizes: Allowing for larger effective batch sizes on memory-constrained hardware, which can improve training stability.
  • Transformer Models: The self-attention mechanism in models like GPT or BERT has a memory cost that scales quadratically with sequence length. Checkpointing the attention computation is often essential for long-sequence training.
  • Scientific Computing: Training Physics-Informed Neural Networks (PINNs) or other models where the computational graph is exceptionally deep due to iterative solvers.
05

Performance and Overhead Analysis

The overhead of gradient checkpointing is not uniform and must be carefully evaluated:

  • Theoretical Overhead: In an optimal setup with √n checkpoints for an n-layer network, the recomputation adds the equivalent of one extra forward pass, increasing total compute by ~33% (1 forward + 1 backward normally, becomes 2 forward + 1 backward).
  • Practical Slowdown: Real-world slowdown is typically between 20% and 40%, depending on checkpoint placement, hardware, and the ratio of computation to memory bandwidth.
  • Memory Reduction: Peak memory can be reduced by 50-80%, which is the enabling factor. The trade-off is always justified when the alternative is an out-of-memory (OOM) error or severe batch size limitation.
06

Relationship to Other Compression Techniques

Gradient checkpointing is complementary to other model compression and optimization techniques:

  • Vs. Quantization/Pruning: Checkpointing optimizes training-time memory, while quantization and pruning optimize inference-time memory and speed of the final model. They are often used in sequence: checkpoint to train a large model, then prune/quantize for deployment.
  • Synergy with Parallelism: It is frequently combined with model parallelism (splitting layers across GPUs) and pipeline parallelism (where checkpoints naturally align with pipeline stage boundaries).
  • Foundation for Advanced Methods: Concepts from checkpointing inform more advanced memory-saving techniques like offloading (moving activations to CPU RAM) and recomputation-aware scheduling in compilers.
MEMORY OPTIMIZATION COMPARISON

Gradient Checkpointing vs. Other Memory Techniques

A comparison of techniques used to reduce memory consumption during the training of deep neural networks, highlighting trade-offs between memory, compute, and implementation complexity.

Feature / MetricGradient CheckpointingMicro-BatchingOffloading to CPU RAMModel Parallelism

Primary Mechanism

Selectively saves activations; recomputes others during backward pass

Splits a batch into smaller sequential chunks

Moves inactive tensors (e.g., optimizer states) from GPU to CPU memory

Distributes model layers across multiple GPUs/devices

Memory Reduction Target

Activation memory (peak during backward pass)

Activation memory (per micro-batch)

Optimizer state and gradient memory

Model parameter and activation memory

Compute Overhead

High (significant recomputation of forward passes)

Low (minimal extra computation, some pipeline bubbles)

Medium (PCIe transfer latency for swapped tensors)

High (communication overhead between devices)

Implementation Complexity

Medium (requires identifying checkpoint layers; framework support varies)

Low (standard data loader modification)

Medium (requires manual tensor management or library like DeepSpeed)

High (requires significant model refactoring and communication logic)

Optimal Use Case

Training very deep models where activation memory is the bottleneck

Training with large batch sizes on memory-constrained hardware

Training extremely large models where optimizer states dominate memory

Training models too large to fit on a single device's memory, even for a single sample

Hardware Requirement

Single GPU (or data parallelism); maximizes usable model size per GPU

Single GPU; enables larger effective batch sizes

Single GPU with substantial CPU RAM available

Multiple GPUs with high-bandwidth interconnects (e.g., NVLink)

Framework Support

Native in PyTorch (torch.utils.checkpoint), TensorFlow (custom)

Manual implementation or pipeline parallelism libraries

Libraries: DeepSpeed (ZeRO-Offload), PyTorch (manual pin_memory)

Native: PyTorch (torch.nn.parallel), Mesh-TensorFlow, Megatron-LM

Compatibility with Other Techniques

High (often combined with quantization, pruning, and data parallelism)

High (can be combined with gradient accumulation)

High (core component of full Zero Redundancy Optimizer (ZeRO) stages)

Medium (can be combined with pipeline parallelism; complex with checkpointing)

GRADIENT CHECKPOINTING

Frequently Asked Questions

Gradient checkpointing is a critical memory optimization technique for training large neural networks. It strategically trades increased computation for reduced memory consumption, enabling the training of models that would otherwise exceed GPU memory limits.

Gradient checkpointing is a memory optimization technique that trades compute for memory by selectively saving only a subset of layer activations during the forward pass and recomputing the non-checkpointed activations during the backward pass. During the standard forward pass, the algorithm saves the activations from only certain designated 'checkpoint' layers (e.g., every k-th layer). The activations from intermediate, non-checkpointed layers are discarded after use. During the backward pass, when gradients for a segment between two checkpoints are needed, the forward pass for that segment is re-executed from the last saved checkpoint. This recomputation regenerates the necessary intermediate activations on-demand for gradient calculation, after which they are discarded again. The primary trade-off is a 20-30% increase in total computation time for a typical 50% or greater reduction in peak memory usage.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.