arashakb commited on
Commit
f7cf333
·
verified ·
1 Parent(s): be1bbb9

Add asp_nvfp4_runtime.py (NVFP4 deflated ASP)

Browse files
Files changed (1) hide show
  1. asp_nvfp4_runtime.py +195 -0
asp_nvfp4_runtime.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the deflated-ASP NVFP4 checkpoint. Real 4-bit execution on the FP4 tensor cores.
2
+
3
+ Per layer, exactly the contract the export wrote and the search scored:
4
+
5
+ x~ = (x / s) H
6
+ y = (x~ V)(W~V)^T + NVFP4GEMM( (I - VV^T) x~ , W~(I-VV^T) ) + bias
7
+
8
+ The weight never leaves E2M1: it is packed nibbles with pre-swizzled E4M3 block scales, handed
9
+ straight to `torch._scaled_mm_v2` with recipe BlockWise1x16. Nothing is dequantised to bf16 and no
10
+ fp16 GEMM runs on the bulk path -- that is what makes this real quantisation rather than a
11
+ simulation of it.
12
+
13
+ The ACTIVATION is quantised per forward: block 16, E4M3 scales, one level (SVDQuant's nvfp4 recipe
14
+ for inputs), then swizzled. The swizzle is unavoidable -- `_scaled_mm_v2` rejects row-major scales
15
+ -- and it is done in torch here rather than fused, so this path is correct first and fast later.
16
+ The rank-r branch stays in bf16 by design: it carries the directions the action depends on, which
17
+ is the whole point of protecting them.
18
+
19
+ FW_ASP_CKPT=/path/to/ur3_step7000_asp_nvfp4.pt
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ import os
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+
29
+ from nvfp4 import nvfp4_mm, quantize_nvfp4, recip_scale, swizzle_scales
30
+
31
+
32
+ def _fwht(x):
33
+ """Orthonormal fast Walsh-Hadamard transform along the last dim (size a power of 2)."""
34
+ orig = x.shape; m = orig[-1]; x = x.reshape(-1, m).clone(); h = 1
35
+ while h < m:
36
+ x = x.view(-1, m // (2 * h), 2, h); a = x[:, :, 0, :]; b = x[:, :, 1, :]
37
+ x = torch.stack([a + b, a - b], dim=2).reshape(-1, m); h *= 2
38
+ return (x / math.sqrt(m)).reshape(orig)
39
+
40
+
41
+ _HMAT_CACHE = {}
42
+
43
+
44
+ def _hadamard_matrix(B, dtype, device):
45
+ """H with x @ H == _fwht(x). Built by running _fwht on the identity, so the butterfly
46
+ ORDERING and the 1/sqrt(B) normalisation match the ones the weights were rotated with at
47
+ export. A Sylvester construction would give a different ordering, and the resulting error
48
+ would look like a quantisation regression rather than a transform mismatch."""
49
+ key = (B, dtype, str(device))
50
+ if key not in _HMAT_CACHE:
51
+ eye = torch.eye(B, device=device, dtype=torch.float32)
52
+ _HMAT_CACHE[key] = _fwht(eye).to(dtype).contiguous()
53
+ return _HMAT_CACHE[key]
54
+
55
+
56
+ _H: dict = {}
57
+
58
+
59
+ def _hmat(B, device, dtype):
60
+ k = (B, str(device), dtype)
61
+ if k not in _H:
62
+ _H[k] = _hadamard_matrix(B, dtype, device)
63
+ return _H[k]
64
+
65
+
66
+ class ASPNVFP4Linear(nn.Module):
67
+ """One exported Linear: NVFP4 deflated weight + bf16 rank-r action subspace."""
68
+
69
+ def __init__(self, e: dict, dtype, device):
70
+ super().__init__()
71
+ self.in_features = int(e["in_features"])
72
+ self.out_features = int(e["out_features"])
73
+ self.block = int(e["fwht_block"])
74
+ self.a_block = int(e["a_block"])
75
+ self.rank = int(e["asp_rank"])
76
+ self.register_buffer("wq", e["wq"].to(device))
77
+
78
+ self.register_buffer("wsc", e["wscale_swizzled"].to(device))
79
+ # The kernel wants the RECIPROCAL of the per-tensor scale, and it is a constant: built
80
+ # once here, not per forward. The transposed weight view is hoisted for the same reason.
81
+ self.register_buffer("w_rglob", recip_scale(e["wglobal"].to(device), device))
82
+ self.register_buffer("a_rglob", recip_scale(None, device).clone())
83
+ # KEPT IN FP32, NOT THE MODEL DTYPE. These are stored fp16; casting them to bf16 throws
84
+ # away three mantissa bits before a 4-bit grid ever sees them, and the grid's codes are
85
+ # ~33% apart, so those bits decide which code an element lands on. Measured: bf16 buffers
86
+ # put the layer output 2e-2 to 5e-2 from the fp32 reference; fp16 -> fp32 is exact and
87
+ # costs a few hundred MB across the model for tensors that are r=32 columns wide.
88
+ self.register_buffer("inv_smooth", e["inv_smooth"].to(device=device, dtype=torch.float32))
89
+ self.register_buffer("bias", e["bias"].to(device=device, dtype=torch.float32)
90
+ if "bias" in e else None)
91
+ # V as [in, r] for the projection, W~V as [out, r] for the epilogue
92
+ self.register_buffer("V", e["lr_a"].t().contiguous().to(device=device,
93
+ dtype=torch.float32)
94
+ if self.rank else None)
95
+ self.register_buffer("WV", e["lr_b"].to(device=device, dtype=torch.float32)
96
+ if self.rank else None)
97
+ self._wqt = self.wq.t() # transposed view, hoisted out of the forward
98
+
99
+ def forward(self, x):
100
+ # THE PROLOGUE RUNS IN FP32, deliberately. What follows it is a 4-bit grid whose codes are
101
+ # ~33% apart, so a bf16 rounding of the smoothed/rotated activation moves elements across
102
+ # code boundaries: measured on the exported layers, a bf16 prologue put the layer output
103
+ # 3.8e-2 to 9.0e-2 from the fp32 one. The search that CHOSE this layer's (alpha, beta) and
104
+ # its subspace scored an fp32 prologue, so a bf16 one would deploy a different arm than the
105
+ # one that was selected. It is also cheap: the rotation is O(d*sqrt(d)) beside an FP4 GEMM.
106
+ shp = x.shape
107
+ x2 = x.reshape(-1, shp[-1]).float()
108
+ xh = x2 * self.inv_smooth
109
+ D = xh.shape[-1]
110
+ xt = (xh.reshape(-1, D // self.block, self.block)
111
+ @ _hmat(self.block, xh.device, torch.float32)).reshape(-1, D)
112
+ if self.rank:
113
+ Vf = self.V
114
+ proj = xt @ Vf # [tok, r]
115
+ xp = xt - proj @ Vf.t() # (I - VV^T) x~
116
+ else:
117
+ proj, xp = None, xt
118
+ ak, asc, _ = quantize_nvfp4(xp, block=self.a_block, two_level=False)
119
+ y = nvfp4_mm(ak, swizzle_scales(asc), self.wq, self.wsc, self.a_rglob, self.w_rglob,
120
+ out_dtype=torch.float32, b_packed_t=self._wqt)[: xp.shape[0]]
121
+ # EVERYTHING IN FP32, THEN ONE CAST AT THE END. The epilogue and the bias are fp32
122
+ # buffers, so casting before adding them promotes the result straight back to fp32 and the
123
+ # next layer_norm fails on a dtype it did not expect. One cast, last.
124
+ if self.rank:
125
+ y = y + proj @ self.WV.t()
126
+ if self.bias is not None:
127
+ y = y + self.bias
128
+ y = y.to(x.dtype)
129
+ return y.reshape(*shp[:-1], self.out_features)
130
+
131
+ def extra_repr(self):
132
+ return (f"in={self.in_features}, out={self.out_features}, NVFP4 w{self.a_block}, "
133
+ f"rank={self.rank}, H={self.block}")
134
+
135
+
136
+ def install_asp_nvfp4(model, ckpt_path=None, verbose=True) -> int:
137
+ """Swap every exported Linear. A partial swap is not a defined arm, so it raises."""
138
+ ckpt_path = ckpt_path or os.environ.get("FW_ASP_CKPT")
139
+ blob = torch.load(str(ckpt_path), map_location="cpu", weights_only=False)
140
+ meta, layers = blob["meta"], blob["layers"]
141
+ if meta.get("lowrank_mode") != "asp_deflated":
142
+ raise RuntimeError(f"{ckpt_path}: lowrank_mode={meta.get('lowrank_mode')!r}; this runtime "
143
+ f"implements the DEFLATED ASP contract and applying it to another "
144
+ f"would give a well-formed GEMM of the wrong bilinear form.")
145
+ if verbose:
146
+ f = meta["format"]
147
+ print(f"[asp-nvfp4] {meta['scheme']}: {meta['n_layers']} Linears "
148
+ f"({meta['asp_layers']} with ASP r{meta['rank']}), {meta['bpw']} BPW", flush=True)
149
+ print(f"[asp-nvfp4] {f['element']} w{f['w_block']}/a{f['a_block']}, {f['scale']} scales, "
150
+ f"{f['weight_scale_levels']}-level weights, {f['scale_layout']}", flush=True)
151
+ named = dict(model.named_modules())
152
+ done, missing = 0, []
153
+ for name, e in layers.items():
154
+ mod = named.get(name)
155
+ if not isinstance(mod, nn.Linear):
156
+ missing.append(name)
157
+ continue
158
+ new = ASPNVFP4Linear(e, mod.weight.dtype, mod.weight.device)
159
+ parent = model.get_submodule(name.rsplit(".", 1)[0])
160
+ setattr(parent, name.rsplit(".", 1)[-1], new)
161
+ named[name] = None
162
+ del mod, new
163
+ done += 1
164
+ if missing:
165
+ raise RuntimeError(f"{ckpt_path}: {len(missing)} layers did not resolve, e.g. {missing[:3]}")
166
+ del blob, layers, named
167
+ import gc
168
+ gc.collect()
169
+ torch.cuda.empty_cache()
170
+ if verbose:
171
+ free, tot = torch.cuda.mem_get_info()
172
+ print(f"[asp-nvfp4] replaced {done} Linears | GPU {(tot-free)/2**30:.1f}/"
173
+ f"{tot/2**30:.0f} GiB", flush=True)
174
+ return done
175
+
176
+
177
+ def load_quantized_asp_model(ckpt_path, build_model, verbose=True):
178
+ """Build the model straight from the self-contained NVFP4 checkpoint.
179
+
180
+ `build_model` is your own bf16 FastWAM constructor and must return `(model, cfg)`; the
181
+ checkpoint carries every tensor the quantised model needs, so it is only used for the
182
+ module graph and the non-Linear submodules. Nothing is read from the bf16 weights.
183
+ """
184
+ blob = torch.load(str(ckpt_path), map_location="cpu", weights_only=False)
185
+ if "mot_rest" not in blob:
186
+ raise RuntimeError(f"{ckpt_path} is not self-contained")
187
+ model, cfg = build_model()
188
+ missing, unexpected = model.mot.load_state_dict(blob["mot_rest"], strict=False)
189
+ if unexpected:
190
+ raise RuntimeError(f"{len(unexpected)} unexpected mot tensors, e.g. {list(unexpected)[:3]}")
191
+ if model.proprio_encoder is not None:
192
+ model.proprio_encoder.load_state_dict(blob["proprio_encoder"], strict=True)
193
+ del blob
194
+ install_asp_nvfp4(model, ckpt_path, verbose=verbose)
195
+ return model, cfg