ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 7)
5b90392 verified
Raw History Blame Contribute Delete
1.44 kB
"""Reference implementation — the CORRECTNESS SPEC for `nvfp4_gemm`.
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py.
"""
import torch
# E2M1: 1 sign bit, 2 exponent bits, 1 mantissa bit -> these 8 magnitudes, negated for codes 8..15.
_E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
BLOCK = 16 # NVFP4 block size: one E4M3 scale per 16 consecutive K elements
def _e2m1_table(device):
t = torch.tensor(_E2M1, dtype=torch.float32, device=device)
return torch.cat([t, -t]) # codes 0..7 positive, 8..15 negative
def nvfp4_gemm(a, w_packed, w_scale, global_scale):
"""Dequantise NVFP4 weights to fp32, then GEMM. The numerical SPECIFICATION, not a performance target."""
N, Kh = w_packed.shape
K = Kh * 2
lo = (w_packed & 0x0F).long() # even k
hi = (w_packed >> 4).long() # odd k
codes = torch.stack([lo, hi], dim=-1).reshape(N, K)
w = _e2m1_table(a.device)[codes] # (N, K) fp32 element magnitudes
w = w * w_scale.float().repeat_interleave(BLOCK, dim=1) # per-16-element E4M3 block scale
w = w * global_scale.float() # per-tensor fp32 scale
return (a.float() @ w.t()).to(torch.float32)