CompressedGemma commited on
Commit
e422a7f
·
verified ·
1 Parent(s): 74aeb5c

Delete embed_hessian.py

Browse files
Files changed (1) hide show
  1. embed_hessian.py +0 -143
embed_hessian.py DELETED
@@ -1,143 +0,0 @@
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()