Testing numerical code: evidence before tolerance
数值代码测试
Test loss and gradient contracts with exact checkpoints, independent references, finite differences and explicit numerical tolerances.
testing-numerical-codeA test needs a reason to believe its expected answer
A loss decreases during training, so the gradient must be right. That conclusion is tempting and unsafe: a wrong gradient can still point downhill on a few examples. Likewise, two implementations can agree because they copied the same error.
We will test a small binary logistic loss through several different kinds of evidence: a hand-computable point, an independent high-precision formula, finite differences, and transformations that should preserve the result. Each answers a different question. The aim is to make failures informative, not to accumulate thousands of comparisons with one unreliable reference.
Start by declaring the interface. This chapter expects finite float64 arrays, exact shapes, a scalar mean loss and a gradient with one entry per parameter. A wrong shape, an unexpected dtype or a NaN is an interface failure before it is a tolerance question.
Separate the comparison rule from the mathematical claim
Absolute and relative tolerances do different jobs
For actual value a and reference b, NumPy’s comparison uses:
The absolute term supplies a scale near zero; the relative term grows with the reference. This rule is asymmetric. For instance, with zero absolute tolerance and relative tolerance 0.1, comparing actual 1 to reference 1.11 passes, while reversing them fails. Choose tolerances from the accuracy needed and the error mechanisms, then inspect failures before changing them. A threshold selected after seeing the result can hide the very defect being tested. NumPy allclose
An approximate-value check is not a schema check. allclose permits broadcasting. NumPy 1.26 assert_allclose checks array shapes but treats a scalar specially, and its default permits corresponding NaNs. Our wrapper requires equal one-dimensional float64 shapes and finite values before calling it, with explicit tolerances and equal_nan=False. An empty comparison can pass vacuously; it says nothing about nonempty cases. assert_allclose contract
A numerical derivative is another approximation
For coordinate j and positive step h, the centered estimate is:
Here e_j changes only coordinate j. If the scalar restriction along that coordinate has a continuous third derivative bounded in magnitude by M on the interval, Taylor’s theorem bounds the exact-arithmetic truncation error by Mh²/6. If each function evaluation additionally has absolute error at most δ, then, ignoring the separate rounding of coordinate construction and arithmetic,
This explains why making h smaller is not automatically better. Truncation falls while cancellation amplifies evaluation error. At sufficiently small h, the floating-point coordinate may not change at all. The code rejects that detectable case; it cannot estimate M or δ and does not turn the displayed bound into an automatic error certificate. The CS231n gradient-check notes discuss centered differences, precision, step choice and nondifferentiable points.
A check should keep inputs and randomness fixed between evaluations. At a kink such as absolute value at zero, a centered value is not evidence that an ordinary derivative exists. A successful test at one parameter vector also cannot establish the gradient everywhere. These limitations are reasons to use several well-chosen points and independent expected values.
A smooth function with a useful exact checkpoint
For binary labels y_i, write t_i=2y_i−1 and margin m_i=t_i x_iᵀw. Our mean loss and gradient are:
Differentiate each log term: its margin derivative is −1/(1+exp(m_i)), then apply the chain rule. At w=0, every margin is zero, the loss is log 2, and the gradient is the average of −t_i x_i/2. This checkpoint is available without running a finite-difference routine.
The implementation evaluates the loss using logaddexp and the gradient using exp(−|m|), avoiding overflow from directly exponentiating a large positive margin. Extremely small positive quantities may still round to zero. Stability reduces a failure mode; it does not make floating point exact.
Test the contract, then the numbers
Run this complete example with Python 3.12 and NumPy 1.26.4. The model permits 1–64 rows, 1–16 features, binary labels, feature magnitudes at most 1000 and parameter magnitudes at most 10. There is no intercept unless a constant feature is supplied, and no regularization. The gradient checker separately accepts up to 16 parameters of magnitude at most one million and a step in (0,1]. Its callback must accept the perturbed points within its own domain.
The checker copies arguments before callback evaluation, validates every returned loss and gradient, and compares the analytic gradient against the computed finite-difference vector as the reference. It returns the values, absolute errors, a tolerance decision and an evaluation count. A failed decision is evidence to investigate, not a verdict that the analytic side must be wrong.
import math
import numpy as np
def finite_array(value, ndim):
if type(value) is not np.ndarray or value.ndim != ndim or value.dtype != np.dtype('float64'):
raise ValueError('expected a float64 ndarray of the stated rank')
if not np.isfinite(value).all():
raise ValueError('nonfinite values are outside this contract')
return value.copy()
def tolerances(atol, rtol):
for value in (atol, rtol):
if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
raise ValueError('finite nonnegative tolerances required')
def assert_result(actual, reference, atol, rtol):
tolerances(atol, rtol)
a = finite_array(actual, 1)
b = finite_array(reference, 1)
if a.shape != b.shape:
raise ValueError('shape mismatch')
np.testing.assert_allclose(a, b, atol=atol, rtol=rtol, equal_nan=False)
def binary_loss_gradient(theta, x, y):
w, a, target = finite_array(theta, 1), finite_array(x, 2), finite_array(y, 1)
n, d = a.shape
if not 1 <= n <= 64 or not 1 <= d <= 16 or w.shape != (d,) or target.shape != (n,):
raise ValueError('incompatible or oversized teaching arrays')
if np.any(np.abs(a) > 1000) or np.any(np.abs(w) > 10) or not np.isin(target, [0., 1.]).all():
raise ValueError('coordinate, parameter or binary-label domain violation')
sign = 2 * target - 1
margin = sign * (a @ w)
# exp(-abs(margin)) cannot overflow; underflow is allowed here.
with np.errstate(under='ignore'):
e = np.exp(-np.abs(margin))
probability_wrong = np.where(margin >= 0, e / (1 + e), 1 / (1 + e))
loss = np.logaddexp(0, -margin).mean()
gradient = ((-sign * probability_wrong) @ a) / n
return float(loss), gradient
def check_gradient(value_gradient, point, step, atol=1e-8, rtol=1e-6):
w = finite_array(point, 1)
tolerances(atol, rtol)
if not 1 <= len(w) <= 16 or np.any(np.abs(w) > 1e6):
raise ValueError('small finite parameter vector required')
if type(step) not in (int, float) or not math.isfinite(step) or not 0 < step <= 1:
raise ValueError('step must lie in (0,1]')
def evaluate(v):
loss, gradient = value_gradient(v.copy())
if type(loss) not in (int, float) or not math.isfinite(loss):
raise ValueError('callback loss must be a finite Python number')
g = finite_array(gradient, 1)
if g.shape != w.shape:
raise ValueError('callback gradient shape mismatch')
return float(loss), g
_, analytic = evaluate(w)
numeric = np.empty_like(w)
for j in range(len(w)):
plus, minus = w.copy(), w.copy()
plus[j] += step
minus[j] -= step
if plus[j] == w[j] or minus[j] == w[j]:
raise ValueError('step does not change this floating-point coordinate')
high, _ = evaluate(plus)
low, _ = evaluate(minus)
numeric[j] = (high - low) / (2 * step)
if not np.isfinite(numeric).all():
raise ValueError('nonfinite finite-difference estimate')
errors = np.abs(analytic - numeric)
return {'analytic': analytic, 'numeric': numeric, 'absolute_error': errors,
'passed': bool(np.all(errors <= atol + rtol * np.abs(numeric))),
'evaluations': 1 + 2 * len(w)}
if __name__ == '__main__':
x = np.array([[1,0],[0,1],[1,1],[-1,1]], dtype=np.float64)
y = np.array([1,0,1,0], dtype=np.float64)
f = lambda w: binary_loss_gradient(w, x, y)
loss, gradient = f(np.zeros(2))
print('zero loss:', round(loss, 12))
print('zero gradient:', gradient.tolist())
point = np.array([.25,-.5])
print('step checks:', [check_gradient(f, point, h)['passed'] for h in (1e-4,1e-6)])
def faulty(w):
loss, gradient = f(w)
return loss, -gradient
print('sign mutant passes:', check_gradient(faulty, point, 1e-5)['passed'])
print('callback evaluations:', check_gradient(f, point, 1e-5)['evaluations'])
try:
check_gradient(f, point, 1e-20)
except ValueError:
print('invisible step: rejected')
large = binary_loss_gradient(np.array([1.]), np.array([[1000.]]), np.array([0.]))
print('large wrong margin:', large[0], large[1].tolist())
try:
assert_result(np.ones(2), np.ones(1), 1e-8, 1e-6)
except ValueError:
print('broadcastable wrong shape: rejected')
try:
assert_result(np.array([np.nan]), np.array([np.nan]), 1e-8, 1e-6)
except ValueError:
print('matching NaNs: rejected')
Output:
zero loss: 0.69314718056
zero gradient: [-0.375, 0.125]
step checks: [True, True]
sign mutant passes: False
callback evaluations: 5
invisible step: rejected
large wrong margin: 1000.0 [1000.0]
broadcastable wrong shape: rejected
matching NaNs: rejected
The hand calculation gives gradient [-3/8,1/8] at zero. The two nonzero-point checks pass at the stated tolerances, while an injected gradient-sign error fails. The deliberately wrong margin of −1000 produces a finite loss and gradient. The tiny step, broadcastable wrong shape and matching NaNs each exercise a different boundary.
Testing only the zero point would be insufficient: some missing factors or indexing errors can vanish on a symmetric fixture. Compare several nonsymmetric points against a separately organized scalar calculation. For this small model, high-precision Decimal can compute each probability and negative log likelihood directly at moderate margins. Convert the actual binary floats exactly into the reference arithmetic; otherwise the test may quietly compare two different inputs.
Metamorphic checks supplement those expected values. Reordering rows preserves the mean loss and gradient mathematically. Repeating every row the same number of times also preserves them, while permuting feature columns and parameter entries together permutes the gradient. Finite-precision reductions may differ slightly. Such checks can catch normalization or axis errors, but a consistently wrong formula can satisfy all of them.
One loss-and-gradient evaluation costs O(nd) arithmetic and O(nd+n+d) temporary storage here, including defensive copies. The checker makes 2d+1 callback evaluations, so this model’s full coordinate check costs O(nd²) work and O(nd+n+d) peak temporary storage, with O(d) returned diagnostics. For large models, selected coordinates or directional checks reduce evaluation count but provide narrower coverage.
Agreement can conceal a shared mistake
If both the loss and gradient are multiplied by two, finite differences can still agree perfectly, even though the requested mean-loss contract is wrong. That is why the log-2 checkpoint and independent loss reference matter. An automatic differentiation result is useful evidence too, but shared preprocessing or a shared mistaken objective can make two derivative implementations agree.
Keep stochastic tests separate from deterministic arithmetic checks. An identical seed does not establish that two different implementations consume randomness identically, and repeated runs need a statistical acceptance rule rather than arbitrary elementwise tolerances. Here there is no randomness in the model or checker.
This example does not certify all float64 inputs, estimate conditioning, validate a GPU kernel or test a full training system. Near saturation, true gradients can become smaller than the selected absolute tolerance. A “passed” result can then provide little evidence about their relative accuracy. Inspect magnitudes and the intended downstream sensitivity.
When a test fails, first retain the failing inputs, expected values, actual values, shape, dtype and environment. Then distinguish an interface mismatch, an incorrect model formula, an unstable reference and an unsuitable tolerance. Loosening every tolerance is not a repair strategy.
Make the test fail for the right reason
- With atol=0 and rtol=0.1, compare actual 1 to reference 1.11, then reverse them.
Use the reference in the relative term
Answer: The difference is 0.11. The first threshold is 0.111, so it passes; the reversed threshold is 0.1, so it fails. The formula is asymmetric, and a relative tolerance alone gives no positive allowance when the reference is zero.
- Why can a finite-difference check pass when the implemented mean loss and gradient are both twice their intended values?
Separate consistency from correctness
Answer: Differentiation preserves constant scaling. The checker confirms that the two implemented quantities are locally consistent, not that either matches the specified objective. A known loss value or an independently derived reference exposes the shared factor.
- At w=0 in the fixture, derive the loss and first gradient entry without finite differences.
Use zero margins
Answer: Every example contributes log 2. The first gradient contributions are −1/2, 0, −1/2 and −1/2; averaging gives −3/8. The second entry is 1/8. A sum instead of a mean would multiply both gradient entries by four.
- Does a centered difference of zero for f(x)=|x| at x=0 prove the derivative is zero?
Check differentiability first
Answer: No. The left and right derivatives are −1 and 1, so an ordinary derivative does not exist. Symmetric evaluations cancel. The smoothness assumptions behind the centered-error bound fail at the kink.
Use references with different failure modes
NumPy’s comparison APIs specify operational details that matter to tests: relative scaling, broadcasting, scalar special cases and NaN handling. The CS231n notes connect derivative checks to parameter scale and local behavior. Their practical heuristics do not supply a universal tolerance for every function or dtype.
Continue with floating point, numerical stability and model debugging. A useful test collection combines exact cases, independently organized references and invariants, then states what each passing result actually establishes.
Make a prediction, then check
Both an implemented loss and its gradient are accidentally doubled. What can a passing gradient check establish?
Learning objectives
- Separate shape, dtype and finite-value requirements from approximate equality.
- Interpret finite differences using truncation, evaluation error and local coverage.
- Combine known values, independent arithmetic and metamorphic properties to expose shared bugs.
Prerequisites & connections
Explore related knowledge →References
- numpy.allclose — NumPy v1.26 Manual
NumPy Developers - numpy.testing.assert_allclose — NumPy v1.26 Manual
NumPy Developers - CS231n: Neural Networks, Part 3 — Learning
Stanford CS231n course staff
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Eight tests pass with project CPython 3.12.4 and NumPy 1.26.4. A 70-digit Decimal direct-probability/negative-log reference independently checks eight fits, 20 gradient entries and eight losses; the production code instead uses signed margins and stable branches. Exact cubic truncation h² and all five perturbation calls are checked separately.
- Verified zero log-2/[-3/8,1/8] checkpoint, ±1000 margin behavior, row reversal/repetition and feature permutation, injected sign bug, shared factor bug, mutation isolation, asymmetric tolerance, vacuous empty comparison, invalid shape/dtype/labels/nonfinite values and invisible steps. Nine actual output lines match both articles.
- Complete bilingual text, identical code, four display formulas, six anchors and four answered exercises pass strict MDX/KaTeX and actual React HTML/MathML. Only article_text controls test paths. Written records AI author checks, not human review; no whole-site build, timing benchmark or all-input numerical proof.
- Root fully read bilingual prose and complete program, manually checked logistic derivatives, zero-point values and the conditional centered-difference error bound. Eight author tests and strict rendered MDX pass: four displays, six anchors and four answers. Frozen hashes match; no changes.
- Existing independent 70-digit Decimal reference and cubic truncation test were rerun; shared-scale and sign mutations distinguish derivative consistency from objective correctness. Reviewed finite inputs, shape/dtype checks, saturation, perturbation domain and limited coverage. No redundant numerical reference added.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- numpy.allclose — NumPy v1.26 Manual · Actually read fixed 1.26 allclose parameters and notes at lines 73–125: relative term uses the reference, asymmetric rule, broadcasting, NaN and infinity behavior. Article wrapper deliberately requires stricter shape/dtype/finite contracts.
- numpy.testing.assert_allclose — NumPy v1.26 Manual · Actually read signature and notes at 68–73 and 127–128: equal_nan=True default, tolerance rule and scalar special case. No strict parameter from newer NumPy versions is used.
- CS231n: Neural Networks, Part 3 — Learning · Actually read Gradient Checks at lines 25–64: centered formula, double precision, step-size sensitivity, kinks, local coverage and fixed randomness. Original Taylor bound states its smoothness/evaluation-error assumptions; does not copy heuristic error cutoffs or the source’s apparent negative-exponent kink-example typo. Also read sanity checks at 65–72 for the next debugging topic. No figure-based timing or training claim.
- numpy.allclose — NumPy v1.26 Manual · Root read NumPy 1.26 allclose comparison, reference-dependent tolerance and broadcasting notes.
- numpy.testing.assert_allclose — NumPy v1.26 Manual · Root read 1.26 assert_allclose signature/defaults, shape checks and scalar exception, lines 68–73 and 128.
- CS231n: Neural Networks, Part 3 — Learning · Root read CS231n centered differences, double precision, kinks and step-size notes, lines 29–55; heuristic thresholds are not adopted as universal guarantees.
Related topics