ML Foundations

Choose a wider accumulator for a float16 sum

Keep a finite reduction when a float16 sum exceeds its representable range.

Example results for Choose a wider accumulator for a float16 sum. input dtype: float16
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

A finite input can have an overflowing sum

Floating-point types have finite representable ranges. A collection of finite float16 values can have a sum that exceeds the float16 range. NumPy sum accepts a dtype argument that controls the accumulator and output type. [1, 2]

Choosing a wider accumulator can avoid overflow for sums that are representable in that wider type. It does not guarantee that every possible sum will be finite or exact. [1, 2]

References: [1], [2]

Compare accumulators

Run python examples/numpy_float16_sum.py. Four float16 inputs of 30000 have an exact mathematical total of 120000, beyond the finite range of float16. The example suppresses the expected overflow warning only around the default reduction, then asserts that its result is infinite. [1, 2]

The second reduction specifies dtype float32 and returns the finite value 120000. The fixture checks the actual output and its dtype. It is a small deterministic example, not a benchmark. [1]

Executed with local Python and NumPy; stdout and checksum are stored in private evidence.

import numpy as np

values = np.array([30000, 30000, 30000, 30000], dtype=np.float16)
with np.errstate(over="ignore"):
    narrow = np.sum(values)
wide = np.sum(values, dtype=np.float32)
assert np.isinf(narrow) and np.isfinite(wide)
assert wide == 120000.0
print("input dtype:", str(values.dtype))
print("default sum:", float(narrow))
print("float32 sum:", float(wide))
print("float32 result dtype:", str(wide.dtype))

Recorded output

input dtype: float16
default sum: inf
float32 sum: 120000.0
float32 result dtype: float32

References: [1], [2]

Check the entire computation

Select an accumulator based on the expected sum range, and check results for finite values where overflow is relevant. A wider reduction cannot recover precision already lost when the inputs were converted to a narrower format. [1, 2]

This example uses positive finite inputs and a float32 accumulator. It does not demonstrate all floating-point error modes, cancellation, GPU behavior or the behavior of other libraries. [1, 2]

References: [1], [2]

Sources

  1. NumPy sum
  2. NumPy numeric types