sum#

A sum adds up the elements of an array, over all of its dimensions or only some, such as the sum of each row. It is the simplest reduction, and the one where the order of additions shows most plainly: the same numbers added in a different order can give a different floating-point result, and parallel implementations add in many different orders.

In ExactRef, er.sum(x, axis=None, *, keepdims=False), also er.reduction.arithmetic.sum, is the sum over the dimensions in axis (all of them by default; an int or a tuple of ints), as in torch.sum. The output can be any format of the input's kind, integer for a bool input. To check another implementation's output against it, use covers(), as in Checking PyTorch below.

Each output element is the exact sum, rounded once: the reference. The order of additions changes a floating-point sum, and the tolerance, per element how far a correct implementation's output can be from the reference, accounts for that: it allows for a rounding after each addition in the compute format, the format an implementation adds in (float32 by default for inputs narrower than float32, else the input format), and for the final rounding to the output format. By default it covers normal accumulation, the order ordinary kernels add in: index order, or a few SIMD lanes side by side. tolerance(standard="any_order") covers any order of additions at all, as a parallel reduction or atomic adds on a GPU may use, and is wider. The terms are the input values themselves, so unlike matmul's products they are not rounded before they are added. Otherwise the tolerance and normal() (what an ordinary implementation that adds in index order computes, emulated exactly) follow the same rules as matmul's sum of products, with each element counted as itself times 1.

index order pairwise 4 lanes a b c d a b c d 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

Three orders for the same eight terms. Each addition rounds, so each order can give a different answer.

Arguments#

Argument

Meaning

Default

x

the array to sum

required

axis

the dimensions to sum over: an int or a tuple of ints

None, every dimension

keepdims

keep the summed dimensions, with size 1

False

dtype

the output format, of the same kind as the inputs (integer for bool inputs)

the input 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#

The sum of each token's activations over a hidden dimension of 4096, as LayerNorm takes it for the mean, for 128 tokens in bfloat16:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The activations of 128 tokens
x = torch.randn(128, 4096, generator=g).bfloat16()

# ExactRef's result for the sum of each row
r = er.sum(x, axis=1)
print("shape:", r.rounded.shape)
# The first three rows' exact sums, rounded once to bfloat16
print("rounded:", r.rounded.tolist()[:3])
# How far a correct implementation's output can be from each of them
print("tolerance:", r.tolerance().tolist()[:3])
Output
shape: (128,)
rounded: [-10.875, 64.5, -20.125]
tolerance: [0.0, 0.0, 0.0]

For bfloat16 inputs the tolerance assumes the additions happen in float32, which is much finer than the bfloat16 output, so for these three rows every correct implementation lands on rounded.

Dimensions#

keepdims=True keeps the summed dimension with size 1, so the result broadcasts back against the input, as LayerNorm subtracts the mean. A tuple sums over several dimensions, such as the batch and the sequence for a bias gradient:

Code
# One sum per row, kept as a column of 128 rows
print("keepdims:", er.sum(x, axis=1, keepdims=True).rounded.shape)

# A batch of 4 sequences of 128 tokens, summed over both to one value per channel
batch = torch.randn(4, 128, 1024, generator=g).bfloat16()
print("axis=(0, 1):", er.sum(batch, axis=(0, 1)).rounded.shape)
# Every dimension, by default
print("all:", er.sum(batch).rounded.shape)
Output
keepdims: (128, 1)
axis=(0, 1): (1024,)
all: ()

Integer and bool inputs#

Integer and bool inputs give int64, as PyTorch sums them. A bool sum counts the True elements, which gives each sequence's length from its padding mask:

Code
# A padding mask for 4 sequences padded to 512 positions: True for a real token
lengths = torch.tensor([512, 300, 77, 1])
keep = torch.arange(512) < lengths[:, None]

# The number of real tokens in each sequence
counted = er.sum(keep, axis=1)
print("lengths:", counted.rounded.tolist())
print("dtype:", counted.rounded.dtype.name)
Output
lengths: [512, 300, 77, 1]
dtype: int64

PyTorch's sum(x, dtype=d)#

torch.sum(x, dtype=d) converts x to d before summing. When d is the same kind of format as x (both floating point, for example), the matching reference is er.sum(er.multiply(x, 1, dtype=d)), a chain: the multiply's result passed to er.sum, whose bounds then cover every value that result allows. Multiplying by 1 rounds x once to d, and the sum then adds in d's compute format. Summing bfloat16 activations into a float32 total, as for a mean, is such a case:

Code
# PyTorch's row sums of the bfloat16 activations, in float32
total = torch.sum(x, dim=1, dtype=torch.float32)

# x converted to float32 (times 1, rounded once), then summed
wide = er.sum(er.multiply(x, 1, dtype="float32"), axis=1)
print("dtype:", wide.rounded.dtype.name)
print("covered:", wide.covers(total).all())
Output
dtype: float32
covered: True

For d of another kind, such as an integer x summed in float32, it is er.sum(er.asarray(x, d)).

Complex sums, empty sums#

Summing complex values, such as the bins of a spectrum, adds the real and imaginary parts as two separate sums. A sum over no elements, as when a shard of a split batch holds no tokens, is +0:

Code
# Real parts 1 + 3, imaginary parts 2 + -1
print("complex sum:",
      er.sum(er.asarray([1 + 2j, 3 - 1j], "complex64")).rounded.tolist())
# A shard with no tokens: shape (0, 1024), summed over the tokens
print("empty sum:", er.sum(torch.zeros(0, 1024), axis=0).rounded.tolist()[:3])
Output
complex sum: (4+1j)
empty sum: [0.0, 0.0, 0.0]

Checking PyTorch#

To check an implementation, pass its output to covers(). PyTorch's CPU sum adds in SIMD lanes and a tree, not in index order, so its float32 row sums differ from what a plain loop gets, normal(). Each is still a correct answer:

Code
# Could a correct implementation produce PyTorch's bfloat16 row sums? covers()
# answers per element, and all() asks whether every element is covered.
print("bfloat16 covered:", r.covers(x.sum(dim=1)).all())

# The same row sums in float32
x32 = x.float()
r32 = er.sum(x32, axis=1)
print("float32 covered:", r32.covers(x32.sum(dim=1)).all())
# A loop that adds in index order gets other values for some rows
print("same as normal():", r32.normal().identical(er.asarray(x32.sum(dim=1))))
Output
bfloat16 covered: True
float32 covered: True
same as normal(): False

Backward#

er.sum.backward(x, grad, axis=None, *, keepdims=False) returns grad_x: at every element of x, the gradient of the output it was summed into. A loss that sums the per-token losses of each sequence and averages over the sequences is one example:

Code
# Per-token losses for 8 sequences of 512 tokens
losses = torch.rand(8, 512, generator=g) * 5
# PyTorch's autograd for the mean over sequences of each sequence's sum
losses_ = losses.clone().requires_grad_()
losses_.sum(dim=1).mean().backward()

# The gradient of each sequence's sum: 1/8 from the mean
grad = torch.full((8,), 0.125)
gb = er.sum.backward(losses, grad, axis=1)
# The backward's one gradient, read by name as a result of its own
print("covered:", gb["grad_x"].covers(losses_.grad).all())
Output
covered: True

Even though the backward has only one gradient, it is still named: read it as gb.rounded.grad_x. To pass it into another operation, as in Chains and any_of, use gb["grad_x"].

Full specification#

er.sum#

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

Sum over axis (None: every dimension; an int or a tuple of ints), keeping the reduced dimensions as 1 with keepdims.

Each output element is the 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. tolerance() budgets accumulation in the compute format and the final rounding; by default normal accumulation (index order of the reduced elements, row-major, or 2 or 4 SIMD-style lanes), with standard="any_order" any order. Each term is an input value, so it is not rounded on its own. A complex sum adds its real and imaginary parts as two separate sums. An exact zero sum is +0 (-0 when rounding toward -inf); an empty sum is +0. Integer results wrap on overflow unless overflow says otherwise. x may also be an earlier result. PyTorch's sum(x, dtype=d) converts x to d before summing: for d of x's kind that is sum(multiply(x, 1, dtype=d)), whose sum accumulates in d's compute format, and for another kind (an integer x summed in a float format) sum(asarray(x, d)).

er.sum.backward#

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

Gradient of sum(x, axis, keepdims=keepdims) for the output gradient grad.

grad_x holds, at every element of x, the gradient of the output it was summed into, in x's dtype (rounded once if grad's dtype is wider); an exact zero keeps grad's sign, as in PyTorch. grad must have the output's shape. x and grad may also be earlier results.

See also#