Lowering PyTorch's Memory Consumption for Selective Differentiation

Samarth Bhatia, Felix Dangel

TL;DR

PyTorch’s automatic differentiation engine unnecessarily saves intermediate activation tensors for certain frozen layers (such as convolutions and evaluation-mode batch normalization), bloating GPU memory during selective fine-tuning or adversarial attacks. The authors introduce MemSave, a drop-in replacement library for these layers that checks parameter differentiability before saving tensors, cutting peak memory by up to 33% on standard CNNs/Transformers and up to 6× when batch normalization is in evaluation mode—all with zero runtime overhead.

What Problem Does This Paper Address?

In modern machine learning workflows, we rarely train every parameter from scratch. Scenarios like parameter-efficient fine-tuning (PEFT), surgical layer-tuning, adversarial example generation, and neural style transfer require gradients for only a small subset of the network’s parameters or its inputs—a setup the authors call selective differentiation.

Ideally, if a layer’s weights are frozen (requires_grad = False), the backward pass only needs to backpropagate gradients to earlier layers. For linear operations ($Z = W * X + b$), the gradient with respect to the input $X$ depends strictly on the weights $W$, not on $X$ itself. Therefore, the activation $X$ can be safely discarded. However, PyTorch’s autograd engine does not check whether $W$ requires gradients; once it detects that the child tensor needs a gradient, it unconditionally caches $X$ on the backward tape. This behavior needlessly hoards precious VRAM.

Methods

The authors introduce lightweight, drop-in replacement modules using torch.autograd.Function:

  • Differentiability-Agnostic Linear Operations: Custom autograd primitives for 1D/2D/3D convolutions, transpose convolutions, and evaluation-mode batch normalization. These check the differentiability of both weights and inputs during the forward pass, storing activations only when the corresponding weights require gradients.
  • Overcoming Layer Interleaving (ReLU & Dropout): Even if a convolution drops its input, an adjacent preceding layer (like standard ReLU) might store that exact same tensor. To prevent this:
  • Mask-based ReLU: Saves a 1-byte boolean mask instead of a 4-byte single-precision float tensor, slashing the activation cache size by 4×.
  • RNG-seeded Dropout: Stores the random seed and recomputes the dropout mask on the backward pass rather than saving the mask tensor in memory.
  • Automated Network Conversion: A single converter utility scans an existing torch.nn.Module and swaps standard layers with memory-saving equivalents.

Datasets

  • Not discussed in the paper. The authors evaluate memory and runtime using synthetic, fixed-shape mini-batch tensors passed through standard pre-trained architectures (e.g., $(64, 3, 224, 224)$ for vision models and $(64, 256, H)$ for language models) to precisely isolate autograd tape memory without I/O or data-loader confounding factors.

Key Insights and Ideas

  • Inconsistent Autograd Optimization: PyTorch’s nn.Linear (fully-connected) implementation is already optimized to discard inputs when weights are frozen. However, its convolution (nn.ConvNd), transpose convolution (nn.ConvTransposeNd), and evaluation-mode nn.BatchNorm2d implementations were overlooked and unconditionally cache inputs.
  • The "Neighboring Layer" Trap: Optimizing linear operations alone yielded zero initial savings on ResNet because the interleaved activation layers (ReLU) cached the exact same tensors. Fixing selective differentiation requires co-designing activation layers.
  • Zero Runtime Cost: Because the autograd backward routines call standard backend operations (torch.ops.aten / torch.nn.functional), memory savings do not trade off execution speed.

Key Results

Experiments conducted across multiple CNN backbones and large language models (LLMs) on an NVIDIA RTX A6000 GPU demonstrated significant memory savings:

  • ResNet-101: When computing gradients only for the input (adversarial setup), memory consumption dropped from 7.83 GiB to 5.24 GiB (a 33% reduction), with backward run time matching PyTorch defaults (~0.36 s vs. 0.37 s).
  • Evaluation-Mode BatchNorm CNNs: Enabling evaluation mode for BatchNorm enabled massive gains. Peak memory dropped by up to 6× (e.g., DeepLabv3 dropped from 22.82 GiB to 4.28 GiB, or 0.19× the default memory; ResNeXt101 dropped from 15.15 GiB to 2.46 GiB, or 0.16×).
  • Attention-Based LLMs: In fine-tuning scenarios (e.g., tuning only LayerNorm or input adapters) across LLaMA3-8B, Mistral-7B, Phi3-4B, and T5, MemSave reduced peak memory by 10% to 32% without degrading throughput.

Limitations and Future Work

  • Fully Differentiable Penalty: When all layers require gradients, storing the custom ReLU boolean mask adds redundant metadata, resulting in a minor memory overhead (~4–10% increase).
  • PyTorch Boolean Representation: PyTorch currently allocates 1 byte per boolean value rather than packing 8 booleans per byte (1 bit each). True 1-bit boolean support would unlock up to an additional 8× reduction in activation mask memory.
  • Future Applications: The authors plan to expand evaluations to real-world parameter-efficient LLM tuning setups, particularly low-rank adaptation (LoRA).

Summary updated

BibTeX
@inproceedings{bhatia2024lowering,
  author = {Samarth Bhatia and Felix Dangel},
  title = {{Lowering PyTorch's Memory Consumption for Selective Differentiation}},
  booktitle = {WANT @ ICML},
  year = {2024},
  url = {https://openreview.net/forum?id=KsUUzxUK7N},
}

Loading related content...

Figure