|
| 1 | +import torch |
| 2 | +import triton |
| 3 | +import triton.language as tl |
| 4 | +from lightllm.utils.dist_utils import get_current_device_id |
| 5 | + |
| 6 | + |
| 7 | +@triton.jit |
| 8 | +def weight_quant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_N: tl.constexpr): |
| 9 | + m_index = tl.program_id(axis=0) |
| 10 | + |
| 11 | + offs_n = tl.arange(0, BLOCK_N) |
| 12 | + mask = offs_n < N |
| 13 | + |
| 14 | + x = tl.load(x_ptr + m_index * N + offs_n, mask=mask, other=0.0).to(tl.float32) |
| 15 | + |
| 16 | + amax = tl.max(tl.abs(x)) |
| 17 | + |
| 18 | + max_fp8e4m3_val = 448.0 |
| 19 | + scale = amax / max_fp8e4m3_val |
| 20 | + y = (x / (scale + 1e-6)).to(y_ptr.dtype.element_ty) |
| 21 | + |
| 22 | + tl.store(y_ptr + m_index * N + offs_n, y, mask=mask) |
| 23 | + tl.store(s_ptr + m_index, scale) |
| 24 | + |
| 25 | + |
| 26 | +def mm_weight_quant(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: |
| 27 | + assert x.is_contiguous(), "Input tensor must be contiguous" |
| 28 | + M, N = x.size() |
| 29 | + |
| 30 | + y_quant = torch.empty((M, N), dtype=torch.float8_e4m3fn, device=x.device) |
| 31 | + s_scales = torch.empty((M, 1), dtype=torch.float32, device=x.device) |
| 32 | + |
| 33 | + grid = (M,) |
| 34 | + weight_quant_kernel[grid](x, s_scales, y_quant, M, N, BLOCK_N=triton.next_power_of_2(N), num_warps=16) |
| 35 | + return y_quant, s_scales |
| 36 | + |
| 37 | + |
| 38 | +def weight_quant(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: |
| 39 | + assert x.is_contiguous(), "Input tensor must be contiguous" |
| 40 | + x = x.cuda(get_current_device_id()) |
| 41 | + if x.dim() == 3: |
| 42 | + y_quant = torch.empty((x.shape[0], x.shape[1], x.shape[2]), dtype=torch.float8_e4m3fn, device=x.device) |
| 43 | + s_scales = torch.empty((x.shape[0], x.shape[1], 1), dtype=torch.float32, device=x.device) |
| 44 | + for i in range(x.shape[0]): |
| 45 | + y_quant[i], s_scales[i] = mm_weight_quant(x[i]) |
| 46 | + return y_quant, s_scales |
| 47 | + else: |
| 48 | + y_quant, s_scales = mm_weight_quant(x) |
| 49 | + return y_quant, s_scales |
0 commit comments