Riptorch’s exact results come from a few pieces of maths. This page explains them with the numbers worked out; none of it depends on how the kernels are tuned. Every result is exact by construction: it follows from the arithmetic, not from a lucky rounding.
Exact integer matmul from 8-bit digits
Matrix hardware multiplies 8-bit integers fast and exactly: each product of two int8 values is at most 128^2 = 2^{14} in size, so a sum of fewer than 2^{17} of them fits in int32 with nothing rounded. Wider integers are written in base 256, as 8-bit digits, and multiplied digit by digit.
Signed digits
A 16-bit value is written with two signed digits:
a = 256\,a_1 + a_0, \qquad a_0, a_1 \in [-128, 127]Two signed digits reach from -128 \cdot 256 - 128 = -32896 to 127 \cdot 256 + 127 = 32639. The int16 range is [-32768, 32767]: the same width, shifted by 128. So first subtract 128 from every entry, which lands every int16 value exactly in the two-digit range, and then split.
Four digit products
With A' = A - 128 and B' = B - 128 split into digit matrices, the product is four int8 matrix products, shifted and added:
A'B' = 2^{16}\,A'_1B'_1 + 2^{8}\,(A'_1B'_0 + A'_0B'_1) + A'_0B'_0Each digit product is exact in int32; the shifted sum is formed in int64.
Putting the shift back
Expanding (A' + 128)(B' + 128) gives the original product, with three cheap correction terms: the row sums of A', the column sums of B' and a constant (k is the inner dimension):
AB = A'B' + 128\,\operatorname{rowsum}(A') + 128\,\operatorname{colsum}(B') + 128^2 kThe corrections cost one pass over each matrix, nothing next to the product itself. Unsigned 8-bit inputs use the same shift with a single digit, which is how int8 @ uint8 runs on signed hardware.
Here it is on the extreme values of int16, in NumPy, checked against the exact product and Riptorch’s own int16 @ int16:
import json
import numpy as np
import riptorch as torch
A = np.array([[32767, -32768, 1000], [-1, 255, -300]], dtype=np.int64) # int16 values, 2 x 3
B = np.array([[-32768, 7], [32767, -2], [12345, 32767]], dtype=np.int64) # 3 x 2
k = A.shape[1]
def digits(M):
"""Shift into the signed two-digit range, then split: M - 128 = 256 * hi + lo, hi and lo in [-128, 127]."""
S = M - 128
lo = (S + 128) % 256 - 128
hi = (S - lo) // 256
assert lo.min() >= -128 and lo.max() <= 127 and hi.min() >= -128 and hi.max() <= 127
return S, hi, lo
SA, a1, a0 = digits(A)
SB, b1, b0 = digits(B)
print("A - 128 high digits:", a1.tolist())
print("A - 128 low digits: ", a0.tolist())
# Four int8 x int8 products; each entry is at most 3 * 128 * 128 in size: exact in int32
P = {(i, j): (x @ y) for i, x in ((1, a1), (0, a0)) for j, y in ((1, b1), (0, b0))}
SS = 65536 * P[1, 1] + 256 * (P[1, 0] + P[0, 1]) + P[0, 0] # (A - 128)(B - 128), in int64
# The shift terms put the 128s back: AB = SS + 128 rowsum(SA) + 128 colsum(SB) + 128^2 k
AB = SS + 128 * SA.sum(axis=1, keepdims=True) + 128 * SB.sum(axis=0, keepdims=True) + 128 * 128 * k
print("rebuilt from digits:", AB.tolist())
print("exact A @ B: ", (A @ B).tolist())
r = torch.tensor(A.tolist(), dtype=torch.int16) @ torch.tensor(B.tolist(), dtype=torch.int16)
print("riptorch int16 @ int16:", r.dtype, r.tolist())A - 128 high digits: [[127, -128, 3], [-1, 0, -2]] A - 128 low digits: [[127, -128, 104], [127, 127, 84]] rebuilt from digits: [[-2135073112, 33061905], [4684853, -9830617]] exact A @ B: [[-2135073112, 33061905], [4684853, -9830617]] riptorch int16 @ int16: int64 [[-2135073112, 33061905], [4684853, -9830617]]
Why it can’t overflow
Each digit product sum stays below 2^{31} for an inner dimension below 2^{17}, and the final int64 holds any int16 product with an inner dimension below 2^{33}:
|a\,b| \le 2^{30} \;\Rightarrow\; \Big|\sum_{t=1}^{k} a_t b_t\Big| \le k \cdot 2^{30} < 2^{63} \quad\text{for } k < 2^{33}Nothing passes through a floating-point number, so the result is the same integer on the CPU’s matrix unit and on the GPU.
Why exact search ranking is exact
Cosine similarity divides by two lengths, and a length is a square root: computing it in floating point rounds. Riptorch ranks by a quantity that needs only dot products. With Q(x) = x \cdot x (the quadrance: the squared length) and d = q \cdot x:
\operatorname{cross}(q, x) = \operatorname{sign}(d)\,\frac{d^2}{Q(q)\,Q(x)} = \cos\theta\,\lvert\cos\theta\rvertThe signed cross grows exactly when the cosine grows, so it ranks documents in the same order.
Comparing two documents without dividing
To decide whether x ranks above y for a query q, multiply both sides by the positive number Q(q)\,Q(x)\,Q(y):
\operatorname{cross}(q,x) > \operatorname{cross}(q,y) \iff \operatorname{sign}(d_x)\,d_x^2\,Q(y) \;>\; \operatorname{sign}(d_y)\,d_y^2\,Q(x)For int8 or int16 vectors every term is an integer, so the comparison is exact: it compares two fractions by cross-multiplying, the way you would on paper. For 1,024-dimensional int8 vectors, d^2\,Q needs up to 72 bits, so the comparison uses 128-bit integers. Ties go to the lowest index.
A worked example in two dimensions: q = (4, 1), x = (3, 2), y = (5, -1).
The cosines agree (0.942 against 0.904), but the integers decided it with no rounding at all.
Where float16 goes wrong
In float16 the cosine is rounded to 11 significant bits, so two documents whose cosines differ by less than about 0.0005 near 0.9 get the same score, and the order between them is decided by whatever breaks the tie. This run searches random int8 vectors for such a pair:
import json
from fractions import Fraction
import numpy as np
def Q(v):
return int(np.dot(v.astype(np.int64), v.astype(np.int64)))
def cross(q, x): # sign(q.x) (q.x)^2 / (Q(q) Q(x)), as an exact fraction
d = int(np.dot(q.astype(np.int64), x.astype(np.int64)))
return Fraction((1 if d >= 0 else -1) * d * d, Q(q) * Q(x))
def cos16(q, x): # float16 inputs, float32 sums, a float16 score
a, b = q.astype(np.float16).astype(np.float32), x.astype(np.float16).astype(np.float32)
return np.float16(np.dot(a, b) / np.sqrt(np.dot(a, a)) / np.sqrt(np.dot(b, b)))
rng = np.random.default_rng(11)
q = rng.integers(-128, 128, 64).astype(np.int8)
base = np.clip(q.astype(np.int32) + rng.integers(-40, 41, 64), -128, 127)
for trial in range(1000): # two documents close to q and to each other
x = np.clip(base + rng.integers(-3, 4, 64), -128, 127).astype(np.int8)
y = np.clip(base + rng.integers(-3, 4, 64), -128, 127).astype(np.int8)
if cross(q, x) != cross(q, y) and (cross(q, x) > cross(q, y)) != (cos16(q, x) > cos16(q, y)):
break
dx, dy = int(np.dot(q.astype(np.int64), x.astype(np.int64))), int(np.dot(q.astype(np.int64), y.astype(np.int64)))
print("found after", trial + 1, "pairs")
print("q.x =", dx, " Q(x) =", Q(x), " q.y =", dy, " Q(y) =", Q(y))
left, right = dx * dx * Q(y), dy * dy * Q(x)
print("compare (q.x)^2 Q(y) =", left, "with (q.y)^2 Q(x) =", right)
print("exact: ", "x ranks first" if left > right else "y ranks first")
print("float16: ", "x ranks first" if cos16(q, x) > cos16(q, y) else ("a tie" if cos16(q, x) == cos16(q, y) else "y ranks first"),
f"(scores {cos16(q, x)} and {cos16(q, y)})")
print("gap between the exact cosines:", float(abs(np.sqrt(float(cross(q, x))) - np.sqrt(float(cross(q, y))))))
th = np.linspace(0, np.pi, 61)found after 27 pairs q.x = 338983 Q(x) = 356386 q.y = 340084 Q(y) = 358820 compare (q.x)^2 Q(y) = 41231817564378980 with (q.y)^2 Q(x) = 41218580882979616 exact: x ranks first float16: a tie (scores 0.94140625 and 0.94140625) gap between the exact cosines: 0.00015110847228561042
sin, exp2 and log2 with the same bits on every device
The same model run on two GPUs usually gives slightly different numbers, and the transcendental functions are a big reason. Devices use different polynomial libraries, some have approximate hardware instructions, and a fused multiply-add (one rounding for a \cdot b + c) gives different bits from a multiply followed by an add (two roundings):
import json
import math
import numpy as np
import riptorch as torch
f32 = np.float32
a = b = f32(1 + 2 ** -12)
c = f32(-(1 + 2 ** -11))
two_roundings = f32(f32(a * b) + c) # multiply, round, add, round
one_rounding = f32(float(a) * float(b) + float(c)) # fused multiply-add: round once
print("a*b + c with two roundings:", two_roundings)
print("a*b + c fused (one rounding):", one_rounding)
# Range reduction: 2^x = 2^n * 2^r with n = round(x), |r| <= 1/2
x = 3.3
n = round(x)
r = x - n
bits = (n + 127) << 23 # 2^n written straight into the exponent field
print(f"x = {x}: n = {n}, r = {r:+.4f}, 2^n = {np.array([bits], dtype=np.uint32).view(np.float32)[0]}")
# Riptorch's float32 exp2, log2 and sin on this CPU against the correctly rounded value
xs = np.linspace(-20, 20, 20001).astype(np.float32)
for name, fn, ref, inp in [("exp2", torch.exp2, lambda v: 2.0 ** v, xs),
("log2", torch.log2, math.log2, np.abs(xs) + f32(1e-3)),
("sin", torch.sin, math.sin, xs)]:
got = fn(torch.from_numpy(inp)).numpy()
want = np.array([ref(float(v)) for v in inp]).astype(np.float32)
ulps = np.abs(got.view(np.int32).astype(np.int64) - want.view(np.int32).astype(np.int64))
print(f"{name}: {len(inp)} inputs, {np.mean(ulps == 0):.1%} correctly rounded, the rest within {ulps.max()} ulp")
# An illustrative polynomial for 2^r on [-1/2, 1/2] (Taylor, degree 5; not Riptorch's) and its error
rs = np.linspace(-0.5, 0.5, 101)
poly = sum((math.log(2) * rs) ** k / math.factorial(k) for k in range(6))a*b + c with two roundings: 0.0 a*b + c fused (one rounding): 5.9604645e-08 x = 3.3: n = 3, r = +0.3000, 2^n = 8.0 exp2: 20001 inputs, 89.3% correctly rounded, the rest within 1 ulp log2: 20001 inputs, 94.8% correctly rounded, the rest within 1 ulp sin: 20001 inputs, 96.5% correctly rounded, the rest within 1 ulp
The rule: only correctly rounded steps, in a fixed order
IEEE 754 requires float32 addition, subtraction and multiplication to be correctly rounded: the result is the exact answer rounded to the nearest float32. So every conforming device gives the same bits for the same sequence of those operations. Riptorch’s GPU programs build sin, exp2 and log2 from exactly that: float32 add, subtract and multiply in a fixed order with no fused multiply-adds, plus integer operations on a float’s bits, comparisons and selects. The result is the same bits on every GPU and on the CPU reference.
exp2: split off the integer part
2^x = 2^n \cdot 2^r, \qquad n = \operatorname{round}(x), \quad r = x - n \in [-\tfrac12, \tfrac12]2^n costs nothing: write n + 127 into the float’s exponent bits. 2^r on the short interval [-\tfrac12, \tfrac12] is a polynomial, evaluated in Horner form with one multiply and one add per step:
2^r \approx c_0 + r\,(c_1 + r\,(c_2 + r\,(c_3 + \cdots)))The chart above shows the error of a plain Taylor polynomial of degree 5 on that interval; Riptorch’s coefficients are fitted for float32, but the shape of the method is the same.
log2: read the exponent, then a polynomial
x = 2^e \cdot m, \quad m \in [1, 2) \qquad\Rightarrow\qquad \log_2 x = e + \log_2 mThe exponent e is read from the float’s bits; \log_2 m is a polynomial on a short interval.
sin: reduce by π/2 exactly
x = k\,\tfrac{\pi}{2} + r, \qquad |r| \le \tfrac{\pi}{4}The reduction is where accuracy is usually lost, because \pi/2 isn’t a float32. It is split into three float32 parts, \tfrac{\pi}{2} = P_1 + P_2 + P_3, where P_1 has few enough bits that k P_1 is exact; subtracting the parts one at a time keeps r accurate:
r = \big((x - k P_1) - k P_2\big) - k P_3Then k \bmod 4 picks \pm\sin r or \pm\cos r, each a polynomial on [-\tfrac{\pi}{4}, \tfrac{\pi}{4}].
What it buys you
A model gives the same outputs on every supported GPU and on the CPU reference, so a result can be checked on another machine bit for bit. The one exception is float32 subnormals (values below 2^{-126}), which some GPUs flush to zero in hardware.