Check MLX autodiff with central differences on a cloud Mac

Check MLX autodiff with central differences on a cloud Mac

After moving a custom loss to a cloud Mac, your training script may run and the loss may decrease even though a set of weights never receives the correct gradients. Before starting a long training run, reduce the model to a small function with fixed inputs and check autodiff against central differences. This makes problems easier to pinpoint than watching the full loss curve. The experiment below requires no model downloads and is suitable as a pre-training check on a dedicated physical node.

Build a small, differentiable test fixture

The function under test must return a scalar and perform the same computation on every call. First remove random sampling, data augmentation, and state updates. If random layers are involved, disable their randomness wherever possible; setting a seed once at the start of the script is not enough. If the two finite-difference evaluations use different masks, you are no longer calculating the derivative of the same function.

Prepare a native Python environment and confirm that uname -m returns arm64. Then create a separate directory:

mkdir -p ~/mlx-gradient-check
cd ~/mlx-gradient-check
python3 -m venv .venv
source .venv/bin/activate
python -m pip install mlx
python -m pip freeze > requirements.lock
sw_vers > environment.txt
python --version >> environment.txt

This installs the MLX version available for the current environment and records the dependency versions for use after validation. For repeat runs, use the same interpreter version and lock file. Do not upgrade dependencies while also trying to determine whether the gradients have changed.

Check each weight with central differences

For the i-th weight, add and subtract a step size h, evaluate the loss twice, and divide the difference by 2h. This calculation does not rely on autodiff, so it provides an independent reference. The example below maps a two-dimensional input to a single prediction and uses mean squared error as the loss. Both weights participate in the calculation, and both expected gradients are nonzero.

Save this as check_grad.py, then run python check_grad.py:

import math
import mlx.core as mx

x = mx.array([[1.0, 2.0], [-1.0, 0.5], [0.25, -2.0]],
             dtype=mx.float32)
y = mx.array([0.5, -0.2, 1.0], dtype=mx.float32)
w = mx.array([0.3, -0.4], dtype=mx.float32)

def loss(weights):
    prediction = x @ weights + 0.1
    return mx.mean(mx.square(prediction - y))

def numerical_gradient(weights, h):
    result = []
    for i in range(weights.size):
        direction = mx.array(
            [1.0 if j == i else 0.0 for j in range(weights.size)],
            dtype=mx.float32
        )
        upper = loss(weights + h * direction).item()
        lower = loss(weights - h * direction).item()
        result.append((upper - lower) / (2.0 * h))
    return result

def matches(actual, expected, atol=2e-3, rtol=2e-2):
    return all(
        math.isfinite(a) and math.isfinite(b)
        and abs(a - b) <= atol + rtol * max(abs(a), abs(b))
        for a, b in zip(actual, expected, strict=True)
    )

automatic = mx.grad(loss)(w).tolist()
checks = []
for h in (1e-2, 3e-3, 1e-3):
    numerical = numerical_gradient(w, h)
    passed = matches(automatic, numerical)
    checks.append(passed)
    print({"step": h, "autodiff": automatic,
           "difference": numerical, "passed": passed})

assert all(checks), "Gradient check failed"
reference = numerical_gradient(w, 3e-3)
assert not matches([0.0, 0.0], reference), "Negative control failed"

.item() and .tolist() materialize the results as host-side numeric values, so the comparison does not merely involve unevaluated computational expressions. The tolerances here are intended only for this small float32 fixture; they should not become a universal standard for all models.

Sweep step sizes instead of loosening tolerances

Central differences involve two opposing sources of error: a large step makes the local approximation less accurate, while an excessively small step causes a loss of significant digits when subtracting two nearly equal loss values. When a check fails, the first step is therefore to compare how the error changes across several step sizes, not to increase the tolerances.

Central differences check local derivatives, not training quality. Passing a check only shows that the two differentiation methods agree near this particular sample.

The inputs and weights in this fixture have a scale close to 1, so 1e-2 to 1e-3 is a reasonable starting range. When real parameters span several orders of magnitude, choose perturbations according to the parameter scale and record the actual step size used for each coordinate. Keep an absolute tolerance when gradients are close to zero; relative error alone can be misleading.

Also avoid points where the function is not differentiable. At a breakpoint in a piecewise function, for example, central differences may average the slopes on either side, while autodiff follows a convention that selects one side. Check each side of the breakpoint separately and write separate tests for behavior at the boundary.

Verify the checker with a negative control

At the end of the script, the autodiff result is replaced with an all-zero gradient, which the checker must reject. This does not simulate a full training run; it confirms that the test does not pass regardless of its input. If the negative control passes too, inspect the comparison logic, tolerances, or test fixture before trusting any further green results.

When integrating a custom loss, make sure the finite-difference evaluations call the actual forward function. Pay particular attention to three types of operation: converting tensors to ordinary numeric values and then rebuilding tensors, accidentally applying stop-gradient operations, and modifying state inside the function that affects later evaluations. These can make the forward result look plausible even though the backward path has been severed.

Do not require every parameter to have a nonzero gradient. Branches that are not taken, symmetric inputs, and saturated regions can all produce legitimate zeros. Instead, choose a sample that activates the target path and compare its gradients with the finite-difference results.

Make local checks a prerequisite for training

Coordinate-wise finite differences require two forward passes per parameter, so this approach cannot be applied unchanged to an entire large model. Start with tiny inputs for custom operators, then spot-check key parameters. For larger parameter sets, you can fix a direction vector and compare the finite difference along that direction with the dot product of the gradient and the direction vector. However, directional checks can miss errors that cancel each other out, so they cannot replace all coordinate-wise tests.

Whenever you change the loss or gradient path, retain at least the following validation records:

  • Fixed inputs, initial parameters, data types, and dependency versions.
  • Analytic gradients, numerical gradients, and pass/fail results for each step size.
  • A passing result for the normal sample and a failing result for the zero-gradient negative control.
  • Results for samples with positive values, negative values, values near zero, and values on both sides of valid boundaries.

Finally, run a few real training steps and separately verify that the parameters actually update and the loss remains finite. Gradient agreement, optimizer updates, and training performance are three distinct pieces of evidence. Validating them separately makes it possible to identify the exact point of failure when a long experiment goes wrong.

Frequently asked questions

Why test more than one finite-difference step size?

Large steps increase truncation error, while very small steps amplify floating-point cancellation. Compare 1e-2, 3e-3, and 1e-3 to find a stable low-error range.

Does passing a gradient check validate the entire training loop?

No. It checks local derivatives near the chosen inputs and parameters. Add boundary cases and test optimizer updates separately.

Choose a cloud Mac by model and memory

Dedicated Apple Silicon M4 / M4 Pro machines with 16 GB, 24 GB, or 64 GB of unified memory. Pay by the day, week, month, or quarter; service stops at the end of your term unless you renew.

Verify your experiment requirements

Compare model size, unified memory, and billing period, then choose a dedicated physical machine.