Test MLX gradient clipping: global norm and update order
A remote training run reports no errors, yet the loss suddenly veers off course. Investigation reveals that each gradient tensor was clipped separately to the threshold. The logs say “clipping succeeded,” but the implementation does not perform the global clipping specified by the training design. Before running MLX on a cloud Mac, validate this step with a few vectors you can check by hand. That makes problems easier to isolate than watching the loss of a full model.
Define the contract
Treat the gradients of all parameters being updated as one long vector. The global L2 norm is the square root of the sum of squared elements across all tensors. If it exceeds the threshold, multiply every tensor by the same factor. Otherwise, leave the values unchanged.
For example, two tensors containing [3, 0] and [0, 4] have a global norm of 5. With a threshold of 2.5, the results should be [1.5, 0] and [0, 2]. Clipping each tensor separately produces a different result and is not an equivalent implementation.
Clipping limits the norm of the gradients passed to the optimizer. It does not guarantee that the parameter update is also below that threshold. Momentum, adaptive scaling, and weight decay still affect the actual update.
This example requires a finite, positive threshold and nonempty gradients whose elements are all finite. Zero gradients are returned unchanged to avoid division by zero. Define these boundary conditions before deciding whether to use a built-in library function.
Build the fixture
Save the following as clip_check.py in an isolated Python environment with MLX installed. This code handles only lists of floating-point gradients. It deliberately retains host-side checks as a reference for validation, rather than serving as a high-throughput training implementation.
import math
import mlx.core as mx
def clip_global(grads, limit):
if not math.isfinite(limit) or limit <= 0:
raise ValueError("Invalid clipping limit")
if not grads or any(g.size == 0 for g in grads):
raise ValueError("Empty gradient input")
if not all(bool(mx.all(mx.isfinite(g)).item()) for g in grads):
raise ValueError("Non-finite gradient")
squares = [
mx.sum(mx.square(g.astype(mx.float32)))
for g in grads
]
total = squares[0]
for value in squares[1:]:
total = total + value
norm = float(mx.sqrt(total).item())
if not math.isfinite(norm):
raise ValueError("Non-finite norm")
scale = 1.0 if norm <= limit else limit / norm
return [g * scale for g in grads], norm
def close(actual, expected):
target = mx.array(expected, dtype=mx.float32)
assert bool(mx.allclose(
actual, target, rtol=1e-5, atol=1e-6
).item())
g = [mx.array([3.0, 0.0]), mx.array([0.0, 4.0])]
out, norm = clip_global(g, 2.5)
assert abs(norm - 5.0) < 1e-6
close(out[0], [1.5, 0.0])
close(out[1], [0.0, 2.0])
unchanged, _ = clip_global(g, 10.0)
for actual, original in zip(unchanged, g):
close(actual, original)
zero, norm = clip_global([mx.zeros((2,))], 1.0)
assert norm == 0.0
close(zero[0], [0.0, 0.0])
for bad in [float("nan"), float("inf")]:
try:
clip_global([mx.array([bad])], 1.0)
except ValueError:
pass
else:
raise AssertionError("Invalid gradient accepted")
Run python clip_check.py. An exit code of zero means the assertions passed. .item() forces evaluation of the corresponding scalar; merely building the computation graph can otherwise defer errors until a later training step.
Cover the boundaries
Add a case with the threshold set to exactly 5 and verify that the results remain unchanged. Then swap the two tensors and check that the outputs only swap positions. This catches implementations that count only the first tensor or depend on traversal order.
Add a vector containing negative values and verify that clipping preserves signs and the ratios between elements. An assertion that only checks “the norm does not exceed the threshold” would also pass if a faulty implementation zeroed everything out. You must check the expected values as well.
Convert half-precision gradients to single precision before squaring and summing, so the squaring operation does not overflow prematurely. Single precision still has a limited range, however. This example rejects the update if the norm is non-finite, rather than computing a scale factor of zero and continuing. If your workload genuinely requires extremely large values, separately test a norm algorithm that uses stable scaling.
Wire clipping into the update
Real models usually return a nested gradient tree. Extract the leaves from that same tree to compute the norm, then map the results back while preserving the original structure. Do not sort parameters and gradients separately and then pair them by position.
Fix the operation order
If training uses loss scaling, unscale the gradients before checking finiteness and clipping. If it uses gradient accumulation, complete the specified sum or average first, then clip the effective gradients for that update. Clipping each microbatch before summing is generally not equivalent.
Only then call the optimizer update. Rejecting invalid gradients must not also advance optimizer state, the update step count, or the learning-rate scheduler. If the product is intended to skip bad steps rather than stop training, define that behavior as a separate policy.
Integration tests should compare at least the before-and-after state snapshots: valid gradients should produce the expected update, while invalid gradients should leave both parameters and optimizer state unchanged. For an optimizer with momentum, checking parameters alone is insufficient because its internal state may already have changed.
Retain the evidence
For every regression run, record the interpreter version, MLX version, dependency lockfile, and test exit code. Training logs need only retain the pre-clipping norm, the threshold, and whether the update was accepted. There is no need to print the full gradients.
Finally, verify that the tests detect deliberately introduced faults. Replace global scaling with per-tensor scaling and confirm that the [3, 0], [0, 4] fixture fails. Then remove the non-finite-value checks and confirm that the invalid-input cases fail. Detecting these faults demonstrates that the tests check the contract, rather than merely execute the code once.
Use the small fixture as a preflight check before training, and keep the same boundary assertions as the model grows. When the loss fluctuates, you can first distinguish gradient-processing errors from problems with the model or data itself.
Frequently asked questions
Is per-tensor clipping equivalent to global clipping?
No. Global clipping applies one scale factor to all gradients. Independent tensor factors can change the relative magnitudes between parameter gradients.
Should NaN gradients be replaced with zeros?
Not silently. Reject the update first. If a step is skipped, explicitly define and test whether optimizer state, step counters, and the scheduler advance.
Choose a cloud Mac
Choose the unified memory and rental term that fit your experiment. Get an entire machine to yourself and connect via SSH. Configuration and availability are shown live in the console.
Rent a cloud Mac