patrickbdevaney commited on
Commit
dcb22e0
·
verified ·
1 Parent(s): 8ba2bc0

research: quant-drift harness, NVFP4 MTP capture/gate, and the MTP capture negative result

Browse files
Files changed (1) hide show
  1. research/nvfp4_mtp_gate.py +171 -0
research/nvfp4_mtp_gate.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gate 2: how often would the UN-fine-tuned MTP head be accepted against the NVFP4 target?
2
+
3
+ The fine-tune is the fallback, not the default. GLM-5.3 ships a trained MTP module as layer 45,
4
+ and against the IQ3_M GGUF it was already accepted 46.5% of the time at depth 2 and 58.5% at
5
+ depth 3 with no training at all. NVFP4 is a higher-fidelity quantisation than IQ3_M in both the
6
+ weights and the states, so the head may well need little or nothing done to it - and a capture
7
+ plus fine-tune is days of GPU that should not be spent before that is checked.
8
+
9
+ It is checkable offline. Under greedy verification a drafted token is accepted exactly when it
10
+ equals the target's own argmax, and both sides are computable from the captured hidden states:
11
+
12
+ target's next token at position t = argmax(lm_head(h_t))
13
+ head's proposal for that position = argmax(lm_head(shared_head_norm(MTP(x_t, h_{t-1}))))
14
+
15
+ so acceptance is the rate at which those agree. No server, no speculative loop, no KV rollback.
16
+
17
+ The (x_t, h_{t-1}) pairing is the one the working llama.cpp path uses: the head is fed the newest
18
+ token together with the hidden state that PRECEDED it, and predicts the token after. Getting that
19
+ off by one would silently measure something else, so it is stated here rather than implied.
20
+
21
+ Layer 45 is built from the NVFP4 checkpoint at bf16. That is deliberate: quantising the head as
22
+ well would confound "is this head good enough" with "does this head survive 4-bit", and only the
23
+ first question is being asked here.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse, sys
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+ import torch
32
+
33
+ ROOT = Path(__file__).resolve().parent.parent
34
+ sys.path.insert(0, str(ROOT / "scripts"))
35
+
36
+ DEFAULT_CKPT = ROOT / "output" / "glm-5.3-flash-reap50-nvfp4-pass2"
37
+ MTP_LAYER = 45
38
+
39
+
40
+ def main() -> None:
41
+ ap = argparse.ArgumentParser(description=__doc__,
42
+ formatter_class=argparse.RawDescriptionHelpFormatter)
43
+ ap.add_argument("--ckpt", default=str(DEFAULT_CKPT))
44
+ ap.add_argument("--states", default=str(ROOT / "artifacts" / "qt_nvfp4.bin"))
45
+ ap.add_argument("--max-seqs", type=int, default=0)
46
+ a = ap.parse_args()
47
+
48
+ from common import log
49
+ from transformers import AutoConfig
50
+ import stream_saliency as SS
51
+ from stages.s03_saliency import _build_layer
52
+
53
+ ckpt = Path(a.ckpt)
54
+ cfg = AutoConfig.from_pretrained(ckpt)
55
+ tcfg = cfg.text_config
56
+
57
+ # transformers has no entry for layer 45: every per-layer table has exactly
58
+ # num_hidden_layers entries, because the reference implementation drops the MTP block on load.
59
+ # Layer 45's own tensors say it is structurally the same as the DSA layers - kv_a_proj_with_mqa
60
+ # + kv_b_proj, its own 7 indexer tensors, a sparse MoE, and no hc_* at all - and layer 43 is
61
+ # the last of those. So extend every such table by copying index 43 rather than naming the
62
+ # values one at a time; three tables need it today (layer_types, mlp_layer_types,
63
+ # indexer_types) and this does not have to be revisited if a fourth appears.
64
+ n_layer = tcfg.num_hidden_layers
65
+ template = n_layer - 2 # layer 43, the last deepseek_sparse_attention
66
+ for k, v in list(vars(tcfg).items()):
67
+ if isinstance(v, (list, tuple)) and len(v) == n_layer:
68
+ setattr(tcfg, k, list(v) + [v[template]])
69
+ log(f"extended cfg.{k} for the MTP layer with {v[template]!r}", "mtp_gate")
70
+
71
+ reader = SS.ShardReader(ckpt)
72
+ dev, dt = "cuda", torch.bfloat16
73
+
74
+ # The hyper-connection parameters WILL be reported missing: the template layer has them and
75
+ # layer 45 does not, because the MTP block is a plain pre-norm residual block. Nothing below
76
+ # calls the decoder layer's own forward, only its sub-modules, so those stay unused.
77
+ layer = _build_layer(tcfg, MTP_LAYER, reader, dt)
78
+
79
+ p = f"model.language_model.layers.{MTP_LAYER}."
80
+ def w(name):
81
+ return reader.get(p + name).to(dev, dt)
82
+ enorm_w, hnorm_w = w("enorm.weight"), w("hnorm.weight")
83
+ eh_proj_w = w("eh_proj.weight")
84
+ head_norm_w = w("shared_head.norm.weight")
85
+
86
+ embed_w = reader.get("model.language_model.embed_tokens.weight").to(dev, dt)
87
+ lm_head_w = reader.get("lm_head.weight").to(dev, dt)
88
+ eps = getattr(tcfg, "rms_norm_eps", 1e-6)
89
+
90
+ def rms(x, weight):
91
+ v = x.float()
92
+ v = v * torch.rsqrt(v.pow(2).mean(-1, keepdim=True) + eps)
93
+ return (v * weight.float()).to(dt)
94
+
95
+ states = Path(a.states)
96
+ H = tcfg.hidden_size
97
+ hs_all = np.fromfile(states, dtype=np.float16).reshape(-1, H)
98
+ ids_all = np.fromfile(str(states) + ".ids", dtype=np.int32)
99
+ lens = np.fromfile(str(states) + ".lens", dtype=np.int32)
100
+ if a.max_seqs:
101
+ lens = lens[: a.max_seqs]
102
+ log(f"gate2 on {len(lens)} sequences / {int(lens.sum())} tokens", "mtp_gate")
103
+
104
+ off = 0
105
+ n_tok = n_acc = n_true = 0
106
+ per_seq = []
107
+ with torch.no_grad():
108
+ for si, L in enumerate(lens):
109
+ L = int(L)
110
+ h = torch.from_numpy(hs_all[off:off + L].copy()).to(dev, dt) # [L, H] post-norm
111
+ ids = torch.from_numpy(ids_all[off:off + L].copy().astype(np.int64)).to(dev)
112
+ off += L
113
+ if L < 3:
114
+ continue
115
+
116
+ # What the target itself would emit next at each position.
117
+ tgt_next = (h @ lm_head_w.T).argmax(-1) # [L]
118
+
119
+ # The head sees (x_t, h_{t-1}) for t = 1..L-1 and predicts x_{t+1}.
120
+ e = rms(embed_w[ids[1:]], enorm_w) # [L-1, H]
121
+ hh = rms(h[:-1], hnorm_w) # [L-1, H]
122
+ x = (torch.cat([e, hh], dim=-1) @ eh_proj_w.T).unsqueeze(0) # [1, L-1, H]
123
+
124
+ # This is the LOCAL BOOLEAN PADDING mask of shape [B, S], not a causal mask - the
125
+ # module builds its own attention mask internally from the DSA indexer's top-k
126
+ # selection (build_attention_mask_from_topk). Handing it a 4D additive causal mask
127
+ # instead fails inside the indexer, where it is concatenated onto the key states.
128
+ S = x.shape[1]
129
+ mask = torch.ones(1, S, dtype=torch.bool, device=dev)
130
+
131
+ r = x
132
+ y = layer.self_attn(layer.input_layernorm(x), attention_mask=mask)
133
+ y = y[0] if isinstance(y, tuple) else y
134
+ x = r + y
135
+ r = x
136
+ x = r + layer.mlp(layer.post_attention_layernorm(x))
137
+
138
+ out = rms(x[0], head_norm_w)
139
+ draft_next = (out @ lm_head_w.T).argmax(-1) # [L-1]
140
+
141
+ # Position t of the head lines up with position t+1 of the target: both are a
142
+ # prediction of the token at t+2 in the original sequence... stated concretely,
143
+ # head row j was built from (x_{j+1}, h_j) so it predicts x_{j+2}, and the target's
144
+ # prediction of x_{j+2} is tgt_next[j+1].
145
+ acc = (draft_next[:-1] == tgt_next[1:-1]).sum().item()
146
+ tru = (draft_next[:-1] == ids[2:]).sum().item()
147
+ m = draft_next[:-1].numel()
148
+ n_acc += acc; n_true += tru; n_tok += m
149
+ per_seq.append(acc / max(m, 1))
150
+ del h, ids, e, hh, x, out, mask
151
+
152
+ if not n_tok:
153
+ sys.exit("no positions scored")
154
+ ps = np.asarray(per_seq)
155
+ print()
156
+ print(f"positions scored {n_tok}")
157
+ print(f"ACCEPTANCE (vs target argmax) {100*n_acc/n_tok:.2f}% "
158
+ f"per-seq p50 {100*np.percentile(ps,50):.1f}% p10 {100*np.percentile(ps,10):.1f}%")
159
+ print(f"top-1 vs ground truth {100*n_true/n_tok:.2f}%")
160
+ print()
161
+ # Depth-k acceptance compounds: a chain of k drafted tokens survives only if every one of them
162
+ # is accepted, so this is the optimistic reading of what depth buys, not a measurement of it.
163
+ t = n_acc / n_tok
164
+ print("if independent, expected accepted-per-iteration at depth k:")
165
+ for k in (1, 2, 3, 4):
166
+ exp = sum(t**j for j in range(1, k + 1))
167
+ print(f" depth {k}: {exp:.2f} drafted tokens accepted + 1 free = {1+exp:.2f} tokens")
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()