#!/usr/bin/env python3 """Fit a candidate W6NL E4M3-exact codebook without loading/serving a model. Samples BF16 down-projection weight rows from safetensors in disjoint layer sets. This is a weight-distribution pilot, not held-out activation-weighted GPTQ validation. """ import argparse, json, struct, pathlib import numpy as np parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('checkpoint', type=pathlib.Path, help='original BF16 checkpoint directory') ROOT = parser.parse_args().checkpoint INDEX = json.loads((ROOT / 'model.safetensors.index.json').read_text())['weight_map'] def sample(layers, seed): rng = np.random.default_rng(seed) chunks = [] for layer in layers: name = f'model.language_model.layers.{layer}.mlp.experts.down_proj' path = ROOT / INDEX[name] with path.open('rb') as f: n = struct.unpack('> 3, b & 7 if exponent == 0: return mant * 2**-9 return (1 + mant/8) * 2**(exponent-7) def score(h, vals, scale, x): u = np.asarray(vals, dtype=np.float64)/scale i = np.searchsorted((u[1:]+u[:-1])/2, x) return float(np.sum(h*(x-u[i])**2)/h.sum()) def fit(h): x=(np.arange(len(h))+.5)/len(h) centers = np.linspace(0.01, 0.99, 32) for _ in range(2500): i=np.searchsorted((centers[1:]+centers[:-1])/2,x) counts=np.bincount(i, weights=h, minlength=32) sums=np.bincount(i, weights=h*x, minlength=32) new=np.divide(sums, counts, out=centers.copy(), where=counts>0) if np.max(np.abs(new-centers)) < 1e-9: break centers=new i=np.searchsorted((centers[1:]+centers[:-1])/2,x) counts=np.bincount(i, weights=h, minlength=32) vals=np.array([e4(b) for b in range(1,127)],dtype=np.float64) best=None for scale in np.arange(20.,80.01,.5): # Find 32 strictly increasing, exactly representable positive fp8 levels. cost=counts[:,None]*(centers[:,None]-vals[None,:]/scale)**2 dp=cost[0].copy(); parents=[] for j in range(1,32): prev=np.r_[np.inf, dp[:-1]] arg=np.minimum.accumulate(prev) inds=np.empty(len(vals),np.int32); k=-1; m=np.inf for z,p in enumerate(prev): if p= scale * .98) & (vals <= scale * 1.02),dp,np.inf) z=int(np.argmin(eligible)); chosen=[z] for parent in reversed(parents): z=int(parent[z]); chosen.append(z) chosen=chosen[::-1] if min(chosen)<0: continue table=vals[chosen] err=score(h,table,scale,x) if best is None or err