interplane.Get Omega
Read in your language

aien-architecture-mv

Canonical architecture for the AIEN ecosystem: flows, boundaries, ADRs, and the map from design to implementation repositories.

Brought by drakestapleton

branch main Branches Tags History

aien-architecture-mv / evidence / QUANTUM_EFFICIENCY / 2026-10-22 / weight_probe.py

130 lines · 6013 bytes Raw Blame History
1"""Throwaway CPU-only representation probe, NOT an inference benchmark.
2Reads three preselected real FP8 matrices over SSH; no GPU, model load, or writes
3on Spark. Results contain hashes/statistics, never model weights. Reproduce:
4OPENBLAS_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 uv run --with numpy weight_probe.py
5"""
6import base64
7import hashlib
8import json
9import pathlib
10import platform
11import shlex
12import subprocess
13import sys
14
15import numpy as np
16
17MODEL = '/home/drakestapleton/models/qwen3.6-35b-a3b-fp8-95a723d0'
18SELECTION = [(0, 0, 'gate_proj'), (20, 128, 'up_proj'), (39, 255, 'down_proj')]
19
20
21def fetch(layer, expert, proj):
22 name = f'model.language_model.layers.{layer}.mlp.experts.{expert}.{proj}'
23 code = '''import json,struct,pathlib,base64,hashlib
24p=pathlib.Path(MODEL)/('layers-'+str(LAYER)+'.safetensors')
25with p.open('rb') as f:
26 n=struct.unpack('<Q',f.read(8))[0]; hdr=json.loads(f.read(n)); out={}
27 for key in [NAME+'.weight',NAME+'.weight_scale_inv']:
28 m=hdr[key];a,b=m['data_offsets'];f.seek(8+n+a);raw=f.read(b-a)
29 assert len(raw)==b-a
30 out[key]={'meta':m,'raw':base64.b64encode(raw).decode(),'sha256':hashlib.sha256(raw).hexdigest()}
31print(json.dumps(out))
32'''
33 code = f'MODEL={MODEL!r};LAYER={layer!r};NAME={name!r}\n' + code
34 raw = subprocess.check_output(['ssh', '-o', 'BatchMode=yes', 'spark', 'python3 -c ' + shlex.quote(code)])
35 data = json.loads(raw)
36 wt = data[name + '.weight']
37 sc = data[name + '.weight_scale_inv']
38 assert wt['meta']['dtype'] == 'F8_E4M3', wt['meta']
39 codes = np.frombuffer(base64.b64decode(wt['raw']), dtype=np.uint8).reshape(wt['meta']['shape'])
40 scales_raw = base64.b64decode(sc['raw'])
41 if sc['meta']['dtype'] == 'F32':
42 scales = np.frombuffer(scales_raw, dtype='<f4').astype(np.float64)
43 elif sc['meta']['dtype'] == 'BF16':
44 scales = (np.frombuffer(scales_raw, dtype='<u2').astype(np.uint32) << 16).view(np.float32).astype(np.float64)
45 else:
46 raise ValueError(sc['meta'])
47 scales = scales.reshape(sc['meta']['shape'])
48 assert np.all(np.isfinite(scales)) and np.all(scales > 0)
49 exp = ((codes >> 3) & 15).astype(int)
50 mant = (codes & 7).astype(int)
51 assert not np.any((exp == 15) & (mant == 7)), 'NaN FP8 code'
52 val = np.where(exp == 0, mant * 2.0**-9, (1 + mant/8) * np.exp2(exp - 7))
53 val *= np.where(codes & 128, -1, 1)
54 assert scales.shape == (val.shape[0]//128, val.shape[1]//128)
55 val *= np.repeat(np.repeat(scales, 128, axis=0), 128, axis=1)
56 provenance = {k: {a: v[a] for a in ('meta', 'sha256')} for k,v in data.items()}
57 return val, provenance
58
59
60def h128(arr):
61 """Orthogonal 128-wide Sylvester Hadamard on contiguous row blocks."""
62 shape = arr.shape
63 out = arr.copy().reshape(-1, 128)
64 step = 1
65 while step < 128:
66 view = out.reshape(-1, 128//(2*step), 2*step)
67 left, right = view[..., :step].copy(), view[..., step:].copy()
68 view[..., :step] = left + right
69 view[..., step:] = left - right
70 step *= 2
71 return (out / np.sqrt(128)).reshape(shape)
72
73
74def q4(arr):
75 """Toy symmetric INT4, [-7,7], one f64 analysis scale per 128 weights.
76 This is NOT NVFP4, GPTQ, QuaRot, SpinQuant or a deployable format.
77 """
78 shape = arr.shape
79 blocks = arr.reshape(-1, 128)
80 scale = np.max(np.abs(blocks), axis=1, keepdims=True)/7
81 scale[scale == 0] = 1
82 return (np.clip(np.rint(blocks/scale), -7, 7)*scale).reshape(shape)
83
84
85def selfcheck():
86 # Independent explicit Hadamard matrix and hand-coded FP8 known values.
87 hh = np.array([[1.]])
88 for _ in range(7):
89 hh = np.block([[hh, hh], [hh, -hh]])
90 hh /= np.sqrt(128)
91 x = np.arange(256, dtype=np.float64).reshape(2,128)/17
92 assert np.allclose(h128(x), x @ hh, rtol=0, atol=1e-12)
93 assert np.allclose(h128(h128(x)), x, rtol=0, atol=1e-12)
94 assert np.array_equal(q4(np.zeros((1,128))), np.zeros((1,128)))
95 assert np.allclose(q4(np.ones((1,128))), 1)
96 assert np.linalg.matrix_rank(np.outer(np.arange(1,5), np.arange(1,7))) == 1
97 return 'PASS: independent explicit Hadamard, inverse, zero/constant quantizer, rank-one control'
98
99
100def main():
101 control = selfcheck()
102 rows = []
103 for layer, expert, proj in SELECTION:
104 ww, provenance = fetch(layer, expert, proj)
105 assert np.isfinite(ww).all()
106 ss = np.linalg.svd(ww, compute_uv=False)
107 norm = np.linalg.norm(ww)
108 ss_energy = float(np.sum(ss*ss))
109 assert np.isclose(ss_energy, norm*norm, rtol=1e-12)
110 plain = float(np.linalg.norm(q4(ww)-ww)/norm)
111 rotated = float(np.linalg.norm(h128(q4(h128(ww)))-ww)/norm)
112 n,k = ww.shape
113 row = {'layer':layer,'expert':expert,'projection':proj,'shape':[n,k],
114 'provenance':provenance,'numerical_rank_tol_maxdim_eps':int(np.sum(ss > ss[0]*max(n,k)*np.finfo(float).eps)),
115 'rank_relative_frobenius_error':{str(r):float(np.sqrt(np.sum(ss[r:]**2)/ss_energy)) for r in [64,128,204,256,409]},
116 'toy_int4_relative_frobenius_error':plain,'block_hadamard_toy_int4_relative_frobenius_error':rotated,
117 'rotation_error_ratio':rotated/plain,
118 'same_dtype_rank64_entry_ratio':64*(n+k)/(n*k),
119 'bf16_rank64_vs_fp8_dense_byte_ratio_no_metadata':2*64*(n+k)/(n*k)}
120 rows.append(row)
121 print(json.dumps(row),flush=True)
122 result = {'verdict':'PARTIAL: feasibility evidence on three selected matrices, NOT model accuracy or speed',
123 'scope':'Frozen predetermined first/middle/last layer and expert selection; not random or representative; existing FP8 checkpoint, not BF16 original. No timings collected.',
124 'model_path':MODEL,'python':sys.version,'numpy':np.__version__,'platform':platform.platform(),
125 'controls':control,'selection':SELECTION,'rows':rows}
126 pathlib.Path(__file__).with_name('weight-probe-results.json').write_text(json.dumps(result,indent=2)+'\n')
127 print(control)
128
129if __name__ == '__main__':
130 main()