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

x, y

the operands, broadcast together; a Python scalar, or an array of shape () beside one with dimensions, is taken exactly

required

alpha (add and subtract)

the factor on y, taken exactly

1

dtype

the output format, of the same kind as the inputs

the operands' promoted format

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 residual add of a transformer block, h + attn_out, for 128 tokens of hidden size 1024 in bfloat16:

Code
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()))
Output
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:

Code
# 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())
Output
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

add, and its alpha, of float32, float16, or complex64

add_held_scalar("operand")

add, and its alpha, of bfloat16

add_held_scalar(("float32", "operand"))

add, and its alpha, of complex32

add_held_scalar(("complex64", "operand"))

mul of float16 or bfloat16, with the scalar second (x * s, or s * x with a Python scalar s)

multiply_held_scalar("compute"): float32, which it computes in

mul of float16, with the scalar first (torch.mul(s, x), or s * x with a tensor s of shape ())

multiply_held_scalar("operand")

mul of bfloat16, with the scalar first

multiply_held_scalar(("float32", "operand"))

mul of float32 or complex64

multiply_held_scalar("operand")

mul of complex32

multiply_held_scalar(("complex64", "operand"))

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:

Code
# 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())
Output
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:

Code
# 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())
Output
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:

Code
# 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())
Output
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:

Code
# 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())
Output
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")):

Code
# 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())
Output
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:

Code
# 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)
Output
-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.

Code
# 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())
Output
(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:

Code
# 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())
Output
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:

Code
# 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())
Output
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:

Code
# 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())
Output
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:

Code
# 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())
Output
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.

Code
# 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())
Output
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:

Code
# 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))
Output
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 * y with broadcasting (NumPy rules).

Each output element is the exact value rounded once to dtype (default: the operands' promoted format, with operands of shape () as in multiply); dtype must be of the inputs' kind; convert across kinds with asarray(x, d) first. alpha is taken exactly as given, like a scalar operand. tolerance() budgets alpha * y rounded in the compute format, the sum rounded in it, and the final rounding; with alpha 1 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 stores alpha * y in a narrower format first is the chain add(x, multiply(y, alpha, dtype=...)); any_of covers both when either may run. An implementation that rounds a scalar operand and alpha to a format first is add_held_scalar. Integer results wrap on overflow unless overflow says otherwise. An exact zero takes the sign IEEE arithmetic gives x + alpha * y, as in PyTorch: -0.0 + -0.0 is -0, and a cancellation is +0 (-0 when rounding toward -inf). In a complex sum, a zero part of alpha (the imaginary part of 1, say) adds no term, by the rule below, where PyTorch multiplies alpha * y out: (-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) is inf + 2j. A complex alpha follows the same rule, which is the mathematical answer: add(1+1j, inf+1j, alpha=1j) is infj, where PyTorch, multiplying alpha * y in complex arithmetic, gives nan+infj. x and y may 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); dtype must be of the inputs' kind; convert across kinds with asarray(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, a Fraction with a power-of-two denominator, a FloatValue or ComplexValue, 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 in matmul. An implementation that rounds a scalar operand to a format first is multiply_held_scalar. Integer results wrap on overflow unless overflow says otherwise. A complex product with a non-finite part follows IEEE rules in each part, as PyTorch's does: (inf + 0j) * (1 + 0j) is inf + nanj. An exact zero takes the sign IEEE arithmetic gives the product (-0.0 * 1 is -0), as in PyTorch. x and y may also be earlier results, as Result describes.

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 * y with 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 are add's. With alpha 1 only the difference is rounded. PyTorch's rsub is 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 gradient grad.

grad_x = grad and grad_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 complex conj(alpha) adds no term, as in add, where PyTorch multiplies grad by conj(alpha) in complex arithmetic unless alpha is 1: with alpha=2, a gradient 1-0j gives grad_y 2-0j, PyTorch's 2+0j. A scalar operand gets no gradient. grad must 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 gradient grad.

grad_x = grad * conj(y) and grad_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). grad must 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 gradient grad.

grad_x = grad and grad_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 with alpha negated. A scalar operand gets no gradient. grad must have the output's shape.

See also#