For now, I tried a few small tests:
Two numerical edge cases, two different testing lessons
I ran a small, controlled CPU experiment with numguard, using the public numguard.check() API rather than just inspecting source code or reproducing individual comparisons. I started with low-precision cases reported in PyTorch and compared numguard’s generated cases with the same checks augmented by a few carefully chosen inputs.
Two different testing situations stood out:
- A missing combination of values and tensor lengths. With BF16 inputs,
torch.add(x, y, alpha=0.1) produced different results for identical input elements at tensor lengths 31, 32, and 33. In the seeded numguard run below, all 59 generated cases passed; adding three fixed cases at those lengths through extra_cases produced three reference failures. This resembles the vectorized-body versus scalar-tail behavior discussed in PyTorch issue #199449. It is not a generic sum() accumulation test, and the high-precision reference is an explicitly chosen mathematical target, not necessarily a statement of PyTorch’s coefficient-rounding contract.
- A generated input whose discrepancy passed the default numerical tolerance. For CPU FP16
torch.erf, the generated subnormal case included a representable nonzero input on which PyTorch returned zero and an FP64 reference rounded back to FP16 returned a nonzero result. Nevertheless, all 23 generated cases passed numguard’s default reference comparison. Re-running the same catalogue with diagnostic rtol=0, atol=0 found three failing cases. The related upstream report is PyTorch issue #199850. Zero tolerance is useful here as an investigative control, not as a general default recommendation.
A compact third example is FP16 torch.special.logit just below 0.5: the generated 15-case panel passed, while adding the exact input 0.499755859375 made the existing reference check fail. This isolates a precision-sensitive internal boundary; see PyTorch issue #199867.
The distinction between case coverage and comparison sensitivity seems the most reusable finding. Both can matter for subtle low-precision drift, even when the overall framework already has good finite-value, NaN/Inf, domain, and reference checks.
What actually ran
The experiment used numguard-ci==1.0.1 (import numguard), Python 3.13.16, NumPy 2.1.3, PyTorch 2.11.0+cpu, Linux x86-64 with AVX2, and backend="torch". The numerical tests used seed=0, n=12, and large_n=64, with a single CPU thread. These n and large_n values were deliberately reduced to keep the experiment small. This is not a claim about every seed, every default-sized catalogue, or every CPU/GPU implementation.
These are the nine completed numguard.check() configurations. Every failure reported in the table was a reference-check failure; this does not mean every check failed:
| Function, dtype, and configuration |
Cases |
numguard.check() result |
Relevant failing cases |
torch.erf, FP16, generated panel |
23 |
Pass |
None |
torch.erf, FP16, same panel with diagnostic zero tolerance |
23 |
Fail |
tiny, subnormal, wide_range |
torch.erf, FP16, generated panel plus 1e-7 input |
24 |
Pass |
None |
torch.erf, FP16, only the 1e-7 input with diagnostic zero tolerance |
1 |
Fail |
erf_1e-7 |
torch.erf, BF16, generated panel |
23 |
Fail |
tiny, subnormal, wide_range |
torch.special.logit, FP16, generated panel in (0, 1) |
15 |
Pass |
None |
torch.special.logit, FP16, panel plus 0.499755859375 |
16 |
Fail |
logit_near_half |
torch.add(..., alpha=0.1), BF16, generated panel |
59 |
Pass |
None |
torch.add(..., alpha=0.1), BF16, panel plus lengths 31/32/33 |
62 |
Fail |
bf16_add_n31, bf16_add_n32, bf16_add_n33 |
The BF16 erf row is an important counterexample to an overbroad conclusion: the default checker did already find substantial errors on that dtype and those inputs. Likewise, passing a given finite seeded panel is not evidence that the implementation is globally accurate.
A practical first step
The project already has extra_cases, high-precision references, BF16 support through the Torch adapter, configurable tolerances, and ULP reporting. Neither example requires replacing the fixed catalogue: a small named fixture catches the shape-sensitive add(alpha) discrepancy, while a stricter diagnostic comparison makes the existing FP16 erf input informative. I would keep the ordinary default comparison and make stricter diagnostics explicit and opt-in. The exact inputs and results follow. They are not blanket accuracy judgments about PyTorch.
1. Exact values and minimal reproductions
Reproduction environment
The formal CPU probe installed numguard-ci==1.0.1, used backend="torch", seed=0, n=12, large_n=64, and fp_signals="ignore". Other environments may select different kernels or generate different case counts. These samples assume a compatible Python environment with NumPy, PyTorch, and numguard-ci. These results describe the tested environment, not a universal guarantee.
Case A: BF16 add(..., alpha=0.1) and the 31/32/33 boundary
The two BF16 operands used in the test are:
x = 0.052978515625
y = -0.53125
alpha = 0.1
Both operand values are representable in BF16. The declared mathematical reference evaluates x + 0.1*y using the quantized BF16 operands but an FP64-valued alpha=0.1, then rounds the result to BF16 for comparison. Under that declared reference, the rounded target for each repeated element is:
-0.0001468658447265625
What the tested PyTorch CPU path returned for the same repeated values depended on length:
| Length |
Observed values in BF16 output |
Extra observation |
| 15 |
-0.000244140625 |
All elements equal |
| 16 |
-0.000244140625 |
All elements equal |
| 31 |
-0.000244140625 |
All elements equal |
| 32 |
-0.0001983642578125 |
All elements equal |
| 33 |
Both of the above |
Earlier elements returned -0.0001983642578125; the last element returned -0.000244140625 |
| 64 |
-0.0001983642578125 |
All elements equal |
At n=33, the difference appears within one tensor even though every input element has the same bit pattern. That length-and-position dependence is worth recording separately from any claim about the ideal coefficient-rounding policy. It is related to PyTorch #199449, which discusses rounding differences between vectorized and scalar-tail paths. The issue offers a plausible mechanism, not proof that every architecture or version follows the same path.
The direct control calls torch.add on BF16 tensors filled with those constants at lengths 31, 32, and 33. The official numguard API comparison is:
import numpy as np
import torch
import numguard
def torch_add_alpha(x, y):
return torch.add(x, y, alpha=0.1)
def mathematical_reference(x, y):
# numguard passes NumPy inputs here. The reference deliberately
# uses real-valued alpha=0.1 on the *quantized operand values*.
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
return x + 0.1 * y
base = dict(
backend="torch", dtypes=["bfloat16"],
seed=0, n=12, large_n=64, fp_signals="ignore",
)
standard = numguard.check(
torch_add_alpha,
reference=mathematical_reference,
**base,
)
length_cases = {
"bf16_add_n31": (
np.full(31, 0.052978515625), np.full(31, -0.53125)
),
"bf16_add_n32": (
np.full(32, 0.052978515625), np.full(32, -0.53125)
),
"bf16_add_n33": (
np.full(33, 0.052978515625), np.full(33, -0.53125)
),
}
augmented = numguard.check(
torch_add_alpha,
reference=mathematical_reference,
extra_cases=length_cases,
**base,
)
print(standard.summary())
print(augmented.summary())
print("reference failures:", [
(r.case, r.max_ulp, r.max_rel_err)
for r in augmented.failures
if r.check == "reference"
])
In this configuration, the API returned 59 generated cases with no failed checks, versus 62 cases with three reference failures after the additions. The worst observed ULP distance was 102 relative to the deliberately chosen BF16-rounded reference. By case, the recorded maxima were:
| Added case |
Maximum reported ULP distance |
Maximum reported relative error |
bf16_add_n31 |
102 |
about 0.6623 |
bf16_add_n32 |
54 |
about 0.3506 |
bf16_add_n33 |
102 |
about 0.6623 |
The output variation by length and position is directly observed. Whether any given difference from mathematical_reference violates the PyTorch API contract is a separate question. The reference treats alpha=0.1 as the numerical coefficient in real arithmetic, whereas a lower-precision implementation can introduce coefficient rounding and intermediate rounding. Recording both the mathematical target and the observed implementation behavior would help future readers interpret the fixture.
Also, this example is not a reduction over the tensor elements. It is an elementwise alpha-scaled addition, with a shape-dependent CPU execution path. It is relevant to ML-oriented BF16 and mixed-precision testing, but it is not evidence of BF16 sum() accumulation drift.
Case B: FP16 erf with a very small, nonzero input
The requested scalar was 1e-7, but the function did not receive exactly that decimal value. Its FP16-quantized value was:
1.1920928955078125e-7
For that value on the tested CPU, the recorded results were:
actual torch.erf(float16): 0.0
math.erf(float(quantized_input)) rounded to float16:
1.1920928955078125e-7
reported difference: 2 FP16 ULPs
The reference must use the value after input quantization, or else the test conflates a function’s arithmetic error with the representation error from storing the original decimal value. Here the quantized value is a representable, nonzero FP16 subnormal and the reference is not zero.
The direct control casts 1e-7 to a PyTorch FP16 tensor, calls torch.erf, and compares it with math.erf evaluated on the same quantized input and rounded back to FP16. The official API test below checks the catalogue and tolerance, not just that one output.
import math
import numpy as np
import torch
import numguard
def erf_reference(x):
x = np.asarray(x, dtype=np.float64)
return np.vectorize(math.erf, otypes=[np.float64])(x)
base = dict(
backend="torch", dtypes=["float16"],
seed=0, n=12, large_n=64, fp_signals="ignore",
)
normal = numguard.check(torch.erf, reference=erf_reference, **base)
normal_with_extra = numguard.check(
torch.erf,
reference=erf_reference,
extra_cases={"erf_1e-7": [1e-7]},
**base,
)
# A deliberately sensitive diagnostic comparison, not a recommended default.
strict_catalogue = numguard.check(
torch.erf,
reference=erf_reference,
rtol=0.0, atol=0.0,
**base,
)
strict_one_input = numguard.check(
torch.erf,
reference=erf_reference,
extra_cases={"erf_1e-7": [1e-7]},
include=["erf_1e-7"],
rtol=0.0, atol=0.0,
**base,
)
for name, report in (
("normal", normal),
("normal_with_extra", normal_with_extra),
("strict_catalogue", strict_catalogue),
("strict_one_input", strict_one_input),
):
print(name, report.n_cases, report.ok, report.failed_cases())
print(report.summary())
The reported case counts and verdicts were, respectively: 23/pass, 24/pass, 23/fail with tiny/subnormal/wide_range, and 1/fail on erf_1e-7.
The key observation is not that numguard lacks subnormal generation. It has such a generator, and a matching quantized input was found in the subnormal case in this exact panel. The point is that the default-tolerance reference comparison accepted the discrepancy. One more sample at 1e-7 did not change the default verdict. Using a much more sensitive diagnostic comparison did.
For applications where small but representable nonzero outputs matter, this suggests documenting or offering optional near-zero diagnostics. It would not justify changing the tolerance globally on the strength of one special function: exact equality is often much too strict for ordinary floating-point implementations.
BF16 erf is a useful counterexample
With BF16 instead of FP16, the default generated panel already flagged tiny, subnormal, and wide_range. Thus the observation is not that numguard is blind to low-precision small-value errors: the exact dtype, generated values, and tolerance change the outcome.
Case C: FP16 logit near one half
This offers another concise missing-input example, separate from the comparison-sensitivity case.
For the already-quantized FP16 value:
x = 0.499755859375
The tested CPU returned:
torch.special.logit(x): -0.00048828125
float64 log(x / (1-x)), rounded to FP16: -0.0009765625
Both outputs are finite and negative, but their magnitudes differ by a factor of two. In the recorded numguard panel, the 15 generated in-domain cases passed; adding that one value gave 16 cases and one reference failure. The report listed a maximum of 1,024 FP16 ULPs for the added case. The associated upstream report is PyTorch #199867.
import numpy as np
import torch
import numguard
def logit_reference(x):
x = np.asarray(x, dtype=np.float64)
with np.errstate(all="ignore"):
return np.log(x / (1.0 - x))
config = dict(
backend="torch", dtypes=["float16"], domain="(0,1)",
seed=0, n=12, large_n=64, fp_signals="ignore",
)
normal = numguard.check(
torch.special.logit,
reference=logit_reference,
**config,
)
extra = numguard.check(
torch.special.logit,
reference=logit_reference,
extra_cases={"logit_near_half": [0.499755859375]},
**config,
)
print(normal.n_cases, normal.ok, normal.failed_cases())
print(extra.n_cases, extra.ok, extra.failed_cases())
print(extra.summary())
The (0, 1) domain is intentional: this tests accuracy inside the domain, not behavior at logit’s singular endpoints. Treating NaN from an out-of-domain input as an accuracy failure would answer a different question.
Identify the specific check
The observed targeted failures were reported by numguard’s reference check. Other checks can independently pass or fail. A reusable report should identify the check, case, dtype, quantized input, observed and reference outputs, error, and ULP count, rather than just saying “the tool failed.”
2. Decision tree: missing input, permissive comparison, or execution path?
Why I would treat these as separate decisions
The examples suggest four distinct stages at which a function-level numerical test can become informative:
- A test constructs an input that reaches a numerically sensitive path.
- The test executes the intended implementation path, with the expected dtype and backend rather than a silently promoted or substituted one.
- The test compares the output under a defensible, explicitly declared numerical or semantic contract.
- The test records the numerical and runtime context well enough to reproduce, explain, and possibly minimize the observation.
This is a way to organize diagnosis, not a proposal for four new numguard components. The tool already covers parts of all four. The possible extension is to represent cases and outcomes with a little more information about the interaction of dtype, magnitude, shape, execution path, and tolerance.
The three examples separate these questions fairly clearly:
| Question |
BF16 add(alpha) |
FP16 erf |
FP16 logit |
| Did the chosen generated panel expose this particular discrepancy? |
No |
The numerical discrepancy was present in a generated input but accepted |
No |
Did an explicit extra_cases input help? |
Yes, three lengths |
Not under unchanged default tolerance |
Yes, one scalar value |
| Did a diagnostic tolerance adjustment help? |
Not needed for the demonstrated failure |
Yes |
Not needed for the demonstrated failure |
Did the existing reference comparison detect the targeted difference when reached under the chosen contract? |
Yes |
Yes, under zero-tolerance control |
Yes |
| Was this shown to be a general bug across versions and devices? |
No |
No |
No |
| Main lesson |
Shape/value coverage and execution path |
Comparator sensitivity and output scale |
Boundary-value coverage and cancellation |
Smallest useful branching test
Choose a numerical contract and input domain.
If the failing value, shape, or vector-tail length was not generated:
Add one deterministic extra_cases fixture; keep original cases as a control.
Else if it was generated but the report passed:
Examine the quantized input, actual/rounded-reference outputs,
absolute error, ULPs, effective tolerance and output scale.
Try stricter comparison only as a diagnostic control.
Else if the result differs by implementation path:
Preserve the smallest dtype/length/index/device/version contrast.
Separate observed variation from a proven API-contract violation.
If the target is not well defined:
State plausible reference conventions before deciding what is wrong.
This separation is intentionally lightweight. A stricter comparator cannot expose an execution path that no input reaches; adding inputs cannot expose a discrepancy that the declared tolerance accepts. And neither solves a reference that tests the wrong expression. For these examples, changing only the input exposed the BF16 add and FP16 logit differences, whereas changing only the diagnostic tolerance revealed the already generated FP16 erf difference.
3. What the reference actually establishes
Start with the low-precision input that the implementation actually sees
Suppose a test caller writes a decimal value x0 and casts it to FP16 before invoking a function. There are two effects to consider:
- The storage conversion gives a representable value
x_q = round_fp16(x0).
- The function computes some approximation to
f(x_q) in its implementation-specific arithmetic, yielding an output that may then be rounded to another dtype.
Comparing an FP64 evaluation of f(x0) directly with the FP16 result also measures the input-quantization difference between x0 and x_q. That may be exactly what someone wants to measure for a full end-to-end pipeline, but it is not the right isolated comparison if the question is the accuracy of the function given an FP16 input.
For a function-level arithmetic probe, a cleaner mathematical target is the ideal function applied to x_q, then rounded according to the declared output contract. The erf test followed this pattern: the intended 1e-7 decimal input became 1.1920928955078125e-7 in FP16; both the function and the reference were evaluated from that representable value. This keeps input representation error separate from function evaluation error.
The same issue arises with BF16, which has a much wider exponent range than FP16 but fewer significand bits. A decimal coefficient, multiplier, scalar argument, or array element may be rounded at different stages. Labeling an operation “BF16” does not specify every rounding stage.
Declare the question the oracle is answering
For BF16 torch.add(x, y, alpha=0.1), the recorded numerical oracle was the real-valued x + 0.1*y on already-quantized BF16 operand values, with a final BF16 rounding. That is an ideal arithmetic target, not a demonstration that PyTorch promises to retain full-precision alpha at every stage. A backend-specific reference might instead round alpha, use separately rounded product/addition, or use fused arithmetic. And a consistency test may simply compare identical input elements at different indices and lengths. Each is a valid question, but the acceptance criteria differ.
Keep two different kinds of discrepancies separate
For alpha-scaled addition, one useful control evaluates x + alpha*y on the already-quantized BF16 operands while retaining the nominal Python coefficient alpha=0.1. A second, explicitly different control could round the coefficient to BF16 before evaluating; still another could emulate fused or separately rounded intermediate operations. They are alternative declared oracles, not interchangeable interpretations of PyTorch’s API. The recorded numguard reference used the first convention. The length-33 result (different output values for identical elements in one tensor) remains independently interesting under a consistency-oriented investigation, even if a different reference changes which individual values are accepted.
The same care applies to reductions: input dtype, product dtype, accumulation dtype, output dtype, rounding order, and backend are separate choices. For instance, a BF16 output does not prove that the reduction accumulated in BF16. PyTorch’s numerical-accuracy notes explicitly warn against assuming bitwise parity between devices or mathematically equivalent evaluation orders. A discrepancy from an ideal oracle is a measurement; classifying it as a bug requires the operation’s accuracy and semantics contract.
4. FP16 subnormals, effective tolerances, and ULPs
What happened to the FP16 erf case
A default relative tolerance is convenient across a broad range of test values, but a near-zero output changes its practical meaning. The comparator’s error normalization matters alongside its nominal rtol.
In the pinned numguard 1.0.1 source used by the experiment, the FP16 default relative tolerance is 1e-2. The comparison’s relative-error denominator uses a floor based on finfo.tiny, which means the smallest positive normal value of the dtype, not its smallest representable subnormal. This stabilizes the denominator near zero, but also lets some subnormal-scale discrepancies pass.
For this particular measured input:
quantized FP16 input 1.1920928955078125e-7
observed FP16 erf result 0
reference rounded to FP16 1.1920928955078125e-7
absolute difference 1.1920928955078125e-7
FP16 minimum positive normal (tiny) 6.103515625e-5
normalized relative difference 0.001953125
FP16 default rtol in this numguard version 0.01
ULP distance 2
The normalized difference is smaller than the chosen default tolerance. Under that policy, a nonzero expected subnormal and zero can compare as close enough; the reference check is not exact equality. The controlled experiment then demonstrated that the same numerical target becomes a failure with rtol=0, atol=0.
One subtle point: zero and a small subnormal may look harmless under an absolute error metric, but representationally they are not identical. In particular applications, the distinction between a representable nonzero value and zero can change subsequent branching, clipping, a normalization denominator, or whether a gradient remains available. In other applications, an error of about 1e-7 is immaterial. Neither interpretation should be silently imposed on every use of the function.
Why rtol=0, atol=0 is a diagnostic control only
A zero-tolerance run checks whether the kernel output differs at all from the rounded reference. It does not establish that a special-function implementation is obliged to be correctly rounded for every input or device. Even good approximate kernels may differ by one or more ULPs. In this probe, the strict FP16 catalogue flagged tiny (maximum 1 ULP), subnormal (5 ULPs), and wide_range (2 ULPs); the custom erf_1e-7 case differed by 2 ULPs. These measurements characterize the tested cases, not all inputs. A practical long-term threshold depends on the function and its downstream error budget.
What is already available, and what is only a possibility
Numguard already reports ULP distances. The question is whether an optional pass/fail accuracy contract should look at ULPs or use a more sensitive near-zero scale for particular functions or case tags. I have not established that a max_ulps= acceptance option exists, so I would treat that as a possible design choice, not a current API. A simpler first step is to document a strict investigation recipe using existing tolerances, then decide case by case whether a persistent guard is warranted. Both false alarms from legitimate approximation and misses of material near-zero behavior are possible; one threshold will not fit every ML operation.
5. Closely related ML cases and what was not tested
The following are sources of additional fixtures if there is interest in expanding beyond these CPU probes. I did not run these scenarios through numguard in this Colab probe, so these are leads rather than confirmed catalogue misses.
- BF16 backward reduction: JAX #30310 describes a precision difference between explicit
jnp.sum and reductions introduced during backpropagation. This is closer to the post’s example of BF16 accumulation than my add(alpha) experiment. A test would need to evaluate the gradient-producing path, or explicitly make a gradient computation the callable under test. The issue discussion also notes different preferences for accuracy and performance, so the desired accumulation rule should be declared rather than assumed.
- Reduced-precision matrix and attention reductions: PyTorch’s numerical-accuracy guide documents configurations in which accumulation precision, reduced-precision truncation, or selected attention backends change results. These need an identified device, matmul size, settings, and target; they are not established by a CPU elementwise probe.
- Fully masked softmax: PyTorch #55056 illustrates the need to define whether an all-masked row should yield zeros, NaNs, or an error. A valid application-specific ‘safe softmax’ contract is different from treating all nonfinite outputs as incorrect.
- Systematic case discovery: Hypothesis and Array API tests offer ways to explore and organize valid values, dtypes, shapes and semantic checks. Herbie and FPBench approach accuracy and expression analysis differently. These may help discover new cases before shrinking and preserving the best as deterministic fixtures, without replacing the project’s CI-friendly catalogue.
The first item is the closest next lead if a genuine BF16 reduction example is desired. Otherwise the two measured CPU cases are enough for a useful, bounded exchange.
6. Reproducibility boundaries and optional next steps
All nine formal configurations completed without execution errors. The targeted failures were reference-check failures, not universal failures of every check. The run used numguard-ci==1.0.1, backend="torch", seed=0, n=12, and large_n=64; the last two deliberately override ordinary catalogue sizes. The installed wheel’s five key source files matched the pinned source fetch by SHA-256, but that does not establish the content of future releases.
If the phenomenon disappears elsewhere, first compare the direct PyTorch result, exact quantized input values, dtype, CPU capability, and length or index. Then compare the chosen reference, tolerance, and numguard’s case/check report. A newer kernel, another instruction set, or a different precision convention can change the results without implying that numguard is at fault. The PyTorch add(alpha) report is useful implementation context, not a universal guarantee.
The smallest useful next action, if any, could be a named fixture, a documented strict diagnostic recipe, or an explicit numerical-contract note. These can remain optional; the observations do not require the author to redesign the catalogue or reproduce a full training workload.
Bottom line
These CPU probes point to two complementary ways to strengthen function-level numerical regression testing while keeping a fixed catalogue simple: preserve a few known difficult value/shape combinations as deterministic fixtures, and consider optional stricter accuracy checks where tiny representable outputs matter. The first is demonstrated by the BF16 add(alpha) and FP16 logit additions; the second by the FP16 erf case that was already generated but passed the default comparator.
The existing numguard mechanisms were sufficient to expose all three when given the corresponding explicit input or diagnostic tolerance. That seems a useful basis for extending coverage, not a reason to replace the existing design. The open question is which numerical contracts and runtime paths are important enough to belong in a shared default catalogue, and which are better as opt-in fixtures for particular workloads.