cumulative_sum#

A running sum replaces each element with the sum of everything up to it. Top-p sampling sorts a language model's next-token probabilities and keeps tokens until their running sum passes p. A batch that packs sequences of different lengths finds where each sequence ends from the running sum of the lengths.

In ExactRef, er.cumulative_sum(x, axis), also er.scan.cumulative.cumulative_sum, is the running sum along axis, in x's shape, as in torch.cumsum. It takes floating-point, complex, integer, and bool inputs. Integers and bools are summed in int64, as in PyTorch. A complex running sum adds the real parts and the imaginary parts separately.

Each output element is the exact sum of its prefix, rounded once: the reference. Integer prefixes are exact.

The tolerance covers an implementation that keeps one running sum in the compute format and adds the elements in index order, rounding after each addition. The tolerance grows along the axis:

x x0 x1 x2 x3 x4 output x0 x0 + x1 ... + x2 ... + x3 ... + x4 one more rounding behind each output

Each output adds one element to the output before it.

A running sum's normal accumulation is index order only, since its outputs are the partial sums themselves. A GPU computes the prefixes with a parallel scan, in an order of its own, which tolerance(standard="any_order") covers.

Arguments#

Argument

Meaning

Default

x

the input: floating-point, complex, integer, or bool

required

axis

the dimension to sum along, an int

required

dtype

the output format: of the input's kind, or integer for integer and bool inputs

the input's format; int64 for integer and bool inputs

rounding

the rounding mode of the reference and of a correct implementation's final rounding into the output format

er.Rounding.NEAREST_EVEN

overflow

what a result past the output format's range becomes: "ieee", "saturate", or "nan" for floats; "wrap", "error", or "saturate" for integers

each format's own rule; integers wrap

workers

the number of threads the call computes on; no result depends on it

the performance cores on Apple Silicon, else the physical cores, as PyTorch picks

Examples#

Sampling takes the running sum of a probability vector. Here are 8 rows of probabilities over GPT-2's vocabulary of 50,257 tokens. PyTorch's CPU keeps a float32 running sum in float64, so check it with that compute format:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# 8 rows of next-token probabilities over 50,257 tokens
probs = torch.softmax(torch.randn(8, 50257, generator=g) * 3, dim=-1)

# ExactRef's result, and PyTorch's running sums
r = er.cumulative_sum(probs, -1)
out = probs.cumsum(-1)
# Could an implementation with float64 steps produce PyTorch's output?
print("covered:", r.covers(out, compute="float64").all())
# normal() emulates float64 steps in index order exactly
print("equal to normal():", r.normal(compute="float64").tolist() == out.tolist())
Output
covered: True
equal to normal(): True

With float32 steps, the default, the tolerance grows along the row. With float64 steps it stays within one float32 ulp:

Code
# The tolerance of the first row with float32 steps, at the 10th and the last element
steps32 = r.tolerance().tolist()[0]
print("10th element:", f"{steps32[9]:.0e}")
print("last element:", f"{steps32[-1]:.0e}")
# The largest tolerance with float64 steps, over every element
print("largest with float64 steps:", f"{max(r.tolerance(compute='float64').scalars()):.0e}")
Output
10th element: 1e-11
last element: 1e-03
largest with float64 steps: 6e-08

Integers#

A batch that packs 64 sequences end to end locates them by the running sum of their lengths. Integer running sums are exact, so the result's guarantee is "exact" and a correct implementation returns rounded itself:

Code
# The lengths of 64 sequences, from 1 to 4096 tokens
lengths = torch.randint(1, 4097, (64,), generator=g)

# Where each sequence ends in the packed batch
ends = er.cumulative_sum(lengths, 0)
print("dtype:", ends.rounded.dtype.name)
print("guarantee:", ends.guarantee)
print("total tokens:", ends.rounded.tolist()[-1])
# PyTorch's int64 running sum, compared bit for bit
print("identical:", ends.rounded.identical(er.asarray(torch.cumsum(lengths, 0))))
Output
dtype: int64
guarantee: exact
total tokens: 129375
identical: True

The offsets that kernels for packed sequences take start with a 0: that exclusive form is this running sum shifted by one place. A reversed running sum is the running sum of the flipped input, read backwards.

Special values#

Infinities and NaN follow IEEE rules on each exact prefix, so they reach every later element. An exact zero is +0, or -0 when rounding toward -inf:

Code
inf = float("inf")
# An infinity, then the other infinity
print("infinities:", er.cumulative_sum(er.asarray([1.0, inf, 2.0, -inf], "float32"), 0).rounded.tolist())
# A prefix that cancels exactly
print("zero:", er.cumulative_sum(er.asarray([1.0, -1.0], "float32"), 0).rounded.tolist())
Output
infinities: [1.0, inf, inf, nan]
zero: [1.0, 0.0]

Backward#

er.cumulative_sum.backward(x, grad, axis), or r.backward(grad), returns grad_x. At each element it is the sum of grad from that element to the end of its line: a running sum taken from the far end, each element rounded once. PyTorch computes it as a flip, a cumsum, and a flip, so check it with the forward's compute format:

Code
# The gradient of the running sums
gy = torch.randn(8, 50257, generator=g)

# PyTorch's autograd, on a copy that records gradients
probs_ = probs.clone().requires_grad_()
probs_.cumsum(-1).backward(gy)

# ExactRef's gradient, held by name
gb = er.cumulative_sum.backward(probs, gy, -1)
print("outputs:", list(gb.rounded))
print("grad_x covered:", gb["grad_x"].covers(probs_.grad, compute="float64").all())
Output
outputs: ['grad_x']
grad_x covered: True

Full specification#

er.cumulative_sum#

cumulative_sum(x, axis: int, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

The running sum of x along axis: element i of each line is the sum of the line's elements 0 to i, in x's shape (torch.cumsum).

Each output element is that exact sum rounded once to dtype (default: the input dtype; int64 for integer and bool inputs, as PyTorch sums them), which must be of that kind. A complex running sum adds its real and imaginary parts as two separate sums. An exact zero sum is +0 (-0 when rounding toward -inf). Integer results wrap on overflow unless overflow says otherwise.

tolerance() bounds an implementation that keeps one running sum in the compute format and rounds it after each addition, in index order: a running sum's normal standard is index order only. With standard="any_order" each prefix may be added in any order, as a parallel scan on a GPU does. Later elements have larger tolerances: each has one more rounding behind it. PyTorch's CPU kernel keeps a float32 running sum in float64, which is tolerance(compute="float64"); its float16 and bfloat16 sums run in float32, the default. x may also be an earlier result. The reversed and exclusive forms are flips and shifts of this one. Proof: proofs/cumulative_sum.md.

er.cumulative_sum.backward#

backward(x, grad, axis: int, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradient of cumulative_sum(x, axis) for the output gradient grad.

grad_x at element i of each line is the sum of grad from i to the line's end: the running sum of grad taken from the far end of the axis, each element exact and rounded once to x's dtype. tolerance() bounds that running sum as cumulative_sum bounds one. grad must have x's shape.

See also#