File size: 3,151 Bytes
5b90392
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference implementation — the CORRECTNESS SPEC for `nvfp4_quantize`.

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 GB/s number. GENERATED by _factory/build.py.
"""
import torch


FP8_MAX = 448.0                                  # max finite magnitude of float8_e4m3fn
FP4_MAX = 6.0                                    # max magnitude of E2M1
BLOCK = 16                                       # NVFP4 block: 16 consecutive elements share one E4M3 scale
_CHUNK = 4096                                    # rows processed at a time, only to bound the reference's memory


def _e2m1_code(v):
    """fp32 -> 4-bit E2M1 code. Round-to-nearest-EVEN on the eight magnitudes, saturating at +-6.

    The eight magnitudes are 0, 0.5, 1, 1.5, 2, 3, 4, 6 (codes 0..7); bit 3 is the sign. The index is the
    number of thresholds the magnitude has passed -- `>` where the tie rounds DOWN to the even code and
    `>=` where it rounds UP to the even code:

        0.25 -> down (code 0)    0.75 -> up (code 2)    1.25 -> down (code 2)    1.75 -> up (code 4)
        2.5  -> down (code 4)    3.5  -> up (code 6)    5.0  -> down (code 6)

    The sign comes from `signbit`, so a NEGATIVE value that rounds to zero magnitude encodes as code 8
    (negative zero), exactly like a hardware `cvt.rn.satfinite.e2m1x2.f32`.
    """
    a = v.abs()
    idx = ((a > 0.25).to(torch.uint8) + (a >= 0.75) + (a > 1.25) + (a >= 1.75)
           + (a > 2.5) + (a >= 3.5) + (a > 5.0))
    return idx + (torch.signbit(v).to(torch.uint8) << 3)


def nvfp4_quantize(x):
    """Quantise a bf16 tensor to NVFP4. The numerical SPECIFICATION, not a performance target.

    NOTE the TENSOR divisors: dividing by a 0-dim tensor is a correctly-rounded IEEE fp32 division, which is
    what `2688.0f / amax` and `v / sf` give in CUDA/Triton. (torch turns `tensor / python_float` into a
    multiply by the rounded reciprocal, which differs by an ulp on ~55% of elements.)
    """
    M, N = x.shape
    dev = x.device
    six = torch.tensor(FP4_MAX, device=dev)
    big = torch.tensor(FP8_MAX * FP4_MAX, device=dev)                  # 2688.0

    amax = x.abs().float().amax().clamp(min=1e-30)                     # over the WHOLE tensor
    global_scale = (big / amax).float()                                # 0-dim fp32

    q = torch.empty(M, N // 2, dtype=torch.uint8, device=dev)
    block_scale = torch.empty(M, N // BLOCK, dtype=torch.float8_e4m3fn, device=dev)
    for m0 in range(0, M, _CHUNK):
        m1 = min(m0 + _CHUNK, M)
        xb = x[m0:m1].float().view(-1, N // BLOCK, BLOCK)
        bamax = xb.abs().amax(-1, keepdim=True)
        sf = ((bamax * global_scale) / six).clamp(0.0, FP8_MAX).to(torch.float8_e4m3fn)
        sff = sf.float()
        v = torch.where(sff > 0, (xb * global_scale) / sff, torch.zeros((), device=dev))
        code = _e2m1_code(v).view(m1 - m0, N)
        q[m0:m1] = code[:, 0::2] | (code[:, 1::2] << 4)                # LOW nibble = even n
        block_scale[m0:m1] = sf.squeeze(-1).view(m1 - m0, N // BLOCK)
    return q, block_scale, global_scale