ML Foundations

Choose an accumulator for NumPy cumulative sums

Detect integer wraparound in running totals and choose an explicit accumulator type.

Example results for Choose an accumulator for NumPy cumulative sums. int16 maximum: 32767
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 running total has a numeric range

A cumulative sum can exceed the range of its accumulator even when every individual observation fits in the input type. NumPy documents modular arithmetic for integer cumulative sums, with no error raised on overflow. A negative running total can therefore result from a narrow accumulator. [1]

The dtype argument selects the accumulator and returned array type. If dtype is omitted, NumPy generally uses the input type, with promotion to the platform integer for narrower integer inputs. Check the actual result type instead of assuming a particular platform default. [1]

References: [1]

Compare narrow and wide accumulators

Run python examples/numpy_cumsum_accumulator_types.py. Each input fits in int16, whose maximum is 32767. The explicitly requested int16 accumulator wraps when its second running total reaches 60000, producing a negative value. [1, 2]

With an explicitly requested int64 accumulator, the same values produce running totals of 30000, 60000 and 61000. Assertions check both results, while the source remains int16. This fixture demonstrates the difference for these values, not an automatic guarantee for every dataset. [1]

Executed with Python 3.12.14; stdout and checksum recorded in private evidence.

import numpy as np

values = np.array([30000, 30000, 1000], dtype=np.int16)
narrow = np.cumsum(values, dtype=np.int16)
wide = np.cumsum(values, dtype=np.int64)
assert narrow.tolist() == [30000, -5536, -4536]
assert wide.tolist() == [30000, 60000, 61000]
print("int16 maximum:", np.iinfo(np.int16).max)
print("narrow accumulation:", narrow.tolist())
print("wide accumulation:", wide.tolist())
print("input dtype:", values.dtype)

Recorded output

int16 maximum: 32767
narrow accumulation: [30000, -5536, -4536]
wide accumulation: [30000, 60000, 61000]
input dtype: int16

References: [1], [2]

Size the range for the whole calculation

Estimate possible cumulative totals as well as individual values, including negative totals when inputs may be negative. Use iinfo on an integer dtype to inspect its minimum and maximum, then choose a type that covers the expected bounds. [2]

A wider fixed-width integer can still overflow. If the required range is unknown, validate bounds or select an appropriate different representation before accumulating. For multidimensional arrays, specify the intended axis because cumsum otherwise flattens the input. [1]

References: [1], [2]

Sources

  1. NumPy cumsum
  2. NumPy iinfo