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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""NVFP4: E2M1 elements, per-16 E4M3 block scales, two-level weight scaling, and the scale swizzle.
|
| 2 |
+
|
| 3 |
+
THE FORMAT, and every constant here is derived rather than remembered.
|
| 4 |
+
|
| 5 |
+
E2M1 element -- 1 sign, 2 exponent (bias 1), 1 mantissa, with subnormals:
|
| 6 |
+
e=0 subnormal : m * 2^0 * 0.5 -> {0, 0.5}
|
| 7 |
+
e>0 normal : (1 + 0.5m) * 2^(e-1) -> {1, 1.5}, {2, 3}, {4, 6}
|
| 8 |
+
magnitudes {0, 0.5, 1, 1.5, 2, 3, 4, 6}, max 6. The 3-bit magnitude field is exactly the
|
| 9 |
+
index into that sorted table, because (e, m) enumerates it in order -- which is what makes
|
| 10 |
+
encoding a bucketize and nothing more.
|
| 11 |
+
NON-UNIFORM, and that is the point: fine near zero, 33% steps at the top, where INT4's
|
| 12 |
+
uniform grid steps 14%. It buys resolution where weights actually live.
|
| 13 |
+
|
| 14 |
+
block 16 consecutive elements along the CONTRACTION axis share one E4M3 scale.
|
| 15 |
+
(MXFP4 is the sibling: block 32, E8M0 power-of-two scale.)
|
| 16 |
+
|
| 17 |
+
two levels, for weights. E4M3 tops out at 448, so a lone block scale cannot span a whole
|
| 18 |
+
tensor's dynamic range. A per-tensor fp32 factor is applied first:
|
| 19 |
+
global = 448 * 6 / amax_tensor
|
| 20 |
+
block = amax_block * global / 6 in [0, 448] -> representable in E4M3
|
| 21 |
+
element= x * global / block in [-6, 6] -> representable in E2M1
|
| 22 |
+
dequant: x ~= element * block / global
|
| 23 |
+
Each step is checked by construction, so a tensor cannot silently overflow either container.
|
| 24 |
+
|
| 25 |
+
THE SCALE SWIZZLE IS MANDATORY, not an optimisation. `torch._scaled_mm_v2` rejects row-major block
|
| 26 |
+
scales outright: "scale_a must be swizzled to SWIZZLE_32_4_4 format". The layout tiles the scale
|
| 27 |
+
matrix 128 rows x 4 columns and rearranges each tile as (32, 4, 4). `swizzle_scales` implements it
|
| 28 |
+
and `verify_nvfp4_gemm` checks it against an fp32 reference -- a wrong permutation still produces a
|
| 29 |
+
well-formed GEMM of the wrong numbers, so it is verified, never assumed.
|
| 30 |
+
"""
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
FP4_MAX = 6.0
|
| 36 |
+
E4M3_MAX = 448.0
|
| 37 |
+
BLOCK = 16
|
| 38 |
+
|
| 39 |
+
# sorted E2M1 magnitudes; index == the 3-bit magnitude field
|
| 40 |
+
_E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
|
| 41 |
+
# midpoints, for round-to-nearest
|
| 42 |
+
_BOUND = tuple((_E2M1[i] + _E2M1[i + 1]) / 2 for i in range(7))
|
| 43 |
+
_CACHE: dict = {}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _tab(device):
|
| 47 |
+
k = str(device)
|
| 48 |
+
if k not in _CACHE:
|
| 49 |
+
_CACHE[k] = (torch.tensor(_E2M1, device=device, dtype=torch.float32),
|
| 50 |
+
torch.tensor(_BOUND, device=device, dtype=torch.float32))
|
| 51 |
+
return _CACHE[k]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def quantize_nvfp4(x: torch.Tensor, block: int = BLOCK, two_level: bool = True):
|
| 55 |
+
"""[.., K] -> (packed float4_e2m1fn_x2 [.., K/2], e4m3 scales [.., K/block], global fp32).
|
| 56 |
+
|
| 57 |
+
`two_level=False` drops the per-tensor factor, which is what SVDQuant's config does for
|
| 58 |
+
ACTIVATIONS (one level, block 16, E4M3). Weights use both levels.
|
| 59 |
+
"""
|
| 60 |
+
assert x.shape[-1] % block == 0, f"last dim {x.shape[-1]} not a multiple of block {block}"
|
| 61 |
+
vals, bounds = _tab(x.device)
|
| 62 |
+
xf = x.detach().float()
|
| 63 |
+
amax = xf.abs().amax().clamp(min=1e-12)
|
| 64 |
+
glob = (E4M3_MAX * FP4_MAX / amax) if two_level else torch.ones((), device=x.device)
|
| 65 |
+
xg = xf * glob
|
| 66 |
+
|
| 67 |
+
shp = xg.shape
|
| 68 |
+
g = xg.reshape(*shp[:-1], shp[-1] // block, block)
|
| 69 |
+
bmax = g.abs().amax(dim=-1, keepdim=True) # [.., nb, 1]
|
| 70 |
+
bs = (bmax / FP4_MAX).clamp(min=1e-12, max=E4M3_MAX)
|
| 71 |
+
bs_q = bs.to(torch.float8_e4m3fn).float() # round the SCALE first ...
|
| 72 |
+
bs_q = torch.where(bs_q > 0, bs_q, torch.full_like(bs_q, 2.0 ** -9))
|
| 73 |
+
e = g / bs_q # ... then divide by the
|
| 74 |
+
e = e.clamp(-FP4_MAX, FP4_MAX) # rounded scale, so the
|
| 75 |
+
# encode: nearest E2M1 magnitude, sign in bit 3 # decoder can reproduce it
|
| 76 |
+
idx = torch.bucketize(e.abs().contiguous(), bounds)
|
| 77 |
+
code = (idx | (torch.signbit(e).to(torch.uint8) << 3)).to(torch.uint8)
|
| 78 |
+
code = code.reshape(*shp)
|
| 79 |
+
lo, hi = code[..., 0::2], code[..., 1::2] # first element in LOW bits
|
| 80 |
+
# VIEWED AS float4_e2m1fn_x2, not left as raw bytes: `_scaled_mm_v2` type-checks its operands
|
| 81 |
+
# and rejects Byte outright ("Expected mat_a to be Float8 or Float4_x2 matrix got Byte"). The
|
| 82 |
+
# storage is identical; the dtype is what tells the kernel how to read it.
|
| 83 |
+
packed = (lo | (hi << 4)).contiguous().view(torch.float4_e2m1fn_x2)
|
| 84 |
+
scales = bs.reshape(*shp[:-1], shp[-1] // block).to(torch.float8_e4m3fn)
|
| 85 |
+
return packed, scales, glob.float()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def dequantize_nvfp4(packed: torch.Tensor, scales: torch.Tensor, glob, block: int = BLOCK):
|
| 89 |
+
"""Exact inverse of `quantize_nvfp4`. This is the reference the hardware must agree with."""
|
| 90 |
+
vals, _ = _tab(packed.device)
|
| 91 |
+
if packed.dtype != torch.uint8:
|
| 92 |
+
packed = packed.view(torch.uint8)
|
| 93 |
+
lo = (packed & 0x0F)
|
| 94 |
+
hi = (packed >> 4) & 0x0F
|
| 95 |
+
K = packed.shape[-1] * 2
|
| 96 |
+
code = torch.empty(*packed.shape[:-1], K, dtype=torch.uint8, device=packed.device)
|
| 97 |
+
code[..., 0::2] = lo
|
| 98 |
+
code[..., 1::2] = hi
|
| 99 |
+
mag = vals[(code & 0x07).long()]
|
| 100 |
+
sign = torch.where((code & 0x08) > 0, -1.0, 1.0)
|
| 101 |
+
e = mag * sign
|
| 102 |
+
s = scales.float().unsqueeze(-1)
|
| 103 |
+
x = (e.reshape(*e.shape[:-1], K // block, block) * s).reshape(*e.shape[:-1], K)
|
| 104 |
+
gv = glob if torch.is_tensor(glob) else torch.tensor(glob, device=packed.device)
|
| 105 |
+
return x / gv
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def swizzle_scales(sf: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
"""[M, K/16] E4M3 block scales -> the SWIZZLE_32_4_4 layout `_scaled_mm_v2` requires.
|
| 110 |
+
|
| 111 |
+
Tiles of 128 rows x 4 scale-columns, each stored as (32, 4, 4): row r of a tile goes to
|
| 112 |
+
(r % 32, (r // 32) % 4) and column c to (c % 4). M and K/16 are zero-padded up to the tile
|
| 113 |
+
quantum, which is why the returned buffer can be larger than the input.
|
| 114 |
+
"""
|
| 115 |
+
M, S = sf.shape
|
| 116 |
+
Mp = (M + 127) // 128 * 128
|
| 117 |
+
Sp = (S + 3) // 4 * 4
|
| 118 |
+
pad = torch.zeros(Mp, Sp, dtype=sf.dtype, device=sf.device)
|
| 119 |
+
pad[:M, :S] = sf
|
| 120 |
+
t = pad.reshape(Mp // 128, 4, 32, Sp // 4, 4) # (tile_m, r//32, r%32, tile_k, c%4)
|
| 121 |
+
t = t.permute(0, 3, 2, 1, 4) # (tile_m, tile_k, 32, 4, 4)
|
| 122 |
+
return t.reshape(-1).contiguous().view(torch.float8_e4m3fn)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
_ONES: dict = {}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def recip_scale(g, device) -> torch.Tensor:
|
| 129 |
+
"""The 1-element fp32 reciprocal `_scaled_mm_v2` wants for the TensorWise level.
|
| 130 |
+
|
| 131 |
+
Build this ONCE, at load, and hand the same tensor to every call. Computing it per forward
|
| 132 |
+
allocates and launches for a constant, which at this model's shapes costs several times the
|
| 133 |
+
GEMM: 13 us of FP4 GEMM behind 40+ us of scalar bookkeeping.
|
| 134 |
+
"""
|
| 135 |
+
if g is None:
|
| 136 |
+
k = str(device)
|
| 137 |
+
if k not in _ONES:
|
| 138 |
+
_ONES[k] = torch.ones(1, device=device, dtype=torch.float32)
|
| 139 |
+
return _ONES[k]
|
| 140 |
+
return (1.0 / (g if torch.is_tensor(g) else torch.tensor(g))).reshape(1).float().to(device)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def nvfp4_mm(a_packed, a_scale_sw, b_packed, b_scale_sw, a_rglob=None, b_rglob=None,
|
| 144 |
+
out_dtype=torch.bfloat16, b_packed_t=None):
|
| 145 |
+
"""A[M,K] x B[K,N] on the FP4 tensor cores. Packed operands, pre-swizzled block scales.
|
| 146 |
+
|
| 147 |
+
`a_rglob` / `b_rglob` are the RECIPROCALS of the per-tensor global scales, as 1-element fp32
|
| 148 |
+
tensors from `recip_scale` -- precomputed, not derived here. They ride inside the kernel as a
|
| 149 |
+
second TensorWise scale level; dividing the output afterwards instead costs two elementwise
|
| 150 |
+
kernels that at these shapes exceed the GEMM itself. Both operands must carry the level or the
|
| 151 |
+
configuration is rejected, so a one-level activation passes a reciprocal of 1.
|
| 152 |
+
|
| 153 |
+
`b_packed_t` lets a caller hand in the transposed view once instead of re-taking it per call.
|
| 154 |
+
"""
|
| 155 |
+
ST = torch._C._ScalingType
|
| 156 |
+
SW = torch._C._SwizzleType
|
| 157 |
+
bw, tw = int(ST.BlockWise1x16.value), int(ST.TensorWise.value)
|
| 158 |
+
swz, nos = int(SW.SWIZZLE_32_4_4.value), int(SW.NO_SWIZZLE.value)
|
| 159 |
+
ra = recip_scale(None, a_packed.device) if a_rglob is None else a_rglob
|
| 160 |
+
rb = recip_scale(None, a_packed.device) if b_rglob is None else b_rglob
|
| 161 |
+
bt = b_packed.t() if b_packed_t is None else b_packed_t
|
| 162 |
+
return torch._scaled_mm_v2(a_packed, bt, [a_scale_sw, ra], [bw, tw], [swz, nos],
|
| 163 |
+
[b_scale_sw, rb], [bw, tw], [swz, nos], None, out_dtype)
|