File size: 1,084 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fused rowwise FP8 baseline with explicit correctly-rounded tensor division."""

import torch
import triton
import triton.language as tl


@triton.jit
def _quantize(X, Q, S, H: tl.constexpr, BLOCK: tl.constexpr):
    row = tl.program_id(0)
    col = tl.arange(0, BLOCK)
    x = tl.load(X + row * H + col, col < H, 0).to(tl.float32)
    amax = tl.max(tl.abs(x), 0)
    # Match PyTorch's FP32 scalar-divide scale construction. Tensor/tensor
    # division below must not be lowered to approximate reciprocal multiply.
    scale = tl.where(amax > 0, amax * (1.0 / 448.0), 1.0)
    value = tl.minimum(tl.maximum(tl.div_rn(x, scale), -448.0), 448.0)
    tl.store(Q + row * H + col, value, col < H)
    tl.store(S + row, scale)


def rowwise_fp8(x):
    out = torch.empty_like(x, dtype=torch.float8_e4m3fn)
    scales = torch.empty((x.shape[0], 1), device=x.device, dtype=torch.float32)
    h = x.shape[-1]
    _quantize[(x.shape[0],)](x, out, scales, h, triton.next_power_of_2(h),
                           num_warps=8 if h > 4096 else 4, enable_fp_fusion=False)
    return out, scales