Internals#

How it works#

Every finite double is an integer multiple of 2^-1074, the smallest subnormal, so a sum of doubles is an integer times 2^-1074. Neal’s superaccumulators hold that integer exactly. They count in units of 2^-1075 (a double with biased exponent e and 53-bit significand m is m · 2^(e − 1075), with e taken as 1 for subnormals), so that the exponent maps directly onto the digit positions.

  • Small superaccumulator: 67 signed 64-bit “digits”, each holding 32 bits of the fixed-point number plus 31 bits of headroom. A double with exponent e is split into two pieces added to digits e/32 and e/32 + 1. Carries are propagated only once every 1023 additions.

  • Large superaccumulator: one 64-bit chunk per sign and exponent (4096 chunks). A double is added by adding its raw bit pattern to the chunk selected by its top 12 bits. The mantissa sum can be recovered exactly as long as a chunk holds at most 2048 values. A full chunk is flushed into the small accumulator. A per-chunk counter of remaining capacity makes the common case a single decrement-and-branch plus one read-modify-write. Each chunk index has 4 lanes (separate chunks in one cache line) that consecutive values alternate between. This breaks the store-to-load dependency chains when many consecutive values share an exponent. The large accumulator handles about 2.3 G values/s on one core, ~20% faster than naive sequential f64 summation on the same machine.

  • Rounding extracts the top 53 bits of the exact integer plus guard and sticky bits. Float32 results first round to f64 with round-to-odd, after which the conversion to f32 is provably correctly rounded.

  • Parallelism: accumulators merge exactly, so long columns (≥ 32Ki values) are split into blocks that are summed on all cores with rayon. The result is bit-identical to the sequential sum. Columns and groups of fewer than 1,536 values use the small accumulator. Large accumulators are cleared and reused through a small per-thread cache (≤ 2 × 160 KiB per thread). This avoids paying allocation and page-fault costs on every call.

  • No unsafe: xsum-core is #![forbid(unsafe_code)]. The plugin crate contains no hand-written unsafe code; its only unsafe code is the FFI glue that the #[polars_expr] (pyo3-polars) and #[pymodule]/#[pyfunction] (pyo3) macros generate.

See Benchmarks for performance measurements.

References#

Radford M. Neal, Fast exact summation using small and large superaccumulators, 2015. arXiv:1505.05571