eyad-silx commited on
Commit
f559eae
·
verified ·
1 Parent(s): 95aa2b3

push artifacts/scripts/identity_check.py

Browse files
Files changed (1) hide show
  1. artifacts/scripts/identity_check.py +97 -0
artifacts/scripts/identity_check.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Identity round-trip sanity v2 (chunked): rebuild PQ2_0 scales from the king's own
2
+ weights (codes unchanged) along the correct block axis; write back as a challenger."""
3
+ import hashlib
4
+ import shutil
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ sys.path.insert(0, "/root/ingot/src")
9
+ import numpy as np
10
+
11
+ from common.gguf import read_header
12
+ from common.gguf.types import PQ2_0
13
+
14
+ KING = Path("/root/models/king-ix/Ingot-IX-27B-Q2.gguf")
15
+ OUT_DIR = Path("/root/models/chal-identity")
16
+ OUT = OUT_DIR / KING.name
17
+ CHUNK = 1 << 20 # blocks per chunk
18
+
19
+ g = read_header(KING)
20
+ pq = [(name, t) for name, t in g.tensors.items() if t.ggml_type == PQ2_0]
21
+ print(f"PQ2_0 tensors: {len(pq)}")
22
+
23
+
24
+ def codes_d(blocks):
25
+ d = blocks[:, :2].copy().view("<f2").astype(np.float32).reshape(-1)
26
+ qs = blocks[:, 2:]
27
+ codes = np.stack([(qs >> (2 * k)) & 3 for k in range(4)], axis=-1).reshape(-1, 128).astype(np.float32) - 1.0
28
+ return codes, d
29
+
30
+
31
+ def refit_scales(blocks):
32
+ codes, d = codes_d(blocks)
33
+ den = (codes * codes).sum(1)
34
+ num = (codes * codes * d[:, None]).sum(1)
35
+ return np.where(den > 0, num / np.maximum(den, 1e-9), d)
36
+
37
+
38
+ # ---- Part A: axis diagnostic on small PQ2_0 tensors ----
39
+ print("=== AXIS DIAGNOSTIC ===")
40
+ shown = 0
41
+ for name, t in pq:
42
+ n_blocks = int(np.prod(t.shape)) // 128
43
+ if n_blocks > 200_000:
44
+ continue
45
+ b = np.asarray(np.memmap(KING, np.uint8, "r", g.data_start + t.offset, (n_blocks * 34,)).reshape(-1, 34))
46
+ d_orig = b[:, :2].copy().view("<f2").astype(np.float32).reshape(-1)
47
+ d_ok = refit_scales(b).astype(np.float16).astype(np.float32)
48
+ err = np.abs(d_ok - d_orig)
49
+ scale = max(np.abs(d_orig).max(), 1e-9)
50
+ # v1's wrong axis on a square grid, for the failure record
51
+ side = int(round(np.sqrt(n_blocks)))
52
+ bad = None
53
+ if side * side == n_blocks:
54
+ codes, _ = codes_d(b)
55
+ dT = d_orig.reshape(side, side).T.reshape(-1)
56
+ den = (codes * codes).sum(1)
57
+ num = (codes * codes * dT[:, None]).sum(1)
58
+ d_bad = np.where(den > 0, num / np.maximum(den, 1e-9), dT).astype(np.float16).astype(np.float32)
59
+ bad = (np.abs(d_bad - d_orig).max() / scale)
60
+ print(f" {name[:46]:<46} blocks={n_blocks:>8} maxerr={err.max()/scale:.2e} bits_flipped={(d_ok.astype('<f2').view(np.uint16) != d_orig.astype('<f2').view(np.uint16)).sum()}"
61
+ + (f" v1-axis maxerr={bad:.2e}" if bad is not None else ""))
62
+ shown += 1
63
+ if shown >= 8:
64
+ break
65
+
66
+ # ---- Part B: write identity challenger ----
67
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
68
+ shutil.copy(KING, OUT)
69
+ patched = changed = 0
70
+ with open(OUT, "r+b") as fh:
71
+ for name, t in pq:
72
+ n_blocks = int(np.prod(t.shape)) // 128
73
+ raw = np.memmap(OUT, np.uint8, "r+", g.data_start + t.offset, (n_blocks * 34,))
74
+ for s in range(0, n_blocks, CHUNK):
75
+ e = min(s + CHUNK, n_blocks)
76
+ b = np.asarray(raw[s * 34:e * 34]).reshape(-1, 34)
77
+ d_new = refit_scales(b).astype(np.float16).astype("<f2").view(np.uint8).reshape(-1, 2)
78
+ changed += int((d_new != b[:, :2]).sum() // 2)
79
+ b[:, :2] = d_new
80
+ patched += 1
81
+ if patched % 100 == 0:
82
+ print(f" patched {patched}/{len(pq)}", flush=True)
83
+
84
+ print(f"\npatched {patched} tensors; scales differing from original: {changed}")
85
+
86
+
87
+ def h(p):
88
+ m = hashlib.sha256()
89
+ with open(p, "rb") as f:
90
+ for c in iter(lambda: f.read(1 << 24), b""):
91
+ m.update(c)
92
+ return m.hexdigest()[:16]
93
+
94
+
95
+ print(f"king sha256 {h(KING)}")
96
+ print(f"identity sha256 {h(OUT)}")
97
+ print("WROTE", OUT)