diff --git a/crates/aien-inference-abi/max/FP8_GROUPED_KERNEL.md b/crates/aien-inference-abi/max/FP8_GROUPED_KERNEL.md new file mode 100644 index 00000000..9dd4050f --- /dev/null +++ b/crates/aien-inference-abi/max/FP8_GROUPED_KERNEL.md @@ -0,0 +1,22 @@ +# Grouped FP8 expert GEMM prototype + +`kernels/qwen3_fp8_gemm.mojo` registers `aien.qwen3_moe.grouped_fp8_gemm`. +It consumes grouped FP8 E4M3 activations `[assignments, K]`, FP32 inverse +activation scales `[assignments, K/128]`, checkpoint FP8 E4M3 weights +`[experts, N, K]`, BF16 inverse weight scales `[experts, N/128, K/128]`, +and expert offsets `[experts+1]`. It returns FP32 `[assignments, N]`. +The weights remain packed FP8 throughout. One warp owns one expert and eight +output channels, walks that expert's ragged token rows in groups of 16, and +uses `mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32`. The result of +each 128-channel K block is multiplied by the corresponding activation and +weight inverse scales before accumulation. Both Qwen gate/up and down +projections fit this contract. + +This primitive expects activations quantized to E4M3 in 128-channel blocks +with a corresponding inverse scale. Activation quantization and integration +with the layer graph are separate work. The standalone GPU parity test is +`test_fp8_grouped_gemm.py`; it checks ragged expert offsets, every MMA +fragment position, both K blocks, and distinct weight and activation scales. +The test is required before using the kernel for model inference. + +Reference: [PTX m16n8k32 fragment layout](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#matrix-fragments-for-mma-m16n8k32). diff --git a/crates/aien-inference-abi/max/kernels/__init__.mojo b/crates/aien-inference-abi/max/kernels/__init__.mojo index 146b183a..62f5dd36 100644 --- a/crates/aien-inference-abi/max/kernels/__init__.mojo +++ b/crates/aien-inference-abi/max/kernels/__init__.mojo @@ -1 +1,2 @@ # AIEN MAX custom operators. +from .qwen3_fp8_gemm import Qwen3GroupedFp8Gemm diff --git a/crates/aien-inference-abi/max/kernels/qwen3_fp8_gemm.mojo b/crates/aien-inference-abi/max/kernels/qwen3_fp8_gemm.mojo new file mode 100644 index 00000000..833ca8ce --- /dev/null +++ b/crates/aien-inference-abi/max/kernels/qwen3_fp8_gemm.mojo @@ -0,0 +1,123 @@ +"""Grouped FP8 E4M3 GEMM for GB10, 16x8x32 warp MMA. + +Inputs are grouped token rows, packed row-major [expert, output, input] +checkpoint weights, BF16 inverse scales per 128x128 weight block, +FP32 activation inverse scales per token and 128 input channels, and +expert offsets. FP8 weight storage is never expanded to BF16. +""" + +import extensibility +from extensibility import InputTensor, OutputTensor, ManagedTensorSlice +from max.gpu.host import DeviceContext +from std.gpu import block_idx, thread_idx +from std.sys._assembly import inlined_assembly +from std.sys import _RegisterPackType +from std.memory import bitcast +from std.utils.index import IndexList + + +def mma_e4m3(a: SIMD[DType.uint32, 4], b: SIMD[DType.uint32, 2], partial: SIMD[DType.float32, 4]) -> SIMD[DType.float32, 4]: + var mma = inlined_assembly[ + "mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 " + "{$0,$1,$2,$3}, {$4,$5,$6,$7}, {$8,$9}, {$10,$11,$12,$13};", + _RegisterPackType[Float32, Float32, Float32, Float32], + constraints="=f,=f,=f,=f,r,r,r,r,r,r,f,f,f,f", + has_side_effect=False, + ](a[0], a[1], a[2], a[3], b[0], b[1], partial[0], partial[1], partial[2], partial[3]) + return SIMD[DType.float32, 4](mma[0], mma[1], mma[2], mma[3]) + + +def _gemm_gpu( + result: ManagedTensorSlice[dtype=DType.float32, rank=2, mut=True, ...], + activations: ManagedTensorSlice[dtype=DType.float8_e4m3fn, rank=2, ...], + activation_scales: ManagedTensorSlice[dtype=DType.float32, rank=2, ...], + weights: ManagedTensorSlice[dtype=DType.float8_e4m3fn, rank=3, ...], + weight_scales: ManagedTensorSlice[dtype=DType.bfloat16, rank=3, ...], + offsets: ManagedTensorSlice[dtype=DType.int32, rank=1, ...], + ctx: DeviceContext, +) raises: + var experts = weights.dim_size(0) + var output_channels = weights.dim_size(1) + var input_channels = weights.dim_size(2) + var assignments = activations.dim_size(0) + if input_channels % 128 != 0 or output_channels % 128 != 0: + raise Error("FP8 expert dimensions must align to 128") + if activations.dim_size(1) != input_channels or result.dim_size(0) != assignments or result.dim_size(1) != output_channels: + raise Error("FP8 grouped GEMM shape mismatch") + if activation_scales.dim_size(0) != assignments or activation_scales.dim_size(1) != input_channels // 128: + raise Error("FP8 activation scale shape mismatch") + if weight_scales.dim_size(0) != experts or weight_scales.dim_size(1) != output_channels // 128 or weight_scales.dim_size(2) != input_channels // 128: + raise Error("FP8 weight scale shape mismatch") + if offsets.dim_size(0) != experts + 1: + raise Error("FP8 expert offset shape mismatch") + + @parameter + def mma_kernel(expert_count: Int32, out_channels: Int32, in_channels: Int32): + var lane = thread_idx.x + var expert = block_idx.x + var out_tile = block_idx.y * 8 + var group = lane // 4 + var quad = lane % 4 + var begin = Int(offsets.load[1](IndexList[1](expert))[0]) + var end = Int(offsets.load[1](IndexList[1](expert + 1))[0]) + # Each warp owns an expert and eight output columns. It walks the + # expert's ragged rows in 16-row tiles, so the launch grid is compact. + for row_tile in range(begin, end, 16): + var total = SIMD[DType.float32, 4](0.0) + for block in range(Int(in_channels) // 128): + var partial = SIMD[DType.float32, 4](0.0) + for k_tile in range(0, 128, 32): + var a = SIMD[DType.uint32, 4](0) + var b = SIMD[DType.uint32, 2](0) + # PTX m16n8k32 operand layout. Four packed E4M3 values + # occupy each 32-bit operand register. + for frag in range(4): + var row = row_tile + group + (8 if frag % 2 == 1 else 0) + var k0 = block * 128 + k_tile + quad * 4 + (16 if frag >= 2 else 0) + var packed: UInt32 = 0 + for byte in range(4): + var value: UInt32 = 0 + if row < end: + value = UInt32(bitcast[DType.uint8, 1](activations.load[1](IndexList[2](row, k0 + byte)))[0]) + packed |= value << UInt32(byte * 8) + a[frag] = packed + for frag in range(2): + var k0 = block * 128 + k_tile + quad * 4 + frag * 16 + var packed: UInt32 = 0 + for byte in range(4): + var raw = weights.load[1](IndexList[3](expert, out_tile + group, k0 + byte))[0] + packed |= UInt32(bitcast[DType.uint8, 1](raw)[0]) << UInt32(byte * 8) + b[frag] = packed + partial = mma_e4m3(a, b, partial) + var w_scale = Float32(weight_scales.load[1](IndexList[3](expert, out_tile // 128, block))[0]) + for frag in range(4): + var row = row_tile + group + (8 if frag >= 2 else 0) + if row < end: + total[frag] += partial[frag] * w_scale * activation_scales.load[1](IndexList[2](row, block))[0] + for frag in range(4): + var row = row_tile + group + (8 if frag >= 2 else 0) + if row < end: + result.store[1](IndexList[2](row, out_tile + quad * 2 + frag % 2), SIMD[DType.float32, 1](total[frag])) + + ctx.enqueue_function[mma_kernel]( + Int32(experts), Int32(output_channels), Int32(input_channels), + grid_dim=(experts, output_channels // 8), block_dim=32, + ) + + +@extensibility.register("aien.qwen3_moe.grouped_fp8_gemm") +struct Qwen3GroupedFp8Gemm: + @staticmethod + def execute[target: StaticString]( + result: OutputTensor[dtype=DType.float32, rank=2, ...], + activations: InputTensor[dtype=DType.float8_e4m3fn, rank=2, ...], + activation_scales: InputTensor[dtype=DType.float32, rank=2, ...], + weights: InputTensor[dtype=DType.float8_e4m3fn, rank=3, ...], + weight_scales: InputTensor[dtype=DType.bfloat16, rank=3, ...], + offsets: InputTensor[dtype=DType.int32, rank=1, ...], + ctx: DeviceContext, + ) raises: + comptime if target == "gpu": + _gemm_gpu(result, activations, activation_scales, weights, weight_scales, offsets, ctx) + else: + raise Error("Grouped FP8 GEMM requires a GPU") diff --git a/crates/aien-inference-abi/max/test_fp8_grouped_gemm.py b/crates/aien-inference-abi/max/test_fp8_grouped_gemm.py new file mode 100644 index 00000000..342480e5 --- /dev/null +++ b/crates/aien-inference-abi/max/test_fp8_grouped_gemm.py @@ -0,0 +1,87 @@ +"""Standalone grouped FP8 tensor-core parity test on GB10.""" + +from pathlib import Path +import unittest + +import numpy as np +from max.driver import Accelerator, Buffer, CPU, accelerator_count +from max.dtype import DType +from max.engine import InferenceSession +from max.graph import DeviceRef, Graph, TensorType, ops + + +def fp8_buffer(bits: np.ndarray, device: Accelerator) -> Buffer: + return Buffer.from_numpy(bits.astype(np.uint8)).view(DType.float8_e4m3fn).to(device) + + +def bf16_buffer(values: np.ndarray, device: Accelerator) -> Buffer: + bits = (values.astype(np.float32).view(np.uint32) >> 16).astype(np.uint16) + return Buffer.from_numpy(bits).view(DType.bfloat16).to(device) + + +@unittest.skipUnless(accelerator_count() > 0, "requires a MAX accelerator") +class GroupedFp8GemmTest(unittest.TestCase): + def test_ragged_group_and_block_scales(self) -> None: + device = Accelerator() + ref = DeviceRef.from_device(device) + rows, experts, channels = 26, 2, 256 + + def forward(activations, activation_scales, weights, weight_scales, offsets): + return ops.custom( + name="aien.qwen3_moe.grouped_fp8_gemm", + device=ref, + values=[activations, activation_scales, weights, weight_scales, offsets], + out_types=[TensorType(DType.float32, [rows, channels], device=ref)], + )[0].tensor + + graph = Graph( + "aien_grouped_fp8_parity", + forward=forward, + input_types=[ + TensorType(DType.float8_e4m3fn, [rows, channels], device=ref), + TensorType(DType.float32, [rows, 2], device=ref), + TensorType(DType.float8_e4m3fn, [experts, channels, channels], device=ref), + TensorType(DType.bfloat16, [experts, 2, 2], device=ref), + TensorType(DType.int32, [experts + 1], device=ref), + ], + custom_extensions=[Path(__file__).parent / "kernels"], + ) + session = InferenceSession(devices=[device]) + model = session.init(session.compile(graph)) + # All values are exactly representable E4M3 values, with distinct + # rows/columns/experts to expose fragment mapping and grouped offsets. + values = np.array([0.0, 0.5, 1.0, 2.0, -0.5, -1.0, -2.0], dtype=np.float32) + bits = np.array([0x00, 0x30, 0x38, 0x40, 0xB0, 0xB8, 0xC0], dtype=np.uint8) + row_indices = (np.arange(rows)[:, None] * 3 + np.arange(channels)[None, :] * 5) % 7 + weight_indices = ( + np.arange(experts)[:, None, None] * 2 + + np.arange(channels)[None, :, None] * 3 + + np.arange(channels)[None, None, :] * 5 + ) % 7 + a = bits[row_indices] + w = bits[weight_indices] + a_scale = np.where(np.arange(rows)[:, None] % 2 == 0, 1.0, 0.5).astype(np.float32) * np.array([1.0, 2.0], dtype=np.float32) + w_scale = np.array([[[1.0, 0.5], [2.0, 1.0]], [[0.5, 2.0], [1.0, 0.5]]], dtype=np.float32) + offsets = np.array([0, 19, rows], dtype=np.int32) + actual = model.execute( + fp8_buffer(a, device), + Buffer.from_numpy(a_scale).to(device), + fp8_buffer(w, device), + bf16_buffer(w_scale, device), + Buffer.from_numpy(offsets).to(device), + )[0].to(CPU()).to_numpy() + expected = np.empty_like(actual) + for row in range(rows): + expert = 0 if row < offsets[1] else 1 + for output in range(channels): + total = 0.0 + for block in range(2): + av = values[row_indices[row, block * 128 : (block + 1) * 128]] + wv = values[weight_indices[expert, output, block * 128 : (block + 1) * 128]] + total += float(np.dot(av, wv)) * float(a_scale[row, block]) * float(w_scale[expert, output // 128, block]) + expected[row, output] = total + np.testing.assert_allclose(actual, expected, rtol=0, atol=2e-4) + + +if __name__ == "__main__": + unittest.main()