scatter_add#
A scatter add sends each element of a source tensor to a position of a
target and adds it there. A graph neural network sums the messages along
each node's incoming edges this way. An embedding layer's backward does
too: every token adds its gradient row to the table's row for that token,
and a frequent token's row receives thousands of contributions. PyTorch's
index_add and index_put with accumulate=True are the same operation.
In ExactRef, er.scatter_add(base, index, src, *, axis, alpha=1), also
er.array.indexing.scatter.scatter_add, adds alpha * src into base,
addressed as torch.scatter_add addresses it. index has src's shape.
Source element i goes to the position whose coordinate along axis is
index[i] and whose other coordinates are i's:
Five source values sent along one axis to four outputs, each output starting from its base value.
Each output element is its base value plus alpha times everything sent to
it, added exactly and rounded once: the reference. An output that
receives nothing keeps its base value. alpha is taken at its exact value.
The tolerance covers an implementation that starts from the base
value and adds the contributions one at a time in the
compute format. By default it adds them in source order, as
PyTorch's CPU scatter_add does. A GPU kernel adds them with atomic
operations, in the order they arrive, which
tolerance(standard="any_order") covers. So do PyTorch's index_put and
put_ with accumulate=True, which add in an order of their own on a CPU
too. Outputs with more contributions
have larger tolerances, as longer sums do.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
the values the sums start from; the output has its shape |
required |
|
an integer array of |
required |
|
the values to add, of |
required |
|
the dimension |
required |
|
a scalar every contribution is multiplied by, taken exactly |
|
|
the output format, of the inputs' kind |
the promoted format of |
|
the rounding mode of the reference and of a correct implementation's final rounding into the output format |
|
|
what a result past the output format's range becomes: |
each format's own rule; integers wrap |
|
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 |
With flush_to_zero=True, an operand promoted to a wider format is read by
its own format: its values below that format's smallest normal number, or
float32's for a narrower format, may be zeros
(flushing).
Examples#
A graph neural network layer sums each node's incoming messages. Here is a graph the size of the Cora citation graph, 2708 nodes and 10,556 edges, with a message of 64 features along each edge:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
nodes, edges = 2708, 10556
# Each edge's destination: a few nodes receive many edges, as in real graphs
popularity = 1 / torch.arange(1, nodes + 1, dtype=torch.float64)
dst = torch.multinomial(popularity, edges, replacement=True, generator=g)
# A message of 64 features along each edge
messages = torch.randn(edges, 64, generator=g)
# The destination written out along each message, as scatter_add's index
index = dst[:, None].expand(edges, 64)
# ExactRef's result: each node's sum of its incoming messages, from zeros
r = er.scatter_add(torch.zeros(nodes, 64), index, messages, axis=0)
out = torch.zeros(nodes, 64).scatter_add(0, index, messages)
print("covered:", r.covers(out).all())
# PyTorch's CPU adds in source order, which normal() emulates exactly
print("equal to normal():", r.normal().tolist() == out.tolist())
covered: True
equal to normal(): True
index_add takes one destination per row of src. Written out along the
row, as index above, it is the same operation:
print("index_add covered:", r.covers(torch.zeros(nodes, 64).index_add(0, dst, messages)).all())
index_add covered: True
A node's tolerance grows with the number of messages it receives:
# The node with the most incoming edges, and a node with none
counts = torch.bincount(dst, minlength=nodes)
hub, alone = int(counts.argmax()), int((counts == 0).nonzero()[0])
tolerance = r.tolerance().tolist()
print("messages into the hub:", int(counts[hub]))
print("the hub's largest tolerance:", max(tolerance[hub]))
print("an isolated node's largest tolerance:", max(tolerance[alone]))
messages into the hub: 1289
the hub's largest tolerance: 0.00391387939453125
an isolated node's largest tolerance: 0.0
16-bit formats#
PyTorch's scatter_add adds bfloat16 and float16 values in float32, the
default compute format. Its index_add and index_put round every
addition to the dtype instead, so check those with compute= the dtype. A
frequent token's row in a bfloat16 embedding gradient shows the
difference. Here 4096 contributions of 1/256 go to an output that holds 1:
# One output holding 1, and 4096 contributions of 1/256 to it, in bfloat16
one = torch.ones(1, dtype=torch.bfloat16)
small = torch.full((4096,), 2.0**-8, dtype=torch.bfloat16)
at = torch.zeros(4096, dtype=torch.long)
rb = er.scatter_add(one, at, small, axis=0)
print("reference:", rb.rounded.tolist())
# index_add rounds each addition to bfloat16, and 1 + 1/256 rounds back to 1
print("index_add gives:", one.index_add(0, at, small).tolist())
print("covered with float32 steps:", rb.covers(one.index_add(0, at, small)).all())
print("covered with bfloat16 steps:", rb.covers(one.index_add(0, at, small), compute="bfloat16").all())
reference: [17.0]
index_add gives: [1.0]
covered with float32 steps: False
covered with bfloat16 steps: True
Special values#
Infinities and NaN follow IEEE rules on each exact sum. An exact zero takes the sign IEEE arithmetic gives a sum that starts at the base value: -0 plus +0 is +0, and a -0 that receives only -0 stays -0.
# Bases -0, -0, and 1
bases = er.asarray([-0.0, -0.0, 1.0], "float32")
# Contributions +0, -0, and -1, one to each base
contributions = er.asarray([0.0, -0.0, -1.0], "float32")
zeros = er.scatter_add(bases, er.asarray([0, 1, 2]), contributions, axis=0)
print("zeros:", zeros.rounded.tolist())
zeros: [0.0, -0.0, 0.0]
Backward#
er.scatter_add.backward(base, index, src, grad, *, axis, alpha=1), or
r.backward(grad), returns grad_base, which is grad, and grad_src,
which is alpha * grad read at each source element's output position
(conj(alpha) for a complex alpha). Each element is one product, rounded
once. For the graph above, the messages' gradient:
# The gradient of each node's sum
grad = torch.randn(nodes, 64, generator=g)
# PyTorch's autograd, on copies that record gradients
base_, messages_ = torch.zeros(nodes, 64, requires_grad=True), messages.clone().requires_grad_()
base_.scatter_add(0, index, messages_).backward(grad)
# ExactRef's gradients, held by name
gb = er.scatter_add.backward(torch.zeros(nodes, 64), index, messages, grad, axis=0)
print("outputs:", list(gb.rounded))
print("grad_src covered:", gb["grad_src"].covers(messages_.grad).all())
outputs: ['grad_base', 'grad_src']
grad_src covered: True
Full specification#
er.scatter_add#
- scatter_add(base, index, src, *, axis: int, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
basewithalpha * srcadded at the positionsindexgives alongaxis, astorch.scatter_addaddresses them: source elementigoes to the position whose coordinate alongaxisisindex[i]and whose other coordinates arei's.indexis an integer array ofsrc's shape with values in[0, base.shape[axis]); several source elements may name one position. A 0-dimensionalbaseis one position on an axis of size 1. Each output element is its base value plusalphatimes every contribution sent to it, as one exact sum rounded once todtype(default: the operands' promoted format). An output that receives nothing is its base value.alphais taken exactly as given.tolerance()bounds an implementation that adds the contributions to the base value in the compute format: by default one after another in source order, starting from the base value, as PyTorch'sscatter_adddoes; withstandard="any_order"in any order, as atomic adds on a GPU do. Withalpha1 or -1 no term is rounded on its own. An exact zero takes the sign IEEE arithmetic gives the sum that starts at the base value. Integer results wrap on overflow unlessoverflowsays otherwise.baseandsrcmay also be earlier results. PyTorch'sindex_addandindex_putwithaccumulate=Trueare this operation withindexwritten out along the axis; in float16 and bfloat16 they round every addition to the dtype, which istolerance(compute=dtype). Proof:proofs/scatter_add.md.
er.scatter_add.backward#
- backward(base, index, src, grad, *, axis: int, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradients of
scatter_add(base, index, src, axis=axis, alpha=alpha)for the output gradientgrad.grad_base = grad, inbase's dtype, andgrad_srcisconj(alpha) * gradread at each source element's output position, insrc's shape and dtype: one product per element, each rounded once.gradmust havebase's shape.
See also#
sum and add, subtract, and multiply, whose rules each output's sum follows.
PyTorch equivalents:
scatter_add,index_add,index_put, and an embedding's backward.