The same inputs still produce text on your remote Mac, but after an MLX upgrade or a change to a normalization operator, the output starts to drift. Before tuning sampling parameters, isolate the suspect computation in a small test with fixed inputs. First check for overflow, then determine whether the error meets the computation’s contract. The root mean square example below demonstrates checks that also apply to reduction and normalization operations in an inference pipeline.
1. Narrow the acceptance test to a single operator
The operation under test is the root mean square of a nonempty one-dimensional array: square the elements, take their mean, then take the square root. Inputs must be finite floating-point numbers, and the output must be a finite scalar. To expose intermediate overflow, include positive and negative three hundred. Both values are representable in half precision, but their squares exceed its finite range.
Keep two questions separate: how much information is lost when the input is converted to half precision, and whether the operator computes the correct result for the input as represented. This example checks the latter. The reference calculation therefore first reproduces the input type conversion, then promotes the values to higher precision. The original, unconverted values cannot serve as the sole reference.
A finite result only tells you that no nonfinite value appeared. It does not tell you that the result is close to the correct answer. You need both finiteness checks and error checks.
Install the dependencies in a separate Python virtual environment, not in the environment used by a running inference service. After the first verification, save the resolved dependency versions. When rerunning the checks, also record the Python and operating system versions.
python3 -m venv .venv-numeric
. .venv-numeric/bin/activate
python -m pip install mlx numpy
python -m pip freeze > requirements-numeric.txt
python --version
sw_vers
2. Promote precision before the risky operation
Save the following script as check_numeric.py. The production function explicitly rejects empty arrays, incorrect dimensions, and nonfinite inputs, and converts the input to single precision before squaring. The tests cover zeros, fractional values, larger magnitudes, and invalid inputs. No model download is required.
import mlx.core as mx
import numpy as np
def rms_checked(x):
if x.ndim != 1 or x.size == 0:
raise ValueError("Expected a nonempty vector")
if not bool(mx.all(mx.isfinite(x)).item()):
raise ValueError("Expected finite input")
work = x.astype(mx.float32)
result = mx.sqrt(mx.mean(work * work))
mx.eval(result)
if not bool(mx.isfinite(result).item()):
raise ValueError("Nonfinite output")
return result
fixtures = [
[0.0, 0.0],
[0.125, -0.25, 1.0],
[300.0, -300.0, 0.125, 1.0],
]
for mx_dtype, np_dtype in [
(mx.float16, np.float16),
(mx.float32, np.float32),
]:
for values in fixtures:
represented = np.asarray(values, dtype=np_dtype)
reference_input = represented.astype(np.float64)
expected = np.sqrt(np.mean(reference_input * reference_input))
actual = rms_checked(mx.array(represented, dtype=mx_dtype))
assert actual.shape == ()
assert actual.dtype == mx.float32
np.testing.assert_allclose(
actual.item(), expected,
rtol=1e-4, atol=1e-4, equal_nan=False,
)
for values in [[], [float("nan")], [float("inf")]]:
try:
rms_checked(mx.array(values, dtype=mx.float32))
except ValueError:
pass
else:
raise AssertionError("Invalid input was accepted")
Run python check_numeric.py. A successful run produces no output; an assertion failure returns a nonzero exit code. Explicitly evaluating the result before reading it ensures that errors are attributed to this check rather than to an unrelated operation later on.
Do not implement the fix as “square in half precision, then convert to single precision.” Once an intermediate result becomes infinite, a type conversion cannot recover the original value. Nor should you replace NaNs just to make the assertions pass: that hides the source of the error.
3. Match tolerances to the computation’s contract
The tolerances in this example are intended only for these small fixtures. They are not defaults for every model. The comparison condition can be read as follows: the absolute error must not exceed the absolute tolerance plus the relative tolerance multiplied by the absolute reference value. Near zero, the absolute tolerance is the main constraint; at larger magnitudes, the relative tolerance becomes more meaningful.
When adding tests for real operators, cover at least values near zero, cancellation between positive and negative values, larger magnitudes, and different array lengths. Increase array sizes gradually and observe whether reduction error grows. Do not keep loosening tolerances simply because a test fails. First determine whether the error comes from input representation, operation order, or an implementation defect.
The single-precision intermediates in this example also have a limited range. Extremely large finite inputs can still overflow when squared, in which case the function rejects the result. If your application genuinely accepts inputs of that magnitude, implement a separate scaling algorithm and add tests for that path. Do not claim that a type conversion solves every overflow problem.
4. Keep failures as replayable evidence
When a check fails, save the input array, input type, shape, expected value, actual value, and both tolerances. For random samples, also record the seed, but do not save only the seed: changes to the random number generator or dependency versions can change the sequence. Keep the actual array as well.
Real inference inputs may contain private text, so first try to reduce the failure to synthetic numerical inputs. If intermediate tensors must be saved, confirm access permissions and the retention period beforehand. Do not write complete prompts to public build logs.
Compare numbers before comparing text
Model-level checks should proceed in layers: first check the shapes and finiteness of intermediate tensors and output scores, then check errors at selected positions. Generated text is useful for application-level acceptance testing, but sampling and nearly tied scores can both change the final tokens. Text comparisons cannot replace operator-level evidence.
5. Make regression scripts actually block changes
Whenever you upgrade dependencies or change a numerical implementation, run the fixed fixtures in the old environment first, then run the same fixtures in the new environment. Any exception or assertion failure should block the subsequent release. Do not report a failed check as a success.
Keep the checklist short: did the reference input undergo the same type conversion? Is the reference calculation precise enough? Does the output shape match? Are nonfinite values explicitly rejected? Are the tolerances justified? Once these checks pass, validate the overall behavior with real application samples.
The value of a small script is not that it proves the entire model will always be correct. It turns “the output seems different” into an engineering fact that can be reproduced, traced to its source, and used to block a change.
Frequently asked questions
Does the absence of NaN mean an MLX result is correct?
No. Finite results can still be wrong. Check shape and dtype, reject nonfinite values, then compare against a reference with explicit absolute and relative tolerances.
Can casting to float32 repair an overflowed float16 square?
No. Infinity remains infinity after conversion. Promote the input before squaring, then recompute the operation.
Rent for a Day to Test Your Model
VPSMain offers dedicated physical Mac mini servers—not virtual machines—from $19.6/day. Rent by the day, week, month, or quarter, with same-day setup. Choose unified memory based on quantized model weights, KV cache, and system overhead.