emerging.systems / bqsm_assist /bitwidth_sweep.py
compunerd's picture
Port full dashboard engine: phoenix_dashboard + agent_core + hyper_vocab_memory + bqsm_assist
bdf5f4a verified
Raw History Blame Contribute Delete
4.26 kB
#!/usr/bin/env python3
"""
bitwidth_sweep.py — what is the lowest bit-width that survives per-column
rescaling, measured against the real weights with NO engine in the loop.
The bundled ternary model scored at chance, but that was measured during the
`theta +=` era, when the engine could not compute the target function with
perfect weights either. Two broken variables, no attribution. This isolates the
weight question: quantize a real matrix, reconstruct it, compare to the original
and to its own output on a real input. Nothing here runs a forward pass, so no
engine can contaminate it.
INPUT real bf16 matrices from the working Llama-3.2-3B
REFERENCE the unquantized matrix, and its exact product W@x
METRIC rel Frobenius error; and rel error + cosine of W_q@x vs W@x
CONTROL the same bit-width with ONE GLOBAL scale instead of per-column
"""
import gc, sys, os
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from bqsm_llama import Safetensors, BASE
RNG = np.random.default_rng(0)
def q_symmetric(W, bits, percol):
"""Round-to-nearest symmetric quantiser. levels = 2^(bits-1)-1 each side."""
lv = (1 << (bits - 1)) - 1
amax = np.abs(W).max(1, keepdims=True) if percol else np.abs(W).max()
s = np.maximum(amax, 1e-30) / lv
return np.clip(np.round(W / s), -lv, lv) * s
def q_ternary(W, percol):
"""{-1,0,+1} with a scale. Threshold and scale follow TWN: zero anything
below 0.7*mean|w|, set the scale to the mean magnitude of what survives."""
A = np.abs(W)
if percol:
thr = 0.7 * A.mean(1, keepdims=True)
m = A > thr
cnt = np.maximum(m.sum(1, keepdims=True), 1)
alpha = (A * m).sum(1, keepdims=True) / cnt
else:
thr = 0.7 * A.mean()
m = A > thr
alpha = (A * m).sum() / max(m.sum(), 1)
return np.sign(W) * m * alpha, float(1.0 - m.mean())
def rel(a, b):
return float(np.linalg.norm(a - b) / (np.linalg.norm(b) + 1e-30))
def cos(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30))
def main():
st = Safetensors(BASE)
targets = [(0, "self_attn.q_proj"), (0, "mlp.gate_proj"),
(13, "mlp.gate_proj"), (13, "mlp.down_proj"),
(27, "mlp.gate_proj"), (27, "self_attn.o_proj")]
FMT = [("ternary per-col", None, True), ("ternary GLOBAL ", None, False),
("int2 per-col", 2, True), ("int2 GLOBAL ", 2, False),
("int4 per-col", 4, True),
("int8 per-col", 8, True), ("int8 GLOBAL ", 8, False)]
agg = {f[0]: [] for f in FMT}
for L, nm in targets:
W = st.get(f"model.layers.{L}.{nm}.weight").astype(np.float32)
nout, nin = W.shape
x = RNG.standard_normal(nin).astype(np.float32)
y = W @ x
print(f"\n L{L} {nm} [{nout}x{nin}] "
f"col-RMS spread {np.sqrt((W**2).mean(1)).max()/np.sqrt((W**2).mean(1)).min():.1f}x")
print(f" {'format':<20}{'W rel err':>11}{'y rel err':>11}{'y cosine':>12}{'zeros':>8}")
for label, bits, pc in FMT:
if bits is None:
Wq, z = q_ternary(W, pc)
else:
Wq, z = q_symmetric(W, bits, pc), 0.0
yq = Wq @ x
we, ye, yc = rel(Wq, W), rel(yq, y), cos(yq, y)
agg[label].append((we, ye, yc))
print(f" {label:<20}{we:>11.4f}{ye:>11.4f}{yc:>12.6f}"
f"{(f'{100*z:.0f}%' if bits is None else '-'):>8}")
del Wq, yq
del W, y, x
gc.collect()
print(f"\n\n {'='*62}\n MEAN ACROSS ALL {len(targets)} MATRICES\n {'='*62}")
print(f" {'format':<20}{'W rel err':>11}{'y rel err':>11}{'y cosine':>12}")
for label, _, _ in FMT:
a = np.array(agg[label])
print(f" {label:<20}{a[:,0].mean():>11.4f}{a[:,1].mean():>11.4f}{a[:,2].mean():>12.6f}")
print(f"\n bytes for 2.82B layer params:")
for nm, bpp in (("bf16", 2.0), ("int8", 1.0), ("int4", 0.5),
("ternary 2-bit", 0.25), ("ternary 5/byte", 0.2)):
print(f" {nm:<16}{2.818572288*bpp:6.2f} GB"
f"{' FITS in RAM' if 2.818572288*bpp < 3.0 else ''}")
if __name__ == "__main__":
main()