GwendalTsang/quantum4 / builders /model_direct.py
GwendalTsang's picture
download
raw
1.67 kB
"""Exhaustive classical model of work/build_invsqrt2.py over all inputs."""
import numpy as np, math, sys
sys.path.insert(0, 'work')
from build_invsqrt2 import quantized_table, T, WY, WR2, WR1, WC3, N_P, WIDTH
xs_all = np.arange(1, 3133452 + 1, dtype=np.int64)
TAB = quantized_table()
def model(xs):
xs = np.asarray(xs, dtype=np.int64)
def bit(v, i): return (v >> i) & 1
s = (WIDTH - (np.floor(np.log2(xs)).astype(np.int64) + 1)) // 2
xn = xs << (2 * s)
scaled = bit(xn, 21)
idx = np.where(scaled == 1, (xn >> (21 - T)) & (2 ** T - 1),
(xn >> (20 - T)) & (2 ** T - 1))
case = scaled * (2 ** T) + idx
c0, c1, c2, c3 = TAB[case, 0], TAB[case, 1], TAB[case, 2], TAB[case, 3]
topbit = 20 - T
delta = [(scaled & bit(xn, topbit), T)] + \
[(bit(xn, topbit - 1 - k), T + 1 + k) for k in range(topbit)]
def prod(mult, Wm, Wa):
acc = np.zeros_like(xs)
for ctl, m in delta:
e = Wa - Wm - m
acc += ctl * ((mult << e) if e >= 0 else (mult >> -e))
return acc
r1 = c2 - prod(c3, WC3, WR1)
r2 = c1 - prod(r1, WR1, WR2)
y = c0 - prod(r2, WR2, WY)
for nm, v, lim in [('r1', r1, WR1), ('r2', r2, WR2), ('y', y, WY)]:
if ((v <= 0) | (v >= 2 ** lim)).any():
raise OverflowError(nm)
return y << s
if __name__ == '__main__':
y1 = model(xs_all)
approx = y1 / 2.0 ** (WY + N_P)
exact = 1 / np.sqrt(xs_all.astype(np.float64))
rel = np.abs(approx - exact) / exact
print(f"max rel error 2^{math.log2(rel.max()):.2f} at x={int(rel.argmax() + 1)} "
f"(tolerance 2^-24, ratio {rel.max() / 2**-24:.3f})")

Xet Storage Details

Size:
1.67 kB
·
Xet hash:
98b2382f420d044ad8d1095d60fe3b18cf628abcb0b8b79b3b4dbe9be2dd5021

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.