diff --git a/flashinfer/experimental/b12x/attention/paged/_controls.py b/flashinfer/experimental/b12x/attention/paged/_controls.py index db9f26911d8..6e9f67021d1 100644 --- a/flashinfer/experimental/b12x/attention/paged/_controls.py +++ b/flashinfer/experimental/b12x/attention/paged/_controls.py @@ -34,6 +34,7 @@ "B12X_PAGED_DECODE_GRAPH_CHUNK_PAGES", "B12X_PAGED_DECODE_GRAPH_MIN_CHUNK_PAGES", "B12X_DEBUG_PAGED_POLICY", + "B12X_SELECTED_FORWARD_FP8", ) _CURRENT: ContextVar[Mapping[str, str | None] | None] = ContextVar( "paged_controls", default=None diff --git a/flashinfer/experimental/b12x/attention/paged/_selected_forward.py b/flashinfer/experimental/b12x/attention/paged/_selected_forward.py index d634adda0a3..462a2d8f281 100644 --- a/flashinfer/experimental/b12x/attention/paged/_selected_forward.py +++ b/flashinfer/experimental/b12x/attention/paged/_selected_forward.py @@ -57,6 +57,7 @@ from b12x._lib.utils.device import current_cuda_stream from b12x._lib.utils.pointers import make_ptr +from ._controls import paged_control from ._selected_forward_config import HEAD_DIM as _HEAD_DIM from ._selected_forward_config import MAX_SPLITS as _NUM_SPLITS from ._selected_forward_config import SELECTION_WIDTH as _SELECTION_WIDTH @@ -164,6 +165,518 @@ def _cp_async_load_128b_zfill( ) +from cutlass import Uint8 as _Uint8 +from b12x._lib.intrinsics.atomics import st_shared_u32 as _fp8_st_shared_u32 +from b12x._lib.intrinsics.conversion import cvt_f32x4_to_e4m3x4 as _fp8_cvt_f32x4_to_e4m3x4 +from b12x._lib.intrinsics.memory import ( + ldmatrix_m8n8x2_b16 as _fp8_ldmatrix_x2, + ldmatrix_m8n8x4_b16 as _fp8_ldmatrix_x4, +) +from b12x._lib.intrinsics.mma import ( + mma_m16n8k32_f32_e4m3 as _fp8_mma_m16n8k32, + mxfp8_mma_m16n8k32_f32_e4m3 as _mxfp8_mma_m16n8k32, +) +from b12x._lib.intrinsics.packed import bfloat2_to_float2_scaled as _fp8_bf2_to_f2 +from b12x.attention._shared.mla.decode_math import _d2_load_b_fp8_perm as _fp8_load_b_perm + +_FP8_KV_STRIDE = 272 +_FP8_Q_STRIDE = 272 + + +@dsl_user_op +def _fp8_cp_async_commit(*, loc=None, ip=None) -> None: + llvm.inline_asm(None, [], "cp.async.commit_group;", "", has_side_effects=True, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip) + + +@dsl_user_op +def _fp8_cp_async_wait_0(*, loc=None, ip=None) -> None: + llvm.inline_asm(None, [], "cp.async.wait_group 0;", "", has_side_effects=True, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip) + + +@dsl_user_op +def _fp8_cp_async_wait_1(*, loc=None, ip=None) -> None: + llvm.inline_asm(None, [], "cp.async.wait_group 1;", "", has_side_effects=True, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip) + + +@dsl_user_op +def _fp8_f32_to_u32(val: Float32, *, loc=None, ip=None) -> Uint32: + return Uint32(llvm.bitcast(T.i32(), Float32(val).ir_value(loc=loc, ip=ip), loc=loc, ip=ip)) + + +@dsl_user_op +def _fp8_u32_to_f32(val: Uint32, *, loc=None, ip=None) -> Float32: + return Float32(llvm.bitcast(T.f32(), Uint32(val).ir_value(loc=loc, ip=ip), loc=loc, ip=ip)) + + +@dsl_user_op +def _fp8_st_shared_u8(addr: Int32, val: Uint32, *, loc=None, ip=None) -> None: + llvm.inline_asm( + None, + [Int32(addr).ir_value(loc=loc, ip=ip), Uint32(val).ir_value(loc=loc, ip=ip)], + "st.shared.u8 [$0], $1;", + "r,r", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _fp8_cvt_f32_to_e4m3_byte(val: Float32, *, loc=None, ip=None) -> Uint32: + return Uint32( + llvm.inline_asm( + T.i32(), + [Float32(val).ir_value(loc=loc, ip=ip)], + "{ .reg .b16 tmp; cvt.rn.satfinite.e4m3x2.f32 tmp, $1, $1; cvt.u32.u16 $0, tmp; and.b32 $0, $0, 0xff; }", + "=r,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +class _FP8SelectedPositionPagedForwardKernel: + """Full-FP8/MXFP8 Tensor Core (m16n8k32.e4m3 + 2-stage K cp.async + perm V) direct QSA prefill kernel.""" + + def __init__( + self, + *, + q_heads: int, + kv_heads: int, + page_size: int, + key_strides: tuple[int, int, int], + value_strides: tuple[int, int, int], + selection_width: int = _SELECTION_WIDTH, + head_dim: int = _HEAD_DIM, + gate_stride: int = -1, + ) -> None: + self.q_heads = int(q_heads) + self.kv_heads = int(kv_heads) + self.heads_per_kv = self.q_heads // self.kv_heads + self.head_dim = int(head_dim) + self.page_size = int(page_size) + self.key_page_stride, self.key_token_stride, self.key_head_stride = map(int, key_strides) + self.value_page_stride, self.value_token_stride, self.value_head_stride = map(int, value_strides) + self.shared_cache_strides = tuple(map(int, key_strides)) == tuple(map(int, value_strides)) + self.selection_width = int(selection_width) + self.gate_stride = int(gate_stride) + + @cute.jit + def __call__( + self, + query: cute.Pointer, + key_cache: cute.Pointer, + value_cache: cute.Pointer, + k_descale: cute.Pointer, + v_descale: cute.Pointer, + block_table: cute.Pointer, + request_ids: cute.Pointer, + selected_positions: cute.Pointer, + query_positions: cute.Pointer, + partial_output: cute.Pointer, + partial_lse: cute.Pointer, + output: cute.Pointer, + output_gate: cute.Pointer, + continuation: tuple, + num_cache_pages: Int64, + table_batch: Int64, + table_width: Int64, + softmax_scale: Float32, + rows: Int32, + splits: Int32, + stream: cuda.CUstream, + ) -> None: + self.kernel( + query, key_cache, value_cache, k_descale, v_descale, + block_table, request_ids, selected_positions, query_positions, + output, output_gate, + num_cache_pages, table_batch, table_width, softmax_scale, + ).launch(grid=(rows, self.kv_heads, 1), block=(128, 1, 1), stream=stream) + + @cute.jit + def _resolve_bases( + self, + tile: Int32, + stage: Int32, + row: Int32, + kv_head: Int32, + request_id: Int64, + request_valid, + query_position: Int64, + block_table: cute.Pointer, + selected_positions: cute.Pointer, + key_bases: cute.Tensor, + value_bases: cute.Tensor, + num_cache_pages: Int64, + table_width: Int64, + thread: Int32, + ) -> None: + if thread < Int32(32): + sel_col = tile * Int32(32) + thread + valid = request_valid & (sel_col < Int32(self.selection_width)) + logical_pos = Int64(-1) + if valid: + logical_pos = selected_positions[row.to(Int64) * Int64(self.selection_width) + sel_col.to(Int64)].to(Int64) + valid = (logical_pos >= Int64(0)) & (logical_pos <= query_position) + phys_page = Int64(-1) + page_off = Int64(0) + if valid: + log_page = logical_pos // Int64(self.page_size) + valid = log_page < table_width + if valid: + phys_page = block_table[request_id * table_width + log_page].to(Int64) + valid = (phys_page >= Int64(0)) & (phys_page < num_cache_pages) + page_off = logical_pos % Int64(self.page_size) + kb = Int64(-1) + vb = Int64(-1) + if valid: + kb = ( + phys_page * Int64(self.key_page_stride) + + page_off * Int64(self.key_token_stride) + + kv_head.to(Int64) * Int64(self.key_head_stride) + ) + if const_expr(self.shared_cache_strides): + vb = kb + else: + vb = ( + phys_page * Int64(self.value_page_stride) + + page_off * Int64(self.value_token_stride) + + kv_head.to(Int64) * Int64(self.value_head_stride) + ) + key_bases[stage * Int32(32) + thread] = kb + if const_expr(not self.shared_cache_strides): + value_bases[stage * Int32(32) + thread] = vb + + @cute.jit + def _issue_k(self, stage: Int32, key_cache: cute.Pointer, key_bases: cute.Tensor, k_smem_base: Int32, thread: Int32) -> None: + k_stage_off = stage * Int32(32 * _FP8_KV_STRIDE) + for vi in cutlass.range_constexpr(4): + lin = thread + Int32(vi * 128) + tok = lin >> Int32(4) + dim_byte = (lin & Int32(15)) << Int32(4) + kb = Int64(key_bases[stage * Int32(32) + tok]) + ok = kb >= Int64(0) + safe_kb = Int64(cutlass.select_(ok, kb, Int64(0))) + _cp_async_load_128b_zfill( + k_smem_base + k_stage_off + tok * Int32(_FP8_KV_STRIDE) + dim_byte, + _pointer_as_int64(key_cache, safe_kb + dim_byte.to(Int64)), + cutlass.select_(ok, Int32(16), Int32(0)), + ) + + @cute.jit + def _issue_v(self, stage: Int32, value_cache: cute.Pointer, key_bases: cute.Tensor, value_bases: cute.Tensor, v_smem_base: Int32, thread: Int32) -> None: + for vi in cutlass.range_constexpr(4): + lin = thread + Int32(vi * 128) + tok = lin >> Int32(4) + dim_byte = (lin & Int32(15)) << Int32(4) + vb = Int64(key_bases[stage * Int32(32) + tok]) if const_expr(self.shared_cache_strides) else Int64(value_bases[stage * Int32(32) + tok]) + ok = vb >= Int64(0) + safe_vb = Int64(cutlass.select_(ok, vb, Int64(0))) + _cp_async_load_128b_zfill( + v_smem_base + tok * Int32(_FP8_KV_STRIDE) + dim_byte, + _pointer_as_int64(value_cache, safe_vb + dim_byte.to(Int64)), + cutlass.select_(ok, Int32(16), Int32(0)), + ) + + @cute.kernel + def kernel( + self, + query: cute.Pointer, + key_cache: cute.Pointer, + value_cache: cute.Pointer, + k_descale: cute.Pointer, + v_descale: cute.Pointer, + block_table: cute.Pointer, + request_ids: cute.Pointer, + selected_positions: cute.Pointer, + query_positions: cute.Pointer, + output: cute.Pointer, + output_gate: cute.Pointer, + num_cache_pages: Int64, + table_batch: Int64, + table_width: Int64, + softmax_scale: Float32, + ) -> None: + row, kv_head, _ = cute.arch.block_idx() + thread, _, _ = cute.arch.thread_idx() + warp = thread >> Int32(5) + lane = thread & Int32(31) + gid = lane >> Int32(2) + tid = lane & Int32(3) + + allocator = cutlass.utils.SmemAllocator() + q_fp8 = allocator.allocate_tensor(_Uint8, cute.make_layout((16 * _FP8_Q_STRIDE,)), byte_alignment=128) + q_scale = allocator.allocate_tensor(Uint32, cute.make_layout((16 * 8,)), byte_alignment=16) + k_fp8 = allocator.allocate_tensor(_Uint8, cute.make_layout((2 * 32 * _FP8_KV_STRIDE,)), byte_alignment=128) + v_fp8 = allocator.allocate_tensor(_Uint8, cute.make_layout((32 * _FP8_KV_STRIDE,)), byte_alignment=128) + p_fp8 = allocator.allocate_tensor(_Uint8, cute.make_layout((16 * 32,)), byte_alignment=128) + key_bases = allocator.allocate_tensor(Int64, cute.make_layout((2 * 32,)), byte_alignment=16) + value_bases = allocator.allocate_tensor(Int64, cute.make_layout((1 if self.shared_cache_strides else 2 * 32,)), byte_alignment=16) + s_row_max = allocator.allocate_tensor(Float32, cute.make_layout((4 * 16,)), byte_alignment=16) + s_row_sum = allocator.allocate_tensor(Float32, cute.make_layout((4 * 16,)), byte_alignment=16) + s_any_valid = allocator.allocate_tensor(Int32, cute.make_layout((2,)), byte_alignment=16) + + q_smem_base = shared_ptr_to_u32(q_fp8.iterator) + k_smem_base = shared_ptr_to_u32(k_fp8.iterator) + v_smem_base = shared_ptr_to_u32(v_fp8.iterator) + p_smem_base = shared_ptr_to_u32(p_fp8.iterator) + + request_id = request_ids[row.to(Int64)].to(Int64) + request_valid = (request_id >= Int64(0)) & (request_id < table_batch) + query_position = Int64(0) + if request_valid: + query_position = query_positions[row.to(Int64)].to(Int64) + + qh = thread >> Int32(3) + qblk = thread & Int32(7) + q_vals = cute.make_rmem_tensor((32,), Float32) + amax = Float32(0.0) + if request_valid & (qh < Int32(self.heads_per_kv)): + q_head_abs = kv_head * Int32(self.heads_per_kv) + qh + q_elem_base = (row.to(Int64) * Int64(self.q_heads) + q_head_abs.to(Int64)) * Int64(self.head_dim) + (qblk * Int32(32)).to(Int64) + q_gaddr = _pointer_as_int64(query, q_elem_base) + if (q_gaddr & Int64(15)) == Int64(0): + for v in cutlass.range_constexpr(4): + w0, w1, w2, w3 = ld_global_nc_v4_u32(q_gaddr + Int64(v * 16)) + f0, f1 = _fp8_bf2_to_f2(w0, Float32(1.0)) + f2, f3 = _fp8_bf2_to_f2(w1, Float32(1.0)) + f4, f5 = _fp8_bf2_to_f2(w2, Float32(1.0)) + f6, f7 = _fp8_bf2_to_f2(w3, Float32(1.0)) + q_vals[v * 8 + 0] = f0; q_vals[v * 8 + 1] = f1 + q_vals[v * 8 + 2] = f2; q_vals[v * 8 + 3] = f3 + q_vals[v * 8 + 4] = f4; q_vals[v * 8 + 5] = f5 + q_vals[v * 8 + 6] = f6; q_vals[v * 8 + 7] = f7 + for kk in cutlass.range_constexpr(8): + val = q_vals[v * 8 + kk] + av = cutlass.select_(val >= Float32(0.0), val, -val) + amax = cutlass.select_(av > amax, av, amax) + else: + for kk in cutlass.range_constexpr(32): + val = Float32(query[q_elem_base + Int64(kk)]) + q_vals[kk] = val + av = cutlass.select_(val >= Float32(0.0), val, -val) + amax = cutlass.select_(av > amax, av, amax) + else: + for kk in cutlass.range_constexpr(32): + q_vals[kk] = Float32(0.0) + + raw_scale = amax * Float32(1.0 / 448.0) + sfa_byte = Uint32(127) + inv_sfa = Float32(1.0) + if raw_scale > Float32(1e-30): + bits = _fp8_f32_to_u32(raw_scale) + exp_u = (bits >> Uint32(23)) & Uint32(0xFF) + mant = bits & Uint32(0x7FFFFF) + sb = Uint32(exp_u + Uint32(cutlass.select_(mant != Uint32(0), Uint32(1), Uint32(0)))) + sb = Uint32(cutlass.select_(sb > Uint32(254), Uint32(254), sb)) + sb = Uint32(cutlass.select_(sb < Uint32(1), Uint32(1), sb)) + sfa_byte = sb + inv_sfa = _fp8_u32_to_f32((Uint32(254) - sb) << Uint32(23)) + q_scale[qh * Int32(8) + qblk] = sfa_byte + q_dst = q_smem_base + qh * Int32(_FP8_Q_STRIDE) + qblk * Int32(32) + for p in cutlass.range_constexpr(8): + packed4 = _fp8_cvt_f32x4_to_e4m3x4( + q_vals[p * 4 + 0] * inv_sfa, + q_vals[p * 4 + 1] * inv_sfa, + q_vals[p * 4 + 2] * inv_sfa, + q_vals[p * 4 + 3] * inv_sfa, + ) + _fp8_st_shared_u32(q_dst + Int32(p * 4), packed4) + + k_scale_val = Float32(k_descale[0]) + v_scale_val = Float32(v_descale[0]) + scale_log2 = softmax_scale * k_scale_val * Float32(_LOG2_E) + neg_inf = Float32(-float("inf")) + + out_acc = cute.make_rmem_tensor((8, 4), Float32) + out_acc.fill(0.0) + row_m0 = neg_inf + row_m1 = neg_inf + row_l0 = Float32(0.0) + row_l1 = Float32(0.0) + + a_row = (lane & Int32(7)) + ((lane >> Int32(3)) & Int32(1)) * Int32(8) + a_col = (lane >> Int32(4)) * Int32(16) + b_row = lane & Int32(7) + b_col = ((lane >> Int32(3)) & Int32(1)) * Int32(16) + sfa_head = gid + (lane & Int32(1)) * Int32(8) + h0_ok = gid < Int32(self.heads_per_kv) + h1_ok = (gid + Int32(8)) < Int32(self.heads_per_kv) + + total_tiles = (self.selection_width + 31) // 32 + col0 = warp * Int32(8) + tid * Int32(2) + col1 = col0 + Int32(1) + c0_lo = col0 & Int32(15); c0_hi = col0 & Int32(16) + pcol0_perm = c0_hi + ((c0_lo & Int32(3)) << Int32(2)) + (c0_lo >> Int32(2)) + c1_lo = col1 & Int32(15); c1_hi = col1 & Int32(16) + pcol1_perm = c1_hi + ((c1_lo & Int32(3)) << Int32(2)) + (c1_lo >> Int32(2)) + + self._resolve_bases( + Int32(0), Int32(0), row, kv_head, request_id, request_valid, query_position, + block_table, selected_positions, key_bases, value_bases, num_cache_pages, table_width, thread, + ) + if thread < Int32(32): + m_any = cute.arch.vote_ballot_sync(Int64(key_bases[thread]) >= Int64(0)) + if thread == Int32(0): + s_any_valid[0] = cutlass.select_(m_any != Uint32(0), Int32(1), Int32(0)) + cute.arch.sync_threads() + if Int32(s_any_valid[0]) != Int32(0): + self._issue_k(Int32(0), key_cache, key_bases, k_smem_base, thread) + _fp8_cp_async_commit() + + for tile in cutlass.range(total_tiles): + cur_stage = tile & Int32(1) + if Int32(s_any_valid[cur_stage]) != Int32(0): + self._issue_v(cur_stage, value_cache, key_bases, value_bases, v_smem_base, thread) + _fp8_cp_async_commit() + _fp8_cp_async_wait_1() + cute.arch.sync_threads() + + k_stage_addr = k_smem_base + cur_stage * Int32(32 * _FP8_KV_STRIDE) + kb_off = cur_stage * Int32(32) + qk0 = Float32(0.0); qk1 = Float32(0.0); qk2 = Float32(0.0); qk3 = Float32(0.0) + cand_base = warp * Int32(8) + for blk in cutlass.range_constexpr(8): + ko = Int32(blk * 32) + a0, a1, a2, a3 = _fp8_ldmatrix_x4(q_smem_base + a_row * Int32(_FP8_Q_STRIDE) + ko + a_col) + sfa = Uint32(q_scale[sfa_head * Int32(8) + Int32(blk)]) + b0, b1 = _fp8_ldmatrix_x2(k_stage_addr + (cand_base + b_row) * Int32(_FP8_KV_STRIDE) + ko + b_col) + qk0, qk1, qk2, qk3 = _mxfp8_mma_m16n8k32( + qk0, qk1, qk2, qk3, a0, a1, a2, a3, b0, b1, sfa, Uint32(0x7F), + ) + + v0 = Int64(key_bases[kb_off + col0]) >= Int64(0) + v1 = Int64(key_bases[kb_off + col1]) >= Int64(0) + s0 = cutlass.select_(h0_ok & v0, qk0, neg_inf) + s1 = cutlass.select_(h0_ok & v1, qk1, neg_inf) + s2 = cutlass.select_(h1_ok & v0, qk2, neg_inf) + s3 = cutlass.select_(h1_ok & v1, qk3, neg_inf) + + lm0 = cutlass.max(s0, s1) + lm1 = cutlass.max(s2, s3) + lm0 = cutlass.max(lm0, cute.arch.shuffle_sync_bfly(lm0, offset=2)) + lm0 = cutlass.max(lm0, cute.arch.shuffle_sync_bfly(lm0, offset=1)) + lm1 = cutlass.max(lm1, cute.arch.shuffle_sync_bfly(lm1, offset=2)) + lm1 = cutlass.max(lm1, cute.arch.shuffle_sync_bfly(lm1, offset=1)) + if tid == Int32(0): + s_row_max[warp * Int32(16) + gid] = lm0 + s_row_max[warp * Int32(16) + gid + Int32(8)] = lm1 + cute.arch.sync_threads() + + tm0 = cutlass.max( + cutlass.max(Float32(s_row_max[gid]), Float32(s_row_max[Int32(16) + gid])), + cutlass.max(Float32(s_row_max[Int32(32) + gid]), Float32(s_row_max[Int32(48) + gid])), + ) + tm1 = cutlass.max( + cutlass.max(Float32(s_row_max[Int32(8) + gid]), Float32(s_row_max[Int32(24) + gid])), + cutlass.max(Float32(s_row_max[Int32(40) + gid]), Float32(s_row_max[Int32(56) + gid])), + ) + mnew0 = cutlass.max(row_m0, tm0) + mnew1 = cutlass.max(row_m1, tm1) + os0 = cutlass.select_(mnew0 == neg_inf, Float32(1.0), cutlass.select_(row_m0 == neg_inf, Float32(0.0), _exp2_approx((row_m0 - mnew0) * scale_log2))) + os1 = cutlass.select_(mnew1 == neg_inf, Float32(1.0), cutlass.select_(row_m1 == neg_inf, Float32(0.0), _exp2_approx((row_m1 - mnew1) * scale_log2))) + p_peak0 = cutlass.select_(tm0 == neg_inf, Float32(0.0), _exp2_approx((tm0 - mnew0) * scale_log2)) + p_peak1 = cutlass.select_(tm1 == neg_inf, Float32(0.0), _exp2_approx((tm1 - mnew1) * scale_log2)) + row_m0 = mnew0 + row_m1 = mnew1 + + e0 = cutlass.select_(s0 == neg_inf, Float32(0.0), _exp2_approx((s0 - tm0) * scale_log2)) + e1 = cutlass.select_(s1 == neg_inf, Float32(0.0), _exp2_approx((s1 - tm0) * scale_log2)) + e2 = cutlass.select_(s2 == neg_inf, Float32(0.0), _exp2_approx((s2 - tm1) * scale_log2)) + e3 = cutlass.select_(s3 == neg_inf, Float32(0.0), _exp2_approx((s3 - tm1) * scale_log2)) + row_l0 = row_l0 * os0 + (e0 + e1) * p_peak0 + row_l1 = row_l1 * os1 + (e2 + e3) * p_peak1 + + _fp8_st_shared_u8(p_smem_base + gid * Int32(32) + pcol0_perm, _fp8_cvt_f32_to_e4m3_byte(e0 * Float32(448.0))) + _fp8_st_shared_u8(p_smem_base + gid * Int32(32) + pcol1_perm, _fp8_cvt_f32_to_e4m3_byte(e1 * Float32(448.0))) + _fp8_st_shared_u8(p_smem_base + (gid + Int32(8)) * Int32(32) + pcol0_perm, _fp8_cvt_f32_to_e4m3_byte(e2 * Float32(448.0))) + _fp8_st_shared_u8(p_smem_base + (gid + Int32(8)) * Int32(32) + pcol1_perm, _fp8_cvt_f32_to_e4m3_byte(e3 * Float32(448.0))) + + _fp8_cp_async_wait_0() + if tile + Int32(1) < Int32(total_tiles): + nxt_stage = cur_stage ^ Int32(1) + self._resolve_bases( + tile + Int32(1), nxt_stage, row, kv_head, request_id, request_valid, query_position, + block_table, selected_positions, key_bases, value_bases, num_cache_pages, table_width, thread, + ) + if thread < Int32(32): + m_any = cute.arch.vote_ballot_sync(Int64(key_bases[nxt_stage * Int32(32) + thread]) >= Int64(0)) + if thread == Int32(0): + s_any_valid[nxt_stage] = cutlass.select_(m_any != Uint32(0), Int32(1), Int32(0)) + cute.arch.sync_threads() + + if tile + Int32(1) < Int32(total_tiles): + nxt_stage = cur_stage ^ Int32(1) + if Int32(s_any_valid[nxt_stage]) != Int32(0): + self._issue_k(nxt_stage, key_cache, key_bases, k_smem_base, thread) + _fp8_cp_async_commit() + + p_unscale0 = p_peak0 * Float32(1.0 / 448.0) + p_unscale1 = p_peak1 * Float32(1.0 / 448.0) + pa0, pa1, pa2, pa3 = _fp8_ldmatrix_x4(p_smem_base + a_row * Int32(32) + a_col) + for nt in cutlass.range_constexpr(8): + dim_base = warp * Int32(64) + Int32(nt * 8) + vb0, vb1 = _fp8_load_b_perm(v_smem_base, Int32(0), dim_base, lane, kv_smem_stride=_FP8_KV_STRIDE) + d0, d1, d2, d3 = _fp8_mma_m16n8k32( + Float32(0.0), Float32(0.0), Float32(0.0), Float32(0.0), + pa0, pa1, pa2, pa3, vb0, vb1, + ) + out_acc[nt, 0] = out_acc[nt, 0] * os0 + d0 * p_unscale0 + out_acc[nt, 1] = out_acc[nt, 1] * os0 + d1 * p_unscale0 + out_acc[nt, 2] = out_acc[nt, 2] * os1 + d2 * p_unscale1 + out_acc[nt, 3] = out_acc[nt, 3] * os1 + d3 * p_unscale1 + cute.arch.sync_threads() + else: + _fp8_cp_async_wait_0() + if tile + Int32(1) < Int32(total_tiles): + nxt_stage = cur_stage ^ Int32(1) + self._resolve_bases( + tile + Int32(1), nxt_stage, row, kv_head, request_id, request_valid, query_position, + block_table, selected_positions, key_bases, value_bases, num_cache_pages, table_width, thread, + ) + if thread < Int32(32): + m_any = cute.arch.vote_ballot_sync(Int64(key_bases[nxt_stage * Int32(32) + thread]) >= Int64(0)) + if thread == Int32(0): + s_any_valid[nxt_stage] = cutlass.select_(m_any != Uint32(0), Int32(1), Int32(0)) + cute.arch.sync_threads() + if Int32(s_any_valid[nxt_stage]) != Int32(0): + self._issue_k(nxt_stage, key_cache, key_bases, k_smem_base, thread) + _fp8_cp_async_commit() + + row_l0 = row_l0 + cute.arch.shuffle_sync_bfly(row_l0, offset=2) + row_l0 = row_l0 + cute.arch.shuffle_sync_bfly(row_l0, offset=1) + row_l1 = row_l1 + cute.arch.shuffle_sync_bfly(row_l1, offset=2) + row_l1 = row_l1 + cute.arch.shuffle_sync_bfly(row_l1, offset=1) + if tid == Int32(0): + s_row_sum[warp * Int32(16) + gid] = row_l0 + s_row_sum[warp * Int32(16) + gid + Int32(8)] = row_l1 + cute.arch.sync_threads() + + tot_l0 = Float32(s_row_sum[gid]) + Float32(s_row_sum[Int32(16) + gid]) + Float32(s_row_sum[Int32(32) + gid]) + Float32(s_row_sum[Int32(48) + gid]) + tot_l1 = Float32(s_row_sum[gid + Int32(8)]) + Float32(s_row_sum[Int32(24) + gid]) + Float32(s_row_sum[Int32(40) + gid]) + Float32(s_row_sum[Int32(56) + gid]) + inv_l0 = cutlass.select_(tot_l0 > Float32(0.0), v_scale_val / tot_l0, Float32(0.0)) + inv_l1 = cutlass.select_(tot_l1 > Float32(0.0), v_scale_val / tot_l1, Float32(0.0)) + + h0_abs = kv_head * Int32(self.heads_per_kv) + gid + h1_abs = kv_head * Int32(self.heads_per_kv) + gid + Int32(8) + row64 = row.to(Int64) + for nt in cutlass.range_constexpr(8): + c0 = warp * Int32(64) + Int32(nt * 8) + tid * Int32(2) + c1 = c0 + Int32(1) + if h0_ok: + base0 = (row64 * Int64(self.q_heads) + h0_abs.to(Int64)) * Int64(self.head_dim) + output[base0 + c0.to(Int64)] = _gated_output(out_acc[nt, 0] * inv_l0, output_gate, row64, h0_abs.to(Int64), self.gate_stride) + output[base0 + c1.to(Int64)] = _gated_output(out_acc[nt, 1] * inv_l0, output_gate, row64, h0_abs.to(Int64), self.gate_stride) + if h1_ok: + base1 = (row64 * Int64(self.q_heads) + h1_abs.to(Int64)) * Int64(self.head_dim) + output[base1 + c0.to(Int64)] = _gated_output(out_acc[nt, 2] * inv_l1, output_gate, row64, h1_abs.to(Int64), self.gate_stride) + output[base1 + c1.to(Int64)] = _gated_output(out_acc[nt, 3] * inv_l1, output_gate, row64, h1_abs.to(Int64), self.gate_stride) + class _SelectedPositionPagedForwardKernel: """Paged-forward entry over caller-selected logical K/V positions.""" @@ -1383,6 +1896,29 @@ def __call__( _MERGE_KERNEL = _ShapeAdaptiveSparseGqaMergeKernel +def _use_fp8_tensor_core( + *, + direct_output: bool, + return_lse: bool, + kv_dtype: torch.dtype, + head_dim: int, + selection_groups: int, + first_position: int, + q_heads: int, + kv_heads: int, +) -> bool: + return ( + paged_control("B12X_SELECTED_FORWARD_FP8", "0") == "1" + and bool(direct_output) + and not bool(return_lse) + and kv_dtype == torch.float8_e4m3fn + and int(head_dim) == 256 + and int(selection_groups) == 1 + and int(first_position) < 0 + and (int(q_heads) // int(kv_heads)) <= 16 + ) + + def _cache_key( query: torch.Tensor, key_cache: torch.Tensor, @@ -1400,6 +1936,17 @@ def _cache_key( device_index = query.device.index if device_index is None: device_index = torch.cuda.current_device() + eff_return_lse = bool(return_lse) if direct_output else True + use_fp8_tc = _use_fp8_tensor_core( + direct_output=direct_output, + return_lse=eff_return_lse, + kv_dtype=key_cache.dtype, + head_dim=int(query.shape[-1]), + selection_groups=selection_groups, + first_position=first_position, + q_heads=int(query.shape[1]), + kv_heads=int(key_cache.shape[2]), + ) return ( int(device_index), int(query.shape[1]), @@ -1410,13 +1957,14 @@ def _cache_key( tuple(map(int, key_cache.stride()[:3])), tuple(map(int, value_cache.stride()[:3])), bool(direct_output), - bool(return_lse) if direct_output else True, + eff_return_lse, int(kv_warps), int(selection_width), int(query.shape[-1]), int(selection_groups), int(first_position), int(gate_stride) if direct_output else -1, + use_fp8_tc, ) @@ -1489,25 +2037,38 @@ def _compile( selection_groups, first_position, gate_stride, + use_fp8_tc, ) = key request_id_type = Int32 if request_id_bits == 32 else Int64 kv_type = Float8E4M3FN if kv_dtype == torch.float8_e4m3fn else BFloat16 - kernel = _SelectedPositionPagedForwardKernel( - q_heads=q_heads, - kv_heads=kv_heads, - kv_is_fp8=kv_dtype == torch.float8_e4m3fn, - direct_output=direct_output, - return_lse=return_lse, - kv_warps=kv_warps, - page_size=page_size, - key_strides=key_strides, - value_strides=value_strides, - selection_width=selection_width, - head_dim=head_dim, - selection_groups=selection_groups, - first_position=first_position, - gate_stride=gate_stride, - ) + if use_fp8_tc: + kernel = _FP8SelectedPositionPagedForwardKernel( + q_heads=q_heads, + kv_heads=kv_heads, + page_size=page_size, + key_strides=key_strides, + value_strides=value_strides, + selection_width=selection_width, + head_dim=head_dim, + gate_stride=gate_stride, + ) + else: + kernel = _SelectedPositionPagedForwardKernel( + q_heads=q_heads, + kv_heads=kv_heads, + kv_is_fp8=kv_dtype == torch.float8_e4m3fn, + direct_output=direct_output, + return_lse=return_lse, + kv_warps=kv_warps, + page_size=page_size, + key_strides=key_strides, + value_strides=value_strides, + selection_width=selection_width, + head_dim=head_dim, + selection_groups=selection_groups, + first_position=first_position, + gate_stride=gate_stride, + ) with torch.cuda.device(key[0]): raise_if_kernel_resolution_frozen( "cute.compile", @@ -1542,8 +2103,10 @@ def _compile( Int32(1), current_cuda_stream(), compile_spec=KernelCompileSpec.from_key( - "attention.paged.selected_forward", - 7, + "attention.paged.selected_forward_fp8" + if use_fp8_tc + else "attention.paged.selected_forward", + 1 if use_fp8_tc else 7, ( q_heads, kv_heads, diff --git a/tests/experimental/b12x/attention/test_qsa_sparse_gqa.py b/tests/experimental/b12x/attention/test_qsa_sparse_gqa.py index 6451e82f954..4d6bc51b4be 100644 --- a/tests/experimental/b12x/attention/test_qsa_sparse_gqa.py +++ b/tests/experimental/b12x/attention/test_qsa_sparse_gqa.py @@ -1687,3 +1687,189 @@ def test_sparse_gqa_uses_int64_for_high_physical_page_offsets( .expand(rows, -1, -1) ) torch.testing.assert_close(actual, expected, rtol=0.0, atol=0.0) + + +@pytest.mark.parametrize("use_gate", [False, True]) +def test_selected_forward_fp8_tensor_core_opt_in_matches_bf16( + use_gate: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from b12x.attention.paged import _selected_forward as sf + from b12x.attention.paged._controls import paged_controls + + device = require_sm120() + torch.manual_seed(20261129) + rows, q_heads, kv_heads, head_dim = 16, 12, 1, 256 + page_size, num_pages, sel_width = 64, 64, 2051 + total_tokens = num_pages * page_size + + q = torch.randn((rows, q_heads, head_dim), dtype=torch.bfloat16, device=device) + k_fp32 = torch.randn( + (num_pages, page_size, kv_heads, head_dim), dtype=torch.float32, device=device + ) + v_fp32 = torch.randn( + (num_pages, page_size, kv_heads, head_dim), dtype=torch.float32, device=device + ) + k_descale = torch.tensor([0.0625], dtype=torch.float32, device=device) + v_descale = torch.tensor([0.03125], dtype=torch.float32, device=device) + k_cache = (k_fp32 / k_descale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn) + v_cache = (v_fp32 / v_descale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn) + + block_table = torch.arange(num_pages, dtype=torch.int32, device=device).view(1, -1) + request_ids = torch.zeros((rows,), dtype=torch.int32, device=device) + request_ids[-1] = -1 # verify padding row zeroes out cleanly + query_positions = torch.full( + (rows,), total_tokens - 1, dtype=torch.int64, device=device + ) + selected_positions = torch.randint( + 0, total_tokens, (rows, sel_width), dtype=torch.int32, device=device + ) + selected_positions[:, 1200:] = -1 # exercise partially filled & empty tiles + output_gate = ( + torch.randn((rows, q_heads), dtype=torch.bfloat16, device=device) + if use_gate + else None + ) + scale = 1.0 / math.sqrt(head_dim) + + compiled_targets: list[type] = [] + orig_compile = sf.b12x_compile + + def traced_compile(kernel, *args, **kwargs): + compiled_targets.append(type(kernel)) + return orig_compile(kernel, *args, **kwargs) + + monkeypatch.setattr(sf, "_KERNEL_CACHE", {}) + monkeypatch.setattr(sf, "_WARMED", {}) + monkeypatch.setattr(sf, "b12x_compile", traced_compile) + + out_bf16 = torch.empty_like(q) + out_fp8 = torch.empty_like(q) + + with paged_controls({"B12X_SELECTED_FORWARD_FP8": "0"}): + sf.launch_selected_paged_gqa_direct( + query=q, + key_cache=k_cache, + value_cache=v_cache, + k_descale=k_descale, + v_descale=v_descale, + block_table=block_table, + request_ids=request_ids, + selected_positions=selected_positions, + query_positions=query_positions, + output=out_bf16, + output_lse=None, + softmax_scale=scale, + kv_warps=2, + output_gate=output_gate, + ) + assert compiled_targets == [sf._SelectedPositionPagedForwardKernel] + + # A warm stock entry must not satisfy the capture guard for a cold FP8 key. + with paged_controls({"B12X_SELECTED_FORWARD_FP8": "1"}): + with monkeypatch.context() as mp: + mp.setattr(torch.cuda, "is_current_stream_capturing", lambda: True) + with pytest.raises( + RuntimeError, + match="must be compiled and warm-run before CUDA graph capture", + ): + sf.launch_selected_paged_gqa_direct( + query=q, + key_cache=k_cache, + value_cache=v_cache, + k_descale=k_descale, + v_descale=v_descale, + block_table=block_table, + request_ids=request_ids, + selected_positions=selected_positions, + query_positions=query_positions, + output=out_fp8, + output_lse=None, + softmax_scale=scale, + kv_warps=2, + output_gate=output_gate, + ) + + with paged_controls({"B12X_SELECTED_FORWARD_FP8": "1"}): + sf.launch_selected_paged_gqa_direct( + query=q, + key_cache=k_cache, + value_cache=v_cache, + k_descale=k_descale, + v_descale=v_descale, + block_table=block_table, + request_ids=request_ids, + selected_positions=selected_positions, + query_positions=query_positions, + output=out_fp8, + output_lse=None, + softmax_scale=scale, + kv_warps=2, + output_gate=output_gate, + ) + assert compiled_targets == [ + sf._SelectedPositionPagedForwardKernel, + sf._FP8SelectedPositionPagedForwardKernel, + ] + graph = torch.cuda.CUDAGraph() + out_replay = torch.empty_like(q) + with torch.cuda.graph(graph): + sf.launch_selected_paged_gqa_direct( + query=q, + key_cache=k_cache, + value_cache=v_cache, + k_descale=k_descale, + v_descale=v_descale, + block_table=block_table, + request_ids=request_ids, + selected_positions=selected_positions, + query_positions=query_positions, + output=out_replay, + output_lse=None, + softmax_scale=scale, + kv_warps=2, + output_gate=output_gate, + ) + out_replay.fill_(float("nan")) + graph.replay() + + # Verify 2-byte misaligned BF16 queries take the scalar fallback cleanly. + q_unaligned_buf = torch.empty( + (q.numel() + 1,), dtype=torch.bfloat16, device=device + ) + q_unaligned = q_unaligned_buf[1:].view_as(q) + q_unaligned.copy_(q) + assert q_unaligned.data_ptr() % 16 != 0 + out_unaligned = torch.empty_like(q) + sf.launch_selected_paged_gqa_direct( + query=q_unaligned, + key_cache=k_cache, + value_cache=v_cache, + k_descale=k_descale, + v_descale=v_descale, + block_table=block_table, + request_ids=request_ids, + selected_positions=selected_positions, + query_positions=query_positions, + output=out_unaligned, + output_lse=None, + softmax_scale=scale, + kv_warps=2, + output_gate=output_gate, + ) + + torch.cuda.synchronize(device) + torch.testing.assert_close(out_replay, out_fp8, rtol=0.0, atol=0.0) + torch.testing.assert_close(out_unaligned, out_fp8, rtol=0.0, atol=0.0) + assert torch.count_nonzero(out_fp8[-1]) == 0 + live_ref = out_bf16[:-1].float().reshape(-1) + live_fp8 = out_fp8[:-1].float().reshape(-1) + cos = torch.nn.functional.cosine_similarity( + live_ref.unsqueeze(0), live_fp8.unsqueeze(0) + ).item() + rel_l2 = ( + torch.linalg.vector_norm(live_fp8 - live_ref) + / torch.linalg.vector_norm(live_ref) + ).item() + assert cos >= 0.999, f"expected cosine similarity >= 0.999, got {cos}" + assert rel_l2 <= 0.06, f"expected relative L2 error <= 0.06, got {rel_l2}"