add, subtract, and multiply#
Elementwise addition, subtraction, and multiplication combine arrays element
by element: x[i] + alpha * y[i], x[i] - alpha * y[i], and x[i] * y[i]. Broadcasting first stretches arrays
of different shapes to a common shape, as NumPy and PyTorch do, so a row can
be added to every row of a matrix. They are the most basic operations of
all, and they still round: the exact sum or product of two floats usually
needs more bits than the format has. A single product, or a sum with alpha
1 or -1, rounds once, so there is usually exactly one correct answer; a sum
with another alpha, and a complex product, round in more places.
In ExactRef, er.add(x, y, *, alpha=1) computes x + alpha * y and
er.multiply(x, y) computes x * y, element by element with NumPy
broadcasting. They are also er.arithmetic.basic.add and
er.arithmetic.basic.multiply. subtract is add with alpha
negated. The output can be any format of the inputs'
kind. To check another implementation's output against
them, use covers(), as in Checking PyTorch below.
Each output element is the exact value rounded once, the
reference. The tolerance, per element how far a correct
implementation's output can be from the reference, is often 0. When the
inputs are arrays, alpha is real, and subnormals are not
flushed to zero, it is never looser than needed: it is
exactly the largest error a correct implementation can make.
ExactRef can work that out because it treats
x * y as a sum with one product, and x + alpha * y as the two-term sum
x * 1 + y * alpha. Otherwise the tolerance and normal() (what an
ordinary implementation computes, emulated exactly) follow the same rules as
matmul's sum of products, which
How tolerance works explains. Those rules allow
for a rounding of each product and sum in the compute format,
the format an implementation computes in along the way (float32 by default
for inputs narrower than float32, else the input format), and for the final
rounding to the output format.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
the operands, broadcast together; a Python scalar, or an array of shape |
required |
|
the factor on |
|
|
the output format, of the same kind as the inputs |
the operands' promoted format |
|
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 |
Examples#
The residual add of a transformer block, h + attn_out, for 128 tokens of
hidden size 1024 in bfloat16:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The residual stream, and the attention block's output
h = torch.randn(128, 1024, generator=g).bfloat16()
attn_out = torch.randn(128, 1024, generator=g).bfloat16()
# ExactRef's result for the add
r = er.add(h, attn_out)
print("dtype:", r.rounded.dtype.name)
# Row 0's first three elements: exact sums, rounded once to bfloat16
print("rounded:", r.rounded.tolist()[0][:3])
# The largest tolerance of the 131,072 elements
print("largest tolerance:", max(r.tolerance().scalars()))
dtype: bfloat16
rounded: [-0.9453125, -0.107421875, 1.0625]
largest tolerance: 0.0
An add with alpha 1 rounds once, so a tolerance of 0 means every correct
implementation returns rounded itself.
Broadcasting#
A per-channel weight, such as RMSNorm's, multiplies every token's row of activations. Broadcasting stretches the weight's one row to every token, as in NumPy and PyTorch:
# Normalized activations of 128 tokens, and RMSNorm's weight of 1024 channels
normed = torch.randn(128, 1024, generator=g).bfloat16()
weight = (1 + torch.randn(1024, generator=g) / 8).bfloat16()
# The weight's row is used for every token
scaled = er.multiply(normed, weight)
print("shape:", scaled.rounded.shape)
print("covered:", scaled.covers(normed * weight).all())
shape: (128, 1024)
covered: True
alpha and scalar operands#
alpha and a scalar operand (an int, float, complex, a Fraction with a
power-of-two denominator, a FloatValue, or a ComplexValue) are taken
exactly and do not change the output format. The reference is the exact
answer for the values as given.
Many implementations round a scalar to a format first, and PyTorch's CPU
kernels do. For them, er.arithmetic.basic has two
algorithms, add_held_scalar(held) and
multiply_held_scalar(held). Each rounds every scalar operand, and alpha,
to nearest even in the format held before the operation: "operand" for
the tensor's format, "compute" for the compute format, or a format
by name. A sequence of these, such as ("float32", "operand"), rounds to
each in turn. Their tolerance(), finite_range(), may_be(), covers(),
and normal() take the operation's arguments after the output, and their
bounds are still measured from the operation's reference. PyTorch's CPU kernels
hold scalars this way:
PyTorch on the CPU |
Algorithm |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The sequences hold a float64 or complex128 value as PyTorch converts it,
through float32 or complex64. For float16, "operand" holds where PyTorch
converts a float64 value to float16 in one rounding, as on aarch64; on
x86_64 it converts through float32, so use ("float32", "operand") there.
An SGD step, p.add(grad, alpha=-lr), is an add with alpha:
# A float32 weight of 1024 by 1024 and its gradient
p = torch.randn(1024, 1024, generator=g) / 32
grad = torch.randn(1024, 1024, generator=g) / 1000
# PyTorch's SGD step with learning rate 0.001
step = p.add(grad, alpha=-0.001)
# add takes alpha at its exact value, -0.001
print("covered by add:", er.add(p, grad, alpha=-0.001).covers(step).all())
# PyTorch's CPU add rounds alpha to float32 first
held = er.arithmetic.basic.add_held_scalar("operand")
print("covered with alpha held in float32:", held.covers(step, p, grad, alpha=-0.001).all())
covered by add: False
covered with alpha held in float32: True
Attention with head dimension 128 scales its queries by 1/sqrt(128), which
float32 cannot hold exactly:
# Queries of 8 heads, 512 positions, and head dimension 128, in float32
q = torch.randn(1, 8, 512, 128, generator=g)
# PyTorch scales them by the Python float 1/sqrt(128)
scale = 128 ** -0.5
out = q * scale
# multiply takes the scale at its exact value
print("covered by multiply:", er.multiply(q, scale).covers(out).all())
# PyTorch's CPU mul rounds the scale to float32 first
held = er.arithmetic.basic.multiply_held_scalar("operand")
print("covered with the scale held in float32:", held.covers(out, q, scale).all())
covered by multiply: False
covered with the scale held in float32: True
Mixed formats#
Mixed-precision code combines tensors of different formats, such as a bfloat16 branch added to a float32 residual stream. Operands of different formats are promoted the way PyTorch promotes them:
# A float32 residual stream, and a branch's output in bfloat16
stream = torch.randn(128, 1024, generator=g)
branch = torch.randn(128, 1024, generator=g).bfloat16()
# float32 holds both formats, so the sum is float32
mixed = er.add(stream, branch)
print("dtype:", mixed.rounded.dtype.name)
print("covered:", mixed.covers(stream + branch).all())
dtype: float32
covered: True
With flush_to_zero=True, a promoted operand flushes below its own
format's smallest normal number, or float32's for a narrower format. float32
data added to float64 data may be read as zero below 2**-126, as PyTorch's
conversion to float64 flushes it.
An array of shape () counts toward the promoted format only when every
operand has shape (). Beside an operand with dimensions it is a scalar
operand: taken exactly, whatever its format, without changing the output
format. Scaling bfloat16 activations by a float32 factor of shape () stays
in bfloat16 and multiplies by the factor's float32 value:
# bfloat16 activations, and a float32 scale held as a tensor of shape ()
acts = torch.randn(128, 1024, generator=g).bfloat16()
scale = torch.tensor(61.264957427978516)
# The output stays bfloat16; the scale is used at its float32 value
scaled = er.multiply(acts, scale)
print("dtype:", scaled.rounded.dtype.name)
print("covered:", scaled.covers(acts * scale).all())
dtype: bfloat16
covered: True
Centering bfloat16 data with its float32 mean is an add case. PyTorch's
CPU add of bfloat16 rounds the mean to float32 and then to bfloat16 first,
as it rounds every scalar operand, so check it with
add_held_scalar(("float32", "operand")):
# bfloat16 data, and its mean as a float32 tensor of shape ()
data = (torch.randn(128, 1024, generator=g) + 3).bfloat16()
mean = data.float().mean()
# data - mean is data + (-1) * mean; add takes the mean at its float32 value
centered = er.add(data, mean, alpha=-1)
print("dtype:", centered.rounded.dtype.name)
print("covered by add:", centered.covers(data - mean).all())
# PyTorch's CPU add rounds the mean to float32, then to bfloat16
held = er.arithmetic.basic.add_held_scalar(("float32", "operand"))
print("covered with the mean held in bfloat16:", held.covers(data - mean, data, mean, alpha=-1).all())
dtype: bfloat16
covered by add: False
covered with the mean held in bfloat16: True
When every operand has shape (), all of them count: a float64 with a
float16 gives float64.
Signs of zero#
The sign of a zero matters to later steps, such as 1 / x, which turns -0
into -inf, and to tests that compare bits. A kernel that always adds a bias,
even one of zeros, turns the -0 of -0.0 + -0.0 into +0. An exact zero takes
the sign IEEE arithmetic gives, as in PyTorch for real values: -0.0 + -0.0
is -0, and a cancellation is +0, or -0 when rounding toward -inf. covers() compares
values, and -0 equals +0, so compare encodings with identical() to check
the sign:
# A float32 -0
neg = er.asarray([-0.0], "float32")
# value((0,)) is element 0's exact value; negative is True for a minus sign
print("-0 + -0 negative:", er.add(neg, neg).rounded.value((0,)).negative)
# What the kernel with a zero bias returns: +0
plus_zero = er.asarray([0.0], "float32")
print("+0 covered:", er.add(neg, neg).covers(plus_zero).all())
print("+0 identical:", er.add(neg, neg).rounded.identical(plus_zero))
# Float32 1 and -1
one, minus_one = er.asarray([1.0], "float32"), er.asarray([-1.0], "float32")
# 1 + -1 cancels to an exact zero, +0
print("1 + -1 negative:", er.add(one, minus_one).rounded.value((0,)).negative)
# The same sum, rounded toward -inf, is -0
down = er.Rounding.TOWARD_NEGATIVE
print("1 + -1 toward -inf negative:",
er.add(one, minus_one, rounding=down).rounded.value((0,)).negative)
-0 + -0 negative: True
+0 covered: True
+0 identical: False
1 + -1 negative: False
1 + -1 toward -inf negative: True
Special values#
Complex data can hold infinities, for example a spectrum after an overflow
in a frequency-domain filter. Complex special values follow IEEE rules in
each part, as in PyTorch. A coefficient that is exactly 0, such as
alpha=0, turns an infinity into NaN, as it does in PyTorch. Where
mathematics gives an answer, ExactRef gives it even when PyTorch differs:
when the real or imaginary part of a complex alpha is 0, ExactRef leaves
that part's product with y out, so it cannot turn an infinity into NaN.
# A shorthand: the values as a complex128 array
def c128(values):
return er.asarray(values, "complex128")
# The imaginary part is inf * 0 + 0 * 1, and inf * 0 is NaN
print("(inf+0j) * (1+0j):",
er.multiply(c128([complex("inf")]), c128([1 + 0j])).rounded.tolist())
# Each part is its own sum: inf + 1 and 1 + 1
print("(inf+1j) + (1+1j):",
er.add(c128([complex("inf+1j")]), c128([1 + 1j])).rounded.tolist())
# alpha=0 gives the term 0 * inf, which is NaN
one, inf = er.asarray([1.0], "float32"), er.asarray([float("inf")], "float32")
print("1 + 0 * inf:", er.add(one, inf, alpha=0).rounded.tolist())
# alpha's real part is 0, so the term 0 * inf is left out
print("(1+1j) + 1j * (inf+1j):",
er.add(c128([1 + 1j]), c128([complex("inf+1j")]), alpha=1j).rounded.tolist())
(inf+0j) * (1+0j): [(inf+nanj)]
(inf+1j) + (1+1j): [(inf+2j)]
1 + 0 * inf: [nan]
(1+1j) + 1j * (inf+1j): [infj]
PyTorch gives nan+infj for the last one, because it multiplies alpha * y
out in complex arithmetic. For the same reason a zero part can differ in
sign, even with the default alpha 1: (-0+1j) + (-0-1j) has the real part
-0 in ExactRef and +0 in PyTorch.
Checking PyTorch#
To check an implementation, pass its output to covers(). Here it checks
PyTorch's residual add from the first example, and the gate of a SwiGLU MLP,
which multiplies two projections of Llama's MLP width 11008, in bfloat16:
# Could a correct implementation produce PyTorch's residual add? covers()
# answers per element, and all() asks whether every element is covered.
print("add covered:", r.covers(h + attn_out).all())
# The SwiGLU gate and up projection of 128 tokens
gate = torch.nn.functional.silu(torch.randn(128, 11008, generator=g)).bfloat16()
up = torch.randn(128, 11008, generator=g).bfloat16()
print("multiply covered:", er.multiply(gate, up).covers(gate * up).all())
add covered: True
multiply covered: True
PyTorch's CPU kernels round a scalar operand and alpha first, so check them
with the algorithms of alpha and scalar operands
above. In float16 and complex32, and in bfloat16 on an ARM CPU, with an
alpha other than 1, PyTorch may also store alpha * y in the tensor's
dtype before adding x, which add_held_scalar does not model. Write that
way of computing as the
chain er.add(x, er.multiply(y, a, dtype=...)), with a the rounded
alpha, and use any_of to accept both.
PyTorch equivalents
has the details and an example.
subtract#
er.subtract(x, y, *, alpha=1), also er.arithmetic.basic.subtract,
computes x - alpha * y. It is er.add(x, y, alpha=-alpha) under its own
name, so this page's rules for add hold for it: the tolerance, the signs of
zero, mixed formats, and integers. LayerNorm starts by subtracting each
token's mean from its activations. Here it is in float32 for 1024 tokens of
hidden size 768, the full context of GPT-2 small:
# The activations of 1024 tokens, and each token's mean, a column of 1024 values
xs = torch.randn(1024, 768, generator=g)
mu = xs.mean(dim=-1, keepdim=True)
# Each token's mean is subtracted from all 768 of its channels
cs = er.subtract(xs, mu)
print("subtract covered:", cs.covers(xs - mu).all())
subtract covered: True
PyTorch computes sub as add with alpha negated, so its CPU kernels
round a scalar operand and alpha as add's do. Check them with
add_held_scalar and the negated alpha. Here is the SGD step from
alpha and scalar operands, written as a
subtraction:
# PyTorch's SGD step as p - 0.001 * grad
sub_step = torch.sub(p, grad, alpha=0.001)
# add with alpha -0.001, held in float32 as PyTorch's sub holds it
held = er.arithmetic.basic.add_held_scalar("operand")
print("covered with alpha held in float32:", held.covers(sub_step, p, grad, alpha=-0.001).all())
covered with alpha held in float32: True
PyTorch's rsub(x, y, alpha=a) computes y - a * x, which is
er.subtract(y, x, alpha=a). er.subtract.backward(x, y, grad, alpha=)
returns grad_x = grad and grad_y = -conj(alpha) * grad, each summed over
its operand's broadcast copies, as in Backward.
Backward#
er.add.backward(x, y, grad, alpha=) returns grad_x = grad and
grad_y = conj(alpha) * grad; er.multiply.backward(x, y, grad) returns
grad_x = grad * conj(y) and grad_y = grad * conj(x). Each is summed over
its operand's broadcast copies and rounded once. They are named outputs of
one result, and gb["grad_x"] reads one as a result of its own.
A per-channel weight is broadcast to every token, so its gradient adds up
grad * x over the tokens. Here the gradients check PyTorch's autograd for
the RMSNorm weight of a float32 layer of hidden size 1024:
# Normalized activations of 128 tokens, the weight, and the gradient of the output
xn = torch.randn(128, 1024, generator=g)
wn = 1 + torch.randn(1024, generator=g) / 8
gy = torch.randn(128, 1024, generator=g)
# PyTorch's autograd, on copies that record gradients
xn_, wn_ = xn.clone().requires_grad_(), wn.clone().requires_grad_()
(xn_ * wn_).backward(gy)
# ExactRef's gradients, held by name
gb = er.multiply.backward(xn, wn, gy)
print("outputs:", list(gb.rounded))
print("grad_x covered:", gb["grad_x"].covers(xn_.grad).all())
# grad_y sums grad * x over the 128 tokens: one sum per channel
print("grad_y covered:", gb["grad_y"].covers(wn_.grad).all())
outputs: ['grad_x', 'grad_y']
grad_x covered: True
grad_y covered: True
In bfloat16, PyTorch rounds each product grad * x to bfloat16 before
adding up the copies, an extra rounding the tolerance does not allow for.
Check it as a chain: the products, rounded and
stored, then their sum. Passing the products' result to er.sum makes its
bounds cover every value the kernel may have stored.
# The same layer in bfloat16
xb, wb, gyb = xn.bfloat16(), wn.bfloat16(), gy.bfloat16()
xb_, wb_ = xb.clone().requires_grad_(), wb.clone().requires_grad_()
(xb_ * wb_).backward(gyb)
# The backward's own grad_y, and the chain: grad * x stored in bfloat16, then summed
own = er.multiply.backward(xb, wb, gyb)["grad_y"]
print("backward covered:", own.covers(wb_.grad).all())
chain = er.sum(er.multiply(gyb, xb), axis=0)
print("chain covered:", chain.covers(wb_.grad).all())
backward covered: False
chain covered: True
A scalar operand gets no gradient, so the result then holds only the other operand's gradient, still by name. The gradient of the scaled queries from above is one example:
# The gradient of the scaled queries, for one head
gq = torch.randn(1, 1, 512, 128, generator=g)
# The scalar operand 1/sqrt(128) gets no gradient, so the outputs hold grad_x alone
scaled_back = er.multiply.backward(q[:, :1], 128 ** -0.5, gq)
print("outputs:", list(scaled_back.rounded))
outputs: ['grad_x']
Signs of zero in gradients#
When a gradient element is exactly zero, its sign follows PyTorch. If broadcasting made only one copy of the operand's element, and the operand has as many dimensions as the output, the gradient element is a single product, and an exact zero takes that product's IEEE sign. Every other gradient element is a sum. That includes every element of an operand with fewer dimensions than the output, because PyTorch sums its gradient over the dimensions broadcasting added in front. An exact zero sum is +0, or -0 when rounding toward -inf, because PyTorch's sums start from +0.
One case can differ from PyTorch. In add's backward with a complex alpha
other than 1, ExactRef applies alpha by the same rule as in the forward
(see Special values above), while PyTorch multiplies the
gradient by conj(alpha) in complex arithmetic. A zero real or imaginary
part of the gradient can then differ in sign. gemm's grad_C with a
complex beta other than 1 is the same case.
Full specification#
er.add#
- add(x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Elementwise
x + alpha * ywith broadcasting (NumPy rules).Each output element is the exact value rounded once to
dtype(default: the operands' promoted format, with operands of shape () as inmultiply);dtypemust be of the inputs' kind; convert across kinds withasarray(x, d)first.alphais taken exactly as given, like a scalar operand.tolerance()budgetsalpha * yrounded in the compute format, the sum rounded in it, and the final rounding; withalpha1 or -1 only the sum is rounded, its terms taken exactly, a scalar operand the compute format does not hold included (a compute format narrower than the array operands' rounds every term first). An implementation that storesalpha * yin a narrower format first is the chainadd(x, multiply(y, alpha, dtype=...));any_ofcovers both when either may run. An implementation that rounds a scalar operand andalphato a format first isadd_held_scalar. Integer results wrap on overflow unlessoverflowsays otherwise. An exact zero takes the sign IEEE arithmetic givesx + alpha * y, as in PyTorch:-0.0 + -0.0is -0, and a cancellation is +0 (-0 when rounding toward -inf). In a complex sum, a zero part ofalpha(the imaginary part of 1, say) adds no term, by the rule below, where PyTorch multipliesalpha * yout:(-0+1j) + (-0-1j)has the real part -0, PyTorch's +0. A complex non-finite part reaches only the parts it is added to, as in PyTorch:(inf + 1j) + (1 + 1j)isinf + 2j. A complexalphafollows the same rule, which is the mathematical answer:add(1+1j, inf+1j, alpha=1j)isinfj, where PyTorch, multiplyingalpha * yin complex arithmetic, givesnan+infj.xandymay also be earlier results.
er.multiply#
- multiply(x, y, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Elementwise product with broadcasting (NumPy rules).
Each output element is the exact product rounded once to
dtype(default: the operands' promoted format: the one that holds both, else the narrowest standard format that does, as PyTorch promotes);dtypemust be of the inputs' kind; convert across kinds withasarray(x, d)first. As in PyTorch, an operand of shape () takes part in the promotion only when both are of shape (). A scalar operand (int, float, complex, aFractionwith a power-of-two denominator, aFloatValueorComplexValue, or an array of shape () of any format beside one with dimensions) is taken by its value and does not change the format.tolerance()budgets the product's rounding in the compute format and the final rounding; a complex product's parts are two-term sums, budgeted as inmatmul. An implementation that rounds a scalar operand to a format first ismultiply_held_scalar. Integer results wrap on overflow unlessoverflowsays otherwise. A complex product with a non-finite part follows IEEE rules in each part, as PyTorch's does:(inf + 0j) * (1 + 0j)isinf + nanj. An exact zero takes the sign IEEE arithmetic gives the product (-0.0 * 1is -0), as in PyTorch.xandymay also be earlier results, asResultdescribes.
er.subtract#
- subtract(x, y, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Elementwise
x - alpha * ywith broadcasting (NumPy rules).It is
add(x, y, alpha=-alpha)under its own name (a proxy): each output element is the exact value rounded once, and the tolerance, the normal answer, the zero signs, the integer overflow, and the results-as-inputs rules areadd's. Withalpha1 only the difference is rounded. PyTorch'srsubis this call with the operands swapped.
er.add.backward#
- backward(x, y, grad, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradients of
add(x, y, alpha=alpha)for the output gradientgrad.grad_x = gradandgrad_y = conj(alpha) * grad, each summed over the copies that broadcasting made of its operand, in that operand's shape and dtype; each is one product, so every element is one exact sum rounded once. An element with one copy, of an operand with the output's number of dimensions, is a single product, so an exact zero takes that product's IEEE sign. Any other element is a sum, as in PyTorch, which also sums the dimensions broadcasting adds in front: its exact zero is +0 (-0 when rounding toward -inf). A zero part of a complexconj(alpha)adds no term, as inadd, where PyTorch multipliesgradbyconj(alpha)in complex arithmetic unlessalphais 1: withalpha=2, a gradient1-0jgivesgrad_y2-0j, PyTorch's2+0j. A scalar operand gets no gradient.gradmust have the output's shape.
er.multiply.backward#
- backward(x, y, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradients of
multiply(x, y)for the output gradientgrad.grad_x = grad * conj(y)andgrad_y = grad * conj(x), each summed over the copies that broadcasting made of its operand, in that operand's shape and dtype. Each is one product (the copies are folded into its sum), so every element is one exact sum rounded once. A scalar operand gets no gradient. Where an operand is broadcast, PyTorch rounds each product to the dtype before summing the copies, an extra rounding the default tolerance does not budget. An element with one copy, of an operand with the output's number of dimensions, is a single product, so an exact zero takes that product's IEEE sign, as in PyTorch. Any other element is a sum, as in PyTorch, which also sums the dimensions broadcasting adds in front: its exact zero is +0 (-0 when rounding toward -inf).gradmust have the output's shape.
er.subtract.backward#
- backward(x, y, grad, *, alpha=1, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradients of
subtract(x, y, alpha=alpha)for the output gradientgrad.grad_x = gradandgrad_y = -conj(alpha) * grad, each summed over the copies that broadcasting made of its operand, in that operand's shape and dtype:add's backward withalphanegated. A scalar operand gets no gradient.gradmust have the output's shape.
See also#
sum, whose tolerance follows the same rules.
The proofs: add.md, multiply.md, and subtract.md.