File size: 6,784 Bytes
688186a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python
"""Requantize Inkling-2-Mini routed experts to the native NVFP4 format using ModelOpt's NVFP4QTensor.

Native NVFP4 (layers 0-19, per expert e):
    W = e2m1(nibble) * e4m3(weight_scale[e, n, k//16]) * weight_amax[e] / outer_scale_denominator
    weight U8 [E, N, K/2] (low nibble = even k), weight_scale F8_E4M3 [E, N, K/16],
    weight_amax F32 [E], outer_scale_denominator F32 [1] (= 2688 = 6*448, ModelOpt's convention).
Native MXFP8 (layers 20-23): W = fp8(weight) * 2**(u8(weight_scale[e, n, k//32]) - 127).

w13 rows are interleaved (gate0, up0, ...) in the checkpoint. Quantization blocks run along K and the
global scale is per expert, so row order does not matter and is kept as-is.

Modes:
  --check-native L ...   re-quantize native NVFP4 layers and compare with the shipped bytes (sanity test)
  --layers L ... --out F requantize MXFP8 layers to NVFP4 and write the tensors to F (safetensors)
"""
import argparse
import json
import os

import torch
from safetensors import safe_open
from safetensors.torch import save_file
from modelopt.torch.quantization.qtensor import NVFP4QTensor

DENOM = 6.0 * 448.0
E2M1 = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6])
PROJS = ("w13", "w2")


def open_ckpt(d):
    idx = json.load(open(os.path.join(d, "model.safetensors.index.json")))["weight_map"]
    handles = {}

    def get(name):
        f = idx[name]
        if f not in handles:
            handles[f] = safe_open(os.path.join(d, f), framework="pt", device="cpu")
        return handles[f].get_tensor(name)

    return idx, get


def unpack_e2m1(packed):
    lo = (packed & 0xF).long()
    hi = (packed >> 4).long()
    lut = E2M1.to(packed.device)
    out = torch.stack([lut[lo], lut[hi]], dim=-1)  # even k = low nibble
    return out.flatten(-2)


def dequant_nvfp4(w, scale, amax, denom):
    vals = unpack_e2m1(w)  # [E, N, K]
    E, N, K = vals.shape
    s = scale.float().repeat_interleave(16, dim=-1)
    return vals * s * (amax.float() / denom.float()).view(E, 1, 1)


def dequant_mxfp8(w, scale):
    s = torch.exp2(scale.float() - 127.0).repeat_interleave(32, dim=-1)
    return w.float() * s


def quant_expert(W, method):
    """W: [N, K] fp32 for one expert. Returns packed U8 [N, K/2], scale F8 [N, K/16], amax scalar."""
    amax = W.abs().max().float()
    ws2 = amax / DENOM
    if method == "max":
        q, scale, _ = NVFP4QTensor.quantize(W, 16, weights_scaling_factor_2=ws2)
        return q._quantized_data, scale, amax
    # mse: per-block search over shrunken block amax, scored by reconstruction error
    N, K = W.shape
    blocks = W.view(N, K // 16, 16)
    bamax = blocks.abs().amax(-1)
    best_err = torch.full_like(bamax, float("inf"))
    best_scale = None
    for c in torch.linspace(0.70, 1.0, 16):
        s = (bamax * c / (6.0 * ws2)).clamp(2**-9, 448).to(torch.float8_e4m3fn)
        q, _, _ = NVFP4QTensor.quantize(W, 16, weights_scaling_factor=s, weights_scaling_factor_2=ws2)
        deq = unpack_e2m1(q._quantized_data).view(N, K // 16, 16) * (s.float() * ws2).unsqueeze(-1)
        err = (deq - blocks).pow(2).sum(-1)
        better = err < best_err
        best_err = torch.where(better, err, best_err)
        best_scale = s if best_scale is None else torch.where(better, s.float(), best_scale.float()).to(torch.float8_e4m3fn)
    q, _, _ = NVFP4QTensor.quantize(W, 16, weights_scaling_factor=best_scale, weights_scaling_factor_2=ws2)
    return q._quantized_data, best_scale, amax


def quant_layer(Wfull, method):
    """Wfull: [E, N, K] fp32 -> dict of native tensors (without name prefix)."""
    packs, scales, amaxes = [], [], []
    for e in range(Wfull.shape[0]):
        p, s, a = quant_expert(Wfull[e].contiguous(), method)
        packs.append(p), scales.append(s), amaxes.append(a)
    w = torch.stack(packs)
    s = torch.stack(scales)
    a = torch.stack(amaxes).float()
    deq = dequant_nvfp4(w, s, a, torch.tensor([DENOM], device=w.device))
    return {"weight": w.cpu(), "weight_scale": s.cpu(), "weight_amax": a.cpu(),
            "weight_outer_scale_denominator": torch.tensor([DENOM])}, deq


def rel_err(a, b):
    return ((a - b).pow(2).sum() / b.pow(2).sum()).sqrt().item()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", required=True)
    ap.add_argument("--check-native", type=int, nargs="*", default=[])
    ap.add_argument("--layers", type=int, nargs="*", default=[])
    ap.add_argument("--method", choices=["max", "mse"], default="max")
    ap.add_argument("--out")
    ap.add_argument("--report")
    args = ap.parse_args()
    dev = "cuda"
    _, get = open_ckpt(args.ckpt)
    report = {"method": args.method, "check_native": {}, "requant": {}}

    for L in args.check_native:
        for p in PROJS:
            pre = f"model.llm.layers.{L}.mlp.experts.{p}_weight"
            w, s = get(pre).to(dev), get(pre + "_scale").to(dev)
            a, d = get(pre + "_amax").to(dev), get(pre + "_outer_scale_denominator").to(dev)
            ref = dequant_nvfp4(w, s, a, d)
            new, deq = quant_layer(ref, "max")
            r = {
                "denominator": d.item(),
                "amax_matches_max_abs": torch.allclose(a, ref.abs().amax((1, 2)), rtol=1e-6),
                "bytes_equal_frac": (new["weight"] == w.cpu()).float().mean().item(),
                "scale_equal_frac": (new["weight_scale"].view(torch.uint8) == s.cpu().view(torch.uint8)).float().mean().item(),
                "amax_equal": torch.equal(new["weight_amax"], a.cpu().float()),
                "dequant_rel_err": rel_err(deq, ref),
            }
            report["check_native"][f"{L}.{p}"] = r
            print(f"[check] L{L} {p}: {r}", flush=True)
            del ref, deq, new

    out = {}
    for L in args.layers:
        for p in PROJS:
            pre = f"model.llm.layers.{L}.mlp.experts.{p}_weight"
            w = get(pre).to(dev)
            assert w.dtype == torch.float8_e4m3fn, f"{pre} is {w.dtype}, expected MXFP8"
            ref = dequant_mxfp8(w, get(pre + "_scale").to(dev))
            new, deq = quant_layer(ref, args.method)
            r = {"rel_err_vs_mxfp8": rel_err(deq, ref), "shape": list(new["weight"].shape)}
            report["requant"][f"{L}.{p}"] = r
            print(f"[requant] L{L} {p} ({args.method}): {r}", flush=True)
            out[pre] = new["weight"]
            out[pre + "_scale"] = new["weight_scale"]
            out[pre + "_amax"] = new["weight_amax"]
            out[pre + "_outer_scale_denominator"] = new["weight_outer_scale_denominator"]
            del ref, deq
    if out:
        save_file(out, args.out)
        print("wrote", args.out)
    if args.report:
        json.dump(report, open(args.report, "w"), indent=2)


if __name__ == "__main__":
    main()