divide and reciprocal#

Division turns a sum into a mean, scales a model's logits by a sampling temperature, and normalizes activations by their standard deviation. er.divide(x, y) computes x / y element by element, and er.reciprocal(x) computes 1 / x. They are also er.arithmetic.basic.divide and er.arithmetic.basic.reciprocal. Operands of different shapes are broadcast as in NumPy and PyTorch, so a column of per-token values can divide every row of activations.

Each output element is the reference: the exact quotient, rounded once to the output format. To check another implementation's output, pass it to covers(), which says per element whether a correct implementation could have produced it. How far such an output can be from the reference is the tolerance, and it depends on how often a correct implementation rounds:

a real quotient x / y an exact fraction round once one rounding to check: the tolerance is usually 0 a complex quotient (a + b i) / (c + d i) by Smith's method, where |c| >= |d| R = d / c the ratio D = c + d R the divisor S = 1 / D its reciprocal (a + b R) S (b - a R) S every step rounds: up to seven roundings in each part, so the tolerance is a few ulps, and more where a part nearly cancels

The roundings behind each tolerance. Where |d| > |c|, Smith's method swaps the roles of c and d.

IEEE 754 requires division to be correctly rounded. A float32 or float64 quotient therefore rounds once, and its tolerance is 0: rounded is the only correct output. A bfloat16 or float16 quotient is computed in float32, the compute format, and rounded again to the 16-bit format. float32 has enough bits that the two roundings always give what one would, so the tolerance is 0 there too. The exception is a subnormal quotient that lies exactly halfway between two values, such as 5 * 2**-149 / 2 in float32. A correct implementation may round that tie either way, so the tolerance there is one ulp.

PyTorch and NumPy divide complex numbers by Smith's method, which takes several steps, each rounded. The tolerance allows for every one of them, with or without fused multiply-adds, so it is a few ulps for most elements. Where a part of the quotient is the small difference of two larger terms, its tolerance is far larger, because a correct implementation of Smith's method can be that far off there.

Arguments#

Argument

Meaning

Default

x, y (reciprocal: x only)

the operands, broadcast together: arrays, tensors, Python scalars, or earlier results, of one kind (integer or bool, floating-point, or complex); a Python scalar, or an array of shape () beside one with dimensions, is taken exactly

required

dtype

the output format: a floating-point format for real, integer, and bool inputs, a complex one for complex inputs

the operands' promoted format; float32 for integers and bools

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"

each format's own rule

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

Operands of different floating-point formats are promoted as in add and multiply (Mixed formats). 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#

LayerNorm divides each token's centered activations by the token's standard deviation, sqrt(var + eps). Here it is in float32 for 1024 tokens of hidden size 768, the full context of GPT-2 small:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The activations of 1024 tokens, centered on each token's mean
x = torch.randn(1024, 768, generator=g)
centered = x - x.mean(dim=-1, keepdim=True)
# Each token's standard deviation, a column of 1024 values
std = torch.sqrt(x.var(dim=-1, keepdim=True, correction=0) + 1e-5)

# ExactRef's result: each token's value divides all 768 of its channels
r = er.divide(centered, std)
print("shape:", r.rounded.shape)
# The largest tolerance of the 786,432 elements
print("largest tolerance:", max(r.tolerance().scalars()))
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(centered / std).all())
Output
shape: (1024, 768)
largest tolerance: 0.0
covered: True

The tolerance is 0, so PyTorch's output is covered only because it is the reference itself, bit for bit. The same holds in bfloat16:

Code
# The same division in bfloat16
cb, sb = centered.bfloat16(), std.bfloat16()
rb = er.divide(cb, sb)

print("largest tolerance:", max(rb.tolerance().scalars()))
print("covered:", rb.covers(cb / sb).all())
Output
largest tolerance: 0.0
covered: True

er.reciprocal(x) is er.divide(1, x), with the same reference, tolerance, and special values. A kernel that multiplies by one over the standard deviation computes it once per token:

Code
# One over each token's standard deviation
print("covered:", er.reciprocal(std).covers(torch.reciprocal(std)).all())
Output
covered: True

PyTorch's Linux ARM build is the exception in bfloat16. Its torch.reciprocal can be up to 1.18 ulps from the exact value, so er.reciprocal rejects some of its outputs: no correct rounding produces them. That kernel computes some elements with Arm's reciprocal estimate, a hardware approximation accurate to about 8 bits. The algorithm er.arithmetic.basic.reciprocal_estimate() describes that kernel and its gradient. Dividing two tensors is not affected. PyTorch equivalents has the details.

Python scalars#

Sampling divides a model's logits by a temperature, a Python float. Here are the logits of 8 sequences over Llama 3's vocabulary of 128,256 tokens, divided by 0.7:

Code
# The logits of the last position of 8 sequences
logits = torch.randn(8, 128256, generator=g) * 4
out = logits / 0.7

# divide takes the Python float 0.7 at its exact value
print("covered by divide(logits, 0.7):", er.divide(logits, 0.7).covers(out).all())
# 0.7 rounded to float32, as a tensor of shape (), which divide takes at that value
held = torch.tensor(0.7, dtype=torch.float32)
print("covered with 0.7 held in float32:", er.divide(logits, held).covers(out).all())
Output
covered by divide(logits, 0.7): False
covered with 0.7 held in float32: True

PyTorch's CPU kernels round a Python scalar to float32 before they divide a float32, bfloat16, or float16 tensor. 0.7 is not a float32 value, so they divide by a slightly different number. Pass the scalar the way they hold it, as a float32 tensor of shape (). A Python float divides a float64 tensor as it is.

PyTorch computes a Python scalar divided by a tensor, s / x, as x.reciprocal() * s. Check it with er.multiply(er.reciprocal(x), held), with held the scalar as a float32 tensor of shape (). On CUDA, a tensor divided by a Python scalar is multiplied by the scalar's rounded reciprocal instead, and PyTorch equivalents gives the call for it. torch.div with rounding_mode="floor" or "trunc" is a different operation, which ExactRef does not have.

Integers#

Dividing integer tensors gives float32, as in PyTorch. The reference is the quotient of the integers themselves. PyTorch first converts each integer to float32, which cannot hold every integer above 2**24, such as 16777217, so its answer can differ from the reference. The tolerance allows for that conversion, and normal(), the normal answer, makes it:

Code
# Counts and totals; 16777217 is 2**24 + 1, which float32 cannot hold
counts = torch.tensor([3, 16777217, 5])
totals = torch.tensor([4, 3, 16777217])

ri = er.divide(counts, totals)
print("dtype:", ri.rounded.dtype.name)
# The exact quotients of the integers, rounded once
print("rounded:", ri.rounded.tolist())
# PyTorch divides the float32 conversions
print("PyTorch:", (counts / totals).tolist())
print("covered:", ri.covers(counts / totals).all())
# What an implementation that converts first computes
print("normal():", ri.normal().tolist())
Output
dtype: float32
rounded: [0.75, 5592405.5, 2.980231954552437e-07]
PyTorch: [0.75, 5592405.5, 2.980232238769531e-07]
covered: True
normal(): [0.75, 5592405.5, 2.980232238769531e-07]

Division by zero#

A zero divisor is common in real data: an empty group's count, or a token whose activations are all equal. Special values follow IEEE arithmetic, as in PyTorch. A nonzero value over a zero is an infinity, 0 / 0 is NaN, and a finite value over an infinity is a zero. may_be() says where a correct implementation may return each:

Code
# 1 / 0, -1 / 0, 0 / 0, and 1 / inf, in float32
x = er.asarray([1.0, -1.0, 0.0, 1.0], "float32")
y = er.asarray([0.0, 0.0, 0.0, float("inf")], "float32")

rz = er.divide(x, y)
print("rounded:", rz.rounded.tolist())
print("may be +inf:", rz.may_be("+inf").tolist())
Output
rounded: [inf, -inf, nan, 0.0]
may be +inf: [True, False, False, False]

Complex values#

Frequency-domain deconvolution divides one spectrum by another. Here are the spectra of 64 signals of 4096 samples, divided by those of 64 filters, in complex64:

Code
# The spectra of the signals and of the filters
signal = torch.fft.fft(torch.randn(64, 4096, generator=g))
kernel = torch.fft.fft(torch.randn(64, 4096, generator=g))

rc = er.divide(signal, kernel)
out = signal / kernel
print("covered:", rc.covers(out).all())
# How many of PyTorch's 262,144 elements are the reference itself
same = sum(a == b for a, b in zip(rc.rounded.scalars(), out.flatten().tolist()))
print("equal to the reference:", same)
Output
covered: True
equal to the reference: 78648

Most of PyTorch's elements differ from the reference, because Smith's method rounds at every step, and every one of them is inside the tolerance.

Mathematics gives no value to a complex quotient with an infinite part or a zero divisor, so ExactRef follows PyTorch there. It applies Smith's formulas by IEEE rules to the exact values, and divides each part of x by a zero divisor's zero. PyTorch's builds disagree in one case, a zero divisor with a -0 part, where some return the infinity of the other sign. may_be() allows both there:

Code
# A shorthand: the values as a complex128 array
def c128(values):
    return er.asarray(values, "complex128")

print("(1+1j) / 0:", er.divide(c128([1 + 1j]), c128([0j])).rounded.tolist())
print("(1+1j) / (inf+0j):",
      er.divide(c128([1 + 1j]), c128([complex("inf")])).rounded.tolist())

# A divisor whose real part is -0
rn = er.divide(c128([1 + 1j]), c128([complex(-0.0, 0.0)]))
print("(1+1j) / (-0+0j):", rn.rounded.tolist())
# may_be() answers per part: element 0's real part first
print("real part may be -inf:", rn.may_be("-inf").tolist()[0][0])
Output
(1+1j) / 0: [(inf+infj)]
(1+1j) / (inf+0j): [0j]
(1+1j) / (-0+0j): [(inf+infj)]
real part may be -inf: True

Backward#

er.divide.backward(x, y, grad) returns grad_x = grad / conj(y) and grad_y = -grad * conj(x / y**2). er.reciprocal.backward(x, grad) returns grad_x = -grad / conj(x)**2. Each is summed over its operand's broadcast copies and rounded once. They are named outputs, and gb["grad_x"] reads one as a result of its own.

PyTorch computes them in steps: grad / y and -grad * ((x / y) / y), and -grad * (r * r) with r = 1 / x. The tolerance allows for each step's rounding in the compute format, then for the sum over the copies. Here the gradients check PyTorch's autograd for the LayerNorm division above:

Code
# The gradient of the normalized activations
gy = torch.randn(1024, 768, generator=g)

# PyTorch's autograd, on copies that record gradients
centered_, std_ = centered.clone().requires_grad_(), std.clone().requires_grad_()
(centered_ / std_).backward(gy)

# ExactRef's gradients, held by name
gb = er.divide.backward(centered, std, gy)
print("outputs:", list(gb.rounded))
print("grad_x covered:", gb["grad_x"].covers(centered_.grad).all())
# grad_y sums over each token's 768 channels: one sum per token
print("grad_y covered:", gb["grad_y"].covers(std_.grad).all())
Output
outputs: ['grad_x', 'grad_y']
grad_x covered: True
grad_y covered: True

Where y is zero the derivative does not exist. The gradients there are what PyTorch's formulas give by IEEE rules, an infinity or NaN:

Code
# x = 1 and grad = 1, at y = +0 and y = -0
one = er.asarray([1.0, 1.0], "float32")
zeros = er.asarray([0.0, -0.0], "float32")

zb = er.divide.backward(one, zeros, one)
print("grad_x:", zb["grad_x"].rounded.tolist())
print("grad_y:", zb["grad_y"].rounded.tolist())
Output
grad_x: [inf, -inf]
grad_y: [-inf, -inf]

A scalar operand gets no gradient, and integer inputs have none. An exact zero's sign follows the rule of add, subtract, and multiply: a gradient element with one copy keeps its term's sign, and a sum is +0.

Full specification#

er.divide#

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

x / y elementwise, with broadcasting (NumPy rules): the exact quotient rounded once.

Each output element is the exact quotient rounded once to dtype (default: the operands' promoted format, as in multiply, whose rules for scalars and for operands of shape () apply). Integer and bool operands give float32 unless dtype names another floating-point format, as PyTorch gives; the reference is the quotient of the integers themselves, and the tolerance covers an implementation that converts each to float32 first.

Special values follow IEEE 754 on the exact values: a nonzero value divided by a zero is an infinity, 0 / 0 and inf / inf are NaN, and a zero quotient has the product of the operands' signs. A complex quotient with a non-finite part or a zero divisor follows PyTorch's division (Smith's formulas by IEEE rules on exact values): (1 + 1j) / 0 is inf + infj. Where a part of a zero divisor is -0, may_be() also allows the infinity of the other sign, which some builds of PyTorch return.

tolerance() bounds an implementation that rounds the quotient once in the compute format and then to the output: with exact operands it is the exact worst case, and 0 where the compute format is the output format, except at a subnormal quotient exactly halfway between two values, which may round either way. A complex quotient's tolerance bounds Smith's method, with or without fused multiply-adds; it is large where one part of the quotient nearly cancels, where a correct implementation of that method can be that far off. x and y may also be earlier results, as Result describes. Proof: proofs/divide.md.

er.reciprocal#

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

1 / x elementwise: divide(1, x), the exact reciprocal rounded once, with divide's special values, tolerance and normal answer (proofs/reciprocal.md).

er.divide.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 divide(x, y) for the output gradient grad.

grad_x = grad / conj(y) and grad_y = -grad * conj(x / y**2), each summed over the copies that broadcasting made of its operand, in that operand's shape and dtype: every element is one exact sum of fractions, rounded once. A scalar operand gets no gradient, and integer operands have none. tolerance() bounds PyTorch's formulas computed step by step in the compute format, grad / conj(y) and -grad * conj((x / y) / y), then the sum over the copies. Where y is zero the derivative does not exist, and the values are those of these formulas by IEEE rules on exact values, as PyTorch gives: for real operands grad_x is an infinity or NaN, and grad_y an infinity of the sign of -grad * x, or NaN where x or grad is zero. An element with one copy, of an operand with the output's number of dimensions, is a single term, so an exact zero takes that term's IEEE sign. Any other element is a sum, as in PyTorch: its exact zero is +0 (-0 when rounding toward -inf). grad must have the output's shape.

er.reciprocal.backward#

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

The gradient of reciprocal(x) for the output gradient grad.

grad_x = -grad / conj(x)**2, in x's shape and dtype: each element one exact fraction, rounded once. tolerance() bounds PyTorch's formula computed step by step in the compute format, -grad * conj(r * r) with r = 1 / x. Where x is zero the value is that formula's by IEEE rules on exact values: an infinity of the sign of -grad, or NaN where grad is zero. grad must have x's shape.

See also#