diff --git a/astrai/extension/fp8.py b/astrai/extension/fp8.py index 591f51f..bf31de5 100644 --- a/astrai/extension/fp8.py +++ b/astrai/extension/fp8.py @@ -35,8 +35,6 @@ from torch.library import Library from astrai.extension.ops.fp8 import ( linear_backward_fp8, linear_forward_fp8, - mm_fp8, - quantize_bf16, ) # Max representable value per FP8 format (E4M3: 448, E5M2: 57344). @@ -275,9 +273,9 @@ def _dynamic_scale(t: torch.Tensor, recipe: FP8Recipe, fmt: str) -> torch.Tensor def fp8_linear_forward(x: torch.Tensor, w: torch.Tensor, bias=None): """Scaled fp8 linear forward (called from the aten::linear impl). - Delayed scaling uses the fused BF16->E4M3 GEMM (quantize + amax inside the - kernel); dynamic scaling measures the current amax first and runs the - pre-quantized path. + Pure FP8 path for both recipes: quantize x/w with the active scales, run + the pre-quantized GEMM, and feed the freshly measured amax back into the + delayed-scaling ring (dynamic scaling measures the current amax itself). """ if bias is None: bias = torch.empty(0, device=x.device, dtype=x.dtype) @@ -287,21 +285,16 @@ def fp8_linear_forward(x: torch.Tensor, w: torch.Tensor, bias=None): if not meta.w_init: meta.init_w(w, fmt) if isinstance(state.recipe, DynamicScaling): - x_2d = x.reshape(-1, w.size(1)) - sx = _dynamic_scale(x_2d, state.recipe, fmt) + sx = _dynamic_scale(x.reshape(-1, w.size(1)), state.recipe, fmt) sw = _dynamic_scale(w, state.recipe, fmt) - x8, _ = quantize_bf16(x_2d, sx, fmt) - w8, _ = quantize_bf16(w, sw, fmt) - out = mm_fp8(x8, w8, sx, sw) - out = out.reshape(*x.shape[:-1], w.size(0)) - if bias.numel(): - out = out + bias - return out - if not meta.x_init: - meta.init_x(x, fmt) - out, amax_x, amax_w = linear_forward_fp8(x, w, bias, meta.x_scale, meta.w_scale) - meta.update_x(amax_x, fmt) - meta.update_w(amax_w, fmt) + else: + if not meta.x_init: + meta.init_x(x, fmt) + sx, sw = meta.x_scale, meta.w_scale + out, amax_x, amax_w = linear_forward_fp8(x, w, bias, sx, sw, fmt) + if not isinstance(state.recipe, DynamicScaling): + meta.update_x(amax_x, fmt) + meta.update_w(amax_w, fmt) return out @@ -373,32 +366,40 @@ def _linear_cuda_impl(x: torch.Tensor, w: torch.Tensor, bias=None): def _linear_backward_cuda_impl(input_tensor, grad_output, weight, output_mask): + # Backward dim contract: grad_output is [..., N], weight is [N, K], so + # the contraction check is grad_output.size(-1) == weight.size(0) (not the + # forward's x.size(-1) == w.size(1) — that would silently skip fp8 for + # every non-square layer). if ( fp8_linear_enabled() and weight.dtype == torch.bfloat16 - and _fp8_supported(grad_output, weight) + and grad_output.dim() >= 2 + and weight.dim() == 2 + and grad_output.size(-1) == weight.size(0) + and input_tensor.dim() >= 2 + and input_tensor.size(-1) == weight.size(1) ): return fp8_linear_backward(grad_output, input_tensor, weight, list(output_mask)) compute_dtype = weight.dtype grad = grad_output.to(compute_dtype) grad_2d = grad.reshape(-1, weight.size(0)) input_2d = input_tensor.reshape(-1, input_tensor.size(-1)).to(compute_dtype) + # Unneeded grads come back full-shape-but-uninitialized (mirroring the + # fp8 binding), so reshape_as can never hit an empty tensor. grad_input = ( - torch.mm(grad_2d, weight) + torch.mm(grad_2d, weight).reshape_as(input_tensor) if output_mask[0] - else torch.empty(0, device=input_tensor.device, dtype=input_tensor.dtype) + else torch.empty_like(input_tensor) ) grad_weight = ( - torch.mm(grad_2d.t(), input_2d) - if output_mask[1] - else torch.empty(0, device=input_tensor.device, dtype=input_tensor.dtype) + torch.mm(grad_2d.t(), input_2d) if output_mask[1] else torch.empty_like(weight) ) grad_bias = ( grad.sum(dim=0) if output_mask[2] - else torch.empty(0, device=input_tensor.device, dtype=input_tensor.dtype) + else torch.empty(0, device=grad.device, dtype=grad.dtype) ) - return grad_input.reshape_as(input_tensor), grad_weight, grad_bias + return grad_input, grad_weight, grad_bias _lib = Library("aten", "IMPL", "CUDA") diff --git a/astrai/extension/ops/fp8.py b/astrai/extension/ops/fp8.py index 3ec0134..3ac9bd6 100644 --- a/astrai/extension/ops/fp8.py +++ b/astrai/extension/ops/fp8.py @@ -1,6 +1,6 @@ """FP8 CUDA kernel interface adapter (the only module touching the pybind). -Isolates the ``fp8_mm`` CUDA extension behind stable Python primitives: +Isolates the ``fp8_ops`` CUDA extension behind stable Python primitives: - ``quantize_bf16(x, scale, fmt) -> (x8, amax)`` — BF16 → FP8 with fused amax - ``mm_fp8(a8, b8, sa, sb) -> out`` — pre-quantized FP8 GEMM (BF16 output) @@ -33,11 +33,11 @@ _MOD: object | None = None def _mod() -> object: global _MOD if _MOD is None: - if not is_available("fp8_mm"): + if not is_available("fp8_ops"): raise RuntimeError( - "CUDA kernel 'fp8_mm' is not available. Build with CSRC_KERNELS=true." + "CUDA kernel 'fp8_ops' is not available. Build with CSRC_KERNELS=true." ) - _MOD = get_module("fp8_mm") + _MOD = get_module("fp8_ops") return _MOD @@ -154,16 +154,18 @@ def mm_fp8( return fp8_gemm(a, b, sa, sb, int(out_dtype == "e4m3"), out_scale) -def linear_forward_fp8(x, w, bias, sx, sw): - """BF16 linear forward, quantizing x/w to E4M3 inside the GEMM. +def linear_forward_fp8(x, w, bias, sx, sw, fmt: str = "e4m3"): + """Pure FP8 linear forward: quantize x/w to ``fmt``, pre-quantized GEMM. - Returns ``(out, amax_x, amax_w)``. ``bias`` may be ``None``. + Returns ``(out, amax_x, amax_w)``. ``bias`` may be ``None``. Both + operands share the same FP8 format (E4M3 by default; E5M2 for a + range-first configuration). """ if not (x.dtype == torch.bfloat16 and w.dtype == torch.bfloat16): raise TypeError(f"fp8 forward requires bf16 inputs, got {x.dtype}/{w.dtype}") if bias is None: bias = torch.empty(0, device=x.device, dtype=x.dtype) - return _mod().linear_forward_fp8(x, w, bias, sx, sw) + return _mod().linear_forward_fp8(x, w, bias, sx, sw, _fmt_int(fmt)) def linear_backward_fp8(g, x, w, masks, sg, sw, sx, fmt: str = "e5m2"): diff --git a/csrc/CMakeLists.txt b/csrc/CMakeLists.txt index 5346253..5dc291f 100644 --- a/csrc/CMakeLists.txt +++ b/csrc/CMakeLists.txt @@ -58,7 +58,7 @@ set(KERNEL_NAMES attn_paged_decode attn_paged_prefill rotary_emb - fp8_mm + fp8_ops ) set(KERNEL_SRCS attention/decode.cu @@ -66,7 +66,7 @@ set(KERNEL_SRCS attention/paged_decode.cu attention/paged_prefill.cu rotary/rotary_emb.cu - fp8/mm.cu + fp8/ops.cu ) list(LENGTH KERNEL_NAMES _kernel_count) diff --git a/csrc/kernels/fp8/gemm.cuh b/csrc/kernels/fp8/gemm.cuh index 6398f33..0d39f9c 100644 --- a/csrc/kernels/fp8/gemm.cuh +++ b/csrc/kernels/fp8/gemm.cuh @@ -32,16 +32,6 @@ struct fp8_input { // Shared device helpers // --------------------------------------------------------------------------- -__device__ __forceinline__ unsigned pack_fp8x4_vector( - float x0, float x1, float x2, float x3, - __nv_fp8_interpretation_t fmt = __NV_E4M3) { - const auto low = __nv_cvt_float2_to_fp8x2(make_float2(x0, x1), - __NV_SATFINITE, fmt); - const auto high = __nv_cvt_float2_to_fp8x2(make_float2(x2, x3), - __NV_SATFINITE, fmt); - return static_cast(low) | (static_cast(high) << 16); -} - // FP8 MMA lives in the shared astrai::mma_sync template (common/mma.cuh); // instantiate it with fp8_input::type. Accumulates in-place: callers // pass the same accumulator array as both `d` and `c`. @@ -61,33 +51,6 @@ __device__ __forceinline__ float warp_reduce_max(float value) { return value; } -// Block-wide max reduction of a per-warp tracked value, then an atomic -// update of the global amax slot when `track` is set. -template -__device__ __forceinline__ void block_reduce_amax(float& local, float* slots, - int warp, int lane, - bool track, float* global) { - local = warp_reduce_max(local); - if (lane == 0) slots[warp] = local; - __syncthreads(); - if (warp == 0) { - float value = lane < NWarps ? slots[lane] : 0.0f; - value = warp_reduce_max(value); - if (lane == 0 && track && global) atomic_max_float(global, value); - } -} - -// One thread moves eight BF16 values (16 bytes) via cp.async; the uint4 -// shape keeps source and destination naturally 128-bit aligned. -__device__ __forceinline__ void cp_async_bf16_8( - __nv_bfloat16* destination, const __nv_bfloat16* source, bool valid) { - const unsigned shared_address = __cvta_generic_to_shared(destination); - const uint4* source_vec = reinterpret_cast(source); - asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" - :: "r"(shared_address), "l"(source_vec), - "r"(valid ? 16 : 0)); -} - // One thread moves sixteen FP8 values (16 bytes) via cp.async. template __device__ __forceinline__ void cp_async_16b(T* destination, @@ -99,28 +62,6 @@ __device__ __forceinline__ void cp_async_16b(T* destination, "r"(valid ? 16 : 0)); } -// Convert four BF16 values to one 4xFP8 pack, tracking the raw (pre-scale) -// amax — scaling first would saturate amax at the FP8 max and collapse the -// scale. Format comes from Traits. -template -__device__ __forceinline__ unsigned load_fp8x4_from_bf16( - const __nv_bfloat16* source, float scale_inv, float& amax, - bool track_amax = true) { - float x0 = __bfloat162float(source[0]); - float x1 = __bfloat162float(source[1]); - float x2 = __bfloat162float(source[2]); - float x3 = __bfloat162float(source[3]); - if constexpr (TrackAmax) { - if (track_amax) { - amax = fmaxf(amax, fmaxf(fabsf(x0), fmaxf(fabsf(x1), - fmaxf(fabsf(x2), fabsf(x3))))); - } - } - return pack_fp8x4_vector(x0 * scale_inv, x1 * scale_inv, - x2 * scale_inv, x3 * scale_inv, - Traits::kNvFormat); -} - // --------------------------------------------------------------------------- // Quantize kernel: BF16 -> FP8 (E4M3 or E5M2), fused amax over raw values. // --------------------------------------------------------------------------- @@ -158,301 +99,24 @@ __global__ void fp8_quantize_kernel(FP8Params p) { } // --------------------------------------------------------------------------- -// Fused kernel: BF16 A/B -> inline E4M3 quantize -> ldmatrix fragments -> -// MMA -> BF16 out. 128x64 CTA / 64x16 warp tile / cp.async pipeline. -// The quantized FP8 tiles live in a separate smem region laid out around -// ldmatrix's single-address, 128-byte-strided matrices (16-byte rows): -// A8: [M/16 block][4 sub-blocks of 8 rows x 16 fp8][...] where sub-block -// order is (h0,m0-7), (h0,m8-15), (h1,m0-7), (h1,m8-15) — one -// ldmatrix.x4 emits the whole m16n8k32 A fragment (regs 0..3 match). -// B8: [N/8 block][2 sub-blocks of 8 rows x 16 fp8][...] with h0 then h1 — -// one ldmatrix.x2 emits the m16n8k32 B fragment (regs 0,1). -// --------------------------------------------------------------------------- - -template -__global__ void fp8_fused_gemm_kernel(FP8Params p) { - using T8 = __nv_fp8_e4m3; // fused forward always quantizes to E4M3 - constexpr int kBlockM = Traits::kBlockM; - constexpr int kBlockN = Traits::kBlockN; - constexpr int kK = Traits::kK; - constexpr int kStages = Traits::kStages; - constexpr int kWarpM = 64; // warp tile rows (BlockM / 2) - constexpr int kWarpN = 16; // warp tile cols (BlockN / 4) - constexpr int a_stride = kBlockM * kK; // bf16 elements per A stage - constexpr int b_stride = kBlockN * kK; // bf16 elements per B stage - // A8 block layout: (M/16) blocks x 4 sub-blocks x 128 B = BlockM*32 B. - // B8 block layout: (N/8) blocks x 2 sub-blocks x 128 B = BlockN*32 B. - constexpr int a8_bytes = kBlockM * 32; - constexpr int b8_bytes = kBlockN * 32; - // smem layout: [A bf16 stages][B bf16 stages][A8 fp8 tiles][B8 fp8 tiles] - constexpr int bf16_bytes = kStages * (a_stride + b_stride) * 2; - extern __shared__ char smem[]; - auto* a_bf16 = reinterpret_cast<__nv_bfloat16*>(smem); - auto* b_bf16 = reinterpret_cast<__nv_bfloat16*>(smem + kStages * a_stride * 2); - auto* a8 = reinterpret_cast(smem + bf16_bytes); - auto* b8 = reinterpret_cast(smem + bf16_bytes + a8_bytes); - __shared__ float warp_amax_a[kWarps]; - __shared__ float warp_amax_b[kWarps]; - - const auto* a = reinterpret_cast(p.a_ptr); - const auto* b = reinterpret_cast(p.b_ptr); - auto* out = reinterpret_cast<__nv_bfloat16*>(p.out_ptr); - const auto* bias = p.bias; - const float* scale_a = p.scale_a; - const float* scale_b = p.scale_b; - float* amax_a = p.amax_a; - float* amax_b = p.amax_b; - const int64_t m = p.m, n = p.n, k = p.k; - - const int tid = threadIdx.x; - const int warp = tid >> 5; - const int lane = tid & 31; - const int group = lane >> 2; - const int thread_in_group = lane & 3; - constexpr int warps_n = kBlockN / 16; - const int warp_m = warp / warps_n; - const int warp_n = warp % warps_n; - const int64_t row_base = blockIdx.y * kBlockM + warp_m * kWarpM + group; - const int64_t output_col = - blockIdx.x * kBlockN + warp_n * 16 + thread_in_group * 2; - const float sa = *scale_a; - const float sb = *scale_b; - const float inv_a = 1.0f / sa; - const float inv_b = 1.0f / sb; - float local_amax_a = 0.0f; - float local_amax_b = 0.0f; - float acc[4 * 4 * 2] = {}; - - const bool track_amax_a = TrackAmax && blockIdx.x == 0; - const bool track_amax_b = TrackAmax && blockIdx.y == 0; - // Each thread issues 8 A chunks and 4 B chunks of 8 BF16 (16B) per stage. - auto load_tile = [&](int stage, int64_t k_base) { - const int r0 = tid >> 2; - const int c0 = (tid & 3) * 8; -#pragma unroll - for (int j = 0; j < kK / 32; ++j) { - const int col = c0 + 32 * j; - const bool full_chunk = k_base + col + 7 < k; - const int64_t a_row = blockIdx.y * kBlockM + r0; - const int64_t b_row = blockIdx.x * kBlockN + r0; - auto* a_dst = &a_bf16[stage * a_stride + r0 * kK + col]; - auto* b_dst = &b_bf16[stage * b_stride + r0 * kK + col]; - const auto* a_ptr = a + a_row * k + k_base + col; - const auto* b_ptr = b + b_row * k + k_base + col; - const bool full_a = a_row < m && full_chunk; - const bool full_b = b_row < n && full_chunk; - const bool aligned_a = - (reinterpret_cast(a_ptr) & 15) == 0; - const bool aligned_b = - (reinterpret_cast(b_ptr) & 15) == 0; - if (full_a && aligned_a) { - cp_async_bf16_8(a_dst, a_ptr, true); - } else { -#pragma unroll - for (int i = 0; i < 8; ++i) { - a_dst[i] = a_row < m && k_base + col + i < k - ? a_ptr[i] - : __float2bfloat16(0.0f); - } - } - if (full_b && aligned_b) { - cp_async_bf16_8(b_dst, b_ptr, true); - } else { -#pragma unroll - for (int i = 0; i < 8; ++i) { - b_dst[i] = b_row < n && k_base + col + i < k - ? b_ptr[i] - : __float2bfloat16(0.0f); - } - } - if (r0 + kWarpM < kBlockM) { - const int64_t a_row_hi = blockIdx.y * kBlockM + r0 + kWarpM; - auto* a_dst_hi = - &a_bf16[stage * a_stride + (r0 + kWarpM) * kK + col]; - const auto* a_ptr_hi = a + a_row_hi * k + k_base + col; - const bool full_a_hi = a_row_hi < m && full_chunk; - const bool aligned_a_hi = - (reinterpret_cast(a_ptr_hi) & 15) == 0; - if (full_a_hi && aligned_a_hi) { - cp_async_bf16_8(a_dst_hi, a_ptr_hi, true); - } else { -#pragma unroll - for (int i = 0; i < 8; ++i) { - a_dst_hi[i] = a_row_hi < m && k_base + col + i < k - ? a_ptr_hi[i] - : __float2bfloat16(0.0f); - } - } - } - } - }; - - // Quantize the BF16 staging area into the ldmatrix-friendly FP8 tiles. - // A8 sub-block for global row `row` and K half `h`: - // (row>>4)*512 + ((h<<1)|((row>>3)&1))*128 + (row&7)*16 - // B8 sub-block: (row>>3)*256 + h*128 + (row&7)*16. - // Each thread emits one 4-FP8 pack at a time (256 threads, kK/4 = 8 packs - // per row). - auto quantize_tile = [&](int stage) { - constexpr int kA_packs = kBlockM * kK / 4; - constexpr int kB_packs = kBlockN * kK / 4; -#pragma unroll - for (int i = tid; i < kA_packs; i += 256) { - const int row = i >> 3; // 8 packs per row - const int k4 = (i & 7) * 4; - const int half = k4 >> 4; // 0: k 0-15, 1: k 16-31 - const int k16 = k4 & 15; - const int a8_idx = - (row >> 4) * 512 + (((half << 1) | ((row >> 3) & 1)) * 128) + - (row & 7) * 16 + k16; - auto* src = &a_bf16[stage * a_stride + row * kK + k4]; - auto* dst = reinterpret_cast(&a8[a8_idx]); - *dst = load_fp8x4_from_bf16( - src, inv_a, local_amax_a, track_amax_a); - } -#pragma unroll - for (int i = tid; i < kB_packs; i += 256) { - const int row = i >> 3; - const int k4 = (i & 7) * 4; - const int half = k4 >> 4; - const int k16 = k4 & 15; - const int b8_idx = - (row >> 3) * 256 + half * 128 + (row & 7) * 16 + k16; - auto* src = &b_bf16[stage * b_stride + row * kK + k4]; - auto* dst = reinterpret_cast(&b8[b8_idx]); - *dst = load_fp8x4_from_bf16( - src, inv_b, local_amax_b, track_amax_b); - } - }; - - const int64_t tile_count = (k + kK - 1) / kK; - load_tile(0, 0); - asm volatile("cp.async.commit_group;"); - if (tile_count > 1) { - load_tile(1, kK); - asm volatile("cp.async.commit_group;"); - } - if (tile_count > 2) { - load_tile(2, 2 * kK); - asm volatile("cp.async.commit_group;"); - } - for (int64_t tile_index = 0; tile_index < tile_count; ++tile_index) { - const int stage = static_cast(tile_index % kStages); - // 3-stage pipeline: at most 2 groups in flight; the tail of the K - // loop waits for everything. - const int64_t remaining = tile_count - tile_index - 1; - if (remaining >= 2) { - asm volatile("cp.async.wait_group 2;"); - } else if (remaining == 1) { - asm volatile("cp.async.wait_group 1;"); - } else { - asm volatile("cp.async.wait_group 0;"); - } - // wait_group only waits for this thread's async copies. All threads - // must finish loading before the tile is read by the CTA. - __syncthreads(); - quantize_tile(stage); - __syncthreads(); - - // kK == kMmaK, so one m16n8k32 MMA segment per K stage; fragments - // come from the fp8 tiles via ldmatrix. -#pragma unroll - for (int k_seg = 0; k_seg < kK / kMmaK; ++k_seg) { -#pragma unroll - for (int nt = 0; nt < 2; ++nt) { - const int b_row0 = warp_n * 16 + nt * 8; - unsigned b_frag[2]; - // B8 block = (b_row0>>3), sub-blocks h0 then h1 at +0/+128. - // ldmatrix: each thread supplies one matrix-row address — - // threads 0-7 feed matrix 0 (h0) rows, 8-15 matrix 1 (h1); - // the remaining threads' addresses are ignored. - const int b8_base = (b_row0 >> 3) * 256; - astrai::ldmatrix_x2( - b_frag, - &b8[b8_base + ((lane / 8) & 1) * 128 + (lane % 8) * 16]); -#pragma unroll - for (int mt = 0; mt < 4; ++mt) { - const int a_row0 = warp_m * kWarpM + mt * 16; - unsigned a_frag[4]; - // A8 block = (a_row0>>4); one x4 emits regs 0..3 in the - // exact mma A-operand order: h0m0-7, h0m8-15, h1m0-7, - // h1m8-15. Each thread supplies matrix (tid/8) row - // (tid%8) — all 32 addresses are used by x4. - const int a8_base = (a_row0 >> 4) * 512; - astrai::ldmatrix_x4( - a_frag, - &a8[a8_base + (lane / 8) * 128 + (lane % 8) * 16]); - astrai::mma_sync::type>( - acc + (nt * 4 + mt) * 4, - a_frag, b_frag, acc + (nt * 4 + mt) * 4); - } - } - } - __syncthreads(); - if (tile_index + 3 < tile_count) { - load_tile(stage, (tile_index + 3) * kK); - asm volatile("cp.async.commit_group;"); - } - } - - if constexpr (TrackAmax) { - block_reduce_amax(local_amax_a, warp_amax_a, warp, lane, - track_amax_a, amax_a); - block_reduce_amax(local_amax_b, warp_amax_b, warp, lane, - track_amax_b, amax_b); - } - - const float output_scale = sa * sb; -#pragma unroll - for (int nt = 0; nt < 2; ++nt) { - const int64_t col = output_col + nt * 8; -#pragma unroll - for (int mt = 0; mt < 4; ++mt) { - const int64_t row0 = row_base + mt * 16; - const int64_t row1 = row0 + 8; - float* tile_acc = acc + (nt * 4 + mt) * 4; - if (col < n) { - float bias0 = 0.0f; - float bias1 = 0.0f; - if constexpr (AddBias) { - bias0 = __bfloat162float(bias[col]); - if (col + 1 < n) - bias1 = __bfloat162float(bias[col + 1]); - } - if (row0 < m) { - out[row0 * n + col] = - __float2bfloat16(tile_acc[0] * output_scale + bias0); - if (col + 1 < n) - out[row0 * n + col + 1] = __float2bfloat16( - tile_acc[1] * output_scale + bias1); - } - if (row1 < m) { - out[row1 * n + col] = - __float2bfloat16(tile_acc[2] * output_scale + bias0); - if (col + 1 < n) - out[row1 * n + col + 1] = __float2bfloat16( - tile_acc[3] * output_scale + bias1); - } - } - } - } -} - -// --------------------------------------------------------------------------- -// Pre-quantized kernel: FP8 A/B read straight into shared memory, FP32 +// Pre-quantized GEMM kernel: FP8 A/B read straight into shared memory, FP32 // accumulation, BF16 or FP8 output. The input format follows Traits; the -// tile is compact (row = kK bytes) so MMA fragments read directly. +// tile is compact (row = kK bytes) so MMA fragments read directly — no +// in-kernel transpose of the operands (the binding handles transposes). // --------------------------------------------------------------------------- template -__global__ void fp8_pq_gemm_kernel(FP8Params p) { +__global__ void fp8_gemm_kernel(FP8Params p) { using T8 = std::conditional_t; constexpr int kBlockM = Traits::kBlockM; constexpr int kBlockN = Traits::kBlockN; constexpr int kK = Traits::kK; constexpr int kStages = Traits::kStages; - __shared__ __align__(16) T8 a_tile[kStages][kBlockM][kK]; - __shared__ __align__(16) T8 b_tile[kStages][kBlockN][kK]; + // Tiles are [M][kK] / [N][kK]: each row is kK bytes (16B-aligned for + // cp.async), and the MMA fragments read 4-byte-aligned K-contiguous + // chunks directly from them. + __shared__ __align__(16) T8 a_smem[kStages][kBlockM][kK]; + __shared__ __align__(16) T8 b_smem[kStages][kBlockN][kK]; const auto* a = reinterpret_cast(p.a_ptr); const auto* b = reinterpret_cast(p.b_ptr); @@ -476,13 +140,15 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) { float acc[4 * 4 * 2] = {}; // One A chunk (16 FP8) per thread covers the 128x32 tile; the first 128 - // threads issue the 64x32 B chunks. + // threads issue the 64x32 B chunks. Both operands are already in the MMA + // row-major / col-major layout ([M][K] with K contiguous), so each thread + // copies a 16-byte-aligned run straight into the tile via cp.async. auto load_tile = [&](int stage, int64_t k_base) { const int r0 = tid >> 1; const int c0 = (tid & 1) * 16; const bool full_chunk = k_base + c0 + 15 < k; const int64_t a_row = blockIdx.y * kBlockM + r0; - auto* a_dst = &a_tile[stage][r0][c0]; + auto* a_dst = &a_smem[stage][r0][c0]; const auto* a_ptr = a + a_row * k + k_base + c0; const bool full_a = a_row < m && full_chunk; const bool aligned_a = @@ -491,15 +157,14 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) { cp_async_16b(a_dst, a_ptr, true); } else { #pragma unroll - for (int i = 0; i < 16; ++i) { + for (int i = 0; i < 16; ++i) a_dst[i] = a_row < m && k_base + c0 + i < k ? a_ptr[i] : T8(0.0f); - } } if (tid < 128) { - const int64_t b_row = blockIdx.x * kBlockN + r0; - auto* b_dst = &b_tile[stage][r0][c0]; + const int b_row = blockIdx.x * kBlockN + r0; + auto* b_dst = &b_smem[stage][r0][c0]; const auto* b_ptr = b + b_row * k + k_base + c0; const bool full_b = b_row < n && full_chunk; const bool aligned_b = @@ -508,11 +173,10 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) { cp_async_16b(b_dst, b_ptr, true); } else { #pragma unroll - for (int i = 0; i < 16; ++i) { + for (int i = 0; i < 16; ++i) b_dst[i] = b_row < n && k_base + c0 + i < k ? b_ptr[i] : T8(0.0f); - } } } }; @@ -548,23 +212,24 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) { #pragma unroll for (int nt = 0; nt < 2; ++nt) { const int b_row = warp_n * 16 + nt * 8 + group; + // B fragment: two 4-FP8 chunks (K-contiguous) at output row. unsigned b_frag[2]; b_frag[0] = *reinterpret_cast( - &b_tile[stage][b_row][frag_col]); + &b_smem[stage][b_row][frag_col]); b_frag[1] = *reinterpret_cast( - &b_tile[stage][b_row][frag_col + 16]); + &b_smem[stage][b_row][frag_col + 16]); #pragma unroll for (int mt = 0; mt < 4; ++mt) { const int a_row0 = warp_m * 64 + mt * 16 + group; unsigned a_frag[4]; a_frag[0] = *reinterpret_cast( - &a_tile[stage][a_row0][frag_col]); + &a_smem[stage][a_row0][frag_col]); a_frag[1] = *reinterpret_cast( - &a_tile[stage][a_row0 + 8][frag_col]); + &a_smem[stage][a_row0 + 8][frag_col]); a_frag[2] = *reinterpret_cast( - &a_tile[stage][a_row0][frag_col + 16]); + &a_smem[stage][a_row0][frag_col + 16]); a_frag[3] = *reinterpret_cast( - &a_tile[stage][a_row0 + 8][frag_col + 16]); + &a_smem[stage][a_row0 + 8][frag_col + 16]); astrai::mma_sync::type>( acc + (nt * 4 + mt) * 4, a_frag, b_frag, acc + (nt * 4 + mt) * 4); @@ -622,13 +287,6 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) { // Launchers — pure CUDA (no torch), usable from the binding and pure C tests. // --------------------------------------------------------------------------- -// Fused forward tile config: 128x64 CTA, K=32, 3-stage cp.async pipeline, -// plus the fp8 ldmatrix tile region (A8[2][BlockM][16] + B8[2][BlockN][16]). -using FusedTraits = Fp8GemmTraits; -// Pre-quantized tile config: 128x64 CTA, K=32, 3-stage pipeline. -template -using PqTraits = Fp8GemmTraits; - template void launch_fp8_quantize(const FP8Params& p, cudaStream_t stream) { constexpr int kThreads = 256; @@ -636,33 +294,13 @@ void launch_fp8_quantize(const FP8Params& p, cudaStream_t stream) { fp8_quantize_kernel<<>>(p); } -template -void launch_fp8_fused(const FP8Params& p, cudaStream_t stream) { - // bf16 staging (3 stages) + fp8 ldmatrix tiles (A8[2][M][16] + B8[2][N][16]) - constexpr int kSmemBytes = - FusedTraits::kStages * - (FusedTraits::kBlockM * FusedTraits::kK + - FusedTraits::kBlockN * FusedTraits::kK) * - 2 + - 2 * FusedTraits::kBlockM * 16 + 2 * FusedTraits::kBlockN * 16; - dim3 grid((p.n + FusedTraits::kBlockN - 1) / FusedTraits::kBlockN, - (p.m + FusedTraits::kBlockM - 1) / FusedTraits::kBlockM); - auto kernel = fp8_fused_gemm_kernel; - static bool attribute_set = false; - if (!attribute_set) { - cudaFuncSetAttribute( - kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kSmemBytes); - attribute_set = true; - } - kernel<<>>(p); -} - +// Pre-quantized GEMM tile config: 128x64 CTA, K=32, 3-stage pipeline. template -void launch_fp8_pq(const FP8Params& p, cudaStream_t stream) { - using Traits = PqTraits; +void launch_fp8_gemm(const FP8Params& p, cudaStream_t stream) { + using Traits = Fp8GemmTraits; dim3 grid((p.n + Traits::kBlockN - 1) / Traits::kBlockN, (p.m + Traits::kBlockM - 1) / Traits::kBlockM); - fp8_pq_gemm_kernel<<>>(p); + fp8_gemm_kernel<<>>(p); } } // namespace fp8 diff --git a/csrc/kernels/fp8/mm.cu b/csrc/kernels/fp8/ops.cu similarity index 76% rename from csrc/kernels/fp8/mm.cu rename to csrc/kernels/fp8/ops.cu index 06af3ed..eb635d8 100644 --- a/csrc/kernels/fp8/mm.cu +++ b/csrc/kernels/fp8/ops.cu @@ -168,15 +168,15 @@ torch::Tensor mm_fp8(torch::Tensor a, torch::Tensor b, torch::Tensor sa, out_fp8 ? &os : nullptr, m, n, k); if (a.scalar_type() == torch::kFloat8_e4m3fn) { if (out_fp8) { - fp8::launch_fp8_pq(p, stream.stream()); + fp8::launch_fp8_gemm(p, stream.stream()); } else { - fp8::launch_fp8_pq(p, stream.stream()); + fp8::launch_fp8_gemm(p, stream.stream()); } } else { if (out_fp8) { - fp8::launch_fp8_pq(p, stream.stream()); + fp8::launch_fp8_gemm(p, stream.stream()); } else { - fp8::launch_fp8_pq(p, stream.stream()); + fp8::launch_fp8_gemm(p, stream.stream()); } } C10_CUDA_CHECK(cudaGetLastError()); @@ -185,9 +185,10 @@ torch::Tensor mm_fp8(torch::Tensor a, torch::Tensor b, torch::Tensor sa, std::tuple linear_forward_fp8( torch::Tensor x, torch::Tensor w, torch::Tensor bias, torch::Tensor sx, - torch::Tensor sw) { - // Fused BF16 -> E4M3 -> MMA -> BF16 linear forward. amax_x / amax_w are - // zero-initialized here and returned (caller does not clear them). + torch::Tensor sw, int64_t fmt) { + // Pure FP8 forward: quantize x/w (fmt: 0 = E4M3, 1 = E5M2), then the + // pre-quantized GEMM; the dequantized BF16 output gets the bias added. + // amax_x / amax_w come from the quantize kernels (zero-initialized here). TORCH_CHECK(x.is_cuda() && w.is_cuda(), "CUDA tensors required"); TORCH_CHECK(x.scalar_type() == torch::kBFloat16 && w.scalar_type() == torch::kBFloat16, @@ -199,14 +200,10 @@ std::tuple linear_forward_fp8( const at::cuda::OptionalCUDAGuard guard(x.device()); auto stream = at::cuda::getCurrentCUDAStream(); - auto x_c = x.reshape({-1, w.size(1)}).contiguous(); - auto w_c = w.contiguous(); + auto x_c = x.reshape({-1, w.size(1)}).contiguous(); // [M, K] + auto w_c = w.contiguous(); // [N, K] int64_t m = x_c.size(0), k = x_c.size(1), n = w_c.size(0); TORCH_CHECK(w_c.dim() == 2 && w_c.size(1) == k, "inner dim mismatch"); - // amax slots are zero-initialized here; the kernel atomically maxes in. - auto amax_x = torch::zeros({1}, x.options().dtype(torch::kFloat32)); - auto amax_w = torch::zeros({1}, x.options().dtype(torch::kFloat32)); - auto out = torch::empty({m, n}, x_c.options()); const bool has_bias = bias.defined() && bias.numel() > 0; if (has_bias) { TORCH_CHECK(bias.is_cuda() && bias.device() == x.device() && @@ -214,23 +211,42 @@ std::tuple linear_forward_fp8( bias.numel() == n, "bias must be CUDA bf16 with shape [N]"); } + const auto f8opt = fmt ? torch::kFloat8_e5m2 : torch::kFloat8_e4m3fn; + auto x8 = torch::empty({m, k}, x_c.options().dtype(f8opt)); + auto w8 = torch::empty({n, k}, x_c.options().dtype(f8opt)); + auto amax_x = torch::zeros({1}, x.options().dtype(torch::kFloat32)); + auto amax_w = torch::zeros({1}, x.options().dtype(torch::kFloat32)); + auto out = torch::empty({m, n}, x_c.options()); + + auto quantize = [&](const torch::Tensor& src, torch::Tensor& dst, + const torch::Tensor& scale, torch::Tensor* amax) { + FP8Params qp; + pack_quantize_params(qp, src.data_ptr(), dst.data_ptr(), scale, amax, + src.numel()); + if (fmt) { + fp8::launch_fp8_quantize(qp, stream.stream()); + } else { + fp8::launch_fp8_quantize(qp, stream.stream()); + } + }; + quantize(x_c, x8, sx, &amax_x); + quantize(w_c, w8, sw, &amax_w); + FP8Params p; - pack_gemm_params(p, x_c.data_ptr(), w_c.data_ptr(), out.data_ptr(), sx, sw, + pack_gemm_params(p, x8.data_ptr(), w8.data_ptr(), out.data_ptr(), sx, sw, nullptr, m, n, k); - p.bias = has_bias ? reinterpret_cast(bias.data_ptr()) - : nullptr; - p.amax_a = amax_x.data_ptr(); - p.amax_b = amax_w.data_ptr(); - if (has_bias) { - fp8::launch_fp8_fused(p, stream.stream()); + if (fmt) { + fp8::launch_fp8_gemm(p, stream.stream()); } else { - fp8::launch_fp8_fused(p, stream.stream()); + fp8::launch_fp8_gemm(p, stream.stream()); } C10_CUDA_CHECK(cudaGetLastError()); std::vector shape(x.sizes().begin(), x.sizes().end() - 1); shape.push_back(n); - return {out.reshape(shape), amax_x, amax_w}; + auto out_r = out.reshape(shape); + if (has_bias) out_r = out_r + bias; + return {out_r, amax_x, amax_w}; } std::tuple @@ -265,7 +281,6 @@ linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w, auto amax_g = torch::zeros({1}, g.options().dtype(torch::kFloat32)); auto f8opt = fmt ? g.options().dtype(torch::kFloat8_e5m2) : g.options().dtype(torch::kFloat8_e4m3fn); - const auto q_fmt = fmt ? FP8Format::E5M2 : FP8Format::E4M3; auto quantize = [&](const torch::Tensor& src, torch::Tensor& dst, const torch::Tensor& scale, torch::Tensor* amax) { @@ -278,38 +293,46 @@ linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w, fp8::launch_fp8_quantize(qp, stream.stream()); } }; - auto pq = [&](const torch::Tensor& a8, const torch::Tensor& b8, - torch::Tensor& out, const torch::Tensor& sa, - const torch::Tensor& sb, int64_t mm, int64_t nn, int64_t kk) { + // Explicit-transpose backward: the gradient/activation tensors keep their + // natural row-major layout, which the GEMM consumes transposed (W is + // [N,K] but dX contracts over N; x is [M,K] and g is [M,N] for dW), so + // the fp8 operands are transposed once and run through the fast non-trans + // pre-quantized GEMM. g is quantized once (amax_g measured here); its + // transpose is derived from the same g8 so both GEMMs share the value. + auto pq_n = [&](const torch::Tensor& a8, const torch::Tensor& b8, + torch::Tensor& out, const torch::Tensor& sa, + const torch::Tensor& sb, int64_t mm, int64_t nn, + int64_t kk) { FP8Params gp; pack_gemm_params(gp, a8.data_ptr(), b8.data_ptr(), out.data_ptr(), sa, sb, nullptr, mm, nn, kk); if (fmt) { - fp8::launch_fp8_pq(gp, stream.stream()); + fp8::launch_fp8_gemm(gp, stream.stream()); } else { - fp8::launch_fp8_pq(gp, stream.stream()); + fp8::launch_fp8_gemm(gp, stream.stream()); } }; - // dX = g @ W: quantize g once, then g8 @ w8^T. - if (masks[0]) { - auto g8 = torch::empty({m, n}, f8opt); + torch::Tensor g8; + if (masks[0] || masks[1]) { + g8 = torch::empty({m, n}, f8opt); quantize(g_c, g8, sg, &amax_g); - auto w_t = w_c.transpose(0, 1).contiguous(); // [K, N] - auto w8_t = torch::empty({k, n}, f8opt); - quantize(w_t, w8_t, sw, nullptr); - auto grad_input_2d = grad_input.reshape({m, k}); - pq(g8, w8_t, grad_input_2d, sg, sw, m, k, n); } - // dW = g^T @ x: transposed layouts for both operands. + // dX = g @ W: A = g8 [M,N] natural; B = W^T [K,N] (w8 transposed in fp8). + if (masks[0]) { + auto w8 = torch::empty({n, k}, f8opt); + quantize(w_c, w8, sw, nullptr); + auto w8T = w8.transpose(0, 1).contiguous(); // [K, N] + auto grad_input_2d = grad_input.reshape({m, k}); + pq_n(g8, w8T, grad_input_2d, sg, sw, m, k, n); + } + // dW = g^T @ x: A = g^T [N,M] (g8 transposed); B = x^T [K,M]. if (masks[1]) { - auto g_t = g_c.transpose(0, 1).contiguous(); // [N, M] - auto x_t = x_c.transpose(0, 1).contiguous(); // [K, M] - auto g8_t = torch::empty({n, m}, f8opt); - auto x8_t = torch::empty({k, m}, f8opt); - quantize(g_t, g8_t, sg, nullptr); - quantize(x_t, x8_t, sx, nullptr); - pq(g8_t, x8_t, grad_weight, sg, sx, n, k, m); + auto g8T = g8.transpose(0, 1).contiguous(); // [N, M] + auto x8 = torch::empty({m, k}, f8opt); + quantize(x_c, x8, sx, nullptr); + auto x8T = x8.transpose(0, 1).contiguous(); // [K, M] + pq_n(g8T, x8T, grad_weight, sg, sx, n, k, m); } if (!masks[0] && !masks[1]) { amax_g.copy_(g_c.abs().amax().to(torch::kFloat32)); @@ -319,38 +342,7 @@ linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w, return {grad_input, grad_weight, grad_bias, amax_g}; } -torch::Tensor fp8_mm(torch::Tensor a, torch::Tensor b, torch::Tensor sx, - torch::Tensor sw) { - // BF16-in fused FP8 GEMM primitive (no bias, no amax): a @ b^T. - TORCH_CHECK(a.is_cuda() && b.is_cuda(), "CUDA tensors required"); - TORCH_CHECK(a.scalar_type() == torch::kBFloat16 && - b.scalar_type() == torch::kBFloat16, - "a and b must be bf16"); - TORCH_CHECK(a.dim() == 2 && b.dim() == 2, "a and b must be 2D"); - TORCH_CHECK(a.device() == b.device(), "a and b must be on the same device"); - TORCH_CHECK(a.size(1) == b.size(1), "inner dim mismatch"); - check_scale(sx, a, "sx"); - check_scale(sw, a, "sw"); - check_fp8_device(a); - const at::cuda::OptionalCUDAGuard guard(a.device()); - auto stream = at::cuda::getCurrentCUDAStream(); - - auto a_c = a.contiguous(); - auto b_c = b.contiguous(); - int64_t m = a_c.size(0), n = b_c.size(0), k = a_c.size(1); - auto out = torch::empty({m, n}, a_c.options()); - FP8Params p; - pack_gemm_params(p, a_c.data_ptr(), b_c.data_ptr(), out.data_ptr(), sx, sw, - nullptr, m, n, k); - fp8::launch_fp8_fused(p, stream.stream()); - C10_CUDA_CHECK(cudaGetLastError()); - return out; -} - PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { - m.def("fp8_mm", &fp8_mm, py::arg("a"), py::arg("b"), py::arg("sx"), - py::arg("sw"), - "Fused BF16 input, E4M3 MMA, FP32 accumulation, BF16 output GEMM"); m.def("quantize_bf16", &quantize_bf16, py::arg("x"), py::arg("scale"), py::arg("fmt"), "BF16 to FP8 (E4M3/E5M2) quantize with fused amax; returns (x8, amax)"); @@ -361,7 +353,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { "1=fp8 e4m3 (requires out_scale)"); m.def("linear_forward_fp8", &linear_forward_fp8, py::arg("x"), py::arg("w"), py::arg("bias"), py::arg("sx"), py::arg("sw"), - "Fused BF16-to-FP8 linear forward; returns (out, amax_x, amax_w)"); + py::arg("fmt") = 0, + "Pure FP8 linear forward: quantize x/w, pre-quantized GEMM; " + "returns (out, amax_x, amax_w)"); m.def("linear_backward_fp8", &linear_backward_fp8, py::arg("g"), py::arg("x"), py::arg("w"), py::arg("masks"), py::arg("sg"), py::arg("sw"), py::arg("sx"), py::arg("fmt"), diff --git a/docs/developer/cuda_kernels.md b/docs/developer/cuda_kernels.md index 44f0167..f959332 100644 --- a/docs/developer/cuda_kernels.md +++ b/docs/developer/cuda_kernels.md @@ -11,7 +11,7 @@ AstrAI includes optional custom CUDA kernels for attention, rotary embedding, an | `attn_paged_decode` | `attention/paged_decode.cu` | Paged KV cache decode attention | | `attn_paged_prefill` | `attention/paged_prefill.cu` | Paged KV cache prefill attention (ragged batch) | | `rotary_emb` | `rotary/rotary_emb.cu` | Fused rotary embedding (cos/sin lookup + rotation) | -| `fp8_mm` | `fp8/mm.cu` | FP8 quantization + tensor-core GEMM (sm_89+) | +| `fp8_ops` | `fp8/ops.cu` | FP8 quantization + tensor-core GEMM (sm_89+) | Additionally, optimized `.cuh` variants with tensor-core MMA (Matrix Multiply-Accumulate) exist: @@ -39,7 +39,7 @@ Standalone benchmark vs torch complex-multiply (48 calls = 24 layers × q+k): 6- ### FP8 GEMM / Linear Kernel -The `fp8_mm` family (`csrc/kernels/fp8/`) accelerates bf16 linear layers by +The `fp8_ops` family (`csrc/kernels/fp8/`) accelerates bf16 linear layers by quantizing to FP8 and running tensor-core GEMMs (**requires sm_89+**; fp8 `mma.sync.m16n8k32` only exists on Ada/Hopper). It follows the same three-layer style as attention, but split into **three** files: @@ -47,8 +47,8 @@ style as attention, but split into **three** files: | File | Role | |------|------| | `fp8/common.h` | `FP8Format` enum (E4M3/E5M2), `Fp8GemmTraits`, `FP8Params` POD — no torch | -| `fp8/gemm.cuh` | pure-CUDA device code: `fp8_quantize_kernel` (BF16→FP8 + amax), `fp8_pq_gemm_kernel` (pre-quantized GEMM, 128×64 CTA / 64×16 warp / 3-stage cp.async) — no torch | -| `fp8/mm.cu` | binding only: `check_fp8_device` (sm_89+), param packing, launch dispatch, pybind → module `fp8_mm` | +| `fp8/gemm.cuh` | pure-CUDA device code: `fp8_quantize_kernel` (BF16→FP8 + amax), `fp8_gemm_kernel` (pre-quantized GEMM, 128×64 CTA / 64×16 warp / 3-stage cp.async) — no torch | +| `fp8/ops.cu` | binding only: `check_fp8_device` (sm_89+), param packing, launch dispatch, pybind → module `fp8_ops` | Scale semantics follow `torch._scaled_mm` (quantization step size: divide by `scale`; the kernel computes the reciprocal internally — the interface never @@ -97,7 +97,7 @@ unset, `setup.py` auto-detects the real GPU capability through - **sm_80+** (Ampere and later): enables the tensor-core MMA path (`mma.sync.m16n8k16.bf16` for bf16 attention, `mma.sync.m16n8k32` for FP8). -- **sm_89+**: required for the FP8 family (`fp8_mm`) — FP8 tensor-core +- **sm_89+**: required for the FP8 family (`fp8_ops`) — FP8 tensor-core instructions only exist on Ada/Hopper and newer. - **`-DASTRAI_NO_MMA`** is a manual escape hatch only — the build never defines it automatically. To disable the MMA path, add it to `NVCC_FLAGS` yourself; @@ -246,9 +246,14 @@ with attn_backend(ATTN_BACKEND.CUDA): The `attention(...)` policy entry point falls back to `FlashAttnBackend` (when flash-attn is installed and supports the call) or `TorchNativeBackend` when the -automatically selected CUDA backend cannot handle an input. An explicit -`ASTR_BACKEND` or `attn_backend(...)` selection is strict and raises instead of -silently switching implementations. +automatically selected CUDA backend cannot handle an input. Resolution +precedence is: explicit `attn_backend(...)` context > `ASTR_BACKEND` env > +default. An explicit `attn_backend(...)` selection is strict and raises instead +of silently switching implementations; the env override (and the implicit +default) fall back to the first compatible backend when incapable. Training +calls (`fwd=None`, no KV cache) resolve by capability: the CUDA cache kernels +cannot run without a cache, so they fall back to flash (mask-free/causal calls +only) and finally to torch SDPA. ### Rotary Backend @@ -372,7 +377,7 @@ csrc/ │ │ └── paged_prefill.cu # → module attn_paged_prefill │ ├── rotary/ │ │ └── rotary_emb.cu # rotary embedding (kernel + binding in one file) → module rotary_emb -│ └── fp8/ # FP8 family (module name fp8_mm) +│ └── fp8/ # FP8 family (module name fp8_ops) │ ├── common.h # FP8Format enum, Fp8GemmTraits, FP8Params POD (no torch) │ ├── gemm.cuh # FP8 device code: quantize + pre-quantized GEMM kernels (no torch) │ └── mm.cu # binding only: validation, param packing, launch dispatch, pybind diff --git a/tests/conftest.py b/tests/conftest.py index e6c6348..e2c79fe 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,7 +17,7 @@ CUDA_AVAIL = torch.cuda.is_available() KERNEL_AVAIL = CUDA_AVAIL and all(is_available(k) for k in KERNEL_NAMES) FP8_AVAIL = ( CUDA_AVAIL - and is_available("fp8_mm") + and is_available("fp8_ops") and torch.cuda.get_device_capability() >= (8, 9) ) skip_no_cuda = pytest.mark.skipif(not CUDA_AVAIL, reason="CUDA not available") diff --git a/tests/extension/test_fp8_mma.py b/tests/extension/test_fp8_mma.py index e172280..4375917 100644 --- a/tests/extension/test_fp8_mma.py +++ b/tests/extension/test_fp8_mma.py @@ -1,6 +1,7 @@ """FP8 primitives: kernel-level (CUDA) and policy-level (CPU-verifiable) tests. -The kernel-level tests exercise the fused and pre-quantized CUDA paths; the +The kernel-level tests exercise the pure FP8 path (quantize_bf16 + mm_fp8 for +the forward GEMM, quantize + pre-quantized GEMMs for the backward); the policy-level tests (recipes, autocast context, per-tensor meta, CPU fallbacks of the custom ops) run without a GPU. """ @@ -16,7 +17,6 @@ from astrai.extension.fp8 import ( fp8_autocast, fp8_state, ) -from astrai.extension.loader import get_module from astrai.extension.ops.fp8 import ( linear_backward_fp8, linear_forward_fp8, @@ -44,14 +44,15 @@ def _quantize(tensor, scale): ("m", "n", "k"), [(16, 8, 32), (17, 9, 33), (31, 15, 64), (32, 48, 96)], ) -def test_fused_fp8_mma_matches_explicit_quantization(m, n, k): +def test_fp8_mm_matches_explicit_quantization(m, n, k): torch.manual_seed(m + n + k) a = torch.randn(m, k, device="cuda", dtype=torch.bfloat16) b = torch.randn(n, k, device="cuda", dtype=torch.bfloat16) scale_a = _scale(a) scale_b = _scale(b) - - out = get_module("fp8_mm").fp8_mm(a, b, scale_a, scale_b) + a8, _ = quantize_bf16(a, scale_a, "e4m3") + b8, _ = quantize_bf16(b, scale_b, "e4m3") + out = mm_fp8(a8, b8, scale_a, scale_b) expected = ( _quantize(a, scale_a) @ _quantize(b, scale_b).t() * scale_a * scale_b ).to(torch.bfloat16) @@ -86,7 +87,7 @@ def test_quantize_bf16_e5m2_format(): @skip_no_fp8 -def test_fused_fp8_linear_forward_and_backward(): +def test_fp8_linear_forward_and_backward(): torch.manual_seed(7) m, n, k = 19, 13, 37 x = torch.randn(m, k, device="cuda", dtype=torch.bfloat16)