Activation checkpointing: keep the boundaries, recompute the middle
激活检查点
Compute identical full-chain gradients while counting the extra forward calls and logical activation storage.
activation-checkpointingStart with the problem
Backpropagation needs intermediate values from the forward pass. Keeping every activation can use more memory than the model weights. Activation checkpointing keeps selected boundary values, discards intermediate activations, and reconstructs them when their gradients are needed.
This is different from saving a training checkpoint to resume tomorrow. Here a “checkpoint” is a retained activation inside one computation. Chen and colleagues, Section 4 and Algorithm 1, describe a segmented chain that trades repeated forward computation for lower activation memory. We implement that mechanism directly, so both the saved values and the extra calls can be counted.
Definitions and derivation
Consider N scalar tanh layers with distinct parameters. The bar over h denotes the loss derivative with respect to that activation. Starting from the final adjoint hN−y, the chain rule gives:
Backward for layer i needs both its input hᵢ₋₁ and output hᵢ. Full storage saves all N+1 activations. Segmenting the chain into blocks of at most B layers saves the input plus each block endpoint. During reverse traversal, reconstruct a block from its saved starting value, hold its local activations, compute that block’s parameter gradients, then release the local values.
Counting references in our deliberately simple storage scheme gives:
The first term counts boundary slots; B+1 counts the largest local block. Shared boundary values are counted in both tables. This is a conservative logical-slot count, not a count of distinct allocated float objects or measured peak bytes. The balance between N/B and B explains the square-root choice for an equal-cost chain.
Our implementation recomputes every block in full once. Its call counts are:
Doubling forward calls does not double total training time: backward work, operation costs and memory traffic also matter. Parameters and their gradients still require O(N) storage in this scalar chain. The square-root claim concerns retained activations under the stated model, not total training memory.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program evaluates 16 layers, each initialized with weight 0.9 and bias 0.02. The input is 0.3 and target 0.5. It returns all weight gradients, bias gradients, the input gradient, loss and counters. The code does not update weights between the initial forward pass and recomputation.
import numpy as np
def evaluate(weights, biases, h0=0.3, target=0.5, block=None):
weights, biases = np.asarray(weights, dtype=float), np.asarray(biases, dtype=float)
n = len(weights)
if weights.ndim != 1 or biases.shape != weights.shape or not 1 <= n <= 64 or not np.isfinite(np.r_[weights, biases, h0, target]).all():
raise ValueError('Use 1 to 64 finite scalar layers.')
if block is not None and (type(block) is not int or not 1 <= block <= n):
raise ValueError('Block size must be an integer from 1 to depth.')
stored, h, calls = {0: float(h0)}, float(h0), 0
for i in range(n):
h = float(np.tanh(weights[i] * h + biases[i])); calls += 1
if block is None or (i + 1) % block == 0 or i + 1 == n:
stored[i + 1] = h
value, adjoint = (h - target) ** 2 / 2, h - target
gw, gb = np.zeros(n), np.zeros(n)
peak = len(stored)
boundaries = list(stored) if block is not None else [0, n]
for start, end in reversed(list(zip(boundaries[:-1], boundaries[1:]))):
if block is None:
local = stored
else:
local = {start: stored[start]}
for i in range(start, end):
local[i + 1] = float(np.tanh(weights[i] * local[i] + biases[i])); calls += 1
peak = max(peak, len(stored) + len(local))
for i in range(end - 1, start - 1, -1):
pre = adjoint * (1 - local[i + 1] ** 2)
gw[i], gb[i] = pre * local[i], pre
adjoint = pre * weights[i]
return value, gw, gb, adjoint, calls, peak
if __name__ == '__main__':
for block in (None, 4):
result = evaluate(np.full(16, 0.9), np.full(16, 0.02), block=block)
print('block', block, 'loss', round(result[0], 12), 'input gradient', round(result[3], 12),
'forward calls', result[4], 'logical activation slots', result[5])
Actual output:
block None loss 0.047575947309 input gradient -0.025169962066 forward calls 16 logical activation slots 17
block 4 loss 0.047575947309 input gradient -0.025169962066 forward calls 32 logical activation slots 10
With block length 4, five boundary slots plus five local slots give a peak of 10, compared with 17 full-storage slots. Both methods produce loss 0.047575947309 and input gradient −0.025169962066. Tests compare every parameter gradient and independently perturb parameters and input for finite differences. Uneven block lengths and the extremes B=1 and B=N are also checked; checkpointing is not automatically a storage improvement for every choice of B.
When the method fails
Recomputation must reproduce the function whose derivative is wanted. Changing parameters, using a different dropout mask, consuming random numbers differently or updating running statistics twice can break equivalence. A deterministic tanh chain avoids those issues, which is why it is useful for learning the storage tradeoff before adding a framework.
The PyTorch 2.8 checkpoint documentation describes RNG preservation, device-related limitations and reentrant versus non-reentrant implementations. It recommends explicitly using the non-reentrant variant. Its runtime can avoid some recomputation, so our exact 2N count is not a universal PyTorch count. Measure actual GPU peak memory and step time on the model you intend to train. Very uneven layer costs, skip connections and attention workspaces require a more careful partition than equal layer counts.
Exercises with answers
- For N=16 and B=4, what does the slot formula count?
Answer 1: Five boundary references and five local references, giving 10. It excludes parameters, gradients and language-runtime overhead.
- How many forward calls does this checkpoint implementation make for 16 layers?
Answer 2: 32: sixteen initially and sixteen during recomputation. Both variants perform sixteen layer-backward calculations.
- Can weights be updated after each recomputed block during the same backward pass?
Answer 3: Not while claiming the gradient of the original full-chain forward pass. Later recomputation would use a different function.
- Why does the square-root activation bound not imply square-root total memory?
Answer 4: The bound omits parameter arrays, gradient arrays, optimizer state and other workspaces, which need their own accounting.
Sources and next steps
The segmented algorithm follows the mechanism in the primary paper; the scalar tanh construction, exact slot accounting and gradient comparisons are original. The PyTorch source was read for practical constraints, not benchmarked here. Revisit backpropagation for the adjoint recursion and gradient accumulation for a complementary way to reduce simultaneous activation storage.
Make a prediction, then check
What must recomputation preserve to recover the intended gradient?
Learning objectives
- Derive a segmented activation-storage bound and count recomputation.
- Verify all gradients while preserving forward state.
Prerequisites & connections
Explore related knowledge →References
- Training Deep Nets with Sublinear Memory Cost — arXiv v1
Tianqi Chen; Bing Xu; Chiyuan Zhang; Carlos Guestrin · 2016 - torch.utils.checkpoint — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. NumPy 1.26.4 is used in six programs; PBT and curriculum use standard-library exact fractions. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Bilingual SVG charts generated by Matplotlib 3.9.1 from executed chapter functions. Actual weighted gradients, logical activation/call counts and fixed-target excess losses are distinguished from hardware measurements. Both locale figures and sample data are hash-bound.
Source locations checked:
- Training Deep Nets with Sublinear Memory Cost — arXiv v1 · Physical pages 4–5, Section 4.1 and Algorithm 1: segment boundaries, dropping local activations and recomputing them during backward.
- torch.utils.checkpoint — PyTorch 2.8 · Introductory RNG-state note and checkpoint API: recomputation, device limits and use_reentrant=False recommendation.
Related topics