Validating activation checkpointing on DGX Spark: RNG, gradients and updates
After enabling activation checkpointing in a training script, memory usage drops—but the convergence curve starts to shift. Do not immediately attribute the change to numerical error. Backpropagation reruns part of the forward computation, so random state, mutable buffers and hidden side effects can all change the gradients. Establish a controlled comparison between ordinary execution and recomputation before increasing the training batch size.
1. Define the correctness contract for recomputation
DGX Spark combines NVIDIA GB10 Grace Blackwell with 128GB LPDDR5x unified memory. Unified memory does not remove capacity limits during training: model parameters, optimizer state and intermediate activations still share the memory budget. Activation checkpointing trades additional computation for lower activation storage by saving fewer intermediate results and recomputing them during the backward pass.
This article assumes an experimental environment running DGX OS with a working CUDA-enabled installation of PyTorch; it does not assume the framework comes preinstalled. First, run the following commands and save their output to confirm that the environment supports the non-reentrant checkpoint interface:
python3 -c 'import torch; print(torch.__version__); print(torch.version.cuda); print(torch.cuda.is_available())'
python3 -c 'import inspect; from torch.utils.checkpoint import checkpoint; print(inspect.signature(checkpoint))'
For validation, fix the initial model values, inputs, labels and random seeds. Use training mode, FP32 and the same optimizer for both paths. Leave automatic mixed precision, compilation and distributed execution out of the initial test. Reduce the number of variables first, then restore the actual training configuration.
Activation checkpointing is not a training checkpoint saved to disk. It does not save optimizer progress and cannot replace the persistent state needed to resume training.
2. Build an executable comparison that includes Dropout
Save the following program as check_recompute.py and run python3 check_recompute.py as a regular user. The example creates only small tensors and does not load model weights. It prints a success marker only after every assertion passes; it fails immediately if CUDA is unavailable or the gradients do not match.
import copy
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
assert torch.cuda.is_available(), "CUDA is required"
torch.use_deterministic_algorithms(True)
class Net(nn.Module):
def __init__(self):
super().__init__()
self.block = nn.Sequential(
nn.Linear(16, 32),
nn.GELU(),
nn.Dropout(0.25),
nn.Linear(32, 16),
)
self.head = nn.Linear(16, 4)
def forward(self, x, recompute):
if recompute:
x = checkpoint(
self.block,
x,
use_reentrant=False,
preserve_rng_state=True,
)
else:
x = self.block(x)
return self.head(x)
torch.manual_seed(71)
reference = Net().cuda()
candidate = copy.deepcopy(reference)
x = torch.linspace(-1, 1, 128, device="cuda").reshape(8, 16)
target = torch.zeros(8, 4, device="cuda")
def run(model, recompute):
model.train()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
optimizer.zero_grad(set_to_none=True)
torch.manual_seed(901)
loss = (model(x, recompute) - target).square().mean()
loss.backward()
gradients = {}
for name, parameter in model.named_parameters():
assert parameter.grad is not None, name
assert torch.isfinite(parameter.grad).all(), name
gradients[name] = parameter.grad.detach().clone()
rng = torch.cuda.get_rng_state().clone()
optimizer.step()
parameters = {
name: parameter.detach().clone()
for name, parameter in model.named_parameters()
}
return loss.detach(), gradients, parameters, rng
loss_a, grads_a, params_a, rng_a = run(reference, False)
loss_b, grads_b, params_b, rng_b = run(candidate, True)
torch.testing.assert_close(loss_a, loss_b, rtol=1e-5, atol=1e-6)
for name in grads_a:
torch.testing.assert_close(
grads_a[name], grads_b[name], rtol=1e-5, atol=1e-6
)
torch.testing.assert_close(
params_a[name], params_b[name], rtol=1e-5, atol=1e-6
)
assert torch.equal(rng_a, rng_b), "CUDA RNG state differs"
print("activation checkpoint validation passed")
The input does not have requires_grad=True, but parameters inside the block must still receive gradients. This is an important check for the non-reentrant path. If a real model contains conditional branches, define the expected set of gradients according to the path taken by each sample. Do not blindly require every parameter to have a gradient in every batch.
If deterministic mode reports an unsupported operator, record the operator and environment, then substitute a deterministic test path. Do not simply disable the check to get a passing result.
3. Diagnose failures layer by layer, not just by comparing loss
If the losses differ, first check the initial model values, training mode and initial random state. If the losses are close but the gradients differ, inspect detach, in-place modifications and hidden state, and verify that both executions took the same branches. If parameter updates differ, also check the optimizer's parameter set and state.
A negative test for random state
Change preserve_rng_state to False in the example and run it again. Dropout recomputation may use a different mask, so the gradient checks or the final random-state check should expose a difference. A single run that happens to pass is not proof of safety. Repeat the test with different seeds and confirm that Dropout is actually in training mode.
The initial forward losses may still match because the difference arises during backward recomputation. The framework's default checkpoint determinism check is no substitute for elementwise numerical comparisons either: matching metadata does not mean matching computed values.
The framework's random-state preservation has a limited scope. Do not assume it provides the same protection for custom generators, external random libraries or operations that temporarily move data to a new device inside the block.
4. Make checkpointed blocks free of side effects
As far as possible, the wrapped function should return outputs based only on its input tensors. Do not write evaluation files, increment application counters, consume queues or submit training metrics inside it. Recomputation may trigger these actions again. The non-reentrant implementation can also stop early once all required intermediate results are available, so do not rely on the function running “exactly twice.”
Modules with running statistics need a separate audit. For example, a buffer that updates a mean may change because of repeated execution even when parameter gradients remain close. For a real model, compare named_buffers() between the two paths as well as named_parameters().
Move logging, checkpoint export and step counting outside the block. If internal state is unavoidable, first define how many times it is allowed to update, then build negative tests for that contract. A single training run without errors is not enough to establish correctness.
5. Validate the benefits only after correctness passes
When returning to the real model, introduce only one variable at a time: increase tensor sizes first, add the actual optimizer next, and restore mixed precision and compilation last. Keep the loss, gradient, parameter-update and buffer comparisons at every stage. Set tolerances according to the data type and error budget; do not keep relaxing them until the test passes.
Warm up and complete CUDA synchronization before measuring. Prefer separate processes for the two paths, with identical input shapes. Reset peak statistics before measuring peak allocated memory, and synchronize again before reading the results. Timing must cover the full forward pass, backward pass and update; otherwise, it will miss the cost of recomputation.
max_memory_allocated() reports the peak tracked by the framework's allocator, not total system-wide unified memory usage. Also monitor available system memory, swap activity and process resident memory. A lower framework figure accompanied by greater system memory pressure does not count as passing capacity validation.
The final record should include environment versions, block boundaries, seeds, error thresholds, per-parameter check results and full training-step time. Activation checkpointing is ready for the formal experiment configuration only when the numerical contract passes, hidden state does not drift and the memory savings are reproducible.
Frequently asked questions
Does matching loss prove activation checkpointing is correct?
No. Verify that every trainable parameter has a finite gradient, then compare parameters after one optimizer update. Similar losses do not rule out a disconnected gradient path.
Should a checkpointed block containing Dropout preserve RNG state?
For equivalent ordinary and recomputed execution, explicitly set preserve_rng_state=True and start both test runs from the same RNG state. Custom generators, external random libraries and device transfers inside the block require separate checks.