#!/usr/bin/env python3 """ quant_probe.py — which bits of a bf16 weight actually carry the answer? The forward is memory-bound (bench_wave.py: 38% of time is weight fetch + bf16->f32 decode), so reading fewer bytes is the right thing to attack. This measures what each candidate encoding costs in accuracy AND what it saves in bytes, on real Llama-3.2-3B weights driven by real activations. Two things this is careful about: * MASKING IS NOT COMPRESSION. Zeroing bits inside a 16-bit word still reads 16 bits. Every scheme here reports the width it would actually be STORED at, because that is the only number that changes the bottleneck. * bf16 is [sign|8 exp|7 mantissa]. The per-column dynamic range of these weights is 13-16x WITHIN a single matrix, and that range lives in the exponent. Dropping exponent bits and dropping mantissa bits are not the same operation and must not be reported as one "bit count". python3 quant_probe.py """ import json, os, sys import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from bqsm_llama import Safetensors, BASE BASE_CFG = json.load(open(os.path.join(BASE, "config.json"))) EPS = BASE_CFG["rms_norm_eps"] def f32_to_bf16_bits(W): """f32 -> the uint16 bf16 pattern it came from (weights are bf16 on disk).""" return (W.view(np.uint32) >> 16).astype(np.uint16) def bits_to_f32(b): return (b.astype(np.uint32) << 16).view(np.float32) def mask_bits(W, keep_mask): """Zero every bf16 bit not in keep_mask. Accuracy probe only -- this does NOT make the tensor smaller, which is exactly the point.""" b = f32_to_bf16_bits(W) return bits_to_f32(b & np.uint16(keep_mask)) def trunc_mantissa(W, keep): """Keep the sign, all 8 exponent bits, and `keep` mantissa bits. Round-to-nearest-even rather than truncate: truncation biases every weight toward zero and that bias accumulates over 3072 accumulations.""" b = f32_to_bf16_bits(W).astype(np.uint32) drop = 7 - keep if drop <= 0: return bits_to_f32(b.astype(np.uint16)) half = (1 << (drop - 1)) lsb = (b >> drop) & 1 b = (b + half - 1 + lsb) >> drop << drop return bits_to_f32(np.clip(b, 0, 0xFFFF).astype(np.uint16)) def int_percol(W, bits): """Symmetric int-N with a PER-OUTPUT-COLUMN scale. This is the encoding the ternary .bqsm should have used: it keeps the 13-16x within-matrix range that a single global scale destroys.""" n = (1 << (bits - 1)) - 1 s = np.abs(W).max(axis=1, keepdims=True) / n s[s == 0] = 1.0 q = np.clip(np.rint(W / s), -n, n) return (q * s).astype(np.float32) def int_global(W, bits): """Same, but ONE scale for the whole matrix -- the failure mode already measured on the ternary model.""" n = (1 << (bits - 1)) - 1 s = np.abs(W).max() / n q = np.clip(np.rint(W / s), -n, n) return (q * s).astype(np.float32) def sparsify(W, frac): """Zero the smallest `frac` of weights by magnitude (unstructured).""" if frac <= 0: return W k = int(frac * W.size) thr = np.partition(np.abs(W).ravel(), k)[k] return np.where(np.abs(W) >= thr, W, 0.0).astype(np.float32) def main(): st = Safetensors(BASE) pre = "model." emb = st.get(pre + "embed_tokens.weight") ids = [128000, 791, 6864, 315, 9822, 374] X = emb[ids].astype(np.float32) # real activations into the biggest matrix in the model L = 13 p = f"{pre}layers.{L}." wn = st.get(p + "post_attention_layernorm.weight") Xn = X / np.sqrt((X * X).mean(-1, keepdims=True) + EPS) * wn W = st.get(p + "mlp.gate_proj.weight") ref = Xn @ W.T nrm = np.linalg.norm(ref) def score(Wq, stored_bits, note): got = Xn @ Wq.T rel = float(np.linalg.norm(got - ref) / nrm) cor = float(np.corrcoef(got.ravel(), ref.ravel())[0, 1]) gb = W.size * stored_bits / 8 / 1e9 * 28 * 7 / 7 # whole-model estimate return rel, cor, stored_bits, note rows = [] rows.append(("bf16 (baseline)",) + score(W, 16, "as shipped")) # --- the literal proposal, both readings of "1st,2nd,4th,6th bit" --- msb = (1 << 15) | (1 << 14) | (1 << 12) | (1 << 10) # sign, exp7, exp5, exp3 lsb = (1 << 0) | (1 << 1) | (1 << 3) | (1 << 5) # low mantissa only rows.append(("bits 1,2,4,6 from MSB",) + score(mask_bits(W, msb), 16, "sign+exp7+exp5+exp3 -- MASKED, still 16b on disk")) rows.append(("bits 1,2,4,6 from LSB",) + score(mask_bits(W, lsb), 16, "mantissa dregs, no sign/exponent")) # --- mantissa truncation: keep sign + full exponent --- for k in (6, 5, 4, 3, 2, 1, 0): rows.append((f"sign+exp+{k} mantissa bits",) + score(trunc_mantissa(W, k), 9 + k, "packs to a real width")) # --- integer with per-column scale (what ternary should have been) --- for b in (8, 6, 4, 3, 2): rows.append((f"int{b} + per-column scale",) + score(int_percol(W, b), b, "scale is 1 f32 per row, ~0.03% overhead")) rows.append(("int2 + ONE global scale",) + score(int_global(W, 2), 2, "the .bqsm failure mode")) # --- sparsity is a different axis --- for f in (0.30, 0.50, 0.70): rows.append((f"bf16, {int(f*100)}% weights zeroed",) + score(sparsify(W, f), 16, "unstructured: no speedup without a sparse kernel")) print(f"Llama-3.2-3B layer {L} mlp.gate_proj {W.shape} real activations, 6 tokens") print(f"per-column RMS range in THIS matrix: " f"{np.sqrt((W**2).mean(1)).min():.5f} - {np.sqrt((W**2).mean(1)).max():.5f} " f"({np.sqrt((W**2).mean(1)).max()/np.sqrt((W**2).mean(1)).min():.1f}x)\n") print(f" {'encoding':<30}{'stored':>8}{'model':>9}{'rel-err':>11}{'corr':>10} note") print(" " + "-" * 104) for name, rel, cor, sb, note in rows: gb = 5.6 * sb / 16 flag = " <-- fits in RAM" if gb < 6.5 and sb < 16 else "" print(f" {name:<30}{sb:>6}b{gb:>8.1f}G{rel:>11.2e}{cor:>10.6f} {note}{flag}") print(""" READING THIS "stored" is the width the weight would actually occupy ON DISK. Masking bits inside a 16-bit word leaves it 16 bits, so those rows save nothing at all -- they are here to show what the bits are worth, not to propose an encoding. The model is 5.6 GB on a 7 GB machine, so it cannot stay in page cache and every token re-reads it. Any encoding that gets the model comfortably under RAM removes the thrashing, which is worth more than the bandwidth saving itself: the clean benchmark was 29 s/token but the real runs took 66-79 s.""") if __name__ == "__main__": main()