emerging.systems / bqsm_assist /reference_ffn.py
compunerd's picture
Port full dashboard engine: phoenix_dashboard + agent_core + hyper_vocab_memory + bqsm_assist
bdf5f4a verified
Raw History Blame Contribute Delete
5.27 kB
#!/usr/bin/env python3
"""
reference_ffn.py — ground truth from the REAL bf16 weights.
Establishes the reference that every mapping claim must be diffed against.
Computes one Gemma 4 FFN block exactly, from the 23.8 GB bf16 GGUF:
xn = RMSNorm(x) * (1 + w_ffn_norm)
g = W_gate @ xn
u = W_up @ xn
h = gelu_tanh(g) * u
out = W_down @ h
then recomputes it with the ONLY substitution the BQSM mapping makes —
the saturated-oscillator gate in place of gelu_tanh — and reports the
difference. Same weights, same input, one term swapped. If the mapping is
real the outputs match; the residual says exactly where it doesn't.
python3 reference_ffn.py --layer 0
"""
import argparse, math, os, sys
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from gestate_gguf import parse_header, GGML_BF16, GGML_F16, GGML_F32
GGUF = ("/home/compunerd/.cache/huggingface/hub/"
"models--huihui-ai--Huihui-gemma-4-12B-it-qat-q4_0-unquantized-abliterated-GGUF/"
"snapshots/2c26f29ecd20b540e66d1f62b5121fb8d251b50b/"
"Huihui-gemma-4-12B-it-qat-q4_0-unquantized-abliterated-bf16.gguf")
ESZ = {GGML_BF16: 2, GGML_F16: 2, GGML_F32: 4}
def tensor(mm, data_start, t, rows=None):
"""Decode a tensor (optionally a row slice) to float32 without copying 23 GB."""
in_dim = int(t['dims'][0])
out_dim = int(t['dims'][1]) if len(t['dims']) > 1 else 1
z = ESZ[t['type']]
r0, r1 = (0, out_dim) if rows is None else rows
off = data_start + t['offset'] + r0 * in_dim * z
raw = np.asarray(mm[off: off + (r1 - r0) * in_dim * z])
if t['type'] == GGML_BF16:
v = ((raw.view(np.uint16).astype(np.uint32) << 16)).view(np.float32)
elif t['type'] == GGML_F16:
v = raw.view(np.float16).astype(np.float32)
else:
v = raw.view(np.float32)
return v.reshape(r1 - r0, in_dim) if len(t['dims']) > 1 else v
def gelu_tanh(x):
return 0.5 * x * (1.0 + np.tanh(0.7978845608 * (x + 0.044715 * x ** 3)))
def wave_gate(x, a, b):
"""The BQSM substitution: driven-oscillator amplitude response."""
z = a * (x - b)
return 0.5 * (z / np.sqrt(1.0 + z * z) + 1.0) * x
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--file", default=GGUF)
ap.add_argument("--layer", type=int, default=0)
ap.add_argument("--a", type=float, default=1.20)
ap.add_argument("--b", type=float, default=-0.25)
ap.add_argument("--fit", action="store_true", help="grid-fit a,b on this layer")
args = ap.parse_args()
f, ver, meta, tensors, data_start = parse_header(args.file)
f.close()
mm = np.memmap(args.file, dtype=np.uint8, mode='r')
by = {t['name']: t for t in tensors}
L = args.layer
need = [f"blk.{L}.ffn_gate.weight", f"blk.{L}.ffn_up.weight",
f"blk.{L}.ffn_down.weight", f"blk.{L}.ffn_norm.weight"]
for n in need:
if n not in by:
print("missing tensor:", n); return
D = int(meta.get("gemma4.embedding_length", 3840))
F = int(meta.get("gemma4.feed_forward_length", 15360))
print(f"layer {L} D={D} F={F} (real bf16 weights)")
w_norm = tensor(mm, data_start, by[need[3]])
Wg = tensor(mm, data_start, by[need[0]]) # [F, D]
Wu = tensor(mm, data_start, by[need[1]]) # [F, D]
Wd = tensor(mm, data_start, by[need[2]]) # [D, F]
print(f" loaded gate{Wg.shape} up{Wu.shape} down{Wd.shape} norm{w_norm.shape}")
rng = np.random.default_rng(0)
x = rng.standard_normal(D).astype(np.float32)
# ── exact Gemma FFN ──
xn = x / np.sqrt((x * x).mean() + 1e-6) * (1.0 + w_norm)
g = Wg @ xn
u = Wu @ xn
h_true = gelu_tanh(g) * u
out_true = Wd @ h_true
def run(a, b):
h = wave_gate(g, a, b) * u
return Wd @ h, h
if args.fit:
best = (None, None, -2)
for a in np.arange(0.4, 3.01, 0.1):
for b in np.arange(-1.0, 1.01, 0.05):
_, h = run(a, b)
c = np.corrcoef(h, h_true)[0, 1]
if c > best[2]:
best = (a, b, c)
args.a, args.b = float(best[0]), float(best[1])
print(f" fitted on this layer: a={args.a:.2f} b={args.b:.2f} (h-corr {best[2]:.6f})")
out_wave, h_wave = run(args.a, args.b)
def rel(p, q):
return float(np.linalg.norm(p - q) / (np.linalg.norm(q) + 1e-12))
print(f"\n substitution: gelu_tanh -> wave_gate(a={args.a:.2f}, b={args.b:.2f})")
print(f" hidden h corr {np.corrcoef(h_wave, h_true)[0,1]:.6f} rel-err {rel(h_wave,h_true):.6f}")
print(f" FFN out corr {np.corrcoef(out_wave, out_true)[0,1]:.6f} rel-err {rel(out_wave,out_true):.6f}")
print(f" out ||true||={np.linalg.norm(out_true):.4f} ||wave||={np.linalg.norm(out_wave):.4f}")
# reference points: how big is that error in context?
zero = np.zeros_like(out_true)
print(f"\n for scale:")
print(f" identity (h=g*u, no activation) rel-err {rel(Wd @ (g*u), out_true):.6f}")
print(f" relu instead of gelu rel-err {rel(Wd @ (np.maximum(g,0)*u), out_true):.6f}")
print(f" zero output rel-err {rel(zero, out_true):.6f}")
if __name__ == "__main__":
main()