CompressedGemma commited on
Commit
07b7227
·
verified ·
1 Parent(s): c3e59d2

Another 15% or so

Browse files
Files changed (2) hide show
  1. dump_tensor.py +97 -0
  2. embed_hessian.py +143 -0
dump_tensor.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Dump one tensor from a source GGUF (F16/BF16/F32) as raw little-endian
3
+ float32, for feeding to ./bound.
4
+
5
+ Usage:
6
+ python3 dump_tensor.py model-f16.gguf blk.2.attn_output.weight out.f32
7
+ python3 dump_tensor.py model-f16.gguf --list
8
+ """
9
+ import struct, sys, os
10
+ import numpy as np
11
+
12
+ # Reuse the parsing helpers from the requantizer so the layout stays in sync.
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+ from hexstate_requantize import (
15
+ GGUF_MAGIC, GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16,
16
+ TYPE_BLOCK_SIZE, TYPE_BLOCK_BYTES,
17
+ read_string, read_kv_value, align_offset, bf16_to_f32, f16_to_f32,
18
+ )
19
+
20
+
21
+ def load(path):
22
+ with open(path, 'rb') as f:
23
+ assert struct.unpack('<I', f.read(4))[0] == GGUF_MAGIC, "bad GGUF magic"
24
+ struct.unpack('<I', f.read(4))[0] # version
25
+ n_tensors = struct.unpack('<Q', f.read(8))[0]
26
+ n_kv = struct.unpack('<Q', f.read(8))[0]
27
+ for _ in range(n_kv):
28
+ read_string(f)
29
+ read_kv_value(f, struct.unpack('<I', f.read(4))[0])
30
+
31
+ infos = []
32
+ for _ in range(n_tensors):
33
+ name = read_string(f)
34
+ n_dims = struct.unpack('<I', f.read(4))[0]
35
+ dims = [struct.unpack('<Q', f.read(8))[0] for _ in range(n_dims)]
36
+ ttype = struct.unpack('<I', f.read(4))[0]
37
+ offset = struct.unpack('<Q', f.read(8))[0]
38
+ n_el = 1
39
+ for d in dims:
40
+ n_el *= d
41
+ bs = TYPE_BLOCK_SIZE.get(ttype, 1)
42
+ bb = TYPE_BLOCK_BYTES.get(ttype, 4)
43
+ infos.append({'name': name, 'dims': dims, 'type': ttype,
44
+ 'offset': offset, 'n_elements': n_el,
45
+ 'data_size': ((n_el + bs - 1) // bs) * bb})
46
+ return infos, align_offset(f.tell())
47
+
48
+
49
+ def main():
50
+ if len(sys.argv) < 3:
51
+ print(__doc__)
52
+ sys.exit(1)
53
+ gguf = sys.argv[1]
54
+ infos, data_start = load(gguf)
55
+
56
+ if sys.argv[2] == '--list':
57
+ for ti in infos:
58
+ print(f" {ti['name']:<50s} type={ti['type']:<3d} "
59
+ f"dims={ti['dims']} n={ti['n_elements']:,}")
60
+ return
61
+
62
+ want = sys.argv[2]
63
+ out = sys.argv[3] if len(sys.argv) > 3 else 'tensor.f32'
64
+ ti = next((t for t in infos if t['name'] == want), None)
65
+ if ti is None:
66
+ print(f"no tensor named {want!r}; run with --list")
67
+ sys.exit(1)
68
+
69
+ with open(gguf, 'rb') as f:
70
+ f.seek(data_start + ti['offset'])
71
+ raw = f.read(ti['data_size'])
72
+
73
+ if ti['type'] == GGML_TYPE_F32:
74
+ a = np.frombuffer(raw, dtype=np.float32).copy()
75
+ elif ti['type'] == GGML_TYPE_F16:
76
+ a = f16_to_f32(raw, ti['n_elements'])
77
+ elif ti['type'] == GGML_TYPE_BF16:
78
+ a = bf16_to_f32(raw, ti['n_elements'])
79
+ else:
80
+ print(f"tensor is type {ti['type']} (already quantized) — "
81
+ f"dump from the F16/BF16 source GGUF instead")
82
+ sys.exit(1)
83
+
84
+ a = np.ascontiguousarray(a[:ti['n_elements']], dtype=np.float32)
85
+ a.tofile(out)
86
+ sigma = float(np.sqrt(np.mean(a.astype(np.float64) ** 2)))
87
+ v = a.astype(np.float64) ** 2
88
+ kurt = float(np.mean(v * v) / (np.mean(v) ** 2)) if np.mean(v) > 0 else 3.0
89
+ print(f" wrote {out}: {a.size:,} elements, dims={ti['dims']}")
90
+ print(f" sigma = {sigma:.6e}")
91
+ print(f" kurtosis = {kurt:.2f} (gaussian = 3)")
92
+ print()
93
+ print(f" next: ./bound --file {out}")
94
+
95
+
96
+ if __name__ == '__main__':
97
+ main()
embed_hessian.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a REAL full Hessian for layer-0 attention straight from a GGUF.
3
+ No calibration data, no forward pass, no transformers.
4
+
5
+ WHY THIS WORKS
6
+ The input to blk.0's attention projections is RMSNorm(token_embd[t]) for
7
+ whatever token t is at that position. So the input distribution is just
8
+ the (normalised) rows of the embedding matrix, weighted by token
9
+ frequency. Both are already in the GGUF. Assuming a uniform token prior:
10
+
11
+ H0 = (1/V) * sum_t xt xt^T , xt = RMSNorm(token_embd[t]) * gamma
12
+
13
+ where gamma is blk.0.attn_norm.weight if present. That is an exact
14
+ Hessian for that layer, not an approximation of one -- and with V ~ 128k
15
+ rows against n_in ~ 2-6k it is ~20-50x oversampled, far past the 2x rank
16
+ floor where estimated Hessians start being useful.
17
+
18
+ SCOPE
19
+ Only blk.0.attn_q / attn_k / attn_v share this input space. Every other
20
+ tensor in the model takes input from a preceding layer's output, which
21
+ cannot be derived from weights alone. So this covers 3 tensors -- enough
22
+ to test whether the full-H path delivers over the diag-H path before
23
+ building a real calibration pipeline for the rest.
24
+
25
+ USAGE
26
+ python3 embed_hessian.py model-f16.gguf h0.hxh
27
+ python3 hexstate_requantize.py in.gguf out.gguf --hessian h0.hxh \\
28
+ --imatrix imat.gguf --analog-imatrix
29
+
30
+ (Keep --analog-imatrix so the other 795 tensors still get diag-H;
31
+ --hessian entries take priority where they exist.)
32
+ """
33
+ import sys, os
34
+ import numpy as np
35
+
36
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
37
+ from hexstate_requantize import (
38
+ write_hessian, QK_K, GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16,
39
+ f16_to_f32, bf16_to_f32,
40
+ )
41
+ from dump_tensor import load
42
+
43
+ DAMP = 0.01
44
+ EPS = 1e-5 # RMSNorm epsilon; llama-family default
45
+
46
+
47
+ def fetch(path, infos, data_start, name):
48
+ ti = next((t for t in infos if t['name'] == name), None)
49
+ if ti is None:
50
+ return None, None
51
+ with open(path, 'rb') as f:
52
+ f.seek(data_start + ti['offset'])
53
+ raw = f.read(ti['data_size'])
54
+ if ti['type'] == GGML_TYPE_F32:
55
+ a = np.frombuffer(raw, dtype=np.float32).copy()
56
+ elif ti['type'] == GGML_TYPE_F16:
57
+ a = f16_to_f32(raw, ti['n_elements'])
58
+ elif ti['type'] == GGML_TYPE_BF16:
59
+ a = bf16_to_f32(raw, ti['n_elements'])
60
+ else:
61
+ raise SystemExit(f"{name}: type {ti['type']} is quantized; "
62
+ f"use the F16/BF16 source GGUF")
63
+ return a[:ti['n_elements']], ti['dims']
64
+
65
+
66
+ def main():
67
+ if len(sys.argv) < 3:
68
+ print(__doc__)
69
+ sys.exit(1)
70
+ gguf, out = sys.argv[1], sys.argv[2]
71
+ infos, data_start = load(gguf)
72
+
73
+ emb, dims = fetch(gguf, infos, data_start, 'token_embd.weight')
74
+ if emb is None:
75
+ raise SystemExit("no token_embd.weight in that GGUF")
76
+ n_in = dims[0] # ne0 = embedding dim = attention n_in
77
+ vocab = emb.size // n_in
78
+ print(f" token_embd.weight: dims={dims} -> n_in={n_in}, vocab={vocab}")
79
+
80
+ if n_in % QK_K:
81
+ raise SystemExit(f"n_in={n_in} is not a multiple of {QK_K}; "
82
+ f"the analog path cannot use it")
83
+
84
+ E = emb.reshape(vocab, n_in).astype(np.float64)
85
+
86
+ # RMSNorm each embedding row, exactly as the model does before attention
87
+ rms = np.sqrt((E * E).mean(axis=1, keepdims=True) + EPS)
88
+ X = E / rms
89
+
90
+ gamma, _ = fetch(gguf, infos, data_start, 'blk.0.attn_norm.weight')
91
+ if gamma is not None and gamma.size == n_in:
92
+ X *= gamma.astype(np.float64)[None, :]
93
+ print(" applied blk.0.attn_norm.weight")
94
+ else:
95
+ print(" WARNING: blk.0.attn_norm.weight not found; H is unscaled")
96
+
97
+ # H = X^T X / vocab, accumulated in chunks to bound peak memory
98
+ H = np.zeros((n_in, n_in), dtype=np.float64)
99
+ step = max(1, 2 ** 24 // n_in)
100
+ for i in range(0, vocab, step):
101
+ blk = X[i:i + step]
102
+ H += blk.T @ blk
103
+ print(f"\r {min(i + step, vocab)}/{vocab} rows", end='', flush=True)
104
+ print()
105
+ H /= float(vocab)
106
+ H[np.diag_indices_from(H)] += DAMP * np.trace(H) / n_in
107
+
108
+ ratio = vocab / n_in
109
+ print(f" oversampling: {ratio:.1f}x n_in "
110
+ f"({'ample' if ratio >= 2 else 'BELOW the 2x floor'})")
111
+ if ratio < 2:
112
+ raise SystemExit(" vocab < 2*n_in -- this H would be rank-poor. Stop.")
113
+
114
+ H32 = H.astype(np.float32)
115
+ entries = {}
116
+ for kind in ('attn_q', 'attn_k', 'attn_v'):
117
+ name = f'blk.0.{kind}.weight'
118
+ ti = next((t for t in infos if t['name'] == name), None)
119
+ if ti is None:
120
+ print(f" skip {name}: not in this GGUF")
121
+ continue
122
+ if ti['dims'][0] != n_in:
123
+ print(f" skip {name}: dims[0]={ti['dims'][0]} != {n_in}")
124
+ continue
125
+ entries[name] = H32
126
+ print(f" {name}: full H, n_in={n_in}")
127
+
128
+ if not entries:
129
+ raise SystemExit(" no eligible layer-0 attention tensors found")
130
+
131
+ write_hessian(out, entries)
132
+ print(f"\n wrote {out}: {len(entries)} tensors, "
133
+ f"{n_in * n_in * 4 / 2**20:.1f} MiB")
134
+ print(f"\n run: python3 hexstate_requantize.py in.gguf out.gguf \\")
135
+ print(f" --hessian {out} --imatrix imat.gguf --analog-imatrix")
136
+ print(f"\n then compare the three blk.0.attn_q/k/v tensors against your")
137
+ print(f" diag-H run. Those three take full-H; everything else is diag-H,")
138
+ print(f" so a whole-model perplexity delta will be small -- the signal is")
139
+ print(f" in whether those tensors improve, not the aggregate.")
140
+
141
+
142
+ if __name__ == '__main__':
143
+ main()