Validate AMP gradient scaling and skipped updates on DGX Spark

Validate AMP gradient scaling and skipped updates on DGX Spark

Mixed-precision training can keep reporting loss values and reducing the learning rate even when parameters have not been updated for several iterations. Non-finite gradients cause the gradient scaler to skip optimizer updates. If the scheduler advances anyway, the “step count” in the training logs drifts away from the actual number of updates. Internal validation on DGX Spark should check this control flow with a small test fixture before introducing a model and dataset.

1. Define the training validation contract first

DGX Spark uses NVIDIA GB10 Grace Blackwell, provides 128GB of LPDDR5x unified memory, and runs NVIDIA DGX OS. Unified memory capacity does not determine numerical range: FP16 intermediate results can still overflow. This article checks only a training loop with one optimizer and one update per iteration. It does not cover gradient accumulation or coordination between multiple optimizers.

The experiment requires PyTorch with support for the local GPU to be installed in the current Python environment. A preinstalled CUDA stack on DGX OS does not mean every Python environment has the same training dependencies. Start by running:

python3 -c 'import torch; print(torch.__version__); print(torch.version.cuda); print(torch.cuda.is_available())'

The final value must be true. If the command reports a missing module, complete the environment setup first. If it reports an unsupported device architecture or an operator execution failure, preserve the error and resolve the build compatibility issue. Switching to CPU execution does not constitute a successful GPU validation.

This article deliberately injects infinite gradients into a newly created small model only. It does not modify drivers, system services, or existing training jobs. Run it in a separate process, and do not copy the fault-injection code into a production training loop.

2. Preserve the order of scaling, unscaling, and updates

FP16 automatic mixed precision typically runs some forward-pass operators at lower precision; it does not require converting all model parameters to FP16. The gradient scaler first scales up the loss, then unscales the gradients before the update while checking for non-finite values.

The correct order is to clear gradients, run the mixed-precision forward pass, scale the loss and backpropagate, unscale gradients, clip them, perform the optimizer update, and update the scale. Clipping before unscaling applies the threshold to amplified gradients, changing its meaning. Also, do not call unscale_() more than once for the same optimizer within a single update.

The following fixture uses plain SGD so that state such as momentum does not affect the observations. Save it as amp_check.py and run python3 amp_check.py. The code uses the current torch.amp API. If that API is unavailable, check the installed version first rather than mixing calling conventions from different tutorials.

import torch

assert torch.cuda.is_available(), "CUDA is required"
torch.manual_seed(23)

model = torch.nn.Linear(4, 2).cuda()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
scheduler = torch.optim.lr_scheduler.StepLR(
    optimizer, step_size=1, gamma=0.9
)
scaler = torch.amp.GradScaler(
    "cuda", init_scale=128.0, growth_interval=100
)
x = torch.ones(8, 4, device="cuda")
target = torch.zeros(8, 2, device="cuda")
updates = 0

def snapshot():
    return [p.detach().clone() for p in model.parameters()]

def run_step(inject):
    global updates
    optimizer.zero_grad(set_to_none=True)
    before = snapshot()
    lr_before = optimizer.param_groups[0]["lr"]
    epoch_before = scheduler.last_epoch

    with torch.autocast(device_type="cuda", dtype=torch.float16):
        prediction = model(x)
        loss = torch.nn.functional.mse_loss(prediction, target)

    assert torch.isfinite(loss).item(), "Non-finite loss"
    scaler.scale(loss).backward()

    if inject:
        next(model.parameters()).grad.view(-1)[0] = float("inf")

    scaler.unscale_(optimizer)
    finite = all(
        torch.isfinite(p.grad).all().item()
        for p in model.parameters() if p.grad is not None
    )
    assert finite == (not inject), "Unexpected gradient state"

    if finite:
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

    scale_before = scaler.get_scale()
    scaler.step(optimizer)
    scaler.update()
    scale_after = scaler.get_scale()
    skipped = scale_after < scale_before

    if not skipped:
        scheduler.step()
        updates += 1

    after = snapshot()
    changed = any(
        not torch.equal(a, b) for a, b in zip(before, after)
    )
    assert all(
        torch.isfinite(p).all().item() for p in after
    ), "Non-finite parameter"

    if inject:
        assert skipped and not changed, "Overflow changed parameters"
        assert scheduler.last_epoch == epoch_before
        assert optimizer.param_groups[0]["lr"] == lr_before
    else:
        assert not skipped and changed, "Expected parameter update"
        assert scheduler.last_epoch == epoch_before + 1

run_step(False)
run_step(True)
run_step(False)
assert updates == 2, "Wrong update count"

3. Use three iterations to distinguish skipping from recovery

The first iteration establishes the normal path: the loss and gradients are finite, parameters change, and the scheduler advances one step. The second iteration changes just one element of an already computed gradient to infinity. Injection happens before unscale_(), allowing the scaler to detect the anomaly during its checks.

The second iteration must meet three conditions simultaneously: the scale decreases, every parameter exactly matches its snapshot, and neither the learning rate nor the scheduler counter changes. The absence of an exception does not prove that the optimizer correctly skipped the update. Unchanged parameters alone do not rule out zero gradients or a zero learning rate.

The third iteration clears the gradients again and runs with normal input. Updates should resume, leaving a final effective update count of two, not three. Clearing gradients here also verifies that anomalous gradients do not carry over into the next iteration. Even if the test happens to pass after removing the clearing operation, that is not a reason to omit gradient management from the production loop.

The fixture passes if the script exits normally without an assertion failure. For any assertion failure, preserve the full exception, environment versions, and the corresponding test iteration. Do not catch the failure and continue generating “success” records.

4. Do not advance the learning-rate scheduler on the wrong signal

The return value of GradScaler.step() is not a universal success indicator. Many optimizers return None even after a normal update. Using that return value to detect skipped updates can leave the scheduler stalled indefinitely.

Under the conditions used here—calling update() once per iteration and not manually overriding the scale—a decrease in the scale identifies an update skipped because of non-finite gradients. During a normal iteration, the scale may stay unchanged or increase after reaching the growth interval. The check is therefore “less than,” not “equal or unequal.”

The parameter-change assertions are suitable only for this fixture, which deliberately produces nonzero gradients. In production training, parameters may remain unchanged because they are frozen, the learning rate is zero, or the update is too small to represent at the current precision. An unchanged parameter must not be treated as a direct definition of overflow.

Production logs should separately record, at a minimum, attempted batches, effective updates, the scale, and the learning rate. Schedulers designed around optimizer updates should follow effective updates. Scheduling policies based on sample counts or training epochs need a separate contract; the same counter cannot be applied mechanically.

5. Check boundary conditions before moving to real training

Remove the infinity injection first, then substitute the real model and loss function. Keep batches small and confirm that every parameter expected to participate in training actually receives a gradient. Enabling the scaler does not automatically bring parameters without gradients into training.

BF16 generally does not need gradient scaling, but that does not mean it cannot produce non-finite results. After changing precision, continue checking the loss, gradients, and parameters, and verify support for the operators actually used. Passing the FP16 fixture does not establish that the real model has converged, nor does it support a performance conclusion.

If the real workload repeatedly skips updates, first inspect anomalous input values, the loss computation, and large-magnitude intermediate results. Then evaluate the learning rate and precision choice. Lowering the initial scale can help diagnose the problem, but it cannot fix an infinite loss already produced by the model itself.

Finally, retain environment versions, precision settings, assertion results for the normal and fault-injected iterations, and the effective update count after the recovery iteration. The validation conclusion should clearly distinguish “safely skipped an update after detecting an anomaly” from “completed a parameter update during normal training.” Both paths must pass before the training control flow can be considered correct.

Frequently asked questions

Does an empty return from GradScaler.step() mean the update was skipped?

No. Many optimizers also return an empty value after a successful update. The example calls update() every iteration and checks scale changes alongside parameter snapshots.

Does BF16 training require gradient scaling?

Usually not. BF16 has a wider exponent range, so typical training does not enable GradScaler. Losses, gradients, parameters, operator support, and training results still need separate validation.

EPYC 7543P Dedicated Server from $454/month

Configure a CloudVni Dedicated Server Browse AMD Rentals

Dedicated Server Specifications

EPYC 7543P configurations offer 128 GB or 256 GB of memory and direct-attached storage with 2×1 TB NVMe drives.