wcamon commited on
Commit
09f4f21
·
verified ·
1 Parent(s): 906d2d7

Upload decode_bitplanes.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. decode_bitplanes.py +61 -0
decode_bitplanes.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decode bitplanes_k2_c0.6.npz -> full bf16 weights (bit-exact vs model.safetensors).
2
+
3
+ The true quantized artifact of circus-0.4-t9. Each target linear layer is stored as
4
+ W = alpha ⊙ (T1 + c·T2), T1,T2 ∈ {-1,0,+1}, c = 0.6
5
+ with per-block-32 fp32 scales alpha (GPTQ column-permuted domain; `inv` restores
6
+ the original column order). Index encoding: idx = (T1+1)*3 + (T2+1) ∈ [0,8],
7
+ two 4-bit indices per byte.
8
+
9
+ Usage:
10
+ python decode_bitplanes.py # verify all layers vs model.safetensors
11
+ python decode_bitplanes.py --tensor NAME # decode one tensor, print stats
12
+ """
13
+ import argparse
14
+
15
+ import numpy as np
16
+
17
+
18
+ def decode(z, name):
19
+ packed = z[f"{name}.idx"] # (M, N//2) uint8
20
+ alpha = z[f"{name}.alpha"] # (M, nB) fp32
21
+ inv = z[f"{name}.inv"] # (N,) int32
22
+ M, nB = alpha.shape
23
+ N = nB * 32
24
+ idx = np.empty((M, N), np.uint8)
25
+ idx[:, 0::2] = packed >> 4
26
+ idx[:, 1::2] = packed & 0x0F
27
+ t1 = (idx.astype(np.float32) // 3) - 1.0
28
+ t2 = (idx % 3).astype(np.float32) - 1.0
29
+ v = (t1 + float(z["meta.c"]) * t2).reshape(M, nB, 32)
30
+ w = (alpha[:, :, None] * v).reshape(M, N)
31
+ return w[:, inv] # un-permute columns (fp32)
32
+
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--planes", default="bitplanes_k2_c0.6.npz")
37
+ ap.add_argument("--safetensors", default="model.safetensors")
38
+ ap.add_argument("--tensor", default=None)
39
+ args = ap.parse_args()
40
+ z = np.load(args.planes)
41
+ names = sorted({k.rsplit(".", 1)[0] for k in z.files if k.endswith(".idx")})
42
+ if args.tensor:
43
+ w = decode(z, args.tensor)
44
+ print(args.tensor, w.shape, "std", w.std())
45
+ return
46
+ import torch
47
+ from safetensors import safe_open
48
+ bad = 0
49
+ with safe_open(args.safetensors, framework="pt") as f:
50
+ for i, n in enumerate(names):
51
+ ref = f.get_tensor(n + ".weight")
52
+ w = torch.from_numpy(decode(z, n)).to(torch.bfloat16)
53
+ ok = torch.equal(w, ref)
54
+ bad += not ok
55
+ if not ok or i % 32 == 0:
56
+ print(f"[{i+1}/{len(names)}] {n} bit-exact={ok}")
57
+ print(f"verified {len(names)} tensors, mismatches={bad}")
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()