File size: 3,900 Bytes
a7e82fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""GPU check of engine/nv4_ct.Nvfp4Linear against a plain-torch emulation (hfdi-speed-20261125, #86662).

  python bench/nv4_check.py <compressed-tensors NVFP4 dir> <BF16 dir of the same model>

Per tested projection: (1) the NVFP4 weight dequantized vs the BF16 weight (relative error; same model?), (2) our own RTN
quantization of the BF16 weight vs the checkpoint's packed codes / block scales (convention check), (3) module output vs
fake-quant(x) @ dequant(W)^T in float32 (GEMM + scale conventions), both GEMM paths, (4) vs the BF16 product (NVFP4 error).
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import torch

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "engine"))
from engine import fp4  # noqa: E402
from engine.nv4_ct import CtCheckpoint, Nvfp4Linear  # noqa: E402


def bf16_weight(bdir: Path, name: str) -> torch.Tensor:
    from safetensors import safe_open
    idx = json.loads((bdir / "model.safetensors.index.json").read_text())["weight_map"]
    if name not in idx:
        name = name.removeprefix("model.")                  # karpo-decision-31B stores language_model.* at the top level
    with safe_open(str(bdir / idx[name]), framework="pt", device="cpu") as f:
        return f.get_tensor(name)


def fake_quant(x: torch.Tensor, g: float) -> torch.Tensor:
    xf = x.float()
    M, K = xf.shape
    blk = xf.view(M, K // 16, 16)
    s = (blk.abs().amax(-1) / (6.0 * g)).clamp(max=448.0).to(torch.float8_e4m3fn).float() * g
    q = (blk / s.clamp(min=1e-30)[..., None]).clamp(-6, 6)
    codes = fp4.f32_to_e2m1_codes(q)
    vals = fp4.E2M1.to(x.device)[(codes & 7).long()] * torch.where(codes >= 8, -1.0, 1.0)
    return (vals * s[..., None]).view(M, K)


def main():
    nvd, bdir = Path(sys.argv[1]), Path(sys.argv[2])
    ct = CtCheckpoint(nvd)
    dev = torch.device("cuda")
    torch.manual_seed(0)
    out = []
    for layer, path in [(0, "self_attn.q_proj"), (0, "mlp.gate_proj"), (0, "mlp.down_proj"), (5, "self_attn.k_proj"),
                        (59, "mlp.up_proj"), (59, "self_attn.o_proj")]:
        lin = ct.linear(layer, path, dev)
        w = bf16_weight(bdir, f"model.language_model.layers.{layer}.{path}.weight").to(dev)
        dq = lin.dequant()
        rec = {"layer": layer, "path": path, "shape": list(w.shape),
               "w_rel_err": float((dq - w.float()).norm() / w.float().norm())}
        rq, rs, rg = fp4.quantize_nvfp4(w)                 # our RTN with the weight's own amax
        rec["own_rtn_codes_equal"] = float((rq.view(torch.uint8) == lin.wq.view(torch.uint8)).float().mean())
        rec["own_rtn_scales_equal"] = float((rs.view(torch.uint8) == lin.ws.view(torch.uint8)).float().mean())
        rec["global_scale_ratio"] = float(rg / lin.wg0)
        K = w.shape[1]
        g = float(lin.xg0)
        x = (torch.randn(300, K, device=dev) * (2688.0 * g / 20)).bfloat16()   # typical range: amax ~ 1/4 of the calib amax
        with torch.inference_mode():
            y = lin(x).float()
            emu = fake_quant(x, g) @ dq.t()
            lin._two = not lin._two
            y2 = lin(x).float()
            lin._two = not lin._two
            ref = x.float() @ w.float().t()
        rec["two_level_path"] = lin._two
        rec["vs_emulation_rel"] = float((y - emu).norm() / emu.norm())
        rec["paths_rel"] = float((y - y2).norm() / y.norm())
        rec["vs_bf16_rel"] = float((y - ref).norm() / ref.norm())
        rec["input_amax_calib"] = 2688.0 * g
        out.append(rec)
        print(json.dumps(rec), flush=True)
    ok = all(r["w_rel_err"] < 0.25 and r["vs_emulation_rel"] < 0.02 and r["paths_rel"] < 0.02 for r in out)
    print(json.dumps({"nv4_check": "PASS" if ok else "FAIL"}))
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()