[Cute,Fwd,Sm90] Faster FP8-KV head_dim 512 attention forward on Hopper #223
GROQ_API_KEY / GROQ_API_KEY_backup in .env
@@ -3796,3 +3797,1389 @@ def warp_scheduler_barrier_arrive(self):
barrier_id=int(NamedBarrierFwd.WarpSchedulerWG1) + next_wg,
number_of_threads=2 * self.num_threads_per_warp_group,
)
+
+
+# FlashAttentionForwardSm90Fp8KV: SM90 forward for FP8 (E4M3) paged K/V with head_dim 512.
+#
+# One CTA handles one (tile_m = 64)-row Q tile with four warp groups:
+# - warp group 0, producer: TMA (or cp.async) Q, TMA K and V pages into two slots each.
+# - warp groups 1-2, PV: quantize Q into two E4M3 terms, then compute O^T = V^T P^T with FP16
+# WGMMA. Each owns half of head_dim. A = V^T is read from the E4M3 V tile with
+# ldmatrix.trans and widened to FP16, which is exact; B = P comes from shared memory.
+# - warp group 3, softmax: S = Q K^T as FP8 WGMMA of both Q terms, online softmax with a lazy
+# row max, then FP16 P and its row rescales into one of two shared memory slots.
+# O is written straight from the PV registers: the output dtype, or FP32 partials with SplitKV.
+
+
+class Fp8KVDescaleTensors(NamedTuple):
+ """Per-(batch, kv_head) FP32 descales; any slot may be None, which means 1.
+
+ Rebuilds each present slot in place, so a missing slot does not shift the later ones.
+ """
+
+ q_descale: Optional[cute.Tensor] = None
+ k_descale: Optional[cute.Tensor] = None
+ v_descale: Optional[cute.Tensor] = None
+
+ def __new_from_mlir_values__(self, values):
+ values = iter(values)
+ return Fp8KVDescaleTensors(*(next(values) if t is not None else None for t in self))
+
+
+class FlashAttentionForwardSm90Fp8KV(FlashAttentionForwardSm90):
+ """SM90 forward for BF16/FP16 Q with paged E4M3 K/V, head_dim = head_dim_v = 512.
+
+ Supported: varlen Q (cu_seqlens_q, no seqused_q), paged K/V with page_size == tile_n == 64
+ and seqused_k, causal, local, softcap (as score_mod), learnable sink, SplitKV, pack_gqa,
+ and q/k/v descales of shape (batch, num_heads_kv). Not supported: mask_mod, block
+ sparsity, dynamic causal, aux tensors, output_scale.
+
+ Accuracy: Q becomes hi + res, two E4M3 terms at a fixed scale of 1 (see
+ utils.e4m3_hi_res_x8 for the exact range). QK runs as FP8 WGMMA, which sums below FP32.
+ P is FP16, scaled by 2^max_offset, and V is widened exactly from E4M3 to FP16.
+ """
+
+ # Lazy row max: the reference max is raised only when a row max grows by more than
+ # 2^rescale_threshold, so most blocks skip the O rescale; P then stays below
+ # 2^rescale_threshold. P is stored as P * 2^max_offset so that small probabilities stay
+ # FP16 normal; see Note [Low Precision Scaling] in flash_fwd_sm100.py.
+ rescale_threshold = 8.0
+ max_offset = 7
+
+ def __init__(
+ self,
+ dtype,
+ head_dim: int,
+ head_dim_v: int,
+ qhead_per_kvhead: int,
+ *,
+ is_causal: bool = False,
+ is_local: bool = False,
+ is_split_kv: bool = False,
+ pack_gqa: bool = True,
+ tile_m: int = 64,
+ tile_n: int = 64,
+ score_mod: Optional[cutlass.Constexpr] = None,
+ kv_dtype=cutlass.Float8E4M3FN,
+ ):
+ self.use_tma_Q = not (pack_gqa and tile_m % qhead_per_kvhead != 0)
+ # Register split per thread (4 warp groups x 128 threads share 64K registers). A
+ # cp.async Q load runs on all 128 producer threads and needs more producer registers.
+ if self.use_tma_Q:
+ producer_regs, self.num_softmax_regs = 24, 152
+ else:
+ producer_regs, self.num_softmax_regs = 40, 136
+ pv_regs = 168
+ super().__init__(
+ dtype,
+ head_dim,
+ head_dim_v,
+ qhead_per_kvhead,
+ is_causal=is_causal,
+ is_local=is_local,
+ pack_gqa=pack_gqa,
+ tile_m=tile_m,
+ tile_n=tile_n,
+ num_stages=1,
+ Q_in_regs=False,
+ score_mod=score_mod,
+ intra_wg_overlap=True,
+ mma_pv_is_rs=True,
+ is_split_kv=is_split_kv,
+ kv_dtype=kv_dtype,
+ fp8_kv_dequant=True,
+ registers=Sm90Registers(mma=pv_regs, producer=producer_regs),
+ )
+ assert dtype == Float16, "P and the PV WGMMA use FP16"
+ assert kv_dtype == cutlass.Float8E4M3FN, "K/V must be E4M3"
+ assert self.tile_hdim == self.tile_hdimv == 512 and not self.check_hdim_oob
+ assert tile_m == 64 and tile_n == 64, "one 64 x 64 WGMMA tile per QK and per P slot"
+ assert self.max_offset + self.rescale_threshold < math.log2(65504.0)
+
+ self.num_threads_per_warp_group = 128
+ self.num_pv_warp_groups = 2
+ self.num_pv_threads = self.num_pv_warp_groups * self.num_threads_per_warp_group
+ self.num_softmax_threads = self.num_threads_per_warp_group
+ self.num_threads = (
+ self.num_threads_per_warp_group + self.num_pv_threads + (self.num_softmax_threads)
+ )
+ assert producer_regs + self.num_pv_warp_groups * pv_regs + self.num_softmax_regs <= (
+ 65536 // self.num_threads_per_warp_group
+ )
+ # Threads in the hand-off barriers between the softmax and the PV warp groups.
+ self.num_handoff_threads = self.num_pv_threads + self.num_softmax_threads
+ self.num_producer_threads = 32
+ self.num_Q_load_threads = self.num_threads_per_warp_group
+ self.num_epilogue_threads = self.num_pv_threads
+ # Head-dim columns per PV warp group and 64-row WGMMA M tiles in each.
+ self.hdim_per_pv_wg = self.tile_hdimv // self.num_pv_warp_groups
+ self.num_pv_m_tiles = self.hdim_per_pv_wg // 64
+ # PV WGMMA groups kept in flight while the next V^T fragment is converted.
+ self.pv_wgmma_window = 2
+ # K and V each use two shared memory slots.
+ self.num_kv_slots = 2
+
+ def _get_tiled_mma(self):
+ # QK: the two K-mode slices of this tiled MMA partition interleaved head_dim halves.
+ # The softmax warp group issues both halves itself into separate accumulators.
+ tiled_mma_qk = sm90_utils_basic.make_trivial_tiled_mma(
+ self.kv_dtype,
+ self.kv_dtype,
+ warpgroup.OperandMajorMode.K,
+ warpgroup.OperandMajorMode.K,
+ Float32,
+ atom_layout_mnk=(self.tile_m // 64, 1, 2),
+ tiler_mn=(64, self.tile_n),
+ )
+ # PV, per warp group and 64 head_dim rows: O^T (hd, q) += V^T (hd, key) P^T (key, q).
+ tiled_mma_pv = sm90_utils_basic.make_trivial_tiled_mma(
+ self.dtype,
+ self.dtype,
+ warpgroup.OperandMajorMode.K,
+ warpgroup.OperandMajorMode.K,
+ Float32,
+ atom_layout_mnk=(1, 1, 1),
+ tiler_mn=(64, self.tile_m),
+ a_source=warpgroup.OperandSource.RMEM,
+ )
+ # Ownership of the (tile_m, head_dim_v) output: one head_dim half per PV warp group.
+ # Not issued; the epilogue writes LSE through its C partition and each PV thread reads
+ # its LSE rows through the same partition.
+ tiled_mma_o = sm90_utils_basic.make_trivial_tiled_mma(
+ self.dtype,
+ self.dtype,
+ warpgroup.OperandMajorMode.K,
+ warpgroup.OperandMajorMode.MN,
+ Float32,
+ atom_layout_mnk=(self.tile_m // 64, self.num_pv_warp_groups, 1),
+ tiler_mn=(64, self.hdim_per_pv_wg),
+ a_source=warpgroup.OperandSource.RMEM,
+ )
+ return tiled_mma_qk, tiled_mma_pv, tiled_mma_o
+
+ def _get_shared_storage_cls(self):
+ align = self.buffer_align_bytes
+
+ @cute.struct
+ class SharedStorage:
+ # The Q input; after quantization it holds Q_res, then Q_hi.
+ sQ: cute.struct.Align[
+ cute.struct.MemRange[self.q_dtype, cute.cosize(self.sQ_layout)], align
+ ]
+ sK: cute.struct.Align[
+ cute.struct.MemRange[self.kv_dtype, cute.cosize(self.sK_layout)], align
+ ]
+ sV: cute.struct.Align[
+ cute.struct.MemRange[self.kv_dtype, cute.cosize(self.sV_layout)], align
+ ]
+ sP: cute.struct.Align[
+ cute.struct.MemRange[self.dtype, cute.cosize(self.sP_layout)], align
+ ]
+ # Per P slot: the online-softmax row rescales and one changed flag per softmax warp.
+ sRowScale: cute.struct.Align[
+ cute.struct.MemRange[Float32, self.tile_m * self.num_kv_slots], 128
+ ]
+ sRowScaleChanged: cute.struct.MemRange[Int32, 4 * self.num_kv_slots]
+ # Final per-row output scales and LSE.
+ sFinalScale: cute.struct.MemRange[Float32, self.tile_m]
+ sLSE: cute.struct.MemRange[Float32, self.tile_m]
+ mbar_ptr_Q: cute.struct.MemRange[cutlass.Int64, 2]
+ mbar_ptr_K: cute.struct.MemRange[cutlass.Int64, self.num_kv_slots * 2]
+ mbar_ptr_V: cute.struct.MemRange[cutlass.Int64, self.num_kv_slots * 2]
+
+ return SharedStorage
+
+ @cute.jit
+ def __call__(
+ self,
+ mQ: cute.Tensor, # (total_q, h, d)
+ mK: cute.Tensor, # (num_pages, page_size, h_k, d)
+ mV: cute.Tensor, # (num_pages, page_size, h_k, dv)
+ mO: cute.Tensor, # (total_q, h, dv), or (num_splits, total_q, h, dv) FP32 with SplitKV
+ mLSE: Optional[cute.Tensor],
+ softmax_scale: Float32,
+ mCuSeqlensQ: Optional[cute.Tensor] = None,
+ mCuSeqlensK: Optional[cute.Tensor] = None,
+ mSeqUsedQ: Optional[cute.Tensor] = None,
+ mSeqUsedK: Optional[cute.Tensor] = None,
+ mDynamicCausal: Optional[cute.Tensor] = None,
+ mPageTable: Optional[cute.Tensor] = None, # (b, max_num_pages_per_seq)
+ window_size_left: Int32 | int | None = None,
+ window_size_right: Int32 | int | None = None,
+ learnable_sink: Optional[cute.Tensor] = None,
+ blocksparse_tensors: Optional[BlockSparseTensors] = None,
+ aux_data: AuxData = AuxData(),
+ descale_tensors: Optional[Fp8KVDescaleTensors] = None,
+ output_scale: Optional[cute.Tensor] = None,
+ mCuTotalMBlocks: Optional[cute.Tensor] = None,
+ mCuTotalSplitsMBlocks: Optional[cute.Tensor] = None,
+ tensormap_workspace: Optional[cute.Tensor] = None,
+ # Always keep stream as the last parameter (EnvStream: obtained implicitly via TVM FFI).
+ stream: cuda.CUstream = None,
+ ):
+ """Launch the kernel. Same positional signature as FlashAttentionForwardSm90."""
+ assert mCuSeqlensQ is not None and mSeqUsedQ is None, "varlen Q through cu_seqlens_q"
+ assert mPageTable is not None and mCuSeqlensK is None, "paged K/V only"
+ assert mDynamicCausal is None, "dynamic causal is not supported"
+ assert blocksparse_tensors is None, "block sparsity is not supported"
+ assert self.mask_mod is None, "mask_mod is not supported"
+ assert aux_data.tensors is None, "aux tensors are not supported"
+ assert output_scale is None, "fused output quantization is not supported"
+ assert mQ.element_type in (Float16, BFloat16), "Q must be fp16 or bf16"
+ assert mK.element_type == self.kv_dtype and mV.element_type == self.kv_dtype
+ if const_expr(self.is_split_kv):
+ assert mO.element_type == Float32, "SplitKV writes FP32 partials"
+ else:
+ assert mO.element_type in (Float16, BFloat16), "O must be fp16 or bf16"
+ self.q_dtype = mQ.element_type
+ self.o_dtype = mO.element_type
+ self.varlen_q = True
+ self.use_tma_O = False # O is stored from registers
+ self.use_block_sparsity = False
+
+ mQ, mK, mV, mO = [assume_tensor_aligned(t) for t in (mQ, mK, mV, mO)]
+ # (total_q, h, d) -> (total_q, d, h); paged K/V -> (page_size, d, h_k, num_pages).
+ mQ = layout_utils.select(mQ, [0, 2, 1])
+ num_splits = Int32(1)
+ if const_expr(not self.is_split_kv):
+ mO = layout_utils.select(mO, [0, 2, 1])
+ mLSE = layout_utils.select(mLSE, [1, 0]) if const_expr(mLSE is not None) else None
+ else:
+ num_splits = mO.shape[0]
+ mO = layout_utils.select(mO, [1, 3, 2, 0])
+ mLSE = layout_utils.select(mLSE, [2, 1, 0]) if const_expr(mLSE is not None) else None
+ mK, mV = [layout_utils.select(t, [1, 3, 2, 0]) for t in (mK, mV)]
+
+ tiled_mma_qk, tiled_mma_pv, tiled_mma_o = self._get_tiled_mma()
+ self._setup_attributes()
+ self.sQ_layout = sm90_utils.make_smem_layout(
+ self.q_dtype, LayoutEnum.ROW_MAJOR, (self.tile_m, self.tile_hdim), None
+ )
+ # Q_res and Q_hi: two E4M3 tiles that reuse the Q input bytes.
+ self.sQ_fp8_layout = sm90_utils.make_smem_layout(
+ self.kv_dtype, LayoutEnum.ROW_MAJOR, (self.tile_m, self.tile_hdim), None
+ )
+ self.sK_layout = sm90_utils.make_smem_layout(
+ self.kv_dtype, LayoutEnum.ROW_MAJOR, (self.tile_n, self.tile_hdim), self.num_kv_slots
+ )
+ self.sV_layout = sm90_utils.make_smem_layout(
+ self.kv_dtype, LayoutEnum.ROW_MAJOR, (self.tile_n, self.tile_hdimv), self.num_kv_slots
+ )
+ # FP16 P (query, key), one tile per slot: the K-major B operand of the PV WGMMA.
+ self.sP_layout = sm90_utils.make_smem_layout(
+ self.dtype, LayoutEnum.ROW_MAJOR, (self.tile_m, self.tile_n), self.num_kv_slots
+ )
+ q_fp8_bytes = cute.cosize(self.sQ_fp8_layout) * self.kv_dtype.width // 8
+ assert 2 * q_fp8_bytes <= cute.cosize(self.sQ_layout) * self.q_dtype.width // 8
+ # Q_hi starts q_fp8_bytes after Q_res; a whole number of swizzle periods keeps its
+ # swizzle phase equal to that of its own layout.
+ assert q_fp8_bytes % self.buffer_align_bytes == 0
+ SharedStorage = self._get_shared_storage_cls()
+
+ mQ_og = mQ
+ if const_expr(self.pack_gqa):
+ nheads_kv = mK.shape[2]
+ mQ = pack_gqa_layout(mQ, self.qhead_per_kvhead, nheads_kv, head_idx=2)
+ mO = pack_gqa_layout(mO, self.qhead_per_kvhead, nheads_kv, head_idx=2)
+ if const_expr(mLSE is not None):
+ mLSE = pack_gqa_layout(mLSE, self.qhead_per_kvhead, nheads_kv, head_idx=1)
+
+ self.tma_copy_bytes = {
+ name: cute.size_in_bytes(dtype, cute.select(layout, mode=[0, 1]))
+ for name, dtype, layout in [
+ ("Q", self.q_dtype, self.sQ_layout),
+ ("K", self.kv_dtype, self.sK_layout),
+ ("V", self.kv_dtype, self.sV_layout),
+ ]
+ }
+ tma_atom_Q = None
+ mQ_load = mQ
+ if const_expr(self.use_tma_Q):
+ make_tiled_tma_atom_fn = (
+ partial(
+ make_packgqa_tiled_tma_atom, qhead_per_kvhead=self.qhead_per_kvhead, head_idx=2
+ )
+ if const_expr(self.pack_gqa)
+ else cpasync.make_tiled_tma_atom
+ )
+ tma_atom_Q, mQ_load = make_tiled_tma_atom_fn(
+ cpasync.CopyBulkTensorTileG2SOp(),
+ mQ_og if const_expr(self.pack_gqa) else mQ,
+ self.sQ_layout,
+ (self.tile_m, self.tile_hdim),
+ )
+ tma_atom_K, mK_tma = cpasync.make_tiled_tma_atom(
+ cpasync.CopyBulkTensorTileG2SOp(),
+ mK,
+ cute.select(self.sK_layout, mode=[0, 1]),
+ (self.tile_n, self.tile_hdim),
+ 1,
+ )
+ tma_atom_V, mV_tma = cpasync.make_tiled_tma_atom(
+ cpasync.CopyBulkTensorTileG2SOp(),
+ mV,
+ cute.select(self.sV_layout, mode=[0, 1]),
+ (self.tile_n, self.tile_hdimv),
+ 1,
+ )
+
+ tile_sched_args = TileSchedulerArguments(
+ cute.ceil_div(cute.size(mQ.shape[0]), self.tile_m),
+ cute.size(mQ.shape[2]),
+ cute.size(mCuSeqlensQ.shape[0] - 1),
+ num_splits,
+ mK.shape[0] * mPageTable.shape[1],
+ mQ.shape[1],
+ mV.shape[1],
+ total_q=cute.size(mQ.shape[0]),
+ tile_shape_mn=(self.tile_m, self.tile_n),
+ mCuSeqlensQ=mCuSeqlensQ,
+ mSeqUsedQ=None,
+ qhead_per_kvhead_packgqa=self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1,
+ element_size=self.dtype.width // 8,
+ is_persistent=False,
+ lpt=self.is_causal or self.is_local,
+ is_split_kv=self.is_split_kv,
+ cu_total_m_blocks_ptr=mCuTotalMBlocks,
+ cu_total_splits_m_blocks_ptr=mCuTotalSplitsMBlocks,
+ )
+ tile_sched_params = SingleTileVarlenScheduler.to_underlying_arguments(tile_sched_args)
+ # The K/V slot parity (_kslot) restarts per tile: one tile per CTA.
+ assert tile_sched_params.scheduling_mode == SchedulingMode.STATIC
+ grid_dim = SingleTileVarlenScheduler.get_grid_shape(tile_sched_params)
+ softmax_scale_log2, softmax_scale = utils.compute_softmax_scale_log2(
+ softmax_scale, self.score_mod
+ )
+ window_size_left = Int32(window_size_left) if window_size_left is not None else None
+ window_size_right = Int32(window_size_right) if window_size_right is not None else None
+
+ self.kernel(
+ mQ_load,
+ mK_tma,
+ mV_tma,
+ mO,
+ mLSE,
+ mCuSeqlensQ,
+ mSeqUsedK,
+ mPageTable,
+ tma_atom_Q,
+ tma_atom_K,
+ tma_atom_V,
+ softmax_scale_log2,
+ softmax_scale,
+ window_size_left,
+ window_size_right,
+ learnable_sink,
+ self.sQ_layout,
+ self.sQ_fp8_layout,
+ self.sK_layout,
+ self.sV_layout,
+ self.sP_layout,
+ self.gmem_tiled_copy_Q,
+ tiled_mma_qk,
+ tiled_mma_pv,
+ tiled_mma_o,
+ tile_sched_params,
+ SingleTileVarlenScheduler,
+ SharedStorage,
+ num_splits,
+ aux_data,
+ descale_tensors,
+ ).launch(
+ grid=grid_dim,
+ block=[self.num_threads, 1, 1],
+ stream=stream,
+ min_blocks_per_mp=1,
+ )
+
+ @cute.kernel
+ def kernel(
+ self,
+ mQ: cute.Tensor,
+ mK: cute.Tensor,
+ mV: cute.Tensor,
+ mO: cute.Tensor,
+ mLSE: Optional[cute.Tensor],
+ mCuSeqlensQ: cute.Tensor,
+ mSeqUsedK: Optional[cute.Tensor],
+ mPageTable: cute.Tensor,
+ tma_atom_Q: Optional[cute.CopyAtom],
+ tma_atom_K: cute.CopyAtom,
+ tma_atom_V: cute.CopyAtom,
+ softmax_scale_log2: Float32,
+ softmax_scale: Optional[Float32],
+ window_size_left: Optional[Int32],
+ window_size_right: Optional[Int32],
+ learnable_sink: Optional[cute.Tensor],
+ sQ_layout: cute.ComposedLayout,
+ sQ_fp8_layout: cute.ComposedLayout,
+ sK_layout: cute.ComposedLayout,
+ sV_layout: cute.ComposedLayout,
+ sP_layout: cute.ComposedLayout,
+ gmem_tiled_copy_Q: cute.TiledCopy,
+ tiled_mma_qk: cute.TiledMma,
+ tiled_mma_pv: cute.TiledMma,
+ tiled_mma_o: cute.TiledMma,
+ tile_sched_params: ParamsBase,
+ TileScheduler: cutlass.Constexpr[Callable],
+ SharedStorage: cutlass.Constexpr[Callable],
+ num_splits: Int32,
+ aux_data: AuxData,
+ descale_tensors: Optional[Fp8KVDescaleTensors],
+ ):
+ warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+ if warp_idx == 0:
+ for tma_atom in (tma_atom_Q, tma_atom_K, tma_atom_V):
+ if const_expr(tma_atom is not None):
+ cpasync.prefetch_descriptor(tma_atom)
+
+ smem = cutlass.utils.SmemAllocator()
+ storage = smem.allocate(SharedStorage)
+
+ ThreadCooperativeGroup = partial(pipeline.CooperativeGroup, pipeline.Agent.Thread)
+ warp_size = cute.arch.WARP_SIZE
+ tma_warp = ThreadCooperativeGroup(1)
+ load_threads = ThreadCooperativeGroup(self.num_threads_per_warp_group)
+ pv_warps = ThreadCooperativeGroup(self.num_pv_threads // warp_size)
+ softmax_warps = ThreadCooperativeGroup(self.num_softmax_threads // warp_size)
+ # Q is consumed (quantized) by the PV warp groups.
+ if const_expr(self.use_tma_Q):
+ pipeline_q = pipeline_custom.PipelineTmaAsync.create(
+ barrier_storage=storage.mbar_ptr_Q.data_ptr(),
+ num_stages=1,
+ producer_group=tma_warp,
+ consumer_group=pv_warps,
+ tx_count=self.tma_copy_bytes["Q"],
+ defer_sync=True,
+ )
+ else:
+ pipeline_q = pipeline_custom.PipelineCpAsync.create(
+ barrier_storage=storage.mbar_ptr_Q.data_ptr(),
+ num_stages=1,
+ producer_group=load_threads,
+ consumer_group=pv_warps,
+ defer_sync=True,
+ elect_one_release=True,
+ syncwarp_before_release=False,
+ )
+ pipeline_k = pipeline_custom.PipelineTmaAsync.create(
+ barrier_storage=storage.mbar_ptr_K.data_ptr(),
+ num_stages=self.num_kv_slots,
+ producer_group=tma_warp,
+ consumer_group=softmax_warps,
+ tx_count=self.tma_copy_bytes["K"],
+ defer_sync=True,
+ )
+ pipeline_v = pipeline_custom.PipelineTmaAsync.create(
+ barrier_storage=storage.mbar_ptr_V.data_ptr(),
+ num_stages=self.num_kv_slots,
+ producer_group=tma_warp,
+ consumer_group=pv_warps,
+ tx_count=self.tma_copy_bytes["V"],
+ defer_sync=True,
+ )
+ pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True)
+
+ sQ = storage.sQ.get_tensor(sQ_layout.outer, swizzle=sQ_layout.inner)
+ sQ_res = storage.sQ.get_tensor(
+ sQ_fp8_layout.outer, swizzle=sQ_fp8_layout.inner, dtype=self.kv_dtype
+ )
+ sQ_hi = cute.make_tensor(sQ_res.iterator + cute.cosize(sQ_fp8_layout), sQ_res.layout)
+ sK = storage.sK.get_tensor(sK_layout.outer, swizzle=sK_layout.inner)
+ sV = storage.sV.get_tensor(sV_layout.outer, swizzle=sV_layout.inner)
+ sP = storage.sP.get_tensor(sP_layout.outer, swizzle=sP_layout.inner)
+ row_stats = (
+ storage.sRowScale.get_tensor(cute.make_layout((self.tile_m, self.num_kv_slots))),
+ storage.sRowScaleChanged.get_tensor(cute.make_layout((4, self.num_kv_slots))),
+ storage.sFinalScale.get_tensor(cute.make_layout(self.tile_m)),
+ storage.sLSE.get_tensor(cute.make_layout(self.tile_m)),
+ )
+
+ block_info = BlockInfo(
+ self.tile_m,
+ self.tile_n,
+ self.is_causal,
+ self.is_local,
+ self.is_split_kv,
+ window_size_left,
+ window_size_right,
+ qhead_per_kvhead_packgqa=self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1,
+ num_splits=num_splits,
+ )
+ SeqlenInfoCls = partial(
+ SeqlenInfoQK.create,
+ seqlen_q_static=mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1],
+ seqlen_k_static=mK.shape[0] * mPageTable.shape[1],
+ mCuSeqlensQ=mCuSeqlensQ,
+ mCuSeqlensK=None,
+ mSeqUsedQ=None,
+ mSeqUsedK=mSeqUsedK,
+ )
+ AttentionMaskCls = partial(
+ AttentionMask,
+ self.tile_m,
+ self.tile_n,
+ window_size_left=window_size_left,
+ window_size_right=window_size_right,
+ qhead_per_kvhead_packgqa=self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1,
+ )
+ TileSchedulerCls = partial(TileScheduler.create, tile_sched_params)
+
+ pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn)
+
+ warps_per_wg = self.num_threads_per_warp_group // warp_size
+ first_softmax_warp = warps_per_wg * (1 + self.num_pv_warp_groups)
+ tidx, _, _ = cute.arch.thread_idx()
+ if warp_idx < warps_per_wg:
+ cute.arch.setmaxregister_decrease(self.num_producer_regs)
+ self.load(
+ mQ,
+ mK,
+ mV,
+ sQ,
+ sK,
+ sV,
+ tma_atom_Q,
+ tma_atom_K,
+ tma_atom_V,
+ pipeline_q,
+ pipeline_k,
+ pipeline_v,
+ gmem_tiled_copy_Q,
+ mPageTable,
+ block_info,
+ SeqlenInfoCls,
+ TileSchedulerCls,
+ num_splits,
+ )
+ elif warp_idx >= first_softmax_warp:
+ cute.arch.setmaxregister_increase(self.num_softmax_regs)
+ self.softmax_wg(
+ tiled_mma_qk,
+ sQ_hi,
+ sQ_res,
+ sK,
+ sP,
+ row_stats,
+ learnable_sink,
+ pipeline_k,
+ tidx - first_softmax_warp * warp_size,
+ softmax_scale_log2,
+ softmax_scale,
+ block_info,
+ SeqlenInfoCls,
+ AttentionMaskCls,
+ TileSchedulerCls,
+ aux_data,
+ num_splits,
+ descale_tensors,
+ )
+ else:
+ cute.arch.setmaxregister_increase(self.num_mma_regs)
+ self.pv_wg(
+ tiled_mma_pv,
+ tiled_mma_o,
+ mO,
+ mLSE,
+ sQ,
+ sQ_hi,
+ sQ_res,
+ sV,
+ sP,
+ row_stats,
+ pipeline_q,
+ pipeline_v,
+ tidx - self.num_threads_per_warp_group,
+ block_info,
+ SeqlenInfoCls,
+ TileSchedulerCls,
+ num_splits,
+ )
+
+ @cute.jit
+ def _kslot(self, n_block, n_block_max):
+ """K (and V) slot of block n_block and its fill parity; fills run n_block_max - 1 down.
+
+ Requires 0 <= n_block < n_block_max.
+ """
+ return n_block & 1, ((n_block_max - 1 - n_block) >> 1) & 1
+
+ @cute.jit
+ def _block_range(self, block_info, seqlen, m_block, split_idx, num_splits):
+ """[n_block_min, n_block_max) of this tile, and whether it is empty. An empty range
+ becomes the single block 0 so that every role keeps one K and one V transaction; its
+ result is discarded."""
+ n_block_min, n_block_max = block_info.get_n_block_min_max(
+ seqlen, m_block, split_idx, num_splits
+ )
+ is_empty = n_block_min >= n_block_max
+ if is_empty:
+ n_block_min = Int32(0)
+ n_block_max = Int32(1)
+ return n_block_min, n_block_max, is_empty
+
+ # ///////////////////////////////////////////////////////////////////////////////////////
+ # Producer
+ # ///////////////////////////////////////////////////////////////////////////////////////
+
+ @cute.jit
+ def load(
+ self,
+ mQ: cute.Tensor,
+ mK: cute.Tensor,
+ mV: cute.Tensor,
+ sQ: cute.Tensor,
+ sK: cute.Tensor,
+ sV: cute.Tensor,
+ tma_atom_Q: Optional[cute.CopyAtom],
+ tma_atom_K: cute.CopyAtom,
+ tma_atom_V: cute.CopyAtom,
+ pipeline_q: pipeline.PipelineAsync,
+ pipeline_k: pipeline.PipelineAsync,
+ pipeline_v: pipeline.PipelineAsync,
+ gmem_tiled_copy_Q: cute.TiledCopy,
+ mPageTable: cute.Tensor,
+ block_info: BlockInfo,
+ SeqlenInfoCls: Callable,
+ TileSchedulerCls: Callable,
+ num_splits: Int32,
+ ):
+ """Q first (it is quantized before the first QK), then K[n_max - 1], then K[n] and
+ V[n + 1] for n descending, then V[n_min]. Each page index is read once."""
+ warp_idx_in_wg = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % 4
+ tidx, _, _ = cute.arch.thread_idx()
+ tile_scheduler = TileSchedulerCls()
+ work_tile = tile_scheduler.initial_work_tile_info()
+ if work_tile.is_valid_tile:
+ m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx
+ seqlen = SeqlenInfoCls(batch_idx)
+ head_idx_kv = (
+ head_idx // self.qhead_per_kvhead if const_expr(not self.pack_gqa) else head_idx
+ )
+ mQ_cur = seqlen.offset_batch_Q(mQ, batch_idx, dim=3)[None, None, head_idx]
+ if const_expr(self.use_tma_Q):
+ if warp_idx_in_wg == 0:
+ gQ = cute.local_tile(mQ_cur, (self.tile_m, self.tile_hdim), (m_block, 0))
+ load_Q, _, _ = copy_utils.tma_get_copy_fn(
+ tma_atom_Q, 0, cute.make_layout(1), gQ, sQ, single_stage=True
+ )
+ pipeline_q.producer_acquire_w_index_phase(0, Int32(1))
+ load_Q(tma_bar_ptr=pipeline_q.sync_object_full.get_barrier(0))
+ else:
+ # All 128 producer threads load Q with cp.async.
+ pack_gqa = PackGQA(
+ self.tile_m, self.tile_hdim, self.check_hdim_oob, self.qhead_per_kvhead
+ )
+ pipeline_q.producer_acquire_w_index_phase(0, Int32(1))
+ pack_gqa.load_Q(mQ_cur, sQ, gmem_tiled_copy_Q, tidx, m_block, seqlen.seqlen_q)
+ cute.arch.cp_async_commit_group()
+ pipeline_q.producer_commit_w_index(0)
+
+ n_block_min, n_block_max, is_empty = self._block_range(
+ block_info, seqlen, m_block, split_idx, num_splits
+ )
+ if warp_idx_in_wg == 0:
+ # Paged TMA tiles, page dimension indexable.
+ gK = cute.local_tile(
+ mK[None, None, head_idx_kv, None], (self.tile_n, self.tile_hdim), (0, 0, None)
+ )
+ gV = cute.local_tile(
+ mV[None, None, head_idx_kv, None], (self.tile_n, self.tile_hdimv), (0, 0, None)
+ )
+ load_K, _, _ = copy_utils.tma_get_copy_fn(
+ tma_atom_K, 0, cute.make_layout(1), gK, sK
+ )
+ load_V, _, _ = copy_utils.tma_get_copy_fn(
+ tma_atom_V, 0, cute.make_layout(1), gV, sV
+ )
+ issue = partial(self._issue_kv, n_block_max=n_block_max)
+ # An empty range reads physical page 0, a valid dummy source.
+ page = Int32(0)
+ if not is_empty:
+ page = mPageTable[batch_idx, n_block_max - 1]
+ issue(pipeline_k, load_K, n_block_max - 1, page)
+ for i in cutlass.range(n_block_max - 1 - n_block_min, unroll=1):
+ n_block = n_block_max - 2 - i
+ page_next = page
+ page = mPageTable[batch_idx, n_block]
+ issue(pipeline_k, load_K, n_block, page)
+ issue(pipeline_v, load_V, n_block + 1, page_next)
+ issue(pipeline_v, load_V, n_block_min, page)
+
+ @cute.jit
+ def _issue_kv(self, pipe, copy_fn, n_block, page, n_block_max):
+ """TMA K or V page `page` of block n_block into its slot."""
+ slot, phase = self._kslot(n_block, n_block_max)
+ pipe.producer_acquire_w_index_phase(slot, phase ^ 1)
+ copy_fn(src_idx=page, dst_idx=slot, tma_bar_ptr=pipe.sync_object_full.get_barrier(slot))
+
+ # ///////////////////////////////////////////////////////////////////////////////////////
+ # Softmax warp group
+ # ///////////////////////////////////////////////////////////////////////////////////////
+
+ @cute.jit
+ def softmax_wg(
+ self,
+ tiled_mma_qk: cute.TiledMma,
+ sQ_hi: cute.Tensor,
+ sQ_res: cute.Tensor,
+ sK: cute.Tensor,
+ sP: cute.Tensor,
+ row_stats: tuple,
+ learnable_sink: Optional[cute.Tensor],
+ pipeline_k: pipeline.PipelineAsync,
+ tidx: Int32,
+ softmax_scale_log2: Float32,
+ softmax_scale: Optional[Float32],
+ block_info: BlockInfo,
+ SeqlenInfoCls: Callable,
+ AttentionMaskCls: Callable,
+ TileSchedulerCls: Callable,
+ aux_data: AuxData,
+ num_splits: Int32,
+ descale_tensors: Optional[Fp8KVDescaleTensors],
+ ):
+ """QK and online softmax over all KV blocks of the tile; hands P and its row rescales
+ to the PV warp groups block by block, then the final row scales and LSE."""
+ sRowScale, sRowScaleChanged, sFinalScale, sLSE = row_stats
+ thr_mma_qk = tiled_mma_qk.get_slice(tidx)
+ # Q_res, Q_hi and K fragments of each head_dim half (K-mode slice of tiled_mma_qk).
+ qk_halves = []
+ for h in cutlass.range_constexpr(2):
+ wg_slice = tiled_mma_qk.get_slice(h * self.num_threads_per_warp_group)
+ _, tQhi, tK = sm90_utils.partition_fragment_ABC(
+ wg_slice, (self.tile_m, self.tile_n, self.tile_hdim), sQ_hi, sK
+ )
+ _, tQres, _ = sm90_utils.partition_fragment_ABC(
+ wg_slice, (self.tile_m, self.tile_n, self.tile_hdim), sQ_res, sK
+ )
+ qk_halves.append((tQres, tQhi, tK))
+ smem_thr_copy_P = cute.make_tiled_copy_C(
+ utils.get_smem_store_atom(self.arch.major * 10 + self.arch.minor, self.dtype),
+ tiled_mma_qk,
+ ).get_slice(tidx)
+ # (row, col) coordinate of each S element.
+ tScS = layout_utils.reshape_acc_to_mn(
+ thr_mma_qk.partition_C(cute.make_identity_tensor((self.tile_m, self.tile_n)))
+ )
+ sm = SimpleNamespace(
+ thr_mma_qk=thr_mma_qk,
+ qk_halves=qk_halves,
+ # Masked S of the block whose softmax is next.
+ S=cute.make_rmem_tensor(
+ tiled_mma_qk.partition_shape_C((self.tile_m, self.tile_n)), Float32
+ ),
+ smem_thr_copy_P=smem_thr_copy_P,
+ tPsP=smem_thr_copy_P.partition_D(sP),
+ is_col0=tScS[0][1] == 0,
+ sRowScale=sRowScale,
+ sRowScaleChanged=sRowScaleChanged,
+ warp=tidx // cute.arch.WARP_SIZE,
+ lane=tidx % cute.arch.WARP_SIZE,
+ )
+ num_rows = cute.size(tScS, mode=[0])
+
+ tile_scheduler = TileSchedulerCls()
+ work_tile = tile_scheduler.initial_work_tile_info()
+ if work_tile.is_valid_tile:
+ m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx
+ seqlen = SeqlenInfoCls(batch_idx)
+ head_idx_kv = (
+ head_idx // self.qhead_per_kvhead if const_expr(not self.pack_gqa) else head_idx
+ )
+ # q * k descales fold into the score scale, v into the final output scale.
+ qk_descale, v_descale = self._load_effective_descales(
+ descale_tensors, batch_idx, head_idx_kv
+ )
+ v_descale = v_descale / Float32(2**self.max_offset)
+ if const_expr(self.score_mod is None):
+ scale_log2_eff = softmax_scale_log2 * qk_descale
+ softmax_scale_eff = None
+ else:
+ scale_log2_eff = softmax_scale_log2
+ softmax_scale_eff = softmax_scale * qk_descale
+ softmax = Softmax.create(
+ scale_log2_eff, num_rows=num_rows, softmax_scale=softmax_scale_eff
+ )
+ mask = AttentionMaskCls(seqlen)
+ mask_fn = partial(
+ mask.apply_mask,
+ batch_idx=batch_idx,
+ head_idx=head_idx,
+ m_block=m_block,
+ thr_mma=thr_mma_qk,
+ mask_causal=self.is_causal,
+ mask_local=self.is_local,
+ aux_data=aux_data,
+ )
+ score_mod_fn = None
+ if const_expr(self.score_mod is not None):
+ score_mod_fn = partial(
+ self.apply_score_mod,
+ thr_mma_qk,
+ batch_idx,
+ head_idx,
+ m_block,
+ softmax_scale=softmax_scale_eff,
+ aux_data=aux_data,
+ )
+ n_block_min, n_block_max, is_empty = self._block_range(
+ block_info, seqlen, m_block, split_idx, num_splits
+ )
+ sink_val = None
+ if const_expr(learnable_sink is not None):
+ sink_val = self._load_sink(learnable_sink, tScS, m_block, head_idx, split_idx)
+ # Wait until the PV warp groups have written Q_hi and Q_res.
+ cute.arch.barrier(
+ barrier_id=int(NamedBarrierFwdSm90Fp8KV.QReady),
+ number_of_threads=self.num_handoff_threads,
+ )
+ nmax = n_block_max
+ # Block nmax - 1: both QK halves, then seed the reference max (the softmax of
+ # each block runs one step after its QK).
+ slot, phase = self._kslot(nmax - 1, nmax)
+ pipeline_k.consumer_wait_w_index_phase(slot, phase)
+ accs = []
+ for h in cutlass.range_constexpr(2):
+ accs.append(self._qk_half(tiled_mma_qk, sm, h, slot))
+ warpgroup.wait_group(0)
+ self._fold_s(
+ sm,
+ accs,
+ pipeline_k,
+ nmax - 1,
+ nmax,
+ seqlen,
+ partial(mask_fn, mask_mod=None, mask_seqlen=True),
+ score_mod_fn,
+ )
+ self._init_row_max(softmax, sm.S)
+ n_block_max -= 1
+ step = partial(
+ self._softmax_step,
+ tiled_mma_qk,
+ sm,
+ pipeline_k,
+ softmax,
+ seqlen,
+ score_mod_fn,
+ nmax,
+ )
+ if const_expr(self.is_causal or self.is_local):
+ n_block_min_causal_local_mask = block_info.get_n_block_min_causal_local_mask(
+ seqlen, m_block, n_block_min
+ )
+ for n_tile in cutlass.range(n_block_max - n_block_min_causal_local_mask, unroll=1):
+ step(
+ n_block_max - 1 - n_tile,
+ mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=False),
+ )
+ n_block_max = cutlass.min(n_block_max, n_block_min_causal_local_mask)
+ n_block_min_before_local_mask = block_info.get_n_block_min_before_local_mask(
+ seqlen, m_block, n_block_min
+ )
+ for n_tile in cutlass.range(n_block_max - n_block_min_before_local_mask, unroll=1):
+ step(n_block_max - 1 - n_tile, mask_fn=None)
+ if const_expr(self.is_local and block_info.window_size_left is not None):
+ n_block_max = cutlass.min(n_block_max, n_block_min_before_local_mask)
+ for n_tile in cutlass.range(n_block_max - n_block_min, unroll=1):
+ step(
+ n_block_max - 1 - n_tile,
+ mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=False),
+ )
+ # The last step stored P[n_block_min + 1] without signalling it.
+ if n_block_min + 1 < nmax:
+ self._signal_p(n_block_min + 1)
+ row_scale = self._online_softmax_lazy_max(softmax, sm.S)
+ self._publish_p(sm, row_scale, n_block_min, n_block_min < nmax - 2)
+ self._signal_p(n_block_min)
+ # The row sums hold sum(P * 2^max_offset): undo the power of two exactly.
+ softmax.row_sum.store(softmax.row_sum.load() * Float32(2.0**-self.max_offset))
+ final_scale = softmax.finalize(final_scale=v_descale, sink_val=sink_val)
[P2] Stabilize the sink contribution when using the lazy row maximum. Consider two 64-key blocks visited in order with scaled logits 0 and then 5, and a sink logit of 90. Since 5 is below the rescale threshold of 8 × ln(2), the reference maximum stays at 0. This call to finalize then evaluates exp(90), which overflows FP32 and gives an infinite LSE. The previous kernel advances the maximum to 5, so it evaluates exp(85) and returns an LSE of 90. Could you fold the sink into the normalizer using a stable common maximum and add this two-page case as a regression test?
@@ -2133,6 +2175,12 @@ def _flash_attn_fwd(
num_splits_dynamic_ptr=num_splits_dynamic,
virtual_batch_idx=virtual_batch_idx if has_scheduler_metadata else None,
output_scale=output_scale,
+ # The SM90 FP8-KV hd512 kernel's partials: PDL, and split groups past 16 splits.
+ **(
+ dict(split_groups=4 if num_splits > 16 else 1, use_pdl=True)
[P3] Trigger the dependent combine from the forward kernel. This enables programmatic dependent launch on the combine, but the new forward kernel never issues griddepcontrol_launch_dependents(). CUDA's implicit trigger fires after every forward CTA has exited, so combine setup cannot overlap the forward epilogue. Please issue the trigger from every forward CTA, including padding CTAs, early enough to allow that overlap. The existing combine-side wait should stay before the partial reads. CUDA programmatic dependent launch guide
Please address the attention-sink overflow and the missing forward-side trigger for SplitKV overlap. I checked the overflow with scalar FP32 arithmetic. I did not run the kernel on Hopper.
@@ -3796,3 +3797,1389 @@ def warp_scheduler_barrier_arrive(self):
barrier_id=int(NamedBarrierFwd.WarpSchedulerWG1) + next_wg,
number_of_threads=2 * self.num_threads_per_warp_group,
)
+
+
+# FlashAttentionForwardSm90Fp8KV: SM90 forward for FP8 (E4M3) paged K/V with head_dim 512.
+#
+# One CTA handles one (tile_m = 64)-row Q tile with four warp groups:
+# - warp group 0, producer: TMA (or cp.async) Q, TMA K and V pages into two slots each.
+# - warp groups 1-2, PV: quantize Q into two E4M3 terms, then compute O^T = V^T P^T with FP16
+# WGMMA. Each owns half of head_dim. A = V^T is read from the E4M3 V tile with
+# ldmatrix.trans and widened to FP16, which is exact; B = P comes from shared memory.
+# - warp group 3, softmax: S = Q K^T as FP8 WGMMA of both Q terms, online softmax with a lazy
+# row max, then FP16 P and its row rescales into one of two shared memory slots.
+# O is written straight from the PV registers: the output dtype, or FP32 partials with SplitKV.
+
+
+class Fp8KVDescaleTensors(NamedTuple):
+ """Per-(batch, kv_head) FP32 descales; any slot may be None, which means 1.
+
+ Rebuilds each present slot in place, so a missing slot does not shift the later ones.
+ """
+
+ q_descale: Optional[cute.Tensor] = None
+ k_descale: Optional[cute.Tensor] = None
+ v_descale: Optional[cute.Tensor] = None
+
+ def __new_from_mlir_values__(self, values):
+ values = iter(values)
+ return Fp8KVDescaleTensors(*(next(values) if t is not None else None for t in self))
+
+
+class FlashAttentionForwardSm90Fp8KV(FlashAttentionForwardSm90):
+ """SM90 forward for BF16/FP16 Q with paged E4M3 K/V, head_dim = head_dim_v = 512.
+
+ Supported: varlen Q (cu_seqlens_q, no seqused_q), paged K/V with page_size == tile_n == 64
+ and seqused_k, causal, local, softcap (as score_mod), learnable sink, SplitKV, pack_gqa,
+ and q/k/v descales of shape (batch, num_heads_kv). Not supported: mask_mod, block
+ sparsity, dynamic causal, aux tensors, output_scale.
+
+ Accuracy: Q becomes hi + res, two E4M3 terms at a fixed scale of 1 (see
+ utils.e4m3_hi_res_x8 for the exact range). QK runs as FP8 WGMMA, which sums below FP32.
+ P is FP16, scaled by 2^max_offset, and V is widened exactly from E4M3 to FP16.
+ """
+
+ # Lazy row max: the reference max is raised only when a row max grows by more than
+ # 2^rescale_threshold, so most blocks skip the O rescale; P then stays below
+ # 2^rescale_threshold. P is stored as P * 2^max_offset so that small probabilities stay
+ # FP16 normal; see Note [Low Precision Scaling] in flash_fwd_sm100.py.
+ rescale_threshold = 8.0
+ max_offset = 7
+
+ def __init__(
+ self,
+ dtype,
+ head_dim: int,
+ head_dim_v: int,
+ qhead_per_kvhead: int,
+ *,
+ is_causal: bool = False,
+ is_local: bool = False,
+ is_split_kv: bool = False,
+ pack_gqa: bool = True,
+ tile_m: int = 64,
+ tile_n: int = 64,
+ score_mod: Optional[cutlass.Constexpr] = None,
+ kv_dtype=cutlass.Float8E4M3FN,
+ ):
+ self.use_tma_Q = not (pack_gqa and tile_m % qhead_per_kvhead != 0)
+ # Register split per thread (4 warp groups x 128 threads share 64K registers). A
+ # cp.async Q load runs on all 128 producer threads and needs more producer registers.
+ if self.use_tma_Q:
+ producer_regs, self.num_softmax_regs = 24, 152
+ else:
+ producer_regs, self.num_softmax_regs = 40, 136
+ pv_regs = 168
+ super().__init__(
+ dtype,
+ head_dim,
+ head_dim_v,
+ qhead_per_kvhead,
+ is_causal=is_causal,
+ is_local=is_local,
+ pack_gqa=pack_gqa,
+ tile_m=tile_m,
+ tile_n=tile_n,
+ num_stages=1,
+ Q_in_regs=False,
+ score_mod=score_mod,
+ intra_wg_overlap=True,
+ mma_pv_is_rs=True,
+ is_split_kv=is_split_kv,
+ kv_dtype=kv_dtype,
+ fp8_kv_dequant=True,
+ registers=Sm90Registers(mma=pv_regs, producer=producer_regs),
+ )
+ assert dtype == Float16, "P and the PV WGMMA use FP16"
+ assert kv_dtype == cutlass.Float8E4M3FN, "K/V must be E4M3"
+ assert self.tile_hdim == self.tile_hdimv == 512 and not self.check_hdim_oob
+ assert tile_m == 64 and tile_n == 64, "one 64 x 64 WGMMA tile per QK and per P slot"
+ assert self.max_offset + self.rescale_threshold < math.log2(65504.0)
+
+ self.num_threads_per_warp_group = 128
+ self.num_pv_warp_groups = 2
+ self.num_pv_threads = self.num_pv_warp_groups * self.num_threads_per_warp_group
+ self.num_softmax_threads = self.num_threads_per_warp_group
+ self.num_threads = (
+ self.num_threads_per_warp_group + self.num_pv_threads + (self.num_softmax_threads)
+ )
+ assert producer_regs + self.num_pv_warp_groups * pv_regs + self.num_softmax_regs <= (
+ 65536 // self.num_threads_per_warp_group
+ )
+ # Threads in the hand-off barriers between the softmax and the PV warp groups.
+ self.num_handoff_threads = self.num_pv_threads + self.num_softmax_threads
+ self.num_producer_threads = 32
+ self.num_Q_load_threads = self.num_threads_per_warp_group
+ self.num_epilogue_threads = self.num_pv_threads
+ # Head-dim columns per PV warp group and 64-row WGMMA M tiles in each.
+ self.hdim_per_pv_wg = self.tile_hdimv // self.num_pv_warp_groups
+ self.num_pv_m_tiles = self.hdim_per_pv_wg // 64
+ # PV WGMMA groups kept in flight while the next V^T fragment is converted.
+ self.pv_wgmma_window = 2
+ # K and V each use two shared memory slots.
+ self.num_kv_slots = 2
+
+ def _get_tiled_mma(self):
+ # QK: the two K-mode slices of this tiled MMA partition interleaved head_dim halves.
+ # The softmax warp group issues both halves itself into separate accumulators.
+ tiled_mma_qk = sm90_utils_basic.make_trivial_tiled_mma(
+ self.kv_dtype,
+ self.kv_dtype,
+ warpgroup.OperandMajorMode.K,
+ warpgroup.OperandMajorMode.K,
+ Float32,
+ atom_layout_mnk=(self.tile_m // 64, 1, 2),
+ tiler_mn=(64, self.tile_n),
+ )
+ # PV, per warp group and 64 head_dim rows: O^T (hd, q) += V^T (hd, key) P^T (key, q).
+ tiled_mma_pv = sm90_utils_basic.make_trivial_tiled_mma(
+ self.dtype,
+ self.dtype,
+ warpgroup.OperandMajorMode.K,
+ warpgroup.OperandMajorMode.K,
+ Float32,
+ atom_layout_mnk=(1, 1, 1),
+ tiler_mn=(64, self.tile_m),
+ a_source=warpgroup.OperandSource.RMEM,
+ )
+ # Ownership of the (tile_m, head_dim_v) output: one head_dim half per PV warp group.
+ # Not issued; the epilogue writes LSE through its C partition and each PV thread reads
+ # its LSE rows through the same partition.
+ tiled_mma_o = sm90_utils_basic.make_trivial_tiled_mma(
+ self.dtype,
+ self.dtype,
+ warpgroup.OperandMajorMode.K,
+ warpgroup.OperandMajorMode.MN,
+ Float32,
+ atom_layout_mnk=(self.tile_m // 64, self.num_pv_warp_groups, 1),
+ tiler_mn=(64, self.hdim_per_pv_wg),
+ a_source=warpgroup.OperandSource.RMEM,
+ )
+ return tiled_mma_qk, tiled_mma_pv, tiled_mma_o
+
+ def _get_shared_storage_cls(self):
+ align = self.buffer_align_bytes
+
+ @cute.struct
+ class SharedStorage:
+ # The Q input; after quantization it holds Q_res, then Q_hi.
+ sQ: cute.struct.Align[
+ cute.struct.MemRange[self.q_dtype, cute.cosize(self.sQ_layout)], align
+ ]
+ sK: cute.struct.Align[
+ cute.struct.MemRange[self.kv_dtype, cute.cosize(self.sK_layout)], align
+ ]
+ sV: cute.struct.Align[
+ cute.struct.MemRange[self.kv_dtype, cute.cosize(self.sV_layout)], align
+ ]
+ sP: cute.struct.Align[
+ cute.struct.MemRange[self.dtype, cute.cosize(self.sP_layout)], align
+ ]
+ # Per P slot: the online-softmax row rescales and one changed flag per softmax warp.
+ sRowScale: cute.struct.Align[
+ cute.struct.MemRange[Float32, self.tile_m * self.num_kv_slots], 128
+ ]
+ sRowScaleChanged: cute.struct.MemRange[Int32, 4 * self.num_kv_slots]
+ # Final per-row output scales and LSE.
+ sFinalScale: cute.struct.MemRange[Float32, self.tile_m]
+ sLSE: cute.struct.MemRange[Float32, self.tile_m]
+ mbar_ptr_Q: cute.struct.MemRange[cutlass.Int64, 2]
+ mbar_ptr_K: cute.struct.MemRange[cutlass.Int64, self.num_kv_slots * 2]
+ mbar_ptr_V: cute.struct.MemRange[cutlass.Int64, self.num_kv_slots * 2]
+
+ return SharedStorage
+
+ @cute.jit
+ def __call__(
+ self,
+ mQ: cute.Tensor, # (total_q, h, d)
+ mK: cute.Tensor, # (num_pages, page_size, h_k, d)
+ mV: cute.Tensor, # (num_pages, page_size, h_k, dv)
+ mO: cute.Tensor, # (total_q, h, dv), or (num_splits, total_q, h, dv) FP32 with SplitKV
+ mLSE: Optional[cute.Tensor],
+ softmax_scale: Float32,
+ mCuSeqlensQ: Optional[cute.Tensor] = None,
+ mCuSeqlensK: Optional[cute.Tensor] = None,
+ mSeqUsedQ: Optional[cute.Tensor] = None,
+ mSeqUsedK: Optional[cute.Tensor] = None,
+ mDynamicCausal: Optional[cute.Tensor] = None,
+ mPageTable: Optional[cute.Tensor] = None, # (b, max_num_pages_per_seq)
+ window_size_left: Int32 | int | None = None,
+ window_size_right: Int32 | int | None = None,
+ learnable_sink: Optional[cute.Tensor] = None,
+ blocksparse_tensors: Optional[BlockSparseTensors] = None,
+ aux_data: AuxData = AuxData(),
+ descale_tensors: Optional[Fp8KVDescaleTensors] = None,
+ output_scale: Optional[cute.Tensor] = None,
+ mCuTotalMBlocks: Optional[cute.Tensor] = None,
+ mCuTotalSplitsMBlocks: Optional[cute.Tensor] = None,
+ tensormap_workspace: Optional[cute.Tensor] = None,
+ # Always keep stream as the last parameter (EnvStream: obtained implicitly via TVM FFI).
+ stream: cuda.CUstream = None,
+ ):
+ """Launch the kernel. Same positional signature as FlashAttentionForwardSm90."""
+ assert mCuSeqlensQ is not None and mSeqUsedQ is None, "varlen Q through cu_seqlens_q"
+ assert mPageTable is not None and mCuSeqlensK is None, "paged K/V only"
+ assert mDynamicCausal is None, "dynamic causal is not supported"
+ assert blocksparse_tensors is None, "block sparsity is not supported"
+ assert self.mask_mod is None, "mask_mod is not supported"
+ assert aux_data.tensors is None, "aux tensors are not supported"
+ assert output_scale is None, "fused output quantization is not supported"
+ assert mQ.element_type in (Float16, BFloat16), "Q must be fp16 or bf16"
+ assert mK.element_type == self.kv_dtype and mV.element_type == self.kv_dtype
+ if const_expr(self.is_split_kv):
+ assert mO.element_type == Float32, "SplitKV writes FP32 partials"
+ else:
+ assert mO.element_type in (Float16, BFloat16), "O must be fp16 or bf16"
+ self.q_dtype = mQ.element_type
+ self.o_dtype = mO.element_type
+ self.varlen_q = True
+ self.use_tma_O = False # O is stored from registers
+ self.use_block_sparsity = False
+
+ mQ, mK, mV, mO = [assume_tensor_aligned(t) for t in (mQ, mK, mV, mO)]
+ # (total_q, h, d) -> (total_q, d, h); paged K/V -> (page_size, d, h_k, num_pages).
+ mQ = layout_utils.select(mQ, [0, 2, 1])
+ num_splits = Int32(1)
+ if const_expr(not self.is_split_kv):
+ mO = layout_utils.select(mO, [0, 2, 1])
+ mLSE = layout_utils.select(mLSE, [1, 0]) if const_expr(mLSE is not None) else None
+ else:
+ num_splits = mO.shape[0]
+ mO = layout_utils.select(mO, [1, 3, 2, 0])
+ mLSE = layout_utils.select(mLSE, [2, 1, 0]) if const_expr(mLSE is not None) else None
+ mK, mV = [layout_utils.select(t, [1, 3, 2, 0]) for t in (mK, mV)]
+
+ tiled_mma_qk, tiled_mma_pv, tiled_mma_o = self._get_tiled_mma()
+ self._setup_attributes()
+ self.sQ_layout = sm90_utils.make_smem_layout(
+ self.q_dtype, LayoutEnum.ROW_MAJOR, (self.tile_m, self.tile_hdim), None
+ )
+ # Q_res and Q_hi: two E4M3 tiles that reuse the Q input bytes.
+ self.sQ_fp8_layout = sm90_utils.make_smem_layout(
+ self.kv_dtype, LayoutEnum.ROW_MAJOR, (self.tile_m, self.tile_hdim), None
+ )
+ self.sK_layout = sm90_utils.make_smem_layout(
+ self.kv_dtype, LayoutEnum.ROW_MAJOR, (self.tile_n, self.tile_hdim), self.num_kv_slots
+ )
+ self.sV_layout = sm90_utils.make_smem_layout(
+ self.kv_dtype, LayoutEnum.ROW_MAJOR, (self.tile_n, self.tile_hdimv), self.num_kv_slots
+ )
+ # FP16 P (query, key), one tile per slot: the K-major B operand of the PV WGMMA.
+ self.sP_layout = sm90_utils.make_smem_layout(
+ self.dtype, LayoutEnum.ROW_MAJOR, (self.tile_m, self.tile_n), self.num_kv_slots
+ )
+ q_fp8_bytes = cute.cosize(self.sQ_fp8_layout) * self.kv_dtype.width // 8
+ assert 2 * q_fp8_bytes <= cute.cosize(self.sQ_layout) * self.q_dtype.width // 8
+ # Q_hi starts q_fp8_bytes after Q_res; a whole number of swizzle periods keeps its
+ # swizzle phase equal to that of its own layout.
+ assert q_fp8_bytes % self.buffer_align_bytes == 0
+ SharedStorage = self._get_shared_storage_cls()
+
+ mQ_og = mQ
+ if const_expr(self.pack_gqa):
+ nheads_kv = mK.shape[2]
+ mQ = pack_gqa_layout(mQ, self.qhead_per_kvhead, nheads_kv, head_idx=2)
+ mO = pack_gqa_layout(mO, self.qhead_per_kvhead, nheads_kv, head_idx=2)
+ if const_expr(mLSE is not None):
+ mLSE = pack_gqa_layout(mLSE, self.qhead_per_kvhead, nheads_kv, head_idx=1)
+
+ self.tma_copy_bytes = {
+ name: cute.size_in_bytes(dtype, cute.select(layout, mode=[0, 1]))
+ for name, dtype, layout in [
+ ("Q", self.q_dtype, self.sQ_layout),
+ ("K", self.kv_dtype, self.sK_layout),
+ ("V", self.kv_dtype, self.sV_layout),
+ ]
+ }
+ tma_atom_Q = None
+ mQ_load = mQ
+ if const_expr(self.use_tma_Q):
+ make_tiled_tma_atom_fn = (
+ partial(
+ make_packgqa_tiled_tma_atom, qhead_per_kvhead=self.qhead_per_kvhead, head_idx=2
+ )
+ if const_expr(self.pack_gqa)
+ else cpasync.make_tiled_tma_atom
+ )
+ tma_atom_Q, mQ_load = make_tiled_tma_atom_fn(
+ cpasync.CopyBulkTensorTileG2SOp(),
+ mQ_og if const_expr(self.pack_gqa) else mQ,
+ self.sQ_layout,
+ (self.tile_m, self.tile_hdim),
+ )
+ tma_atom_K, mK_tma = cpasync.make_tiled_tma_atom(
+ cpasync.CopyBulkTensorTileG2SOp(),
+ mK,
+ cute.select(self.sK_layout, mode=[0, 1]),
+ (self.tile_n, self.tile_hdim),
+ 1,
+ )
+ tma_atom_V, mV_tma = cpasync.make_tiled_tma_atom(
+ cpasync.CopyBulkTensorTileG2SOp(),
+ mV,
+ cute.select(self.sV_layout, mode=[0, 1]),
+ (self.tile_n, self.tile_hdimv),
+ 1,
+ )
+
+ tile_sched_args = TileSchedulerArguments(
+ cute.ceil_div(cute.size(mQ.shape[0]), self.tile_m),
+ cute.size(mQ.shape[2]),
+ cute.size(mCuSeqlensQ.shape[0] - 1),
+ num_splits,
+ mK.shape[0] * mPageTable.shape[1],
+ mQ.shape[1],
+ mV.shape[1],
+ total_q=cute.size(mQ.shape[0]),
+ tile_shape_mn=(self.tile_m, self.tile_n),
+ mCuSeqlensQ=mCuSeqlensQ,
+ mSeqUsedQ=None,
+ qhead_per_kvhead_packgqa=self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1,
+ element_size=self.dtype.width // 8,
+ is_persistent=False,
+ lpt=self.is_causal or self.is_local,
+ is_split_kv=self.is_split_kv,
+ cu_total_m_blocks_ptr=mCuTotalMBlocks,
+ cu_total_splits_m_blocks_ptr=mCuTotalSplitsMBlocks,
+ )
+ tile_sched_params = SingleTileVarlenScheduler.to_underlying_arguments(tile_sched_args)
+ # The K/V slot parity (_kslot) restarts per tile: one tile per CTA.
+ assert tile_sched_params.scheduling_mode == SchedulingMode.STATIC
+ grid_dim = SingleTileVarlenScheduler.get_grid_shape(tile_sched_params)
+ softmax_scale_log2, softmax_scale = utils.compute_softmax_scale_log2(
+ softmax_scale, self.score_mod
+ )
+ window_size_left = Int32(window_size_left) if window_size_left is not None else None
+ window_size_right = Int32(window_size_right) if window_size_right is not None else None
+
+ self.kernel(
+ mQ_load,
+ mK_tma,
+ mV_tma,
+ mO,
+ mLSE,
+ mCuSeqlensQ,
+ mSeqUsedK,
+ mPageTable,
+ tma_atom_Q,
+ tma_atom_K,
+ tma_atom_V,
+ softmax_scale_log2,
+ softmax_scale,
+ window_size_left,
+ window_size_right,
+ learnable_sink,
+ self.sQ_layout,
+ self.sQ_fp8_layout,
+ self.sK_layout,
+ self.sV_layout,
+ self.sP_layout,
+ self.gmem_tiled_copy_Q,
+ tiled_mma_qk,
+ tiled_mma_pv,
+ tiled_mma_o,
+ tile_sched_params,
+ SingleTileVarlenScheduler,
+ SharedStorage,
+ num_splits,
+ aux_data,
+ descale_tensors,
+ ).launch(
+ grid=grid_dim,
+ block=[self.num_threads, 1, 1],
+ stream=stream,
+ min_blocks_per_mp=1,
+ )
+
+ @cute.kernel
+ def kernel(
+ self,
+ mQ: cute.Tensor,
+ mK: cute.Tensor,
+ mV: cute.Tensor,
+ mO: cute.Tensor,
+ mLSE: Optional[cute.Tensor],
+ mCuSeqlensQ: cute.Tensor,
+ mSeqUsedK: Optional[cute.Tensor],
+ mPageTable: cute.Tensor,
+ tma_atom_Q: Optional[cute.CopyAtom],
+ tma_atom_K: cute.CopyAtom,
+ tma_atom_V: cute.CopyAtom,
+ softmax_scale_log2: Float32,
+ softmax_scale: Optional[Float32],
+ window_size_left: Optional[Int32],
+ window_size_right: Optional[Int32],
+ learnable_sink: Optional[cute.Tensor],
+ sQ_layout: cute.ComposedLayout,
+ sQ_fp8_layout: cute.ComposedLayout,
+ sK_layout: cute.ComposedLayout,
+ sV_layout: cute.ComposedLayout,
+ sP_layout: cute.ComposedLayout,
+ gmem_tiled_copy_Q: cute.TiledCopy,
+ tiled_mma_qk: cute.TiledMma,
+ tiled_mma_pv: cute.TiledMma,
+ tiled_mma_o: cute.TiledMma,
+ tile_sched_params: ParamsBase,
+ TileScheduler: cutlass.Constexpr[Callable],
+ SharedStorage: cutlass.Constexpr[Callable],
+ num_splits: Int32,
+ aux_data: AuxData,
+ descale_tensors: Optional[Fp8KVDescaleTensors],
+ ):
+ warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+ if warp_idx == 0:
+ for tma_atom in (tma_atom_Q, tma_atom_K, tma_atom_V):
+ if const_expr(tma_atom is not None):
+ cpasync.prefetch_descriptor(tma_atom)
+
+ smem = cutlass.utils.SmemAllocator()
+ storage = smem.allocate(SharedStorage)
+
+ ThreadCooperativeGroup = partial(pipeline.CooperativeGroup, pipeline.Agent.Thread)
+ warp_size = cute.arch.WARP_SIZE
+ tma_warp = ThreadCooperativeGroup(1)
+ load_threads = ThreadCooperativeGroup(self.num_threads_per_warp_group)
+ pv_warps = ThreadCooperativeGroup(self.num_pv_threads // warp_size)
+ softmax_warps = ThreadCooperativeGroup(self.num_softmax_threads // warp_size)
+ # Q is consumed (quantized) by the PV warp groups.
+ if const_expr(self.use_tma_Q):
+ pipeline_q = pipeline_custom.PipelineTmaAsync.create(
+ barrier_storage=storage.mbar_ptr_Q.data_ptr(),
+ num_stages=1,
+ producer_group=tma_warp,
+ consumer_group=pv_warps,
+ tx_count=self.tma_copy_bytes["Q"],
+ defer_sync=True,
+ )
+ else:
+ pipeline_q = pipeline_custom.PipelineCpAsync.create(
+ barrier_storage=storage.mbar_ptr_Q.data_ptr(),
+ num_stages=1,
+ producer_group=load_threads,
+ consumer_group=pv_warps,
+ defer_sync=True,
+ elect_one_release=True,
+ syncwarp_before_release=False,
+ )
+ pipeline_k = pipeline_custom.PipelineTmaAsync.create(
+ barrier_storage=storage.mbar_ptr_K.data_ptr(),
+ num_stages=self.num_kv_slots,
+ producer_group=tma_warp,
+ consumer_group=softmax_warps,
+ tx_count=self.tma_copy_bytes["K"],
+ defer_sync=True,
+ )
+ pipeline_v = pipeline_custom.PipelineTmaAsync.create(
+ barrier_storage=storage.mbar_ptr_V.data_ptr(),
+ num_stages=self.num_kv_slots,
+ producer_group=tma_warp,
+ consumer_group=pv_warps,
+ tx_count=self.tma_copy_bytes["V"],
+ defer_sync=True,
+ )
+ pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True)
+
+ sQ = storage.sQ.get_tensor(sQ_layout.outer, swizzle=sQ_layout.inner)
+ sQ_res = storage.sQ.get_tensor(
+ sQ_fp8_layout.outer, swizzle=sQ_fp8_layout.inner, dtype=self.kv_dtype
+ )
+ sQ_hi = cute.make_tensor(sQ_res.iterator + cute.cosize(sQ_fp8_layout), sQ_res.layout)
+ sK = storage.sK.get_tensor(sK_layout.outer, swizzle=sK_layout.inner)
+ sV = storage.sV.get_tensor(sV_layout.outer, swizzle=sV_layout.inner)
+ sP = storage.sP.get_tensor(sP_layout.outer, swizzle=sP_layout.inner)
+ row_stats = (
+ storage.sRowScale.get_tensor(cute.make_layout((self.tile_m, self.num_kv_slots))),
+ storage.sRowScaleChanged.get_tensor(cute.make_layout((4, self.num_kv_slots))),
+ storage.sFinalScale.get_tensor(cute.make_layout(self.tile_m)),
+ storage.sLSE.get_tensor(cute.make_layout(self.tile_m)),
+ )
+
+ block_info = BlockInfo(
+ self.tile_m,
+ self.tile_n,
+ self.is_causal,
+ self.is_local,
+ self.is_split_kv,
+ window_size_left,
+ window_size_right,
+ qhead_per_kvhead_packgqa=self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1,
+ num_splits=num_splits,
+ )
+ SeqlenInfoCls = partial(
+ SeqlenInfoQK.create,
+ seqlen_q_static=mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1],
+ seqlen_k_static=mK.shape[0] * mPageTable.shape[1],
+ mCuSeqlensQ=mCuSeqlensQ,
+ mCuSeqlensK=None,
+ mSeqUsedQ=None,
+ mSeqUsedK=mSeqUsedK,
+ )
+ AttentionMaskCls = partial(
+ AttentionMask,
+ self.tile_m,
+ self.tile_n,
+ window_size_left=window_size_left,
+ window_size_right=window_size_right,
+ qhead_per_kvhead_packgqa=self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1,
+ )
+ TileSchedulerCls = partial(TileScheduler.create, tile_sched_params)
+
+ pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn)
+
+ warps_per_wg = self.num_threads_per_warp_group // warp_size
+ first_softmax_warp = warps_per_wg * (1 + self.num_pv_warp_groups)
+ tidx, _, _ = cute.arch.thread_idx()
+ if warp_idx < warps_per_wg:
+ cute.arch.setmaxregister_decrease(self.num_producer_regs)
+ self.load(
+ mQ,
+ mK,
+ mV,
+ sQ,
+ sK,
+ sV,
+ tma_atom_Q,
+ tma_atom_K,
+ tma_atom_V,
+ pipeline_q,
+ pipeline_k,
+ pipeline_v,
+ gmem_tiled_copy_Q,
+ mPageTable,
+ block_info,
+ SeqlenInfoCls,
+ TileSchedulerCls,
+ num_splits,
+ )
+ elif warp_idx >= first_softmax_warp:
+ cute.arch.setmaxregister_increase(self.num_softmax_regs)
+ self.softmax_wg(
+ tiled_mma_qk,
+ sQ_hi,
+ sQ_res,
+ sK,
+ sP,
+ row_stats,
+ learnable_sink,
+ pipeline_k,
+ tidx - first_softmax_warp * warp_size,
+ softmax_scale_log2,
+ softmax_scale,
+ block_info,
+ SeqlenInfoCls,
+ AttentionMaskCls,
+ TileSchedulerCls,
+ aux_data,
+ num_splits,
+ descale_tensors,
+ )
+ else:
+ cute.arch.setmaxregister_increase(self.num_mma_regs)
+ self.pv_wg(
+ tiled_mma_pv,
+ tiled_mma_o,
+ mO,
+ mLSE,
+ sQ,
+ sQ_hi,
+ sQ_res,
+ sV,
+ sP,
+ row_stats,
+ pipeline_q,
+ pipeline_v,
+ tidx - self.num_threads_per_warp_group,
+ block_info,
+ SeqlenInfoCls,
+ TileSchedulerCls,
+ num_splits,
+ )
+
+ @cute.jit
+ def _kslot(self, n_block, n_block_max):
+ """K (and V) slot of block n_block and its fill parity; fills run n_block_max - 1 down.
+
+ Requires 0 <= n_block < n_block_max.
+ """
+ return n_block & 1, ((n_block_max - 1 - n_block) >> 1) & 1
+
+ @cute.jit
+ def _block_range(self, block_info, seqlen, m_block, split_idx, num_splits):
+ """[n_block_min, n_block_max) of this tile, and whether it is empty. An empty range
+ becomes the single block 0 so that every role keeps one K and one V transaction; its
+ result is discarded."""
+ n_block_min, n_block_max = block_info.get_n_block_min_max(
+ seqlen, m_block, split_idx, num_splits
+ )
+ is_empty = n_block_min >= n_block_max
+ if is_empty:
+ n_block_min = Int32(0)
+ n_block_max = Int32(1)
+ return n_block_min, n_block_max, is_empty
+
+ # ///////////////////////////////////////////////////////////////////////////////////////
+ # Producer
+ # ///////////////////////////////////////////////////////////////////////////////////////
+
+ @cute.jit
+ def load(
+ self,
+ mQ: cute.Tensor,
+ mK: cute.Tensor,
+ mV: cute.Tensor,
+ sQ: cute.Tensor,
+ sK: cute.Tensor,
+ sV: cute.Tensor,
+ tma_atom_Q: Optional[cute.CopyAtom],
+ tma_atom_K: cute.CopyAtom,
+ tma_atom_V: cute.CopyAtom,
+ pipeline_q: pipeline.PipelineAsync,
+ pipeline_k: pipeline.PipelineAsync,
+ pipeline_v: pipeline.PipelineAsync,
+ gmem_tiled_copy_Q: cute.TiledCopy,
+ mPageTable: cute.Tensor,
+ block_info: BlockInfo,
+ SeqlenInfoCls: Callable,
+ TileSchedulerCls: Callable,
+ num_splits: Int32,
+ ):
+ """Q first (it is quantized before the first QK), then K[n_max - 1], then K[n] and
+ V[n + 1] for n descending, then V[n_min]. Each page index is read once."""
+ warp_idx_in_wg = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % 4
+ tidx, _, _ = cute.arch.thread_idx()
+ tile_scheduler = TileSchedulerCls()
+ work_tile = tile_scheduler.initial_work_tile_info()
+ if work_tile.is_valid_tile:
+ m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx
+ seqlen = SeqlenInfoCls(batch_idx)
+ head_idx_kv = (
+ head_idx // self.qhead_per_kvhead if const_expr(not self.pack_gqa) else head_idx
+ )
+ mQ_cur = seqlen.offset_batch_Q(mQ, batch_idx, dim=3)[None, None, head_idx]
+ if const_expr(self.use_tma_Q):
+ if warp_idx_in_wg == 0:
+ gQ = cute.local_tile(mQ_cur, (self.tile_m, self.tile_hdim), (m_block, 0))
+ load_Q, _, _ = copy_utils.tma_get_copy_fn(
+ tma_atom_Q, 0, cute.make_layout(1), gQ, sQ, single_stage=True
+ )
+ pipeline_q.producer_acquire_w_index_phase(0, Int32(1))
+ load_Q(tma_bar_ptr=pipeline_q.sync_object_full.get_barrier(0))
+ else:
+ # All 128 producer threads load Q with cp.async.
+ pack_gqa = PackGQA(
+ self.tile_m, self.tile_hdim, self.check_hdim_oob, self.qhead_per_kvhead
+ )
+ pipeline_q.producer_acquire_w_index_phase(0, Int32(1))
+ pack_gqa.load_Q(mQ_cur, sQ, gmem_tiled_copy_Q, tidx, m_block, seqlen.seqlen_q)
+ cute.arch.cp_async_commit_group()
+ pipeline_q.producer_commit_w_index(0)
+
+ n_block_min, n_block_max, is_empty = self._block_range(
+ block_info, seqlen, m_block, split_idx, num_splits
+ )
+ if warp_idx_in_wg == 0:
+ # Paged TMA tiles, page dimension indexable.
+ gK = cute.local_tile(
+ mK[None, None, head_idx_kv, None], (self.tile_n, self.tile_hdim), (0, 0, None)
+ )
+ gV = cute.local_tile(
+ mV[None, None, head_idx_kv, None], (self.tile_n, self.tile_hdimv), (0, 0, None)
+ )
+ load_K, _, _ = copy_utils.tma_get_copy_fn(
+ tma_atom_K, 0, cute.make_layout(1), gK, sK
+ )
+ load_V, _, _ = copy_utils.tma_get_copy_fn(
+ tma_atom_V, 0, cute.make_layout(1), gV, sV
+ )
+ issue = partial(self._issue_kv, n_block_max=n_block_max)
+ # An empty range reads physical page 0, a valid dummy source.
+ page = Int32(0)
+ if not is_empty:
+ page = mPageTable[batch_idx, n_block_max - 1]
+ issue(pipeline_k, load_K, n_block_max - 1, page)
+ for i in cutlass.range(n_block_max - 1 - n_block_min, unroll=1):
+ n_block = n_block_max - 2 - i
+ page_next = page
+ page = mPageTable[batch_idx, n_block]
+ issue(pipeline_k, load_K, n_block, page)
+ issue(pipeline_v, load_V, n_block + 1, page_next)
+ issue(pipeline_v, load_V, n_block_min, page)
+
+ @cute.jit
+ def _issue_kv(self, pipe, copy_fn, n_block, page, n_block_max):
+ """TMA K or V page `page` of block n_block into its slot."""
+ slot, phase = self._kslot(n_block, n_block_max)
+ pipe.producer_acquire_w_index_phase(slot, phase ^ 1)
+ copy_fn(src_idx=page, dst_idx=slot, tma_bar_ptr=pipe.sync_object_full.get_barrier(slot))
+
+ # ///////////////////////////////////////////////////////////////////////////////////////
+ # Softmax warp group
+ # ///////////////////////////////////////////////////////////////////////////////////////
+
+ @cute.jit
+ def softmax_wg(
+ self,
+ tiled_mma_qk: cute.TiledMma,
+ sQ_hi: cute.Tensor,
+ sQ_res: cute.Tensor,
+ sK: cute.Tensor,
+ sP: cute.Tensor,
+ row_stats: tuple,
+ learnable_sink: Optional[cute.Tensor],
+ pipeline_k: pipeline.PipelineAsync,
+ tidx: Int32,
+ softmax_scale_log2: Float32,
+ softmax_scale: Optional[Float32],
+ block_info: BlockInfo,
+ SeqlenInfoCls: Callable,
+ AttentionMaskCls: Callable,
+ TileSchedulerCls: Callable,
+ aux_data: AuxData,
+ num_splits: Int32,
+ descale_tensors: Optional[Fp8KVDescaleTensors],
+ ):
+ """QK and online softmax over all KV blocks of the tile; hands P and its row rescales
+ to the PV warp groups block by block, then the final row scales and LSE."""
+ sRowScale, sRowScaleChanged, sFinalScale, sLSE = row_stats
+ thr_mma_qk = tiled_mma_qk.get_slice(tidx)
+ # Q_res, Q_hi and K fragments of each head_dim half (K-mode slice of tiled_mma_qk).
+ qk_halves = []
+ for h in cutlass.range_constexpr(2):
+ wg_slice = tiled_mma_qk.get_slice(h * self.num_threads_per_warp_group)
+ _, tQhi, tK = sm90_utils.partition_fragment_ABC(
+ wg_slice, (self.tile_m, self.tile_n, self.tile_hdim), sQ_hi, sK
+ )
+ _, tQres, _ = sm90_utils.partition_fragment_ABC(
+ wg_slice, (self.tile_m, self.tile_n, self.tile_hdim), sQ_res, sK
+ )
+ qk_halves.append((tQres, tQhi, tK))
+ smem_thr_copy_P = cute.make_tiled_copy_C(
+ utils.get_smem_store_atom(self.arch.major * 10 + self.arch.minor, self.dtype),
+ tiled_mma_qk,
+ ).get_slice(tidx)
+ # (row, col) coordinate of each S element.
+ tScS = layout_utils.reshape_acc_to_mn(
+ thr_mma_qk.partition_C(cute.make_identity_tensor((self.tile_m, self.tile_n)))
+ )
+ sm = SimpleNamespace(
+ thr_mma_qk=thr_mma_qk,
+ qk_halves=qk_halves,
+ # Masked S of the block whose softmax is next.
+ S=cute.make_rmem_tensor(
+ tiled_mma_qk.partition_shape_C((self.tile_m, self.tile_n)), Float32
+ ),
+ smem_thr_copy_P=smem_thr_copy_P,
+ tPsP=smem_thr_copy_P.partition_D(sP),
+ is_col0=tScS[0][1] == 0,
+ sRowScale=sRowScale,
+ sRowScaleChanged=sRowScaleChanged,
+ warp=tidx // cute.arch.WARP_SIZE,
+ lane=tidx % cute.arch.WARP_SIZE,
+ )
+ num_rows = cute.size(tScS, mode=[0])
+
+ tile_scheduler = TileSchedulerCls()
+ work_tile = tile_scheduler.initial_work_tile_info()
+ if work_tile.is_valid_tile:
+ m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx
+ seqlen = SeqlenInfoCls(batch_idx)
+ head_idx_kv = (
+ head_idx // self.qhead_per_kvhead if const_expr(not self.pack_gqa) else head_idx
+ )
+ # q * k descales fold into the score scale, v into the final output scale.
+ qk_descale, v_descale = self._load_effective_descales(
+ descale_tensors, batch_idx, head_idx_kv
+ )
+ v_descale = v_descale / Float32(2**self.max_offset)
+ if const_expr(self.score_mod is None):
+ scale_log2_eff = softmax_scale_log2 * qk_descale
+ softmax_scale_eff = None
+ else:
+ scale_log2_eff = softmax_scale_log2
+ softmax_scale_eff = softmax_scale * qk_descale
+ softmax = Softmax.create(
+ scale_log2_eff, num_rows=num_rows, softmax_scale=softmax_scale_eff
+ )
+ mask = AttentionMaskCls(seqlen)
+ mask_fn = partial(
+ mask.apply_mask,
+ batch_idx=batch_idx,
+ head_idx=head_idx,
+ m_block=m_block,
+ thr_mma=thr_mma_qk,
+ mask_causal=self.is_causal,
+ mask_local=self.is_local,
+ aux_data=aux_data,
+ )
+ score_mod_fn = None
+ if const_expr(self.score_mod is not None):
+ score_mod_fn = partial(
+ self.apply_score_mod,
+ thr_mma_qk,
+ batch_idx,
+ head_idx,
+ m_block,
+ softmax_scale=softmax_scale_eff,
+ aux_data=aux_data,
+ )
+ n_block_min, n_block_max, is_empty = self._block_range(
+ block_info, seqlen, m_block, split_idx, num_splits
+ )
+ sink_val = None
+ if const_expr(learnable_sink is not None):
+ sink_val = self._load_sink(learnable_sink, tScS, m_block, head_idx, split_idx)
+ # Wait until the PV warp groups have written Q_hi and Q_res.
+ cute.arch.barrier(
+ barrier_id=int(NamedBarrierFwdSm90Fp8KV.QReady),
+ number_of_threads=self.num_handoff_threads,
+ )
+ nmax = n_block_max
+ # Block nmax - 1: both QK halves, then seed the reference max (the softmax of
+ # each block runs one step after its QK).
+ slot, phase = self._kslot(nmax - 1, nmax)
+ pipeline_k.consumer_wait_w_index_phase(slot, phase)
+ accs = []
+ for h in cutlass.range_constexpr(2):
+ accs.append(self._qk_half(tiled_mma_qk, sm, h, slot))
+ warpgroup.wait_group(0)
+ self._fold_s(
+ sm,
+ accs,
+ pipeline_k,
+ nmax - 1,
+ nmax,
+ seqlen,
+ partial(mask_fn, mask_mod=None, mask_seqlen=True),
+ score_mod_fn,
+ )
+ self._init_row_max(softmax, sm.S)
+ n_block_max -= 1
+ step = partial(
+ self._softmax_step,
+ tiled_mma_qk,
+ sm,
+ pipeline_k,
+ softmax,
+ seqlen,
+ score_mod_fn,
+ nmax,
+ )
+ if const_expr(self.is_causal or self.is_local):
+ n_block_min_causal_local_mask = block_info.get_n_block_min_causal_local_mask(
+ seqlen, m_block, n_block_min
+ )
+ for n_tile in cutlass.range(n_block_max - n_block_min_causal_local_mask, unroll=1):
+ step(
+ n_block_max - 1 - n_tile,
+ mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=False),
+ )
+ n_block_max = cutlass.min(n_block_max, n_block_min_causal_local_mask)
+ n_block_min_before_local_mask = block_info.get_n_block_min_before_local_mask(
+ seqlen, m_block, n_block_min
+ )
+ for n_tile in cutlass.range(n_block_max - n_block_min_before_local_mask, unroll=1):
+ step(n_block_max - 1 - n_tile, mask_fn=None)
+ if const_expr(self.is_local and block_info.window_size_left is not None):
+ n_block_max = cutlass.min(n_block_max, n_block_min_before_local_mask)
+ for n_tile in cutlass.range(n_block_max - n_block_min, unroll=1):
+ step(
+ n_block_max - 1 - n_tile,
+ mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=False),
+ )
+ # The last step stored P[n_block_min + 1] without signalling it.
+ if n_block_min + 1 < nmax:
+ self._signal_p(n_block_min + 1)
+ row_scale = self._online_softmax_lazy_max(softmax, sm.S)
+ self._publish_p(sm, row_scale, n_block_min, n_block_min < nmax - 2)
+ self._signal_p(n_block_min)
+ # The row sums hold sum(P * 2^max_offset): undo the power of two exactly.
+ softmax.row_sum.store(softmax.row_sum.load() * Float32(2.0**-self.max_offset))
+ final_scale = softmax.finalize(final_scale=v_descale, sink_val=sink_val)
Thanks, was able to reproduce it and your two-block case returns an infinite LSE. Fixed in commit 834c5c5.
With the lazy row max, the reference max can sit well below the sink logit, so exp(sink - max) overflows when the sink is added at finalize. The FP8 KV kernel now finalizes sink rows in its own _finalize_with_sink: if the sink logit is above the reference max, the row sum and the O scale are moved to the sink logit first, and the LSE is taken from that max. Rows with sink <= max, and rows without a sink, take the previous arithmetic. Softmax.finalize and the other kernels are unchanged.
Added test_flash_attn_varlen_fp8_kv_sink_above_lazy_row_max_sm90 and ran your case (two 64-key pages with logits 0 then 5) against FP32 reference, sweeping the sink from 0 to 120 with one head and with pack_gqa. Before the fix, sinks >= 89 gave an infinite LSE, now all 16 cases pass.
@@ -2133,6 +2175,12 @@ def _flash_attn_fwd(
num_splits_dynamic_ptr=num_splits_dynamic,
virtual_batch_idx=virtual_batch_idx if has_scheduler_metadata else None,
output_scale=output_scale,
+ # The SM90 FP8-KV hd512 kernel's partials: PDL, and split groups past 16 splits.
+ **(
+ dict(split_groups=4 if num_splits > 16 else 1, use_pdl=True)
Thanks. I tried it but the forward fills 128 of 132 SMs, so the early combine CTAs pile onto the free SMs and MTP verify (q5, b1, 8K KV) regressed from 20.3 to 29.1 us, hence I left it out. The combine still waits on PDL, so launch latency stays hidden.
@xuanzic, could you rebase this PR onto the latest main and resolve the merge conflicts? Thanks.
Hi @zyongye, rebased! Thank you!
xuanzic
Residual = Change × (1 − Confidence)
zyongye
Summary
With an FP8 KV cache, attention with head_dim 512 (for example the global-attention layers of Gemma 4) runs on Hopper through the FP8 mainloop of the CuTe SM90 forward kernel (
fp8_kv_dequant=True, #199).This PR adds a dedicated kernel for that case,
FlashAttentionForwardSm90Fp8KV, a subclass ofFlashAttentionForwardSm90.On H100 it is about 2.1x faster on prefill, 2.2x on chunked prefill and 1.35x on decode (CUDA-graph replay, vLLM's call).
The output stays within 1 ulp of
main.main.flash_fwd_combine.py. Whichever lands second will rebase onto the other and use one combine.When the new path is used
All of these must hold:
fp8_kv_dequant=True, E4M3 K / V,head_dim == head_dim_v == 512, paged KV with page size 64cu_seqlens_q) withseqused_k, noseqused_qscore_mod(softcap is fine), nomask_mod, no aux tensors, no dynamic causalSupported with it: causal and non-causal, sliding window, softcap, attention sink, any GQA ratio, K/V descales of shape (batch, num_kv_heads) (vLLM's per-tensor scale, expanded), and SplitKV.
Q is split into two E4M3 terms, so the path assumes |q| ≤ 448 (the E4M3 range), as for the existing FP8 mainloop with an identity Q descale.
All other requests run on the existing kernel, as before.
Why it was slow
The existing FP8-KV path is the generic SM90 kernel with an FP8 mainloop. At head_dim 512 the O accumulator is split across two MMA warpgroups, so:
1. S = Q K^T and the softmax are computed twice, once per warpgroup.
2. PV runs in E4M3. P is quantized to a compensated pair of E4M3 terms, so each PV block takes two FP8 GEMMs plus an FP32 fold, on the critical path after the softmax.
3. V is copied every block. FP8 WGMMA needs a K-major B operand, so each V tile is transposed through registers into a second shared-memory buffer before PV.
<!-- drag fig 1 (pr_fp8_fig0_upstream.png) here -->
Changes
1. Epilogue store hook and E4M3 helpers (no behaviour change)
FlashAttentionForwardBase.epiloguetakes an optionalstore_O_fnthat writes O from registers, while the epilogue still writes LSE and handles varlen / pack_gqa / SplitKV indexing.utilsgainse4m3_hi_res_x8, which splits BF16/FP16 values into two E4M3 terms, ande4m3_2x2_to_f16x2_transposed, which widens and transposes E4M3 to FP16 exactly.Existing callers compile to the same code.
2.
FlashAttentionForwardSm90Fp8KVOne CTA runs four warpgroups on a 64-row Q tile:
- S is an FP8 WGMMA of the two E4M3 terms of Q over interleaved head_dim halves, with two FP32 accumulators;
- the row max is lazy: O is rescaled only when the max grows by more than 2^8;
- V^T comes from the E4M3 tile through
ldmatrix.transand an exact widening to FP16;- P comes from shared memory as FP16, scaled by 2^7.
P and the per-row scales move between the warpgroups through two shared-memory slots guarded by named barriers, so the softmax of block n+1 overlaps the PV of block n.
O is written from the PV registers through the store hook.
<!-- drag fig 2 (pr_fp8_fig1_roles.png), fig 3 (pr_fp8_fig3_pv_transposed.png) and fig 4 (pr_fp8_fig5_schedule.png) here -->
Why a separate class. Almost every stage differs from the FP8 mainloop of
FlashAttentionForwardSm90: the warpgroup roles, the transposed FP16 PV, the shared-memory layout and barriers, and the register-resident O store. Expressing that as flags would put branches through most of the base mainloop. So the kernel is its own subclass inflash_fwd_sm90.py, like other specialized forwards that have their own classes (FlashAttentionForwardSm120, the SM100 decode and MLA forwards). It reuses the base epilogue, masking, sink and block info.The subclass still repeats parts of the base
__call__/kernelsetup (TMA atoms, scheduler, launch). If maintainers prefer, those can move into a few overridable base methods with no change to the generated code.3. SplitKV combine: split groups and PDL
FlashAttentionForwardCombinetakessplit_groupsanduse_pdl.With
split_groups > 1the CTA's threads form groups that each merge everysplit_groups-th split, which shortens the serial loop when there are many splits.use_pdllaunches the combine with programmatic dependent launch.The defaults compile to the same code as before. The new kernel uses PDL always, and split groups above 16 splits.
4. Routing
_flash_attn_fwdselects the new kernel with one predicate after config selection. Unit tests for the new kernel and the combine options will follow as a separate commit on this branch.Performance
All numbers: one H100 80GB.
num_splits=0, head_dim = head_dim_v = 512.fp8_kv_dequant=True, with K/V descales passed as vLLM passes them (a 0-dim scale expanded to (batch, num_kv_heads)).M1 = Gemma-4-26B-A4B at TP2 (8 Q heads, 1 KV head per GPU); M2 = Gemma-4-31B at TP1 (32 Q heads, 4 KV heads).
Speedup =
mainlatency / this PR latency.mainis vllm-project/flash-attention 8dd9eae, whose FP8-KV path includes #213 and #218.Prefill (one sequence, varlen, q = k)
| seqlen | M1 main (ms) | M1 this PR (ms) | M1 speedup | M2 main (ms) | M2 this PR (ms) | M2 speedup |
|---|---:|---:|---:|---:|---:|---:|
| 1K | 0.0671 | 0.0344 | 1.95x | 0.1577 | 0.0859 | 1.84x |
| 4K | 0.4839 | 0.2202 | 2.20x | 2.057 | 0.9833 | 2.09x |
| 8K | 1.838 | 0.8812 | 2.09x | 7.774 | 3.631 | 2.14x |
| 16K | 7.402 | 3.456 | 2.14x | 30.56 | 13.89 | 2.20x |
| 32K | 29.86 | 13.47 | 2.22x | 121.62 | 55.48 | 2.19x |
| 64K | 118.86 | 54.37 | 2.19x | 482.20 | 222.55 | 2.17x |
| geomean | | | 2.13x | | | 2.10x |
Chunked prefill / prefix-cache hit (one sequence, new q tokens on top of cached keys)
| new q / cached k | M1 main (ms) | M1 this PR (ms) | M1 speedup | M2 main (ms) | M2 this PR (ms) | M2 speedup |
|---|---:|---:|---:|---:|---:|---:|
| 2K / 8K | 1.105 | 0.5115 | 2.16x | 4.420 | 2.010 | 2.20x |
| 8K / 8K | 5.781 | 2.645 | 2.19x | 23.37 | 10.46 | 2.23x |
| 2K / 32K | 4.028 | 1.796 | 2.24x | 16.21 | 7.183 | 2.26x |
| 8K / 32K | 17.53 | 7.787 | 2.25x | 70.16 | 31.48 | 2.23x |
| 2K / 64K | 8.008 | 3.540 | 2.26x | 31.69 | 14.26 | 2.22x |
| 8K / 64K | 32.97 | 14.63 | 2.25x | 131.38 | 59.80 | 2.20x |
| geomean | | | 2.23x | | | 2.22x |
Decode (q = 1 per sequence)
| batch x KV len | M1 main (us) | M1 this PR (us) | M1 speedup | M2 main (us) | M2 this PR (us) | M2 speedup |
|---|---:|---:|---:|---:|---:|---:|
| 1 x 4K | 24.7 | 17.0 | 1.45x | 25.9 | 17.9 | 1.45x |
| 1 x 16K | 33.9 | 21.2 | 1.60x | 52.6 | 39.2 | 1.34x |
| 1 x 32K | 40.4 | 25.1 | 1.61x | 76.8 | 61.4 | 1.25x |
| 1 x 128K | 84.6 | 64.9 | 1.30x | 227.6 | 192.0 | 1.19x |
| 16 x 4K | 52.4 | 39.6 | 1.32x | 132.2 | 106.0 | 1.25x |
| 16 x 16K | 130.4 | 105.9 | 1.23x | 477.9 | 374.3 | 1.28x |
| 16 x 32K | 242.9 | 194.6 | 1.25x | 955.9 | 723.2 | 1.32x |
| 16 x 128K | 955.6 | 720.0 | 1.33x | 3740.9 | 2827.9 | 1.32x |
| 64 x 4K | 133.6 | 107.0 | 1.25x | 516.8 | 370.1 | 1.40x |
| 64 x 16K | 490.5 | 373.3 | 1.31x | 2008.5 | 1423.4 | 1.41x |
| 64 x 32K | 970.4 | 723.8 | 1.34x | 3953.3 | 2808.9 | 1.41x |
| 64 x 128K | 3797.7 | 2825.7 | 1.34x | 15894.0 | 11239.7 | 1.41x |
| 128 x 4K | 255.5 | 190.6 | 1.34x | 1032.9 | 723.6 | 1.43x |
| 128 x 16K | 997.2 | 721.3 | 1.38x | 3981.4 | 2801.4 | 1.42x |
| 128 x 32K | 1978.9 | 1424.8 | 1.39x | 7924.1 | 5603.4 | 1.41x |
| 128 x 128K | 7909.8 | 5625.6 | 1.41x | - | - | - |
| geomean | | | 1.36x | | | 1.35x |
"-": the M2 FP8 KV cache (69 GB) does not fit next to the benchmark buffers on one 80 GB GPU.
Speculative-decode verify (q = 5 per sequence)
| batch x KV len | M1 main (us) | M1 this PR (us) | M1 speedup | M2 main (us) | M2 this PR (us) | M2 speedup |
|---|---:|---:|---:|---:|---:|---:|
| 1 x 8K | 32.2 | 20.0 | 1.61x | 43.9 | 29.7 | 1.48x |
| 1 x 32K | 51.5 | 31.0 | 1.66x | 82.8 | 67.6 | 1.22x |
| 16 x 8K | 81.5 | 68.1 | 1.20x | 255.6 | 204.7 | 1.25x |
| 16 x 32K | 251.8 | 201.3 | 1.25x | 988.3 | 734.1 | 1.35x |
| 64 x 8K | 258.0 | 206.2 | 1.25x | 1021.9 | 730.8 | 1.40x |
| 64 x 32K | 992.4 | 733.7 | 1.35x | 3961.6 | 2822.0 | 1.40x |
| geomean | | | 1.38x | | | 1.35x |
Mixed varlen batch (chunked prefill and decode in one call: 1 x (q 2K, k 32K) + 64 x (q 1, k 8K))
| model | main (ms) | this PR (ms) | speedup |
|---|---:|---:|---:|
| M1 | 4.168 | 1.895 | 2.20x |
| M2 | 16.44 | 7.370 | 2.23x |
Ragged varlen batches (sequences of different lengths in one call)
| batch | M1 main | M1 this PR | M1 speedup | M2 main | M2 this PR | M2 speedup |
|---|---:|---:|---:|---:|---:|---:|
| prefill, 8 seqs of 32K, 8K, 2K, 512, 128, 64, 16, 1 | 30.95 ms | 13.67 ms | 2.26x | 119.69 ms | 59.23 ms | 2.02x |
| prefill, 8 x 4K + 24 x 512 | 4.017 ms | 2.017 ms | 1.99x | 16.46 ms | 8.058 ms | 2.04x |
| prefill, 16 x q 2K on k 2K-8K | 7.356 ms | 3.418 ms | 2.15x | 30.23 ms | 13.73 ms | 2.20x |
| decode, 64 seqs, KV 1K-64K (log-uniform) | 1505 us | 710 us | 2.12x | 3301 us | 1722 us | 1.92x |
| verify q = 5, 16 seqs, KV 100-64K (log-spaced) | 420.7 us | 198.7 us | 2.12x | 1611 us | 733 us | 2.20x |
| geomean | | | 2.13x | | | 2.07x |
Decode shapes from #199 (q = 1, 8 Q heads / 4 KV heads)
| batch x context | main (us) | this PR (us) | speedup |
|---|---:|---:|---:|
| 1 x 4K | 26.9 | 20.0 | 1.35x |
| 1 x 16K | 52.2 | 38.5 | 1.36x |
| 1 x 28K | 71.9 | 55.1 | 1.31x |
| 16 x 4K | 126.3 | 103.5 | 1.22x |
| 16 x 16K | 450.1 | 368.3 | 1.22x |
| 16 x 28K | 786.5 | 627.2 | 1.25x |
| 64 x 4K | 496.6 | 368.1 | 1.35x |
| 64 x 16K | 1965.2 | 1419.9 | 1.38x |
| 64 x 28K | 3398.9 | 2469.4 | 1.38x |
| geomean | | | 1.31x |
FP8 KV vs BF16 KV (M1 prefill)
On
main, FP8 KV prefill is slower than BF16 KV. With this PR it is faster.| shape | main, BF16 KV (ms) | main, FP8 KV (ms) | this PR, FP8 KV (ms) | this PR FP8 vs main BF16 |
|---|---:|---:|---:|---:|
| prefill 4K | 0.3782 | 0.4952 | 0.2237 | 1.69x |
| prefill 32K | 23.77 | 28.51 | 13.37 | 1.78x |
Accuracy
Error against an FP64 reference computed from the same paged FP8 cache (exact E4M3 values x descale, in FP64; causal), M1 and M2,
num_splits=0.This kernel is not bitwise equal to
main, because its PV runs in FP16 on the exactly widened V. Over 16 rows x 5 seeds:main;mainon 73 of 80 row-seeds, and at most 2.4% higher on the other 7 (mostly M2 decode KV 128K, V mean 2);main(at most 3e-6 on decode, 3e-4 on prefill).Representative rows (seed 0):
| model | case | max abs err (main / PR) | mean abs err (main / PR) | max ulp (main / PR) | max LSE err (main / PR) | max \|PR - main\| (ulp) |
|---|---|---|---|---|---|---:|
| M1 | decode, KV 32K | 6.46e-05 / 6.14e-05 | 6.91e-06 / 6.46e-06 | 0.53 / 0.50 | 1.5e-06 / 1.5e-06 | 1 |
| M1 | prefill 32K | 8.10e-03 / 7.52e-03 | 1.32e-05 / 1.22e-05 | 0.68 / 0.57 | 2.4e-04 / 2.4e-04 | 1 |
| M2 | decode, KV 128K | 3.16e-05 / 3.16e-05 | 3.42e-06 / 3.18e-06 | 0.55 / 0.52 | 1.6e-06 / 1.4e-06 | 1 |
| M2 | chunked prefill q 2K, k 64K | 3.88e-05 / 3.44e-05 | 4.87e-06 / 4.51e-06 | 0.64 / 0.56 | 4.9e-06 / 4.8e-06 | 1 |
| M2 | decode, KV 128K, V mean 2 | 7.89e-03 / 7.93e-03 | 1.93e-03 / 1.93e-03 | 0.51 / 0.51 | 1.6e-06 / 1.4e-06 | 1 |
End-to-end (vLLM)
Gemma-4-26B-A4B at TP2 on 2x H100, vLLM nightly with
--kv-cache-dtype fp8 --block-size 64and MTP 4. The two runs differ only invllm_flash_attn/cute(mainvs this PR); a route probe confirmed the new kernel ran on both ranks, with and without SplitKV.| accuracy | main | this PR |
|---|---:|---:|
| GSM8K (1319, greedy) | 0.9644 | 0.9651 |
| RULER 32K / 48K (120 items) | 0.775 | 0.783 |
Both differences are well within noise (McNemar p = 1.0).
|
vllm bench serve(mean of 2 runs) | change vs main ||---|---:|
| 32K in / 32 out, concurrency 4 | TTFT -16.6%, output throughput +17.3% |
| 16K in / 512 out, concurrency 16 | TPOT -6.1%, output throughput +5.4% |
| 1K in / 1K out, concurrency 32 | +3.3% throughput (within run-to-run noise) |
Tests
| Check | Result |
|---|---|
| New path vs an fp32-accurate reference: 168 FP8-KV shapes x 8 seeds. Covers causal / non-causal, local, softcap, sink, GQA ratios including odd ones, prefill / chunked / decode / verify, SplitKV and long-accumulation stress. Per-row error budget = 1.1x
main's worst over the seeds (LSE 1.5x) | pass; at most 1 ulp frommainon every row || Other FP8-KV inputs vs
main(FP16 Q, batched Q, V-only descale, noseqused_k,score_mod,mask_mod, aux tensors) | bit-identical, same compiled code || BF16 / FP16 head_dim 512 and head_dim 64 / 128 / 256 vs
main| bit-identical, same compiled code || Zero-length sequences (with and without sink) | same as
main|| CUDA-graph replay | pass, replay == eager bitwise |
|
pytest tests/cute/test_flash_attn.py(hdim512 / sm90 / ragged / sink / empty selection) | 338 passed (same asmain) ||
pytest tests/cute/test_cuda_graph.py tests/cute/test_flash_attn_combine.py tests/cute/test_fwd_config.py(withFLASH_ATTENTION_NUM_SMSset) | pass, no failures ||
pytest tests/cute/test_flash_attn_fp8_kv_cache.py| 14 passed ||
ruff check/ruff format --check(v0.11.13, pre-commit scope) | pass |Not in this PR yet
These
fp8_kv_dequantinputs still use the existing FP8 mainloop:seqused_q;score_mod(with or without aux tensors) andmask_mod;seqused_k.