Inferensys

Glossary

Gradient Checkpointing

Gradient checkpointing is a memory optimization technique for neural network training that trades increased computation for reduced memory usage by selectively storing and recomputing intermediate activations during backpropagation.
Engineer optimizing context window usage on laptop, token usage charts visible, technical work session.
MEMORY OPTIMIZATION

What is Gradient Checkpointing?

Gradient checkpointing is a memory-for-compute trade-off technique essential for training large neural networks on hardware with limited GPU memory.

Gradient checkpointing is a memory optimization technique for neural network training that trades increased computation for reduced memory consumption. During the forward pass, instead of saving all intermediate activations (which is memory-intensive), the system selectively saves only a subset, known as checkpoints. The unsaved activations are later recomputed during the backward pass when needed for gradient calculation. This strategic recomputation enables the training of models that would otherwise exceed available GPU memory.

The technique is governed by a checkpointing schedule, which determines which activations to store. A common strategy is to store activations at the boundaries of model segments. While it reduces peak memory usage by approximately the square root of the number of layers, it increases total computation time by up to 30%. It is a foundational method for enabling large-scale model training and is often combined with other parallelism techniques like model and data 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 larger than available GPU memory by strategically saving and recomputing intermediate activations.

01

Core Trade-Off: Memory vs. Compute

Gradient checkpointing fundamentally trades increased computation for reduced memory consumption. During the standard backpropagation algorithm, all intermediate activations from the forward pass must be stored to compute gradients, leading to an O(n) memory complexity with respect to network depth. Checkpointing reduces this to O(√n) by saving only a subset of these activations (checkpoints). The non-checkpointed activations are recomputed during the backward pass from the nearest saved checkpoint, requiring additional forward passes but freeing significant GPU VRAM. This is a classic time-memory trade-off, making it possible to train models that would otherwise cause out-of-memory errors.

02

Selective Activation Storage

The technique does not save every layer's output. Instead, it strategically selects specific layers as checkpoints. Common strategies include:

  • Uniform Checkpointing: Saving every k-th layer.
  • Dynamic Programming-Based Selection: Using an algorithm to determine the optimal set of layers to checkpoint to minimize total recomputation cost for a given memory budget.
  • Manual Selection: For models with known bottlenecks (e.g., exceptionally large attention layers), engineers manually designate those layers as checkpoints. The choice directly balances the memory saved against the computational overhead incurred during recomputation.
03

Recomputation During Backward Pass

This is the computational cost of the optimization. During the backward pass, when the gradient for a non-checkpointed layer is needed, the system performs a local forward recomputation. It starts from the nearest upstream checkpoint, re-executes the forward pass through the necessary layers, calculates the required activations, uses them for the gradient calculation, and then discards them again. This process turns one monolithic backward pass into a series of smaller backward passes interspersed with recomputation steps. The overhead is non-trivial but predictable, typically increasing total training time by 20-40%.

04

Enables Larger Models & Batch Sizes

The primary benefit is the ability to overcome hardware memory constraints. By drastically reducing the peak memory footprint of the training process, gradient checkpointing allows for:

  • Training models with more parameters than GPU VRAM would normally permit.
  • Using larger batch sizes, which can improve training stability and convergence speed.
  • Adding more features or context length to a model without changing hardware. This is critical for state-of-the-art LLMs and vision transformers where model size is a key differentiator.
05

Implementation in Major Frameworks

Gradient checkpointing is a standard feature in deep learning frameworks, abstracting away the complex recomputation logic.

  • PyTorch: torch.utils.checkpoint.checkpoint and torch.utils.checkpoint.checkpoint_sequential. It uses a custom autograd Function that reruns the forward pass in a no-grad context during backward.
  • TensorFlow: tf.recompute_grad decorator or the GradientTape with explicit checkpointing.
  • JAX: jax.checkpoint (formerly jax.remat). Integration is typically a one-line wrapper around a model block, but requires the wrapped function to be deterministic and without side effects, as it will be executed multiple times.
06

Related Optimization: CPU Offloading

Gradient checkpointing is often combined with activation offloading for further memory savings. In this hybrid approach, the checkpoints (saved activations) are not kept in expensive GPU VRAM but are instead moved to the host's CPU RAM. They are fetched back to the GPU only when needed for recomputation. This introduces additional PCIe transfer overhead but can enable training models that are 2-5x larger than GPU memory alone would allow. Tools like DeepSpeed (via its ZeRO-Offload optimizer) and PyTorch's torch.cuda.set_per_process_memory_fraction can facilitate this pattern.

COMPARISON

Gradient Checkpointing vs. Other Memory Optimization Techniques

A technical comparison of memory optimization strategies used during the training and inference of large neural networks, highlighting trade-offs between memory, compute, and implementation complexity.

Feature / MetricGradient CheckpointingModel Parallelism (Tensor/Pipeline)Quantization (e.g., INT8/FP8)Pruning

Primary Optimization Target

Activation memory during training

Model parameter memory

Weight & activation memory

Model parameter memory

Core Mechanism

Selectively saves activations; recomputes others during backward pass

Distributes model layers or tensors across multiple devices

Reduces numerical precision of weights/activations (e.g., 32-bit to 8-bit)

Removes redundant or low-saliency weights/neurons

Memory Reduction (Typical)

Up to 70-80% for activations

Enables models larger than single GPU memory

50-75% reduction for weights

10-50% reduction in parameters

Compute Overhead

High (30-40% increase in training time due to recomputation)

High (Communication overhead between devices)

Low (Hardware-accelerated low-precision ops)

Low to Moderate (Sparse computation may not be fully accelerated)

Applicable Phase

Primarily training

Training & inference

Primarily inference (QAT for training)

Training (pruning-aware) & inference

Implementation Complexity

Moderate (Framework-integrated, e.g., torch.utils.checkpoint)

High (Requires significant model code refactoring & orchestration)

Low (Many post-training tools; QAT requires retraining)

Moderate (Requires iterative pruning & fine-tuning cycles)

Impact on Model Accuracy

None (Exact computation preserved)

None (Exact computation preserved)

Minimal to Moderate (Controlled accuracy loss)

Moderate (Risk of accuracy degradation)

Hardware Requirements

Standard GPUs

Multiple GPUs with high-speed interconnects (NVLink, InfiniBand)

GPUs with low-precision support (e.g., Tensor Cores)

Standard GPUs (benefits from sparse tensor cores)

IMPLEMENTATION LANDSCAPE

Frameworks and Platforms Implementing Gradient Checkpointing

Gradient checkpointing is a foundational memory optimization technique integrated into major deep learning frameworks and specialized training platforms. Its implementation varies from core library functions to automated, system-level management.

01

PyTorch

PyTorch provides native gradient checkpointing via the torch.utils.checkpoint module. The checkpoint and checkpoint_sequential functions allow developers to wrap model segments, trading compute for memory.

  • Core Function: torch.utils.checkpoint.checkpoint(function, *args, **kwargs)
  • Mechanism: During the forward pass, only the input and the function are saved. The segment's activations are recomputed during the backward pass.
  • Use Case: Essential for training large transformer models (e.g., LLMs, vision transformers) on memory-constrained hardware.
  • Consideration: Requires the wrapped function to be stateless (no in-place operations on tensors requiring grad) to guarantee correct gradient computation.
02

TensorFlow

TensorFlow implements gradient checkpointing through the tf.recompute_grad decorator and the tf.contrib.layers.recompute_grad function (in older TF 1.x). In modern TF 2.x, the pattern is often integrated into custom training loops or high-level APIs like Keras with custom callbacks.

  • Core Decorator: tf.recompute_grad creates a function that recomputes its forward pass during the backward pass.
  • Integration: Commonly used within custom layer definitions or model subclassing to mark specific computational blocks for recomputation.
  • Framework Support: Fully supported in both eager execution and graph mode, though implementation details differ.
03

JAX

In JAX, gradient checkpointing (rematerialization) is achieved via the jax.checkpoint transformation (formerly jax.remat). It is a first-class citizen in JAX's functional transformation system, allowing fine-grained control over the recomputation strategy.

  • Core Transformation: jax.checkpoint(fun, **kwargs) returns a transformed version of fun that rematerializes its intermediates.
  • Policies: Supports advanced policies like policy=jax.checkpoint_policies.everything_saveable or custom functions to determine which sub-expressions to save.
  • Advantage: Seamlessly composes with other JAX transformations (jit, grad, vmap), making it powerful for optimizing complex, composable functions in high-performance computing.
GRADIENT CHECKPOINTING

Frequently Asked Questions

Gradient checkpointing is a critical memory optimization technique for training large neural networks. This FAQ addresses common technical questions about its mechanisms, trade-offs, and implementation.

Gradient checkpointing is a memory optimization technique that trades compute for memory by selectively saving only certain intermediate activations during the forward pass and recomputing the others during the backward pass. During the standard forward pass of neural network training, all intermediate layer outputs (activations) are stored in memory to calculate gradients later. Gradient checkpointing reduces this memory footprint by saving only a subset of these activations, known as checkpoints. During the backward pass, when gradients for a non-checkpointed layer are needed, the system re-executes the forward pass for that segment of the network, starting from the nearest upstream checkpoint. This recomputation eliminates the need to store all activations, enabling the training of models that would otherwise exceed GPU memory limits.

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.