From 59da05aa9122cb2ef7b07d7c0a5c7a8076d1426c Mon Sep 17 00:00:00 2001 From: peihengh <259410613+peihu-nv@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:51:32 -0700 Subject: [PATCH 01/27] [None][perf] MiniMax-M3 NVFP4 context (prefill) path on Rubin (SM107) Speeds up the MiniMax-M3 NVFP4 context worker on SM107. Changes are default ON and engage only on SM107 unless marked opt-in below. Changes that alter numerics or add a kernel have an environment kill switch. The exact kernel-selection changes inside existing launchers are constants. Projections and boundaries: - Fused QKV-index GEMM + NVFP4/FP8 cache producer (CuTe DSL, 2-CTA M256, CLC tile scheduler) above 1024 rows, also on breakable-graph buckets through an eager break (TRTLLM_CTX_QKV_FUSED, TRTLLM_CTX_BCG_P5A). - CLC MXFP8 GEMM for o_proj, the shared-expert gate_up and the dense MLP, with every tile-width variant built on the first take (TRTLLM_CTX_CLC_GEMM, TRTLLM_CTX_CLC_GEMM_PRECOMPILE). - Fused boundary AllReduce + residual RMSNorm + MXFP8 (and NVFP4 MoE input) quantize at >= 8192 rows (TRTLLM_CTX_NORM_MXFP8, TRTLLM_CTX_NORM_FP4). - SwiGLU-OAI + MXFP8 quantize for the dense MLP (TRTLLM_CTX_SWIGLU_MXFP8). - One-entry MXFP8 prequant slots between producers and the consuming linear, kept out of compiled graphs, with an opt-in take audit. Attention: - FP8 dense prefill on FA4 over the paged cache, with the V tail zeroed on private partial pages (TRTLLM_MSA_DISABLE_DENSE_FA4). - MSA combine writes the o_proj input as MXFP8 (TRTLLM_CTX_COMBINE_MXFP8, TRTLLM_CTX_P5A_COMBINE_MXFP8). - Prefill tile selection, a segmented/split indexer proxy with SM-wide KV splits, in-place NVFP4 sparse prefill output, and an in-forward cache-location tail fill. - Eagle3 drafter context attention on the last rows only, dead-row skipping in the drafter's o_proj/MLP, and KV-tail zeroing on private partial pages (TRTLLM_CTX_DRAFTER_LAST_ROW, _DEAD_ROWS, _KV_TAIL_ZERO). - Fused token-embedding gather and strided-row E4M3 query cast (TRTLLM_CTX_EMBEDDING_GATHER, TRTLLM_CTX_Q_E4M3_ROWS). MoE and router: - Deterministic CuteDSL NVFP4 MoE: FC2 stores per permuted row and a fixed-order unpermute finalizes, optionally folding the shared-expert output (TLLM_CUTEDSL_MOE_DETERMINISTIC, TLLM_M3_MOE_FOLD_SHARED). - Batch-invariant fixed-tile TF32 router GEMM for context steps and the SM107 TF32 tensor-core router for 9..16-row generation steps (TRTLLM_CTX_ROUTER_TF32_FIXED). - Opt-in FP4 MoE tactic table for the trtllm-gen runner (TLLM_FP4_MOE_TACTIC_TABLE, resolved at import). - The TF32 context router GEMM splits K into 8 fixed slices up to 8192 rows (deterministic, not bitwise to the unsplit GEMM). MiniMax-M3 sm_107 TP2 target (modeling_v2): - Context steps past 48 rows route on the fixed-tile TF32 router. - Prefill steps of at least 4096 context rows take the built-in CTX stack (fused QKV GEMM + producer, CTX norm + MXFP8 / NVFP4 MoE input, built-in MoE forward), eager steps only; Eagle3 capture layers keep the generic boundary. - The fused QKV producer stays out of the AutoTuner pass. MSA: - Deferred adaptive-plan split decision, a k2q CSR build scratch arena, per-shape k2q CSR buffers with a direct extension call, and per_token_valid_blocks as one NumPy pass. Scheduling: - Opt-in context append reserve in KVCacheV2Scheduler (TLLM_CTX_APPEND_RESERVE), adaptive, with shortest-first ordering of the requests behind the first (TLLM_CTX_APPEND_RESERVE_SJF). Numerics: bitwise vs each item's off switch, except the fused QKV GEMM, the CLC GEMM, FA4 dense prefill, the deterministic MoE FC2, the TF32 router and its split-K. Those are deterministic and not bitwise to the stock kernels; all but the router split-K are chunk-size invariant, and the router split-K changes its K reduction order at 8192 rows (logits are M-invariant on each side of that cap). Dependencies: - 3rdparty/patches/msa_strided_paged_kv.patch carries the fmha_sm100 changes this path uses. Two are correctness fixes (V tail zeroed past kv_valid_cols; griddepcontrol.wait restored). The performance changes are gated to SM107 at runtime; SM100/103 keep the stock fmha_sm100. - FA4 dense prefill needs flash-attn-4 4.0.0b19 with the FP8 rescale_threshold change (3rdparty/patches/fa4_fp8_rescale0.patch, applied by examples/minimax_m3/rubin/setup_fa4.sh); without it the dense layers keep fmha_sm100. setup_fa4.sh pins the FA4 file and the patch by SHA256; an FA4 update re-derives the patch, re-runs the FP8 dense-prefill check and updates both pins, and the patch goes once FA4 ships the change. Example Rubin context-worker and aggregated TP2 serving recipes in examples/minimax_m3/rubin/. Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com> --- 3rdparty/patches/fa4_fp8_rescale0.patch | 11 + 3rdparty/patches/msa_strided_paged_kv.patch | 11145 +++++++++------- .../kernels/customAllReduceKernels.cu | 119 + .../kernels/fusedQKNormRopeKernel.cu | 196 +- .../kernels/minimaxM3/selectPrefillTile.cu | 542 + .../kernels/minimaxM3/selectPrefillTile.h | 48 + .../ctxResidualRmsNormMxfp8.cu | 232 + .../ctxResidualRmsNormMxfp8.h | 43 + .../minimaxM3SelectPrefillTileOp.cpp | 81 + .../minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp | 101 + cpp/tensorrt_llm/thop/mxfp8Gemm.cpp | 39 + examples/minimax_m3/rubin/README.md | 70 + examples/minimax_m3/rubin/agg/README.md | 49 + examples/minimax_m3/rubin/agg/agg_c14.yaml | 47 + examples/minimax_m3/rubin/agg/agg_c20.yaml | 46 + examples/minimax_m3/rubin/agg/agg_c46.yaml | 50 + examples/minimax_m3/rubin/agg/agg_c56.yaml | 50 + examples/minimax_m3/rubin/agg/agg_env.sh | 30 + examples/minimax_m3/rubin/ctx_agentx_c24.yaml | 51 + .../rubin/fp4_moe_tactics_tp2ctx_v1.json | 64 + examples/minimax_m3/rubin/setup_fa4.sh | 51 + .../minimax_m3_nvfp4__sm_107__tp2/modeling.py | 390 +- .../backends/fmha/drafter_last_row.py | 306 + .../backends/fmha/flashinfer_trtllm_gen.py | 79 +- .../backends/fmha/msa_combine_mxfp8.py | 162 + .../attention/backends/fmha/msa_prefill.py | 458 +- .../attention/backends/fmha/registry.py | 4 + .../sparse/minimax_m3/kernels/msa_utils.py | 54 +- .../backends/sparse/minimax_m3/msa_backend.py | 268 +- .../backends/sparse/minimax_m3/msa_indexer.py | 88 +- .../_torch/custom_ops/cpp_custom_ops.py | 22 + .../_torch/custom_ops/cute_dsl_custom_ops.py | 72 +- .../_torch/custom_ops/torch_custom_ops.py | 24 +- .../custom_ops/trtllm_gen_custom_ops.py | 50 + .../kernels/rubin/m3_qkv_fusion/__init__.py | 2 + .../rubin/m3_qkv_fusion/clc_tile_scheduler.py | 559 + .../kernels/rubin/m3_qkv_fusion/kernel.py | 1996 +++ .../kernels/rubin/m3_qkv_fusion/plain_gemm.py | 229 + .../_torch/models/modeling_minimaxm3.py | 1082 +- tensorrt_llm/_torch/modules/linear.py | 115 +- .../_torch/modules/m3_ctx_clc_gemm.py | 190 + tensorrt_llm/_torch/modules/swiglu.py | 119 + .../cutedsl/grouped_gemm/eligibility.py | 9 +- .../fused_moe/cutedsl/grouped_gemm/nvfp4.py | 126 +- .../_torch/moe/fused_moe/router_gemm_tf32.py | 169 + .../moe/fused_moe/unpermute_residual.py | 77 + ...her_grouped_blockscaled_gemm_act_fusion.py | 51 +- ...rouped_blockscaled_gemm_finalize_fusion.py | 42 +- .../_torch/pyexecutor/resource_manager.py | 1 + .../pyexecutor/scheduler/scheduler_v2.py | 138 + .../integration/test_lists/test-db/l0_cpu.yml | 9 + .../attention/fmha/test_msa_combine_mxfp8.py | 184 + .../sparse/msa/test_fmha_sm107_gates.py | 172 + .../msa/test_minimax_m3_dense_prefill_fa4.py | 176 + .../test_minimax_m3_dense_prefill_fa4_arch.py | 30 + .../msa/test_minimax_m3_proxy_nofill.py | 125 + .../msa/test_minimax_m3_sparse_attn_decode.py | 2 + .../sparse/msa/test_minimax_m3_tile_select.py | 206 + .../attention/sparse/msa/test_msa_backend.py | 56 + .../sparse/msa/test_msa_k2q_ws_stream.py | 60 + .../test_msa_per_token_valid_blocks_numpy.py | 76 + .../test_msa_prefill_nvfp4_out_in_place.py | 56 + .../msa/test_msa_proxy_few_rows_kv_splits.py | 31 + .../attention/test_drafter_kv_tail_zero.py | 140 + .../kernels/parallel/test_mxfp8_mxfp8_gemm.py | 49 + .../kernels/serial/test_m3_ctx_clc_gemm.py | 456 + .../kernels/serial/test_m3_ctx_fused_quant.py | 80 + .../kernels/serial/test_m3_qkv_fusion.py | 364 + .../_torch/misc/test_fp4_moe_tactic_table.py | 64 + .../test_minimax_m3_router_fp32_cast.py | 45 + .../modeling/test_minimax_m3_router_tc_gen.py | 125 + .../test_modeling_v2_m3_capture_boundary.py | 17 +- .../test_modeling_v2_m3_ctx_stack_route.py | 167 + .../unittest/_torch/models/test_minimax_m3.py | 193 +- .../_torch/modules/test_mxfp8_linear.py | 22 +- .../test_prequantized_mxfp8_streams.py | 66 + .../moe/test_cutedsl_rubin_deterministic.py | 197 + .../moe/test_cutedsl_swiglu_oai_resolution.py | 111 + .../moe/test_m3_fold_shared_finalize.py | 136 + .../_torch/moe/test_m3_router_tc_fp4_moe.py | 93 + .../_torch/moe/test_router_gemm_tf32.py | 217 + .../_torch/moe/test_unpermute_residual.py | 67 + .../_torch/peft/test_moe_lora_model_path.py | 8 + .../kv_cache/test_kv_cache_v2_scheduler.py | 156 + ...est_kv_connector_v2_prefix_real_manager.py | 115 + 85 files changed, 19332 insertions(+), 4686 deletions(-) create mode 100644 3rdparty/patches/fa4_fp8_rescale0.patch create mode 100644 cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.cu create mode 100644 cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.h create mode 100644 cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.cu create mode 100644 cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.h create mode 100644 cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp create mode 100644 cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp create mode 100644 examples/minimax_m3/rubin/README.md create mode 100644 examples/minimax_m3/rubin/agg/README.md create mode 100644 examples/minimax_m3/rubin/agg/agg_c14.yaml create mode 100644 examples/minimax_m3/rubin/agg/agg_c20.yaml create mode 100644 examples/minimax_m3/rubin/agg/agg_c46.yaml create mode 100644 examples/minimax_m3/rubin/agg/agg_c56.yaml create mode 100644 examples/minimax_m3/rubin/agg/agg_env.sh create mode 100644 examples/minimax_m3/rubin/ctx_agentx_c24.yaml create mode 100644 examples/minimax_m3/rubin/fp4_moe_tactics_tp2ctx_v1.json create mode 100755 examples/minimax_m3/rubin/setup_fa4.sh create mode 100644 tensorrt_llm/_torch/attention/backends/fmha/drafter_last_row.py create mode 100644 tensorrt_llm/_torch/attention/backends/fmha/msa_combine_mxfp8.py create mode 100644 tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/__init__.py create mode 100644 tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/clc_tile_scheduler.py create mode 100644 tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/kernel.py create mode 100644 tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py create mode 100644 tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py create mode 100644 tensorrt_llm/_torch/moe/fused_moe/router_gemm_tf32.py create mode 100644 tensorrt_llm/_torch/moe/fused_moe/unpermute_residual.py create mode 100644 tests/unittest/_torch/attention/fmha/test_msa_combine_mxfp8.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_fmha_sm107_gates.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4_arch.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_proxy_nofill.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_msa_k2q_ws_stream.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_msa_per_token_valid_blocks_numpy.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_msa_prefill_nvfp4_out_in_place.py create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_msa_proxy_few_rows_kv_splits.py create mode 100644 tests/unittest/_torch/attention/test_drafter_kv_tail_zero.py create mode 100644 tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py create mode 100644 tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py create mode 100644 tests/unittest/_torch/kernels/serial/test_m3_qkv_fusion.py create mode 100644 tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py create mode 100644 tests/unittest/_torch/modeling/test_minimax_m3_router_fp32_cast.py create mode 100644 tests/unittest/_torch/modeling/test_minimax_m3_router_tc_gen.py create mode 100644 tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_ctx_stack_route.py create mode 100644 tests/unittest/_torch/modules/test_prequantized_mxfp8_streams.py create mode 100644 tests/unittest/_torch/moe/test_cutedsl_rubin_deterministic.py create mode 100644 tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py create mode 100644 tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py create mode 100644 tests/unittest/_torch/moe/test_m3_router_tc_fp4_moe.py create mode 100644 tests/unittest/_torch/moe/test_router_gemm_tf32.py create mode 100644 tests/unittest/_torch/moe/test_unpermute_residual.py diff --git a/3rdparty/patches/fa4_fp8_rescale0.patch b/3rdparty/patches/fa4_fp8_rescale0.patch new file mode 100644 index 000000000000..4aa1392cdaa0 --- /dev/null +++ b/3rdparty/patches/fa4_fp8_rescale0.patch @@ -0,0 +1,11 @@ +--- a/flash_attn/cute/flash_fwd_sm100.py ++++ b/flash_attn/cute/flash_fwd_sm100.py +@@ -2021,7 +2021,7 @@ + + rescale_threshold = ( + 8.0 if const_expr(self.q_dtype.width == 16) else +- 4.0 if const_expr(self.q_dtype.width == 8) else ++ 0.0 if const_expr(self.q_dtype.width == 8) else + 0.0 + ) + softmax = SoftmaxSm100.create( diff --git a/3rdparty/patches/msa_strided_paged_kv.patch b/3rdparty/patches/msa_strided_paged_kv.patch index 6506479447a1..732680ff6b1b 100644 --- a/3rdparty/patches/msa_strided_paged_kv.patch +++ b/3rdparty/patches/msa_strided_paged_kv.patch @@ -1,8 +1,108 @@ diff --git a/python/fmha_sm100/api.py b/python/fmha_sm100/api.py -index b02f747..17d7cfb 100644 +index b02f747..47dea78 100644 --- a/python/fmha_sm100/api.py +++ b/python/fmha_sm100/api.py -@@ -532,9 +532,8 @@ def _fmha_sm100_plan( +@@ -17,6 +17,8 @@ __all__ = [ + ] + + import numpy as np ++import os as _ss_os0 ++_SS_VERIFY_ZERO = _ss_os0.environ.get("TLLM_FMHA_PLAN_SS_VERIFY", "0") == "1" + import torch + + from .jit import _dlpack_dtype_code, _PACK_FACTORS, get_fmha_variant, get_reduction_module, get_plan_fn, get_sparse_topk_module +@@ -91,6 +93,8 @@ def _get_workspace_buf(tag, device): + return _workspace_cache[device_id][tag] + + def _alloc_perplan_buf(tag, size, device, dtype): ++ if _SS_VERIFY_ZERO: ++ return torch.zeros(size, dtype=dtype, device=device) # verify mode only: unwritten tails compare equal + # global _workspace_cache + # device_id = torch.device(device).index + # buf = _workspace_cache[-1][device_id][tag] +@@ -482,6 +486,72 @@ def _make_plan_info( + }) + + ++# ---- MiniMax-M3 (SM107 only): DEFERRED split decision (exact). The adaptive plan's split decision (plan_cost[0] = split, ++# [1] = predicted speedup) is read back with plan_cost.tolist() in prepare(); its single-CTA plan kernel waits for an SM ++# under the previous step's kernels, so that read stalls the prepare thread (~1 ms per ctx-bearing step) and costs the ++# overlap scheduler its run-ahead. Deferred: the same plan kernel, its 2 floats copied to a pinned per-plan buffer with ++# an event, and the split-dependent plan fields filled at their first read -- the attention launch that consumes the plan, ++# an eager point, by which time the event has normally completed. The fields are then the ones the immediate read gives. ++# Never resolved under stream capture (asserted). Kill: TLLM_FMHA_PLAN_DEFER_READ=0. TLLM_FMHA_PLAN_DECISION_LOG= ++# appends one line per adaptive plan (split, speedup, max_kv_splits, total_qo) on either path, for the trace gate. ++_PLAN_DEFER_READ = _ss_os0.environ.get("TLLM_FMHA_PLAN_DEFER_READ", "1") != "0" ++_PLAN_DECISION_LOG = _ss_os0.environ.get("TLLM_FMHA_PLAN_DECISION_LOG") ++_SPLIT_KEYS = frozenset(( ++ "kv_tile_begin_indices", "kv_tile_end_indices", "kv_split_indices", "num_kv_splits", "workspace_o", ++ "workspace_lse", "predicted_speedup", "num_kv_splits_per_row", ++)) ++ ++ ++def _log_plan_decision(split, speedup, max_kv_splits, total_qo_len, path): ++ if _PLAN_DECISION_LOG: ++ with open(_PLAN_DECISION_LOG, "a") as f: ++ f.write(f"pid={_ss_os0.getpid()} {path} split={int(bool(split))} speedup={speedup!r} " ++ f"max_kv_splits={max_kv_splits} total_qo={total_qo_len}\n") ++ ++ ++class _DeferredSplitPlanInfo(PlanInfo): ++ """A PlanInfo whose split-dependent fields are filled from the plan's cost read at their first access.""" ++ ++ def _resolve(self): ++ lazy = self.__dict__.pop("_lazy", None) ++ if lazy is None: ++ return ++ if torch.cuda.is_current_stream_capturing(): ++ raise RuntimeError("fmha_sm100: a deferred plan decision was first read under CUDA graph capture") ++ lazy["event"].synchronize() ++ split_flag, speedup = lazy["host"].tolist() ++ do_split = split_flag > 0 ++ _log_plan_decision(do_split, speedup, lazy["max_kv_splits"], lazy["total_qo_len"], "deferred") ++ put = dict.__setitem__ ++ if do_split: ++ put(self, "workspace_o", _alloc_workspace_buf( ++ _BuffTag.workspace_o, lazy["total_qo_len"] * lazy["max_kv_splits"] * lazy["num_qo_heads"] * 128, ++ lazy["device"], dtype=torch.bfloat16)) ++ put(self, "num_kv_splits", lazy["max_kv_splits"]) ++ else: ++ for key in ("kv_tile_begin_indices", "kv_tile_end_indices", "kv_split_indices", ++ "num_kv_splits_per_row", "workspace_o", "workspace_lse"): ++ put(self, key, None) ++ put(self, "num_kv_splits", 1) ++ put(self, "predicted_speedup", speedup) ++ ++ def __getitem__(self, key): ++ if key in _SPLIT_KEYS and "_lazy" in self.__dict__: ++ self._resolve() ++ return dict.__getitem__(self, key) ++ ++ def get(self, key, default=None): ++ if key in _SPLIT_KEYS and "_lazy" in self.__dict__: ++ self._resolve() ++ return dict.get(self, key, default) ++ ++ def items(self): ++ # fmha_sm100_plan's mixed-batch path clones a sub-plan through items(): resolve first (that path keeps the ++ # immediate read). values() stays unresolved: the side-stream wrapper only record_stream()s the tensors. ++ self._resolve() ++ return dict.items(self) ++ ++ + def _call_plan(qo_segment_offsets, qo_segment_lens, kv_segment_lens, + packed_work_range, packed_work_info, + qo_tile_size, kv_tile_size, num_qo_heads, num_ctas, causal, +@@ -507,7 +577,7 @@ def _call_plan(qo_segment_offsets, qo_segment_lens, kv_segment_lens, + pack_factor, + ) + +-def _fmha_sm100_plan( ++def _fmha_sm100_plan_impl( + qo_segment_lens: torch.Tensor, + kv_segment_lens: torch.Tensor, + num_qo_heads: int, +@@ -532,9 +602,8 @@ def _fmha_sm100_plan( if kv_block_num > 0 and (sparse_kernel_mode == 'prefill' or (sparse_kernel_mode == 'auto' and max_qo_len_orig > _prefill_qlen_threshold(True))): # print("Nv-Prefill") @@ -14,7 +114,217 @@ index b02f747..17d7cfb 100644 return sparse_fmha_plan(qo_segment_lens=qo_segment_lens, kv_segment_lens=kv_segment_lens, num_qo_heads=num_qo_heads, causal=causal, qo_offset=qo_offset, num_kv_splits=num_kv_splits, page_size=page_size, output_maxscore=output_maxscore, -@@ -941,6 +940,62 @@ def _fmha_sm100( +@@ -652,7 +721,10 @@ def _fmha_sm100_plan( + kv_tile_end_indices = _alloc_perplan_buf(_BuffTag.kv_tile_end_indices, max_work_items, device, torch.int32) + kv_split_indices = _alloc_perplan_buf(_BuffTag.kv_split_indices, max_work_items, device, torch.int32) + num_kv_splits_per_row = _alloc_perplan_buf(_BuffTag.num_kv_splits_per_row, total_qo_len, device, torch.int32) +- plan_cost = _alloc_workspace_buf(_BuffTag.plan_cost, 2, device, dtype=torch.float32) ++ defer = _PLAN_DEFER_READ and _ss_is_sm107(device) and not torch.cuda.is_current_stream_capturing() ++ # A deferred read owns its plan_cost (the shared one may be rewritten by a later plan on another stream). ++ plan_cost = (torch.empty(2, dtype=torch.float32, device=device) if defer ++ else _alloc_workspace_buf(_BuffTag.plan_cost, 2, device, dtype=torch.float32)) + + lse_total_size = max_kv_splits * total_qo_len * num_qo_heads + workspace_lse = _alloc_perplan_buf(_BuffTag.workspace_lse, lse_total_size, device, torch.float32) +@@ -669,7 +741,32 @@ def _fmha_sm100_plan( + chunk_size, plan_cost, num_kv_splits_per_row, workspace_lse, lse_total_size, + pack_factor, cuda_stream) + ++ if defer: ++ host_cost = torch.empty(2, dtype=torch.float32, pin_memory=True) ++ host_cost.copy_(plan_cost, non_blocking=True) ++ cost_ready = torch.cuda.Event() ++ cost_ready.record() ++ info = _make_plan_info( ++ packed_work_range=packed_work_range, packed_work_info=packed_work_info, ++ kv_tile_begin_indices=kv_tile_begin_indices, kv_tile_end_indices=kv_tile_end_indices, ++ kv_split_indices=kv_split_indices, num_kv_splits=max_kv_splits, workspace_o=None, ++ workspace_lse=workspace_lse, max_qo_len=max_qo_len, predicted_speedup=None, ++ num_kv_splits_per_row=num_kv_splits_per_row, qo_segment_offsets=qo_segment_offsets, ++ kv_segment_offsets=kv_segment_offsets, kv_page_indptr=kv_page_indptr, max_k_tiles=max_k_tiles, ++ qo_segment_lens=qo_segment_lens_gpu, kv_segment_lens=kv_segment_lens, qo_offset=qo_offset, ++ pack_factor=pack_factor, orig_num_qo_heads=orig_num_qo_heads, ++ qo_len_uniform=qo_len_uniform, cute_workspace_buffer=cute_workspace_buffer) ++ deferred = _DeferredSplitPlanInfo(info) ++ # plan_cost is kept alive until the read resolves (the copy reads it on this stream). ++ deferred.__dict__["_lazy"] = dict(event=cost_ready, host=host_cost, plan_cost=plan_cost, ++ max_kv_splits=max_kv_splits, total_qo_len=total_qo_len, ++ num_qo_heads=num_qo_heads, device=device) ++ return deferred ++ ++ _tl0 = _ss_time.perf_counter() + _cost = plan_cost.tolist() ++ _log_plan_decision(_cost[0] > 0, _cost[1], max_kv_splits, total_qo_len, "immediate") ++ _SS_STATS["tl"].append((_ss_time.perf_counter() - _tl0) * 1e3) + do_split = _cost[0] > 0 + predicted_speedup = _cost[1] + +@@ -747,6 +844,164 @@ def _fmha_sm100_plan( + + + ++ ++# ---- TTFT/CTX: side-stream plan (exact). The adaptive plan reads plan_cost back to the host (.tolist()); on the current ++# stream that read waits for every kernel queued before it (the previous prefill chunk), so the host can no longer run ++# ahead. All plan inputs come from host lists and every plan buffer is fresh, so the whole plan can run on a dedicated ++# HIGH-priority stream: the read then waits only for the plan stream's own copies + the tiny plan kernel. The consumer ++# stream (caller's stream, else current) then waits device-side on the plan stream, and every returned tensor is ++# record_stream()'d for it. Same kernel, same inputs -> same plan. Kill: TLLM_FMHA_PLAN_SIDE_STREAM=0. ++import inspect as _ss_inspect ++import os as _ss_os ++import sys as _ss_sys ++import time as _ss_time ++ ++_SS_ON = _ss_os.environ.get("TLLM_FMHA_PLAN_SIDE_STREAM", "1") != "0" ++_SS_STREAMS = {} ++_SS_SIG = _ss_inspect.signature(_fmha_sm100_plan_impl) ++_SS_STATS = {"n": 0, "waits": [], "logged": False, "vn": 0, "vbad": 0, "tl": []} ++_SS_VERIFY = _ss_os.environ.get("TLLM_FMHA_PLAN_SS_VERIFY", "0") == "1" # gate arm only (implies a main-stream sync) ++ ++ ++_SS_CC = {} ++ ++ ++def _ss_index(device): ++ if device is None: ++ return torch.cuda.current_device() ++ if isinstance(device, int): ++ return device ++ d = torch.device(device) ++ return d.index if d.index is not None else torch.cuda.current_device() ++ ++ ++def _ss_is_sm107(device): ++ idx = _ss_index(device) ++ cc = _SS_CC.get(idx) ++ if cc is None: ++ cc = _SS_CC[idx] = torch.cuda.get_device_capability(idx) ++ return cc == (10, 7) ++ ++ ++def _ss_stream(device): ++ idx = _ss_index(device) ++ st = _SS_STREAMS.get(idx) ++ if st is None: ++ lo, hi = torch.cuda.Stream.priority_range() ++ st = _SS_STREAMS[idx] = torch.cuda.Stream(device=idx, priority=min(lo, hi)) ++ return st ++ ++ ++def _ss_tensors(obj): ++ if isinstance(obj, torch.Tensor): ++ yield obj ++ elif isinstance(obj, dict): ++ for v in obj.values(): ++ yield from _ss_tensors(v) ++ elif isinstance(obj, (list, tuple)): ++ for v in obj: ++ yield from _ss_tensors(v) ++ ++ ++def _ss_same(a, b): ++ if isinstance(a, torch.Tensor) or isinstance(b, torch.Tensor): ++ return (isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor) and a.shape == b.shape ++ and a.dtype == b.dtype and torch.equal(a, b)) ++ if isinstance(a, dict) and isinstance(b, dict): ++ return a.keys() == b.keys() and all(_ss_same(a[k], b[k]) for k in a) ++ if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): ++ return len(a) == len(b) and all(_ss_same(x, y) for x, y in zip(a, b)) ++ return a == b ++ ++ ++def _ss_verify(side_out, ref_out): ++ st = _SS_STATS ++ st["vn"] += 1 ++ ok = True ++ if isinstance(side_out, dict) and isinstance(ref_out, dict): ++ for k in side_out: ++ if k in ("cute_workspace_buffer", "workspace_o"): ++ continue # scratch buffers the plan never writes ++ if not _ss_same(side_out.get(k), ref_out.get(k)): ++ ok = False ++ _ss_sys.stderr.write(f"[fmha_sm100] SS VERIFY MISMATCH key={k}\n") ++ else: ++ ok = _ss_same(side_out, ref_out) ++ if not ok: ++ st["vbad"] += 1 ++ if st["vn"] % 200 == 0 or not ok: ++ _ss_sys.stderr.write(f"[fmha_sm100] SS VERIFY calls {st['vn']} mismatches {st['vbad']}\n") ++ ++ ++def _ss_eligible(b): ++ a = b.arguments ++ if not _ss_is_sm107(a.get("device")): ++ return False # validated on SM107 only: SM100 / SM103 keep the stock current-stream plan ++ for name in ("qo_segment_lens", "kv_segment_lens", "qo_offset"): ++ v = a.get(name) ++ if isinstance(v, torch.Tensor) and v.is_cuda: ++ return False # produced on a CUDA stream: reading it on the plan stream would race ++ if torch.cuda.is_current_stream_capturing(): ++ return False ++ kv_block_num = a.get("kv_block_num", -1) ++ mode = a.get("sparse_kernel_mode", "auto") ++ lens = a.get("qo_segment_lens") ++ mq = int(lens.max()) if isinstance(lens, torch.Tensor) and lens.numel() else 0 ++ if kv_block_num > 0 and (mode == "prefill" or (mode == "auto" and mq > _prefill_qlen_threshold(True))): ++ return False # sparse_fmha_plan branch: not audited for the side stream ++ return True ++ ++ ++def _ss_tl_report(tag): ++ st = _SS_STATS ++ st["n"] += 1 ++ if st["n"] % 50 == 0 and st["tl"]: ++ t = sorted(st["tl"]); st["tl"] = [] ++ _ss_sys.stderr.write(f"[fmha_sm100] {tag}: last {len(t)} plan_cost.tolist() host waits ms p50 " ++ f"{t[len(t)//2]:.3f} p99 {t[min(len(t)-1, int(0.99*len(t)))]:.3f} max {t[-1]:.3f}\n") ++ ++ ++def _fmha_sm100_plan(*args, **kwargs): ++ if not _SS_ON: ++ out = _fmha_sm100_plan_impl(*args, **kwargs) ++ _ss_tl_report("stock-stream plan (kill switch)") ++ return out ++ b = _SS_SIG.bind(*args, **kwargs) ++ b.apply_defaults() ++ if not _ss_eligible(b): ++ _SS_STATS["tl"].clear() # never reported on this path (e.g. off SM107): keep the sample list bounded ++ return _fmha_sm100_plan_impl(*args, **kwargs) ++ dev = b.arguments.get("device") ++ caller = b.arguments.get("stream") ++ consumer = torch.cuda.ExternalStream(caller) if isinstance(caller, int) and caller else torch.cuda.current_stream() ++ side = _ss_stream(dev) ++ b.arguments["stream"] = side.cuda_stream ++ t0 = _ss_time.perf_counter() ++ with torch.cuda.stream(side): ++ out = _fmha_sm100_plan_impl(*b.args, **b.kwargs) ++ dt = (_ss_time.perf_counter() - t0) * 1e3 ++ consumer.wait_stream(side) ++ for t in _ss_tensors(out): ++ if t.is_cuda: ++ t.record_stream(consumer) ++ if _SS_VERIFY: ++ _ss_verify(out, _fmha_sm100_plan_impl(*args, **kwargs)) ++ st = _SS_STATS ++ st["n"] += 1 ++ st["waits"].append(dt) ++ if not st["logged"]: ++ st["logged"] = True ++ _ss_sys.stderr.write("[fmha_sm100] plan decision on side stream taken (high priority)\n") ++ if st["n"] % 50 == 0: ++ w = sorted(st["waits"]); st["waits"] = [] ++ t = sorted(st["tl"]); st["tl"] = [] ++ if t: ++ _ss_sys.stderr.write(f"[fmha_sm100] side-stream plan: last {len(t)} plan_cost.tolist() host waits ms p50 " ++ f"{t[len(t)//2]:.3f} p99 {t[min(len(t)-1, int(0.99*len(t)))]:.3f} max {t[-1]:.3f}\n") ++ _ss_sys.stderr.write(f"[fmha_sm100] side-stream plan: last {len(w)} calls, plan wall ms (upper bound of the plan_cost read wait) p50 {w[len(w)//2]:.3f} " ++ f"p99 {w[min(len(w)-1, int(0.99*len(w)))]:.3f} max {w[-1]:.3f}\n") ++ return out ++ + def _fmha_sm100( + q: torch.Tensor, + k: torch.Tensor, +@@ -941,6 +1196,62 @@ def _fmha_sm100( return out, max_score @@ -77,7 +387,7 @@ index b02f747..17d7cfb 100644 def fmha_sm100_plan( qo_segment_lens: torch.Tensor, kv_segment_lens: torch.Tensor, -@@ -973,9 +1028,11 @@ def fmha_sm100_plan( +@@ -973,9 +1284,11 @@ def fmha_sm100_plan( ``kv_segment_lens - qo_segment_lens`` for bottom-right causal masking. A tensor must have shape ``[batch_size]``. split_prefill_decode : bool, optional @@ -92,7 +402,7 @@ index b02f747..17d7cfb 100644 **kwargs Planner options forwarded to ``_fmha_sm100_plan``. Common options are ``num_kv_heads``, ``num_kv_splits``, ``page_size``, -@@ -985,8 +1042,13 @@ def fmha_sm100_plan( +@@ -985,8 +1298,13 @@ def fmha_sm100_plan( Returns ------- tuple @@ -108,7 +418,7 @@ index b02f747..17d7cfb 100644 """ # assert qo_segment_lens.device.type == 'cpu' \ -@@ -997,31 +1059,23 @@ def fmha_sm100_plan( +@@ -997,31 +1315,23 @@ def fmha_sm100_plan( qo_offset = kv_segment_lens - qo_segment_lens elif isinstance(qo_offset, int): qo_offset = torch.full_like(qo_segment_lens, qo_offset) @@ -153,7 +463,7 @@ index b02f747..17d7cfb 100644 qo_offset=qo_offset, **kwargs) return (False, 0, batch_size, plan, None) -@@ -1081,16 +1135,23 @@ def fmha_sm100( +@@ -1081,16 +1391,23 @@ def fmha_sm100( ------- tuple[torch.Tensor | None, torch.Tensor | None] ``(out, max_score)``. Either item may be ``None`` if the corresponding @@ -182,7 +492,7 @@ index b02f747..17d7cfb 100644 is_paged = kv_indices is not None nnz_qo = q.shape[0] num_qo_heads = q.shape[1] -@@ -1101,10 +1162,12 @@ def fmha_sm100( +@@ -1101,10 +1418,12 @@ def fmha_sm100( if is_paged: k_decode, v_decode = k, v k_prefill, v_prefill = k, v @@ -199,7 +509,7 @@ index b02f747..17d7cfb 100644 decode_kv_indices = kv_indices[:kv_page_split] prefill_kv_indices = kv_indices[kv_page_split:] else: -@@ -1129,27 +1192,35 @@ def fmha_sm100( +@@ -1129,27 +1448,35 @@ def fmha_sm100( decode_qo_offset = None prefill_qo_offset = None @@ -240,4756 +550,6507 @@ index b02f747..17d7cfb 100644 out.copy_(combined_out) # ---- Merge max_score ---- -diff --git a/python/fmha_sm100/cute/interface.py b/python/fmha_sm100/cute/interface.py -index d72b17a..0cf430c 100644 ---- a/python/fmha_sm100/cute/interface.py -+++ b/python/fmha_sm100/cute/interface.py -@@ -136,6 +136,35 @@ def _prepare_paged_kv_for_tma(k, v, blk_kv: int): - return k, v - +diff --git a/python/fmha_sm100/csrc/fmha_sm100_inst.jinja b/python/fmha_sm100/csrc/fmha_sm100_inst.jinja +index 6949035..ec10e51 100644 +--- a/python/fmha_sm100/csrc/fmha_sm100_inst.jinja ++++ b/python/fmha_sm100/csrc/fmha_sm100_inst.jinja +@@ -1,4 +1,5 @@ + // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax ++// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES + // SPDX-License-Identifier: MIT -+def _prepare_paged_hnd_input(tensor: torch.Tensor, blk_kv: int) -> torch.Tensor: -+ """Keep TMA-compatible paged HND views strided across physical pages. -+ -+ The sparse prefill kernel imports the runtime tensor strides through -+ DLPack. It requires each ``[page_size, head_dim]`` head plane to be packed, -+ but the outer physical-page stride may include other coalesced cache roles. -+ Materialize every other layout to preserve the public API's old contract. -+ """ -+ if tensor.ndim != 4: -+ return tensor.contiguous() -+ if int(tensor.shape[2]) != int(blk_kv): -+ return tensor -+ -+ head_dim = int(tensor.shape[3]) -+ page_size = int(tensor.shape[2]) -+ packed_within_page = ( -+ tensor.stride(3) == 1 -+ and tensor.stride(2) == head_dim -+ and tensor.stride(1) == page_size * head_dim -+ ) -+ alignment_bytes = 16 -+ aligned_for_tma = ( -+ tensor.data_ptr() % alignment_bytes == 0 -+ and tensor.stride(0) >= 0 -+ and tensor.stride(0) * tensor.element_size() % alignment_bytes == 0 -+ ) -+ return tensor if packed_within_page and aligned_for_tma else tensor.contiguous() -+ -+ - def _validate_cu_seqlens( - cu_seqlens: torch.Tensor, - *, -@@ -303,8 +332,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - q: torch.Tensor, - k: torch.Tensor, - v: torch.Tensor, -- k_scale_128x4: torch.Tensor, -- v_scale_128x4: torch.Tensor, -+ k_scale: torch.Tensor, -+ v_scale: torch.Tensor, - k_global_scale: Optional[torch.Tensor], - v_global_scale: Optional[torch.Tensor], - k2q_row_ptr: torch.Tensor, -@@ -326,10 +355,14 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - ) - if k.dtype != torch.uint8 or v.dtype != torch.uint8: - raise TypeError(f"KVFP4 k/v must be torch.uint8, got {k.dtype} and {v.dtype}") -- if k_scale_128x4.dtype != torch.uint8 or v_scale_128x4.dtype != torch.uint8: -+ if k_scale.dtype != torch.uint8 or v_scale.dtype != torch.uint8: -+ # NOTE: vllm.utils.torch_utils.nvfp4_split_data_scale (:466) hands back -+ # the scale view as float8_e4m3fn, not uint8. The caller must pass -+ # ``sf.view(torch.uint8)`` -- zero-copy, same bytes -- or this raises. - raise TypeError( - "KVFP4 block scales must be torch.uint8 E4M3 tensors, got " -- f"{k_scale_128x4.dtype} and {v_scale_128x4.dtype}" -+ f"{k_scale.dtype} and {v_scale.dtype}; a vLLM scale view from " -+ "nvfp4_split_data_scale is float8_e4m3fn and needs .view(torch.uint8)" - ) - if k_global_scale is not None and k_global_scale.dtype != torch.float32: - raise TypeError("KVFP4 K global scale must be a torch.float32 tensor or None") -@@ -338,8 +371,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - tensors = ( - k, - v, -- k_scale_128x4, -- v_scale_128x4, -+ k_scale, -+ v_scale, - k2q_row_ptr, - k2q_q_indices, - cu_seqlens_q, -@@ -352,12 +385,15 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - raise ValueError(f"KVFP4 k and v must have the same shape, got {k.shape} and {v.shape}") - packed_dim = q.shape[-1] // 2 - scale_cols = q.shape[-1] // 16 -- if k_scale_128x4.ndim != 2 or v_scale_128x4.ndim != 2: -- raise ValueError("KVFP4 block scales must be rank-2 128x4 tiled tensors") -- if k_scale_128x4.shape[1] < scale_cols or v_scale_128x4.shape[1] < scale_cols: -- raise ValueError( -- "KVFP4 block scales must have at least D/16 columns; " -- f"need {scale_cols}, got {k_scale_128x4.shape[1]} and {v_scale_128x4.shape[1]}" -+ # head_size % 64 == 0 <=> scale_cols % 4 == 0. The V token-quad swizzle -+ # (t//4)*(4*S) + 4*s + (t%4) is a bijection over a region for ANY S, so a -+ # bijectivity check cannot catch a ragged S; only 4 | S makes it agree with -+ # vLLM's writer, whose swizzle group size is scale_dim/4 -+ # (nvfp4_kv_cache_kernels.cu:25-39, checked at :208-215). -+ if scale_cols % 4 != 0: -+ raise NotImplementedError( -+ "KVFP4 scale factors require head_size % 64 == 0 so that D/16 is " -+ f"divisible by 4; got D={int(q.shape[-1])}, D/16={scale_cols}" - ) - if k_global_scale is not None and k_global_scale.numel() < 1: - raise ValueError("KVFP4 K global scale must contain at least one element") -@@ -373,7 +409,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - raise ValueError(f"KVFP4 packed K/V last dimension must be D/2={packed_dim}") - total_k = int(k.shape[0]) - head_kv = int(k.shape[1]) -- required_scale_rows = total_k * head_kv -+ num_pages = None -+ page_size = None - else: - if k.ndim != 4: - raise ValueError( -@@ -388,7 +425,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - f"KVFP4 Sparse Page Attention requires page_size == blk_kv, got {page_size} vs {blk_kv}" - ) - head_kv = int(k.shape[1]) -- required_scale_rows = int(k.shape[0]) * head_kv * page_size -+ total_k = None -+ num_pages = int(k.shape[0]) - if page_table.device != q.device: - raise ValueError("page_table must be on the same device as q") - if page_table.dtype != torch.int32: -@@ -405,13 +443,102 @@ def _validate_csr_varlen_nvfp4_kv_inputs( - if not seqused_k.is_contiguous(): - raise ValueError("seqused_k must be contiguous") + // Auto-generated FMHA variant: {{ variant_name }} +@@ -28,12 +29,14 @@ cudaError_t {{ func_name }}(const FMHACutlassSM100Params& p) { -- padded_scale_rows = ((required_scale_rows + 127) // 128) * 128 -- padded_scale_cols = ((scale_cols + 3) // 4) * 4 -- for name, scale in (("k_scale_128x4", k_scale_128x4), ("v_scale_128x4", v_scale_128x4)): -- if scale.shape[0] < padded_scale_rows or scale.shape[1] < padded_scale_cols: -+ # ---- scale-factor containers ------------------------------------------- -+ # A scale region is EXACTLY region_tokens * D/16 bytes: no row padding, no -+ # column padding. (The deleted 128x4 layout demanded -+ # round_up(rows,128) x round_up(cols,4); nothing here does.) The kernel -+ # addresses inside a region with page/head strides supplied by the host, -+ # so what has to be checked is the shape and the *in-region* byte order. -+ for name, scale in (("k_scale", k_scale), ("v_scale", v_scale)): -+ if scale.stride(-1) != 1: -+ raise ValueError( -+ f"{name} must be contiguous in its last dimension, got " -+ f"stride(-1)={scale.stride(-1)}" -+ ) -+ if page_table is None: -+ expected = (total_k, head_kv, scale_cols) -+ if scale.ndim != 3 or tuple(int(d) for d in scale.shape) != expected: -+ raise ValueError( -+ f"KVFP4 flat-varlen {name} must have shape " -+ f"[total_k, Hkv, D/16] = {expected}, got " -+ f"{tuple(int(d) for d in scale.shape)}" -+ ) -+ # Flat varlen has no production producer (vLLM is paged only); it -+ # exists because flat test inputs are cheap. The kernel derives -+ # the flat region geometry in-kernel from num_heads_kv and S and -+ # IGNORES the four host stride arguments, so the container has to -+ # be exactly the plain contiguous one it assumes. -+ if ( -+ int(scale.stride(0)) != head_kv * scale_cols -+ or int(scale.stride(1)) != scale_cols -+ ): -+ raise ValueError( -+ f"KVFP4 flat-varlen {name} must be contiguous with strides " -+ f"{(head_kv * scale_cols, scale_cols, 1)}, got " -+ f"{tuple(int(s) for s in scale.stride())}" -+ ) -+ else: -+ expected = (num_pages, head_kv, page_size, scale_cols) -+ if scale.ndim != 4 or tuple(int(d) for d in scale.shape) != expected: -+ raise ValueError( -+ f"KVFP4 paged {name} must have shape " -+ f"[num_pages, Hkv, page_size, D/16] = {expected}, got " -+ f"{tuple(int(d) for d in scale.shape)}" -+ ) -+ # HND ONLY -- and this is not an arbitrary house rule. vLLM's -+ # NVFP4 store kernel sniffs the physical layout from strides, -+ # `bool is_hnd = key_cache.stride(2) > key_cache.stride(1)` -+ # (csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu:222, on the -+ # logical [pages, block, heads, dim] view), and then picks -+ # HND: scale_head_stride = block_size*S, token stride = S -+ # NHD: scale_head_stride = S, token stride = Hkv*S -+ # (:245-251). MSA's in-region offsets -- `t*S + s` for K and -+ # `(t//4)*(4*S) + 4*s + (t%4)` for V, the latter round-tripped -+ # through `swizzled_t * scale_block_offset_stride + swizzled_s` -+ # at :167-170 -- are correct ONLY when the token stride is S, -+ # i.e. only under HND. The kernel BAKES IN token stride == S; it -+ # does not read stride(2). So `stride(1) > stride(2)` alone is not -+ # enough: pin both inner strides exactly. Under NHD a -+ # per-(page, head) region is not contiguous at all, yet every -+ # shape, dtype, size(-1) and stride(-1) check above still passes -+ # and the kernel would read silently wrong bytes -- no exception, -+ # just degraded accuracy. M3 is HND -+ # (vllm/models/minimax_m3/nvidia/sparse_attention_msa.py:86-95), -+ # so assert it rather than discovering it as an accuracy loss. -+ if ( -+ int(scale.stride(2)) != scale_cols -+ or int(scale.stride(1)) != page_size * scale_cols -+ ): -+ raise ValueError( -+ f"KVFP4 paged {name} must use the HND NVFP4 KV-cache " -+ "layout: token stride must be exactly D/16==" -+ f"{scale_cols} and head stride exactly page_size*D/16==" -+ f"{page_size * scale_cols}; got stride(1)=" -+ f"{int(scale.stride(1))}, stride(2)={int(scale.stride(2))}. " -+ "NHD is unsupported: vLLM's writer branches on " -+ "`is_hnd = key_cache.stride(2) > key_cache.stride(1)` " -+ "(nvfp4_kv_cache_kernels.cu:222) and lays the scale bytes " -+ "out differently (:245-251), which no shape or dtype check " -+ "can catch." -+ ) -+ -+ # Packed FP4 data. These are no longer forced contiguous at the call site -+ # (that copied the whole KV cache against a vLLM view), so state the two -+ # properties the TMA descriptor actually needs. -+ for name, data in (("k", k), ("v", v)): -+ if int(data.stride(-1)) != 1: - raise ValueError( -- f"{name} is too small for 128x4 layout: got {tuple(scale.shape)}, " -- f"need at least {(padded_scale_rows, padded_scale_cols)}" -+ f"KVFP4 {name} must be contiguous in its last dimension, got " -+ f"stride(-1)={int(data.stride(-1))}" -+ ) -+ if page_table is not None and int(data.stride(1)) <= int(data.stride(2)): -+ # HND, for the same reason as the scale views above: the page/head -+ # addressing and the TMA descriptor assume head-major pages. -+ raise ValueError( -+ f"KVFP4 paged {name} must use the HND NVFP4 KV-cache layout " -+ f"(head stride > token stride); got stride(1)=" -+ f"{int(data.stride(1))}, stride(2)={int(data.stride(2))}. " -+ "See nvfp4_kv_cache_kernels.cu:222." - ) + using ActiveMaskType = {% if pack_factor is defined and pack_factor > 1 %}PackedCausalMask<{{ pack_factor }}>{% else %}CausalMask{% endif %}; - if k2q_row_ptr.device != q.device or k2q_q_indices.device != q.device: -@@ -622,6 +749,7 @@ def sparse_atten_func( - usable_SM_count: int = -1, - qk_dtype: Optional[torch.dtype] = None, - pv_dtype: Optional[torch.dtype] = None, -+ out: Optional[torch.Tensor] = None, - ): - """Run SM100 CSR block-sparse varlen attention. +- return run_fmha_fwd( ++ cutlass::fmha::collective::SparseAttnMode::{{ sparse_mode }}, ++ decltype(unit_selector_column)::value>( + p.workspace_buffer_ptr, + static_cast(p.q_ptr), + static_cast(p.k_ptr), +@@ -58,6 +61,7 @@ cudaError_t {{ func_name }}(const FMHACutlassSM100Params& p) { + p.kv_indices_ptr, p.kv_page_indptr_ptr, p.total_page_num, + p.max_score_ptr, p.max_k_tiles, + p.kv_block_indexes_ptr, p.kv_block_num, ++ p.kv_block_stride_n, p.kv_block_stride_h, p.kv_block_stride_b, + p.pack_factor, p.q_stride_n_original, p.q_stride_h_original, p.h_r_original, + flashinfer::PackGQAUnpackParams{p.max_score_direct_ptr, p.total_qo_len_orig, + p.o_direct_ptr, p.num_qo_heads_orig, +@@ -67,4 +71,13 @@ cudaError_t {{ func_name }}(const FMHACutlassSM100Params& p) { + #endif + }, + p.num_ctas); ++ }; ++{% if dtype_in == "nv_bfloat16" and page_size > 0 and sparse_mode == "Sparse" %} ++ // The selector layout is host metadata; capture the matching existing kernel ++ // specialization without copying the selector or reading device values. ++ if (p.kv_block_stride_b == 1) { ++ return run(cute::true_type{}); ++ } ++{% endif %} ++ return run(cute::false_type{}); + } +diff --git a/python/fmha_sm100/csrc/fmha_sm100_params.h b/python/fmha_sm100/csrc/fmha_sm100_params.h +index 878a90c..8972c64 100644 +--- a/python/fmha_sm100/csrc/fmha_sm100_params.h ++++ b/python/fmha_sm100/csrc/fmha_sm100_params.h +@@ -1,4 +1,5 @@ + // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax ++// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES + // SPDX-License-Identifier: MIT -@@ -691,6 +819,10 @@ def sparse_atten_func( - pv_dtype : torch.dtype, optional - Compile-time MMA operand dtype for PV. Defaults to V storage dtype, - except supported FP8 K/V cache staging modes. -+ out : torch.Tensor, optional -+ Destination for the attention output, written in place by the reduction -+ instead of being allocated here. Must be contiguous BF16 of shape -+ ``[total_q, Hq, 128]`` on the same device as ``q``. + #pragma once +@@ -54,6 +55,9 @@ struct FMHACutlassSM100Params { + int max_k_tiles; + int* kv_block_indexes_ptr; + int kv_block_num; ++ int64_t kv_block_stride_n = 0; ++ int64_t kv_block_stride_h = 0; ++ int64_t kv_block_stride_b = 1; + int pack_factor = 1; + int h_r_original = 0; + int q_stride_n_original = 0; +diff --git a/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja b/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja +index 7e21585..ac0ac05 100644 +--- a/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja ++++ b/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja +@@ -1,9 +1,11 @@ + // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax ++// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES + // SPDX-License-Identifier: MIT - Returns - ------- -@@ -736,10 +868,21 @@ def sparse_atten_func( - max_seqlen_q = int(max_seqlen_q) - max_seqlen_k = int(max_seqlen_k) + // Auto-generated per-variant FMHA run binding: {{ variant_name }} + #include "fmha_sm100_params.h" + #include "tvm_ffi_utils.h" ++#include + #include + #include -+ k_input = ( -+ k.contiguous() -+ if page_table is None -+ else _prepare_paged_hnd_input(k, blk_kv) -+ ) -+ v_input = ( -+ v.contiguous() -+ if page_table is None -+ else _prepare_paged_hnd_input(v, blk_kv) -+ ) -+ - return _sparse_atten_csr_varlen_forward( - q.contiguous(), -- k.contiguous(), -- v.contiguous(), -+ k_input, -+ v_input, - k2q_row_ptr.contiguous(), - k2q_q_indices.contiguous(), - int(topK), -@@ -762,6 +905,7 @@ def sparse_atten_func( - int(max_seqlen_k), - qk_dtype, - pv_dtype, -+ out=out, - ) +@@ -121,9 +123,25 @@ void FMHAVariantRun_{{ variant_name }}(ffi::TensorView workspace_buffer, ffi::Te + params.max_score_ptr = max_score_ptr; + params.max_k_tiles = static_cast(max_k_tiles); + params.kv_block_indexes_ptr = kv_block_indexes_ptr; +- params.kv_block_num = maybe_kv_block_indexes.has_value() +- ? static_cast(maybe_kv_block_indexes.value().size(2)) +- : 0; ++ params.kv_block_num = 0; ++ if (maybe_kv_block_indexes.has_value()) { ++ auto const selector = maybe_kv_block_indexes.value(); ++ CHECK_CUDA(selector); ++ CHECK_DEVICE(selector, q); ++ CHECK_INPUT_TYPE(selector, dl_int32); ++ CHECK_DIM(3, selector); ++ TVM_FFI_ICHECK_EQ(selector.size(0), q.size(0)); ++ TVM_FFI_ICHECK_EQ(selector.size(1), num_kv_heads); ++ TVM_FFI_ICHECK_GT(selector.size(2), 0); ++ TVM_FFI_ICHECK_LE(selector.size(2), INT_MAX); ++ for (int dim = 0; dim < 3; ++dim) { ++ TVM_FFI_ICHECK_GE(selector.stride(dim), 0); ++ } ++ params.kv_block_num = static_cast(selector.size(2)); ++ params.kv_block_stride_n = selector.stride(0); ++ params.kv_block_stride_h = selector.stride(1); ++ params.kv_block_stride_b = selector.stride(2); ++ } + params.pack_factor = static_cast(pack_factor); + params.num_ctas = static_cast(packed_work_range.size(0)); +@@ -187,10 +205,18 @@ void FMHAVariantRun_{{ variant_name }}(ffi::TensorView workspace_buffer, ffi::Te + ? static_cast(maybe_max_score.value().size(0) + * maybe_max_score.value().size(1) + * maybe_max_score.value().size(2)) : 0; +- params.gmem_bounds.kv_block_indexes_numel = maybe_kv_block_indexes.has_value() +- ? static_cast(maybe_kv_block_indexes.value().size(0) +- * maybe_kv_block_indexes.value().size(1) +- * maybe_kv_block_indexes.value().size(2)) : 0; ++ // A sliced head-major view can span more storage than its logical numel. ++ // TensorView::data_ptr() already includes the view's storage offset. ++ params.gmem_bounds.kv_block_indexes_span = 0; ++ if (maybe_kv_block_indexes.has_value()) { ++ auto const selector = maybe_kv_block_indexes.value(); ++ if (selector.size(0) > 0 && selector.size(1) > 0) { ++ params.gmem_bounds.kv_block_indexes_span = ++ (selector.size(0) - 1) * params.kv_block_stride_n ++ + (selector.size(1) - 1) * params.kv_block_stride_h ++ + (selector.size(2) - 1) * params.kv_block_stride_b + 1; ++ } ++ } + params.gmem_bounds.split_kv_size = maybe_kv_tile_begin_indices.has_value() + ? static_cast(maybe_kv_tile_begin_indices.value().size(0)) : 0; + params.gmem_bounds.qo_offsets_size = maybe_qo_offsets.has_value() +diff --git a/python/fmha_sm100/csrc/gmem_bounds_check.h b/python/fmha_sm100/csrc/gmem_bounds_check.h +index 9d0e672..a2759e9 100644 +--- a/python/fmha_sm100/csrc/gmem_bounds_check.h ++++ b/python/fmha_sm100/csrc/gmem_bounds_check.h +@@ -1,4 +1,5 @@ + // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax ++// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES + // SPDX-License-Identifier: MIT -@@ -769,8 +913,8 @@ def sparse_atten_nvfp4_kv_func( - q: torch.Tensor, - k: torch.Tensor, - v: torch.Tensor, -- k_scale_128x4: torch.Tensor, -- v_scale_128x4: torch.Tensor, -+ k_scale: torch.Tensor, -+ v_scale: torch.Tensor, - k_global_scale: Optional[torch.Tensor], - v_global_scale: Optional[torch.Tensor], - k2q_row_ptr: torch.Tensor, -@@ -805,16 +949,25 @@ def sparse_atten_nvfp4_kv_func( - because each byte packs two FP4 values. - v : torch.Tensor - Packed NVFP4 V data with the same shape as ``k``. -- k_scale_128x4 : torch.Tensor -- K block scales in cuBLAS/cuDNN 128x4 tiled storage. Dtype uint8 -- containing FP8 E4M3 scale values. -- v_scale_128x4 : torch.Tensor -- V block scales in the same 128x4 tiled storage. -+ k_scale : torch.Tensor -+ K block scales, dtype uint8 holding FP8 E4M3 values, in the **linear** -+ scale-factor layout: byte ``t*S + s`` inside each scale region, with -+ ``S = 128//16 = 8``. Shape is ``[num_pages, Hkv, blk_kv, S]`` (paged) -+ or ``[total_k, Hkv, S]`` (flat), with no row or column padding -- a -+ region is exactly ``blk_kv * S`` bytes. Paged views must be HND (see -+ ``_validate_csr_varlen_nvfp4_kv_inputs``). A vLLM scale view from -+ ``nvfp4_split_data_scale`` is ``float8_e4m3fn`` and must be passed as -+ ``.view(torch.uint8)`` -- zero-copy, but a ``TypeError`` if forgotten. -+ v_scale : torch.Tensor -+ V block scales, same shape and dtype rules, but in the **4x4 -+ token-quad swizzle**: byte ``(t//4)*(4*S) + 4*s + (t%4)``. This is the -+ K/V layout pair vLLM's NVFP4 KV-cache store kernel writes, so a vLLM -+ cache is consumed with no repack pass. - k_global_scale : torch.Tensor, optional - FP32 tensor/global dequant scale for K. May be ``None``. - v_global_scale : torch.Tensor, optional -- FP32 tensor/global dequant scale for V. May be ``None``. The V global -- scale is applied in the combine stage. -+ FP32 tensor/global dequant scale for V. May be ``None``. FP8 staging -+ applies it before conversion; BF16 staging applies it during combine. - k2q_row_ptr : torch.Tensor - CSR row pointers with shape ``[Hkv, total_rows + 1]`` and dtype int32. - k2q_q_indices : torch.Tensor -@@ -847,7 +1000,14 @@ def sparse_atten_nvfp4_kv_func( - Paged-KV physical page table with shape - ``[batch_size, max_num_pages_per_seq]`` and dtype int32. - seqused_k : torch.Tensor, optional -- Effective KV length per request for paged causal attention. -+ Effective KV length per request for paged causal attention. **Always -+ pass this for paged KV.** Without it ``_logical_seqlen_k`` falls back -+ to ``page_table.shape[1] * page_size`` -- the full *allocated* span -- -+ so every KV block looks fully valid and the mask silently does nothing. -+ The failure mode is not NaN: unwritten K dequantizes to 0, giving -+ ``S = 0``, which still receives non-zero softmax weight and inflates -+ ``row_sum``. The output is then uniformly scaled down and reads like a -+ tolerance problem. - schedule : SparseAttentionSchedule, optional - Prebuilt sparse forward schedule. + #pragma once +@@ -9,6 +10,7 @@ + #ifdef FMHA_GMEM_BOUNDS_CHECK -@@ -878,8 +1038,8 @@ def sparse_atten_nvfp4_kv_func( - q, - k, - v, -- k_scale_128x4, -- v_scale_128x4, -+ k_scale, -+ v_scale, - k_global_scale, - v_global_scale, - k2q_row_ptr, -@@ -939,12 +1099,19 @@ def sparse_atten_nvfp4_kv_func( - k2q_qsplit_indices = schedule.qsplit_indices - split_counts = schedule.split_counts + #include ++#include -+ # K/V and their block scales are deliberately NOT forced contiguous. They -+ # are consumed through TMA descriptors (data) and host-supplied page/head -+ # strides (scales), both of which handle the strided views vLLM hands in. -+ # ``.contiguous()`` here would copy the *entire* selected KV cache on every -+ # layer of every forward against a ``nvfp4_split_data_scale`` view. The -+ # validator asserts what actually matters instead: exact shapes, -+ # ``stride(-1) == 1`` and the HND inner strides. - schedule = _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - q.contiguous(), -- k.contiguous(), -- v.contiguous(), -- k_scale_128x4.contiguous(), -- v_scale_128x4.contiguous(), -+ k, -+ v, -+ k_scale, -+ v_scale, - None if k_global_scale is None else k_global_scale.contiguous(), - None if v_global_scale is None else v_global_scale.contiguous(), - k2q_row_ptr.contiguous(), -@@ -978,7 +1145,7 @@ def sparse_atten_nvfp4_kv_func( - lse_temperature_out=LSE_temperature_out, - cu_seqlens=cu_seqlens_q, - split_counts=split_counts, -- output_scale=v_global_scale, -+ output_scale=None if q.dtype == torch.float8_e4m3fn else v_global_scale, - use_pdl=True, - ) - if temperature_lse_fast_path: -@@ -1296,13 +1463,34 @@ class SparseDecodePagedAttentionWrapper: - self.work_count = schedule.work_count - self.padded_work_count = schedule.padded_work_count - if schedule.split_kv: -+ # O_partial stays uninitialised on purpose: it is only ever read -+ # for splits whose LSE_partial weight is non-zero (combine.py's -+ # ``scale[m] > 0.0`` predicate, and the ``thr_max_valid_split`` -+ # loop bound), so seeding LSE_partial below is enough to make any -+ # unwritten partial row neutral. Zeroing O_partial as well was -+ # measured at +1.7% .. +17.7% of the decode forward (it scales -+ # with partial_rows: 12us for a 64MiB partial buffer, 140us for a -+ # 1GiB one), which is not worth paying for a strictly weaker -+ # guarantee. - self.O_partial = torch.empty( - (schedule.partial_rows, self.num_qo_heads, self.head_dim), - dtype=torch.float32, - device=page_table.device, - ) -- self.LSE_partial = torch.empty( -+ # -inf, not torch.empty. If the forward ever fails to write a -+ # partial row -- a pipeline desync, a schedule bug, a future -+ # kernel edit -- torch.empty makes the combine consume whatever -+ # was in that allocation, which is non-deterministic garbage and -+ # was exactly what turned a decode desync into randomly varying -+ # NaNs. Seeding -inf gives the combine a defined answer instead: -+ # exp(-inf - lse_max) == 0, so the split is dropped, the result is -+ # reproducible, and a correctness test can actually catch it. -+ # Cost is one ~5-6us launch-bound fill per plan() (partial_rows x -+ # Hq fp32 is small), i.e. ~2.5% of plan() and 0.7-4% of the -+ # forward. -+ self.LSE_partial = torch.full( - (schedule.partial_rows, self.num_qo_heads), -+ float("-inf"), - dtype=torch.float32, - device=page_table.device, - ) -@@ -1449,6 +1637,7 @@ def _sparse_atten_csr_varlen_forward( - max_seqlen_k: int, - qk_dtype: torch.dtype, - pv_dtype: torch.dtype, -+ out: Optional[torch.Tensor] = None, - ): - total_q, head_q, dim = q.shape - if head_q % head_kv != 0: -@@ -1478,7 +1667,24 @@ def _sparse_atten_csr_varlen_forward( - if kernel_return_temperature_lse - else None - ) -- O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device) -+ if out is None: -+ O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device) -+ else: -+ # `combine` writes its output with a plain contiguous layout, so a -+ # caller that already owns a matching buffer can have it written -+ # directly instead of copying the result afterwards. -+ if tuple(out.shape) != (total_q, head_q, dim): -+ raise ValueError( -+ f"out must have shape {(total_q, head_q, dim)}, " -+ f"got {tuple(out.shape)}" -+ ) -+ if out.dtype != torch.bfloat16: -+ raise TypeError(f"out must be torch.bfloat16, got {out.dtype}") -+ if out.device != q.device: -+ raise ValueError("out must be on the same device as q") -+ if not out.is_contiguous(): -+ raise ValueError("out must be contiguous") -+ O_out = out - LSE_out = torch.empty(total_q, head_q, dtype=torch.float32, device=q.device) - LSE_temperature_out = ( - torch.empty_like(LSE_out) if kernel_return_temperature_lse else None -@@ -1807,12 +2013,47 @@ def _call_sparse_forward_sm100_csr_varlen( - return schedule + struct GmemBounds { + int packed_work_range_size; +@@ -19,17 +21,17 @@ struct GmemBounds { + int kv_page_indptr_size; + int kv_indices_size; + int max_score_numel; +- int kv_block_indexes_numel; ++ int64_t kv_block_indexes_span; + int split_kv_size; + int qo_offsets_size; + }; + template + __device__ __forceinline__ T gmem_load_checked( +- const T* base, int idx, int size, const char* name) { ++ const T* base, int64_t idx, int64_t size, const char* name) { + if (__builtin_expect(idx < 0 || idx >= size, 0)) { +- printf("GMEM-OOB-LOAD [%s] idx=%d size=%d blk=(%d,%d,%d) thr=%d\n", +- name, idx, size, blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x); ++ printf("GMEM-OOB-LOAD [%s] idx=%lld size=%lld blk=(%d,%d,%d) thr=%d\n", ++ name, static_cast(idx), static_cast(size), blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x); + return T(0); + } + return base[idx]; +@@ -82,6 +84,7 @@ __device__ __forceinline__ bool gmem_range_ok( + // Macros for paged KV reads + #define KV_INDPTR_LOAD(ptr, idx, sz) gmem_load_checked((ptr), (idx), (sz), "kv_page_indptr") + #define KV_INDICES_LOAD(ptr, idx, sz) gmem_load_checked((ptr), (idx), (sz), "kv_indices") ++#define KV_BLOCK_INDEX_LOAD(ptr, idx, sz) gmem_load_checked((ptr), (idx), (sz), "kv_block_indexes") -+_INT32_MAX = 2**31 - 1 -+ -+ -+def _nvfp4_scale_strides(sf, name: str) -> tuple[int, int]: -+ """Return ``(page_stride, head_stride)`` of an NVFP4 scale view, in BYTES. -+ -+ The kernel addresses a scale factor as ``region_base + in_region_offset`` -+ with ``region_base = page*page_stride + head*head_stride`` evaluated in -+ Int64, so these two scalars are the only geometry that has to travel from -+ the host. ``sf`` is a uint8 view (enforced by the validator), so element -+ strides already are byte strides; the ``element_size()`` factor is kept -+ explicit so the unit is not accidental. -+ -+ For a vLLM paged cache these come straight out of ``nvfp4_split_data_scale`` -+ (``vllm/utils/torch_utils.py:419-467``) as ``(page_bytes, block_size * S)``. -+ The page stride is the FULL page, data bytes included -- -+ ``2*Hkv*block_size*72`` = 73728 B at M3 -- which is why the kernel does the -+ region arithmetic in Int64: a 100 GB cache reaches ~1e11 and overflows Int32 -+ by ~50x. The strides themselves fit in Int32 with room to spare, which is -+ what makes Int32 kernel arguments safe; assert it rather than assume it. -+ """ -+ -+ itemsize = int(sf.element_size()) -+ strides = [] -+ for axis, label in ((0, "page"), (1, "head")): -+ value = int(sf.stride(axis)) * itemsize -+ if value < 0 or value > _INT32_MAX: -+ raise ValueError( -+ f"{name} {label} stride must be a non-negative byte count that " -+ f"fits in int32, got {value}" -+ ) -+ strides.append(value) -+ return strides[0], strides[1] -+ -+ - def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - q, - k, - v, -- k_scale_128x4, -- v_scale_128x4, -+ k_scale, -+ v_scale, - k_global_scale, - v_global_scale, - k2q_row_ptr, -@@ -1859,9 +2100,9 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - qhead_per_kv = head_q // head_kv - fp8_pair_dequant = os.environ.get("MINIMAX_KVFP4_FP8_PAIR_DEQUANT", "1") != "0" - k_global_scale_kernel = k_global_scale -- # V global scale is linear in the final output. Keep K1 on block-scale-only V -- # and apply the tensor scale once in K2 combine. -- v_global_scale_kernel = None -+ # FP8 cannot hold the block-scaled NVFP4 intermediate (up to 6 * 448). -+ # Reconstruct V before the FP8 cast. BF16 keeps its existing deferred scale. -+ v_global_scale_kernel = v_global_scale if q.dtype == torch.float8_e4m3fn else None - has_k_global_scale = k_global_scale_kernel is not None - has_v_global_scale = v_global_scale_kernel is not None - paged_kv = page_table is not None -@@ -1873,6 +2114,18 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - _prepare_paged_kv_for_tma(k, v, n_block_size) - k_kernel = k - v_kernel = v -+ if paged_kv: -+ k_sf_page_stride, k_sf_head_stride = _nvfp4_scale_strides(k_scale, "k_scale") -+ v_sf_page_stride, v_sf_head_stride = _nvfp4_scale_strides(v_scale, "v_scale") -+ else: -+ # Flat varlen: the kernel derives its region geometry in-kernel from -+ # num_heads_kv and S (there is no host-side owner of it, and no -+ # production flat producer), so it IGNORES these four arguments. Pass -+ # 0 rather than the real strides so nothing here reads as meaningful -+ # input; the validator has already pinned the flat container to the -+ # exact contiguous layout the kernel assumes. -+ k_sf_page_stride = k_sf_head_stride = 0 -+ v_sf_page_stride = v_sf_head_stride = 0 - O_partial_flat = O_partial.reshape(-1, head_dim).contiguous() - Q_flat = q.reshape(-1, head_dim).contiguous() - Q_gather4_desc = ( -@@ -1948,8 +2201,8 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - kernel, - to_cute_tensor_kvouter(k_kernel), - to_cute_tensor_kvouter(v_kernel), -- to_cute_tensor_kvouter(k_scale_128x4), -- to_cute_tensor_kvouter(v_scale_128x4), -+ to_cute_tensor_kvouter(k_scale), -+ to_cute_tensor_kvouter(v_scale), - None if k_global_scale_kernel is None else to_cute_tensor_kvouter(k_global_scale_kernel), - None if v_global_scale_kernel is None else to_cute_tensor_kvouter(v_global_scale_kernel), - to_cute_tensor_kvouter(k2q_q_indices), -@@ -1974,6 +2227,13 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - Int32(head_kv), - Int32(max_seqlen_q), - Int32(work_capacity), -+ # Scale-factor page/head strides, in BYTES, after -+ # work_capacity and before the stream. Same order in the -+ # launch below. See _nvfp4_scale_strides. -+ Int32(k_sf_page_stride), -+ Int32(k_sf_head_stride), -+ Int32(v_sf_page_stride), -+ Int32(v_sf_head_stride), - cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), - options="--enable-tvm-ffi", - ) -@@ -1983,8 +2243,8 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - _compile_cache[key]( - k_kernel, - v_kernel, -- k_scale_128x4, -- v_scale_128x4, -+ k_scale, -+ v_scale, - k_global_scale_kernel, - v_global_scale_kernel, - k2q_q_indices, -@@ -2007,5 +2267,11 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( - head_kv, - max_seqlen_q, - work_capacity, -+ # Scale-factor page/head strides, in BYTES. Must match the order -+ # in the cute.compile() call above exactly. -+ k_sf_page_stride, -+ k_sf_head_stride, -+ v_sf_page_stride, -+ v_sf_head_stride, - ) - return schedule -diff --git a/python/fmha_sm100/cute/quantize.py b/python/fmha_sm100/cute/quantize.py -index 4719a48..65e51be 100644 ---- a/python/fmha_sm100/cute/quantize.py -+++ b/python/fmha_sm100/cute/quantize.py -@@ -1,18 +1,68 @@ - # SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax - # SPDX-License-Identifier: MIT + #else // FMHA_GMEM_BOUNDS_CHECK not defined --"""Transformer Engine NVFP4 quantization helper. -+"""NVFP4 quantization helpers for the KVFP4 sparse attention kernel. +@@ -93,5 +96,6 @@ __device__ __forceinline__ bool gmem_range_ok( + #define SEG_LEN_LOAD(vl, idx, sz) (vl).segment_lens[(idx)] + #define KV_INDPTR_LOAD(ptr, idx, sz) __ldg(&(ptr)[(idx)]) + #define KV_INDICES_LOAD(ptr, idx, sz) __ldg(&(ptr)[(idx)]) ++#define KV_BLOCK_INDEX_LOAD(ptr, idx, sz) __ldg(&(ptr)[(idx)]) - This file is intended as a customer-facing example for preparing KV tensors - for the KVFP4 attention kernel: - - BF16/FP16 K/V input -- - packed E2M1 FP4 data from Transformer Engine -- - E4M3 block scales in cuBLAS/cuDNN 128x4 tiled layout -+ - packed E2M1 FP4 data (Transformer Engine, or a dependency-free PyTorch -+ fallback) -+ - E4M3 block scales in **vLLM's** scale-factor byte order - - one FP32 tensor/global scale per tensor -+ -+Scale-factor layouts -+-------------------- -+There is exactly one supported layout *pair*, matching what vLLM's NVFP4 -+KV-cache store kernel writes (``csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu``), -+so MSA reads that cache with no repack pass: -+ -+=============== ========================================= =============== -+layout byte offset inside a scale region used for -+=============== ========================================= =============== -+``"linear"`` ``t*S + s`` K -+``"swizzle4x4"`` ``(t//4)*(4*S) + 4*s + (t%4)`` V -+=============== ========================================= =============== -+ -+``t`` is the token index inside the region, ``s`` the scale column, and -+``S = head_dim // 16`` the number of scale columns. ``S`` must be a multiple -+of 4 and, for ``"swizzle4x4"``, the region must hold a whole number of token -+quads. The cuBLAS/cuDNN **128x4** layout this module used to emit is deleted: -+MSA uses no block-scaled MMA, so it bought nothing, and it did not match vLLM. -+ -+Physical containers -+------------------- -+A *region* is exactly ``region_tokens * S`` bytes -- there is no row or column -+padding. The container returned by :func:`quantize_bf16_to_nvfp4` has the -+input's shape with the last dimension replaced by ``S``: -+ -+* **paged** input ``[num_pages, Hkv, page_size, D]`` -+ -> container ``[num_pages, Hkv, page_size, S]``. -+ One region per ``(page, head)``, ``region_tokens = page_size``. This is -+ byte-for-byte the view ``vllm.utils.torch_utils.nvfp4_split_data_scale`` -+ hands back (modulo its ``float8_e4m3fn`` dtype; see the note in -+ ``interface.py``). -+ -+* **flat varlen** input ``[total_k, Hkv, D]`` (or ``[total_k, D]``, Hkv = 1) -+ -> container ``[total_k, Hkv, S]``. For ``"linear"`` one region per -+ ``(token, head)`` (``region_tokens = 1``, so the container is also -+ *logically* indexed by ``(token, head, s)``). For ``"swizzle4x4"`` one -+ region per ``(token_quad, head)``, ``region_tokens = 4``, regions ordered -+ quad-major then head; the container is then only a **byte container** -- -+ element ``(t, h, s)`` of the tensor is not the scale of token ``t``. -+ Byte address of the scale for ``(t, h, s)``, with -+ ``page_stride = stride(0) = Hkv*S`` and ``head_stride = stride(1) = S``:: -+ -+ linear : t*page_stride + h*head_stride + s -+ swizzle4x4 : (t & ~3)*page_stride + 4*h*head_stride + 4*s + (t & 3) -+ -+ The flat swizzle has no production producer (vLLM is paged only); it exists -+ because flat test inputs are far cheaper to build than paged ones. - """ - - from __future__ import annotations + #endif // FMHA_GMEM_BOUNDS_CHECK +diff --git a/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh b/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh +index b11abe6..96757b6 100644 +--- a/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh ++++ b/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh +@@ -1,3 +1,4 @@ ++// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES + /* + * Copyright (c) 2023 by FlashInfer team. + * +@@ -57,7 +58,8 @@ template ++ cutlass::fmha::collective::SparseAttnMode::Off, ++ bool UnitSelectorColumn = false> + struct FwdRunner { + using Element = DTypeIn; + using ElementAccumulatorQK = float; +@@ -89,7 +91,8 @@ struct FwdRunner { -+import os - from dataclasses import dataclass - from typing import Tuple + using Mainloop = cutlass::fmha::collective::Sm100FmhaFwdMainloopTmaWarpspecialized< + Element, ElementAccumulatorQK, ElementAccumulatorPV, TileShapeQK, TileShapePV, StrideQ, +- StrideK, StrideV, ActiveMask, ThreadShape, IsSplitKV, KVPageSize, kSparseAttnMode>; ++ StrideK, StrideV, ActiveMask, ThreadShape, IsSplitKV, KVPageSize, kSparseAttnMode, ++ UnitSelectorColumn>; + using Epilogue = cutlass::fmha::collective::Sm100FmhaFwdEpilogueTmaWarpspecialized< + ElementOut, ElementAccumulatorPV, typename Mainloop::TileShapePV, NumQStages, IsSplitKV, bNeedOutput, kPackFactor>; + using Operation = +@@ -126,6 +129,9 @@ struct FwdRunner { + int max_k_tiles = 0, + int* kv_block_indexes = nullptr, + int kv_block_num = 0, ++ int64_t kv_block_stride_n = 0, ++ int64_t kv_block_stride_h = 0, ++ int64_t kv_block_stride_b = 1, + int pack_factor = 1, + int q_stride_n_original = 0, + int q_stride_h_original = 0, +@@ -223,11 +229,28 @@ struct FwdRunner { + if constexpr (IsSplitKV) { + arguments = { + {problem_shape, +- {{q, layout_Q, k, layout_K, v, layout_V, kv_indices, kv_page_indptr, kv_block_indexes, kv_block_num, ++ {{.ptr_Q = q, ++ .layout_Q = layout_Q, ++ .ptr_K = k, ++ .layout_K = layout_K, ++ .ptr_V = v, ++ .layout_V = layout_V, ++ .kv_indices = kv_indices, ++ .kv_page_indptr = kv_page_indptr, ++ .kv_block_indexes = kv_block_indexes, ++ .kv_block_num = kv_block_num, ++ .kv_block_stride_n = kv_block_stride_n, ++ .kv_block_stride_h = kv_block_stride_h, ++ .kv_block_stride_b = kv_block_stride_b, + #ifdef FMHA_GMEM_BOUNDS_CHECK +- pack_gqa.gmem_bounds.kv_page_indptr_size, pack_gqa.gmem_bounds.kv_indices_size, pack_gqa.gmem_bounds.kv_block_indexes_numel, ++ .kv_page_indptr_size = pack_gqa.gmem_bounds.kv_page_indptr_size, ++ .kv_indices_size = pack_gqa.gmem_bounds.kv_indices_size, ++ .kv_block_indexes_span = pack_gqa.gmem_bounds.kv_block_indexes_span, + #endif +- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, ++ .pack_factor = pack_factor, ++ .q_stride_n_original = q_stride_n_original, ++ .q_stride_h_original = q_stride_h_original, ++ .h_r_original = h_r_original}, + sm_scale, q_scale, k_scale, v_scale, o_scale}, + epi_args, + sched_args, +@@ -244,11 +267,28 @@ struct FwdRunner { + } else { + arguments = { + problem_shape, +- {{q, layout_Q, k, layout_K, v, layout_V, kv_indices, kv_page_indptr, kv_block_indexes, kv_block_num, ++ {{.ptr_Q = q, ++ .layout_Q = layout_Q, ++ .ptr_K = k, ++ .layout_K = layout_K, ++ .ptr_V = v, ++ .layout_V = layout_V, ++ .kv_indices = kv_indices, ++ .kv_page_indptr = kv_page_indptr, ++ .kv_block_indexes = kv_block_indexes, ++ .kv_block_num = kv_block_num, ++ .kv_block_stride_n = kv_block_stride_n, ++ .kv_block_stride_h = kv_block_stride_h, ++ .kv_block_stride_b = kv_block_stride_b, + #ifdef FMHA_GMEM_BOUNDS_CHECK +- pack_gqa.gmem_bounds.kv_page_indptr_size, pack_gqa.gmem_bounds.kv_indices_size, pack_gqa.gmem_bounds.kv_block_indexes_numel, ++ .kv_page_indptr_size = pack_gqa.gmem_bounds.kv_page_indptr_size, ++ .kv_indices_size = pack_gqa.gmem_bounds.kv_indices_size, ++ .kv_block_indexes_span = pack_gqa.gmem_bounds.kv_block_indexes_span, + #endif +- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, ++ .pack_factor = pack_factor, ++ .q_stride_n_original = q_stride_n_original, ++ .q_stride_h_original = q_stride_h_original, ++ .h_r_original = h_r_original}, + sm_scale, q_scale, k_scale, v_scale, o_scale}, + epi_args, + sched_args, +@@ -343,8 +383,28 @@ struct FwdRunner { + if constexpr (IsSplitKV) { + arguments = { + {problem_shape, +- {{q, layout_Q, k, layout_K, v, layout_V, nullptr, nullptr, nullptr, 0, +- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, ++ {{.ptr_Q = q, ++ .layout_Q = layout_Q, ++ .ptr_K = k, ++ .layout_K = layout_K, ++ .ptr_V = v, ++ .layout_V = layout_V, ++ .kv_indices = nullptr, ++ .kv_page_indptr = nullptr, ++ .kv_block_indexes = nullptr, ++ .kv_block_num = 0, ++ .kv_block_stride_n = 0, ++ .kv_block_stride_h = 0, ++ .kv_block_stride_b = 1, ++#ifdef FMHA_GMEM_BOUNDS_CHECK ++ .kv_page_indptr_size = 0, ++ .kv_indices_size = 0, ++ .kv_block_indexes_span = 0, ++#endif ++ .pack_factor = pack_factor, ++ .q_stride_n_original = q_stride_n_original, ++ .q_stride_h_original = q_stride_h_original, ++ .h_r_original = h_r_original}, + sm_scale, q_scale, k_scale, v_scale, o_scale}, + epi_args, + sched_args, +@@ -361,8 +421,28 @@ struct FwdRunner { + } else { + arguments = { + problem_shape, +- {{q, layout_Q, k, layout_K, v, layout_V, nullptr, nullptr, nullptr, 0, +- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, ++ {{.ptr_Q = q, ++ .layout_Q = layout_Q, ++ .ptr_K = k, ++ .layout_K = layout_K, ++ .ptr_V = v, ++ .layout_V = layout_V, ++ .kv_indices = nullptr, ++ .kv_page_indptr = nullptr, ++ .kv_block_indexes = nullptr, ++ .kv_block_num = 0, ++ .kv_block_stride_n = 0, ++ .kv_block_stride_h = 0, ++ .kv_block_stride_b = 1, ++#ifdef FMHA_GMEM_BOUNDS_CHECK ++ .kv_page_indptr_size = 0, ++ .kv_indices_size = 0, ++ .kv_block_indexes_span = 0, ++#endif ++ .pack_factor = pack_factor, ++ .q_stride_n_original = q_stride_n_original, ++ .q_stride_h_original = q_stride_h_original, ++ .h_r_original = h_r_original}, + sm_scale, q_scale, k_scale, v_scale, o_scale}, + epi_args, + sched_args, +@@ -412,7 +492,8 @@ template ++ cutlass::fmha::collective::SparseAttnMode::Off, ++ bool UnitSelectorColumn = false> + cudaError_t run_fmha_fwd(void* workspace_buffer, DTypeIn* q, DTypeIn* k, DTypeIn* v, + IdType* qo_segment_lens, IdType* kv_segment_lens, + IdType* qo_segment_offsets, IdType* kv_segment_offsets, +@@ -436,6 +517,9 @@ cudaError_t run_fmha_fwd(void* workspace_buffer, DTypeIn* q, DTypeIn* k, DTypeIn + int max_k_tiles = 0, + int* kv_block_indexes = nullptr, + int kv_block_num = 0, ++ int64_t kv_block_stride_n = 0, ++ int64_t kv_block_stride_h = 0, ++ int64_t kv_block_stride_b = 1, + int pack_factor = 1, + int q_stride_n_original = 0, + int q_stride_h_original = 0, +@@ -443,7 +527,8 @@ cudaError_t run_fmha_fwd(void* workspace_buffer, DTypeIn* q, DTypeIn* k, DTypeIn + PackGQAUnpackParams pack_gqa = {}, + int num_ctas = 0) { + return FwdRunner::run( ++ ThreadShape, IsSplitKV, SingleSoftmaxWarpGroup, KVPageSize, kSparseAttnMode, ++ UnitSelectorColumn>::run( + workspace_buffer, q, k, v, qo_segment_lens, kv_segment_lens, + qo_segment_offsets, kv_segment_offsets, packed_work_range, + packed_work_info, o, mask_mode_code, sm_scale, +@@ -455,6 +540,7 @@ cudaError_t run_fmha_fwd(void* workspace_buffer, DTypeIn* q, DTypeIn* k, DTypeIn + kv_indices, kv_page_indptr, total_page_num, + maybe_max_score, max_k_tiles, + kv_block_indexes, kv_block_num, ++ kv_block_stride_n, kv_block_stride_h, kv_block_stride_b, + pack_factor, q_stride_n_original, q_stride_h_original, h_r_original, + pack_gqa, num_ctas); + } +diff --git a/python/fmha_sm100/csrc/include/sm100_fmha_fwd_kernel_tma_warpspecialized.hpp b/python/fmha_sm100/csrc/include/sm100_fmha_fwd_kernel_tma_warpspecialized.hpp +index 0e41ce0..09f3c80 100644 +--- a/python/fmha_sm100/csrc/include/sm100_fmha_fwd_kernel_tma_warpspecialized.hpp ++++ b/python/fmha_sm100/csrc/include/sm100_fmha_fwd_kernel_tma_warpspecialized.hpp +@@ -214,9 +214,9 @@ struct Sm100FmhaFwdKernelTmaWarpspecialized { + } -@@ -23,6 +73,10 @@ NVFP4_BLOCK_SIZE = 16 - NVFP4_FP4_MAX = 6.0 - NVFP4_FP8_E4M3_MAX = 448.0 + CUTLASS_DEVICE void operator()(const Params& params, char* smem) { +-// #if (__CUDACC_VER_MAJOR__ >= 12 && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) +-// asm volatile("griddepcontrol.wait;"); +-// #endif ++#if (__CUDACC_VER_MAJOR__ >= 12 && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) ++ asm volatile("griddepcontrol.wait;" ::: "memory"); // t0fix (Indexer): PDL-launched; wait before any input read ++#endif -+#: The only supported scale-factor layouts. ``"linear"`` for K, -+#: ``"swizzle4x4"`` for V -- see the module docstring. -+NVFP4_SCALE_LAYOUTS: Tuple[str, ...] = ("linear", "swizzle4x4") -+ + GPU_TRACE_INIT; - @dataclass(frozen=True) - class Nvfp4QuantizedTensor: -@@ -31,115 +85,294 @@ class Nvfp4QuantizedTensor: - Attributes - ---------- - data : torch.Tensor -- Packed E2M1 FP4 data from Transformer Engine. The last dimension is -- half of the original logical last dimension because each byte stores -- two FP4 values. -- scale_128x4 : torch.Tensor -- E4M3 block scales in cuBLAS/cuDNN 128x4 tiled rowwise storage. -+ Packed E2M1 FP4 data. The last dimension is half of the original -+ logical last dimension because each byte stores two FP4 values. -+ scale : torch.Tensor -+ E4M3 block scales as uint8, in the physical container described in the -+ module docstring (input shape with the last dim replaced by -+ ``head_dim // 16``). - global_scale : torch.Tensor - FP32 tensor/global dequant scale. - logical_scale_shape : tuple[int, int] -- Logical 2D scale shape ``(rows, cols)`` before 128x4 swizzling. -+ Logical 2D scale shape ``(rows, cols)`` before packing, where ``rows`` -+ is ``prod(original_shape[:-1])``. - original_shape : tuple[int, ...] - Original BF16/FP16 tensor shape before quantization. -+ layout : str -+ Scale-factor layout of ``scale``: ``"linear"`` or ``"swizzle4x4"``. - """ +diff --git a/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp b/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp +index 5a5d0f3..5c923c1 100644 +--- a/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp ++++ b/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp +@@ -1,5 +1,5 @@ + /*************************************************************************************************** +- * Copyright (c) 2024 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. ++ * Copyright (c) 2024 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without +@@ -158,7 +158,8 @@ template , + bool IsSplitKV_ = false, + int KVPageSize_ = -1, +- SparseAttnMode kSparseAttnMode = SparseAttnMode::Off> ++ SparseAttnMode kSparseAttnMode = SparseAttnMode::Off, ++ bool UnitSelectorColumn = false> + struct Sm100FmhaFwdMainloopTmaWarpspecialized { + static constexpr bool IsSplitKV = IsSplitKV_; + static constexpr int KVPageSize = KVPageSize_; +@@ -173,6 +174,16 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + // for safety (no sync elision in v1 — those are TODO for v2). + static constexpr bool kFuseMaxScoreIntoSoftmax = + (kSparseAttnMode == SparseAttnMode::OnlyScore); ++ // OnlyScore K-split: correction has no per-tile work (softmax writes the max scores itself), so the per-tile ++ // softmax -> correction -> MMA handshake (pipeline_c commit/acquire, correction's s0_c/s1_c wait/release and ++ // pipeline_corr arrive/wait) only serializes the two softmax warpgroups. It is skipped; pipeline_s (S0/S1 TMEM ++ // reuse between MMA and softmax) and the final pipeline_c handshake into the split-KV merge/epilogue are kept. ++ // Defining FMHA_ONLYSCORE_PER_TILE_CORRECTION (jit.py: TLLM_FMHA_PROXY_CORRECTION_CHAIN=1) keeps the handshake. ++#ifdef FMHA_ONLYSCORE_PER_TILE_CORRECTION ++ static constexpr bool kSkipPerTileCorrection = false; ++#else ++ static constexpr bool kSkipPerTileCorrection = kFuseMaxScoreIntoSoftmax && (get<1>(ThreadShape{}) > 1); ++#endif - data: torch.Tensor -- scale_128x4: torch.Tensor -+ scale: torch.Tensor - global_scale: torch.Tensor - logical_scale_shape: Tuple[int, int] - original_shape: Tuple[int, ...] -+ layout: str -+ -+ -+def nvfp4_scale_linear_offset(t, s, S): -+ """Byte offset of scale column ``s`` of token ``t`` in a linear region. -+ -+ ``off = t*S + s``. Matches vLLM's K scale store -+ (``nvfp4_kv_cache_kernels.cu:162``). -+ -+ ``t`` and ``s`` may be Python ints or integer tensors (broadcasting). -+ """ -+ -+ return t * S + s + struct SplitKVParams { + float scale_output_splitkv = 1.0f; +@@ -345,7 +356,18 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + // from mma to softmax0/1 warp, protects S in tmem + // (not sure yet about the reverse direction) + // there is one pipe per softmax warp, and the mma warp alternates between them +- using PipelineS = cutlass::PipelineUmmaAsync<1>; ++ // OnlyScore K-split keeps no O accumulator in TMEM, so each Q stage double-buffers S: buffer 1 of S0 / S1 sits in ++ // the O0 / O1 columns (+256), and the MMA fills tile i+1 while the softmax warps still read tile i. Nothing in ++ // OnlyScore reads or writes O (the O-touching correction paths static_assert kNeedOutput). ++ // Defining FMHA_ONLYSCORE_SINGLE_S (jit.py: TLLM_FMHA_PROXY_S_DOUBLE_BUFFER=0) keeps one S buffer per Q stage. ++#ifdef FMHA_ONLYSCORE_SINGLE_S ++ static constexpr bool kSDoubleBuf = false; ++#else ++ static constexpr bool kSDoubleBuf = kSkipPerTileCorrection; ++#endif ++ static_assert(!kSDoubleBuf || !kNeedOutput, "S double-buffering reuses the O TMEM columns"); ++ static constexpr uint32_t kSBuf1Offset = uint32_t(TmemAllocation::O0) - uint32_t(TmemAllocation::S0); ++ using PipelineS = cutlass::PipelineUmmaAsync; + // from softmax0/1/ to correction wg + using PipelineC = cutlass::PipelineAsync<1>; +@@ -376,7 +398,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + using Load = Sm100FmhaLoadTmaWarpspecialized; ++ kSparseAttnMode, UnitSelectorColumn>; + using LayoutQ = typename Load::LayoutQ; + using LayoutK = typename Load::LayoutK; + using LayoutV = typename Load::LayoutV; +@@ -494,6 +516,12 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + tStS0.data() = tStS.data().get() + uint32_t(TmemAllocation::S0); + Tensor tStS1 = tStS; + tStS1.data() = tStS.data().get() + uint32_t(TmemAllocation::S1); ++ Tensor tStS0b = tStS0; ++ tStS0b.data() = tStS0.data().get() + kSBuf1Offset; ++ Tensor tStS1b = tStS1; ++ tStS1b.data() = tStS1.data().get() + kSBuf1Offset; ++ auto s0_buf = [&](auto const& state) { return (kSDoubleBuf && state.index() == 1) ? tStS0b : tStS0; }; ++ auto s1_buf = [&](auto const& state) { return (kSDoubleBuf && state.index() == 1) ? tStS1b : tStS1; }; + + Tensor tOtO0 = tOtO; + tOtO0.data() = tOtO.data().get() + uint32_t(TmemAllocation::O0); +@@ -571,7 +599,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + pipeline_s0.producer_acquire(pipeline_s0_producer_state); + { + // GPU_TRACE_SCOPE(GEMM_QK0); +- gemm_zero_acc(mma_qk, tSrQ0, tSrK(_, _, _, k_index), tStS0); ++ { auto tS_cur = s0_buf(pipeline_s0_producer_state); gemm_zero_acc(mma_qk, tSrQ0, tSrK(_, _, _, k_index), tS_cur); } + } + pipeline_s0.producer_commit(pipeline_s0_producer_state); + ++pipeline_s0_producer_state; +@@ -596,7 +624,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + // QK_s1: Q-split: Q1 * K0 -> S1; K-split: Q0 * K1 -> S1 + pipeline_s1.producer_acquire(pipeline_s1_producer_state); + {//GPU_TRACE_SCOPE(GEMM_QK1); +- gemm_zero_acc(mma_qk, tSrQ1, tSrK(_, _, _, k_index), tStS1); ++ { auto tS_cur = s1_buf(pipeline_s1_producer_state); gemm_zero_acc(mma_qk, tSrQ1, tSrK(_, _, _, k_index), tS_cur); } + } + pipeline_s1.producer_commit(pipeline_s1_producer_state); + ++pipeline_s1_producer_state; +@@ -623,7 +651,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + } --def _round_up(x: int, multiple: int) -> int: -- return ((int(x) + multiple - 1) // multiple) * multiple -+def nvfp4_scale_swizzle4x4_offset(t, s, S): -+ """Byte offset of scale column ``s`` of token ``t`` in a 4x4-swizzled region. + // PV0: P0 * V_even -> O0 +- pipeline_corr.wait(); ++ if constexpr (!kSkipPerTileCorrection) { pipeline_corr.wait(); } + pipeline_s0.producer_acquire(pipeline_s0_producer_state); + if constexpr(kNeedOutput) { + // GPU_TRACE_SCOPE(GEMM_PV0); +@@ -648,7 +676,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + // QK_s0: Q0 * K_even -> S0 + { + // GPU_TRACE_SCOPE(GEMM_QK0); +- gemm_zero_acc(mma_qk, tSrQ0, tSrK(_, _, _, k_index), tStS0); ++ { auto tS_cur = s0_buf(pipeline_s0_producer_state); gemm_zero_acc(mma_qk, tSrQ0, tSrK(_, _, _, k_index), tS_cur); } + pipeline_s0.producer_commit(pipeline_s0_producer_state); + ++pipeline_s0_producer_state; + } +@@ -666,7 +694,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + } + } -+ ``off = (t//4)*(4*S) + 4*s + (t%4)`` -- i.e. a plain row-major -+ ``[T/4][S][4]`` array indexed by ``(t//4, s, t%4)``. Matches vLLM's V -+ scale store (``nvfp4_kv_cache_kernels.cu:25-39``, ``:164-171``); the two -+ forms are algebraically identical for every ``S`` divisible by 4. +- pipeline_corr.wait(); ++ if constexpr (!kSkipPerTileCorrection) { pipeline_corr.wait(); } + pipeline_s1.producer_acquire(pipeline_s1_producer_state); + if constexpr(kNeedOutput) { + // GPU_TRACE_SCOPE(GEMM_PV1); +@@ -693,7 +721,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + // Must happen BEFORE releasing K! + { + // GPU_TRACE_SCOPE(GEMM_QK1); +- gemm_zero_acc(mma_qk, tSrQ1, tSrK(_, _, _, k_index), tStS1); ++ { auto tS_cur = s1_buf(pipeline_s1_producer_state); gemm_zero_acc(mma_qk, tSrQ1, tSrK(_, _, _, k_index), tS_cur); } + pipeline_s1.producer_commit(pipeline_s1_producer_state); + ++pipeline_s1_producer_state; + } +@@ -725,7 +753,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + } --def nvfp4_scale_128x4_offset( -- row: torch.Tensor, -- col: torch.Tensor, -+ ``t`` and ``s`` may be Python ints or integer tensors (broadcasting). -+ """ -+ -+ return (t // 4) * (4 * S) + 4 * s + (t % 4) -+ -+ -+_SCALE_OFFSET_FNS = { -+ "linear": nvfp4_scale_linear_offset, -+ "swizzle4x4": nvfp4_scale_swizzle4x4_offset, -+} -+ -+ -+def _check_layout(layout: str) -> str: -+ layout = str(layout) -+ if layout not in NVFP4_SCALE_LAYOUTS: -+ raise ValueError( -+ f"layout must be one of {list(NVFP4_SCALE_LAYOUTS)}, got {layout!r}" -+ ) -+ return layout -+ -+ -+def _region_offsets(page_size: int, scale_cols: int, layout: str, device) -> torch.Tensor: -+ """Flat physical offsets for one region, in logical ``(t, s)`` row-major order.""" -+ -+ t = torch.arange(page_size, device=device, dtype=torch.int64)[:, None] -+ s = torch.arange(scale_cols, device=device, dtype=torch.int64)[None, :] -+ return _SCALE_OFFSET_FNS[layout](t, s, scale_cols).reshape(-1) -+ -+ -+def _validate_region(page_size: int, scale_cols: int, layout: str) -> None: -+ if page_size <= 0: -+ raise ValueError(f"page_size must be positive, got {page_size}") -+ if scale_cols <= 0 or scale_cols % 4 != 0: -+ raise ValueError( -+ "scale_cols must be a positive multiple of 4 (the 4x4 swizzle " -+ f"derivation assumes S % 4 == 0), got {scale_cols}" -+ ) -+ if layout == "swizzle4x4" and page_size % 4 != 0: -+ raise ValueError( -+ "layout='swizzle4x4' tiles tokens in quads, so the region must hold " -+ f"a whole number of quads; got page_size={page_size}" -+ ) -+ -+ -+def pack_nvfp4_scale( -+ scale: torch.Tensor, -+ *, -+ page_size: int, - scale_cols: int, -+ layout: str, - ) -> torch.Tensor: -- """Return flat offsets for cuBLAS/cuDNN 128x4 rowwise scale storage. -+ """Pack logical per-region block scales into physical scale-factor order. + // final PV0: P0 * V_last_even -> O0 +- pipeline_corr.wait(); ++ if constexpr (!kSkipPerTileCorrection) { pipeline_corr.wait(); } + pipeline_s0.producer_acquire(pipeline_s0_producer_state); + if constexpr(kNeedOutput) { + GPU_TRACE_SCOPE(GEMM_PV0); +@@ -746,7 +774,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + } - Parameters - ---------- -- row : torch.Tensor -- Logical row indices. -- col : torch.Tensor -- Logical scale-column indices. -+ scale : torch.Tensor -+ Logical scales with shape ``[n_regions, page_size, scale_cols]``. -+ Reinterpreted as uint8 if it is not already uint8. -+ page_size : int -+ Tokens per region. Must be a multiple of 4 for ``"swizzle4x4"``. - scale_cols : int -- Logical number of scale columns before padding to a multiple of 4. -+ Scale columns per token, ``S = head_dim // 16``. Must be a multiple -+ of 4. -+ layout : str -+ ``"linear"`` or ``"swizzle4x4"``. + // final PV1: P1 * V_last -> O1 +- pipeline_corr.wait(); ++ if constexpr (!kSkipPerTileCorrection) { pipeline_corr.wait(); } + pipeline_s1.producer_acquire(pipeline_s1_producer_state); + if constexpr(kNeedOutput) { + GPU_TRACE_SCOPE(GEMM_PV1); +@@ -899,7 +927,13 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + + {GPU_TRACE_SCOPE(SOFTMAX_Mask); + if constexpr (!skip_computation) { +- copy(tiled_tmem_load, l_tTMEM_LOADtS, tTMEM_LOADrS); ++ auto l_ld = l_tTMEM_LOADtS; ++ if constexpr (kSDoubleBuf) { ++ if (pipeline_s_consumer_state.index() == 1) { ++ l_ld.data() = l_ld.data().get() + kSBuf1Offset; ++ } ++ } ++ copy(tiled_tmem_load, l_ld, tTMEM_LOADrS); + if constexpr (need_apply_mask) { + Mask{}.apply_mask(tTMEM_LOADrS, tTMEM_LOADcS, problem_shape); + } +@@ -977,8 +1011,10 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + copy(tiled_tmem_storev, tTMEM_STOREVrS, l_tTMEM_STOREVtS); + } - Returns - ------- - torch.Tensor -- Flat offsets into the padded 128x4 tiled storage. -+ Contiguous uint8 tensor with the same shape, whose *bytes* are the -+ packed region layout: region ``r`` occupies exactly -+ ``page_size * scale_cols`` contiguous bytes (**no padding** -- unlike -+ the deleted 128x4 layout, which padded to -+ ``round_up(rows,128) x round_up(cols,4)``), and the scale of token -+ ``t``, column ``s`` sits at byte ``offset_(t, s, scale_cols)`` -+ inside it. -+ -+ ``"linear"`` is the identity: a row-major ``[n_regions, page_size, -+ scale_cols]`` array already *is* the linear layout. - """ +- pipeline_c.producer_commit(pipeline_c_producer_state); +- ++pipeline_c_producer_state; ++ if constexpr (!kSkipPerTileCorrection) { ++ pipeline_c.producer_commit(pipeline_c_producer_state); ++ ++pipeline_c_producer_state; ++ } + + Tensor tTMEM_STORErS_x4 = make_tensor(shape(tTMEM_STOREcS)); + +@@ -1043,7 +1079,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + + CUTE_STATIC_ASSERT_V(size<2>(tTMEM_STORErS_x4) <= _2{}); + CUTE_STATIC_ASSERT_V(size<1>(tTMEM_STORErS_x4) == _1{}); +- if constexpr (skip_computation) { ++ if constexpr (skip_computation && !kSDoubleBuf) { + CUTLASS_PRAGMA_UNROLL + for (int k = 0; k < size<2>(tTMEM_STORErS_x4); ++k) { + copy(tiled_tmem_store, tTMEM_STORErS_x4(_, _, k), l_tTMEM_STOREtS_x4(_, _, k)); +@@ -1058,7 +1094,9 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + pipeline_s.consumer_release(pipeline_s_consumer_state); + ++pipeline_s_consumer_state; + +- pipeline_c.producer_acquire(pipeline_c_producer_state); ++ if constexpr (!kSkipPerTileCorrection) { ++ pipeline_c.producer_acquire(pipeline_c_producer_state); ++ } + + {GPU_TRACE_SCOPE(SOFTMAX_Sum); + if constexpr (!skip_computation && kNeedOutput) { +@@ -1104,7 +1142,9 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + tTMEM_STOREVrS(kIdxFinalRowMax) = 0; + tTMEM_STOREVrS(kIdxFinalRowSum) = 0; + } +- copy(tiled_tmem_storev, tTMEM_STOREVrS, l_tTMEM_STOREVtS); ++ if constexpr (!kSDoubleBuf) { ++ copy(tiled_tmem_storev, tTMEM_STOREVrS, l_tTMEM_STOREVtS); ++ } + }} + } // end step() + }; +@@ -1131,14 +1171,13 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + int skip_count, real_masked_count, unmasked_count; + int effective_end; -- tiles_n = _round_up(scale_cols, 4) // 4 -- tile_m = row // 128 -- tile_n = col // 4 -- outer = row % 128 -- inner = col % 4 -- return ( -- (tile_m * tiles_n + tile_n) * 512 -- + (outer % 32) * 16 -- + (outer // 32) * 4 -- + inner -- ) -+ layout = _check_layout(layout) -+ page_size = int(page_size) -+ scale_cols = int(scale_cols) -+ _validate_region(page_size, scale_cols, layout) +- int kbi_off_s = 0; ++ int64_t kbi_off_s = 0; + if constexpr (kNeedSparse) { + int h_r_s = get<3, 0, 0>(problem_shape); +- int num_kv_heads_s = get<3, 0, 1>(problem_shape); + int kv_head_idx_s = get<2, 0>(blk_coord) / h_r_s; + int batch_idx_s = get<2, 1>(blk_coord); +- kbi_off_s = batch_idx_s * num_kv_heads_s * params.load.kv_block_num +- + kv_head_idx_s * params.load.kv_block_num; ++ kbi_off_s = batch_idx_s * params.load.kv_block_stride_n ++ + kv_head_idx_s * params.load.kv_block_stride_h; + } -+ if scale.ndim != 3: -+ raise ValueError( -+ "scale must be rank-3 [n_regions, page_size, scale_cols], got shape " -+ f"{tuple(scale.shape)}" -+ ) -+ if int(scale.shape[1]) != page_size or int(scale.shape[2]) != scale_cols: -+ raise ValueError( -+ f"scale shape {tuple(scale.shape)} does not match " -+ f"page_size={page_size}, scale_cols={scale_cols}" -+ ) -+ if scale.dtype is not torch.uint8: -+ scale = scale.view(torch.uint8) -+ -+ n_regions = int(scale.shape[0]) -+ src = scale.reshape(n_regions, page_size * scale_cols).contiguous() -+ if layout == "linear": -+ return src.reshape(n_regions, page_size, scale_cols) -+ -+ offsets = _region_offsets(page_size, scale_cols, layout, src.device) -+ out = torch.empty_like(src) -+ out[:, offsets] = src -+ return out.reshape(n_regions, page_size, scale_cols) -+ + if constexpr (kNeedSparse) { +@@ -1154,7 +1193,12 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + + // Count padding blocks (backward scan for -1) + int valid_blks = params.load.kv_block_num; +- while (valid_blks > 0 && __ldg(¶ms.load.kv_block_indexes[kbi_off_s + valid_blks - 1]) < 0) ++ while (valid_blks > 0 && (UnitSelectorColumn ++ ? KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, ++ kbi_off_s + valid_blks - 1, params.load.kv_block_indexes_span) ++ : KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, ++ kbi_off_s + (valid_blks - 1) * params.load.kv_block_stride_b, ++ params.load.kv_block_indexes_span)) < 0) + valid_blks--; + + int valid_tiles = (valid_blks * KVPageSize + full_tile_kv - 1) / full_tile_kv; +@@ -1223,7 +1267,12 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + cS = domain_offset(make_coord(q_s, INT_MAX / 2), cS_base); + return false; + } +- int pos = __ldg(¶ms.load.kv_block_indexes[kbi_off_s + page_idx]); ++ int pos = UnitSelectorColumn ++ ? KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, ++ kbi_off_s + page_idx, params.load.kv_block_indexes_span) ++ : KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, ++ kbi_off_s + page_idx * params.load.kv_block_stride_b, ++ params.load.kv_block_indexes_span); + if (pos < 0) { + cS = domain_offset(make_coord(q_s, INT_MAX / 2), cS_base); + return false; +@@ -1441,6 +1490,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + + template + CUTLASS_DEVICE auto correction_epilogue(float scale, Stage stage, TensorO const& sO_01) { ++ static_assert(kNeedOutput, "O TMEM columns are S buffer 1 in OnlyScore"); + using ElementOut = typename TensorO::value_type; + + int thread_idx = threadIdx.x % (4 * cutlass::NumThreadsPerWarp); +@@ -1530,6 +1580,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + } + + CUTLASS_DEVICE auto correction_rescale(float scale, uint32_t tmem_O) { ++ static_assert(kNeedOutput, "O TMEM columns are S buffer 1 in OnlyScore"); + int thread_idx = threadIdx.x % (4 * cutlass::NumThreadsPerWarp); + + // As opposed to the softmax, we do not have enough registers here +@@ -1615,6 +1666,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + CUTLASS_DEVICE auto correction_merge_ksplit( + Params const& params, TensorV const& tTMEM_LOADVrS0, TensorV const& tTMEM_LOADVrS1, + float* smem_scratch = nullptr) { ++ static_assert(kNeedOutput, "O TMEM columns are S buffer 1 in OnlyScore"); + ElementPV row_max_0 = tTMEM_LOADVrS0(kIdxFinalRowMax); + ElementPV row_sum_0 = tTMEM_LOADVrS0(kIdxFinalRowSum); + ElementPV row_max_1 = tTMEM_LOADVrS1(kIdxFinalRowMax); +@@ -1887,6 +1939,7 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + max_score(kIdxNewRowMax) = max_score(kIdxNewRowMax) == -INFINITY ? 0 : max_score(kIdxNewRowMax); + }; + ++ if constexpr (!kSkipPerTileCorrection) { + pipeline_s0_c.consumer_wait(pipeline_s0_c_consumer_state); + if constexpr (kNeedMaxScore) { + // P2 (v3): in OnlyScore fuse mode, the V-channel STOREV on the softmax +@@ -1992,6 +2045,8 @@ struct Sm100FmhaFwdMainloopTmaWarpspecialized { + pipeline_s1_c.consumer_release(pipeline_s1_c_consumer_state); + ++pipeline_s1_c_consumer_state; + ++ } + -+def _unpack_nvfp4_scale( -+ packed: torch.Tensor, -+ *, -+ page_size: int, -+ scale_cols: int, -+ layout: str, -+) -> torch.Tensor: -+ """Inverse of :func:`pack_nvfp4_scale`; returns logical ``(t, s)`` order.""" -+ -+ layout = _check_layout(layout) -+ page_size = int(page_size) -+ scale_cols = int(scale_cols) -+ _validate_region(page_size, scale_cols, layout) -+ -+ n_regions = int(packed.shape[0]) -+ src = packed.reshape(n_regions, page_size * scale_cols) -+ if layout == "linear": -+ return src.reshape(n_regions, page_size, scale_cols) -+ offsets = _region_offsets(page_size, scale_cols, layout, src.device) -+ return src[:, offsets].reshape(n_regions, page_size, scale_cols) -+ -+ -+def _scale_region_grid(original_shape, layout: str) -> Tuple[int, int, bool]: -+ """Region decomposition of a K/V tensor of shape ``original_shape``. -+ -+ Returns ``(n_regions, region_tokens, quad_regroup)``. ``quad_regroup`` -+ marks the flat-varlen swizzle case, whose logical rows (token-major, then -+ head) have to be regrouped into ``(token_quad, head)`` regions. -+ """ -+ -+ shape = tuple(int(v) for v in original_shape) -+ if len(shape) == 4: -+ # Paged: [num_pages, Hkv, page_size, D] -> one region per (page, head). -+ return shape[0] * shape[1], shape[2], False -+ if len(shape) not in (2, 3): -+ raise ValueError( -+ "NVFP4 K/V must be rank-4 [num_pages, Hkv, page_size, D], rank-3 " -+ f"[total_k, Hkv, D] or rank-2 [total_k, D]; got rank {len(shape)}" -+ ) -+ total_k = shape[0] -+ heads = shape[1] if len(shape) == 3 else 1 -+ if layout == "linear": -+ # One region per (token, head): a single token row of S bytes. -+ return total_k * heads, 1, False -+ if total_k % 4 != 0: -+ raise ValueError( -+ "flat-varlen layout='swizzle4x4' tiles the global token axis in " -+ f"quads, so total_k must be a multiple of 4; got {total_k}" -+ ) -+ return (total_k // 4) * heads, 4, True + // do the final correction to O1 + // better to somehow special-case it in the loop above + // doesn't matter for non-persistent code, but if it were +diff --git a/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp b/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp +index 0fdcbfa..d3d7c11 100644 +--- a/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp ++++ b/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp +@@ -1,5 +1,5 @@ + /*************************************************************************************************** +- * Copyright (c) 2024 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. ++ * Copyright (c) 2024 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without +@@ -64,7 +64,8 @@ struct MaskPackFactor> { static constexpr int value = P; }; + template ++ SparseAttnMode kSparseAttnMode = SparseAttnMode::Off, ++ bool UnitSelectorColumn = false> + struct Sm100FmhaLoadTmaWarpspecialized { + // P0: OnlyScore mode never reads V — skip every V slot in the KV pipeline. + // mma() gates the matching wait_V/release_V under `kNeedOutput` so producer +@@ -112,10 +113,13 @@ struct Sm100FmhaLoadTmaWarpspecialized { + int* kv_page_indptr = nullptr; + int* kv_block_indexes = nullptr; + int kv_block_num = 0; ++ int64_t kv_block_stride_n = 0; ++ int64_t kv_block_stride_h = 0; ++ int64_t kv_block_stride_b = 1; + #ifdef FMHA_GMEM_BOUNDS_CHECK + int kv_page_indptr_size = 0; + int kv_indices_size = 0; +- int kv_block_indexes_numel = 0; ++ int64_t kv_block_indexes_span = 0; + #endif + int pack_factor = 1; + int q_stride_n_original = 0; +@@ -148,10 +152,13 @@ struct Sm100FmhaLoadTmaWarpspecialized { + int* kv_page_indptr = nullptr; + int* kv_block_indexes = nullptr; + int kv_block_num = 0; ++ int64_t kv_block_stride_n = 0; ++ int64_t kv_block_stride_h = 0; ++ int64_t kv_block_stride_b = 1; + #ifdef FMHA_GMEM_BOUNDS_CHECK + int kv_page_indptr_size = 0; + int kv_indices_size = 0; +- int kv_block_indexes_numel = 0; ++ int64_t kv_block_indexes_span = 0; + #endif + const Element* ptr_Q_orig = nullptr; + int q_stride_n_orig = 0; +@@ -218,8 +225,9 @@ struct Sm100FmhaLoadTmaWarpspecialized { --def swizzle_nvfp4_scale_to_128x4( -+ -+def _pack_block_scale( - scale: torch.Tensor, - *, - rows: int, -- cols: int, -+ scale_cols: int, -+ original_shape, -+ layout: str, - ) -> torch.Tensor: -- """Convert TE logical rowwise scales to cuBLAS/cuDNN 128x4 tiled layout. -+ """Pack logical ``[rows, scale_cols]`` block scales into the kernel container. + Params p{tma_load_Q, layout_Q, tma_load_K, layout_K, tma_load_V, layout_V, + args.kv_indices, args.kv_page_indptr, args.kv_block_indexes, args.kv_block_num, ++ args.kv_block_stride_n, args.kv_block_stride_h, args.kv_block_stride_b, + #ifdef FMHA_GMEM_BOUNDS_CHECK +- args.kv_page_indptr_size, args.kv_indices_size, args.kv_block_indexes_numel, ++ args.kv_page_indptr_size, args.kv_indices_size, args.kv_block_indexes_span, + #endif + args.ptr_Q, args.q_stride_n_original, args.q_stride_h_original, args.h_r_original, + tma_desc_q_pack}; +@@ -525,11 +533,10 @@ struct Sm100FmhaLoadTmaWarpspecialized { + constexpr int effective_tile_kv = get<1>(TileShapeQK{}); + constexpr int tiles_per_page = KVPageSize / effective_tile_kv; -- Parameters -- ---------- -- scale : torch.Tensor -- Logical rowwise scale tensor with at least shape ``[rows, cols]``. -- rows : int -- Number of logical rows to convert. -- cols : int -- Number of logical scale columns to convert. -- -- Returns -- ------- -- torch.Tensor -- Scale tensor padded to ``round_up(rows, 128)`` by ``round_up(cols, 4)`` -- and swizzled into 128x4 tiled storage. -+ ``scale`` may be larger than ``[rows, scale_cols]`` (Transformer Engine -+ returns padded rowwise scales); the excess is dropped. - """ +- int kv_block_offset = 0; ++ int64_t kv_block_offset = 0; + if constexpr (kSparseAttnMode == SparseAttnMode::Sparse) { +- int num_kv_heads_val = get<3, 0, 1>(params_problem_shape); +- kv_block_offset = batch_idx * num_kv_heads_val * params.kv_block_num +- + kv_head_idx * params.kv_block_num; ++ kv_block_offset = batch_idx * params.kv_block_stride_n ++ + kv_head_idx * params.kv_block_stride_h; + } -+ layout = _check_layout(layout) -+ shape = tuple(int(v) for v in original_shape) -+ rows = int(rows) -+ scale_cols = int(scale_cols) -+ if scale.dtype is not torch.uint8: -+ scale = scale.view(torch.uint8) - if scale.ndim != 2: -- raise ValueError(f"scale must be 2D, got shape {tuple(scale.shape)}") -+ raise ValueError(f"block scale must be 2D, got shape {tuple(scale.shape)}") -+ if int(scale.shape[0]) < rows or int(scale.shape[1]) < scale_cols: -+ raise ValueError( -+ "block scale is smaller than the logical shape: got " -+ f"{tuple(scale.shape)}, need at least {(rows, scale_cols)}" -+ ) -+ logical = scale[:rows, :scale_cols].contiguous() + // Keep full 4D tensor (page_size, D, H_kv, P) — select head at copy time +@@ -549,7 +556,12 @@ struct Sm100FmhaLoadTmaWarpspecialized { + int page_for_lookup; + if constexpr (kSparseAttnMode == SparseAttnMode::Sparse) { + int sparse_idx = (logical_page < params.kv_block_num) +- ? __ldg(¶ms.kv_block_indexes[kv_block_offset + logical_page]) ++ ? (UnitSelectorColumn ++ ? KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, ++ kv_block_offset + logical_page, params.kv_block_indexes_span) ++ : KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, ++ kv_block_offset + logical_page * params.kv_block_stride_b, ++ params.kv_block_indexes_span)) + : -1; + page_for_lookup = (sparse_idx >= 0) ? sparse_idx : 0; + } else { +@@ -573,7 +585,12 @@ struct Sm100FmhaLoadTmaWarpspecialized { + int page_for_lookup; + if constexpr (kSparseAttnMode == SparseAttnMode::Sparse) { + int sparse_idx = (logical_page < params.kv_block_num) +- ? __ldg(¶ms.kv_block_indexes[kv_block_offset + logical_page]) ++ ? (UnitSelectorColumn ++ ? KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, ++ kv_block_offset + logical_page, params.kv_block_indexes_span) ++ : KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, ++ kv_block_offset + logical_page * params.kv_block_stride_b, ++ params.kv_block_indexes_span)) + : -1; + page_for_lookup = (sparse_idx >= 0) ? sparse_idx : 0; + } else { +diff --git a/python/fmha_sm100/cute/interface.py b/python/fmha_sm100/cute/interface.py +index d72b17a..55be196 100644 +--- a/python/fmha_sm100/cute/interface.py ++++ b/python/fmha_sm100/cute/interface.py +@@ -136,6 +136,35 @@ def _prepare_paged_kv_for_tma(k, v, blk_kv: int): + return k, v + + ++def _prepare_paged_hnd_input(tensor: torch.Tensor, blk_kv: int) -> torch.Tensor: ++ """Keep TMA-compatible paged HND views strided across physical pages. + -+ n_regions, region_tokens, quad_regroup = _scale_region_grid(shape, layout) -+ if quad_regroup: -+ heads = shape[1] if len(shape) == 3 else 1 -+ regions = ( -+ logical.reshape(shape[0] // 4, 4, heads, scale_cols) -+ .permute(0, 2, 1, 3) -+ .reshape(n_regions, region_tokens, scale_cols) -+ ) -+ else: -+ regions = logical.reshape(n_regions, region_tokens, scale_cols) ++ The sparse prefill kernel imports the runtime tensor strides through ++ DLPack. It requires each ``[page_size, head_dim]`` head plane to be packed, ++ but the outer physical-page stride may include other coalesced cache roles. ++ Materialize every other layout to preserve the public API's old contract. ++ """ ++ if tensor.ndim != 4: ++ return tensor.contiguous() ++ if int(tensor.shape[2]) != int(blk_kv): ++ return tensor + -+ packed = pack_nvfp4_scale( -+ regions, page_size=region_tokens, scale_cols=scale_cols, layout=layout ++ head_dim = int(tensor.shape[3]) ++ page_size = int(tensor.shape[2]) ++ packed_within_page = ( ++ tensor.stride(3) == 1 ++ and tensor.stride(2) == head_dim ++ and tensor.stride(1) == page_size * head_dim + ) -+ return packed.reshape(shape[:-1] + (scale_cols,)).contiguous() - ++ alignment_bytes = 16 ++ aligned_for_tma = ( ++ tensor.data_ptr() % alignment_bytes == 0 ++ and tensor.stride(0) >= 0 ++ and tensor.stride(0) * tensor.element_size() % alignment_bytes == 0 ++ ) ++ return tensor if packed_within_page and aligned_for_tma else tensor.contiguous() + -+def _unpack_block_scale( -+ packed: torch.Tensor, -+ *, -+ rows: int, -+ scale_cols: int, -+ original_shape, -+ layout: str, -+) -> torch.Tensor: -+ """Inverse of :func:`_pack_block_scale`; returns ``[rows, scale_cols]`` uint8.""" + -+ layout = _check_layout(layout) -+ shape = tuple(int(v) for v in original_shape) - rows = int(rows) -- cols = int(cols) -- padded_rows = _round_up(rows, 128) -- padded_cols = _round_up(cols, 4) -- if scale.shape[0] < rows or scale.shape[1] < cols: -+ scale_cols = int(scale_cols) -+ if packed.dtype is not torch.uint8: -+ packed = packed.view(torch.uint8) -+ if packed.numel() < rows * scale_cols: - raise ValueError( -- "scale is smaller than the requested logical shape: " -- f"got {tuple(scale.shape)}, need at least {(rows, cols)}" -+ f"packed scale holds {packed.numel()} bytes, need " -+ f"{rows * scale_cols} for shape {shape}" - ) + def _validate_cu_seqlens( + cu_seqlens: torch.Tensor, + *, +@@ -303,8 +332,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, +- k_scale_128x4: torch.Tensor, +- v_scale_128x4: torch.Tensor, ++ k_scale: torch.Tensor, ++ v_scale: torch.Tensor, + k_global_scale: Optional[torch.Tensor], + v_global_scale: Optional[torch.Tensor], + k2q_row_ptr: torch.Tensor, +@@ -326,10 +355,14 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + ) + if k.dtype != torch.uint8 or v.dtype != torch.uint8: + raise TypeError(f"KVFP4 k/v must be torch.uint8, got {k.dtype} and {v.dtype}") +- if k_scale_128x4.dtype != torch.uint8 or v_scale_128x4.dtype != torch.uint8: ++ if k_scale.dtype != torch.uint8 or v_scale.dtype != torch.uint8: ++ # NOTE: vllm.utils.torch_utils.nvfp4_split_data_scale (:466) hands back ++ # the scale view as float8_e4m3fn, not uint8. The caller must pass ++ # ``sf.view(torch.uint8)`` -- zero-copy, same bytes -- or this raises. + raise TypeError( + "KVFP4 block scales must be torch.uint8 E4M3 tensors, got " +- f"{k_scale_128x4.dtype} and {v_scale_128x4.dtype}" ++ f"{k_scale.dtype} and {v_scale.dtype}; a vLLM scale view from " ++ "nvfp4_split_data_scale is float8_e4m3fn and needs .view(torch.uint8)" + ) + if k_global_scale is not None and k_global_scale.dtype != torch.float32: + raise TypeError("KVFP4 K global scale must be a torch.float32 tensor or None") +@@ -338,8 +371,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + tensors = ( + k, + v, +- k_scale_128x4, +- v_scale_128x4, ++ k_scale, ++ v_scale, + k2q_row_ptr, + k2q_q_indices, + cu_seqlens_q, +@@ -352,12 +385,15 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + raise ValueError(f"KVFP4 k and v must have the same shape, got {k.shape} and {v.shape}") + packed_dim = q.shape[-1] // 2 + scale_cols = q.shape[-1] // 16 +- if k_scale_128x4.ndim != 2 or v_scale_128x4.ndim != 2: +- raise ValueError("KVFP4 block scales must be rank-2 128x4 tiled tensors") +- if k_scale_128x4.shape[1] < scale_cols or v_scale_128x4.shape[1] < scale_cols: +- raise ValueError( +- "KVFP4 block scales must have at least D/16 columns; " +- f"need {scale_cols}, got {k_scale_128x4.shape[1]} and {v_scale_128x4.shape[1]}" ++ # head_size % 64 == 0 <=> scale_cols % 4 == 0. The V token-quad swizzle ++ # (t//4)*(4*S) + 4*s + (t%4) is a bijection over a region for ANY S, so a ++ # bijectivity check cannot catch a ragged S; only 4 | S makes it agree with ++ # vLLM's writer, whose swizzle group size is scale_dim/4 ++ # (nvfp4_kv_cache_kernels.cu:25-39, checked at :208-215). ++ if scale_cols % 4 != 0: ++ raise NotImplementedError( ++ "KVFP4 scale factors require head_size % 64 == 0 so that D/16 is " ++ f"divisible by 4; got D={int(q.shape[-1])}, D/16={scale_cols}" + ) + if k_global_scale is not None and k_global_scale.numel() < 1: + raise ValueError("KVFP4 K global scale must contain at least one element") +@@ -373,7 +409,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + raise ValueError(f"KVFP4 packed K/V last dimension must be D/2={packed_dim}") + total_k = int(k.shape[0]) + head_kv = int(k.shape[1]) +- required_scale_rows = total_k * head_kv ++ num_pages = None ++ page_size = None + else: + if k.ndim != 4: + raise ValueError( +@@ -388,7 +425,8 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + f"KVFP4 Sparse Page Attention requires page_size == blk_kv, got {page_size} vs {blk_kv}" + ) + head_kv = int(k.shape[1]) +- required_scale_rows = int(k.shape[0]) * head_kv * page_size ++ total_k = None ++ num_pages = int(k.shape[0]) + if page_table.device != q.device: + raise ValueError("page_table must be on the same device as q") + if page_table.dtype != torch.int32: +@@ -405,13 +443,102 @@ def _validate_csr_varlen_nvfp4_kv_inputs( + if not seqused_k.is_contiguous(): + raise ValueError("seqused_k must be contiguous") -- logical = scale[:rows, :cols].contiguous() -- if logical.shape != (padded_rows, padded_cols): -- logical = torch.nn.functional.pad( -- logical.to(torch.float32), -- (0, padded_cols - cols, 0, padded_rows - rows), -- ).to(scale.dtype) -- swizzled = torch.empty_like(logical) -- -- row = torch.arange(padded_rows, device=scale.device, dtype=torch.int64)[:, None] -- col = torch.arange(padded_cols, device=scale.device, dtype=torch.int64)[None, :] -- offset = nvfp4_scale_128x4_offset(row, col, padded_cols).reshape(-1) -- swizzled.reshape(-1)[offset] = logical.reshape(-1) -- return swizzled -+ n_regions, region_tokens, quad_regroup = _scale_region_grid(shape, layout) -+ flat = packed.contiguous().reshape(n_regions, region_tokens * scale_cols) -+ logical = _unpack_nvfp4_scale( -+ flat, page_size=region_tokens, scale_cols=scale_cols, layout=layout -+ ) -+ if quad_regroup: -+ heads = shape[1] if len(shape) == 3 else 1 -+ logical = ( -+ logical.reshape(shape[0] // 4, heads, 4, scale_cols) -+ .permute(0, 2, 1, 3) -+ .reshape(rows, scale_cols) -+ ) -+ return logical.reshape(rows, scale_cols) +- padded_scale_rows = ((required_scale_rows + 127) // 128) * 128 +- padded_scale_cols = ((scale_cols + 3) // 4) * 4 +- for name, scale in (("k_scale_128x4", k_scale_128x4), ("v_scale_128x4", v_scale_128x4)): +- if scale.shape[0] < padded_scale_rows or scale.shape[1] < padded_scale_cols: ++ # ---- scale-factor containers ------------------------------------------- ++ # A scale region is EXACTLY region_tokens * D/16 bytes: no row padding, no ++ # column padding. (The deleted 128x4 layout demanded ++ # round_up(rows,128) x round_up(cols,4); nothing here does.) The kernel ++ # addresses inside a region with page/head strides supplied by the host, ++ # so what has to be checked is the shape and the *in-region* byte order. ++ for name, scale in (("k_scale", k_scale), ("v_scale", v_scale)): ++ if scale.stride(-1) != 1: + raise ValueError( +- f"{name} is too small for 128x4 layout: got {tuple(scale.shape)}, " +- f"need at least {(padded_scale_rows, padded_scale_cols)}" ++ f"{name} must be contiguous in its last dimension, got " ++ f"stride(-1)={scale.stride(-1)}" ++ ) ++ if page_table is None: ++ expected = (total_k, head_kv, scale_cols) ++ if scale.ndim != 3 or tuple(int(d) for d in scale.shape) != expected: ++ raise ValueError( ++ f"KVFP4 flat-varlen {name} must have shape " ++ f"[total_k, Hkv, D/16] = {expected}, got " ++ f"{tuple(int(d) for d in scale.shape)}" ++ ) ++ # Flat varlen has no production producer (vLLM is paged only); it ++ # exists because flat test inputs are cheap. The kernel derives ++ # the flat region geometry in-kernel from num_heads_kv and S and ++ # IGNORES the four host stride arguments, so the container has to ++ # be exactly the plain contiguous one it assumes. ++ if ( ++ int(scale.stride(0)) != head_kv * scale_cols ++ or int(scale.stride(1)) != scale_cols ++ ): ++ raise ValueError( ++ f"KVFP4 flat-varlen {name} must be contiguous with strides " ++ f"{(head_kv * scale_cols, scale_cols, 1)}, got " ++ f"{tuple(int(s) for s in scale.stride())}" ++ ) ++ else: ++ expected = (num_pages, head_kv, page_size, scale_cols) ++ if scale.ndim != 4 or tuple(int(d) for d in scale.shape) != expected: ++ raise ValueError( ++ f"KVFP4 paged {name} must have shape " ++ f"[num_pages, Hkv, page_size, D/16] = {expected}, got " ++ f"{tuple(int(d) for d in scale.shape)}" ++ ) ++ # HND ONLY -- and this is not an arbitrary house rule. vLLM's ++ # NVFP4 store kernel sniffs the physical layout from strides, ++ # `bool is_hnd = key_cache.stride(2) > key_cache.stride(1)` ++ # (csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu:222, on the ++ # logical [pages, block, heads, dim] view), and then picks ++ # HND: scale_head_stride = block_size*S, token stride = S ++ # NHD: scale_head_stride = S, token stride = Hkv*S ++ # (:245-251). MSA's in-region offsets -- `t*S + s` for K and ++ # `(t//4)*(4*S) + 4*s + (t%4)` for V, the latter round-tripped ++ # through `swizzled_t * scale_block_offset_stride + swizzled_s` ++ # at :167-170 -- are correct ONLY when the token stride is S, ++ # i.e. only under HND. The kernel BAKES IN token stride == S; it ++ # does not read stride(2). So `stride(1) > stride(2)` alone is not ++ # enough: pin both inner strides exactly. Under NHD a ++ # per-(page, head) region is not contiguous at all, yet every ++ # shape, dtype, size(-1) and stride(-1) check above still passes ++ # and the kernel would read silently wrong bytes -- no exception, ++ # just degraded accuracy. M3 is HND ++ # (vllm/models/minimax_m3/nvidia/sparse_attention_msa.py:86-95), ++ # so assert it rather than discovering it as an accuracy loss. ++ if ( ++ int(scale.stride(2)) != scale_cols ++ or int(scale.stride(1)) != page_size * scale_cols ++ ): ++ raise ValueError( ++ f"KVFP4 paged {name} must use the HND NVFP4 KV-cache " ++ "layout: token stride must be exactly D/16==" ++ f"{scale_cols} and head stride exactly page_size*D/16==" ++ f"{page_size * scale_cols}; got stride(1)=" ++ f"{int(scale.stride(1))}, stride(2)={int(scale.stride(2))}. " ++ "NHD is unsupported: vLLM's writer branches on " ++ "`is_hnd = key_cache.stride(2) > key_cache.stride(1)` " ++ "(nvfp4_kv_cache_kernels.cu:222) and lays the scale bytes " ++ "out differently (:245-251), which no shape or dtype check " ++ "can catch." ++ ) ++ ++ # Packed FP4 data. These are no longer forced contiguous at the call site ++ # (that copied the whole KV cache against a vLLM view), so state the two ++ # properties the TMA descriptor actually needs. ++ for name, data in (("k", k), ("v", v)): ++ if int(data.stride(-1)) != 1: ++ raise ValueError( ++ f"KVFP4 {name} must be contiguous in its last dimension, got " ++ f"stride(-1)={int(data.stride(-1))}" ++ ) ++ if page_table is not None and int(data.stride(1)) <= int(data.stride(2)): ++ # HND, for the same reason as the scale views above: the page/head ++ # addressing and the TMA descriptor assume head-major pages. ++ raise ValueError( ++ f"KVFP4 paged {name} must use the HND NVFP4 KV-cache layout " ++ f"(head stride > token stride); got stride(1)=" ++ f"{int(data.stride(1))}, stride(2)={int(data.stride(2))}. " ++ "See nvfp4_kv_cache_kernels.cu:222." + ) + if k2q_row_ptr.device != q.device or k2q_q_indices.device != q.device: +@@ -622,6 +749,7 @@ def sparse_atten_func( + usable_SM_count: int = -1, + qk_dtype: Optional[torch.dtype] = None, + pv_dtype: Optional[torch.dtype] = None, ++ out: Optional[torch.Tensor] = None, + ): + """Run SM100 CSR block-sparse varlen attention. - def nvfp4_global_scale_from_amax(amax: torch.Tensor) -> torch.Tensor: -@@ -171,34 +404,182 @@ def _import_te_nvfp4_quantizer(): - return NVFP4Quantizer +@@ -691,6 +819,10 @@ def sparse_atten_func( + pv_dtype : torch.dtype, optional + Compile-time MMA operand dtype for PV. Defaults to V storage dtype, + except supported FP8 K/V cache staging modes. ++ out : torch.Tensor, optional ++ Destination for the attention output, written in place by the reduction ++ instead of being allocated here. Must be contiguous BF16 of shape ++ ``[total_q, Hq, 128]`` on the same device as ``q``. + Returns + ------- +@@ -736,10 +868,21 @@ def sparse_atten_func( + max_seqlen_q = int(max_seqlen_q) + max_seqlen_k = int(max_seqlen_k) --def quantize_bf16_to_nvfp4_128x4(x: torch.Tensor) -> Nvfp4QuantizedTensor: -- """Quantize a BF16/FP16 tensor to NVFP4 using Transformer Engine. -+# --------------------------------------------------------------------------- -+# Dependency-free (pure PyTorch) NVFP4 quantizer -+# --------------------------------------------------------------------------- -+# -+# This is a drop-in replacement for the Transformer Engine path above. It -+# exists so the NVFP4 accuracy tests can run on machines without a working -+# Transformer Engine build; it is an exact round-trip partner of -+# ``dequantize_nvfp4_to_bf16`` below and uses the same physical layout the -+# kernel reads (``_scale_offset_linear`` / ``_scale_offset_swizzle4x4`` in -+# ``src/sm100/fwd/atten_fwd_nvfp4_kv.py``). -+ -+# FP4 E2M1: 1 sign bit, 2 exponent bits, 1 mantissa bit. Codes 0..7 hold the -+# non-negative magnitudes and bit 3 is the sign. Same table as the LUT used by -+# ``dequantize_nvfp4_to_bf16``. -+_E2M1_MAGNITUDES: Tuple[float, ...] = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) -+ -+# ``_E2M1_MIDPOINTS[i]`` is the tie point between code ``i`` and code ``i + 1``. -+_E2M1_MIDPOINTS: Tuple[float, ...] = (0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0) -+ -+ -+def _round_to_e2m1_codes(x: torch.Tensor) -> torch.Tensor: -+ """Round FP32 values to FP4 E2M1 codes, round-to-nearest-even. -+ -+ Ties resolve to the code whose mantissa bit is zero, i.e. the even code, -+ matching ``cvt.rn.satfinite.e2m1x2.f32``. Magnitudes above 6 saturate to -+ code 7 (6.0); the sign is preserved in bit 3, including for negative zero. -+ """ -+ -+ xf = torch.nan_to_num(x.to(torch.float32), nan=0.0) -+ sign = torch.signbit(xf) -+ magnitude = xf.abs().contiguous() -+ midpoints = torch.tensor( -+ _E2M1_MIDPOINTS, dtype=torch.float32, device=xf.device -+ ) -+ # ``low`` counts midpoints strictly below the magnitude (round down on a -+ # tie); ``high`` counts midpoints at or below it (round up on a tie). They -+ # differ only exactly on a tie, where the tie sits at index ``low``. -+ low = torch.searchsorted(midpoints, magnitude, right=False) -+ high = torch.searchsorted(midpoints, magnitude, right=True) -+ code = torch.where(low % 2 == 0, low, high).to(torch.uint8) -+ return code | (sign.to(torch.uint8) << 3) -+ -+ -+def _pack_e2m1_codes(codes: torch.Tensor) -> torch.Tensor: -+ """Pack pairs of E2M1 codes into bytes; even element in the low nibble.""" -+ -+ return (codes[..., 0::2] & 0x0F) | (codes[..., 1::2] << 4) -+ -+ -+def _quantize_bf16_to_nvfp4_torch( -+ x: torch.Tensor, -+ *, -+ rows: int, -+ scale_cols: int, -+ layout: str, -+) -> "Nvfp4QuantizedTensor": -+ """Quantize to NVFP4 with plain PyTorch, no Transformer Engine. -+ -+ Follows the same recipe TE uses: -+ global_scale = amax(|x|) / (448 * 6) -+ block_scale = to_e4m3(amax(|block|) / (6 * global_scale)) <= 448 -+ fp4 = to_e2m1(block / (block_scale * global_scale)) -+ so ``fp4 * block_scale * global_scale`` reconstructs the value exactly in -+ FP32, which is what ``dequantize_nvfp4_to_bf16`` computes. -+ -+ Everything except the final :func:`_pack_block_scale` call is -+ layout-agnostic: the global scale, the block amax, the E4M3 encode, the -+ E2M1 rounding and the nibble packing do not depend on where the scale -+ bytes end up. -+ """ -+ -+ flat = x.detach().to(torch.float32).contiguous().reshape(rows, -1) -+ amax = flat.abs().amax() -+ global_scale = nvfp4_global_scale_from_amax(amax.reshape(1)) -+ # An all-zero tensor would give a zero (and thus unusable) global scale. -+ global_scale = torch.where( -+ global_scale > 0, global_scale, torch.ones_like(global_scale) -+ ) -+ -+ blocks = flat.reshape(rows, scale_cols, NVFP4_BLOCK_SIZE) -+ block_amax = blocks.abs().amax(dim=-1) -+ encoded = (block_amax / (NVFP4_FP4_MAX * global_scale)).clamp( -+ min=0.0, max=NVFP4_FP8_E4M3_MAX -+ ) -+ block_scale = encoded.to(torch.float8_e4m3fn) -+ dequant_step = block_scale.to(torch.float32) * global_scale -+ nonzero = dequant_step > 0 -+ safe_step = torch.where(nonzero, dequant_step, torch.ones_like(dequant_step)) -+ -+ codes = _round_to_e2m1_codes(blocks / safe_step.unsqueeze(-1)) -+ codes = torch.where(nonzero.unsqueeze(-1), codes, torch.zeros_like(codes)) -+ data = _pack_e2m1_codes(codes.reshape(rows, -1)).reshape( -+ *x.shape[:-1], x.shape[-1] // 2 -+ ) -+ -+ scale = _pack_block_scale( -+ block_scale.view(torch.uint8), -+ rows=rows, -+ scale_cols=scale_cols, -+ original_shape=x.shape, -+ layout=layout, ++ k_input = ( ++ k.contiguous() ++ if page_table is None ++ else _prepare_paged_hnd_input(k, blk_kv) + ) -+ -+ return Nvfp4QuantizedTensor( -+ data=data.contiguous(), -+ scale=scale.contiguous(), -+ global_scale=global_scale.to(torch.float32).contiguous(), -+ logical_scale_shape=(rows, scale_cols), -+ original_shape=tuple(int(v) for v in x.shape), -+ layout=layout, ++ v_input = ( ++ v.contiguous() ++ if page_table is None ++ else _prepare_paged_hnd_input(v, blk_kv) + ) + -+ -+def te_nvfp4_quantizer_available() -> bool: -+ """Return True when Transformer Engine's NVFP4 quantizer can be imported.""" -+ -+ try: -+ _import_te_nvfp4_quantizer() -+ except RuntimeError: -+ return False -+ return True -+ -+ -+def quantize_bf16_to_nvfp4( -+ x: torch.Tensor, -+ *, -+ layout: str, -+ backend: str = "auto", -+) -> Nvfp4QuantizedTensor: -+ """Quantize a BF16/FP16 tensor to NVFP4. - - TE returns rowwise scales in logical padded layout. This helper returns -- the scales in physical 128x4 tiled storage, so the attention kernel can -- load them with ``nvfp4_scale_128x4_offset``. -+ the scales in the physical container the attention kernel reads -- -+ ``"linear"`` for K, ``"swizzle4x4"`` for V (see the module docstring). -+ 128x4 was this module's own choice and never a TE constraint, so the TE -+ backend is unaffected by the layout change: it still hands back logical -+ ``meta["rowwise_scale_inv"]`` and the packing happens here. -+ -+ Two backends produce the same layout: -+ * ``"te"`` - Transformer Engine's ``NVFP4Quantizer``. -+ * ``"torch"`` - a dependency-free PyTorch implementation of the same -+ recipe. Use it when Transformer Engine is not installed. -+ * ``"auto"`` - TE if importable, otherwise ``"torch"``. Override with -+ the ``MSA_NVFP4_QUANTIZER_BACKEND`` environment variable. - - Parameters - ---------- - x : torch.Tensor -- CUDA BF16 or FP16 tensor. The last dimension must be divisible by 16, -- and the flattened row dimension ``prod(x.shape[:-1])`` must also be -- divisible by 16. -+ CUDA BF16 or FP16 tensor, shaped ``[num_pages, Hkv, page_size, D]`` -+ (paged), ``[total_k, Hkv, D]`` or ``[total_k, D]`` (flat varlen). The -+ last dimension must be divisible by 16, and the flattened row -+ dimension ``prod(x.shape[:-1])`` must also be divisible by 16. -+ layout : str -+ ``"linear"`` (K) or ``"swizzle4x4"`` (V). Required -- there is no -+ default, because silently picking the wrong one for V produces -+ plausible-looking but wrong numbers. -+ backend : str, optional -+ ``"auto"``, ``"te"`` or ``"torch"``. - - Returns - ------- - Nvfp4QuantizedTensor -- Packed FP4 data, 128x4-swizzled block scales, global scale, and shape -- metadata needed by the KVFP4 attention kernel or by reference -- dequantization. -+ Packed FP4 data, packed block scales, global scale, and shape metadata -+ needed by the KVFP4 attention kernel or by reference dequantization. - """ - -+ layout = _check_layout(layout) - if not x.is_cuda: - raise ValueError("NVFP4 quantization requires a CUDA tensor") - if x.dtype not in (torch.bfloat16, torch.float16): - raise TypeError(f"x must be bf16 or fp16, got {x.dtype}") -- if x.ndim < 2: -- raise ValueError(f"x must have at least 2 dimensions, got {x.ndim}") -+ if x.ndim not in (2, 3, 4): -+ raise ValueError( -+ "x must be rank-4 [num_pages, Hkv, page_size, D], rank-3 " -+ f"[total_k, Hkv, D] or rank-2 [total_k, D], got rank {x.ndim}" -+ ) - if x.shape[-1] % NVFP4_BLOCK_SIZE != 0: - raise ValueError( - f"last dimension must be divisible by {NVFP4_BLOCK_SIZE}, got {x.shape[-1]}" -@@ -213,6 +594,26 @@ def quantize_bf16_to_nvfp4_128x4(x: torch.Tensor) -> Nvfp4QuantizedTensor: - f"{NVFP4_BLOCK_SIZE}, got {rows}" - ) - -+ scale_cols = int(x.shape[-1]) // NVFP4_BLOCK_SIZE -+ # Fail here rather than after a full quantization pass. -+ _scale_region_grid(x.shape, layout) -+ -+ # An explicit argument wins; the environment only supplies the default, so -+ # a caller that asks for a specific backend always gets it (or an error). -+ backend = backend.lower() -+ if backend == "auto": -+ backend = os.environ.get("MSA_NVFP4_QUANTIZER_BACKEND", "auto").lower() -+ if backend not in ("auto", "te", "torch"): -+ raise ValueError( -+ f"backend must be 'auto', 'te' or 'torch', got {backend!r}" -+ ) -+ if backend == "auto": -+ backend = "te" if te_nvfp4_quantizer_available() else "torch" -+ if backend == "torch": -+ return _quantize_bf16_to_nvfp4_torch( -+ x, rows=rows, scale_cols=scale_cols, layout=layout -+ ) -+ - NVFP4Quantizer = _import_te_nvfp4_quantizer() - quantizer = NVFP4Quantizer(rowwise=True, columnwise=False) - qx = quantizer.quantize(x.contiguous()) -@@ -223,29 +624,34 @@ def quantize_bf16_to_nvfp4_128x4(x: torch.Tensor) -> Nvfp4QuantizedTensor: - data = data.view(torch.uint8) - logical_scale = meta["rowwise_scale_inv"] - amax = meta["amax_rowwise"] -- scale_cols = int(x.shape[-1]) // NVFP4_BLOCK_SIZE -- scale_128x4 = swizzle_nvfp4_scale_to_128x4( -+ scale = _pack_block_scale( - logical_scale, - rows=rows, -- cols=scale_cols, -+ scale_cols=scale_cols, -+ original_shape=x.shape, -+ layout=layout, - ) - global_scale = nvfp4_global_scale_from_amax(amax).contiguous() - - return Nvfp4QuantizedTensor( - data=data, -- scale_128x4=scale_128x4, -+ scale=scale, - global_scale=global_scale, - logical_scale_shape=(rows, scale_cols), - original_shape=tuple(int(v) for v in x.shape), -+ layout=layout, + return _sparse_atten_csr_varlen_forward( + q.contiguous(), +- k.contiguous(), +- v.contiguous(), ++ k_input, ++ v_input, + k2q_row_ptr.contiguous(), + k2q_q_indices.contiguous(), + int(topK), +@@ -762,6 +905,7 @@ def sparse_atten_func( + int(max_seqlen_k), + qk_dtype, + pv_dtype, ++ out=out, ) --def quantize_kv_bf16_to_nvfp4_128x4( -+def quantize_kv_bf16_to_nvfp4( +@@ -769,8 +913,8 @@ def sparse_atten_nvfp4_kv_func( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, - ) -> tuple[Nvfp4QuantizedTensor, Nvfp4QuantizedTensor]: - """Quantize BF16/FP16 K and V tensors independently for KVFP4 attention. - -+ K is packed ``"linear"`` and V ``"swizzle4x4"``, which is exactly what the -+ attention kernel reads and what vLLM's NVFP4 KV-cache store kernel writes. -+ - Parameters - ---------- - k : torch.Tensor -@@ -259,10 +665,13 @@ def quantize_kv_bf16_to_nvfp4_128x4( - Quantized K and V tensors with independent scales. - """ - -- return quantize_bf16_to_nvfp4_128x4(k), quantize_bf16_to_nvfp4_128x4(v) -+ return ( -+ quantize_bf16_to_nvfp4(k, layout="linear"), -+ quantize_bf16_to_nvfp4(v, layout="swizzle4x4"), -+ ) - - --def dequantize_nvfp4_128x4_to_bf16( -+def dequantize_nvfp4_to_bf16( - qx: Nvfp4QuantizedTensor, - *, - include_global_scale: bool = True, -@@ -272,10 +681,15 @@ def dequantize_nvfp4_128x4_to_bf16( - This mirrors the kernel contract: - x = e2m1 * E4M3_block_scale_1x16 * FP32_global_scale +- k_scale_128x4: torch.Tensor, +- v_scale_128x4: torch.Tensor, ++ k_scale: torch.Tensor, ++ v_scale: torch.Tensor, + k_global_scale: Optional[torch.Tensor], + v_global_scale: Optional[torch.Tensor], + k2q_row_ptr: torch.Tensor, +@@ -791,9 +935,17 @@ def sparse_atten_nvfp4_kv_func( + page_table: Optional[torch.Tensor] = None, + seqused_k: Optional[torch.Tensor] = None, + schedule: Optional[SparseAttentionSchedule] = None, ++ out: Optional[torch.Tensor] = None, ++ o_fp8: Optional[torch.Tensor] = None, ++ sf_out: Optional[torch.Tensor] = None, ++ write_bf16: bool = True, + ): + """Run SM100 CSR sparse attention with packed NVFP4 K/V. -+ The scale gather uses ``qx.layout``, so the result is layout-independent: -+ the same logical block scales give the same BF16 output whether they were -+ packed ``"linear"`` or ``"swizzle4x4"``. ++ ``o_fp8`` / ``sf_out`` (with ``out``): the combine also writes the final O as MXFP8 for an MXFP8 o_proj ++ (E4M3 [total_q, head_q * dim] + swizzled 128x4 K32 UE8M0 scales), bitwise mxfp8_quantize(O, True); ++ ``write_bf16=False`` skips the bf16 store. See combine(). + Parameters ---------- - qx : Nvfp4QuantizedTensor -- Quantized tensor returned by ``quantize_bf16_to_nvfp4_128x4``. -+ Quantized tensor returned by ``quantize_bf16_to_nvfp4``. ``qx.scale`` -+ must be a contiguous packed container. - include_global_scale : bool, optional - If True, multiply by ``qx.global_scale`` after applying per-block - scales. -@@ -286,6 +700,7 @@ def dequantize_nvfp4_128x4_to_bf16( - BF16 tensor with shape ``qx.original_shape``. - """ - -+ layout = _check_layout(qx.layout) - data = qx.data if qx.data.dtype is torch.uint8 else qx.data.view(torch.uint8) - if data.shape[-1] * 2 != qx.original_shape[-1]: - raise ValueError( -@@ -330,10 +745,13 @@ def dequantize_nvfp4_128x4_to_bf16( - values[:, 0::2] = fp4_lut[lo.long()] - values[:, 1::2] = fp4_lut[hi.long()] - -- row = torch.arange(rows, device=data.device, dtype=torch.int64)[:, None] -- col = torch.arange(scale_cols, device=data.device, dtype=torch.int64)[None, :] -- offset = nvfp4_scale_128x4_offset(row, col, scale_cols) -- scale_u8 = qx.scale_128x4.reshape(-1)[offset.reshape(-1)].reshape(rows, scale_cols) -+ scale_u8 = _unpack_block_scale( -+ qx.scale, -+ rows=rows, -+ scale_cols=scale_cols, -+ original_shape=qx.original_shape, -+ layout=layout, -+ ) - scale = scale_u8.view(torch.float8_e4m3fn).to(torch.float32) - scale = scale.repeat_interleave(NVFP4_BLOCK_SIZE, dim=1) - out = values * scale -@@ -347,12 +765,12 @@ def _example() -> None: - device = torch.device("cuda") - k = torch.randn(128, 2, 128, device=device, dtype=torch.bfloat16) - v = torch.randn_like(k) -- k_q, v_q = quantize_kv_bf16_to_nvfp4_128x4(k, v) -+ k_q, v_q = quantize_kv_bf16_to_nvfp4(k, v) - print("K FP4 data:", tuple(k_q.data.shape), k_q.data.dtype) -- print("K scale 128x4:", tuple(k_q.scale_128x4.shape), k_q.scale_128x4.dtype) -+ print("K scale (linear):", tuple(k_q.scale.shape), k_q.scale.dtype) - print("K global scale:", tuple(k_q.global_scale.shape), k_q.global_scale.dtype) - print("V FP4 data:", tuple(v_q.data.shape), v_q.data.dtype) -- print("V scale 128x4:", tuple(v_q.scale_128x4.shape), v_q.scale_128x4.dtype) -+ print("V scale (swizzle4x4):", tuple(v_q.scale.shape), v_q.scale.dtype) - print("V global scale:", tuple(v_q.global_scale.shape), v_q.global_scale.dtype) - - -diff --git a/python/fmha_sm100/cute/src/common/aot_cache.py b/python/fmha_sm100/cute/src/common/aot_cache.py -index 99fd0b4..05b3254 100644 ---- a/python/fmha_sm100/cute/src/common/aot_cache.py -+++ b/python/fmha_sm100/cute/src/common/aot_cache.py -@@ -6,6 +6,12 @@ - Saves compiled TVM FFI kernels as .o files on first compile, - loads them on subsequent runs to skip JIT compilation. - -+Cached objects are keyed by the caller's kernel key *and* a build fingerprint -+covering the target GPU architecture and the kernel sources. Without the -+fingerprint a .o built for one architecture (or from an older revision of the -+kernel) is silently reused on another, which both miscompiles across -+SM100/SM103 and makes local kernel edits appear to have no effect. -+ - Environment variables: - MM_SPARSE_ATTN_AOT_CACHE: Override cache directory - (default: ~/.cache/minfer/mm_sparse_attn) -@@ -25,10 +31,64 @@ _AOT_CACHE_DIR = os.environ.get( - _AOT_DISABLE = os.environ.get("MM_SPARSE_ATTN_AOT_DISABLE", "0") == "1" - - _loaded_modules: dict[str, object] = {} -+_build_fingerprint_cache: str | None = None -+ -+# .../cute/src/common/aot_cache.py -> .../cute -+_PACKAGE_ROOT = os.path.dirname( -+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -+) -+ -+ -+def _source_fingerprint() -> str: -+ """Hash every .py under the cute package so edits invalidate the cache.""" -+ h = hashlib.sha256() -+ for dirpath, dirnames, filenames in os.walk(_PACKAGE_ROOT): -+ dirnames[:] = sorted(d for d in dirnames if d != "__pycache__") -+ for filename in sorted(filenames): -+ if not filename.endswith(".py"): -+ continue -+ path = os.path.join(dirpath, filename) -+ h.update(os.path.relpath(path, _PACKAGE_ROOT).encode()) -+ try: -+ with open(path, "rb") as f: -+ h.update(f.read()) -+ except OSError: -+ # Unreadable source: fold the error in rather than silently -+ # producing the same digest as if the file did not exist. -+ h.update(b"") -+ return h.hexdigest()[:16] -+ -+ -+def _target_arch() -> str: -+ """Compute capability of the device the kernel will be launched on.""" -+ try: -+ import torch -+ -+ major, minor = torch.cuda.get_device_capability() -+ return f"sm{major}{minor}" -+ except Exception: -+ return "smunknown" -+ -+ -+def _build_fingerprint() -> str: -+ global _build_fingerprint_cache -+ if _build_fingerprint_cache is None: -+ try: -+ import cutlass -+ -+ cutlass_version = getattr(cutlass, "__version__", "unknown") -+ except Exception: -+ cutlass_version = "unknown" -+ _build_fingerprint_cache = "-".join( -+ (_target_arch(), str(cutlass_version), _source_fingerprint()) -+ ) -+ return _build_fingerprint_cache - + q : torch.Tensor +@@ -805,16 +957,25 @@ def sparse_atten_nvfp4_kv_func( + because each byte packs two FP4 values. + v : torch.Tensor + Packed NVFP4 V data with the same shape as ``k``. +- k_scale_128x4 : torch.Tensor +- K block scales in cuBLAS/cuDNN 128x4 tiled storage. Dtype uint8 +- containing FP8 E4M3 scale values. +- v_scale_128x4 : torch.Tensor +- V block scales in the same 128x4 tiled storage. ++ k_scale : torch.Tensor ++ K block scales, dtype uint8 holding FP8 E4M3 values, in the **linear** ++ scale-factor layout: byte ``t*S + s`` inside each scale region, with ++ ``S = 128//16 = 8``. Shape is ``[num_pages, Hkv, blk_kv, S]`` (paged) ++ or ``[total_k, Hkv, S]`` (flat), with no row or column padding -- a ++ region is exactly ``blk_kv * S`` bytes. Paged views must be HND (see ++ ``_validate_csr_varlen_nvfp4_kv_inputs``). A vLLM scale view from ++ ``nvfp4_split_data_scale`` is ``float8_e4m3fn`` and must be passed as ++ ``.view(torch.uint8)`` -- zero-copy, but a ``TypeError`` if forgotten. ++ v_scale : torch.Tensor ++ V block scales, same shape and dtype rules, but in the **4x4 ++ token-quad swizzle**: byte ``(t//4)*(4*S) + 4*s + (t%4)``. This is the ++ K/V layout pair vLLM's NVFP4 KV-cache store kernel writes, so a vLLM ++ cache is consumed with no repack pass. + k_global_scale : torch.Tensor, optional + FP32 tensor/global dequant scale for K. May be ``None``. + v_global_scale : torch.Tensor, optional +- FP32 tensor/global dequant scale for V. May be ``None``. The V global +- scale is applied in the combine stage. ++ FP32 tensor/global dequant scale for V. May be ``None``. FP8 staging ++ applies it before conversion; BF16 staging applies it during combine. + k2q_row_ptr : torch.Tensor + CSR row pointers with shape ``[Hkv, total_rows + 1]`` and dtype int32. + k2q_q_indices : torch.Tensor +@@ -847,7 +1008,14 @@ def sparse_atten_nvfp4_kv_func( + Paged-KV physical page table with shape + ``[batch_size, max_num_pages_per_seq]`` and dtype int32. + seqused_k : torch.Tensor, optional +- Effective KV length per request for paged causal attention. ++ Effective KV length per request for paged causal attention. **Always ++ pass this for paged KV.** Without it ``_logical_seqlen_k`` falls back ++ to ``page_table.shape[1] * page_size`` -- the full *allocated* span -- ++ so every KV block looks fully valid and the mask silently does nothing. ++ The failure mode is not NaN: unwritten K dequantizes to 0, giving ++ ``S = 0``, which still receives non-zero softmax weight and inflates ++ ``row_sum``. The output is then uniformly scaled down and reads like a ++ tolerance problem. + schedule : SparseAttentionSchedule, optional + Prebuilt sparse forward schedule. - def _key_to_path(key: tuple) -> str: -- h = hashlib.sha256(repr(key).encode()).hexdigest()[:16] -+ h = hashlib.sha256( -+ repr((_build_fingerprint(), key)).encode() -+ ).hexdigest()[:16] - name = str(key[0]).replace("/", "_") - return os.path.join(_AOT_CACHE_DIR, f"{name}_{h}") +@@ -878,8 +1046,8 @@ def sparse_atten_nvfp4_kv_func( + q, + k, + v, +- k_scale_128x4, +- v_scale_128x4, ++ k_scale, ++ v_scale, + k_global_scale, + v_global_scale, + k2q_row_ptr, +@@ -917,7 +1085,24 @@ def sparse_atten_nvfp4_kv_func( + if kernel_return_temperature_lse + else None + ) +- O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device) ++ if out is None: ++ O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device) ++ else: ++ # `combine` writes its output with a plain contiguous layout, so a ++ # caller that already owns a matching buffer can have it written ++ # directly instead of copying the result afterwards. ++ if tuple(out.shape) != (total_q, head_q, dim): ++ raise ValueError( ++ f"out must have shape {(total_q, head_q, dim)}, " ++ f"got {tuple(out.shape)}" ++ ) ++ if out.dtype != torch.bfloat16: ++ raise TypeError(f"out must be torch.bfloat16, got {out.dtype}") ++ if out.device != q.device: ++ raise ValueError("out must be on the same device as q") ++ if not out.is_contiguous(): ++ raise ValueError("out must be contiguous") ++ O_out = out + LSE_out = torch.empty(total_q, head_q, dtype=torch.float32, device=q.device) + LSE_temperature_out = ( + torch.empty_like(LSE_out) if kernel_return_temperature_lse else None +@@ -939,12 +1124,19 @@ def sparse_atten_nvfp4_kv_func( + k2q_qsplit_indices = schedule.qsplit_indices + split_counts = schedule.split_counts -diff --git a/python/fmha_sm100/cute/src/common/cuda_toolchain.py b/python/fmha_sm100/cute/src/common/cuda_toolchain.py -new file mode 100644 -index 0000000..80cae6e ---- /dev/null -+++ b/python/fmha_sm100/cute/src/common/cuda_toolchain.py -@@ -0,0 +1,169 @@ -+# SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax -+# SPDX-License-Identifier: MIT -+ -+"""Capability probes for the CUDA toolchain that assembles our inline PTX. -+ -+``cutlass.CUDA_VERSION`` reports the CUDA version the CuTe DSL was *built* -+against, not the version of the libNVVM/ptxas that will actually compile the -+generated device IR. Those differ whenever a wheel built against a newer CUDA -+is installed next to an older toolkit -- and when they do, version-gated inline -+PTX is emitted that the assembler cannot parse. The only diagnostic surfaced in -+that case is a bare:: -+ -+ NVVM backend compilation failed -+ libNVVM failed while compiling generated device IR. -+ -+with no mention of the offending instruction, which is extremely hard to -+diagnose from the kernel side. -+ -+``ptxas_supports()`` answers the question directly by assembling a -+one-instruction kernel with the real ptxas. That is correct across mixed -+toolkit installations and self-maintaining as instructions land in new -+releases, so gates built on it do not need to encode a CUDA version threshold -+that may turn out to be wrong. -+""" -+ -+import functools -+import os -+import shutil -+import subprocess -+import tempfile -+ -+__all__ = [ -+ "find_ptxas", -+ "toolkit_cuda_version", -+ "max_ptx_isa_version", -+ "ptxas_supports", -+] -+ -+# Highest first: the probe takes the first version ptxas accepts. -+_CANDIDATE_ISA_VERSIONS = ( -+ "9.5", "9.4", "9.3", "9.2", "9.1", "9.0", -+ "8.8", "8.7", "8.6", "8.5", "8.4", "8.3", "8.2", "8.1", "8.0", -+) -+ -+_PROBE_TIMEOUT_SECONDS = 30 -+ -+ -+@functools.lru_cache(maxsize=1) -+def find_ptxas() -> str | None: -+ """Locate the ptxas that belongs to the toolkit the DSL will use.""" -+ for var in ("CUDA_TOOLKIT_PATH", "CUDA_HOME", "CUDA_PATH"): -+ root = os.environ.get(var) -+ if root: -+ candidate = os.path.join(root, "bin", "ptxas") -+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK): -+ return candidate -+ found = shutil.which("ptxas") -+ if found: -+ return found -+ candidate = "/usr/local/cuda/bin/ptxas" -+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK): -+ return candidate -+ return None -+ -+ -+@functools.lru_cache(maxsize=1) -+def toolkit_cuda_version() -> tuple[int, int] | None: -+ """(major, minor) of the local ptxas, or None if it cannot be determined.""" -+ ptxas = find_ptxas() -+ if ptxas is None: -+ return None -+ try: -+ proc = subprocess.run( -+ [ptxas, "--version"], -+ capture_output=True, -+ text=True, -+ timeout=_PROBE_TIMEOUT_SECONDS, -+ ) -+ except (OSError, subprocess.SubprocessError): -+ return None -+ # "Cuda compilation tools, release 13.2, V13.2.51" -+ for token in proc.stdout.replace(",", " ").split(): -+ if token.startswith("V") and token.count(".") >= 1: -+ parts = token[1:].split(".") -+ try: -+ return int(parts[0]), int(parts[1]) -+ except (IndexError, ValueError): -+ continue -+ return None ++ # K/V and their block scales are deliberately NOT forced contiguous. They ++ # are consumed through TMA descriptors (data) and host-supplied page/head ++ # strides (scales), both of which handle the strided views vLLM hands in. ++ # ``.contiguous()`` here would copy the *entire* selected KV cache on every ++ # layer of every forward against a ``nvfp4_split_data_scale`` view. The ++ # validator asserts what actually matters instead: exact shapes, ++ # ``stride(-1) == 1`` and the HND inner strides. + schedule = _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + q.contiguous(), +- k.contiguous(), +- v.contiguous(), +- k_scale_128x4.contiguous(), +- v_scale_128x4.contiguous(), ++ k, ++ v, ++ k_scale, ++ v_scale, + None if k_global_scale is None else k_global_scale.contiguous(), + None if v_global_scale is None else v_global_scale.contiguous(), + k2q_row_ptr.contiguous(), +@@ -978,8 +1170,11 @@ def sparse_atten_nvfp4_kv_func( + lse_temperature_out=LSE_temperature_out, + cu_seqlens=cu_seqlens_q, + split_counts=split_counts, +- output_scale=v_global_scale, ++ output_scale=None if q.dtype == torch.float8_e4m3fn else v_global_scale, + use_pdl=True, ++ o_fp8=o_fp8, ++ sf_out=sf_out, ++ write_bf16=write_bf16, + ) + if temperature_lse_fast_path: + LSE_temperature_out = LSE_out +@@ -1296,13 +1491,34 @@ class SparseDecodePagedAttentionWrapper: + self.work_count = schedule.work_count + self.padded_work_count = schedule.padded_work_count + if schedule.split_kv: ++ # O_partial stays uninitialised on purpose: it is only ever read ++ # for splits whose LSE_partial weight is non-zero (combine.py's ++ # ``scale[m] > 0.0`` predicate, and the ``thr_max_valid_split`` ++ # loop bound), so seeding LSE_partial below is enough to make any ++ # unwritten partial row neutral. Zeroing O_partial as well was ++ # measured at +1.7% .. +17.7% of the decode forward (it scales ++ # with partial_rows: 12us for a 64MiB partial buffer, 140us for a ++ # 1GiB one), which is not worth paying for a strictly weaker ++ # guarantee. + self.O_partial = torch.empty( + (schedule.partial_rows, self.num_qo_heads, self.head_dim), + dtype=torch.float32, + device=page_table.device, + ) +- self.LSE_partial = torch.empty( ++ # -inf, not torch.empty. If the forward ever fails to write a ++ # partial row -- a pipeline desync, a schedule bug, a future ++ # kernel edit -- torch.empty makes the combine consume whatever ++ # was in that allocation, which is non-deterministic garbage and ++ # was exactly what turned a decode desync into randomly varying ++ # NaNs. Seeding -inf gives the combine a defined answer instead: ++ # exp(-inf - lse_max) == 0, so the split is dropped, the result is ++ # reproducible, and a correctness test can actually catch it. ++ # Cost is one ~5-6us launch-bound fill per plan() (partial_rows x ++ # Hq fp32 is small), i.e. ~2.5% of plan() and 0.7-4% of the ++ # forward. ++ self.LSE_partial = torch.full( + (schedule.partial_rows, self.num_qo_heads), ++ float("-inf"), + dtype=torch.float32, + device=page_table.device, + ) +@@ -1449,6 +1665,7 @@ def _sparse_atten_csr_varlen_forward( + max_seqlen_k: int, + qk_dtype: torch.dtype, + pv_dtype: torch.dtype, ++ out: Optional[torch.Tensor] = None, + ): + total_q, head_q, dim = q.shape + if head_q % head_kv != 0: +@@ -1478,7 +1695,24 @@ def _sparse_atten_csr_varlen_forward( + if kernel_return_temperature_lse + else None + ) +- O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device) ++ if out is None: ++ O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device) ++ else: ++ # `combine` writes its output with a plain contiguous layout, so a ++ # caller that already owns a matching buffer can have it written ++ # directly instead of copying the result afterwards. ++ if tuple(out.shape) != (total_q, head_q, dim): ++ raise ValueError( ++ f"out must have shape {(total_q, head_q, dim)}, " ++ f"got {tuple(out.shape)}" ++ ) ++ if out.dtype != torch.bfloat16: ++ raise TypeError(f"out must be torch.bfloat16, got {out.dtype}") ++ if out.device != q.device: ++ raise ValueError("out must be on the same device as q") ++ if not out.is_contiguous(): ++ raise ValueError("out must be contiguous") ++ O_out = out + LSE_out = torch.empty(total_q, head_q, dtype=torch.float32, device=q.device) + LSE_temperature_out = ( + torch.empty_like(LSE_out) if kernel_return_temperature_lse else None +@@ -1807,12 +2041,47 @@ def _call_sparse_forward_sm100_csr_varlen( + return schedule + + ++_INT32_MAX = 2**31 - 1 + + -+def _default_target() -> str: -+ """Arch string to probe with; matches the device we will compile for.""" -+ try: -+ import torch ++def _nvfp4_scale_strides(sf, name: str) -> tuple[int, int]: ++ """Return ``(page_stride, head_stride)`` of an NVFP4 scale view, in BYTES. + -+ major, minor = torch.cuda.get_device_capability() -+ return f"sm_{major}{minor}a" -+ except Exception: -+ return "sm_100a" ++ The kernel addresses a scale factor as ``region_base + in_region_offset`` ++ with ``region_base = page*page_stride + head*head_stride`` evaluated in ++ Int64, so these two scalars are the only geometry that has to travel from ++ the host. ``sf`` is a uint8 view (enforced by the validator), so element ++ strides already are byte strides; the ``element_size()`` factor is kept ++ explicit so the unit is not accidental. + ++ For a vLLM paged cache these come straight out of ``nvfp4_split_data_scale`` ++ (``vllm/utils/torch_utils.py:419-467``) as ``(page_bytes, block_size * S)``. ++ The page stride is the FULL page, data bytes included -- ++ ``2*Hkv*block_size*72`` = 73728 B at M3 -- which is why the kernel does the ++ region arithmetic in Int64: a 100 GB cache reaches ~1e11 and overflows Int32 ++ by ~50x. The strides themselves fit in Int32 with room to spare, which is ++ what makes Int32 kernel arguments safe; assert it rather than assume it. ++ """ + -+def _assemble(body: str, isa_version: str, target: str) -> bool: -+ """True iff ptxas accepts a kernel whose body is ``body``.""" -+ ptxas = find_ptxas() -+ if ptxas is None: -+ return False -+ source = ( -+ f".version {isa_version}\n" -+ f".target {target}\n" -+ ".address_size 64\n" -+ ".visible .entry _msa_probe()\n" -+ "{\n" -+ " .reg .b8 %b<8>;\n" -+ " .reg .b16 %h<8>;\n" -+ " .reg .b32 %r<8>;\n" -+ " .reg .b64 %rd<8>;\n" -+ " mov.u32 %r1, 0;\n" -+ " mov.u64 %rd1, 0;\n" -+ f"{body}\n" -+ " ret;\n" -+ "}\n" -+ ) -+ with tempfile.TemporaryDirectory() as tmp: -+ path = os.path.join(tmp, "probe.ptx") -+ with open(path, "w") as f: -+ f.write(source) -+ try: -+ proc = subprocess.run( -+ [ptxas, f"-arch={target}", path, "-o", os.path.join(tmp, "probe.cubin")], -+ capture_output=True, -+ text=True, -+ timeout=_PROBE_TIMEOUT_SECONDS, ++ itemsize = int(sf.element_size()) ++ strides = [] ++ for axis, label in ((0, "page"), (1, "head")): ++ value = int(sf.stride(axis)) * itemsize ++ if value < 0 or value > _INT32_MAX: ++ raise ValueError( ++ f"{name} {label} stride must be a non-negative byte count that " ++ f"fits in int32, got {value}" + ) -+ except (OSError, subprocess.SubprocessError): -+ return False -+ return proc.returncode == 0 -+ ++ strides.append(value) ++ return strides[0], strides[1] + -+@functools.lru_cache(maxsize=8) -+def max_ptx_isa_version(target: str | None = None) -> str | None: -+ """Highest ``.version`` the local ptxas accepts for ``target``. + -+ Probing the instruction at too low an ISA version would report a false -+ negative for an instruction the toolkit actually supports, so the capability -+ probe must first find the ceiling. -+ """ -+ target = target or _default_target() -+ for isa_version in _CANDIDATE_ISA_VERSIONS: -+ if _assemble("", isa_version, target): -+ return isa_version -+ return None -+ -+ -+@functools.lru_cache(maxsize=64) -+def ptxas_supports(body: str, target: str | None = None) -> bool | None: -+ """Whether ptxas assembles ``body``. -+ -+ Returns True/False when ptxas could be run, and None when it could not, so -+ callers can distinguish "unsupported" from "unknown" and fall back to a -+ version comparison rather than silently taking the slow path. -+ """ -+ if find_ptxas() is None: -+ return None -+ target = target or _default_target() -+ isa_version = max_ptx_isa_version(target) -+ if isa_version is None: -+ return None -+ return _assemble(body, isa_version, target) -diff --git a/python/fmha_sm100/cute/src/common/cute_dsl_utils.py b/python/fmha_sm100/cute/src/common/cute_dsl_utils.py -index e3473fb..dc4cfb0 100644 ---- a/python/fmha_sm100/cute/src/common/cute_dsl_utils.py -+++ b/python/fmha_sm100/cute/src/common/cute_dsl_utils.py -@@ -128,10 +128,8 @@ if os.getenv("MINIMAX_LOG_COMPILE", "0") == "1": - logger.setLevel(logging.DEBUG) - - --# Monkey-patch cute.compile so every JIT compile across the repo gets timed --# without touching individual call sites. Idempotent: only patches once. --if cute.compile is not cute_compile_patched: -- cute.compile = cute_compile_patched -+# TensorRT-LLM shares CUTLASS across attention backends, so importing MSA must -+# not replace the process-global cute.compile callable. - - - def assume_strides_aligned(t): -diff --git a/python/fmha_sm100/cute/src/common/tma_utils.py b/python/fmha_sm100/cute/src/common/tma_utils.py -index 5bdc19a..9df4699 100644 ---- a/python/fmha_sm100/cute/src/common/tma_utils.py -+++ b/python/fmha_sm100/cute/src/common/tma_utils.py -@@ -118,9 +118,15 @@ def prefetch_tma_desc_raw(tma_desc_ptr, *, loc=None, ip=None): - ptr_i64 = tma_desc_ptr.toint().ir_value(loc=loc, ip=ip) - ptr_i64_align_ty = cute_ir.ConstrainedIntType.get(128, ptr_i64.type.width) - ptr_i64_align = cute_ir.assume(ptr_i64_align_ty, ptr_i64, loc=loc, ip=ip) -+ # `arch.prefetch_tma_desc` is defined to take a *generic*-addressing pointer -+ # (no specific state space). Building it in the gmem address space instead -+ # passes MLIR verification -- nothing checks the address space here -- but -+ # leaves the NVVM backend with no ISel pattern for the tensormap-prefetch -+ # intrinsic on addrspace(1), so libNVVM aborts with a bare "NVVM backend -+ # compilation failed" and no location or instruction name. - ptr_ty = cute_ir.PtrType.get( - cute_nvgpu_ir.TmaDescriptorTiledType.get(), -- cute_ir.AddressSpace.gmem, -+ cute_ir.AddressSpace.generic, - 128, - ) - desc_ptr = cute_ir.inttoptr(ptr_ty, ptr_i64_align, loc=loc, ip=ip) -diff --git a/python/fmha_sm100/cute/src/common/utils.py b/python/fmha_sm100/cute/src/common/utils.py -index 10b2b1f..3b9f909 100644 ---- a/python/fmha_sm100/cute/src/common/utils.py -+++ b/python/fmha_sm100/cute/src/common/utils.py -@@ -17,8 +17,42 @@ from cutlass.cute.runtime import from_dlpack + def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + q, + k, + v, +- k_scale_128x4, +- v_scale_128x4, ++ k_scale, ++ v_scale, + k_global_scale, + v_global_scale, + k2q_row_ptr, +@@ -1859,9 +2128,9 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + qhead_per_kv = head_q // head_kv + fp8_pair_dequant = os.environ.get("MINIMAX_KVFP4_FP8_PAIR_DEQUANT", "1") != "0" + k_global_scale_kernel = k_global_scale +- # V global scale is linear in the final output. Keep K1 on block-scale-only V +- # and apply the tensor scale once in K2 combine. +- v_global_scale_kernel = None ++ # FP8 cannot hold the block-scaled NVFP4 intermediate (up to 6 * 448). ++ # Reconstruct V before the FP8 cast. BF16 keeps its existing deferred scale. ++ v_global_scale_kernel = v_global_scale if q.dtype == torch.float8_e4m3fn else None + has_k_global_scale = k_global_scale_kernel is not None + has_v_global_scale = v_global_scale_kernel is not None + paged_kv = page_table is not None +@@ -1873,6 +2142,18 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + _prepare_paged_kv_for_tma(k, v, n_block_size) + k_kernel = k + v_kernel = v ++ if paged_kv: ++ k_sf_page_stride, k_sf_head_stride = _nvfp4_scale_strides(k_scale, "k_scale") ++ v_sf_page_stride, v_sf_head_stride = _nvfp4_scale_strides(v_scale, "v_scale") ++ else: ++ # Flat varlen: the kernel derives its region geometry in-kernel from ++ # num_heads_kv and S (there is no host-side owner of it, and no ++ # production flat producer), so it IGNORES these four arguments. Pass ++ # 0 rather than the real strides so nothing here reads as meaningful ++ # input; the validator has already pinned the flat container to the ++ # exact contiguous layout the kernel assumes. ++ k_sf_page_stride = k_sf_head_stride = 0 ++ v_sf_page_stride = v_sf_head_stride = 0 + O_partial_flat = O_partial.reshape(-1, head_dim).contiguous() + Q_flat = q.reshape(-1, head_dim).contiguous() + Q_gather4_desc = ( +@@ -1948,8 +2229,8 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + kernel, + to_cute_tensor_kvouter(k_kernel), + to_cute_tensor_kvouter(v_kernel), +- to_cute_tensor_kvouter(k_scale_128x4), +- to_cute_tensor_kvouter(v_scale_128x4), ++ to_cute_tensor_kvouter(k_scale), ++ to_cute_tensor_kvouter(v_scale), + None if k_global_scale_kernel is None else to_cute_tensor_kvouter(k_global_scale_kernel), + None if v_global_scale_kernel is None else to_cute_tensor_kvouter(v_global_scale_kernel), + to_cute_tensor_kvouter(k2q_q_indices), +@@ -1974,6 +2255,13 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + Int32(head_kv), + Int32(max_seqlen_q), + Int32(work_capacity), ++ # Scale-factor page/head strides, in BYTES, after ++ # work_capacity and before the stream. Same order in the ++ # launch below. See _nvfp4_scale_strides. ++ Int32(k_sf_page_stride), ++ Int32(k_sf_head_stride), ++ Int32(v_sf_page_stride), ++ Int32(v_sf_head_stride), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) +@@ -1983,8 +2271,8 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + _compile_cache[key]( + k_kernel, + v_kernel, +- k_scale_128x4, +- v_scale_128x4, ++ k_scale, ++ v_scale, + k_global_scale_kernel, + v_global_scale_kernel, + k2q_q_indices, +@@ -2007,5 +2295,11 @@ def _call_sparse_forward_sm100_csr_varlen_nvfp4_kv( + head_kv, + max_seqlen_q, + work_capacity, ++ # Scale-factor page/head strides, in BYTES. Must match the order ++ # in the cute.compile() call above exactly. ++ k_sf_page_stride, ++ k_sf_head_stride, ++ v_sf_page_stride, ++ v_sf_head_stride, + ) + return schedule +diff --git a/python/fmha_sm100/cute/quantize.py b/python/fmha_sm100/cute/quantize.py +index 4719a48..65e51be 100644 +--- a/python/fmha_sm100/cute/quantize.py ++++ b/python/fmha_sm100/cute/quantize.py +@@ -1,18 +1,68 @@ + # SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax + # SPDX-License-Identifier: MIT - import quack.activation +-"""Transformer Engine NVFP4 quantization helper. ++"""NVFP4 quantization helpers for the KVFP4 sparse attention kernel. -+from . import cuda_toolchain + This file is intended as a customer-facing example for preparing KV tensors + for the KVFP4 attention kernel: + - BF16/FP16 K/V input +- - packed E2M1 FP4 data from Transformer Engine +- - E4M3 block scales in cuBLAS/cuDNN 128x4 tiled layout ++ - packed E2M1 FP4 data (Transformer Engine, or a dependency-free PyTorch ++ fallback) ++ - E4M3 block scales in **vLLM's** scale-factor byte order + - one FP32 tensor/global scale per tensor + - _MIXER_ATTRS = ("__vec_size__",) - -+# Inline-PTX capability gates. -+# -+# These instructions are not available in every CUDA toolkit, so each has a -+# portable fallback below. The gate must reflect the toolkit that will actually -+# assemble the PTX -- NOT `cutlass.CUDA_VERSION`, which is the CUDA version the -+# CuTe DSL wheel was *built* against. When a DSL built against a newer CUDA is -+# installed beside an older toolkit, trusting `cutlass.CUDA_VERSION` emits PTX -+# that ptxas cannot parse, and libNVVM reports only "NVVM backend compilation -+# failed" with no mention of the instruction. -+_PTX_PROBE_SCALED_E4M3_MUL = " mul.e4m3x4.e2m1x4.e4m3x4.satfinite %r2, %r3, %r4;" -+_PTX_PROBE_F16X2_FROM_E2M1 = " cvt.rn.f16x2.e2m1x2 %r2, %b1;" -+_PTX_PROBE_BF16X2_FROM_E2M1 = " cvt.rn.bf16x2.e2m1x2 %r2, %b1;" ++Scale-factor layouts ++-------------------- ++There is exactly one supported layout *pair*, matching what vLLM's NVFP4 ++KV-cache store kernel writes (``csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu``), ++so MSA reads that cache with no repack pass: + -+# Used only when ptxas cannot be run at all, so the gate still has an answer. -+_PTX_PROBE_FALLBACK_MIN_CUDA = (13, 3) ++=============== ========================================= =============== ++layout byte offset inside a scale region used for ++=============== ========================================= =============== ++``"linear"`` ``t*S + s`` K ++``"swizzle4x4"`` ``(t//4)*(4*S) + 4*s + (t%4)`` V ++=============== ========================================= =============== + ++``t`` is the token index inside the region, ``s`` the scale column, and ++``S = head_dim // 16`` the number of scale columns. ``S`` must be a multiple ++of 4 and, for ``"swizzle4x4"``, the region must hold a whole number of token ++quads. The cuBLAS/cuDNN **128x4** layout this module used to emit is deleted: ++MSA uses no block-scaled MMA, so it bought nothing, and it did not match vLLM. + -+def _toolchain_supports(probe_body: str) -> bool: -+ # CuTeDSL lowers with the NVPTX compiler embedded in its wheel, then may -+ # coexist with a newer external ptxas. Both must support the instruction: -+ # checking only /usr/local/cuda/bin/ptxas can otherwise accept an opcode -+ # that the embedded compiler rejects while serializing the GPU module. -+ from cutlass import CUDA_VERSION ++Physical containers ++------------------- ++A *region* is exactly ``region_tokens * S`` bytes -- there is no row or column ++padding. The container returned by :func:`quantize_bf16_to_nvfp4` has the ++input's shape with the last dimension replaced by ``S``: + -+ if (CUDA_VERSION.major, -+ CUDA_VERSION.minor) < _PTX_PROBE_FALLBACK_MIN_CUDA: -+ return False -+ supported = cuda_toolchain.ptxas_supports(probe_body) -+ if supported is not None: -+ return supported -+ return True ++* **paged** input ``[num_pages, Hkv, page_size, D]`` ++ -> container ``[num_pages, Hkv, page_size, S]``. ++ One region per ``(page, head)``, ``region_tokens = page_size``. This is ++ byte-for-byte the view ``vllm.utils.torch_utils.nvfp4_split_data_scale`` ++ hands back (modulo its ``float8_e4m3fn`` dtype; see the note in ++ ``interface.py``). + - # Obtained from sollya: - # fpminimax(exp(x * log(2.0)), 1, [|1,24...|],[0;1],relative); - POLY_EX2 = { -@@ -153,7 +187,7 @@ def make_tiled_copy_B( - ++* **flat varlen** input ``[total_k, Hkv, D]`` (or ``[total_k, D]``, Hkv = 1) ++ -> container ``[total_k, Hkv, S]``. For ``"linear"`` one region per ++ ``(token, head)`` (``region_tokens = 1``, so the container is also ++ *logically* indexed by ``(token, head, s)``). For ``"swizzle4x4"`` one ++ region per ``(token_quad, head)``, ``region_tokens = 4``, regions ordered ++ quad-major then head; the container is then only a **byte container** -- ++ element ``(t, h, s)`` of the tensor is not the scale of token ``t``. ++ Byte address of the scale for ``(t, h, s)``, with ++ ``page_stride = stride(0) = Hkv*S`` and ``head_stride = stride(1) = S``:: ++ ++ linear : t*page_stride + h*head_stride + s ++ swizzle4x4 : (t & ~3)*page_stride + 4*h*head_stride + 4*s + (t & 3) ++ ++ The flat swizzle has no production producer (vLLM is paged only); it exists ++ because flat test inputs are far cheaper to build than paged ones. + """ - def mma_make_fragment_A( -- smem: cute.Tensor, thr_mma: cute.core.ThrMma, swapAB: cutlass.Constexpr[bool] = False -+ smem: cute.Tensor, thr_mma: cute.ThrMma, swapAB: cutlass.Constexpr[bool] = False - ) -> cute.Tensor: - if const_expr(swapAB): - return mma_make_fragment_B(smem, thr_mma) -@@ -162,7 +196,7 @@ def mma_make_fragment_A( + from __future__ import annotations ++import os + from dataclasses import dataclass + from typing import Tuple - def mma_make_fragment_B( -- smem: cute.Tensor, thr_mma: cute.core.ThrMma, swapAB: cutlass.Constexpr[bool] = False -+ smem: cute.Tensor, thr_mma: cute.ThrMma, swapAB: cutlass.Constexpr[bool] = False - ) -> cute.Tensor: - if const_expr(swapAB): - return mma_make_fragment_A(smem, thr_mma) -@@ -625,6 +659,59 @@ def cvt_fp4x8_e2m1_f16x8( - ) -> Tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32]: - """Convert four packed E2M1 bytes into four packed f16x2 registers.""" +@@ -23,6 +73,10 @@ NVFP4_BLOCK_SIZE = 16 + NVFP4_FP4_MAX = 6.0 + NVFP4_FP8_E4M3_MAX = 448.0 -+ if not _toolchain_supports(_PTX_PROBE_F16X2_FROM_E2M1): -+ out = llvm.inline_asm( -+ llvm.StructType.get_literal( -+ [T.i32(), T.i32(), T.i32(), T.i32()]), -+ [cutlass.Int32(src).ir_value(loc=loc, ip=ip)], -+ "{\n\t" -+ ".reg .b32 x, sel, hi, signs, tmp, zero, lut0, lut1;\n\t" -+ "mov.b32 zero, 0;\n\t" -+ # Positive E2M1 values 0, .5, 1, 1.5, 2, 3, 4, 6 expressed as -+ # the high byte of their exact FP16 representation. -+ "mov.b32 lut0, 0x3e3c3800;\n\t" -+ "mov.b32 lut1, 0x46444240;\n\t" -+ "mov.b32 x, $4;\n\t" -+ "and.b32 sel, x, 0x00007777;\n\t" -+ "prmt.b32 hi, lut0, lut1, sel;\n\t" -+ "and.b32 signs, x, 0x00000088;\n\t" -+ "mul.lo.u32 signs, signs, 0x00000110;\n\t" -+ "and.b32 signs, signs, 0x00008080;\n\t" -+ "shr.u32 tmp, x, 8;\n\t" -+ "and.b32 tmp, tmp, 0x00000088;\n\t" -+ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" -+ "and.b32 tmp, tmp, 0x00008080;\n\t" -+ "shl.b32 tmp, tmp, 16;\n\t" -+ "or.b32 signs, signs, tmp;\n\t" -+ "or.b32 hi, hi, signs;\n\t" -+ "prmt.b32 $0, zero, hi, 0x5040;\n\t" -+ "prmt.b32 $1, zero, hi, 0x7060;\n\t" -+ "shr.u32 x, $4, 16;\n\t" -+ "and.b32 sel, x, 0x00007777;\n\t" -+ "prmt.b32 hi, lut0, lut1, sel;\n\t" -+ "and.b32 signs, x, 0x00000088;\n\t" -+ "mul.lo.u32 signs, signs, 0x00000110;\n\t" -+ "and.b32 signs, signs, 0x00008080;\n\t" -+ "shr.u32 tmp, x, 8;\n\t" -+ "and.b32 tmp, tmp, 0x00000088;\n\t" -+ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" -+ "and.b32 tmp, tmp, 0x00008080;\n\t" -+ "shl.b32 tmp, tmp, 16;\n\t" -+ "or.b32 signs, signs, tmp;\n\t" -+ "or.b32 hi, hi, signs;\n\t" -+ "prmt.b32 $2, zero, hi, 0x5040;\n\t" -+ "prmt.b32 $3, zero, hi, 0x7060;\n\t" -+ "}\n", -+ "=r,=r,=r,=r,r", -+ has_side_effects=False, -+ is_align_stack=False, -+ asm_dialect=llvm.AsmDialect.AD_ATT, -+ ) -+ return tuple( -+ cutlass.Int32( -+ llvm.extractvalue(T.i32(), out, [i], loc=loc, ip=ip)) -+ for i in range(4)) ++#: The only supported scale-factor layouts. ``"linear"`` for K, ++#: ``"swizzle4x4"`` for V -- see the module docstring. ++NVFP4_SCALE_LAYOUTS: Tuple[str, ...] = ("linear", "swizzle4x4") + - out = llvm.inline_asm( - llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), - [cutlass.Int32(src).ir_value(loc=loc, ip=ip)], -@@ -657,9 +744,7 @@ def cvt_fp4x8_e2m1_bf16x8( - ) -> Tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32]: - """Convert four packed E2M1 bytes into four packed bf16x2 registers.""" -- from cutlass import CUDA_VERSION -- -- if CUDA_VERSION.major > 13 or (CUDA_VERSION.major == 13 and CUDA_VERSION.minor >= 2): -+ if _toolchain_supports(_PTX_PROBE_BF16X2_FROM_E2M1): - out = llvm.inline_asm( - llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), - [cutlass.Int32(src).ir_value(loc=loc, ip=ip)], -@@ -697,15 +782,18 @@ def cvt_fp4x8_e2m1_bf16x8( - def cvt_fp4x8_e2m1_scaled_e4m3x8( - src: cutlass.Int32, - scale_e4m3: cutlass.Int32, -+ global_scale: Optional[Float32] = None, - *, - loc=None, - ip=None, - ) -> Tuple[cutlass.Int32, cutlass.Int32]: -- """Scale eight packed E2M1 values by one E4M3 byte and convert to E4M3.""" -+ """Reconstruct eight NVFP4 values before rounding them to E4M3. + @dataclass(frozen=True) + class Nvfp4QuantizedTensor: +@@ -31,115 +85,294 @@ class Nvfp4QuantizedTensor: + Attributes + ---------- + data : torch.Tensor +- Packed E2M1 FP4 data from Transformer Engine. The last dimension is +- half of the original logical last dimension because each byte stores +- two FP4 values. +- scale_128x4 : torch.Tensor +- E4M3 block scales in cuBLAS/cuDNN 128x4 tiled rowwise storage. ++ Packed E2M1 FP4 data. The last dimension is half of the original ++ logical last dimension because each byte stores two FP4 values. ++ scale : torch.Tensor ++ E4M3 block scales as uint8, in the physical container described in the ++ module docstring (input shape with the last dim replaced by ++ ``head_dim // 16``). + global_scale : torch.Tensor + FP32 tensor/global dequant scale. + logical_scale_shape : tuple[int, int] +- Logical 2D scale shape ``(rows, cols)`` before 128x4 swizzling. ++ Logical 2D scale shape ``(rows, cols)`` before packing, where ``rows`` ++ is ``prod(original_shape[:-1])``. + original_shape : tuple[int, ...] + Original BF16/FP16 tensor shape before quantization. ++ layout : str ++ Scale-factor layout of ``scale``: ``"linear"`` or ``"swizzle4x4"``. + """ -- from cutlass import CUDA_VERSION -+ The block-scaled intermediate can reach 6 * 448. Applying the FP32 -+ global scale after an E4M3 conversion would preserve its saturation error. + data: torch.Tensor +- scale_128x4: torch.Tensor ++ scale: torch.Tensor + global_scale: torch.Tensor + logical_scale_shape: Tuple[int, int] + original_shape: Tuple[int, ...] ++ layout: str ++ ++ ++def nvfp4_scale_linear_offset(t, s, S): ++ """Byte offset of scale column ``s`` of token ``t`` in a linear region. ++ ++ ``off = t*S + s``. Matches vLLM's K scale store ++ (``nvfp4_kv_cache_kernels.cu:162``). ++ ++ ``t`` and ``s`` may be Python ints or integer tensors (broadcasting). + """ ++ ++ return t * S + s -- if CUDA_VERSION.major > 13 or (CUDA_VERSION.major == 13 and CUDA_VERSION.minor >= 2): -+ if global_scale is None and _toolchain_supports(_PTX_PROBE_SCALED_E4M3_MUL): - out = llvm.inline_asm( - llvm.StructType.get_literal([T.i32(), T.i32()]), - [ -@@ -731,44 +819,91 @@ def cvt_fp4x8_e2m1_scaled_e4m3x8( - out1 = cutlass.Int32(llvm.extractvalue(T.i32(), out, [1], loc=loc, ip=ip)) - return out0, out1 -+ # Keep the E4M3 pack in the established operand-constrained helper below. -+ # CUDA 13.1's embedded NVPTX compiler rejects the equivalent conversion -+ # when its E4M3x2 destination is a local .b16 register in this larger asm. - out = llvm.inline_asm( -- llvm.StructType.get_literal([T.i32(), T.i32()]), -+ llvm.StructType.get_literal([T.f32()] * 8), - [ - cutlass.Int32(src).ir_value(loc=loc, ip=ip), - cutlass.Int32(scale_e4m3).ir_value(loc=loc, ip=ip), - ], - "{\n\t" -- ".reg .b32 sf_bytes, sf_f16x2;\n\t" -- ".reg .b16 sf_pair, e0, e1, e2, e3;\n\t" -- ".reg .b8 byte0, byte1, byte2, byte3;\n\t" -+ ".reg .b32 sf_bytes, sf_f16x2, x, sel, hi, signs, tmp, zero, lut0, lut1;\n\t" -+ ".reg .b16 sf_pair;\n\t" -+ ".reg .b16 h0_lo, h0_hi, h1_lo, h1_hi, h2_lo, h2_hi, h3_lo, h3_hi;\n\t" - ".reg .b32 h0, h1, h2, h3;\n\t" -- "prmt.b32 sf_bytes, $3, 0, 0;\n\t" -+ "prmt.b32 sf_bytes, $9, 0, 0;\n\t" - "mov.b32 {sf_pair, _}, sf_bytes;\n\t" - "cvt.rn.f16x2.e4m3x2 sf_f16x2, sf_pair;\n\t" -- "mov.b32 {byte0, byte1, byte2, byte3}, $2;\n\t" -- "cvt.rn.f16x2.e2m1x2 h0, byte0;\n\t" -- "cvt.rn.f16x2.e2m1x2 h1, byte1;\n\t" -- "cvt.rn.f16x2.e2m1x2 h2, byte2;\n\t" -- "cvt.rn.f16x2.e2m1x2 h3, byte3;\n\t" -+ # Decode four E2M1 nibbles at a time through a byte lookup. The -+ # positive FP16 high bytes are 00,38,3c,3e,40,42,44,46; the sign bit -+ # is expanded from each nibble into the corresponding byte's MSB. -+ "mov.b32 zero, 0;\n\t" -+ "mov.b32 lut0, 0x3e3c3800;\n\t" -+ "mov.b32 lut1, 0x46444240;\n\t" -+ "mov.b32 x, $8;\n\t" -+ "and.b32 sel, x, 0x00007777;\n\t" -+ "prmt.b32 hi, lut0, lut1, sel;\n\t" -+ "and.b32 signs, x, 0x00000088;\n\t" -+ "mul.lo.u32 signs, signs, 0x00000110;\n\t" -+ "and.b32 signs, signs, 0x00008080;\n\t" -+ "shr.u32 tmp, x, 8;\n\t" -+ "and.b32 tmp, tmp, 0x00000088;\n\t" -+ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" -+ "and.b32 tmp, tmp, 0x00008080;\n\t" -+ "shl.b32 tmp, tmp, 16;\n\t" -+ "or.b32 signs, signs, tmp;\n\t" -+ "or.b32 hi, hi, signs;\n\t" -+ "prmt.b32 h0, zero, hi, 0x5040;\n\t" -+ "prmt.b32 h1, zero, hi, 0x7060;\n\t" -+ "shr.u32 x, $8, 16;\n\t" -+ "and.b32 sel, x, 0x00007777;\n\t" -+ "prmt.b32 hi, lut0, lut1, sel;\n\t" -+ "and.b32 signs, x, 0x00000088;\n\t" -+ "mul.lo.u32 signs, signs, 0x00000110;\n\t" -+ "and.b32 signs, signs, 0x00008080;\n\t" -+ "shr.u32 tmp, x, 8;\n\t" -+ "and.b32 tmp, tmp, 0x00000088;\n\t" -+ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" -+ "and.b32 tmp, tmp, 0x00008080;\n\t" -+ "shl.b32 tmp, tmp, 16;\n\t" -+ "or.b32 signs, signs, tmp;\n\t" -+ "or.b32 hi, hi, signs;\n\t" -+ "prmt.b32 h2, zero, hi, 0x5040;\n\t" -+ "prmt.b32 h3, zero, hi, 0x7060;\n\t" - "mul.rn.f16x2 h0, h0, sf_f16x2;\n\t" - "mul.rn.f16x2 h1, h1, sf_f16x2;\n\t" - "mul.rn.f16x2 h2, h2, sf_f16x2;\n\t" - "mul.rn.f16x2 h3, h3, sf_f16x2;\n\t" -- "cvt.rn.satfinite.e4m3x2.f16x2 e0, h0;\n\t" -- "cvt.rn.satfinite.e4m3x2.f16x2 e1, h1;\n\t" -- "cvt.rn.satfinite.e4m3x2.f16x2 e2, h2;\n\t" -- "cvt.rn.satfinite.e4m3x2.f16x2 e3, h3;\n\t" -- "mov.b32 $0, {e0, e1};\n\t" -- "mov.b32 $1, {e2, e3};\n\t" -+ "mov.b32 {h0_lo, h0_hi}, h0;\n\t" -+ "mov.b32 {h1_lo, h1_hi}, h1;\n\t" -+ "mov.b32 {h2_lo, h2_hi}, h2;\n\t" -+ "mov.b32 {h3_lo, h3_hi}, h3;\n\t" -+ "cvt.f32.f16 $0, h0_lo;\n\t" -+ "cvt.f32.f16 $1, h0_hi;\n\t" -+ "cvt.f32.f16 $2, h1_lo;\n\t" -+ "cvt.f32.f16 $3, h1_hi;\n\t" -+ "cvt.f32.f16 $4, h2_lo;\n\t" -+ "cvt.f32.f16 $5, h2_hi;\n\t" -+ "cvt.f32.f16 $6, h3_lo;\n\t" -+ "cvt.f32.f16 $7, h3_hi;\n\t" - "}\n", -- "=r,=r,r,r", -+ "=f,=f,=f,=f,=f,=f,=f,=f,r,r", - has_side_effects=False, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - ) -- out0 = cutlass.Int32(llvm.extractvalue(T.i32(), out, [0], loc=loc, ip=ip)) -- out1 = cutlass.Int32(llvm.extractvalue(T.i32(), out, [1], loc=loc, ip=ip)) -- return out0, out1 -+ values = [ -+ Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) -+ for i in range(8) -+ ] -+ if global_scale is not None: -+ values = [value * global_scale for value in values] -+ return ( -+ cvt_fp8x4_e4m3_f32(*values[:4], loc=loc, ip=ip), -+ cvt_fp8x4_e4m3_f32(*values[4:], loc=loc, ip=ip), -+ ) - - - @dsl_user_op -diff --git a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py -index f5950f3..caad594 100644 ---- a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py -+++ b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py -@@ -1939,8 +1939,8 @@ class SparseAttentionForwardSm100: - self, - tiled_mma_qk: cute.TiledMma, - tiled_mma_pv: cute.TiledMma, -- thr0_qk: cute.core.ThrMma, -- thr0_pv: cute.core.ThrMma, -+ thr0_qk: cute.ThrMma, -+ thr0_pv: cute.ThrMma, - tStS: cute.Tensor, - tOrP: cute.Tensor, - sK: cute.Tensor, -diff --git a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py -index ba930a6..f2d7fb3 100644 ---- a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py -+++ b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py -@@ -9,7 +9,8 @@ forward contract: - - varlen Q metadata via `cu_seqlens_q` - - BF16 Q - - packed NVFP4 K/V data --- E4M3 per-1x16 K/V scales in cuBLAS/cuDNN 128x4 tiled layout -+- E4M3 per-1x16 K/V scales in vLLM's byte order: K linear, V 4x4 token-quad -+ swizzled, addressed through host-supplied per-page / per-head byte strides - - FP32 per-tensor K/V global scales - """ - -@@ -297,8 +298,8 @@ class SparseAttentionForwardNvfp4KvSm100: - self, - mK: cute.Tensor, # packed NVFP4: flat [total_k, head_kv, dim/2] or paged [page, head_kv, token, dim/2] - mV: cute.Tensor, # packed NVFP4: flat [total_k, head_kv, dim/2] or paged [page, head_kv, token, dim/2] -- mKScale: cute.Tensor, # E4M3 uint8, 128x4 tiled over flattened K rows and dim/16 cols -- mVScale: cute.Tensor, # E4M3 uint8, 128x4 tiled over flattened V rows and dim/16 cols -+ mKScale: cute.Tensor, # E4M3 uint8 K block scales, linear inside each (page, head) region -+ mVScale: cute.Tensor, # E4M3 uint8 V block scales, 4x4 token-quad swizzled inside the region - mKGlobalScale: Optional[cute.Tensor], # optional FP32 tensor/global dequant scale - mVGlobalScale: Optional[cute.Tensor], # optional FP32 tensor/global dequant scale - mK2qIndices: cute.Tensor, # csr payload: [head_kv, nnz] -@@ -321,6 +322,17 @@ class SparseAttentionForwardNvfp4KvSm100: - num_heads_kv: Int32, - seq_len_q: Int32, - work_capacity: Int32, -+ # Block-scale region strides, in BYTES. For the paged cache these are -+ # the stride of a whole vLLM page (data bytes included, 73728 B at M3 -+ # geometry) and the stride of one KV head inside that page. They are -+ # Int32 kernel arguments; every product built from them is Int64 -+ # (see `_scale_region_base`). Ignored when `paged_kv=False`, where the -+ # region is derived from `num_heads_kv` instead -- see -+ # `_scale_region_base_flat`. -+ k_sf_page_stride: Int32, -+ k_sf_head_stride: Int32, -+ v_sf_page_stride: Int32, -+ v_sf_head_stride: Int32, - stream=None, - ): - self.q_dtype = mQ_flat.element_type -@@ -358,9 +370,11 @@ class SparseAttentionForwardNvfp4KvSm100: - not in [Float32, cutlass.BFloat16, cutlass.Float16, cutlass.Float8E4M3FN] - ): - raise TypeError(f"Unsupported O_partial dtype: {self.o_dtype}") -- mK, mV, mKScale, mVScale = [ -- assume_tensor_aligned(t) for t in (mK, mV, mKScale, mVScale) -- ] -+ # Only the packed FP4 data tensors may claim 128-bit aligned strides: -+ # the block scales' 8 B token stride would break that promise. The -+ # scale readers therefore do raw pointer arithmetic off -+ # `scale.iterator` and never index the tensor -- keep them that way. -+ mK, mV = [assume_tensor_aligned(t) for t in (mK, mV)] +-def _round_up(x: int, multiple: int) -> int: +- return ((int(x) + multiple - 1) // multiple) * multiple ++def nvfp4_scale_swizzle4x4_offset(t, s, S): ++ """Byte offset of scale column ``s`` of token ``t`` in a 4x4-swizzled region. - if const_expr(not self.paged_kv): - # Flat varlen K/V: -@@ -588,6 +602,8 @@ class SparseAttentionForwardNvfp4KvSm100: - tiled_mma_qk, tiled_mma_pv, - k_fp4_tma_bytes, v_fp4_tma_bytes, q_tma_bytes, q_subtile_bytes, - num_kv_blocks, num_heads_kv, seq_len_q, work_capacity, -+ k_sf_page_stride, k_sf_head_stride, -+ v_sf_page_stride, v_sf_head_stride, - ).launch( - grid=(num_ctas,), - block=[self.threads_per_cta, 1, 1], -@@ -653,6 +669,11 @@ class SparseAttentionForwardNvfp4KvSm100: - num_heads_kv: Int32, - seq_len_q: Int32, - work_capacity: Int32, -+ # Block-scale region strides, in bytes (see `__call__`). -+ k_sf_page_stride: Int32, -+ k_sf_head_stride: Int32, -+ v_sf_page_stride: Int32, -+ v_sf_head_stride: Int32, - ): - # ------------------------------------------------------------------ - # Thread / warp identity, CTA coordinate -@@ -1085,6 +1106,8 @@ class SparseAttentionForwardNvfp4KvSm100: - head_kv_idx, kv_block_idx_softmax, - sRowMeta[6], - num_heads_kv, -+ k_sf_page_stride, -+ k_sf_head_stride, - ) - tmem.wait_for_alloc() - tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype) -@@ -1152,6 +1175,8 @@ class SparseAttentionForwardNvfp4KvSm100: - head_kv_idx, kv_block_idx_softmax, - sRowMeta[6], - num_heads_kv, -+ v_sf_page_stride, -+ v_sf_head_stride, - ) - tmem.wait_for_alloc() - tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype) -@@ -1193,66 +1218,147 @@ class SparseAttentionForwardNvfp4KvSm100: - # Warp-specialized helpers - # ------------------------------------------------------------------ ++ ``off = (t//4)*(4*S) + 4*s + (t%4)`` -- i.e. a plain row-major ++ ``[T/4][S][4]`` array indexed by ``(t//4, s, t%4)``. Matches vLLM's V ++ scale store (``nvfp4_kv_cache_kernels.cu:25-39``, ``:164-171``); the two ++ forms are algebraically identical for every ``S`` divisible by 4. -+ # ------------------------------------------------------------------ -+ # NVFP4 block-scale (scale-factor) addressing -+ # -+ # One unconditional layout pair -- the byte order vLLM's NVFP4 KV store -+ # kernel already writes (csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu). -+ # S = D/16 scale columns per token, `t` the token index inside a -+ # (page, head) region: -+ # -+ # K, linear (:162) off = t*S + s -+ # V, 4x4 swizzle (:25-39) off = (t>>2)*(4*S) + (s<<2) + (t&3) -+ # -+ # The old cuBLAS/cuDNN 128x4 tiling is DELETED: it is the block-scaled -+ # tcgen05 MMA operand format and this kernel runs no block-scaled MMA. -+ # ------------------------------------------------------------------ +-def nvfp4_scale_128x4_offset( +- row: torch.Tensor, +- col: torch.Tensor, ++ ``t`` and ``s`` may be Python ints or integer tensors (broadcasting). ++ """ + - @cute.jit -- def _scale_128x4_offset( -+ def _scale_region_base( - self, -- row: Int32, -- col: Int32, -- scale_cols: cutlass.Constexpr[int], -- ) -> Int32: -- tiles_n: cutlass.Constexpr[int] = (scale_cols + 3) // 4 -- tile_m = row // Int32(128) -- tile_n = col // Int32(4) -- outer = row % Int32(128) -- inner = col % Int32(4) -+ page_idx: Int32, -+ head_kv_idx: Int32, -+ sf_page_stride: Int32, -+ sf_head_stride: Int32, -+ ) -> Int64: -+ """Byte offset of one (page, head) scale region from the tensor base. ++ return (t // 4) * (4 * S) + 4 * s + (t % 4) + -+ MUST be Int64: `sf_page_stride` spans a WHOLE vLLM page, data bytes -+ included, so page_idx * stride overflows Int32 on a large KV cache -+ (the strides themselves fit, only the product does not). -+ """ - return ( -- (tile_m * Int32(tiles_n) + tile_n) * Int32(512) -- + (outer % Int32(32)) * Int32(16) -- + (outer // Int32(32)) * Int32(4) -- + inner -+ Int64(page_idx) * Int64(sf_page_stride) -+ + Int64(head_kv_idx) * Int64(sf_head_stride) - ) - - @cute.jit -- def _load_scale_bf16x2( -+ def _scale_region_base_flat( - self, -- scale: cute.Tensor, -- logical_row: Int32, -- scale_col: Int32, -- ) -> Int32: -- scale_offset = self._scale_128x4_offset( -- logical_row, -- scale_col, -- self.head_dim // 16, -+ token_global: Int32, -+ head_kv_idx: Int32, -+ num_heads_kv: Int32, -+ tokens_per_region: cutlass.Constexpr[int], -+ ) -> Int64: -+ """Region base for flat (non-paged) varlen KV; test path only, not an ABI. + -+ base = (token_global // R) * (Hkv * R * S) + head * (R * S) ++_SCALE_OFFSET_FNS = { ++ "linear": nvfp4_scale_linear_offset, ++ "swizzle4x4": nvfp4_scale_swizzle4x4_offset, ++} + -+ R = 1 for K, R = 4 for V (the 4x4 swizzle needs a whole token quad; -+ requires total_k % 4 == 0). Host strides are deliberately not -+ consulted -- nothing on the host owns this geometry. -+ """ -+ S: cutlass.Constexpr[int] = self.head_dim // 16 -+ R: cutlass.Constexpr[int] = int(tokens_per_region) -+ assert R > 0 and (R & (R - 1)) == 0, "tokens_per_region must be a power of two" -+ shift: cutlass.Constexpr[int] = R.bit_length() - 1 -+ region_idx = token_global >> Int32(shift) -+ return Int64(region_idx * num_heads_kv + head_kv_idx) * Int64(R * S) + -+ @cute.jit -+ def _scale_offset_linear(self, token: Int32, scale_col: Int32) -> Int32: -+ """K: `t*S + s`, byte offset inside a (page, head) region.""" -+ S: cutlass.Constexpr[int] = self.head_dim // 16 -+ return token * Int32(S) + scale_col ++def _check_layout(layout: str) -> str: ++ layout = str(layout) ++ if layout not in NVFP4_SCALE_LAYOUTS: ++ raise ValueError( ++ f"layout must be one of {list(NVFP4_SCALE_LAYOUTS)}, got {layout!r}" ++ ) ++ return layout + -+ @cute.jit -+ def _scale_offset_swizzle4x4(self, token: Int32, scale_col: Int32) -> Int32: -+ """V: `(t>>2)*(4*S) + (s<<2) + (t&3)`, byte offset inside a region.""" -+ S: cutlass.Constexpr[int] = self.head_dim // 16 -+ return ( -+ (token >> Int32(2)) * Int32(4 * S) -+ + (scale_col << Int32(2)) -+ + (token & Int32(3)) - ) + -+ @cute.jit -+ def _load_scale_byte(self, scale: cute.Tensor, byte_offset: Int64) -> Int32: -+ """One E4M3 block-scale byte, by raw pointer arithmetic. ++def _region_offsets(page_size: int, scale_cols: int, layout: str, device) -> torch.Tensor: ++ """Flat physical offsets for one region, in logical ``(t, s)`` row-major order.""" + -+ Must not touch `scale.layout`: the 8 B token stride breaks the 16 B -+ alignment promise, so indexing the tensor would be live UB. -+ """ - scale_ptr = cute.make_ptr( - cutlass.Uint8, -- scale.iterator.toint() + Int64(scale_offset), -+ scale.iterator.toint() + byte_offset, - mem_space=scale.iterator.memspace, - assumed_align=1, - ) -- scale_byte = cute.make_tensor(scale_ptr, cute.make_layout(1))[0] -- return utils.cvt_fp8_e4m3_to_bf16x2_replicated(cutlass.Int32(scale_byte)) -+ return cutlass.Int32(cute.make_tensor(scale_ptr, cute.make_layout(1))[0]) - - @cute.jit -- def _load_scale_e4m3_u8( -+ def _load_scale_bf16x2_linear( - self, - scale: cute.Tensor, -- logical_row: Int32, -+ region_base: Int64, -+ token: Int32, - scale_col: Int32, - ) -> Int32: -- scale_offset = self._scale_128x4_offset( -- logical_row, -- scale_col, -- self.head_dim // 16, -+ scale_byte = self._load_scale_byte( -+ scale, -+ region_base + Int64(self._scale_offset_linear(token, scale_col)), - ) -- scale_ptr = cute.make_ptr( -- cutlass.Uint8, -- scale.iterator.toint() + Int64(scale_offset), -- mem_space=scale.iterator.memspace, -- assumed_align=1, -+ return utils.cvt_fp8_e4m3_to_bf16x2_replicated(scale_byte) ++ t = torch.arange(page_size, device=device, dtype=torch.int64)[:, None] ++ s = torch.arange(scale_cols, device=device, dtype=torch.int64)[None, :] ++ return _SCALE_OFFSET_FNS[layout](t, s, scale_cols).reshape(-1) + -+ @cute.jit -+ def _load_scale_bf16x2_swizzle4x4( -+ self, -+ scale: cute.Tensor, -+ region_base: Int64, -+ token: Int32, -+ scale_col: Int32, -+ ) -> Int32: -+ scale_byte = self._load_scale_byte( -+ scale, -+ region_base + Int64(self._scale_offset_swizzle4x4(token, scale_col)), ++ ++def _validate_region(page_size: int, scale_cols: int, layout: str) -> None: ++ if page_size <= 0: ++ raise ValueError(f"page_size must be positive, got {page_size}") ++ if scale_cols <= 0 or scale_cols % 4 != 0: ++ raise ValueError( ++ "scale_cols must be a positive multiple of 4 (the 4x4 swizzle " ++ f"derivation assumes S % 4 == 0), got {scale_cols}" ++ ) ++ if layout == "swizzle4x4" and page_size % 4 != 0: ++ raise ValueError( ++ "layout='swizzle4x4' tiles tokens in quads, so the region must hold " ++ f"a whole number of quads; got page_size={page_size}" + ) -+ return utils.cvt_fp8_e4m3_to_bf16x2_replicated(scale_byte) + -+ @cute.jit -+ def _load_scale_e4m3_u8_linear( -+ self, -+ scale: cute.Tensor, -+ region_base: Int64, -+ token: Int32, -+ scale_col: Int32, -+ ) -> Int32: -+ return self._load_scale_byte( -+ scale, -+ region_base + Int64(self._scale_offset_linear(token, scale_col)), ++ ++def pack_nvfp4_scale( ++ scale: torch.Tensor, ++ *, ++ page_size: int, + scale_cols: int, ++ layout: str, + ) -> torch.Tensor: +- """Return flat offsets for cuBLAS/cuDNN 128x4 rowwise scale storage. ++ """Pack logical per-region block scales into physical scale-factor order. + + Parameters + ---------- +- row : torch.Tensor +- Logical row indices. +- col : torch.Tensor +- Logical scale-column indices. ++ scale : torch.Tensor ++ Logical scales with shape ``[n_regions, page_size, scale_cols]``. ++ Reinterpreted as uint8 if it is not already uint8. ++ page_size : int ++ Tokens per region. Must be a multiple of 4 for ``"swizzle4x4"``. + scale_cols : int +- Logical number of scale columns before padding to a multiple of 4. ++ Scale columns per token, ``S = head_dim // 16``. Must be a multiple ++ of 4. ++ layout : str ++ ``"linear"`` or ``"swizzle4x4"``. + + Returns + ------- + torch.Tensor +- Flat offsets into the padded 128x4 tiled storage. ++ Contiguous uint8 tensor with the same shape, whose *bytes* are the ++ packed region layout: region ``r`` occupies exactly ++ ``page_size * scale_cols`` contiguous bytes (**no padding** -- unlike ++ the deleted 128x4 layout, which padded to ++ ``round_up(rows,128) x round_up(cols,4)``), and the scale of token ++ ``t``, column ``s`` sits at byte ``offset_(t, s, scale_cols)`` ++ inside it. ++ ++ ``"linear"`` is the identity: a row-major ``[n_regions, page_size, ++ scale_cols]`` array already *is* the linear layout. + """ + +- tiles_n = _round_up(scale_cols, 4) // 4 +- tile_m = row // 128 +- tile_n = col // 4 +- outer = row % 128 +- inner = col % 4 +- return ( +- (tile_m * tiles_n + tile_n) * 512 +- + (outer % 32) * 16 +- + (outer // 32) * 4 +- + inner +- ) ++ layout = _check_layout(layout) ++ page_size = int(page_size) ++ scale_cols = int(scale_cols) ++ _validate_region(page_size, scale_cols, layout) + ++ if scale.ndim != 3: ++ raise ValueError( ++ "scale must be rank-3 [n_regions, page_size, scale_cols], got shape " ++ f"{tuple(scale.shape)}" ++ ) ++ if int(scale.shape[1]) != page_size or int(scale.shape[2]) != scale_cols: ++ raise ValueError( ++ f"scale shape {tuple(scale.shape)} does not match " ++ f"page_size={page_size}, scale_cols={scale_cols}" + ) ++ if scale.dtype is not torch.uint8: ++ scale = scale.view(torch.uint8) + -+ @cute.jit -+ def _load_scale_e4m3_u8_swizzle4x4( -+ self, -+ scale: cute.Tensor, -+ region_base: Int64, -+ token: Int32, -+ scale_col: Int32, -+ ) -> Int32: -+ return self._load_scale_byte( -+ scale, -+ region_base + Int64(self._scale_offset_swizzle4x4(token, scale_col)), - ) -- scale_byte = cute.make_tensor(scale_ptr, cute.make_layout(1))[0] -- return cutlass.Int32(scale_byte) ++ n_regions = int(scale.shape[0]) ++ src = scale.reshape(n_regions, page_size * scale_cols).contiguous() ++ if layout == "linear": ++ return src.reshape(n_regions, page_size, scale_cols) ++ ++ offsets = _region_offsets(page_size, scale_cols, layout, src.device) ++ out = torch.empty_like(src) ++ out[:, offsets] = src ++ return out.reshape(n_regions, page_size, scale_cols) ++ ++ ++def _unpack_nvfp4_scale( ++ packed: torch.Tensor, ++ *, ++ page_size: int, ++ scale_cols: int, ++ layout: str, ++) -> torch.Tensor: ++ """Inverse of :func:`pack_nvfp4_scale`; returns logical ``(t, s)`` order.""" ++ ++ layout = _check_layout(layout) ++ page_size = int(page_size) ++ scale_cols = int(scale_cols) ++ _validate_region(page_size, scale_cols, layout) ++ ++ n_regions = int(packed.shape[0]) ++ src = packed.reshape(n_regions, page_size * scale_cols) ++ if layout == "linear": ++ return src.reshape(n_regions, page_size, scale_cols) ++ offsets = _region_offsets(page_size, scale_cols, layout, src.device) ++ return src[:, offsets].reshape(n_regions, page_size, scale_cols) ++ ++ ++def _scale_region_grid(original_shape, layout: str) -> Tuple[int, int, bool]: ++ """Region decomposition of a K/V tensor of shape ``original_shape``. ++ ++ Returns ``(n_regions, region_tokens, quad_regroup)``. ``quad_regroup`` ++ marks the flat-varlen swizzle case, whose logical rows (token-major, then ++ head) have to be regrouped into ``(token_quad, head)`` regions. ++ """ ++ ++ shape = tuple(int(v) for v in original_shape) ++ if len(shape) == 4: ++ # Paged: [num_pages, Hkv, page_size, D] -> one region per (page, head). ++ return shape[0] * shape[1], shape[2], False ++ if len(shape) not in (2, 3): ++ raise ValueError( ++ "NVFP4 K/V must be rank-4 [num_pages, Hkv, page_size, D], rank-3 " ++ f"[total_k, Hkv, D] or rank-2 [total_k, D]; got rank {len(shape)}" ++ ) ++ total_k = shape[0] ++ heads = shape[1] if len(shape) == 3 else 1 ++ if layout == "linear": ++ # One region per (token, head): a single token row of S bytes. ++ return total_k * heads, 1, False ++ if total_k % 4 != 0: ++ raise ValueError( ++ "flat-varlen layout='swizzle4x4' tiles the global token axis in " ++ f"quads, so total_k must be a multiple of 4; got {total_k}" ++ ) ++ return (total_k // 4) * heads, 4, True - @cute.jit - def _dequant_fp4x16_to_bf16( -@@ -1282,12 +1388,14 @@ class SparseAttentionForwardNvfp4KvSm100: - src_words: cute.Tensor, - scale_e4m3: Int32, - dst: cute.Tensor, -+ global_scale: Optional[Float32], - ): - dst_i32 = cute.recast_tensor(dst, cutlass.Int32) - for word_idx in cutlass.range_constexpr(2): - fp8_lo, fp8_hi = utils.cvt_fp4x8_e2m1_scaled_e4m3x8( - src_words[word_idx], - scale_e4m3, -+ global_scale, - ) - dst_i32[word_idx * 2] = fp8_lo - dst_i32[word_idx * 2 + 1] = fp8_hi -@@ -1299,12 +1407,14 @@ class SparseAttentionForwardNvfp4KvSm100: - scale_e4m3_lo: Int32, - scale_e4m3_hi: Int32, - dst: cute.Tensor, -+ global_scale: Optional[Float32], - ): - dst_i32 = cute.recast_tensor(dst, cutlass.Int32) - for word_idx in cutlass.range_constexpr(2): - fp8_lo, fp8_hi = utils.cvt_fp4x8_e2m1_scaled_e4m3x8( - src_words[word_idx], - scale_e4m3_lo, -+ global_scale, - ) - dst_i32[word_idx * 2] = fp8_lo - dst_i32[word_idx * 2 + 1] = fp8_hi -@@ -1312,29 +1422,11 @@ class SparseAttentionForwardNvfp4KvSm100: - fp8_lo, fp8_hi = utils.cvt_fp4x8_e2m1_scaled_e4m3x8( - src_words[word_idx + 2], - scale_e4m3_hi, -+ global_scale, - ) - dst_i32[word_idx * 2 + 4] = fp8_lo - dst_i32[word_idx * 2 + 5] = fp8_hi +-def swizzle_nvfp4_scale_to_128x4( ++ ++def _pack_block_scale( + scale: torch.Tensor, + *, + rows: int, +- cols: int, ++ scale_cols: int, ++ original_shape, ++ layout: str, + ) -> torch.Tensor: +- """Convert TE logical rowwise scales to cuBLAS/cuDNN 128x4 tiled layout. ++ """Pack logical ``[rows, scale_cols]`` block scales into the kernel container. -- @cute.jit -- def _flat_kv_scale_row( -- self, -- token_idx: Int32, -- head_kv_idx: Int32, -- num_heads_kv: Int32, -- ) -> Int32: -- return token_idx * num_heads_kv + head_kv_idx -- -- @cute.jit -- def _paged_kv_scale_row( -- self, -- page_idx: Int32, -- token_idx: Int32, -- head_kv_idx: Int32, -- num_heads_kv: Int32, -- ) -> Int32: -- return (page_idx * num_heads_kv + head_kv_idx) * Int32(self.page_size) + token_idx +- Parameters +- ---------- +- scale : torch.Tensor +- Logical rowwise scale tensor with at least shape ``[rows, cols]``. +- rows : int +- Number of logical rows to convert. +- cols : int +- Number of logical scale columns to convert. - - @cute.jit - def _load_k_fp4_to_smem( - self, -@@ -1350,11 +1442,37 @@ class SparseAttentionForwardNvfp4KvSm100: - kv_block_idx: Int32, - k_batch_offset: Int32, - num_heads_kv: Int32, -+ k_sf_page_stride: Int32, -+ k_sf_head_stride: Int32, - ): - elems_per_block: cutlass.Constexpr[int] = 16 - bytes_per_block: cutlass.Constexpr[int] = 8 - scale_cols: cutlass.Constexpr[int] = self.head_dim // elems_per_block -- token_in_block_base = kv_block_idx * Int32(self.n_block_size) -+ # Loop-invariant scale addressing. In paged mode the whole region base -+ # is fixed: the page is sPagedKvIdx[0] and the KV head does not change -+ # across the task loop, so hoisting it removes a multiply chain per -+ # task. In flat mode only the block's first global token is invariant. -+ if const_expr(self.paged_kv): -+ k_sf_region_base = self._scale_region_base( -+ sPagedKvIdx[0], -+ head_kv_idx, -+ k_sf_page_stride, -+ k_sf_head_stride, -+ ) -+ else: -+ flat_token_base = ( -+ k_batch_offset + kv_block_idx * Int32(self.n_block_size) -+ ) -+ # Three trace-time dequant modes (no branch survives into the kernel; -+ # k_dtype is q_dtype, and fp8_pair_dequant is part of the compile key): -+ # 1. FP8 pair : 2 blocks/iter, 128-bit load, 2 scale bytes. == mode 2 x2, loop fusion. -+ # 2. FP8 scalar: 1 block/iter, 64-bit load. Half a 32-elem tile, hence the local_tile(). -+ # 3. BF16 : 1 block/iter; global scale folded here since mul_bf16x2 runs anyway. -+ # FP8 staging must include the global scale before conversion, since -+ # the block-scaled FP4 intermediate can exceed E4M3's finite range. -+ k_global = None -+ if const_expr(self.has_k_global_scale): -+ k_global = mKGlobalScale[0] - if const_expr(self.k_dtype == cutlass.Float8E4M3FN and self.fp8_pair_dequant): - elems_per_pair: cutlass.Constexpr[int] = 32 - bytes_per_pair: cutlass.Constexpr[int] = 16 -@@ -1379,22 +1497,17 @@ class SparseAttentionForwardNvfp4KvSm100: - pair_col = task_idx - row * Int32(scale_pairs) - scale_col = pair_col * Int32(2) - byte_col = pair_col * Int32(bytes_per_pair) -- token = token_in_block_base + row - if const_expr(self.paged_kv): -- page = sPagedKvIdx[0] -- scale_row = self._paged_kv_scale_row( -- page, -- row, -- head_kv_idx, -- num_heads_kv, -- ) -+ sf_region_base = k_sf_region_base -+ sf_token = row - else: -- token = k_batch_offset + token -- scale_row = self._flat_kv_scale_row( -- token, -+ sf_region_base = self._scale_region_base_flat( -+ flat_token_base + row, - head_kv_idx, - num_heads_kv, -+ 1, - ) -+ sf_token = Int32(0) - smem_offset = row * Int32(self.head_dim // 2) + byte_col - s_ptr = cute.make_ptr( - cutlass.Int32, -@@ -1404,10 +1517,16 @@ class SparseAttentionForwardNvfp4KvSm100: - ) - s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_pair // 4)) - cute.copy(g2r_pair_atom, s_vec, r_words_pair) -- scale_e4m3_lo = self._load_scale_e4m3_u8(mKScale, scale_row, scale_col) -- scale_e4m3_hi = self._load_scale_e4m3_u8( -+ scale_e4m3_lo = self._load_scale_e4m3_u8_linear( -+ mKScale, -+ sf_region_base, -+ sf_token, -+ scale_col, -+ ) -+ scale_e4m3_hi = self._load_scale_e4m3_u8_linear( - mKScale, -- scale_row, -+ sf_region_base, -+ sf_token, - scale_col + Int32(1), - ) - self._dequant_fp4x32_to_fp8( -@@ -1415,98 +1534,101 @@ class SparseAttentionForwardNvfp4KvSm100: - scale_e4m3_lo, - scale_e4m3_hi, - r_vals_pair, -+ k_global, - ) - sK_vec = sK[(row, None), 0, pair_col, 0] - r_tiles = cute.logical_divide(r_vals_pair, cute.make_layout(16)) - s_tiles = cute.logical_divide(sK_vec, cute.make_layout(16)) - for v in cutlass.range_constexpr(elems_per_pair // 16): - cute.copy(r2s_pair_atom, r_tiles[None, v], s_tiles[None, v]) -- cute.arch.fence_view_async_shared() -- return -- r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) -- r_vals = cute.make_rmem_tensor((elems_per_block,), self.k_dtype) -- g2r_atom = cute.make_copy_atom( -- cute.nvgpu.CopyUniversalOp(), -- cutlass.Int32, -- num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, -- ) -- elems_per_store: cutlass.Constexpr[int] = ( -- 16 if self.k_dtype == cutlass.Float8E4M3FN else 8 -- ) -- r2s_atom = cute.make_copy_atom( -- cute.nvgpu.CopyUniversalOp(), -- self.k_dtype, -- num_bits_per_copy=elems_per_store * self.k_dtype.width, -- ) -- total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols -- task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE -- task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane -- for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): -- row = task_idx // Int32(scale_cols) -- scale_col = task_idx - row * Int32(scale_cols) -- byte_col = scale_col * Int32(bytes_per_block) -- token = token_in_block_base + row -- if const_expr(self.paged_kv): -- page = sPagedKvIdx[0] -- scale_row = self._paged_kv_scale_row( -- page, -- row, -- head_kv_idx, -- num_heads_kv, -- ) -- else: -- token = k_batch_offset + token -- scale_row = self._flat_kv_scale_row( -- token, -- head_kv_idx, -- num_heads_kv, -- ) -- smem_offset = row * Int32(self.head_dim // 2) + byte_col -- s_ptr = cute.make_ptr( -+ else: -+ r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) -+ r_vals = cute.make_rmem_tensor((elems_per_block,), self.k_dtype) -+ g2r_atom = cute.make_copy_atom( -+ cute.nvgpu.CopyUniversalOp(), - cutlass.Int32, -- sKFp4.iterator.toint() + Int64(smem_offset), -- mem_space=sKFp4.iterator.memspace, -- assumed_align=bytes_per_block, -+ num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, - ) -- s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) -- cute.copy(g2r_atom, s_vec, r_words) -- if const_expr(self.k_dtype == cutlass.Float8E4M3FN): -- scale_e4m3 = self._load_scale_e4m3_u8(mKScale, scale_row, scale_col) -- else: -- combined_bf16x2 = self._load_scale_bf16x2(mKScale, scale_row, scale_col) -- if const_expr(self.has_k_global_scale): -- global_bf16x2 = utils.cvt_f16x2_f32( -- mKGlobalScale[0], -- mKGlobalScale[0], -- cutlass.BFloat16, -+ elems_per_store: cutlass.Constexpr[int] = ( -+ 16 if self.k_dtype == cutlass.Float8E4M3FN else 8 -+ ) -+ r2s_atom = cute.make_copy_atom( -+ cute.nvgpu.CopyUniversalOp(), -+ self.k_dtype, -+ num_bits_per_copy=elems_per_store * self.k_dtype.width, -+ ) -+ total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols -+ task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE -+ task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane -+ for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): -+ row = task_idx // Int32(scale_cols) -+ scale_col = task_idx - row * Int32(scale_cols) -+ byte_col = scale_col * Int32(bytes_per_block) -+ if const_expr(self.paged_kv): -+ sf_region_base = k_sf_region_base -+ sf_token = row -+ else: -+ sf_region_base = self._scale_region_base_flat( -+ flat_token_base + row, -+ head_kv_idx, -+ num_heads_kv, -+ 1, - ) -- combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) -- if const_expr(self.k_dtype == cutlass.Float8E4M3FN): -- sK_cols = sK[(row, None), 0, scale_col // Int32(2), 0] -- sK_vec = cute.local_tile( -- sK_cols, -- (elems_per_block,), -- (scale_col % Int32(2),), -- ) -- else: -- sK_vec = sK[ -- (row, None), -- 0, -- (scale_col % Int32(4), scale_col // Int32(4)), -- 0, -- ] -- if const_expr(self.k_dtype == cutlass.Float8E4M3FN): -- self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals) -- else: -- self._dequant_fp4x16_to_bf16( -- r_words, -- combined_bf16x2, -- r_vals, -+ sf_token = Int32(0) -+ smem_offset = row * Int32(self.head_dim // 2) + byte_col -+ s_ptr = cute.make_ptr( -+ cutlass.Int32, -+ sKFp4.iterator.toint() + Int64(smem_offset), -+ mem_space=sKFp4.iterator.memspace, -+ assumed_align=bytes_per_block, - ) -- r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) -- s_tiles = cute.logical_divide(sK_vec, cute.make_layout(elems_per_store)) -- for v in cutlass.range_constexpr(elems_per_block // elems_per_store): -- cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) -+ s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) -+ cute.copy(g2r_atom, s_vec, r_words) -+ if const_expr(self.k_dtype == cutlass.Float8E4M3FN): -+ # Mode 2: scale byte is a conversion operand, no multiply. -+ scale_e4m3 = self._load_scale_e4m3_u8_linear( -+ mKScale, -+ sf_region_base, -+ sf_token, -+ scale_col, -+ ) -+ sK_cols = sK[(row, None), 0, scale_col // Int32(2), 0] -+ sK_vec = cute.local_tile( -+ sK_cols, -+ (elems_per_block,), -+ (scale_col % Int32(2),), -+ ) -+ self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals, k_global) -+ else: -+ # Mode 3: replicated bf16x2 scale, global scale folded in. -+ combined_bf16x2 = self._load_scale_bf16x2_linear( -+ mKScale, -+ sf_region_base, -+ sf_token, -+ scale_col, -+ ) -+ if const_expr(self.has_k_global_scale): -+ global_bf16x2 = utils.cvt_f16x2_f32( -+ mKGlobalScale[0], -+ mKGlobalScale[0], -+ cutlass.BFloat16, -+ ) -+ combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) -+ sK_vec = sK[ -+ (row, None), -+ 0, -+ (scale_col % Int32(4), scale_col // Int32(4)), -+ 0, -+ ] -+ self._dequant_fp4x16_to_bf16( -+ r_words, -+ combined_bf16x2, -+ r_vals, -+ ) -+ r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) -+ s_tiles = cute.logical_divide(sK_vec, cute.make_layout(elems_per_store)) -+ for v in cutlass.range_constexpr(elems_per_block // elems_per_store): -+ cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) - cute.arch.fence_view_async_shared() +- Returns +- ------- +- torch.Tensor +- Scale tensor padded to ``round_up(rows, 128)`` by ``round_up(cols, 4)`` +- and swizzled into 128x4 tiled storage. ++ ``scale`` may be larger than ``[rows, scale_cols]`` (Transformer Engine ++ returns padded rowwise scales); the excess is dropped. + """ - @cute.jit -@@ -1524,11 +1646,30 @@ class SparseAttentionForwardNvfp4KvSm100: - kv_block_idx: Int32, - k_batch_offset: Int32, - num_heads_kv: Int32, -+ v_sf_page_stride: Int32, -+ v_sf_head_stride: Int32, - ): - elems_per_block: cutlass.Constexpr[int] = 16 - bytes_per_block: cutlass.Constexpr[int] = 8 - scale_cols: cutlass.Constexpr[int] = self.head_dim // elems_per_block -- token_in_block_base = kv_block_idx * Int32(self.n_block_size) -+ # Loop-invariant scale addressing; see `_load_k_fp4_to_smem`. Only the -+ # offset formula differs -- V is 4x4 token-quad swizzled. -+ if const_expr(self.paged_kv): -+ v_sf_region_base = self._scale_region_base( -+ sPagedKvIdx[0], -+ head_kv_idx, -+ v_sf_page_stride, -+ v_sf_head_stride, -+ ) -+ else: -+ flat_token_base = ( -+ k_batch_offset + kv_block_idx * Int32(self.n_block_size) -+ ) -+ # Same three trace-time modes as `_load_k_fp4_to_smem`; V only differs -+ # in the smem destination and the 4x4-swizzled scale reads. -+ v_global = None -+ if const_expr(self.has_v_global_scale): -+ v_global = mVGlobalScale[0] - if const_expr(self.v_dtype == cutlass.Float8E4M3FN and self.fp8_pair_dequant): - elems_per_pair: cutlass.Constexpr[int] = 32 - bytes_per_pair: cutlass.Constexpr[int] = 16 -@@ -1553,22 +1694,18 @@ class SparseAttentionForwardNvfp4KvSm100: - pair_col = task_idx - row * Int32(scale_pairs) - scale_col = pair_col * Int32(2) - byte_col = pair_col * Int32(bytes_per_pair) -- token = token_in_block_base + row - if const_expr(self.paged_kv): -- page = sPagedKvIdx[0] -- scale_row = self._paged_kv_scale_row( -- page, -- row, -- head_kv_idx, -- num_heads_kv, -- ) -+ sf_region_base = v_sf_region_base -+ sf_token = row - else: -- token = k_batch_offset + token -- scale_row = self._flat_kv_scale_row( -- token, -+ token_global = flat_token_base + row -+ sf_region_base = self._scale_region_base_flat( -+ token_global, - head_kv_idx, - num_heads_kv, -+ 4, - ) -+ sf_token = token_global & Int32(3) - smem_offset = row * Int32(self.head_dim // 2) + byte_col - s_ptr = cute.make_ptr( - cutlass.Int32, -@@ -1578,10 +1715,16 @@ class SparseAttentionForwardNvfp4KvSm100: - ) - s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_pair // 4)) - cute.copy(g2r_pair_atom, s_vec, r_words_pair) -- scale_e4m3_lo = self._load_scale_e4m3_u8(mVScale, scale_row, scale_col) -- scale_e4m3_hi = self._load_scale_e4m3_u8( -+ scale_e4m3_lo = self._load_scale_e4m3_u8_swizzle4x4( -+ mVScale, -+ sf_region_base, -+ sf_token, -+ scale_col, -+ ) -+ scale_e4m3_hi = self._load_scale_e4m3_u8_swizzle4x4( - mVScale, -- scale_row, -+ sf_region_base, -+ sf_token, - scale_col + Int32(1), - ) - self._dequant_fp4x32_to_fp8( -@@ -1589,6 +1732,7 @@ class SparseAttentionForwardNvfp4KvSm100: - scale_e4m3_lo, - scale_e4m3_hi, - r_vals_pair, -+ v_global, - ) - sV_cols = sV[(None, row % Int32(32)), 0, row // Int32(32), 0] - sV_vec = cute.local_tile(sV_cols, (elems_per_pair,), (pair_col,)) -@@ -1596,81 +1740,86 @@ class SparseAttentionForwardNvfp4KvSm100: - s_tiles = cute.logical_divide(sV_vec, cute.make_layout(16)) - for v in cutlass.range_constexpr(elems_per_pair // 16): - cute.copy(r2s_pair_atom, r_tiles[None, v], s_tiles[None, v]) -- cute.arch.fence_view_async_shared() -- return -- r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) -- r_vals = cute.make_rmem_tensor((elems_per_block,), self.v_dtype) -- g2r_atom = cute.make_copy_atom( -- cute.nvgpu.CopyUniversalOp(), -- cutlass.Int32, -- num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, -- ) -- elems_per_store: cutlass.Constexpr[int] = ( -- 16 if self.v_dtype == cutlass.Float8E4M3FN else 8 -- ) -- r2s_atom = cute.make_copy_atom( -- cute.nvgpu.CopyUniversalOp(), -- self.v_dtype, -- num_bits_per_copy=elems_per_store * self.v_dtype.width, -- ) -- total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols -- task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE -- task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane -- for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): -- row = task_idx // Int32(scale_cols) -- scale_col = task_idx - row * Int32(scale_cols) -- byte_col = scale_col * Int32(bytes_per_block) -- token = token_in_block_base + row -- if const_expr(self.paged_kv): -- page = sPagedKvIdx[0] -- scale_row = self._paged_kv_scale_row( -- page, -- row, -- head_kv_idx, -- num_heads_kv, -- ) -- else: -- token = k_batch_offset + token -- scale_row = self._flat_kv_scale_row( -- token, -- head_kv_idx, -- num_heads_kv, -- ) -- smem_offset = row * Int32(self.head_dim // 2) + byte_col -- s_ptr = cute.make_ptr( -+ else: -+ r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) -+ r_vals = cute.make_rmem_tensor((elems_per_block,), self.v_dtype) -+ g2r_atom = cute.make_copy_atom( -+ cute.nvgpu.CopyUniversalOp(), - cutlass.Int32, -- sVFp4.iterator.toint() + Int64(smem_offset), -- mem_space=sVFp4.iterator.memspace, -- assumed_align=bytes_per_block, -+ num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, - ) -- s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) -- cute.copy(g2r_atom, s_vec, r_words) -- if const_expr(self.v_dtype == cutlass.Float8E4M3FN): -- scale_e4m3 = self._load_scale_e4m3_u8(mVScale, scale_row, scale_col) -- self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals) -- else: -- combined_bf16x2 = self._load_scale_bf16x2(mVScale, scale_row, scale_col) -- if const_expr(self.has_v_global_scale): -- global_bf16x2 = utils.cvt_f16x2_f32( -- mVGlobalScale[0], -- mVGlobalScale[0], -- cutlass.BFloat16, -+ elems_per_store: cutlass.Constexpr[int] = ( -+ 16 if self.v_dtype == cutlass.Float8E4M3FN else 8 -+ ) -+ r2s_atom = cute.make_copy_atom( -+ cute.nvgpu.CopyUniversalOp(), -+ self.v_dtype, -+ num_bits_per_copy=elems_per_store * self.v_dtype.width, -+ ) -+ total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols -+ task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE -+ task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane -+ for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): -+ row = task_idx // Int32(scale_cols) -+ scale_col = task_idx - row * Int32(scale_cols) -+ byte_col = scale_col * Int32(bytes_per_block) -+ if const_expr(self.paged_kv): -+ sf_region_base = v_sf_region_base -+ sf_token = row -+ else: -+ token_global = flat_token_base + row -+ sf_region_base = self._scale_region_base_flat( -+ token_global, -+ head_kv_idx, -+ num_heads_kv, -+ 4, - ) -- combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) -- self._dequant_fp4x16_to_bf16( -- r_words, -- combined_bf16x2, -- r_vals, -+ sf_token = token_global & Int32(3) -+ smem_offset = row * Int32(self.head_dim // 2) + byte_col -+ s_ptr = cute.make_ptr( -+ cutlass.Int32, -+ sVFp4.iterator.toint() + Int64(smem_offset), -+ mem_space=sVFp4.iterator.memspace, -+ assumed_align=bytes_per_block, - ) -- if const_expr(self.v_dtype == cutlass.Float8E4M3FN): -- sV_cols = sV[(None, row % Int32(32)), 0, row // Int32(32), 0] -- else: -- sV_cols = sV[(None, row % Int32(16)), 0, row // Int32(16), 0] -- sV_vec = cute.local_tile(sV_cols, (elems_per_block,), (scale_col,)) -- r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) -- s_tiles = cute.logical_divide(sV_vec, cute.make_layout(elems_per_store)) -- for v in cutlass.range_constexpr(elems_per_block // elems_per_store): -- cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) -+ s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) -+ cute.copy(g2r_atom, s_vec, r_words) -+ if const_expr(self.v_dtype == cutlass.Float8E4M3FN): -+ # Mode 2: scale byte is a conversion operand; 32-row smem groups. -+ scale_e4m3 = self._load_scale_e4m3_u8_swizzle4x4( -+ mVScale, -+ sf_region_base, -+ sf_token, -+ scale_col, -+ ) -+ self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals, v_global) -+ sV_cols = sV[(None, row % Int32(32)), 0, row // Int32(32), 0] -+ else: -+ # Mode 3: bf16x2 scale, global folded in; 16-row smem groups. -+ combined_bf16x2 = self._load_scale_bf16x2_swizzle4x4( -+ mVScale, -+ sf_region_base, -+ sf_token, -+ scale_col, -+ ) -+ if const_expr(self.has_v_global_scale): -+ global_bf16x2 = utils.cvt_f16x2_f32( -+ mVGlobalScale[0], -+ mVGlobalScale[0], -+ cutlass.BFloat16, -+ ) -+ combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) -+ self._dequant_fp4x16_to_bf16( -+ r_words, -+ combined_bf16x2, -+ r_vals, -+ ) -+ sV_cols = sV[(None, row % Int32(16)), 0, row // Int32(16), 0] -+ sV_vec = cute.local_tile(sV_cols, (elems_per_block,), (scale_col,)) -+ r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) -+ s_tiles = cute.logical_divide(sV_vec, cute.make_layout(elems_per_store)) -+ for v in cutlass.range_constexpr(elems_per_block // elems_per_store): -+ cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) - cute.arch.fence_view_async_shared() ++ layout = _check_layout(layout) ++ shape = tuple(int(v) for v in original_shape) ++ rows = int(rows) ++ scale_cols = int(scale_cols) ++ if scale.dtype is not torch.uint8: ++ scale = scale.view(torch.uint8) + if scale.ndim != 2: +- raise ValueError(f"scale must be 2D, got shape {tuple(scale.shape)}") ++ raise ValueError(f"block scale must be 2D, got shape {tuple(scale.shape)}") ++ if int(scale.shape[0]) < rows or int(scale.shape[1]) < scale_cols: ++ raise ValueError( ++ "block scale is smaller than the logical shape: got " ++ f"{tuple(scale.shape)}, need at least {(rows, scale_cols)}" ++ ) ++ logical = scale[:rows, :scale_cols].contiguous() ++ ++ n_regions, region_tokens, quad_regroup = _scale_region_grid(shape, layout) ++ if quad_regroup: ++ heads = shape[1] if len(shape) == 3 else 1 ++ regions = ( ++ logical.reshape(shape[0] // 4, 4, heads, scale_cols) ++ .permute(0, 2, 1, 3) ++ .reshape(n_regions, region_tokens, scale_cols) ++ ) ++ else: ++ regions = logical.reshape(n_regions, region_tokens, scale_cols) ++ ++ packed = pack_nvfp4_scale( ++ regions, page_size=region_tokens, scale_cols=scale_cols, layout=layout ++ ) ++ return packed.reshape(shape[:-1] + (scale_cols,)).contiguous() + ++ ++def _unpack_block_scale( ++ packed: torch.Tensor, ++ *, ++ rows: int, ++ scale_cols: int, ++ original_shape, ++ layout: str, ++) -> torch.Tensor: ++ """Inverse of :func:`_pack_block_scale`; returns ``[rows, scale_cols]`` uint8.""" ++ ++ layout = _check_layout(layout) ++ shape = tuple(int(v) for v in original_shape) + rows = int(rows) +- cols = int(cols) +- padded_rows = _round_up(rows, 128) +- padded_cols = _round_up(cols, 4) +- if scale.shape[0] < rows or scale.shape[1] < cols: ++ scale_cols = int(scale_cols) ++ if packed.dtype is not torch.uint8: ++ packed = packed.view(torch.uint8) ++ if packed.numel() < rows * scale_cols: + raise ValueError( +- "scale is smaller than the requested logical shape: " +- f"got {tuple(scale.shape)}, need at least {(rows, cols)}" ++ f"packed scale holds {packed.numel()} bytes, need " ++ f"{rows * scale_cols} for shape {shape}" + ) + +- logical = scale[:rows, :cols].contiguous() +- if logical.shape != (padded_rows, padded_cols): +- logical = torch.nn.functional.pad( +- logical.to(torch.float32), +- (0, padded_cols - cols, 0, padded_rows - rows), +- ).to(scale.dtype) +- swizzled = torch.empty_like(logical) +- +- row = torch.arange(padded_rows, device=scale.device, dtype=torch.int64)[:, None] +- col = torch.arange(padded_cols, device=scale.device, dtype=torch.int64)[None, :] +- offset = nvfp4_scale_128x4_offset(row, col, padded_cols).reshape(-1) +- swizzled.reshape(-1)[offset] = logical.reshape(-1) +- return swizzled ++ n_regions, region_tokens, quad_regroup = _scale_region_grid(shape, layout) ++ flat = packed.contiguous().reshape(n_regions, region_tokens * scale_cols) ++ logical = _unpack_nvfp4_scale( ++ flat, page_size=region_tokens, scale_cols=scale_cols, layout=layout ++ ) ++ if quad_regroup: ++ heads = shape[1] if len(shape) == 3 else 1 ++ logical = ( ++ logical.reshape(shape[0] // 4, heads, 4, scale_cols) ++ .permute(0, 2, 1, 3) ++ .reshape(rows, scale_cols) ++ ) ++ return logical.reshape(rows, scale_cols) + + + def nvfp4_global_scale_from_amax(amax: torch.Tensor) -> torch.Tensor: +@@ -171,34 +404,182 @@ def _import_te_nvfp4_quantizer(): + return NVFP4Quantizer + + +-def quantize_bf16_to_nvfp4_128x4(x: torch.Tensor) -> Nvfp4QuantizedTensor: +- """Quantize a BF16/FP16 tensor to NVFP4 using Transformer Engine. ++# --------------------------------------------------------------------------- ++# Dependency-free (pure PyTorch) NVFP4 quantizer ++# --------------------------------------------------------------------------- ++# ++# This is a drop-in replacement for the Transformer Engine path above. It ++# exists so the NVFP4 accuracy tests can run on machines without a working ++# Transformer Engine build; it is an exact round-trip partner of ++# ``dequantize_nvfp4_to_bf16`` below and uses the same physical layout the ++# kernel reads (``_scale_offset_linear`` / ``_scale_offset_swizzle4x4`` in ++# ``src/sm100/fwd/atten_fwd_nvfp4_kv.py``). ++ ++# FP4 E2M1: 1 sign bit, 2 exponent bits, 1 mantissa bit. Codes 0..7 hold the ++# non-negative magnitudes and bit 3 is the sign. Same table as the LUT used by ++# ``dequantize_nvfp4_to_bf16``. ++_E2M1_MAGNITUDES: Tuple[float, ...] = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) ++ ++# ``_E2M1_MIDPOINTS[i]`` is the tie point between code ``i`` and code ``i + 1``. ++_E2M1_MIDPOINTS: Tuple[float, ...] = (0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0) ++ ++ ++def _round_to_e2m1_codes(x: torch.Tensor) -> torch.Tensor: ++ """Round FP32 values to FP4 E2M1 codes, round-to-nearest-even. ++ ++ Ties resolve to the code whose mantissa bit is zero, i.e. the even code, ++ matching ``cvt.rn.satfinite.e2m1x2.f32``. Magnitudes above 6 saturate to ++ code 7 (6.0); the sign is preserved in bit 3, including for negative zero. ++ """ ++ ++ xf = torch.nan_to_num(x.to(torch.float32), nan=0.0) ++ sign = torch.signbit(xf) ++ magnitude = xf.abs().contiguous() ++ midpoints = torch.tensor( ++ _E2M1_MIDPOINTS, dtype=torch.float32, device=xf.device ++ ) ++ # ``low`` counts midpoints strictly below the magnitude (round down on a ++ # tie); ``high`` counts midpoints at or below it (round up on a tie). They ++ # differ only exactly on a tie, where the tie sits at index ``low``. ++ low = torch.searchsorted(midpoints, magnitude, right=False) ++ high = torch.searchsorted(midpoints, magnitude, right=True) ++ code = torch.where(low % 2 == 0, low, high).to(torch.uint8) ++ return code | (sign.to(torch.uint8) << 3) ++ ++ ++def _pack_e2m1_codes(codes: torch.Tensor) -> torch.Tensor: ++ """Pack pairs of E2M1 codes into bytes; even element in the low nibble.""" ++ ++ return (codes[..., 0::2] & 0x0F) | (codes[..., 1::2] << 4) ++ ++ ++def _quantize_bf16_to_nvfp4_torch( ++ x: torch.Tensor, ++ *, ++ rows: int, ++ scale_cols: int, ++ layout: str, ++) -> "Nvfp4QuantizedTensor": ++ """Quantize to NVFP4 with plain PyTorch, no Transformer Engine. ++ ++ Follows the same recipe TE uses: ++ global_scale = amax(|x|) / (448 * 6) ++ block_scale = to_e4m3(amax(|block|) / (6 * global_scale)) <= 448 ++ fp4 = to_e2m1(block / (block_scale * global_scale)) ++ so ``fp4 * block_scale * global_scale`` reconstructs the value exactly in ++ FP32, which is what ``dequantize_nvfp4_to_bf16`` computes. ++ ++ Everything except the final :func:`_pack_block_scale` call is ++ layout-agnostic: the global scale, the block amax, the E4M3 encode, the ++ E2M1 rounding and the nibble packing do not depend on where the scale ++ bytes end up. ++ """ ++ ++ flat = x.detach().to(torch.float32).contiguous().reshape(rows, -1) ++ amax = flat.abs().amax() ++ global_scale = nvfp4_global_scale_from_amax(amax.reshape(1)) ++ # An all-zero tensor would give a zero (and thus unusable) global scale. ++ global_scale = torch.where( ++ global_scale > 0, global_scale, torch.ones_like(global_scale) ++ ) ++ ++ blocks = flat.reshape(rows, scale_cols, NVFP4_BLOCK_SIZE) ++ block_amax = blocks.abs().amax(dim=-1) ++ encoded = (block_amax / (NVFP4_FP4_MAX * global_scale)).clamp( ++ min=0.0, max=NVFP4_FP8_E4M3_MAX ++ ) ++ block_scale = encoded.to(torch.float8_e4m3fn) ++ dequant_step = block_scale.to(torch.float32) * global_scale ++ nonzero = dequant_step > 0 ++ safe_step = torch.where(nonzero, dequant_step, torch.ones_like(dequant_step)) ++ ++ codes = _round_to_e2m1_codes(blocks / safe_step.unsqueeze(-1)) ++ codes = torch.where(nonzero.unsqueeze(-1), codes, torch.zeros_like(codes)) ++ data = _pack_e2m1_codes(codes.reshape(rows, -1)).reshape( ++ *x.shape[:-1], x.shape[-1] // 2 ++ ) ++ ++ scale = _pack_block_scale( ++ block_scale.view(torch.uint8), ++ rows=rows, ++ scale_cols=scale_cols, ++ original_shape=x.shape, ++ layout=layout, ++ ) ++ ++ return Nvfp4QuantizedTensor( ++ data=data.contiguous(), ++ scale=scale.contiguous(), ++ global_scale=global_scale.to(torch.float32).contiguous(), ++ logical_scale_shape=(rows, scale_cols), ++ original_shape=tuple(int(v) for v in x.shape), ++ layout=layout, ++ ) ++ ++ ++def te_nvfp4_quantizer_available() -> bool: ++ """Return True when Transformer Engine's NVFP4 quantizer can be imported.""" ++ ++ try: ++ _import_te_nvfp4_quantizer() ++ except RuntimeError: ++ return False ++ return True ++ ++ ++def quantize_bf16_to_nvfp4( ++ x: torch.Tensor, ++ *, ++ layout: str, ++ backend: str = "auto", ++) -> Nvfp4QuantizedTensor: ++ """Quantize a BF16/FP16 tensor to NVFP4. - @cute.jit -@@ -1794,6 +1943,8 @@ class SparseAttentionForwardNvfp4KvSm100: - kv_block_idx: Int32, - k_batch_offset: Int32, - num_heads_kv: Int32, -+ k_sf_page_stride: Int32, -+ k_sf_head_stride: Int32, - ): - warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) - warp_idx_in_wg = warp_idx - Int32(dequant_warp_base) -@@ -1814,6 +1965,8 @@ class SparseAttentionForwardNvfp4KvSm100: - kv_block_idx, - k_batch_offset, - num_heads_kv, -+ k_sf_page_stride, -+ k_sf_head_stride, - ) - dequant_barrier.arrive_and_wait() - if warp_idx_in_wg == Int32(0): -@@ -1838,6 +1991,8 @@ class SparseAttentionForwardNvfp4KvSm100: - kv_block_idx: Int32, - k_batch_offset: Int32, - num_heads_kv: Int32, -+ v_sf_page_stride: Int32, -+ v_sf_head_stride: Int32, - ): - warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) - warp_idx_in_wg = warp_idx - Int32(dequant_warp_base) -@@ -1858,6 +2013,8 @@ class SparseAttentionForwardNvfp4KvSm100: - kv_block_idx, - k_batch_offset, - num_heads_kv, -+ v_sf_page_stride, -+ v_sf_head_stride, - ) - dequant_barrier.arrive_and_wait() - if warp_idx_in_wg == Int32(0): -@@ -2191,8 +2348,8 @@ class SparseAttentionForwardNvfp4KvSm100: - self, - tiled_mma_qk: cute.TiledMma, - tiled_mma_pv: cute.TiledMma, -- thr0_qk: cute.core.ThrMma, -- thr0_pv: cute.core.ThrMma, -+ thr0_qk: cute.ThrMma, -+ thr0_pv: cute.ThrMma, - tStS: cute.Tensor, - tOrP: cute.Tensor, - sK: cute.Tensor, -@@ -2479,17 +2636,6 @@ class SparseAttentionForwardNvfp4KvSm100: - self.qk_acc_dtype) - cute.copy(thr_tmem_load, tStS_t2r, tSrS_t2r) + TE returns rowwise scales in logical padded layout. This helper returns +- the scales in physical 128x4 tiled storage, so the attention kernel can +- load them with ``nvfp4_scale_128x4_offset``. ++ the scales in the physical container the attention kernel reads -- ++ ``"linear"`` for K, ``"swizzle4x4"`` for V (see the module docstring). ++ 128x4 was this module's own choice and never a TE constraint, so the TE ++ backend is unaffected by the layout change: it still hands back logical ++ ``meta["rowwise_scale_inv"]`` and the packing happens here. ++ ++ Two backends produce the same layout: ++ * ``"te"`` - Transformer Engine's ``NVFP4Quantizer``. ++ * ``"torch"`` - a dependency-free PyTorch implementation of the same ++ recipe. Use it when Transformer Engine is not installed. ++ * ``"auto"`` - TE if importable, otherwise ``"torch"``. Override with ++ the ``MSA_NVFP4_QUANTIZER_BACKEND`` environment variable. + + Parameters + ---------- + x : torch.Tensor +- CUDA BF16 or FP16 tensor. The last dimension must be divisible by 16, +- and the flattened row dimension ``prod(x.shape[:-1])`` must also be +- divisible by 16. ++ CUDA BF16 or FP16 tensor, shaped ``[num_pages, Hkv, page_size, D]`` ++ (paged), ``[total_k, Hkv, D]`` or ``[total_k, D]`` (flat varlen). The ++ last dimension must be divisible by 16, and the flattened row ++ dimension ``prod(x.shape[:-1])`` must also be divisible by 16. ++ layout : str ++ ``"linear"`` (K) or ``"swizzle4x4"`` (V). Required -- there is no ++ default, because silently picking the wrong one for V produces ++ plausible-looking but wrong numbers. ++ backend : str, optional ++ ``"auto"``, ``"te"`` or ``"torch"``. + + Returns + ------- + Nvfp4QuantizedTensor +- Packed FP4 data, 128x4-swizzled block scales, global scale, and shape +- metadata needed by the KVFP4 attention kernel or by reference +- dequantization. ++ Packed FP4 data, packed block scales, global scale, and shape metadata ++ needed by the KVFP4 attention kernel or by reference dequantization. + """ + ++ layout = _check_layout(layout) + if not x.is_cuda: + raise ValueError("NVFP4 quantization requires a CUDA tensor") + if x.dtype not in (torch.bfloat16, torch.float16): + raise TypeError(f"x must be bf16 or fp16, got {x.dtype}") +- if x.ndim < 2: +- raise ValueError(f"x must have at least 2 dimensions, got {x.ndim}") ++ if x.ndim not in (2, 3, 4): ++ raise ValueError( ++ "x must be rank-4 [num_pages, Hkv, page_size, D], rank-3 " ++ f"[total_k, Hkv, D] or rank-2 [total_k, D], got rank {x.ndim}" ++ ) + if x.shape[-1] % NVFP4_BLOCK_SIZE != 0: + raise ValueError( + f"last dimension must be divisible by {NVFP4_BLOCK_SIZE}, got {x.shape[-1]}" +@@ -213,6 +594,26 @@ def quantize_bf16_to_nvfp4_128x4(x: torch.Tensor) -> Nvfp4QuantizedTensor: + f"{NVFP4_BLOCK_SIZE}, got {rows}" + ) + ++ scale_cols = int(x.shape[-1]) // NVFP4_BLOCK_SIZE ++ # Fail here rather than after a full quantization pass. ++ _scale_region_grid(x.shape, layout) ++ ++ # An explicit argument wins; the environment only supplies the default, so ++ # a caller that asks for a specific backend always gets it (or an error). ++ backend = backend.lower() ++ if backend == "auto": ++ backend = os.environ.get("MSA_NVFP4_QUANTIZER_BACKEND", "auto").lower() ++ if backend not in ("auto", "te", "torch"): ++ raise ValueError( ++ f"backend must be 'auto', 'te' or 'torch', got {backend!r}" ++ ) ++ if backend == "auto": ++ backend = "te" if te_nvfp4_quantizer_available() else "torch" ++ if backend == "torch": ++ return _quantize_bf16_to_nvfp4_torch( ++ x, rows=rows, scale_cols=scale_cols, layout=layout ++ ) ++ + NVFP4Quantizer = _import_te_nvfp4_quantizer() + quantizer = NVFP4Quantizer(rowwise=True, columnwise=False) + qx = quantizer.quantize(x.contiguous()) +@@ -223,29 +624,34 @@ def quantize_bf16_to_nvfp4_128x4(x: torch.Tensor) -> Nvfp4QuantizedTensor: + data = data.view(torch.uint8) + logical_scale = meta["rowwise_scale_inv"] + amax = meta["amax_rowwise"] +- scale_cols = int(x.shape[-1]) // NVFP4_BLOCK_SIZE +- scale_128x4 = swizzle_nvfp4_scale_to_128x4( ++ scale = _pack_block_scale( + logical_scale, + rows=rows, +- cols=scale_cols, ++ scale_cols=scale_cols, ++ original_shape=x.shape, ++ layout=layout, + ) + global_scale = nvfp4_global_scale_from_amax(amax).contiguous() + + return Nvfp4QuantizedTensor( + data=data, +- scale_128x4=scale_128x4, ++ scale=scale, + global_scale=global_scale, + logical_scale_shape=(rows, scale_cols), + original_shape=tuple(int(v) for v in x.shape), ++ layout=layout, + ) + + +-def quantize_kv_bf16_to_nvfp4_128x4( ++def quantize_kv_bf16_to_nvfp4( + k: torch.Tensor, + v: torch.Tensor, + ) -> tuple[Nvfp4QuantizedTensor, Nvfp4QuantizedTensor]: + """Quantize BF16/FP16 K and V tensors independently for KVFP4 attention. + ++ K is packed ``"linear"`` and V ``"swizzle4x4"``, which is exactly what the ++ attention kernel reads and what vLLM's NVFP4 KV-cache store kernel writes. ++ + Parameters + ---------- + k : torch.Tensor +@@ -259,10 +665,13 @@ def quantize_kv_bf16_to_nvfp4_128x4( + Quantized K and V tensors with independent scales. + """ -- if const_expr( -- self.q_dtype == cutlass.Float8E4M3FN -- and self.has_k_global_scale -- ): -- k_global = mKGlobalScale[0] -- for i in cutlass.range_constexpr(0, cute.size(tSrS_t2r.shape), 2): -- tSrS_t2r[i], tSrS_t2r[i + 1] = cute.arch.mul_packed_f32x2( -- (tSrS_t2r[i], tSrS_t2r[i + 1]), -- (k_global, k_global), -- ) -- - seqlen_info = SeqlenInfoQK( - Int32(0), - Int32(0), -@@ -3071,11 +3217,6 @@ class SparseAttentionForwardNvfp4KvSm100: - row_sum_val - if not is_zero_or_nan - else Float32(1.0)) -- if const_expr( -- self.q_dtype == cutlass.Float8E4M3FN -- and self.has_v_global_scale -- ): -- row_scale *= mVGlobalScale[0] - row_base_ptr = ( - flat_row * Int64(self.head_dim)) - o0 = tOrO_mn[r, c_base] -@@ -3133,11 +3274,6 @@ class SparseAttentionForwardNvfp4KvSm100: - row_sum_val - if not is_zero_or_nan - else Float32(1.0)) -- if const_expr( -- self.q_dtype == cutlass.Float8E4M3FN -- and self.has_v_global_scale -- ): -- row_scale *= mVGlobalScale[0] - row_base_ptr = ( - flat_row * Int64(self.head_dim)) - o0 = tOrO_mn[r, c_base] -@@ -3211,11 +3347,6 @@ class SparseAttentionForwardNvfp4KvSm100: - if not is_zero_or_nan - else Float32(1.0) - ) -- if const_expr( -- self.q_dtype == cutlass.Float8E4M3FN -- and self.has_v_global_scale -- ): -- row_scale *= mVGlobalScale[0] - row_base_ptr = flat_row * Int64(self.head_dim) - o0 = tOrO_mn[r, c_base] - o1 = tOrO_mn[r, c_base + Int32(1)] -diff --git a/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py b/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py -index 8ccc2cb..daf0e74 100644 ---- a/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py -+++ b/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py -@@ -424,7 +424,13 @@ class SparseDecodeAttentionForwardSm100: - self.tile_scheduler_cls = DecodeTileScheduler - grid = DecodeTileScheduler.get_grid_shape(tile_sched_params) +- return quantize_bf16_to_nvfp4_128x4(k), quantize_bf16_to_nvfp4_128x4(v) ++ return ( ++ quantize_bf16_to_nvfp4(k, layout="linear"), ++ quantize_bf16_to_nvfp4(v, layout="swizzle4x4"), ++ ) -- clc_response_size = self.sched_stages * 4 if self.use_clc_scheduler else 0 -+ # One CLC response record per scheduler stage. A response is a 16B -+ # opaque record that `cute.arch.clc_response` reads back with a -+ # 128-bit `universal_copy`, so each slot must be 16B aligned. cute -+ # derives a MemRange's alignment from its element width, so the range -+ # is typed Int128 rather than 4 x Int32 (which only guarantees 4B and -+ # makes the copy fail the `cute.copy` verifier). -+ clc_response_size = self.sched_stages if self.use_clc_scheduler else 0 - clc_mbar_size = self.sched_stages * 2 if self.use_clc_scheduler else 0 - # ------------------------------------------------------------------ -@@ -455,7 +461,7 @@ class SparseDecodeAttentionForwardSm100: - tmem_dealloc_mbar_ptr: Int64 - tmem_holding_buf: Int32 - clc_mbar_ptr: cute.struct.MemRange[cutlass.Int64, clc_mbar_size] -- clc_response: cute.struct.MemRange[Int32, clc_response_size] -+ clc_response: cute.struct.MemRange[cutlass.Int128, clc_response_size] - sQ: cute.struct.Align[ - cute.struct.MemRange[self.q_dtype, cute.cosize(sQ_layout)], - self.buffer_align_bytes, -@@ -1536,8 +1542,8 @@ class SparseDecodeAttentionForwardSm100: - tOtO1_t2r_i = tOtO1_t2r[None, 0, 0, col_pass_idx] - tOsO_r2s_i = tOsO_s2r[None, 0, 0, col_pass_idx] - frg_shape = tOcO_t2r[None, 0, 0, col_pass_idx].shape -- tOrO0_frg = cute.make_fragment(frg_shape, self.pv_acc_dtype) -- tOrO1_frg = cute.make_fragment(frg_shape, self.pv_acc_dtype) -+ tOrO0_frg = cute.make_rmem_tensor(frg_shape, self.pv_acc_dtype) -+ tOrO1_frg = cute.make_rmem_tensor(frg_shape, self.pv_acc_dtype) - is_zero_output = ( - scale0 == Float32(0.0) and scale1 == Float32(0.0) - ) -@@ -1600,8 +1606,7 @@ class SparseDecodeAttentionForwardSm100: +-def dequantize_nvfp4_128x4_to_bf16( ++def dequantize_nvfp4_to_bf16( + qx: Nvfp4QuantizedTensor, + *, + include_global_scale: bool = True, +@@ -272,10 +681,15 @@ def dequantize_nvfp4_128x4_to_bf16( + This mirrors the kernel contract: + x = e2m1 * E4M3_block_scale_1x16 * FP32_global_scale - frg_count: cutlass.Constexpr[int] = self.head_dim // corr_tile_size - for fi in cutlass.range_constexpr(frg_count): -- tOrO_frg = cute.make_fragment( -- tOrO_t2r_shape, self.pv_acc_dtype) -+ tOrO_frg = cute.make_rmem_tensor(tOrO_t2r_shape, self.pv_acc_dtype) - tOtO_t2r_i = cute.make_tensor( - tOtO_t2r.iterator + fi * corr_tile_size, - tOtO_t2r.layout, -@@ -1708,6 +1713,11 @@ class SparseDecodeAttentionForwardSm100: - pipeline.PipelineUserType.Consumer, self.kv_stage) - phase_s0 = Int32(0) - phase_s1 = Int32(0) -+ # pipeline_o_acc producer phases. Producers start at phase 1 so the -+ # very first acquire passes trivially (same convention as -+ # ``corr_epi_producer_phase`` in correction_loop). -+ o_acc_producer_phase0 = Int32(1) -+ o_acc_producer_phase1 = Int32(1) ++ The scale gather uses ``qx.layout``, so the result is layout-independent: ++ the same logical block scales give the same BF16 output whether they were ++ packed ``"linear"`` or ``"swizzle4x4"``. ++ + Parameters + ---------- + qx : Nvfp4QuantizedTensor +- Quantized tensor returned by ``quantize_bf16_to_nvfp4_128x4``. ++ Quantized tensor returned by ``quantize_bf16_to_nvfp4``. ``qx.scale`` ++ must be a contiguous packed container. + include_global_scale : bool, optional + If True, multiply by ``qx.global_scale`` after applying per-block + scales. +@@ -286,6 +700,7 @@ def dequantize_nvfp4_128x4_to_bf16( + BF16 tensor with shape ``qx.original_shape``. + """ - work_tile = tile_scheduler.initial_work_tile_info() - while work_tile.is_valid_tile: -@@ -1727,6 +1737,52 @@ class SparseDecodeAttentionForwardSm100: - block_iter_count_mma = ( - page_count_mma + Int32(1)) & ~Int32(1) ++ layout = _check_layout(qx.layout) + data = qx.data if qx.data.dtype is torch.uint8 else qx.data.view(torch.uint8) + if data.shape[-1] * 2 != qx.original_shape[-1]: + raise ValueError( +@@ -330,10 +745,13 @@ def dequantize_nvfp4_128x4_to_bf16( + values[:, 0::2] = fp4_lut[lo.long()] + values[:, 1::2] = fp4_lut[hi.long()] + +- row = torch.arange(rows, device=data.device, dtype=torch.int64)[:, None] +- col = torch.arange(scale_cols, device=data.device, dtype=torch.int64)[None, :] +- offset = nvfp4_scale_128x4_offset(row, col, scale_cols) +- scale_u8 = qx.scale_128x4.reshape(-1)[offset.reshape(-1)].reshape(rows, scale_cols) ++ scale_u8 = _unpack_block_scale( ++ qx.scale, ++ rows=rows, ++ scale_cols=scale_cols, ++ original_shape=qx.original_shape, ++ layout=layout, ++ ) + scale = scale_u8.view(torch.float8_e4m3fn).to(torch.float32) + scale = scale.repeat_interleave(NVFP4_BLOCK_SIZE, dim=1) + out = values * scale +@@ -347,12 +765,12 @@ def _example() -> None: + device = torch.device("cuda") + k = torch.randn(128, 2, 128, device=device, dtype=torch.bfloat16) + v = torch.randn_like(k) +- k_q, v_q = quantize_kv_bf16_to_nvfp4_128x4(k, v) ++ k_q, v_q = quantize_kv_bf16_to_nvfp4(k, v) + print("K FP4 data:", tuple(k_q.data.shape), k_q.data.dtype) +- print("K scale 128x4:", tuple(k_q.scale_128x4.shape), k_q.scale_128x4.dtype) ++ print("K scale (linear):", tuple(k_q.scale.shape), k_q.scale.dtype) + print("K global scale:", tuple(k_q.global_scale.shape), k_q.global_scale.dtype) + print("V FP4 data:", tuple(v_q.data.shape), v_q.data.dtype) +- print("V scale 128x4:", tuple(v_q.scale_128x4.shape), v_q.scale_128x4.dtype) ++ print("V scale (swizzle4x4):", tuple(v_q.scale.shape), v_q.scale.dtype) + print("V global scale:", tuple(v_q.global_scale.shape), v_q.global_scale.dtype) + + +diff --git a/python/fmha_sm100/cute/src/common/aot_cache.py b/python/fmha_sm100/cute/src/common/aot_cache.py +index 99fd0b4..8037d13 100644 +--- a/python/fmha_sm100/cute/src/common/aot_cache.py ++++ b/python/fmha_sm100/cute/src/common/aot_cache.py +@@ -6,6 +6,12 @@ + Saves compiled TVM FFI kernels as .o files on first compile, + loads them on subsequent runs to skip JIT compilation. + ++Cached objects are keyed by the caller's kernel key *and* a build fingerprint ++covering the target GPU architecture and the kernel sources. Without the ++fingerprint a .o built for one architecture (or from an older revision of the ++kernel) is silently reused on another, which both miscompiles across ++SM100/SM103 and makes local kernel edits appear to have no effect. ++ + Environment variables: + MM_SPARSE_ATTN_AOT_CACHE: Override cache directory + (default: ~/.cache/minfer/mm_sparse_attn) +@@ -25,10 +31,87 @@ _AOT_CACHE_DIR = os.environ.get( + _AOT_DISABLE = os.environ.get("MM_SPARSE_ATTN_AOT_DISABLE", "0") == "1" + + _loaded_modules: dict[str, object] = {} ++_build_fingerprint_cache: str | None = None ++ ++# .../cute/src/common/aot_cache.py -> .../cute ++_PACKAGE_ROOT = os.path.dirname( ++ os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ++) ++ ++ ++def _source_fingerprint() -> str: ++ """Hash every .py under the cute package so edits invalidate the cache.""" ++ h = hashlib.sha256() ++ for dirpath, dirnames, filenames in os.walk(_PACKAGE_ROOT): ++ dirnames[:] = sorted(d for d in dirnames if d != "__pycache__") ++ for filename in sorted(filenames): ++ if not filename.endswith(".py"): ++ continue ++ path = os.path.join(dirpath, filename) ++ h.update(os.path.relpath(path, _PACKAGE_ROOT).encode()) ++ try: ++ with open(path, "rb") as f: ++ h.update(f.read()) ++ except OSError: ++ # Unreadable source: fold the error in rather than silently ++ # producing the same digest as if the file did not exist. ++ h.update(b"") ++ return h.hexdigest()[:16] ++ ++ ++def _target_arch() -> str: ++ """Compute capability of the device the kernel will be launched on.""" ++ try: ++ import torch ++ ++ major, minor = torch.cuda.get_device_capability() ++ return f"sm{major}{minor}" ++ except Exception: ++ return "smunknown" ++ ++ ++_r2_store_cache: bool | None = None ++ ++ ++def r2_store_enabled() -> bool: ++ """Whether the NVFP4-KV sparse prefill uses the R2 store warpgroup. ++ ++ SM107 only (resolved once from the device capability); TRTLLM_MSA_DISABLE_R2STORE=1 restores the stock ++ in-softmax epilogue there too. ++ """ ++ global _r2_store_cache ++ if _r2_store_cache is None: ++ import torch ++ ++ _r2_store_cache = ( ++ torch.cuda.get_device_capability() == (10, 7) ++ and os.environ.get("TRTLLM_MSA_DISABLE_R2STORE", "0") != "1" ++ ) ++ return _r2_store_cache ++ ++ ++def _build_fingerprint() -> str: ++ global _build_fingerprint_cache ++ if _build_fingerprint_cache is None: ++ try: ++ import cutlass ++ ++ cutlass_version = getattr(cutlass, "__version__", "unknown") ++ except Exception: ++ cutlass_version = "unknown" ++ # Construction-time codegen knobs must be part of the key: the source hash ++ # alone would hand one mode's cached .o to the other. ++ r2store = "r2store" + ("0" if r2_store_enabled() else "1") ++ _build_fingerprint_cache = "-".join( ++ (_target_arch(), str(cutlass_version), _source_fingerprint(), r2store) ++ ) ++ return _build_fingerprint_cache -+ # --------------------------------------------------------- -+ # Tile-level O-accumulator acquire. -+ # -+ # The MMA is the pipeline_o_acc producer but used to -+ # ``producer_commit`` without ever calling producer_acquire, -+ # so nothing bounded how far ahead of the correction warp it -+ # could run *across work tiles*. That matters because the -+ # softmax->correction stats mailbox (row_sum / row_max / -+ # acc_scale) lives in the first two columns of the S -+ # accumulator, TMEM S[stage][:, 0:2] (see the -+ # ``tStS_vec_layout`` compositions in softmax_loop and -+ # correction_loop). The first QK GEMM of the *next* work -+ # tile overwrites S[stage] wholesale and therefore destroys -+ # the stats the correction warp is about to read. -+ # -+ # The only thing that previously ordered that overwrite was -+ # the borrowed pipeline_s_p_o credit chain, whose depth is -+ # ``block_iter_count // 2`` acquires per tile. With -+ # block_iter_count == 2 (per-split chunk of 1 or 2 pages) -+ # that depth is 1, and the license to clobber S[stage] in -+ # tile N+1 comes from tile N-1's correction release -- a -+ # full tile stale. The MMA then races the correction warp -+ # for the tile-N stats and wins often enough to corrupt -+ # ~50% of the partial rows (negative/garbage row_sum -> -+ # log2(neg) -> NaN LSE_partial -> garbage after combine). -+ # -+ # pipeline_o_acc already has exactly the right semantics -- -+ # the correction warp releases it (correction_loop, right -+ # after it has read the final stats and run the epilogue -+ # combine) -- it was simply never waited on. Acquiring it -+ # here, before the first QK of the tile, makes the producer -+ # side of pipeline_o_acc well formed (1 acquire + 1 commit -+ # per stage per tile against 1 wait + 1 release on the -+ # consumer side) and bounds the MMA to at most one tile -+ # ahead of the correction warp for every chunk size. -+ # --------------------------------------------------------- -+ if block_iter_count_mma > Int32(0): -+ pipeline_o_acc.producer_acquire_w_index_phase( -+ Int32(0), o_acc_producer_phase0) -+ pipeline_o_acc.producer_acquire_w_index_phase( -+ Int32(1), o_acc_producer_phase1) -+ o_acc_producer_phase0 = ( -+ o_acc_producer_phase0 ^ Int32(1)) -+ o_acc_producer_phase1 = ( -+ o_acc_producer_phase1 ^ Int32(1)) + + def _key_to_path(key: tuple) -> str: +- h = hashlib.sha256(repr(key).encode()).hexdigest()[:16] ++ h = hashlib.sha256( ++ repr((_build_fingerprint(), key)).encode() ++ ).hexdigest()[:16] + name = str(key[0]).replace("/", "_") + return os.path.join(_AOT_CACHE_DIR, f"{name}_{h}") + +diff --git a/python/fmha_sm100/cute/src/common/cuda_toolchain.py b/python/fmha_sm100/cute/src/common/cuda_toolchain.py +new file mode 100644 +index 0000000..80cae6e +--- /dev/null ++++ b/python/fmha_sm100/cute/src/common/cuda_toolchain.py +@@ -0,0 +1,169 @@ ++# SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax ++# SPDX-License-Identifier: MIT + - pipeline_q.consumer_wait_w_index_phase( - Int32(0), mma_q_consumer_phase) - mma_q_consumer_phase = mma_q_consumer_phase ^ Int32(1) -@@ -1899,7 +1955,7 @@ class SparseDecodeAttentionForwardSm100: - tmem_load_atom_pre: cute.CopyAtom, - tmem_store_atom_pre: cute.CopyAtom, - tmem_store_vec_atom_pre: cute.CopyAtom, -- thr_mma_qk_pre: cute.core.ThrMma, -+ thr_mma_qk_pre: cute.ThrMma, - pipeline_s_p_o: pipeline.PipelineAsync, - pipeline_p_lastsplit: pipeline.PipelineAsync, - pipeline_sm_stats: pipeline.PipelineAsync, -diff --git a/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py b/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py -index 599dace..f29b5b0 100644 ---- a/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py -+++ b/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py -@@ -179,8 +179,10 @@ class DecodeTileScheduler: - ) -> WorkTileInfo: - # CLC responses are 16B opaque records. The scheduler warp can query - # the next stage before all consumer warps have read the current one, -- # so each pipeline stage needs its own response slot. -- response_ptr = self._clc_response_ptr + response_stage * Int32(4) -+ # so each pipeline stage needs its own response slot. The slot -+ # array is typed Int128 in SharedStorage, so the stage index is also -+ # the element index and the 16B alignment survives the offset. -+ response_ptr = self._clc_response_ptr + response_stage - m_idx, n_idx, l_idx, is_valid = cute.arch.clc_response( - response_ptr, loc=loc, ip=ip) - cute.arch.fence_proxy("async.shared", space="cta") -@@ -239,7 +241,7 @@ class DecodeTileScheduler: - ): - if const_expr(self.params.scheduling_mode == SchedulingMode.CLC): - assert mbarrier_addr is not None -- response_ptr = self._clc_response_ptr + response_stage * Int32(4) -+ response_ptr = self._clc_response_ptr + response_stage - with cute.arch.elect_one(): - cute.arch.issue_clc_query( - mbarrier_addr, response_ptr, loc=loc, ip=ip) -diff --git a/python/fmha_sm100/cute/test_sparse_atten.py b/python/fmha_sm100/cute/test_sparse_atten.py -index 21c777e..fa48c96 100644 ---- a/python/fmha_sm100/cute/test_sparse_atten.py -+++ b/python/fmha_sm100/cute/test_sparse_atten.py -@@ -19,9 +19,11 @@ from __future__ import annotations ++"""Capability probes for the CUDA toolchain that assembles our inline PTX. ++ ++``cutlass.CUDA_VERSION`` reports the CUDA version the CuTe DSL was *built* ++against, not the version of the libNVVM/ptxas that will actually compile the ++generated device IR. Those differ whenever a wheel built against a newer CUDA ++is installed next to an older toolkit -- and when they do, version-gated inline ++PTX is emitted that the assembler cannot parse. The only diagnostic surfaced in ++that case is a bare:: ++ ++ NVVM backend compilation failed ++ libNVVM failed while compiling generated device IR. ++ ++with no mention of the offending instruction, which is extremely hard to ++diagnose from the kernel side. ++ ++``ptxas_supports()`` answers the question directly by assembling a ++one-instruction kernel with the real ptxas. That is correct across mixed ++toolkit installations and self-maintaining as instructions land in new ++releases, so gates built on it do not need to encode a CUDA version threshold ++that may turn out to be wrong. ++""" ++ ++import functools ++import os ++import shutil ++import subprocess ++import tempfile ++ ++__all__ = [ ++ "find_ptxas", ++ "toolkit_cuda_version", ++ "max_ptx_isa_version", ++ "ptxas_supports", ++] ++ ++# Highest first: the probe takes the first version ptxas accepts. ++_CANDIDATE_ISA_VERSIONS = ( ++ "9.5", "9.4", "9.3", "9.2", "9.1", "9.0", ++ "8.8", "8.7", "8.6", "8.5", "8.4", "8.3", "8.2", "8.1", "8.0", ++) ++ ++_PROBE_TIMEOUT_SECONDS = 30 ++ ++ ++@functools.lru_cache(maxsize=1) ++def find_ptxas() -> str | None: ++ """Locate the ptxas that belongs to the toolkit the DSL will use.""" ++ for var in ("CUDA_TOOLKIT_PATH", "CUDA_HOME", "CUDA_PATH"): ++ root = os.environ.get(var) ++ if root: ++ candidate = os.path.join(root, "bin", "ptxas") ++ if os.path.isfile(candidate) and os.access(candidate, os.X_OK): ++ return candidate ++ found = shutil.which("ptxas") ++ if found: ++ return found ++ candidate = "/usr/local/cuda/bin/ptxas" ++ if os.path.isfile(candidate) and os.access(candidate, os.X_OK): ++ return candidate ++ return None ++ ++ ++@functools.lru_cache(maxsize=1) ++def toolkit_cuda_version() -> tuple[int, int] | None: ++ """(major, minor) of the local ptxas, or None if it cannot be determined.""" ++ ptxas = find_ptxas() ++ if ptxas is None: ++ return None ++ try: ++ proc = subprocess.run( ++ [ptxas, "--version"], ++ capture_output=True, ++ text=True, ++ timeout=_PROBE_TIMEOUT_SECONDS, ++ ) ++ except (OSError, subprocess.SubprocessError): ++ return None ++ # "Cuda compilation tools, release 13.2, V13.2.51" ++ for token in proc.stdout.replace(",", " ").split(): ++ if token.startswith("V") and token.count(".") >= 1: ++ parts = token[1:].split(".") ++ try: ++ return int(parts[0]), int(parts[1]) ++ except (IndexError, ValueError): ++ continue ++ return None ++ ++ ++def _default_target() -> str: ++ """Arch string to probe with; matches the device we will compile for.""" ++ try: ++ import torch ++ ++ major, minor = torch.cuda.get_device_capability() ++ return f"sm_{major}{minor}a" ++ except Exception: ++ return "sm_100a" ++ ++ ++def _assemble(body: str, isa_version: str, target: str) -> bool: ++ """True iff ptxas accepts a kernel whose body is ``body``.""" ++ ptxas = find_ptxas() ++ if ptxas is None: ++ return False ++ source = ( ++ f".version {isa_version}\n" ++ f".target {target}\n" ++ ".address_size 64\n" ++ ".visible .entry _msa_probe()\n" ++ "{\n" ++ " .reg .b8 %b<8>;\n" ++ " .reg .b16 %h<8>;\n" ++ " .reg .b32 %r<8>;\n" ++ " .reg .b64 %rd<8>;\n" ++ " mov.u32 %r1, 0;\n" ++ " mov.u64 %rd1, 0;\n" ++ f"{body}\n" ++ " ret;\n" ++ "}\n" ++ ) ++ with tempfile.TemporaryDirectory() as tmp: ++ path = os.path.join(tmp, "probe.ptx") ++ with open(path, "w") as f: ++ f.write(source) ++ try: ++ proc = subprocess.run( ++ [ptxas, f"-arch={target}", path, "-o", os.path.join(tmp, "probe.cubin")], ++ capture_output=True, ++ text=True, ++ timeout=_PROBE_TIMEOUT_SECONDS, ++ ) ++ except (OSError, subprocess.SubprocessError): ++ return False ++ return proc.returncode == 0 ++ ++ ++@functools.lru_cache(maxsize=8) ++def max_ptx_isa_version(target: str | None = None) -> str | None: ++ """Highest ``.version`` the local ptxas accepts for ``target``. ++ ++ Probing the instruction at too low an ISA version would report a false ++ negative for an instruction the toolkit actually supports, so the capability ++ probe must first find the ceiling. ++ """ ++ target = target or _default_target() ++ for isa_version in _CANDIDATE_ISA_VERSIONS: ++ if _assemble("", isa_version, target): ++ return isa_version ++ return None ++ ++ ++@functools.lru_cache(maxsize=64) ++def ptxas_supports(body: str, target: str | None = None) -> bool | None: ++ """Whether ptxas assembles ``body``. ++ ++ Returns True/False when ptxas could be run, and None when it could not, so ++ callers can distinguish "unsupported" from "unknown" and fall back to a ++ version comparison rather than silently taking the slow path. ++ """ ++ if find_ptxas() is None: ++ return None ++ target = target or _default_target() ++ isa_version = max_ptx_isa_version(target) ++ if isa_version is None: ++ return None ++ return _assemble(body, isa_version, target) +diff --git a/python/fmha_sm100/cute/src/common/cute_dsl_utils.py b/python/fmha_sm100/cute/src/common/cute_dsl_utils.py +index e3473fb..dc4cfb0 100644 +--- a/python/fmha_sm100/cute/src/common/cute_dsl_utils.py ++++ b/python/fmha_sm100/cute/src/common/cute_dsl_utils.py +@@ -128,10 +128,8 @@ if os.getenv("MINIMAX_LOG_COMPILE", "0") == "1": + logger.setLevel(logging.DEBUG) - import argparse - import math -+import os - import sys - import types - from contextlib import contextmanager -+from pathlib import Path - from typing import Optional - import pytest -@@ -61,6 +63,78 @@ DECODE_DIM = 128 - DECODE_KV_TOKEN_SWEEP = tuple(2**exp for exp in range(3, 21)) +-# Monkey-patch cute.compile so every JIT compile across the repo gets timed +-# without touching individual call sites. Idempotent: only patches once. +-if cute.compile is not cute_compile_patched: +- cute.compile = cute_compile_patched ++# TensorRT-LLM shares CUTLASS across attention backends, so importing MSA must ++# not replace the process-global cute.compile callable. -+def test_prepare_paged_hnd_input_keeps_aligned_outer_page_stride() -> None: -+ pages, roles, heads, page_size, head_dim = 5, 3, 2, 128, 128 -+ pool = torch.empty( -+ pages, -+ roles, -+ heads, -+ page_size, -+ head_dim, -+ dtype=torch.float8_e4m3fn, -+ device="cuda", + def assume_strides_aligned(t): +diff --git a/python/fmha_sm100/cute/src/common/mxfp8_epi.py b/python/fmha_sm100/cute/src/common/mxfp8_epi.py +new file mode 100644 +index 0000000..b771f5d +--- /dev/null ++++ b/python/fmha_sm100/cute/src/common/mxfp8_epi.py +@@ -0,0 +1,100 @@ ++# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. ++# SPDX-License-Identifier: MIT ++"""PTX helpers for the combine's MXFP8 epilogue: the exact instructions of the CUDA quantizer ++(quantization.cuh cvt_warp_fp16_to_mxfp8), so the epilogue's E4M3 values and UE8M0 scales are bitwise those of ++mxfp8_quantize / quantize_mxfp8_rows on the same bf16 values.""" ++ ++import cutlass ++from cutlass import Float32, Int32 ++from cutlass.cutlass_dsl import T, dsl_user_op ++from cutlass._mlir.dialects import llvm ++ ++ ++def _asm(ret, args, text, cons): ++ return llvm.inline_asm( ++ ret, args, text, cons, has_side_effects=False, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT + ) -+ view = pool[:, 1] + -+ assert not view.is_contiguous() -+ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size) -+ assert prepared.data_ptr() == view.data_ptr() -+ assert prepared.stride() == view.stride() + ++@dsl_user_op ++def rcp_approx_ftz(a: Float32, *, loc=None, ip=None) -> Float32: ++ """reciprocal_approximate_ftz.""" ++ return Float32(_asm(T.f32(), [Float32(a).ir_value(loc=loc, ip=ip)], "rcp.approx.ftz.f32 $0, $1;", "=f,f")) + -+def test_prepare_paged_hnd_input_materializes_unpacked_tokens() -> None: -+ pages, heads, page_size, head_dim = 5, 2, 128, 128 -+ storage = torch.arange( -+ pages * heads * page_size * 2 * head_dim, -+ dtype=torch.int32, -+ device="cuda", -+ ).remainder(16).to(torch.float8_e4m3fn).reshape(pages, heads, page_size * 2, head_dim) -+ view = storage[:, :, ::2, :] + -+ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size) -+ assert prepared.is_contiguous() -+ assert prepared.data_ptr() != view.data_ptr() -+ torch.testing.assert_close(prepared, view, rtol=0, atol=0) ++@dsl_user_op ++def ue8m0_round_up(a: Float32, *, loc=None, ip=None) -> Int32: ++ """__nv_cvt_float_to_e8m0(a, __NV_SATFINITE, cudaRoundPosInf): the low byte of the packed pair.""" ++ return Int32( ++ _asm( ++ T.i32(), ++ [Float32(a).ir_value(loc=loc, ip=ip)], ++ "{\n.reg .b16 h;\ncvt.rp.satfinite.ue8m0x2.f32 h, $1, $1;\ncvt.u32.u16 $0, h;\n}\n", ++ "=r,f", ++ ) ++ ) & Int32(0xFF) + + -+def test_prepare_paged_hnd_input_materializes_unaligned_outer_stride() -> None: -+ pages, heads, page_size, head_dim = 5, 2, 128, 128 -+ outer_stride = heads * page_size * head_dim + 1 -+ storage = torch.arange( -+ pages * outer_stride, -+ dtype=torch.int32, -+ device="cuda", -+ ).remainder(16).to(torch.float8_e4m3fn) -+ view = storage.as_strided( -+ (pages, heads, page_size, head_dim), -+ (outer_stride, page_size * head_dim, head_dim, 1), ++@dsl_user_op ++def as_f32(a: Int32, *, loc=None, ip=None) -> Float32: ++ """Reinterpret 32 bits as fp32.""" ++ return Float32(_asm(T.f32(), [Int32(a).ir_value(loc=loc, ip=ip)], "mov.b32 $0, $1;", "=f,r")) ++ ++ ++@dsl_user_op ++def bf16x2_lo_f32(w: Int32, *, loc=None, ip=None) -> Float32: ++ """The low bf16 of a packed pair as fp32 (exact).""" ++ return Float32(_asm(T.f32(), [Int32(w).ir_value(loc=loc, ip=ip)], "shl.b32 $0, $1, 16;", "=f,r")) ++ ++ ++@dsl_user_op ++def bf16x2_hi_f32(w: Int32, *, loc=None, ip=None) -> Float32: ++ """The high bf16 of a packed pair as fp32 (exact).""" ++ return Float32(_asm(T.f32(), [Int32(w).ir_value(loc=loc, ip=ip)], "and.b32 $0, $1, 0xFFFF0000;", "=f,r")) ++ ++ ++@dsl_user_op ++def fabs_f32(a: Float32, *, loc=None, ip=None) -> Float32: ++ return Float32(_asm(T.f32(), [Float32(a).ir_value(loc=loc, ip=ip)], "abs.f32 $0, $1;", "=f,f")) ++ ++ ++@dsl_user_op ++def fmax_f32(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32: ++ return Float32( ++ _asm( ++ T.f32(), ++ [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)], ++ "max.f32 $0, $1, $2;", ++ "=f,f,f", ++ ) + ) + -+ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size) -+ assert prepared.is_contiguous() -+ assert prepared.data_ptr() != view.data_ptr() -+ torch.testing.assert_close(prepared, view, rtol=0, atol=0) + ++@dsl_user_op ++def ue8m0_to_f32(sf_bits: Int32, *, loc=None, ip=None) -> Float32: ++ """static_cast(__nv_fp8_e8m0): 0 -> 2^-127 (0x00400000), 0xFF -> NaN (0x7FFFFFFF), else bits << 23.""" ++ return Float32( ++ _asm( ++ T.f32(), ++ [Int32(sf_bits).ir_value(loc=loc, ip=ip)], ++ "{\n.reg .b32 s;\n.reg .pred z, n;\n" ++ "shl.b32 s, $1, 23;\n" ++ "setp.eq.u32 z, $1, 0;\n" ++ "setp.eq.u32 n, $1, 255;\n" ++ "selp.b32 s, 0x00400000, s, z;\n" ++ "selp.b32 s, 0x7FFFFFFF, s, n;\n" ++ "mov.b32 $0, s;\n}\n", ++ "=f,r", ++ ) ++ ) + -+def test_prepare_paged_hnd_input_defers_page_size_validation() -> None: -+ pages, roles, heads, page_size, head_dim = 5, 2, 2, 128, 128 -+ pool = torch.empty( -+ pages, -+ roles, -+ heads, -+ page_size, -+ head_dim, -+ dtype=torch.float8_e4m3fn, -+ device="cuda", ++ ++def sf_offset_128x4(m_idx, k_idx, num_k_tiles): ++ """get_sf_out_offset_128x4 (batch 0): [m tiles, k tiles, 32, 4, 4].""" ++ return ( ++ (m_idx // 128) * (num_k_tiles * 512) ++ + (k_idx // 4) * 512 ++ + (m_idx % 32) * 16 ++ + ((m_idx % 128) // 32) * 4 ++ + (k_idx % 4) + ) -+ view = pool[:, 0] +diff --git a/python/fmha_sm100/cute/src/common/tma_utils.py b/python/fmha_sm100/cute/src/common/tma_utils.py +index 5bdc19a..9df4699 100644 +--- a/python/fmha_sm100/cute/src/common/tma_utils.py ++++ b/python/fmha_sm100/cute/src/common/tma_utils.py +@@ -118,9 +118,15 @@ def prefetch_tma_desc_raw(tma_desc_ptr, *, loc=None, ip=None): + ptr_i64 = tma_desc_ptr.toint().ir_value(loc=loc, ip=ip) + ptr_i64_align_ty = cute_ir.ConstrainedIntType.get(128, ptr_i64.type.width) + ptr_i64_align = cute_ir.assume(ptr_i64_align_ty, ptr_i64, loc=loc, ip=ip) ++ # `arch.prefetch_tma_desc` is defined to take a *generic*-addressing pointer ++ # (no specific state space). Building it in the gmem address space instead ++ # passes MLIR verification -- nothing checks the address space here -- but ++ # leaves the NVVM backend with no ISel pattern for the tensormap-prefetch ++ # intrinsic on addrspace(1), so libNVVM aborts with a bare "NVVM backend ++ # compilation failed" and no location or instruction name. + ptr_ty = cute_ir.PtrType.get( + cute_nvgpu_ir.TmaDescriptorTiledType.get(), +- cute_ir.AddressSpace.gmem, ++ cute_ir.AddressSpace.generic, + 128, + ) + desc_ptr = cute_ir.inttoptr(ptr_ty, ptr_i64_align, loc=loc, ip=ip) +diff --git a/python/fmha_sm100/cute/src/common/utils.py b/python/fmha_sm100/cute/src/common/utils.py +index 10b2b1f..3b9f909 100644 +--- a/python/fmha_sm100/cute/src/common/utils.py ++++ b/python/fmha_sm100/cute/src/common/utils.py +@@ -17,8 +17,42 @@ from cutlass.cute.runtime import from_dlpack + + import quack.activation + ++from . import cuda_toolchain + -+ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size // 2) -+ assert prepared.data_ptr() == view.data_ptr() -+ with pytest.raises(ValueError, match="page_size == blk_kv"): -+ sparse_interface._prepare_paged_kv_for_tma(prepared, prepared, page_size // 2) + _MIXER_ATTRS = ("__vec_size__",) + ++# Inline-PTX capability gates. ++# ++# These instructions are not available in every CUDA toolkit, so each has a ++# portable fallback below. The gate must reflect the toolkit that will actually ++# assemble the PTX -- NOT `cutlass.CUDA_VERSION`, which is the CUDA version the ++# CuTe DSL wheel was *built* against. When a DSL built against a newer CUDA is ++# installed beside an older toolkit, trusting `cutlass.CUDA_VERSION` emits PTX ++# that ptxas cannot parse, and libNVVM reports only "NVVM backend compilation ++# failed" with no mention of the instruction. ++_PTX_PROBE_SCALED_E4M3_MUL = " mul.e4m3x4.e2m1x4.e4m3x4.satfinite %r2, %r3, %r4;" ++_PTX_PROBE_F16X2_FROM_E2M1 = " cvt.rn.f16x2.e2m1x2 %r2, %b1;" ++_PTX_PROBE_BF16X2_FROM_E2M1 = " cvt.rn.bf16x2.e2m1x2 %r2, %b1;" ++ ++# Used only when ptxas cannot be run at all, so the gate still has an answer. ++_PTX_PROBE_FALLBACK_MIN_CUDA = (13, 3) ++ ++ ++def _toolchain_supports(probe_body: str) -> bool: ++ # CuTeDSL lowers with the NVPTX compiler embedded in its wheel, then may ++ # coexist with a newer external ptxas. Both must support the instruction: ++ # checking only /usr/local/cuda/bin/ptxas can otherwise accept an opcode ++ # that the embedded compiler rejects while serializing the GPU module. ++ from cutlass import CUDA_VERSION ++ ++ if (CUDA_VERSION.major, ++ CUDA_VERSION.minor) < _PTX_PROBE_FALLBACK_MIN_CUDA: ++ return False ++ supported = cuda_toolchain.ptxas_supports(probe_body) ++ if supported is not None: ++ return supported ++ return True + + # Obtained from sollya: + # fpminimax(exp(x * log(2.0)), 1, [|1,24...|],[0;1],relative); + POLY_EX2 = { +@@ -153,7 +187,7 @@ def make_tiled_copy_B( + + + def mma_make_fragment_A( +- smem: cute.Tensor, thr_mma: cute.core.ThrMma, swapAB: cutlass.Constexpr[bool] = False ++ smem: cute.Tensor, thr_mma: cute.ThrMma, swapAB: cutlass.Constexpr[bool] = False + ) -> cute.Tensor: + if const_expr(swapAB): + return mma_make_fragment_B(smem, thr_mma) +@@ -162,7 +196,7 @@ def mma_make_fragment_A( + + + def mma_make_fragment_B( +- smem: cute.Tensor, thr_mma: cute.core.ThrMma, swapAB: cutlass.Constexpr[bool] = False ++ smem: cute.Tensor, thr_mma: cute.ThrMma, swapAB: cutlass.Constexpr[bool] = False + ) -> cute.Tensor: + if const_expr(swapAB): + return mma_make_fragment_A(smem, thr_mma) +@@ -625,6 +659,59 @@ def cvt_fp4x8_e2m1_f16x8( + ) -> Tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32]: + """Convert four packed E2M1 bytes into four packed f16x2 registers.""" + ++ if not _toolchain_supports(_PTX_PROBE_F16X2_FROM_E2M1): ++ out = llvm.inline_asm( ++ llvm.StructType.get_literal( ++ [T.i32(), T.i32(), T.i32(), T.i32()]), ++ [cutlass.Int32(src).ir_value(loc=loc, ip=ip)], ++ "{\n\t" ++ ".reg .b32 x, sel, hi, signs, tmp, zero, lut0, lut1;\n\t" ++ "mov.b32 zero, 0;\n\t" ++ # Positive E2M1 values 0, .5, 1, 1.5, 2, 3, 4, 6 expressed as ++ # the high byte of their exact FP16 representation. ++ "mov.b32 lut0, 0x3e3c3800;\n\t" ++ "mov.b32 lut1, 0x46444240;\n\t" ++ "mov.b32 x, $4;\n\t" ++ "and.b32 sel, x, 0x00007777;\n\t" ++ "prmt.b32 hi, lut0, lut1, sel;\n\t" ++ "and.b32 signs, x, 0x00000088;\n\t" ++ "mul.lo.u32 signs, signs, 0x00000110;\n\t" ++ "and.b32 signs, signs, 0x00008080;\n\t" ++ "shr.u32 tmp, x, 8;\n\t" ++ "and.b32 tmp, tmp, 0x00000088;\n\t" ++ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" ++ "and.b32 tmp, tmp, 0x00008080;\n\t" ++ "shl.b32 tmp, tmp, 16;\n\t" ++ "or.b32 signs, signs, tmp;\n\t" ++ "or.b32 hi, hi, signs;\n\t" ++ "prmt.b32 $0, zero, hi, 0x5040;\n\t" ++ "prmt.b32 $1, zero, hi, 0x7060;\n\t" ++ "shr.u32 x, $4, 16;\n\t" ++ "and.b32 sel, x, 0x00007777;\n\t" ++ "prmt.b32 hi, lut0, lut1, sel;\n\t" ++ "and.b32 signs, x, 0x00000088;\n\t" ++ "mul.lo.u32 signs, signs, 0x00000110;\n\t" ++ "and.b32 signs, signs, 0x00008080;\n\t" ++ "shr.u32 tmp, x, 8;\n\t" ++ "and.b32 tmp, tmp, 0x00000088;\n\t" ++ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" ++ "and.b32 tmp, tmp, 0x00008080;\n\t" ++ "shl.b32 tmp, tmp, 16;\n\t" ++ "or.b32 signs, signs, tmp;\n\t" ++ "or.b32 hi, hi, signs;\n\t" ++ "prmt.b32 $2, zero, hi, 0x5040;\n\t" ++ "prmt.b32 $3, zero, hi, 0x7060;\n\t" ++ "}\n", ++ "=r,=r,=r,=r,r", ++ has_side_effects=False, ++ is_align_stack=False, ++ asm_dialect=llvm.AsmDialect.AD_ATT, ++ ) ++ return tuple( ++ cutlass.Int32( ++ llvm.extractvalue(T.i32(), out, [i], loc=loc, ip=ip)) ++ for i in range(4)) + - @contextmanager - def _nvtx_range(message: str): - torch.cuda.nvtx.range_push(message) -@@ -435,12 +509,116 @@ def _install_flash_attn3_stub_for_te_import() -> None: - sys.modules.setdefault("flash_attn_3.flash_attn_interface", interface) + out = llvm.inline_asm( + llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), + [cutlass.Int32(src).ir_value(loc=loc, ip=ip)], +@@ -657,9 +744,7 @@ def cvt_fp4x8_e2m1_bf16x8( + ) -> Tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32]: + """Convert four packed E2M1 bytes into four packed bf16x2 registers.""" +- from cutlass import CUDA_VERSION +- +- if CUDA_VERSION.major > 13 or (CUDA_VERSION.major == 13 and CUDA_VERSION.minor >= 2): ++ if _toolchain_supports(_PTX_PROBE_BF16X2_FROM_E2M1): + out = llvm.inline_asm( + llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), + [cutlass.Int32(src).ir_value(loc=loc, ip=ip)], +@@ -697,15 +782,18 @@ def cvt_fp4x8_e2m1_bf16x8( + def cvt_fp4x8_e2m1_scaled_e4m3x8( + src: cutlass.Int32, + scale_e4m3: cutlass.Int32, ++ global_scale: Optional[Float32] = None, + *, + loc=None, + ip=None, + ) -> Tuple[cutlass.Int32, cutlass.Int32]: +- """Scale eight packed E2M1 values by one E4M3 byte and convert to E4M3.""" ++ """Reconstruct eight NVFP4 values before rounding them to E4M3. -+# The kernel reads exactly one scale-factor layout pair, unconditionally: K -+# linear (`t*S + s`) and V in the 4x4 token-quad swizzle -+# (`(t//4)*(4*S) + 4*s + (t%4)`). There is no third option, no runtime flag and -+# no 128x4 path left anywhere in the branch. -+NVFP4_K_SCALE_LAYOUT = "linear" -+NVFP4_V_SCALE_LAYOUT = "swizzle4x4" -+ -+ -+def _pack_synthetic_nvfp4_scale( -+ logical: torch.Tensor, -+ *, -+ layout: str, -+) -> torch.Tensor: -+ """Pack a *logical* block-scale array into the bytes the kernel reads. -+ -+ ``logical`` is indexed exactly like the interface's scale argument: -+ ``[num_pages, Hkv, page_size, S]`` when paged and ``[total_k, Hkv, S]`` -+ when flat. The result has the same shape and the same bytes, permuted -+ within each region. -+ -+ Only the *within-region* permutation comes from -+ ``quantize.pack_nvfp4_scale``. The region decomposition is re-derived here -+ from the kernel on purpose, so that a silent change of region on either -+ side surfaces as a failure rather than as agreement: -+ -+ * paged -- a region is one ``(page, head)`` pair covering ``page_size`` -+ tokens (``src/sm100/fwd/atten_fwd_nvfp4_kv.py::_scale_region_base``). -+ * flat -- a region is ``R`` consecutive global tokens of a single KV -+ head, laid out head-minor, with ``R = 1`` for ``"linear"`` and -+ ``R = 4`` for ``"swizzle4x4"`` -+ (``..._scale_region_base_flat``). ``R = 4`` requires -+ ``total_k % 4 == 0``. Flat is a test-only geometry with no production -+ producer, so it is not an ABI. -+ -+ ``"linear"`` is ``t*S + s``, i.e. plain row-major over ``[tokens, S]``, and -+ is therefore the identity for both geometries. +- from cutlass import CUDA_VERSION ++ The block-scaled intermediate can reach 6 * 448. Applying the FP32 ++ global scale after an E4M3 conversion would preserve its saturation error. + """ -+ -+ if layout == NVFP4_K_SCALE_LAYOUT: -+ return logical.contiguous() -+ if layout != NVFP4_V_SCALE_LAYOUT: -+ raise ValueError(f"unknown NVFP4 scale layout {layout!r}") -+ -+ from quantize import pack_nvfp4_scale -+ -+ if logical.ndim == 4: -+ num_pages, head_kv, page_size, scale_cols = (int(d) for d in logical.shape) -+ regions = logical.reshape(num_pages * head_kv, page_size, scale_cols) -+ packed = pack_nvfp4_scale( -+ regions.contiguous(), -+ page_size=page_size, -+ scale_cols=scale_cols, -+ layout=layout, -+ ) -+ return packed.reshape(num_pages, head_kv, page_size, scale_cols).contiguous() -+ -+ if logical.ndim != 3: -+ raise ValueError( -+ "logical NVFP4 scales must be rank-4 [num_pages, Hkv, page_size, S] " -+ f"or rank-3 [total_k, Hkv, S], got shape {tuple(logical.shape)}" -+ ) -+ total_k, head_kv, scale_cols = (int(d) for d in logical.shape) -+ if total_k % 4 != 0: -+ raise ValueError( -+ "the flat V swizzle tiles tokens in quads, so total_k must be a " -+ f"multiple of 4, got {total_k}" -+ ) -+ regions = ( -+ logical.reshape(total_k // 4, 4, head_kv, scale_cols) -+ .permute(0, 2, 1, 3) -+ .reshape(total_k // 4 * head_kv, 4, scale_cols) -+ .contiguous() -+ ) -+ packed = pack_nvfp4_scale( -+ regions, -+ page_size=4, -+ scale_cols=scale_cols, -+ layout=layout, + +- if CUDA_VERSION.major > 13 or (CUDA_VERSION.major == 13 and CUDA_VERSION.minor >= 2): ++ if global_scale is None and _toolchain_supports(_PTX_PROBE_SCALED_E4M3_MUL): + out = llvm.inline_asm( + llvm.StructType.get_literal([T.i32(), T.i32()]), + [ +@@ -731,44 +819,91 @@ def cvt_fp4x8_e2m1_scaled_e4m3x8( + out1 = cutlass.Int32(llvm.extractvalue(T.i32(), out, [1], loc=loc, ip=ip)) + return out0, out1 + ++ # Keep the E4M3 pack in the established operand-constrained helper below. ++ # CUDA 13.1's embedded NVPTX compiler rejects the equivalent conversion ++ # when its E4M3x2 destination is a local .b16 register in this larger asm. + out = llvm.inline_asm( +- llvm.StructType.get_literal([T.i32(), T.i32()]), ++ llvm.StructType.get_literal([T.f32()] * 8), + [ + cutlass.Int32(src).ir_value(loc=loc, ip=ip), + cutlass.Int32(scale_e4m3).ir_value(loc=loc, ip=ip), + ], + "{\n\t" +- ".reg .b32 sf_bytes, sf_f16x2;\n\t" +- ".reg .b16 sf_pair, e0, e1, e2, e3;\n\t" +- ".reg .b8 byte0, byte1, byte2, byte3;\n\t" ++ ".reg .b32 sf_bytes, sf_f16x2, x, sel, hi, signs, tmp, zero, lut0, lut1;\n\t" ++ ".reg .b16 sf_pair;\n\t" ++ ".reg .b16 h0_lo, h0_hi, h1_lo, h1_hi, h2_lo, h2_hi, h3_lo, h3_hi;\n\t" + ".reg .b32 h0, h1, h2, h3;\n\t" +- "prmt.b32 sf_bytes, $3, 0, 0;\n\t" ++ "prmt.b32 sf_bytes, $9, 0, 0;\n\t" + "mov.b32 {sf_pair, _}, sf_bytes;\n\t" + "cvt.rn.f16x2.e4m3x2 sf_f16x2, sf_pair;\n\t" +- "mov.b32 {byte0, byte1, byte2, byte3}, $2;\n\t" +- "cvt.rn.f16x2.e2m1x2 h0, byte0;\n\t" +- "cvt.rn.f16x2.e2m1x2 h1, byte1;\n\t" +- "cvt.rn.f16x2.e2m1x2 h2, byte2;\n\t" +- "cvt.rn.f16x2.e2m1x2 h3, byte3;\n\t" ++ # Decode four E2M1 nibbles at a time through a byte lookup. The ++ # positive FP16 high bytes are 00,38,3c,3e,40,42,44,46; the sign bit ++ # is expanded from each nibble into the corresponding byte's MSB. ++ "mov.b32 zero, 0;\n\t" ++ "mov.b32 lut0, 0x3e3c3800;\n\t" ++ "mov.b32 lut1, 0x46444240;\n\t" ++ "mov.b32 x, $8;\n\t" ++ "and.b32 sel, x, 0x00007777;\n\t" ++ "prmt.b32 hi, lut0, lut1, sel;\n\t" ++ "and.b32 signs, x, 0x00000088;\n\t" ++ "mul.lo.u32 signs, signs, 0x00000110;\n\t" ++ "and.b32 signs, signs, 0x00008080;\n\t" ++ "shr.u32 tmp, x, 8;\n\t" ++ "and.b32 tmp, tmp, 0x00000088;\n\t" ++ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" ++ "and.b32 tmp, tmp, 0x00008080;\n\t" ++ "shl.b32 tmp, tmp, 16;\n\t" ++ "or.b32 signs, signs, tmp;\n\t" ++ "or.b32 hi, hi, signs;\n\t" ++ "prmt.b32 h0, zero, hi, 0x5040;\n\t" ++ "prmt.b32 h1, zero, hi, 0x7060;\n\t" ++ "shr.u32 x, $8, 16;\n\t" ++ "and.b32 sel, x, 0x00007777;\n\t" ++ "prmt.b32 hi, lut0, lut1, sel;\n\t" ++ "and.b32 signs, x, 0x00000088;\n\t" ++ "mul.lo.u32 signs, signs, 0x00000110;\n\t" ++ "and.b32 signs, signs, 0x00008080;\n\t" ++ "shr.u32 tmp, x, 8;\n\t" ++ "and.b32 tmp, tmp, 0x00000088;\n\t" ++ "mul.lo.u32 tmp, tmp, 0x00000110;\n\t" ++ "and.b32 tmp, tmp, 0x00008080;\n\t" ++ "shl.b32 tmp, tmp, 16;\n\t" ++ "or.b32 signs, signs, tmp;\n\t" ++ "or.b32 hi, hi, signs;\n\t" ++ "prmt.b32 h2, zero, hi, 0x5040;\n\t" ++ "prmt.b32 h3, zero, hi, 0x7060;\n\t" + "mul.rn.f16x2 h0, h0, sf_f16x2;\n\t" + "mul.rn.f16x2 h1, h1, sf_f16x2;\n\t" + "mul.rn.f16x2 h2, h2, sf_f16x2;\n\t" + "mul.rn.f16x2 h3, h3, sf_f16x2;\n\t" +- "cvt.rn.satfinite.e4m3x2.f16x2 e0, h0;\n\t" +- "cvt.rn.satfinite.e4m3x2.f16x2 e1, h1;\n\t" +- "cvt.rn.satfinite.e4m3x2.f16x2 e2, h2;\n\t" +- "cvt.rn.satfinite.e4m3x2.f16x2 e3, h3;\n\t" +- "mov.b32 $0, {e0, e1};\n\t" +- "mov.b32 $1, {e2, e3};\n\t" ++ "mov.b32 {h0_lo, h0_hi}, h0;\n\t" ++ "mov.b32 {h1_lo, h1_hi}, h1;\n\t" ++ "mov.b32 {h2_lo, h2_hi}, h2;\n\t" ++ "mov.b32 {h3_lo, h3_hi}, h3;\n\t" ++ "cvt.f32.f16 $0, h0_lo;\n\t" ++ "cvt.f32.f16 $1, h0_hi;\n\t" ++ "cvt.f32.f16 $2, h1_lo;\n\t" ++ "cvt.f32.f16 $3, h1_hi;\n\t" ++ "cvt.f32.f16 $4, h2_lo;\n\t" ++ "cvt.f32.f16 $5, h2_hi;\n\t" ++ "cvt.f32.f16 $6, h3_lo;\n\t" ++ "cvt.f32.f16 $7, h3_hi;\n\t" + "}\n", +- "=r,=r,r,r", ++ "=f,=f,=f,=f,=f,=f,=f,=f,r,r", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + ) +- out0 = cutlass.Int32(llvm.extractvalue(T.i32(), out, [0], loc=loc, ip=ip)) +- out1 = cutlass.Int32(llvm.extractvalue(T.i32(), out, [1], loc=loc, ip=ip)) +- return out0, out1 ++ values = [ ++ Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) ++ for i in range(8) ++ ] ++ if global_scale is not None: ++ values = [value * global_scale for value in values] ++ return ( ++ cvt_fp8x4_e4m3_f32(*values[:4], loc=loc, ip=ip), ++ cvt_fp8x4_e4m3_f32(*values[4:], loc=loc, ip=ip), + ) -+ return packed.reshape(total_k, head_kv, scale_cols).contiguous() + + + @dsl_user_op +diff --git a/python/fmha_sm100/cute/src/sm100/build_k2q_csr/build_k2q_csr.cu b/python/fmha_sm100/cute/src/sm100/build_k2q_csr/build_k2q_csr.cu +index 8ee5457..428b5a3 100644 +--- a/python/fmha_sm100/cute/src/sm100/build_k2q_csr/build_k2q_csr.cu ++++ b/python/fmha_sm100/cute/src/sm100/build_k2q_csr/build_k2q_csr.cu +@@ -27,6 +27,10 @@ + #include + + #include ++#include ++#include ++#include ++#include + + #define CHECK_CUDA(x) TORCH_CHECK((x).is_cuda(), #x " must be CUDA") + #define CHECK_CONTIGUOUS(x) TORCH_CHECK((x).is_contiguous(), #x " must be contiguous") +@@ -196,6 +200,79 @@ __global__ void k2q_hist_kernel( + // --------------------------------------------------------------------------- + // PR: row prefix. One block per head. + // --------------------------------------------------------------------------- ++template ++__global__ void k2q_row_prefix_agg_kernel( ++ int const* __restrict__ row_counts, ++ int* __restrict__ row_ptr, ++ int const* __restrict__ row_coords, ++ int* __restrict__ scheduler_metadata, ++ int* __restrict__ work_count, ++ int total_rows, ++ int target_q_per_cta, ++ int work_capacity) ++{ ++ // Same row_ptr as k2q_row_prefix_kernel. Work items are claimed with one atomic per warp per 32-row group ++ // (the order of scheduler_metadata entries was already atomic-order, i.e. unspecified). ++ int h = blockIdx.x; ++ int tid = threadIdx.x; ++ int lane = tid & 31; ++ __shared__ int scan_buf[kThreads]; ++ int const* head_counts = row_counts + (size_t)h * total_rows; ++ int* head_rowptr = row_ptr + (size_t)h * (total_rows + 1); ++ int chunk = (total_rows + kThreads - 1) / kThreads; ++ int lo = tid * chunk; ++ int hi = min(lo + chunk, total_rows); ++ int local_sum = 0; ++ for (int i = lo; i < hi; ++i) local_sum += head_counts[i]; ++ scan_buf[tid] = local_sum; ++ __syncthreads(); ++ for (int off = 1; off < kThreads; off <<= 1) { ++ int add = (tid >= off) ? scan_buf[tid - off] : 0; ++ __syncthreads(); ++ scan_buf[tid] += add; ++ __syncthreads(); ++ } ++ int running = scan_buf[tid] - local_sum; ++ for (int i = lo; i < hi; ++i) { ++ running += head_counts[i]; ++ head_rowptr[i + 1] = running; ++ } ++ if (scheduler_metadata == nullptr || work_count == nullptr) return; ++ // Work items: rows strided by thread so each warp instruction covers 32 consecutive rows. ++ for (int i0 = 0; i0 < total_rows; i0 += kThreads) { ++ int i = i0 + tid; ++ int row_count = i < total_rows ? head_counts[i] : 0; ++ int num_chunks = row_count > 0 ? (row_count + target_q_per_cta - 1) / target_q_per_cta : 0; ++ int x = num_chunks; ++ #pragma unroll ++ for (int off = 1; off < 32; off <<= 1) { ++ int nbr = __shfl_up_sync(0xFFFFFFFFu, x, off); ++ if (lane >= off) x += nbr; ++ } ++ int warp_total = __shfl_sync(0xFFFFFFFFu, x, 31); ++ int base = 0; ++ if (lane == 31 && warp_total > 0) base = atomicAdd(work_count, warp_total); ++ base = __shfl_sync(0xFFFFFFFFu, base, 31) + x - num_chunks; ++ if (num_chunks > 0) { ++ int batch_idx = row_coords[(size_t)i * 2]; ++ int kv_block_idx = row_coords[(size_t)i * 2 + 1]; ++ for (int c = 0; c < num_chunks; ++c) { ++ int work_idx = base + c; ++ if (work_idx < work_capacity) { ++ int q_begin = c * target_q_per_cta; ++ int* meta = scheduler_metadata + (size_t)work_idx * 6; ++ meta[0] = h; ++ meta[1] = i; ++ meta[2] = q_begin; ++ meta[3] = min(target_q_per_cta, row_count - q_begin); ++ meta[4] = batch_idx; ++ meta[5] = kv_block_idx; ++ } ++ } ++ } ++ } ++} + + template + __global__ void k2q_row_prefix_kernel( + int const* __restrict__ row_counts, +@@ -256,6 +333,194 @@ __global__ void k2q_row_prefix_kernel( + } + } + ++// --------------------------------------------------------------------------- ++// MiniMax-M3 (MSA) edge-rank build (kill: FMHA_K2Q_EDGE_RANK=0): hist in the scatter's lane layout (lanes = ++// (q pair, slot)); each edge's per-warp rank comes from __match_any_sync + popc (lane order = q order), not from ++// the order of same-address atomics, which CUDA leaves unspecified (the stock scatter relies on it). Each edge keeps ++// its per-warp rank in registers (q_per_warp <= 2 * kIters); after the CTA sync the per-warp counts become an exclusive ++// cross-warp prefix in SMEM (warp order = q order), so rank + prefix = the edge's q-ordered rank inside the CTA ++// tile. Stored per edge (int16); the scatter is then a flat per-edge kernel with no SMEM and no atomics. ++// --------------------------------------------------------------------------- ++template ++__global__ void k2q_hist_rank_kernel( ++ int const* __restrict__ q2k, int const* __restrict__ cu_q, int const* __restrict__ row_map, ++ int* __restrict__ row_counts, int* __restrict__ tile_counts, short* __restrict__ edge_rank, ++ int H, int B, int S_Q, int total_rows, int max_kv_blocks, int q_per_cta, int q_per_warp) ++{ ++ constexpr int kQPerIter = kWarpSize / kTopK; ++ constexpr int kThreads = kWarps * kWarpSize; ++ extern __shared__ int smem_hist_int[]; ++ int tid = threadIdx.x; ++ int warp_id = tid >> 5; ++ int lane = tid & 31; ++ int c = blockIdx.x; ++ int q_start_cta = c * q_per_cta; ++ int q_end_cta = min(q_start_cta + q_per_cta, S_Q); ++ int q_start_warp = min(q_start_cta + warp_id * q_per_warp, q_end_cta); ++ int q_end_warp = min(q_start_warp + q_per_warp, q_end_cta); ++ int q_in_iter = lane / kTopK; ++ int slot_in_q = lane % kTopK; ++ int packed_per_warp = (total_rows + 1) >> 1; ++ int* my_hist = smem_hist_int + warp_id * packed_per_warp; ++ ++ for (int h = 0; h < H; ++h) { ++ for (int i = lane; i < packed_per_warp; i += kWarpSize) my_hist[i] = 0; ++ __syncwarp(); ++ int const* head_q2k = q2k + (size_t)h * S_Q * kTopK; ++ int row[kIters]; ++ int rank[kIters]; ++ int bi = 0; ++ #pragma unroll ++ for (int it = 0; it < kIters; ++it) { ++ int qi = q_start_warp + it * kQPerIter + q_in_iter; ++ row[it] = -1; ++ rank[it] = 0; ++ if (qi < q_end_warp) { ++ advance_batch_only(cu_q, B, qi, bi); ++ int kvb = head_q2k[(size_t)qi * kTopK + slot_in_q]; ++ if (kvb >= 0 && kvb < max_kv_blocks) { ++ int r = row_map[(size_t)bi * max_kv_blocks + kvb]; ++ if (r >= 0 && r < total_rows) row[it] = r; ++ } ++ } ++ } ++ // Deterministic per-warp rank (no reliance on the order of same-address atomics): the lanes holding the ++ // same row in this step are matched; rank = warp base for that row + earlier matching lanes (lane order = ++ // q order). The group leader adds the group size with one atomic whose return is the base; __syncwarp ++ // orders the warp's successive steps. ++ unsigned int const lt_mask = lane == 0 ? 0u : ((1u << lane) - 1u); ++ #pragma unroll ++ for (int it = 0; it < kIters; ++it) { ++ int r = row[it]; ++ unsigned int peers = __match_any_sync(0xFFFFFFFFu, r >= 0 ? r : -1 - lane); ++ int leader = __ffs(peers) - 1; ++ int base = 0; ++ if (r >= 0 && lane == leader) { ++ int shift = (r & 1) << 4; ++ base = (atomicAdd(&my_hist[r >> 1], __popc(peers) << shift) >> shift) & 0xFFFF; ++ } ++ base = __shfl_sync(0xFFFFFFFFu, base, leader); ++ rank[it] = base + __popc(peers & lt_mask); ++ __syncwarp(); ++ } ++ __syncthreads(); ++ // Exclusive cross-warp prefix in place (packed int16 words add without carry: per-CTA row count ++ // <= q_per_cta < 32768), CTA totals -> tile_counts [G, H, rows] + row_counts. ++ int* cta_tile = tile_counts + ((size_t)c * H + h) * total_rows; ++ int* head_row_counts = row_counts + (size_t)h * total_rows; ++ for (int j = tid; j < packed_per_warp; j += kThreads) { ++ int running = 0; ++ #pragma unroll ++ for (int w = 0; w < kWarps; ++w) { ++ int v = smem_hist_int[w * packed_per_warp + j]; ++ smem_hist_int[w * packed_per_warp + j] = running; ++ running += v; ++ } ++ int r0 = 2 * j, s0 = running & 0xFFFF, s1 = (running >> 16) & 0xFFFF; ++ cta_tile[r0] = s0; ++ if (s0 > 0) atomicAdd(&head_row_counts[r0], s0); ++ if (r0 + 1 < total_rows) { ++ cta_tile[r0 + 1] = s1; ++ if (s1 > 0) atomicAdd(&head_row_counts[r0 + 1], s1); ++ } ++ } ++ __syncthreads(); ++ short* head_rank = edge_rank + (size_t)h * S_Q * kTopK; ++ #pragma unroll ++ for (int it = 0; it < kIters; ++it) { ++ int qi = q_start_warp + it * kQPerIter + q_in_iter; ++ if (row[it] >= 0) ++ head_rank[(size_t)qi * kTopK + slot_in_q] = (short)(rank[it] + read_int16_packed(my_hist, row[it])); ++ } ++ if (h + 1 < H) __syncthreads(); ++ } ++} + - def _make_synthetic_nvfp4_tensor( - shape: tuple[int, ...], - *, -+ layout: str, - global_scale_value: float = 1.0, -+ generator: Optional[torch.Generator] = None, - ) -> object: -- """Create deterministic packed NVFP4 data with unit block/global scales.""" -+ """Create deterministic packed NVFP4 data with *varying* block scales. ++template ++__global__ void k2q_scatter_rank_kernel( ++ int const* __restrict__ q2k, int const* __restrict__ cu_q, int const* __restrict__ row_map, ++ int const* __restrict__ abs_base, short const* __restrict__ edge_rank, ++ int* __restrict__ q_idx, int* __restrict__ qsplit_idx, int* __restrict__ split_counts, ++ int H, int B, int S_Q, int total_rows, int max_kv_blocks, int q_per_cta) ++{ ++ long long e = (long long)blockIdx.x * blockDim.x + threadIdx.x; // e = (h * S_Q + q) * kTopK + slot ++ long long n = (long long)H * S_Q * kTopK; ++ int lane = threadIdx.x & 31; ++ bool in = e < n; ++ int slot = (int)(e % kTopK); ++ long long hq = e / kTopK; ++ int q = in ? (int)(hq % S_Q) : 0; ++ int h = in ? (int)(hq / S_Q) : 0; ++ int row = -1, qloc = 0; ++ if (in) { ++ int lo = 0, hi = B - 1; ++ while (lo < hi) { int mid = (lo + hi + 1) >> 1; if (cu_q[mid] <= q) lo = mid; else hi = mid - 1; } ++ qloc = q - cu_q[lo]; ++ int kvb = q2k[e]; ++ if (kvb >= 0 && kvb < max_kv_blocks) { ++ int r = row_map[(size_t)lo * max_kv_blocks + kvb]; ++ if (r >= 0 && r < total_rows) row = r; ++ } ++ } ++ bool valid = row >= 0; ++ unsigned int vmask = __ballot_sync(0xFFFFFFFFu, valid); ++ unsigned int gmask = (kTopK >= 32) ? 0xFFFFFFFFu : (((1u << kTopK) - 1u) << ((lane / kTopK) * kTopK)); ++ unsigned int lower = lane == 0 ? 0u : ((1u << lane) - 1u); ++ int split_slot = __popc(vmask & gmask & lower); ++ if (!in) return; ++ if (split_counts != nullptr && slot == 0) split_counts[(size_t)q * H + h] = __popc(vmask & gmask); ++ if (!valid) return; ++ int c = q / q_per_cta; ++ int pos = abs_base[((size_t)c * H + h) * total_rows + row] + (int)edge_rank[e]; ++ size_t o = (size_t)h * S_Q * kTopK + pos; ++ q_idx[o] = qloc; ++ if (qsplit_idx != nullptr) qsplit_idx[o] = qloc | ((split_slot & 0xFF) << 24); ++} + -+ The block scales must vary for these tests to mean anything: with every -+ scale byte set to the same value, permuting the whole scale array leaves -+ the dequantized result bit-identical, so a wrong scale-layout decode in the -+ kernel is undetectable. Varying scales make the layout observable. ++// MiniMax-M3 (MSA): the work-item emission of k2q_row_prefix_agg_kernel on a multi-CTA grid (rows x heads) ++// instead of H CTAs. Same per-warp claims; only the (already atomic) order of the items changes. ++__global__ void k2q_sched_emit_kernel( ++ int const* __restrict__ row_counts, ++ int const* __restrict__ row_coords, ++ int* __restrict__ scheduler_metadata, ++ int* __restrict__ work_count, ++ int total_rows, ++ int target_q_per_cta, ++ int work_capacity) ++{ ++ int h = blockIdx.y; ++ int i = blockIdx.x * blockDim.x + threadIdx.x; ++ int lane = threadIdx.x & 31; ++ int row_count = i < total_rows ? row_counts[(size_t)h * total_rows + i] : 0; ++ int num_chunks = row_count > 0 ? (row_count + target_q_per_cta - 1) / target_q_per_cta : 0; ++ int x = num_chunks; ++ #pragma unroll ++ for (int off = 1; off < 32; off <<= 1) { ++ int nbr = __shfl_up_sync(0xFFFFFFFFu, x, off); ++ if (lane >= off) x += nbr; ++ } ++ int warp_total = __shfl_sync(0xFFFFFFFFu, x, 31); ++ int base = 0; ++ if (lane == 31 && warp_total > 0) base = atomicAdd(work_count, warp_total); ++ base = __shfl_sync(0xFFFFFFFFu, base, 31) + x - num_chunks; ++ if (num_chunks == 0) return; ++ int batch_idx = row_coords[(size_t)i * 2]; ++ int kv_block_idx = row_coords[(size_t)i * 2 + 1]; ++ for (int c = 0; c < num_chunks; ++c) { ++ int work_idx = base + c; ++ if (work_idx < work_capacity) { ++ int q_begin = c * target_q_per_cta; ++ int* meta = scheduler_metadata + (size_t)work_idx * 6; ++ meta[0] = h; ++ meta[1] = i; ++ meta[2] = q_begin; ++ meta[3] = min(target_q_per_cta, row_count - q_begin); ++ meta[4] = batch_idx; ++ meta[5] = kv_block_idx; ++ } ++ } ++} + -+ Bytes 0x30..0x3E are positive E4M3 values in [0.5, 1.875] -- no NaN, zero -+ or denormal -- so the reference stays well conditioned. + // --------------------------------------------------------------------------- + // PT_smem: SMEM-staged tile prefix scan. + // Each block handles kRowsPerBlock rows for one head h. Cooperative load +@@ -521,6 +786,49 @@ __global__ void k2q_scatter_kernel( + // Host orchestration + // =========================================================================== + ++// MiniMax-M3 (MSA) F2 host-cost cut (SM107 only, eager only): the pipeline's five scratch buffers (row_counts, ++// row_map, row_coords, tile_counts, edge_rank) are slices of one per-device int32 arena that grows on demand instead of ++// five allocations per call (row_counts zeroed by a memset instead of torch::zeros), the SM count is read once per ++// device, and cudaFuncSetAttribute is called only when a kernel's requested dynamic SMEM differs from the value last set ++// (stock sets it on every call; the attribute state is the same). Every user of the arena runs on the caller's current ++// stream, so reuse is stream-ordered; a capturing stream takes the stock allocations. Same kernels, same launches. ++// Kill: FMHA_K2Q_WS_ARENA=0. ++static bool k2q_arena_enabled() { ++ static bool const on = [] { ++ char const* env = std::getenv("FMHA_K2Q_WS_ARENA"); ++ bool const v = env == nullptr || std::atoi(env) != 0; ++ std::fprintf(stderr, "[fmha_sm100] k2q CSR build: scratch arena %s (FMHA_K2Q_WS_ARENA)\n", v ? "on" : "off (stock)"); ++ return v; ++ }(); ++ return on; ++} + -+ The scales are drawn in *logical* ``[..., S]`` order and only then packed, -+ so the same seed produces the same logical scale for a given -+ ``(token, scale_col)`` under every layout. Filling the *physical* array -+ with random bytes instead -- which is what the 128x4 version of this helper -+ did -- would make the logical scales a permutation of each other and no two -+ layouts would ever agree. ++// Leaked on purpose: a static tensor array would free CUDA memory during static destruction, after the context is gone. ++static torch::Tensor* const k2q_arena_slots = new torch::Tensor[64]; ++static cudaStream_t k2q_arena_stream[64] = {}; ++static bool k2q_arena_bound[64] = {}; // the default stream is a null handle, so binding needs its own flag + -+ Pass ``generator=`` when the draw must be independent of how many global -+ RNG draws the surrounding input builder happened to make; the golden gate -+ below depends on that. -+ """ ++static torch::Tensor k2q_arena_take(int dev, torch::TensorOptions const& opts, int64_t words) { ++ torch::Tensor& a = k2q_arena_slots[dev & 63]; ++ if (!a.defined() || a.numel() < words) { ++ int64_t const grow = a.defined() ? std::max(words, a.numel() + a.numel() / 2) : words; ++ a = torch::empty({grow}, opts); ++ } ++ return a; ++} ++ ++// Every set is recorded (cached or not), so a cached skip always matches the attribute's current value. ++static void k2q_set_max_dyn_smem(bool cached, int dev, void const* fn, int bytes) { ++ static std::mutex mu; ++ static std::unordered_map last[64]; ++ std::lock_guard lock(mu); ++ auto& m = last[dev & 63]; ++ auto it = m.find(fn); ++ if (cached && it != m.end() && it->second == bytes) return; ++ AT_CUDA_CHECK(cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes)); ++ m[fn] = bytes; ++} ++ + template + static void launch_pipeline( + torch::Tensor q2k, +@@ -554,15 +862,13 @@ static void launch_pipeline( + (size_t)H * S_Q * kTopK * sizeof(int), stream)); + + auto opts = torch::TensorOptions().dtype(torch::kInt32).device(device); +- auto row_counts = torch::zeros({H, total_rows}, opts); +- auto row_map = torch::empty({B, max_kv_blocks}, opts); ++ torch::Tensor row_counts, row_map, row_coords; // allocated below, once the tile grid is known + bool emit_schedule = scheduler_metadata.defined(); +- auto row_coords = emit_schedule ? torch::empty({total_rows, 2}, opts) : torch::Tensor(); + int* scheduler_metadata_ptr = emit_schedule ? scheduler_metadata.data_ptr() : nullptr; + int* work_count_ptr = emit_schedule ? work_count.data_ptr() : nullptr; + int* qsplit_idx_ptr = emit_schedule ? qsplit_idx.data_ptr() : nullptr; + int* split_counts_ptr = emit_schedule ? split_counts.data_ptr() : nullptr; +- int* row_coords_ptr = emit_schedule ? row_coords.data_ptr() : nullptr; ++ int* row_coords_ptr = nullptr; + if (emit_schedule) { + AT_CUDA_CHECK(cudaMemsetAsync(work_count_ptr, 0, sizeof(int), stream)); + AT_CUDA_CHECK(cudaMemsetAsync( +@@ -571,9 +877,39 @@ static void launch_pipeline( + } - from quantize import Nvfp4QuantizedTensor + int dev = q2k.get_device(); ++ // The MiniMax-M3 k2q changes below (min q per CTA, edge-rank, multi-CTA emission, row-prefix claims, the scratch ++ // arena) are validated on SM107 only; SM100 / SM103 keep the stock pipeline and allocations. SM107 loads the sm_100 ++ // build, so this is a runtime check, resolved once per device (host code only; the device code is unchanged). ++ static signed char sm107_by_dev[64] = {}; // 0 unknown, 1 SM107, 2 other ++ signed char& sm107_state = sm107_by_dev[dev & 63]; ++ if (sm107_state == 0) { ++ int cc_major = 0, cc_minor = 0; ++ AT_CUDA_CHECK(cudaDeviceGetAttribute(&cc_major, cudaDevAttrComputeCapabilityMajor, dev)); ++ AT_CUDA_CHECK(cudaDeviceGetAttribute(&cc_minor, cudaDevAttrComputeCapabilityMinor, dev)); ++ sm107_state = (cc_major == 10 && cc_minor == 7) ? 1 : 2; ++ } ++ bool const is_sm107 = sm107_state == 1; ++ bool use_arena = false; ++ if (is_sm107 && k2q_arena_enabled()) { ++ cudaStreamCaptureStatus capture = cudaStreamCaptureStatusNone; ++ AT_CUDA_CHECK(cudaStreamIsCapturing(stream, &capture)); ++ // The arena is bound to the first stream that uses it; any other stream takes the stock allocations, so ++ // reuse stays stream-ordered. ++ if (capture == cudaStreamCaptureStatusNone && !k2q_arena_bound[dev & 63]) { ++ k2q_arena_stream[dev & 63] = stream; ++ k2q_arena_bound[dev & 63] = true; ++ } ++ use_arena = capture == cudaStreamCaptureStatusNone && k2q_arena_stream[dev & 63] == stream; ++ } + int num_sms = 0; +- AT_CUDA_CHECK(cudaDeviceGetAttribute( +- &num_sms, cudaDevAttrMultiProcessorCount, dev)); ++ static int num_sms_by_dev[64] = {}; ++ if (use_arena && num_sms_by_dev[dev & 63] > 0) { ++ num_sms = num_sms_by_dev[dev & 63]; ++ } else { ++ AT_CUDA_CHECK(cudaDeviceGetAttribute( ++ &num_sms, cudaDevAttrMultiProcessorCount, dev)); ++ num_sms_by_dev[dev & 63] = num_sms; ++ } -@@ -448,21 +626,26 @@ def _make_synthetic_nvfp4_tensor( - raise ValueError("NVFP4 synthetic shape requires D divisible by 16") - rows = math.prod(int(dim) for dim in shape[:-1]) - scale_cols = int(shape[-1]) // 16 -- padded_rows = ((rows + 127) // 128) * 128 -- padded_cols = ((scale_cols + 3) // 4) * 4 -+ draw = {} if generator is None else {"generator": generator} - data = torch.randint( - 0, - 256, - (*shape[:-1], shape[-1] // 2), - device="cuda", - dtype=torch.uint8, -+ **draw, - ) -- scale_128x4 = torch.full( -- (padded_rows, padded_cols), -- 0x38, -+ # Drawn as rank-2 [rows, S] and reshaped, not drawn in the final rank: the -+ # golden capture script draws it that way, and only an identical draw makes -+ # the two comparable. -+ logical_scale = torch.randint( -+ 0x30, -+ 0x3F, -+ (rows, scale_cols), - device="cuda", - dtype=torch.uint8, -- ) -+ **draw, -+ ).reshape(*shape[:-1], scale_cols) - global_scale = torch.full( - (1,), - float(global_scale_value), -@@ -471,27 +654,62 @@ def _make_synthetic_nvfp4_tensor( - ) - return Nvfp4QuantizedTensor( - data=data, -- scale_128x4=scale_128x4, -+ scale=_pack_synthetic_nvfp4_scale(logical_scale, layout=layout), - global_scale=global_scale, - logical_scale_shape=(rows, scale_cols), -- original_shape=shape, -+ original_shape=tuple(shape), -+ layout=layout, - ) + // -- Pick kWarps per CTA based on SMEM budget for cursor/hist --------- + // SMEM per CTA = kWarps * total_rows * sizeof(int) (for both H and S). +@@ -596,26 +932,86 @@ static void launch_pipeline( + int max_ctas_per_sm = std::max( + 1, (228 * 1024) / std::max(1, per_cta_smem_bytes)); + if (max_ctas_per_sm > 8) max_ctas_per_sm = 8; +- constexpr int kMinQPerCta = 256; ++ // MiniMax-M3 (MSA): 128 query tokens per CTA (stock 256) doubles the hist / scatter grid at long context, where ++ // the per-warp row histograms make each CTA latency-bound; the CSR (row_ptr, q_idx, qsplit, split_counts) is ++ // bitwise the stock one, since rows stay q-ascending whatever the tile split. Kill: FMHA_K2Q_MIN_Q_PER_CTA=256. ++ static int const kMinQPerCta = [] { ++ char const* env = std::getenv("FMHA_K2Q_MIN_Q_PER_CTA"); ++ int const v = (env != nullptr && std::atoi(env) > 0) ? std::atoi(env) : 128; ++ std::fprintf(stderr, "[fmha_sm100] k2q CSR build: %d query tokens per CTA (FMHA_K2Q_MIN_Q_PER_CTA)\n", v); ++ return v; ++ }(); + // Cap target_g at num_sms * 3 — empirically this balances + // per-CTA work-size against parallelism. Higher caps regress + // mid-size cases due to row_counts atomicAdd contention and + // smaller q_per_cta. SMEM-bound configurations naturally cap + // lower if max_ctas_per_sm < 3. + int target_g = num_sms * std::min(max_ctas_per_sm, 3); +- int max_g_for_q = (S_Q + kMinQPerCta - 1) / kMinQPerCta; ++ int const min_q_per_cta = is_sm107 ? kMinQPerCta : 256; // SM107 only; stock 256 elsewhere ++ int max_g_for_q = (S_Q + min_q_per_cta - 1) / min_q_per_cta; + int G = std::min({target_g, max_g_for_q, S_Q}); + if (G < 1) G = 1; + int q_per_cta = (S_Q + G - 1) / G; + G = (S_Q + q_per_cta - 1) / q_per_cta; + int q_per_warp = (q_per_cta + kWarps_pick - 1) / kWarps_pick; +- int G_total = G * kWarps_pick; +- +- auto tile_counts = torch::empty({G_total, H, total_rows}, opts); ++ // MiniMax-M3 (MSA) edge-rank build: per-CTA tiles, deterministic per-edge ranks, flat scatter (see ++ // k2q_hist_rank_kernel). Same CSR as the per-warp pipeline. Kill: FMHA_K2Q_EDGE_RANK=0. ++ static bool const kEdgeRankOn = [] { ++ char const* env = std::getenv("FMHA_K2Q_EDGE_RANK"); ++ bool const on = env == nullptr || std::atoi(env) != 0; ++ std::fprintf(stderr, "[fmha_sm100] k2q CSR build: edge-rank %s (FMHA_K2Q_EDGE_RANK)\n", on ? "on" : "off (stock)"); ++ return on; ++ }(); ++ // Work items emitted on a (rows x heads) grid instead of H CTAs; order was already atomic-order. ++ // Kill: FMHA_K2Q_SCHED_PAR=0. ++ static bool const kSchedPar = [] { ++ char const* env = std::getenv("FMHA_K2Q_SCHED_PAR"); ++ bool const on = env == nullptr || std::atoi(env) != 0; ++ std::fprintf(stderr, "[fmha_sm100] k2q CSR build: multi-CTA work emission %s (FMHA_K2Q_SCHED_PAR)\n", ++ on ? "on" : "off (stock)"); ++ return on; ++ }(); ++ bool const kEdgeRank = is_sm107 && kEdgeRankOn && kTopK == 16 && kWarps_pick == 4 && q_per_warp <= 32; // SM107 only ++ int G_total = kEdgeRank ? G : G * kWarps_pick; ++ ++ torch::Tensor tile_counts, edge_rank_ws; ++ if (use_arena) { ++ auto pad = [](int64_t w) { return (w + 31) / 32 * 32; }; // 128-byte aligned slices ++ int64_t const n_rc = (int64_t)H * total_rows; ++ int64_t const n_rm = (int64_t)B * max_kv_blocks; ++ int64_t const n_co = emit_schedule ? (int64_t)total_rows * 2 : 0; ++ int64_t const n_tc = (int64_t)G_total * H * total_rows; ++ int64_t const n_er = kEdgeRank ? ((int64_t)H * S_Q * kTopK + 1) / 2 : 0; // int16 entries in int32 words ++ int64_t const o_rm = pad(n_rc), o_co = o_rm + pad(n_rm), o_tc = o_co + pad(n_co), o_er = o_tc + pad(n_tc); ++ torch::Tensor arena = k2q_arena_take(dev, opts, o_er + pad(n_er)); ++ row_counts = arena.narrow(0, 0, n_rc).view({H, total_rows}); ++ AT_CUDA_CHECK(cudaMemsetAsync(row_counts.data_ptr(), 0, (size_t)n_rc * sizeof(int), stream)); ++ row_map = arena.narrow(0, o_rm, n_rm).view({B, max_kv_blocks}); ++ if (emit_schedule) row_coords = arena.narrow(0, o_co, n_co).view({total_rows, 2}); ++ tile_counts = arena.narrow(0, o_tc, n_tc).view({G_total, H, total_rows}); ++ if (kEdgeRank) edge_rank_ws = arena.narrow(0, o_er, n_er); ++ } else { ++ row_counts = torch::zeros({H, total_rows}, opts); ++ row_map = torch::empty({B, max_kv_blocks}, opts); ++ if (emit_schedule) row_coords = torch::empty({total_rows, 2}, opts); ++ tile_counts = torch::empty({G_total, H, total_rows}, opts); ++ } ++ row_coords_ptr = emit_schedule ? row_coords.data_ptr() : nullptr; + + // -- Compile-time switch on kWarps for the templated kernels --------- + auto rmap_fn = k2q_build_row_map_kernel; +- auto rprefix_fn = k2q_row_prefix_kernel<1024>; ++ // MiniMax-M3 (MSA): work items are claimed with one atomic per warp (a warp prefix sum of the per-row chunk ++ // counts) instead of one per row. Only the order of scheduler_metadata entries changes, which was already ++ // atomic-order in stock; the attention consumer is order-invariant (O/LSE bitwise under permuted orders). ++ // Kill: FMHA_K2Q_ROW_PREFIX_AGG=0. ++ static bool const kRowPrefixAgg = [] { ++ char const* env = std::getenv("FMHA_K2Q_ROW_PREFIX_AGG"); ++ bool const on = env == nullptr || std::atoi(env) != 0; ++ std::fprintf(stderr, "[fmha_sm100] k2q CSR build: row-prefix work claims %s (FMHA_K2Q_ROW_PREFIX_AGG)\n", ++ on ? "warp-aggregated" : "per row (stock)"); ++ return on; ++ }(); ++ auto rprefix_fn = (is_sm107 && kRowPrefixAgg) ? k2q_row_prefix_agg_kernel<1024> : k2q_row_prefix_kernel<1024>; // SM107 only + constexpr int kPtRowsPerBlock = 8; + constexpr int kPtThreads = 256; + auto tprefix_smem_fn = k2q_tile_prefix_smem_kernel; +@@ -630,24 +1026,54 @@ static void launch_pipeline( + size_t smem_bytes = (size_t)W * per_warp_smem; + auto hist_fn = k2q_hist_kernel; + auto scat_fn = k2q_scatter_kernel; +- AT_CUDA_CHECK(cudaFuncSetAttribute( +- hist_fn, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_bytes)); +- AT_CUDA_CHECK(cudaFuncSetAttribute( +- scat_fn, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_bytes)); +- +- hist_fn<<>>( +- q2k.data_ptr(), cu_q.data_ptr(), row_map.data_ptr(), +- row_counts.data_ptr(), tile_counts.data_ptr(), +- H, B, S_Q, total_rows, max_kv_blocks, q_per_cta, q_per_warp); ++ k2q_set_max_dyn_smem(use_arena, dev, (void const*)hist_fn, (int)smem_bytes); ++ k2q_set_max_dyn_smem(use_arena, dev, (void const*)scat_fn, (int)smem_bytes); ++ ++ torch::Tensor edge_rank; ++ if constexpr (W == 4 && kTopK == 16) { ++ if (kEdgeRank) { ++ edge_rank = use_arena ? edge_rank_ws : torch::empty({(long long)H * S_Q * kTopK}, opts.dtype(torch::kInt16)); ++ // More warps per CTA (the tiles are per CTA, so the CSR does not depend on it): the rank pass is ++ // latency-bound at 4 warps. 16 / 8 / 4 warps by SMEM (warps x packed rows) and q per CTA. ++ int rw = 16; ++ while (rw > 4 && ((size_t)rw * per_warp_smem > 200 * 1024 || (q_per_cta + rw - 1) / rw < 2)) rw >>= 1; ++ int qpw = (q_per_cta + rw - 1) / rw; ++ auto go = [&](auto kern, int warps) { ++ size_t sb = (size_t)warps * per_warp_smem; ++ k2q_set_max_dyn_smem(use_arena, dev, (void const*)kern, (int)sb); ++ kern<<>>( ++ q2k.data_ptr(), cu_q.data_ptr(), row_map.data_ptr(), ++ row_counts.data_ptr(), tile_counts.data_ptr(), ++ reinterpret_cast(edge_rank.data_ptr()), ++ H, B, S_Q, total_rows, max_kv_blocks, q_per_cta, (q_per_cta + warps - 1) / warps); ++ }; ++ if (rw == 16 && qpw <= 8) go(k2q_hist_rank_kernel, 16); ++ else if (rw >= 8 && (q_per_cta + 7) / 8 <= 16) go(k2q_hist_rank_kernel, 8); ++ else go(k2q_hist_rank_kernel, 4); ++ } ++ } ++ if (!kEdgeRank) { ++ hist_fn<<>>( ++ q2k.data_ptr(), cu_q.data_ptr(), row_map.data_ptr(), ++ row_counts.data_ptr(), tile_counts.data_ptr(), ++ H, B, S_Q, total_rows, max_kv_blocks, q_per_cta, q_per_warp); ++ } + ++ bool const par = is_sm107 && kSchedPar && emit_schedule; // SM107 only + rprefix_fn<<>>( + row_counts.data_ptr(), row_ptr.data_ptr(), + emit_schedule ? row_coords.data_ptr() : nullptr, +- scheduler_metadata_ptr, +- work_count_ptr, ++ par ? nullptr : scheduler_metadata_ptr, ++ par ? nullptr : work_count_ptr, + total_rows, + target_q_per_cta, + work_capacity); ++ if (par) { ++ dim3 eg((total_rows + 255) / 256, H); ++ k2q_sched_emit_kernel<<>>( ++ row_counts.data_ptr(), row_coords.data_ptr(), scheduler_metadata_ptr, work_count_ptr, ++ total_rows, target_q_per_cta, work_capacity); ++ } + + // Grid is H * blocks_per_h so each block stays within a single + // head; flat (H*total_rows) grid would skip rows when total_rows +@@ -656,19 +1082,26 @@ static void launch_pipeline( + int pt_grid = H * blocks_per_h; + if (pt_grid < 1) pt_grid = 1; + size_t pt_smem = (size_t)kPtRowsPerBlock * G_total * sizeof(int); +- AT_CUDA_CHECK(cudaFuncSetAttribute( +- tprefix_smem_fn, cudaFuncAttributeMaxDynamicSharedMemorySize, +- (int)pt_smem)); ++ k2q_set_max_dyn_smem(use_arena, dev, (void const*)tprefix_smem_fn, (int)pt_smem); + tprefix_smem_fn<<>>( + tile_counts.data_ptr(), row_ptr.data_ptr(), + H, total_rows, G_total); + +- scat_fn<<>>( +- q2k.data_ptr(), cu_q.data_ptr(), row_map.data_ptr(), +- tile_counts.data_ptr(), q_idx.data_ptr(), +- qsplit_idx_ptr, split_counts_ptr, +- H, B, S_Q, total_rows, max_kv_blocks, q_per_cta, q_per_warp, +- max_seqlen_q); ++ if (kEdgeRank) { ++ long long ne = (long long)H * S_Q * kTopK; ++ k2q_scatter_rank_kernel<<<(unsigned)((ne + 255) / 256), 256, 0, stream>>>( ++ q2k.data_ptr(), cu_q.data_ptr(), row_map.data_ptr(), ++ tile_counts.data_ptr(), reinterpret_cast(edge_rank.data_ptr()), ++ q_idx.data_ptr(), qsplit_idx_ptr, split_counts_ptr, ++ H, B, S_Q, total_rows, max_kv_blocks, q_per_cta); ++ } else { ++ scat_fn<<>>( ++ q2k.data_ptr(), cu_q.data_ptr(), row_map.data_ptr(), ++ tile_counts.data_ptr(), q_idx.data_ptr(), ++ qsplit_idx_ptr, split_counts_ptr, ++ H, B, S_Q, total_rows, max_kv_blocks, q_per_cta, q_per_warp, ++ max_seqlen_q); ++ } + }; + + if (kWarps_pick == 4) { +diff --git a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py +index f5950f3..caad594 100644 +--- a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py ++++ b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd.py +@@ -1939,8 +1939,8 @@ class SparseAttentionForwardSm100: + self, + tiled_mma_qk: cute.TiledMma, + tiled_mma_pv: cute.TiledMma, +- thr0_qk: cute.core.ThrMma, +- thr0_pv: cute.core.ThrMma, ++ thr0_qk: cute.ThrMma, ++ thr0_pv: cute.ThrMma, + tStS: cute.Tensor, + tOrP: cute.Tensor, + sK: cute.Tensor, +diff --git a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py +index ba930a6..25c4537 100644 +--- a/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py ++++ b/python/fmha_sm100/cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py +@@ -9,7 +9,8 @@ forward contract: + - varlen Q metadata via `cu_seqlens_q` + - BF16 Q + - packed NVFP4 K/V data +-- E4M3 per-1x16 K/V scales in cuBLAS/cuDNN 128x4 tiled layout ++- E4M3 per-1x16 K/V scales in vLLM's byte order: K linear, V 4x4 token-quad ++ swizzled, addressed through host-supplied per-page / per-head byte strides + - FP32 per-tensor K/V global scales + """ +@@ -28,6 +29,7 @@ from cutlass.cutlass_dsl import BaseDSL + + from quack import copy_utils + ++from src.common.aot_cache import r2_store_enabled + from src.common.cute_dsl_utils import assume_tensor_aligned + from src.common import utils + from src.common import pipeline +@@ -139,10 +141,18 @@ class SparseAttentionForwardNvfp4KvSm100: + self.store_warp_base = self.softmax1_warp_base + self.warps_per_group + self.mma_warp_id = self.store_warp_base + self.warps_per_group + self.load_warp_base = self.mma_warp_id + 1 +- self.q_load_warp_base = self.store_warp_base ++ # R2 store WG (SM107 only, see aot_cache.r2_store_enabled): warps 8-11 drain partial O/LSE for every q-group ++ # while the softmax WGs move on; the Q load then runs on warp 15 (formerly empty). ++ # TRTLLM_MSA_DISABLE_R2STORE=1, or any other device, keeps the stock in-softmax epilogue. ++ self.r2_store = r2_store_enabled() ++ self.q_load_warp_base = ( ++ self.load_warp_base + 2 if self.r2_store else self.store_warp_base) + self.kv_load_warp_base = self.load_warp_base + self.num_kv_load_warps = 2 +- self.num_q_load_warps = self.warps_per_group ++ self.num_q_load_warps = 1 if self.r2_store else self.warps_per_group ++ # Softmax stats ring: with the store WG, 2 slots per softmax stage ++ # (meta = qi_group & 3); stock uses one slot per stage. ++ self.sm_meta_stages = 4 if self.r2_store else self.o_stage + self.total_warps = 16 + self.threads_per_cta = cute.arch.WARP_SIZE * self.total_warps # 512 + +@@ -297,8 +307,8 @@ class SparseAttentionForwardNvfp4KvSm100: + self, + mK: cute.Tensor, # packed NVFP4: flat [total_k, head_kv, dim/2] or paged [page, head_kv, token, dim/2] + mV: cute.Tensor, # packed NVFP4: flat [total_k, head_kv, dim/2] or paged [page, head_kv, token, dim/2] +- mKScale: cute.Tensor, # E4M3 uint8, 128x4 tiled over flattened K rows and dim/16 cols +- mVScale: cute.Tensor, # E4M3 uint8, 128x4 tiled over flattened V rows and dim/16 cols ++ mKScale: cute.Tensor, # E4M3 uint8 K block scales, linear inside each (page, head) region ++ mVScale: cute.Tensor, # E4M3 uint8 V block scales, 4x4 token-quad swizzled inside the region + mKGlobalScale: Optional[cute.Tensor], # optional FP32 tensor/global dequant scale + mVGlobalScale: Optional[cute.Tensor], # optional FP32 tensor/global dequant scale + mK2qIndices: cute.Tensor, # csr payload: [head_kv, nnz] +@@ -321,6 +331,17 @@ class SparseAttentionForwardNvfp4KvSm100: + num_heads_kv: Int32, + seq_len_q: Int32, + work_capacity: Int32, ++ # Block-scale region strides, in BYTES. For the paged cache these are ++ # the stride of a whole vLLM page (data bytes included, 73728 B at M3 ++ # geometry) and the stride of one KV head inside that page. They are ++ # Int32 kernel arguments; every product built from them is Int64 ++ # (see `_scale_region_base`). Ignored when `paged_kv=False`, where the ++ # region is derived from `num_heads_kv` instead -- see ++ # `_scale_region_base_flat`. ++ k_sf_page_stride: Int32, ++ k_sf_head_stride: Int32, ++ v_sf_page_stride: Int32, ++ v_sf_head_stride: Int32, + stream=None, + ): + self.q_dtype = mQ_flat.element_type +@@ -358,9 +379,11 @@ class SparseAttentionForwardNvfp4KvSm100: + not in [Float32, cutlass.BFloat16, cutlass.Float16, cutlass.Float8E4M3FN] + ): + raise TypeError(f"Unsupported O_partial dtype: {self.o_dtype}") +- mK, mV, mKScale, mVScale = [ +- assume_tensor_aligned(t) for t in (mK, mV, mKScale, mVScale) +- ] ++ # Only the packed FP4 data tensors may claim 128-bit aligned strides: ++ # the block scales' 8 B token stride would break that promise. The ++ # scale readers therefore do raw pointer arithmetic off ++ # `scale.iterator` and never index the tensor -- keep them that way. ++ mK, mV = [assume_tensor_aligned(t) for t in (mK, mV)] --def _quantize_bf16_to_nvfp4_or_skip(x: torch.Tensor) -> object: -+def _quantize_bf16_to_nvfp4_with_layout(x: torch.Tensor, layout: str) -> object: -+ """Quantize one tensor to NVFP4 under an explicitly chosen SF layout. -+ -+ Used both for the correct layout and -- by the negative controls -- for the -+ wrong one. The kernel has no layout flag, so packing on the host with the -+ wrong ``layout=`` is the only way to build a mismatched input. -+ """ + if const_expr(not self.paged_kv): + # Flat varlen K/V: +@@ -516,18 +539,18 @@ class SparseAttentionForwardNvfp4KvSm100: + mbar_p: cute.struct.MemRange[Int64, self.s_stage * 2] + mbar_p_lastsplit: cute.struct.MemRange[Int64, self.s_stage * 2] + mbar_o: cute.struct.MemRange[Int64, self.o_stage * 2] +- mbar_sm_stats: cute.struct.MemRange[Int64, self.o_stage * 2] ++ mbar_sm_stats: cute.struct.MemRange[Int64, self.sm_meta_stages * 2] + tmem_dealloc_mbar_ptr: Int64 + tmem_holding_buf: Int32 + # Per-row softmax stats cache (for epilogue LSE + rescale): + # [0 : m_block_size) row_sum + # [m_block_size : 2*m_block_size) row_max + sScale: cute.struct.MemRange[ +- Float32, self.o_stage * self.m_block_size * 2] ++ Float32, self.sm_meta_stages * self.m_block_size * 2] + # Per-row temperature LSE row_sum cache. The row_max is shared with + # sScale because lse_temperature_scale is positive. + sScaleTemperature: cute.struct.MemRange[ +- Float32, self.o_stage * self.m_block_size] ++ Float32, self.sm_meta_stages * self.m_block_size] + # Per-token split_id from prepare-time per-edge metadata. + sSplitIdx: cute.struct.MemRange[ + Int32, self.o_stage * self.q_tokens_per_group] +@@ -588,6 +611,8 @@ class SparseAttentionForwardNvfp4KvSm100: + tiled_mma_qk, tiled_mma_pv, + k_fp4_tma_bytes, v_fp4_tma_bytes, q_tma_bytes, q_subtile_bytes, + num_kv_blocks, num_heads_kv, seq_len_q, work_capacity, ++ k_sf_page_stride, k_sf_head_stride, ++ v_sf_page_stride, v_sf_head_stride, + ).launch( + grid=(num_ctas,), + block=[self.threads_per_cta, 1, 1], +@@ -653,6 +678,11 @@ class SparseAttentionForwardNvfp4KvSm100: + num_heads_kv: Int32, + seq_len_q: Int32, + work_capacity: Int32, ++ # Block-scale region strides, in bytes (see `__call__`). ++ k_sf_page_stride: Int32, ++ k_sf_head_stride: Int32, ++ v_sf_page_stride: Int32, ++ v_sf_head_stride: Int32, + ): + # ------------------------------------------------------------------ + # Thread / warp identity, CTA coordinate +@@ -709,9 +739,9 @@ class SparseAttentionForwardNvfp4KvSm100: + sQ = storage.sQ.get_tensor(sQ_layout.outer, swizzle=sQ_layout.inner) + sQ_load = storage.sQ.get_tensor(sQ_load_layout.outer, swizzle=sQ_load_layout.inner) + sScale = storage.sScale.get_tensor( +- cute.make_layout(self.o_stage * self.m_block_size * 2)) ++ cute.make_layout(self.sm_meta_stages * self.m_block_size * 2)) + sScaleTemperature = storage.sScaleTemperature.get_tensor( +- cute.make_layout(self.o_stage * self.m_block_size)) ++ cute.make_layout(self.sm_meta_stages * self.m_block_size)) + sSplitIdx = storage.sSplitIdx.get_tensor( + cute.make_layout((self.o_stage * self.q_tokens_per_group,))) + sQIdx = storage.sQIdx.get_tensor( +@@ -731,7 +761,8 @@ class SparseAttentionForwardNvfp4KvSm100: + # ------------------------------------------------------------------ + # TMEM allocator — allocator warp 0 serves the whole CTA. + # ------------------------------------------------------------------ +- tmem_alloc_warps: cutlass.Constexpr[int] = self.warps_per_group * 2 + 1 ++ tmem_alloc_warps: cutlass.Constexpr[int] = ( ++ self.warps_per_group * (3 if self.r2_store else 2) + 1) + tmem_alloc_threads = cute.arch.WARP_SIZE * tmem_alloc_warps + tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=int(NamedBarrierFwdSm100.TmemPtr), +@@ -799,7 +830,7 @@ class SparseAttentionForwardNvfp4KvSm100: + ) + pipeline_sm_stats = pipeline.PipelineAsync.create( + barrier_storage=storage.mbar_sm_stats.data_ptr(), +- num_stages=self.o_stage, ++ num_stages=self.sm_meta_stages, + producer_group=softmax_threads, + consumer_group=epilogue_threads, + defer_sync=True, +@@ -941,7 +972,8 @@ class SparseAttentionForwardNvfp4KvSm100: + num_threads=cute.arch.WARP_SIZE * self.warps_per_group, + ) + if ( +- warp_idx == Int32(self.total_warps - 1) ++ warp_idx == Int32( ++ self.total_warps if self.r2_store else self.total_warps - 1) + and warp_idx >= Int32(self.kv_load_warp_base + self.num_kv_load_warps) + ): + cute.arch.setmaxregister_decrease(self.num_regs_empty) +@@ -952,7 +984,9 @@ class SparseAttentionForwardNvfp4KvSm100: + ) + is_q_load_thread = tidx >= q_load_thread_base and tidx < q_load_thread_end + if is_q_load_thread and cta_valid_work: +- if self.store_reg_decrease: ++ if self.r2_store: ++ cute.arch.setmaxregister_decrease(self.num_regs_empty) ++ elif self.store_reg_decrease: + cute.arch.setmaxregister_decrease(self.num_regs_store) + else: + cute.arch.setmaxregister_increase(self.num_regs_store) +@@ -1056,6 +1090,49 @@ class SparseAttentionForwardNvfp4KvSm100: + tmem.free(tmem_ptr, num_columns=tmem_cols) + cute.arch.griddepcontrol_launch_dependents() + ++ if const_expr(self.r2_store): ++ if ( ++ warp_idx >= Int32(self.store_warp_base) ++ and warp_idx < Int32(self.store_warp_base + self.warps_per_group) ++ and cta_valid_work ++ ): ++ if self.store_reg_decrease: ++ cute.arch.setmaxregister_decrease(self.num_regs_store) ++ else: ++ cute.arch.setmaxregister_increase(self.num_regs_store) ++ count_raw_store = sRowMeta[3] ++ has_work_store = count_raw_store > Int32(0) ++ num_q_groups_store = ( ++ count_raw_store + Int32(self.q_tokens_per_group - 1) ++ ) // Int32(self.q_tokens_per_group) ++ tmem.wait_for_alloc() ++ tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype) ++ self._wg_store( ++ tiled_mma_pv, ++ sScale, ++ sScaleTemperature, ++ sSplitIdx, ++ sQIdx, ++ sQIdxMeta, ++ pipeline_o, ++ pipeline_sm_stats, ++ sm_stats_barrier, ++ epilogue_barrier, ++ mO_partial, mLSE_partial, mLSE_temperature_partial, ++ softmax_scale_log2, ++ lse_temperature_scale_log2, ++ mVGlobalScale, ++ num_q_groups_store, count_raw_store, has_work_store, ++ sRowMeta[0], ++ head_kv_idx, ++ seq_len_q, ++ head_q, ++ num_heads_kv, ++ sRowMeta[5], ++ mQ_2d, ++ ) ++ tmem_alloc_barrier.arrive() + - _install_flash_attn3_stub_for_te_import() -- from quantize import quantize_bf16_to_nvfp4_128x4 -+ from quantize import quantize_bf16_to_nvfp4 + if ( + warp_idx >= Int32(self.softmax0_warp_base) + and warp_idx < Int32(self.softmax1_warp_base) +@@ -1085,6 +1162,8 @@ class SparseAttentionForwardNvfp4KvSm100: + head_kv_idx, kv_block_idx_softmax, + sRowMeta[6], + num_heads_kv, ++ k_sf_page_stride, ++ k_sf_head_stride, + ) + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype) +@@ -1152,6 +1231,9 @@ class SparseAttentionForwardNvfp4KvSm100: + head_kv_idx, kv_block_idx_softmax, + sRowMeta[6], + num_heads_kv, ++ v_sf_page_stride, ++ v_sf_head_stride, ++ kv_valid_cols_softmax, + ) + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype) +@@ -1193,66 +1275,147 @@ class SparseAttentionForwardNvfp4KvSm100: + # Warp-specialized helpers + # ------------------------------------------------------------------ -- try: -- return quantize_bf16_to_nvfp4_128x4(x) -- except RuntimeError as exc: -- pytest.skip(str(exc)) -+ return quantize_bf16_to_nvfp4(x, layout=layout) -+ ++ # ------------------------------------------------------------------ ++ # NVFP4 block-scale (scale-factor) addressing ++ # ++ # One unconditional layout pair -- the byte order vLLM's NVFP4 KV store ++ # kernel already writes (csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu). ++ # S = D/16 scale columns per token, `t` the token index inside a ++ # (page, head) region: ++ # ++ # K, linear (:162) off = t*S + s ++ # V, 4x4 swizzle (:25-39) off = (t>>2)*(4*S) + (s<<2) + (t&3) ++ # ++ # The old cuBLAS/cuDNN 128x4 tiling is DELETED: it is the block-scaled ++ # tcgen05 MMA operand format and this kernel runs no block-scaled MMA. ++ # ------------------------------------------------------------------ + -+def _quantize_kv_bf16_to_nvfp4(k: torch.Tensor, v: torch.Tensor) -> tuple[object, object]: -+ """Quantize a BF16 K/V pair for the NVFP4 KV path. + @cute.jit +- def _scale_128x4_offset( ++ def _scale_region_base( + self, +- row: Int32, +- col: Int32, +- scale_cols: cutlass.Constexpr[int], +- ) -> Int32: +- tiles_n: cutlass.Constexpr[int] = (scale_cols + 3) // 4 +- tile_m = row // Int32(128) +- tile_n = col // Int32(4) +- outer = row % Int32(128) +- inner = col % Int32(4) ++ page_idx: Int32, ++ head_kv_idx: Int32, ++ sf_page_stride: Int32, ++ sf_head_stride: Int32, ++ ) -> Int64: ++ """Byte offset of one (page, head) scale region from the tensor base. + -+ K is packed linear and V with the 4x4 token-quad swizzle, which is the one -+ layout pair the kernel reads. ++ MUST be Int64: `sf_page_stride` spans a WHOLE vLLM page, data bytes ++ included, so page_idx * stride overflows Int32 on a large KV cache ++ (the strides themselves fit, only the product does not). ++ """ + return ( +- (tile_m * Int32(tiles_n) + tile_n) * Int32(512) +- + (outer % Int32(32)) * Int32(16) +- + (outer // Int32(32)) * Int32(4) +- + inner ++ Int64(page_idx) * Int64(sf_page_stride) ++ + Int64(head_kv_idx) * Int64(sf_head_stride) + ) + + @cute.jit +- def _load_scale_bf16x2( ++ def _scale_region_base_flat( + self, +- scale: cute.Tensor, +- logical_row: Int32, +- scale_col: Int32, +- ) -> Int32: +- scale_offset = self._scale_128x4_offset( +- logical_row, +- scale_col, +- self.head_dim // 16, ++ token_global: Int32, ++ head_kv_idx: Int32, ++ num_heads_kv: Int32, ++ tokens_per_region: cutlass.Constexpr[int], ++ ) -> Int64: ++ """Region base for flat (non-paged) varlen KV; test path only, not an ABI. + -+ This deliberately does not skip on error. It used to swallow any -+ ``RuntimeError`` from the quantizer and call ``pytest.skip``, which turned a -+ missing Transformer Engine into 141 green-looking skips and silently removed -+ *all* NVFP4 accuracy coverage on machines that have the hardware -- and would -+ equally have hidden a genuine quantizer bug. The quantizer now has a -+ dependency-free PyTorch backend, so there is nothing left to be unavailable -+ and a raised error here is a real defect. -+ """ ++ base = (token_global // R) * (Hkv * R * S) + head * (R * S) + -+ _install_flash_attn3_stub_for_te_import() -+ from quantize import quantize_kv_bf16_to_nvfp4 ++ R = 1 for K, R = 4 for V (the 4x4 swizzle needs a whole token quad; ++ requires total_k % 4 == 0). Host strides are deliberately not ++ consulted -- nothing on the host owns this geometry. ++ """ ++ S: cutlass.Constexpr[int] = self.head_dim // 16 ++ R: cutlass.Constexpr[int] = int(tokens_per_region) ++ assert R > 0 and (R & (R - 1)) == 0, "tokens_per_region must be a power of two" ++ shift: cutlass.Constexpr[int] = R.bit_length() - 1 ++ region_idx = token_global >> Int32(shift) ++ return Int64(region_idx * num_heads_kv + head_kv_idx) * Int64(R * S) + -+ return quantize_kv_bf16_to_nvfp4(k, v) - - - def _dequant_nvfp4_to_bf16(qx: object, *, include_global_scale: bool = True) -> torch.Tensor: -- from quantize import dequantize_nvfp4_128x4_to_bf16 -+ """Reference dequantization. ++ @cute.jit ++ def _scale_offset_linear(self, token: Int32, scale_col: Int32) -> Int32: ++ """K: `t*S + s`, byte offset inside a (page, head) region.""" ++ S: cutlass.Constexpr[int] = self.head_dim // 16 ++ return token * Int32(S) + scale_col + -+ Layout-independent by construction: it reads ``qx.layout`` and undoes -+ whatever packing produced ``qx.scale``, so the same logical block scales -+ give the same BF16 K/V no matter how the FP4 kernel addresses the bytes. -+ That is what lets the BF16 reference stand as an absolute gate across the -+ layout change. -+ """ ++ @cute.jit ++ def _scale_offset_swizzle4x4(self, token: Int32, scale_col: Int32) -> Int32: ++ """V: `(t>>2)*(4*S) + (s<<2) + (t&3)`, byte offset inside a region.""" ++ S: cutlass.Constexpr[int] = self.head_dim // 16 ++ return ( ++ (token >> Int32(2)) * Int32(4 * S) ++ + (scale_col << Int32(2)) ++ + (token & Int32(3)) + ) + -+ from quantize import dequantize_nvfp4_to_bf16 - -- return dequantize_nvfp4_128x4_to_bf16( -+ return dequantize_nvfp4_to_bf16( - qx, - include_global_scale=include_global_scale, - ) -@@ -1130,7 +1348,16 @@ def _decode_paged_dense_reference( - inputs: dict[str, object], - *, - chunk_tokens: int = 8192, -+ p_dtype: torch.dtype | None = torch.float8_e4m3fn, - ) -> tuple[torch.Tensor, torch.Tensor]: -+ """Reference decode attention. ++ @cute.jit ++ def _load_scale_byte(self, scale: cute.Tensor, byte_offset: Int64) -> Int32: ++ """One E4M3 block-scale byte, by raw pointer arithmetic. + -+ ``p_dtype`` selects the rounding applied to unnormalized P. The default -+ (e4m3) models the kernel. ``p_dtype=None`` skips that rounding entirely -+ and yields the same reference with its own P-quantization noise removed; -+ ``_assert_fp8_forward_close`` uses the difference of the two as a measured -+ noise floor. See the derivation in that function. -+ """ - q = inputs["q"].float() - k_paged = inputs["k_paged"] - v_paged = inputs["v_paged"] -@@ -1231,7 +1458,11 @@ def _decode_paged_dense_reference( - # normalized probabilities here would model a different - # rounding point and overstate the kernel error for short-KV - # decode rows. -- p_unnorm = exp_scores.to(torch.float8_e4m3fn).float() -+ p_unnorm = ( -+ exp_scores -+ if p_dtype is None -+ else exp_scores.to(p_dtype).float() -+ ) - out_cur += torch.einsum("hst,td->shd", p_unnorm, v_chunk) - out_cur = out_cur / safe_row_sum.transpose(0, 1).unsqueeze(-1) ++ Must not touch `scale.layout`: the 8 B token stride breaks the 16 B ++ alignment promise, so indexing the tensor would be live UB. ++ """ + scale_ptr = cute.make_ptr( + cutlass.Uint8, +- scale.iterator.toint() + Int64(scale_offset), ++ scale.iterator.toint() + byte_offset, + mem_space=scale.iterator.memspace, + assumed_align=1, + ) +- scale_byte = cute.make_tensor(scale_ptr, cute.make_layout(1))[0] +- return utils.cvt_fp8_e4m3_to_bf16x2_replicated(cutlass.Int32(scale_byte)) ++ return cutlass.Int32(cute.make_tensor(scale_ptr, cute.make_layout(1))[0]) -@@ -1342,18 +1573,167 @@ def _assert_fp8_forward_close( - lse: torch.Tensor, - lse_ref: torch.Tensor, - partial_is_fp8: bool = False, -+ out_ref_unquantized_p: torch.Tensor | None = None, - ) -> None: -+ out_ref_f = out_ref.float() - out_ref_bf16 = out_ref.to(torch.bfloat16).float() -- bf16_floor = (out_ref_bf16 - out_ref.float()).abs().max().item() -- kernel_diff = (out.float() - out_ref_bf16).abs().max().item() -- # QK/LSE should be tight. O additionally includes P(e4m3) @ V(e4m3) -- # with hardware FP8 MMA accumulation, so allow the observed PV rounding -- # envelope up through topK=32 rather than a bf16-only floor. -- # With fp8 O_partial, each split additionally quantizes the partial output -- # to e4m3 before combine; this adds another ~6% relative error per split -- # and pushes the worst-case |diff| up to ~0.5 on the standard cases. -- floor = 5.0e-1 if partial_is_fp8 else 1.25e-1 -- assert kernel_diff <= max(floor, 4.0 * bf16_floor) -+ bf16_err = out_ref_bf16 - out_ref_f -+ bf16_floor = bf16_err.abs().max().item() -+ bf16_rms_floor = bf16_err.pow(2).mean().sqrt().item() -+ diff = out.float() - out_ref_bf16 -+ kernel_diff = diff.abs().max().item() -+ diff_rms = diff.pow(2).mean().sqrt().item() -+ out_scale = out_ref_bf16.abs().max().item() -+ out_rms = out_ref_bf16.pow(2).mean().sqrt().item() -+ # QK/LSE should be tight. O additionally includes P(e4m3) @ V(e4m3) with -+ # hardware FP8 MMA accumulation, so it needs a slacker bound -- but that -+ # bound has to be RELATIVE to |O|. It used to be the bare constant 0.125 -+ # (0.5 with fp8 O_partial), which is not scale-invariant: it silently gets -+ # stricter as the data grows. Making the synthetic NVFP4 block scales vary -+ # over [0.5, 1.875] instead of being pinned at 1.0 raised max|O| by 1.75x -+ # and raised |diff| by the same factor at *constant* relative error -+ # (measured 1.4-1.9% of max|O| in every scale window from constant-0x38 to -+ # 0x30-0x3E), and that alone flipped the test to failing. A relative bound -+ # would not have moved. -+ # -+ # Error model for the constant. P is rounded to E4M3, which carries 3 -+ # explicit mantissa bits, so its round-to-nearest relative error is at most -+ # 2**-4. The kernel and the reference arrive at P by different roundings, -+ # so any P entry may land one E4M3 step away; O = sum_j P_j V_j / sum_j P_j -+ # is a convex combination of V rows, so that carries into O as the same -+ # relative perturbation. With fp8 O_partial every split additionally -+ # re-quantizes the partial output to E4M3 before the combine, which -+ # empirically costs ~4x more (measured max 12.4% vs 4.3% relative) -- the -+ # same 4x the two old constants encoded, now expressed relatively. -+ # -+ # Calibration: 561 measurements over the fp8 and NVFP4 test set give a -+ # worst observed relative error of 4.35% (441 bf16-O_partial cases) and -+ # 12.38% (120 fp8-O_partial cases), i.e. 1.4x and 2.0x of headroom below -+ # the bounds used here. The 4 * bf16_floor term is the reference's own -+ # bf16 storage floor; bf16 keeps 8 significand bits, so it is bounded by -+ # 4 * 2**-8 * max|O| = 1.6% * max|O| and is scale-invariant too. The -+ # headroom figures above count only the rtol term, so they are lower -+ # bounds on the real margin. -+ # -+ # The rtol term above is *only* valid while the reference's own P entries -+ # stay inside E4M3's normal range. They do not, for long-KV decode. The -+ # reference normalizes P by the GLOBAL row max, so p_j = exp(s_j - max_j -+ # s_j) covers (0, 1]; as the KV length N grows the row max grows like -+ # sqrt(2 ln N) and an ever larger share of p_j falls below E4M3's smallest -+ # normal 2**-6, where the rounding error is an ABSOLUTE half-ulp of 2**-10 -+ # rather than a relative 2**-4. Measured on the decode sweep, the -+ # subnormal share of the reference's P goes 0.9% (N=8) -> 34% (N=8192) -> -+ # 74% (N=1048576). Meanwhile max|O| shrinks like 1/sqrt(N) (O is a convex -+ # combination of random V rows), so that absolute noise shows up as a -+ # relative error that climbs with N -- entirely on the reference's side. -+ # -+ # The kernel does not have this problem: it normalizes P against a -+ # per-tile running max (`rescale_threshold = 4.0` in -+ # src/sm100/fwd_decode/atten_fwd.py), never against a 1M-token global max. -+ # Measured against the same reference evaluated with an *unquantized* P, -+ # rms|kernel - exact| / rms|exact| is FLAT at 2.7% over N = 8192 .. -+ # 1048576, while rms|ref - exact| / rms|exact| climbs 2.68% -> 3.79% and -+ # max|ref - exact| / max|O| climbs 3.97% -> 12.74%. At N = 1048576 the -+ # kernel is closer to the unquantized answer (6.9%) than the reference is -+ # (12.7%). A bound that charges the reference's own quantization noise to -+ # the kernel is mis-modelled, not a kernel defect. -+ # -+ # So: when the caller can supply the same reference computed without the -+ # E4M3 P rounding, subtract the two to get that noise directly and admit -+ # it into the tolerance. This is measured from the *inputs*, not from the -+ # kernel, so it cannot be inflated by a broken kernel. Callers that do -+ # not supply it (all prefill/NVFP4 sites) keep exactly the previous bound. -+ e4m3_relative_ulp = 2.0**-4 -+ rtol = 4.0 * e4m3_relative_ulp if partial_is_fp8 else e4m3_relative_ulp -+ if out_ref_unquantized_p is None: -+ ref_noise_max = 0.0 -+ ref_noise_rms = 0.0 -+ else: -+ ref_noise = out_ref_f - out_ref_unquantized_p.float() -+ ref_noise_max = ref_noise.abs().max().item() -+ ref_noise_rms = ref_noise.pow(2).mean().sqrt().item() -+ -+ # Triangle inequality through the unquantized-P reference: -+ # |out - out_ref| <= |out - exact| + |exact - out_ref|. -+ # The second leg is ref_noise. The first leg is the kernel's own E4M3 P -+ # rounding, which is of the same class and (per the measurements above) -+ # never coarser, so it is charged the same quantity -- hence the factor 2. -+ tol = 4.0 * bf16_floor + rtol * out_scale + 2.0 * ref_noise_max -+ assert kernel_diff <= tol, ( -+ f"max|out - out_ref| = {kernel_diff:.6g} exceeds {tol:.6g} " -+ f"(= 4 * bf16_floor {bf16_floor:.6g} + rtol {rtol:.6g} " -+ f"* max|out_ref| {out_scale:.6g} + 2 * ref_quant_noise " -+ f"{ref_noise_max:.6g}); relative error " -+ f"{kernel_diff / max(out_scale, 1e-30):.4%}" -+ ) -+ -+ # The same model evaluated in RMS instead of at the single worst element. -+ # rms <= max elementwise, so the same relative constants are conservative -+ # here; this is the coarse net for "the kernel got noisier everywhere", -+ # which a max over millions of elements reports only weakly. -+ rms_tol = 4.0 * bf16_rms_floor + rtol * out_rms + 2.0 * ref_noise_rms -+ assert diff_rms <= rms_tol, ( -+ f"rms(out - out_ref) = {diff_rms:.6g} exceeds {rms_tol:.6g} " -+ f"(= 4 * bf16_rms_floor {bf16_rms_floor:.6g} + rtol {rtol:.6g} " -+ f"* rms|out_ref| {out_rms:.6g} + 2 * ref_quant_noise_rms " -+ f"{ref_noise_rms:.6g}); ratio {diff_rms / max(out_rms, 1e-30):.4%}" -+ ) + @cute.jit +- def _load_scale_e4m3_u8( ++ def _load_scale_bf16x2_linear( + self, + scale: cute.Tensor, +- logical_row: Int32, ++ region_base: Int64, ++ token: Int32, + scale_col: Int32, + ) -> Int32: +- scale_offset = self._scale_128x4_offset( +- logical_row, +- scale_col, +- self.head_dim // 16, ++ scale_byte = self._load_scale_byte( ++ scale, ++ region_base + Int64(self._scale_offset_linear(token, scale_col)), + ) +- scale_ptr = cute.make_ptr( +- cutlass.Uint8, +- scale.iterator.toint() + Int64(scale_offset), +- mem_space=scale.iterator.memspace, +- assumed_align=1, ++ return utils.cvt_fp8_e4m3_to_bf16x2_replicated(scale_byte) + -+ # Both bounds above are set by the quantization NOISE, which is a few -+ # percent for any E4M3 attention kernel and grows with N on the reference -+ # side. On their own they would accept a several-percent systematic -+ # corruption at large N, i.e. they would be close to vacuous exactly where -+ # the old absolute constant already was. The two projections below are -+ # what keep the criterion sharp: they are insensitive to zero-mean noise -+ # (it averages down by sqrt(n_elem)) but respond linearly to a systematic -+ # error. -+ # -+ # gain_err = / -+ # -+ # is exactly eps for a corruption out -> (1 + eps) * out. For a correct -+ # kernel it is not zero, because round-to-nearest on the E4M3 grid is only -+ # unbiased to FIRST order in the relative ulp; writing the residual as -+ # sum_j e_j p_j / sum_j p_j^2 with |e_j| <= rtol * p_j, the surviving -+ # systematic part is second order, O(rtol**2). Measured: the kernel's own -+ # projection (against the unquantized-P reference) is flat at -6.2e-4 .. -+ # -7.2e-4 across N = 1024 .. 1048576 = 0.16 .. 0.18 * rtol**2, and over -+ # 141 prefill/NVFP4 measurements |gain_err| <= 9.7e-5 = 0.025 * rtol**2. -+ # The reference's own projection is what grows with N (+4.6e-5 at N=1024 -+ # -> +9.1e-4 at N=1048576), so it enters through ref_noise like the terms -+ # above. The 8 * (statistical null sd) term covers small tensors, where -+ # the projection of a genuinely zero-mean residual fluctuates. -+ n_elem = diff.numel() -+ ref_energy = (out_ref_bf16 * out_ref_bf16).sum().item() -+ gain_err = (diff * out_ref_bf16).sum().item() / ref_energy if ref_energy > 0 else 0.0 -+ gain_null_sd = diff_rms / (math.sqrt(n_elem) * out_rms) if out_rms > 0 else 0.0 -+ ref_gain_noise = 0.0 -+ if out_ref_unquantized_p is not None and ref_energy > 0: -+ ref_gain_noise = abs( -+ (ref_noise * out_ref_bf16).sum().item() / ref_energy ++ @cute.jit ++ def _load_scale_bf16x2_swizzle4x4( ++ self, ++ scale: cute.Tensor, ++ region_base: Int64, ++ token: Int32, ++ scale_col: Int32, ++ ) -> Int32: ++ scale_byte = self._load_scale_byte( ++ scale, ++ region_base + Int64(self._scale_offset_swizzle4x4(token, scale_col)), + ) -+ gain_tol = rtol * rtol + 2.0 * ref_gain_noise + 8.0 * gain_null_sd -+ assert abs(gain_err) <= gain_tol, ( -+ f" / = {gain_err:.6g} " -+ f"exceeds {gain_tol:.6g} (= rtol**2 {rtol * rtol:.6g} + 2 * " -+ f"ref_gain_noise {ref_gain_noise:.6g} + 8 * null_sd " -+ f"{gain_null_sd:.6g}); the kernel output is systematically scaled" -+ ) ++ return utils.cvt_fp8_e4m3_to_bf16x2_replicated(scale_byte) + -+ # Companion projection onto the constant vector: catches an additive -+ # offset, which the gain statistic cannot see when out_ref is zero-mean. -+ # Its null is diff_rms / sqrt(n_elem); over the 160 fp8/NVFP4 measurements -+ # the observed |mean| never exceeded 2.38 of those sd, so 8 is >3x the -+ # worst observation. The gain_tol * |mean(out_ref)| term keeps the two -+ # checks from double-counting when out_ref does have a nonzero mean. -+ mean_err = diff.mean().item() -+ mean_ref = out_ref_bf16.mean().item() -+ mean_tol = 8.0 * diff_rms / math.sqrt(n_elem) + gain_tol * abs(mean_ref) -+ assert abs(mean_err) <= mean_tol, ( -+ f"mean(out - out_ref) = {mean_err:.6g} exceeds {mean_tol:.6g} " -+ f"(= 8 * null_sd {diff_rms / math.sqrt(n_elem):.6g} + gain_tol " -+ f"{gain_tol:.6g} * |mean(out_ref)| {abs(mean_ref):.6g}); the kernel " -+ f"output carries a systematic offset" -+ ) ++ @cute.jit ++ def _load_scale_e4m3_u8_linear( ++ self, ++ scale: cute.Tensor, ++ region_base: Int64, ++ token: Int32, ++ scale_col: Int32, ++ ) -> Int32: ++ return self._load_scale_byte( ++ scale, ++ region_base + Int64(self._scale_offset_linear(token, scale_col)), ++ ) ++ ++ @cute.jit ++ def _load_scale_e4m3_u8_swizzle4x4( ++ self, ++ scale: cute.Tensor, ++ region_base: Int64, ++ token: Int32, ++ scale_col: Int32, ++ ) -> Int32: ++ return self._load_scale_byte( ++ scale, ++ region_base + Int64(self._scale_offset_swizzle4x4(token, scale_col)), + ) +- scale_byte = cute.make_tensor(scale_ptr, cute.make_layout(1))[0] +- return cutlass.Int32(scale_byte) - finite = lse_ref.isfinite() - if finite.any(): -@@ -1786,6 +2166,74 @@ def test_sparse_page_atten( + @cute.jit + def _dequant_fp4x16_to_bf16( +@@ -1282,12 +1445,14 @@ class SparseAttentionForwardNvfp4KvSm100: + src_words: cute.Tensor, + scale_e4m3: Int32, + dst: cute.Tensor, ++ global_scale: Optional[Float32], + ): + dst_i32 = cute.recast_tensor(dst, cutlass.Int32) + for word_idx in cutlass.range_constexpr(2): + fp8_lo, fp8_hi = utils.cvt_fp4x8_e2m1_scaled_e4m3x8( + src_words[word_idx], + scale_e4m3, ++ global_scale, + ) + dst_i32[word_idx * 2] = fp8_lo + dst_i32[word_idx * 2 + 1] = fp8_hi +@@ -1299,12 +1464,14 @@ class SparseAttentionForwardNvfp4KvSm100: + scale_e4m3_lo: Int32, + scale_e4m3_hi: Int32, + dst: cute.Tensor, ++ global_scale: Optional[Float32], + ): + dst_i32 = cute.recast_tensor(dst, cutlass.Int32) + for word_idx in cutlass.range_constexpr(2): + fp8_lo, fp8_hi = utils.cvt_fp4x8_e2m1_scaled_e4m3x8( + src_words[word_idx], + scale_e4m3_lo, ++ global_scale, + ) + dst_i32[word_idx * 2] = fp8_lo + dst_i32[word_idx * 2 + 1] = fp8_hi +@@ -1312,29 +1479,11 @@ class SparseAttentionForwardNvfp4KvSm100: + fp8_lo, fp8_hi = utils.cvt_fp4x8_e2m1_scaled_e4m3x8( + src_words[word_idx + 2], + scale_e4m3_hi, ++ global_scale, + ) + dst_i32[word_idx * 2 + 4] = fp8_lo + dst_i32[word_idx * 2 + 5] = fp8_hi + +- @cute.jit +- def _flat_kv_scale_row( +- self, +- token_idx: Int32, +- head_kv_idx: Int32, +- num_heads_kv: Int32, +- ) -> Int32: +- return token_idx * num_heads_kv + head_kv_idx +- +- @cute.jit +- def _paged_kv_scale_row( +- self, +- page_idx: Int32, +- token_idx: Int32, +- head_kv_idx: Int32, +- num_heads_kv: Int32, +- ) -> Int32: +- return (page_idx * num_heads_kv + head_kv_idx) * Int32(self.page_size) + token_idx +- + @cute.jit + def _load_k_fp4_to_smem( + self, +@@ -1350,11 +1499,37 @@ class SparseAttentionForwardNvfp4KvSm100: + kv_block_idx: Int32, + k_batch_offset: Int32, + num_heads_kv: Int32, ++ k_sf_page_stride: Int32, ++ k_sf_head_stride: Int32, + ): + elems_per_block: cutlass.Constexpr[int] = 16 + bytes_per_block: cutlass.Constexpr[int] = 8 + scale_cols: cutlass.Constexpr[int] = self.head_dim // elems_per_block +- token_in_block_base = kv_block_idx * Int32(self.n_block_size) ++ # Loop-invariant scale addressing. In paged mode the whole region base ++ # is fixed: the page is sPagedKvIdx[0] and the KV head does not change ++ # across the task loop, so hoisting it removes a multiply chain per ++ # task. In flat mode only the block's first global token is invariant. ++ if const_expr(self.paged_kv): ++ k_sf_region_base = self._scale_region_base( ++ sPagedKvIdx[0], ++ head_kv_idx, ++ k_sf_page_stride, ++ k_sf_head_stride, ++ ) ++ else: ++ flat_token_base = ( ++ k_batch_offset + kv_block_idx * Int32(self.n_block_size) ++ ) ++ # Three trace-time dequant modes (no branch survives into the kernel; ++ # k_dtype is q_dtype, and fp8_pair_dequant is part of the compile key): ++ # 1. FP8 pair : 2 blocks/iter, 128-bit load, 2 scale bytes. == mode 2 x2, loop fusion. ++ # 2. FP8 scalar: 1 block/iter, 64-bit load. Half a 32-elem tile, hence the local_tile(). ++ # 3. BF16 : 1 block/iter; global scale folded here since mul_bf16x2 runs anyway. ++ # FP8 staging must include the global scale before conversion, since ++ # the block-scaled FP4 intermediate can exceed E4M3's finite range. ++ k_global = None ++ if const_expr(self.has_k_global_scale): ++ k_global = mKGlobalScale[0] + if const_expr(self.k_dtype == cutlass.Float8E4M3FN and self.fp8_pair_dequant): + elems_per_pair: cutlass.Constexpr[int] = 32 + bytes_per_pair: cutlass.Constexpr[int] = 16 +@@ -1379,22 +1554,17 @@ class SparseAttentionForwardNvfp4KvSm100: + pair_col = task_idx - row * Int32(scale_pairs) + scale_col = pair_col * Int32(2) + byte_col = pair_col * Int32(bytes_per_pair) +- token = token_in_block_base + row + if const_expr(self.paged_kv): +- page = sPagedKvIdx[0] +- scale_row = self._paged_kv_scale_row( +- page, +- row, +- head_kv_idx, +- num_heads_kv, +- ) ++ sf_region_base = k_sf_region_base ++ sf_token = row + else: +- token = k_batch_offset + token +- scale_row = self._flat_kv_scale_row( +- token, ++ sf_region_base = self._scale_region_base_flat( ++ flat_token_base + row, + head_kv_idx, + num_heads_kv, ++ 1, + ) ++ sf_token = Int32(0) + smem_offset = row * Int32(self.head_dim // 2) + byte_col + s_ptr = cute.make_ptr( + cutlass.Int32, +@@ -1404,10 +1574,16 @@ class SparseAttentionForwardNvfp4KvSm100: + ) + s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_pair // 4)) + cute.copy(g2r_pair_atom, s_vec, r_words_pair) +- scale_e4m3_lo = self._load_scale_e4m3_u8(mKScale, scale_row, scale_col) +- scale_e4m3_hi = self._load_scale_e4m3_u8( ++ scale_e4m3_lo = self._load_scale_e4m3_u8_linear( ++ mKScale, ++ sf_region_base, ++ sf_token, ++ scale_col, ++ ) ++ scale_e4m3_hi = self._load_scale_e4m3_u8_linear( + mKScale, +- scale_row, ++ sf_region_base, ++ sf_token, + scale_col + Int32(1), + ) + self._dequant_fp4x32_to_fp8( +@@ -1415,98 +1591,101 @@ class SparseAttentionForwardNvfp4KvSm100: + scale_e4m3_lo, + scale_e4m3_hi, + r_vals_pair, ++ k_global, + ) + sK_vec = sK[(row, None), 0, pair_col, 0] + r_tiles = cute.logical_divide(r_vals_pair, cute.make_layout(16)) + s_tiles = cute.logical_divide(sK_vec, cute.make_layout(16)) + for v in cutlass.range_constexpr(elems_per_pair // 16): + cute.copy(r2s_pair_atom, r_tiles[None, v], s_tiles[None, v]) +- cute.arch.fence_view_async_shared() +- return +- r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) +- r_vals = cute.make_rmem_tensor((elems_per_block,), self.k_dtype) +- g2r_atom = cute.make_copy_atom( +- cute.nvgpu.CopyUniversalOp(), +- cutlass.Int32, +- num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, +- ) +- elems_per_store: cutlass.Constexpr[int] = ( +- 16 if self.k_dtype == cutlass.Float8E4M3FN else 8 +- ) +- r2s_atom = cute.make_copy_atom( +- cute.nvgpu.CopyUniversalOp(), +- self.k_dtype, +- num_bits_per_copy=elems_per_store * self.k_dtype.width, +- ) +- total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols +- task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE +- task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane +- for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): +- row = task_idx // Int32(scale_cols) +- scale_col = task_idx - row * Int32(scale_cols) +- byte_col = scale_col * Int32(bytes_per_block) +- token = token_in_block_base + row +- if const_expr(self.paged_kv): +- page = sPagedKvIdx[0] +- scale_row = self._paged_kv_scale_row( +- page, +- row, +- head_kv_idx, +- num_heads_kv, +- ) +- else: +- token = k_batch_offset + token +- scale_row = self._flat_kv_scale_row( +- token, +- head_kv_idx, +- num_heads_kv, +- ) +- smem_offset = row * Int32(self.head_dim // 2) + byte_col +- s_ptr = cute.make_ptr( ++ else: ++ r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) ++ r_vals = cute.make_rmem_tensor((elems_per_block,), self.k_dtype) ++ g2r_atom = cute.make_copy_atom( ++ cute.nvgpu.CopyUniversalOp(), + cutlass.Int32, +- sKFp4.iterator.toint() + Int64(smem_offset), +- mem_space=sKFp4.iterator.memspace, +- assumed_align=bytes_per_block, ++ num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, + ) +- s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) +- cute.copy(g2r_atom, s_vec, r_words) +- if const_expr(self.k_dtype == cutlass.Float8E4M3FN): +- scale_e4m3 = self._load_scale_e4m3_u8(mKScale, scale_row, scale_col) +- else: +- combined_bf16x2 = self._load_scale_bf16x2(mKScale, scale_row, scale_col) +- if const_expr(self.has_k_global_scale): +- global_bf16x2 = utils.cvt_f16x2_f32( +- mKGlobalScale[0], +- mKGlobalScale[0], +- cutlass.BFloat16, ++ elems_per_store: cutlass.Constexpr[int] = ( ++ 16 if self.k_dtype == cutlass.Float8E4M3FN else 8 ++ ) ++ r2s_atom = cute.make_copy_atom( ++ cute.nvgpu.CopyUniversalOp(), ++ self.k_dtype, ++ num_bits_per_copy=elems_per_store * self.k_dtype.width, ++ ) ++ total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols ++ task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE ++ task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane ++ for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): ++ row = task_idx // Int32(scale_cols) ++ scale_col = task_idx - row * Int32(scale_cols) ++ byte_col = scale_col * Int32(bytes_per_block) ++ if const_expr(self.paged_kv): ++ sf_region_base = k_sf_region_base ++ sf_token = row ++ else: ++ sf_region_base = self._scale_region_base_flat( ++ flat_token_base + row, ++ head_kv_idx, ++ num_heads_kv, ++ 1, + ) +- combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) +- if const_expr(self.k_dtype == cutlass.Float8E4M3FN): +- sK_cols = sK[(row, None), 0, scale_col // Int32(2), 0] +- sK_vec = cute.local_tile( +- sK_cols, +- (elems_per_block,), +- (scale_col % Int32(2),), +- ) +- else: +- sK_vec = sK[ +- (row, None), +- 0, +- (scale_col % Int32(4), scale_col // Int32(4)), +- 0, +- ] +- if const_expr(self.k_dtype == cutlass.Float8E4M3FN): +- self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals) +- else: +- self._dequant_fp4x16_to_bf16( +- r_words, +- combined_bf16x2, +- r_vals, ++ sf_token = Int32(0) ++ smem_offset = row * Int32(self.head_dim // 2) + byte_col ++ s_ptr = cute.make_ptr( ++ cutlass.Int32, ++ sKFp4.iterator.toint() + Int64(smem_offset), ++ mem_space=sKFp4.iterator.memspace, ++ assumed_align=bytes_per_block, + ) +- r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) +- s_tiles = cute.logical_divide(sK_vec, cute.make_layout(elems_per_store)) +- for v in cutlass.range_constexpr(elems_per_block // elems_per_store): +- cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) ++ s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) ++ cute.copy(g2r_atom, s_vec, r_words) ++ if const_expr(self.k_dtype == cutlass.Float8E4M3FN): ++ # Mode 2: scale byte is a conversion operand, no multiply. ++ scale_e4m3 = self._load_scale_e4m3_u8_linear( ++ mKScale, ++ sf_region_base, ++ sf_token, ++ scale_col, ++ ) ++ sK_cols = sK[(row, None), 0, scale_col // Int32(2), 0] ++ sK_vec = cute.local_tile( ++ sK_cols, ++ (elems_per_block,), ++ (scale_col % Int32(2),), ++ ) ++ self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals, k_global) ++ else: ++ # Mode 3: replicated bf16x2 scale, global scale folded in. ++ combined_bf16x2 = self._load_scale_bf16x2_linear( ++ mKScale, ++ sf_region_base, ++ sf_token, ++ scale_col, ++ ) ++ if const_expr(self.has_k_global_scale): ++ global_bf16x2 = utils.cvt_f16x2_f32( ++ mKGlobalScale[0], ++ mKGlobalScale[0], ++ cutlass.BFloat16, ++ ) ++ combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) ++ sK_vec = sK[ ++ (row, None), ++ 0, ++ (scale_col % Int32(4), scale_col // Int32(4)), ++ 0, ++ ] ++ self._dequant_fp4x16_to_bf16( ++ r_words, ++ combined_bf16x2, ++ r_vals, ++ ) ++ r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) ++ s_tiles = cute.logical_divide(sK_vec, cute.make_layout(elems_per_store)) ++ for v in cutlass.range_constexpr(elems_per_block // elems_per_store): ++ cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) + cute.arch.fence_view_async_shared() - _assert_forward_close(out, out_ref, out_pt.float(), lse, lse_ref) + @cute.jit +@@ -1524,11 +1703,34 @@ class SparseAttentionForwardNvfp4KvSm100: + kv_block_idx: Int32, + k_batch_offset: Int32, + num_heads_kv: Int32, ++ v_sf_page_stride: Int32, ++ v_sf_head_stride: Int32, ++ kv_valid_cols: Int32, + ): + elems_per_block: cutlass.Constexpr[int] = 16 + bytes_per_block: cutlass.Constexpr[int] = 8 + scale_cols: cutlass.Constexpr[int] = self.head_dim // elems_per_block +- token_in_block_base = kv_block_idx * Int32(self.n_block_size) ++ # Rows at or past kv_valid_cols take a zero block scale: their P is 0, but a never-written pool slot can hold a ++ # NaN / Inf scale byte, and 0 * NaN = NaN would reach O. E2M1 data is always finite, so such a row dequantizes ++ # to exact zeros; valid rows are unchanged (bitwise). ++ # Loop-invariant scale addressing; see `_load_k_fp4_to_smem`. Only the ++ # offset formula differs -- V is 4x4 token-quad swizzled. ++ if const_expr(self.paged_kv): ++ v_sf_region_base = self._scale_region_base( ++ sPagedKvIdx[0], ++ head_kv_idx, ++ v_sf_page_stride, ++ v_sf_head_stride, ++ ) ++ else: ++ flat_token_base = ( ++ k_batch_offset + kv_block_idx * Int32(self.n_block_size) ++ ) ++ # Same three trace-time modes as `_load_k_fp4_to_smem`; V only differs ++ # in the smem destination and the 4x4-swizzled scale reads. ++ v_global = None ++ if const_expr(self.has_v_global_scale): ++ v_global = mVGlobalScale[0] + if const_expr(self.v_dtype == cutlass.Float8E4M3FN and self.fp8_pair_dequant): + elems_per_pair: cutlass.Constexpr[int] = 32 + bytes_per_pair: cutlass.Constexpr[int] = 16 +@@ -1553,22 +1755,18 @@ class SparseAttentionForwardNvfp4KvSm100: + pair_col = task_idx - row * Int32(scale_pairs) + scale_col = pair_col * Int32(2) + byte_col = pair_col * Int32(bytes_per_pair) +- token = token_in_block_base + row + if const_expr(self.paged_kv): +- page = sPagedKvIdx[0] +- scale_row = self._paged_kv_scale_row( +- page, +- row, +- head_kv_idx, +- num_heads_kv, +- ) ++ sf_region_base = v_sf_region_base ++ sf_token = row + else: +- token = k_batch_offset + token +- scale_row = self._flat_kv_scale_row( +- token, ++ token_global = flat_token_base + row ++ sf_region_base = self._scale_region_base_flat( ++ token_global, + head_kv_idx, + num_heads_kv, ++ 4, + ) ++ sf_token = token_global & Int32(3) + smem_offset = row * Int32(self.head_dim // 2) + byte_col + s_ptr = cute.make_ptr( + cutlass.Int32, +@@ -1578,17 +1776,26 @@ class SparseAttentionForwardNvfp4KvSm100: + ) + s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_pair // 4)) + cute.copy(g2r_pair_atom, s_vec, r_words_pair) +- scale_e4m3_lo = self._load_scale_e4m3_u8(mVScale, scale_row, scale_col) +- scale_e4m3_hi = self._load_scale_e4m3_u8( ++ scale_e4m3_lo = self._load_scale_e4m3_u8_swizzle4x4( ++ mVScale, ++ sf_region_base, ++ sf_token, ++ scale_col, ++ ) ++ scale_e4m3_hi = self._load_scale_e4m3_u8_swizzle4x4( + mVScale, +- scale_row, ++ sf_region_base, ++ sf_token, + scale_col + Int32(1), + ) ++ scale_e4m3_lo = scale_e4m3_lo if row < kv_valid_cols else Int32(0) ++ scale_e4m3_hi = scale_e4m3_hi if row < kv_valid_cols else Int32(0) + self._dequant_fp4x32_to_fp8( + r_words_pair, + scale_e4m3_lo, + scale_e4m3_hi, + r_vals_pair, ++ v_global, + ) + sV_cols = sV[(None, row % Int32(32)), 0, row // Int32(32), 0] + sV_vec = cute.local_tile(sV_cols, (elems_per_pair,), (pair_col,)) +@@ -1596,81 +1803,88 @@ class SparseAttentionForwardNvfp4KvSm100: + s_tiles = cute.logical_divide(sV_vec, cute.make_layout(16)) + for v in cutlass.range_constexpr(elems_per_pair // 16): + cute.copy(r2s_pair_atom, r_tiles[None, v], s_tiles[None, v]) +- cute.arch.fence_view_async_shared() +- return +- r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) +- r_vals = cute.make_rmem_tensor((elems_per_block,), self.v_dtype) +- g2r_atom = cute.make_copy_atom( +- cute.nvgpu.CopyUniversalOp(), +- cutlass.Int32, +- num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, +- ) +- elems_per_store: cutlass.Constexpr[int] = ( +- 16 if self.v_dtype == cutlass.Float8E4M3FN else 8 +- ) +- r2s_atom = cute.make_copy_atom( +- cute.nvgpu.CopyUniversalOp(), +- self.v_dtype, +- num_bits_per_copy=elems_per_store * self.v_dtype.width, +- ) +- total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols +- task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE +- task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane +- for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): +- row = task_idx // Int32(scale_cols) +- scale_col = task_idx - row * Int32(scale_cols) +- byte_col = scale_col * Int32(bytes_per_block) +- token = token_in_block_base + row +- if const_expr(self.paged_kv): +- page = sPagedKvIdx[0] +- scale_row = self._paged_kv_scale_row( +- page, +- row, +- head_kv_idx, +- num_heads_kv, +- ) +- else: +- token = k_batch_offset + token +- scale_row = self._flat_kv_scale_row( +- token, +- head_kv_idx, +- num_heads_kv, +- ) +- smem_offset = row * Int32(self.head_dim // 2) + byte_col +- s_ptr = cute.make_ptr( ++ else: ++ r_words = cute.make_rmem_tensor((bytes_per_block // 4,), cutlass.Int32) ++ r_vals = cute.make_rmem_tensor((elems_per_block,), self.v_dtype) ++ g2r_atom = cute.make_copy_atom( ++ cute.nvgpu.CopyUniversalOp(), + cutlass.Int32, +- sVFp4.iterator.toint() + Int64(smem_offset), +- mem_space=sVFp4.iterator.memspace, +- assumed_align=bytes_per_block, ++ num_bits_per_copy=bytes_per_block * cutlass.Uint8.width, + ) +- s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) +- cute.copy(g2r_atom, s_vec, r_words) +- if const_expr(self.v_dtype == cutlass.Float8E4M3FN): +- scale_e4m3 = self._load_scale_e4m3_u8(mVScale, scale_row, scale_col) +- self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals) +- else: +- combined_bf16x2 = self._load_scale_bf16x2(mVScale, scale_row, scale_col) +- if const_expr(self.has_v_global_scale): +- global_bf16x2 = utils.cvt_f16x2_f32( +- mVGlobalScale[0], +- mVGlobalScale[0], +- cutlass.BFloat16, ++ elems_per_store: cutlass.Constexpr[int] = ( ++ 16 if self.v_dtype == cutlass.Float8E4M3FN else 8 ++ ) ++ r2s_atom = cute.make_copy_atom( ++ cute.nvgpu.CopyUniversalOp(), ++ self.v_dtype, ++ num_bits_per_copy=elems_per_store * self.v_dtype.width, ++ ) ++ total_tasks: cutlass.Constexpr[int] = self.n_block_size * scale_cols ++ task_stride: cutlass.Constexpr[int] = num_dequant_warps * cute.arch.WARP_SIZE ++ task = warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) + lane ++ for task_idx in cutlass.range(task, total_tasks, task_stride, unroll=1): ++ row = task_idx // Int32(scale_cols) ++ scale_col = task_idx - row * Int32(scale_cols) ++ byte_col = scale_col * Int32(bytes_per_block) ++ if const_expr(self.paged_kv): ++ sf_region_base = v_sf_region_base ++ sf_token = row ++ else: ++ token_global = flat_token_base + row ++ sf_region_base = self._scale_region_base_flat( ++ token_global, ++ head_kv_idx, ++ num_heads_kv, ++ 4, + ) +- combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) +- self._dequant_fp4x16_to_bf16( +- r_words, +- combined_bf16x2, +- r_vals, ++ sf_token = token_global & Int32(3) ++ smem_offset = row * Int32(self.head_dim // 2) + byte_col ++ s_ptr = cute.make_ptr( ++ cutlass.Int32, ++ sVFp4.iterator.toint() + Int64(smem_offset), ++ mem_space=sVFp4.iterator.memspace, ++ assumed_align=bytes_per_block, + ) +- if const_expr(self.v_dtype == cutlass.Float8E4M3FN): +- sV_cols = sV[(None, row % Int32(32)), 0, row // Int32(32), 0] +- else: +- sV_cols = sV[(None, row % Int32(16)), 0, row // Int32(16), 0] +- sV_vec = cute.local_tile(sV_cols, (elems_per_block,), (scale_col,)) +- r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) +- s_tiles = cute.logical_divide(sV_vec, cute.make_layout(elems_per_store)) +- for v in cutlass.range_constexpr(elems_per_block // elems_per_store): +- cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) ++ s_vec = cute.make_tensor(s_ptr, cute.make_layout(bytes_per_block // 4)) ++ cute.copy(g2r_atom, s_vec, r_words) ++ if const_expr(self.v_dtype == cutlass.Float8E4M3FN): ++ # Mode 2: scale byte is a conversion operand; 32-row smem groups. ++ scale_e4m3 = self._load_scale_e4m3_u8_swizzle4x4( ++ mVScale, ++ sf_region_base, ++ sf_token, ++ scale_col, ++ ) ++ scale_e4m3 = scale_e4m3 if row < kv_valid_cols else Int32(0) ++ self._dequant_fp4x16_to_fp8(r_words, scale_e4m3, r_vals, v_global) ++ sV_cols = sV[(None, row % Int32(32)), 0, row // Int32(32), 0] ++ else: ++ # Mode 3: bf16x2 scale, global folded in; 16-row smem groups. ++ combined_bf16x2 = self._load_scale_bf16x2_swizzle4x4( ++ mVScale, ++ sf_region_base, ++ sf_token, ++ scale_col, ++ ) ++ combined_bf16x2 = combined_bf16x2 if row < kv_valid_cols else Int32(0) ++ if const_expr(self.has_v_global_scale): ++ global_bf16x2 = utils.cvt_f16x2_f32( ++ mVGlobalScale[0], ++ mVGlobalScale[0], ++ cutlass.BFloat16, ++ ) ++ combined_bf16x2 = utils.mul_bf16x2(combined_bf16x2, global_bf16x2) ++ self._dequant_fp4x16_to_bf16( ++ r_words, ++ combined_bf16x2, ++ r_vals, ++ ) ++ sV_cols = sV[(None, row % Int32(16)), 0, row // Int32(16), 0] ++ sV_vec = cute.local_tile(sV_cols, (elems_per_block,), (scale_col,)) ++ r_tiles = cute.logical_divide(r_vals, cute.make_layout(elems_per_store)) ++ s_tiles = cute.logical_divide(sV_vec, cute.make_layout(elems_per_store)) ++ for v in cutlass.range_constexpr(elems_per_block // elems_per_store): ++ cute.copy(r2s_atom, r_tiles[None, v], s_tiles[None, v]) + cute.arch.fence_view_async_shared() + @cute.jit +@@ -1794,6 +2008,8 @@ class SparseAttentionForwardNvfp4KvSm100: + kv_block_idx: Int32, + k_batch_offset: Int32, + num_heads_kv: Int32, ++ k_sf_page_stride: Int32, ++ k_sf_head_stride: Int32, + ): + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + warp_idx_in_wg = warp_idx - Int32(dequant_warp_base) +@@ -1814,6 +2030,8 @@ class SparseAttentionForwardNvfp4KvSm100: + kv_block_idx, + k_batch_offset, + num_heads_kv, ++ k_sf_page_stride, ++ k_sf_head_stride, + ) + dequant_barrier.arrive_and_wait() + if warp_idx_in_wg == Int32(0): +@@ -1838,6 +2056,9 @@ class SparseAttentionForwardNvfp4KvSm100: + kv_block_idx: Int32, + k_batch_offset: Int32, + num_heads_kv: Int32, ++ v_sf_page_stride: Int32, ++ v_sf_head_stride: Int32, ++ kv_valid_cols: Int32, + ): + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + warp_idx_in_wg = warp_idx - Int32(dequant_warp_base) +@@ -1858,6 +2079,9 @@ class SparseAttentionForwardNvfp4KvSm100: + kv_block_idx, + k_batch_offset, + num_heads_kv, ++ v_sf_page_stride, ++ v_sf_head_stride, ++ kv_valid_cols, + ) + dequant_barrier.arrive_and_wait() + if warp_idx_in_wg == Int32(0): +@@ -2191,8 +2415,8 @@ class SparseAttentionForwardNvfp4KvSm100: + self, + tiled_mma_qk: cute.TiledMma, + tiled_mma_pv: cute.TiledMma, +- thr0_qk: cute.core.ThrMma, +- thr0_pv: cute.core.ThrMma, ++ thr0_qk: cute.ThrMma, ++ thr0_pv: cute.ThrMma, + tStS: cute.Tensor, + tOrP: cute.Tensor, + sK: cute.Tensor, +@@ -2441,6 +2665,7 @@ class SparseAttentionForwardNvfp4KvSm100: + s_consumer_phase: Int32, + p_producer_phase: Int32, + sm_stats_producer_phase: Int32, ++ sm_meta_idx: Int32, + softmax: SoftmaxSm100, + sScale: cute.Tensor, + sScaleTemperature: cute.Tensor, +@@ -2479,17 +2704,6 @@ class SparseAttentionForwardNvfp4KvSm100: + self.qk_acc_dtype) + cute.copy(thr_tmem_load, tStS_t2r, tSrS_t2r) + +- if const_expr( +- self.q_dtype == cutlass.Float8E4M3FN +- and self.has_k_global_scale +- ): +- k_global = mKGlobalScale[0] +- for i in cutlass.range_constexpr(0, cute.size(tSrS_t2r.shape), 2): +- tSrS_t2r[i], tSrS_t2r[i + 1] = cute.arch.mul_packed_f32x2( +- (tSrS_t2r[i], tSrS_t2r[i + 1]), +- (k_global, k_global), +- ) +- + seqlen_info = SeqlenInfoQK( + Int32(0), + Int32(0), +@@ -2593,11 +2807,11 @@ class SparseAttentionForwardNvfp4KvSm100: + else: + pipeline_p_lastsplit.producer_commit_w_index(slot_rt) + pipeline_sm_stats.producer_acquire_w_index_phase( +- slot_rt, sm_stats_producer_phase) ++ sm_meta_idx, sm_stats_producer_phase) + softmax.update_row_sum(tSrS_t2r.load(), Float32(0.0), True) + del tSrS_t2r + sScale_slot = cute.make_tensor( +- sScale.iterator + slot_rt * Int32(self.m_block_size * 2), ++ sScale.iterator + sm_meta_idx * Int32(self.m_block_size * 2), + cute.make_layout(self.m_block_size * 2), + ) + sScale_slot[group_tidx] = softmax.row_sum[0] +@@ -2605,11 +2819,13 @@ class SparseAttentionForwardNvfp4KvSm100: + softmax.row_max[0]) + if const_expr(return_temperature_lse): + sScale_temperature_slot = cute.make_tensor( +- sScaleTemperature.iterator + slot_rt * Int32(self.m_block_size), ++ sScaleTemperature.iterator + sm_meta_idx * Int32(self.m_block_size), + cute.make_layout(self.m_block_size), + ) + sScale_temperature_slot[group_tidx] = lse_temperature_row_sum + cute.arch.fence_view_async_shared() ++ if const_expr(self.r2_store): ++ pipeline_sm_stats.producer_commit_w_index(sm_meta_idx) + + if const_expr(signal_stats_barrier): + sm_stats_barrier.arrive_w_index(index=stats_barrier_idx) +@@ -2734,6 +2950,12 @@ class SparseAttentionForwardNvfp4KvSm100: + qi_group = qi_iter * Int32(2) + Int32(stage) + phase = qi_iter & Int32(1) + producer_phase = phase ^ Int32(1) ++ sm_meta_idx = Int32(stage) ++ sm_meta_producer_phase = producer_phase ++ if const_expr(self.r2_store): ++ sm_meta_idx = Int32(stage) + Int32(2) * (qi_iter & Int32(1)) ++ sm_meta_producer_phase = ( ++ (qi_iter // Int32(2)) & Int32(1)) ^ Int32(1) + qidx_meta_slot = ( + (qi_group & Int32(self.qidx_meta_stages - 1)) + * Int32(self.q_tokens_per_group) +@@ -2754,7 +2976,8 @@ class SparseAttentionForwardNvfp4KvSm100: + stage, + phase, + producer_phase, +- producer_phase, ++ sm_meta_producer_phase, ++ sm_meta_idx, + softmax, + sScale, + sScaleTemperature, +@@ -2789,7 +3012,8 @@ class SparseAttentionForwardNvfp4KvSm100: + stage, + phase, + producer_phase, +- producer_phase, ++ sm_meta_producer_phase, ++ sm_meta_idx, + softmax, + sScale, + sScaleTemperature, +@@ -2819,7 +3043,98 @@ class SparseAttentionForwardNvfp4KvSm100: + False, + False, + ) +- epilogue_barrier.arrive_and_wait_w_index(index=Int32(stage)) ++ if const_expr(not self.r2_store): ++ epilogue_barrier.arrive_and_wait_w_index(index=Int32(stage)) ++ self._epilogue_step( ++ qi_group, ++ group_tidx, ++ warp_idx_in_wg, ++ tOtO_base, ++ tOcO_i, ++ o_tmem_copy_atom, ++ sScale, ++ sScaleTemperature, ++ sSplitIdx, ++ sQIdx, ++ sQIdxMeta, ++ pipeline_o, ++ pipeline_sm_stats, ++ sm_stats_barrier, ++ epilogue_barrier, ++ mO_partial, ++ mLSE_partial, ++ mLSE_temperature_partial, ++ softmax_scale_log2, ++ lse_temperature_scale_log2, ++ mVGlobalScale, ++ count_raw, ++ batch_idx, ++ head_kv_idx, ++ seq_len_q, ++ head_q, ++ num_heads_kv, ++ q_batch_offset, ++ total_q, ++ False, ++ stage, ++ ) + -+def test_sparse_page_atten_strided_outer_page_matches_packed() -> None: -+ inputs = _build_paged_inputs( -+ batch=1, -+ seqlen_q=2048, -+ seqlen_kv=2048, -+ head_kv=2, -+ qhead_per_kv=16, -+ dim=128, -+ topk=16, -+ blk_kv=128, -+ causal=True, -+ page_size=128, -+ seqused_trim=0, -+ dtype=torch.float8_e4m3fn, -+ ) -+ k_packed = inputs["k_paged"].detach().clone() -+ v_packed = inputs["v_paged"].detach().clone() -+ pool = torch.empty( -+ k_packed.shape[0], -+ 4, -+ *k_packed.shape[1:], -+ dtype=k_packed.dtype, -+ device=k_packed.device, -+ ) -+ k_strided = pool[:, 1] -+ v_strided = pool[:, 3] -+ k_strided.copy_(k_packed) -+ v_strided.copy_(v_packed) -+ -+ assert not k_strided.is_contiguous() -+ assert not v_strided.is_contiguous() -+ assert ( -+ sparse_interface._prepare_paged_hnd_input(k_strided, inputs["blk_kv"]).data_ptr() -+ == k_strided.data_ptr() -+ ) -+ assert ( -+ sparse_interface._prepare_paged_hnd_input(v_strided, inputs["blk_kv"]).data_ptr() -+ == v_strided.data_ptr() -+ ) -+ -+ def run(k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: -+ return sparse_atten_func( -+ inputs["q"], -+ k, -+ v, -+ inputs["k2q_row_ptr"], -+ inputs["k2q_q_indices"], -+ 16, -+ blk_kv=inputs["blk_kv"], -+ causal=True, -+ softmax_scale=inputs["softmax_scale"], -+ return_softmax_lse=True, -+ cu_seqlens_q=inputs["cu_seqlens_q"], -+ cu_seqlens_k=inputs["cu_seqlens_k"], -+ max_seqlen_q=inputs["max_seqlen_q"], -+ max_seqlen_k=inputs["max_seqlen_k"], -+ page_table=inputs["page_table"], -+ seqused_k=inputs["seqused_k"], -+ schedule=inputs["schedule"], -+ ) -+ -+ packed_out, packed_lse = run(k_packed, v_packed) -+ strided_out, strided_lse = run(k_strided, v_strided) -+ torch.testing.assert_close(strided_out, packed_out, rtol=0, atol=0) -+ torch.testing.assert_close(strided_lse, packed_lse, rtol=0, atol=0) -+ ++ @cute.jit ++ def _wg_store( ++ self, ++ tiled_mma_pv: cute.TiledMma, ++ sScale: cute.Tensor, ++ sScaleTemperature: cute.Tensor, ++ sSplitIdx: cute.Tensor, ++ sQIdx: cute.Tensor, ++ sQIdxMeta: cute.Tensor, ++ pipeline_o, ++ pipeline_sm_stats, ++ sm_stats_barrier, ++ epilogue_barrier, ++ mO_partial: cute.Tensor, ++ mLSE_partial: cute.Tensor, ++ mLSE_temperature_partial: Optional[cute.Tensor], ++ softmax_scale_log2: Float32, ++ lse_temperature_scale_log2: Float32, ++ mVGlobalScale: Optional[cute.Tensor], ++ num_q_groups: Int32, ++ count_raw: Int32, ++ has_work: Int32, ++ batch_idx: Int32, ++ head_kv_idx: Int32, ++ seq_len_q: Int32, ++ head_q: Int32, ++ num_heads_kv: Int32, ++ q_batch_offset: Int32, ++ mQ_2d: cute.Tensor, ++ ): ++ """R2 store WG: partial O/LSE epilogue for every q-group, in order. + - @pytest.mark.parametrize("paged", [False, True]) - @pytest.mark.parametrize("causal", [True]) - @pytest.mark.parametrize("batch", [3]) -@@ -1857,8 +2305,7 @@ def test_sparse_atten_nvfp4_kv_matches_dequantized_bf16( - k_source = inputs["k"] - v_source = inputs["v"] - -- k_q = _quantize_bf16_to_nvfp4_or_skip(k_source) -- v_q = _quantize_bf16_to_nvfp4_or_skip(v_source) -+ k_q, v_q = _quantize_kv_bf16_to_nvfp4(k_source, v_source) - k_deq = _dequant_nvfp4_to_bf16(k_q) - v_deq = _dequant_nvfp4_to_bf16(v_q) - -@@ -1886,8 +2333,8 @@ def test_sparse_atten_nvfp4_kv_matches_dequantized_bf16( - inputs["q"], - k_q.data, - v_q.data, -- k_q.scale_128x4, -- v_q.scale_128x4, -+ k_q.scale, -+ v_q.scale, - k_q.global_scale, - v_q.global_scale, - inputs["k2q_row_ptr"], -@@ -2184,8 +2631,7 @@ def test_sparse_atten_nvfp4_kv_te_quantized_flat_smoke() -> None: - dtype=torch.bfloat16, - q2k_pattern=Q2KPattern.UNIFORM, - ) -- k_q = _quantize_bf16_to_nvfp4_or_skip(inputs["k"]) -- v_q = _quantize_bf16_to_nvfp4_or_skip(inputs["v"]) -+ k_q, v_q = _quantize_kv_bf16_to_nvfp4(inputs["k"], inputs["v"]) - k_deq = _dequant_nvfp4_to_bf16(k_q) - v_deq = _dequant_nvfp4_to_bf16(v_q) - -@@ -2211,8 +2657,8 @@ def test_sparse_atten_nvfp4_kv_te_quantized_flat_smoke() -> None: - inputs["q"], - k_q.data, - v_q.data, -- k_q.scale_128x4, -- v_q.scale_128x4, -+ k_q.scale, -+ v_q.scale, - k_q.global_scale, - v_q.global_scale, - inputs["k2q_row_ptr"], -@@ -2237,7 +2683,7 @@ def test_sparse_atten_nvfp4_kv_te_quantized_flat_smoke() -> None: - @pytest.mark.parametrize("paged", [False, True]) - @pytest.mark.parametrize("qhead_per_kv", [1, 2, 4, 8, 16]) - @pytest.mark.parametrize("topk", [4, 8]) --def test_sparse_atten_nvfp4_kv_fp8_q_matches_block_scaled_fp8_reference( -+def test_sparse_atten_nvfp4_kv_fp8_q_matches_calibrated_fp8_reference( - topk: int, - qhead_per_kv: int, - paged: bool, -@@ -2280,15 +2726,14 @@ def test_sparse_atten_nvfp4_kv_fp8_q_matches_block_scaled_fp8_reference( - v_source = inputs["v"] ++ O(qi_group) is released through pipeline_o (gates PV(qi_group + 2)); the softmax ++ stats come through the 4-slot pipeline_sm_stats ring. ++ """ ++ tidx = cute.arch.thread_idx()[0] ++ warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) ++ warp_idx_in_wg = warp_idx % Int32(self.warps_per_group) ++ group_tidx = ( ++ warp_idx_in_wg * Int32(cute.arch.WARP_SIZE) ++ + tidx % Int32(cute.arch.WARP_SIZE) ++ ) ++ total_q = mQ_2d.shape[0] // head_q ++ thr0_pv = tiled_mma_pv.get_slice(0) ++ pv_acc_shape = thr0_pv.partition_shape_C(self.mma_tiler_pv[:2]) ++ tOtO_base = thr0_pv.make_fragment_C(pv_acc_shape) ++ corr_tile_size = 64 ++ tOcO = thr0_pv.partition_C( ++ cute.make_identity_tensor(self.mma_tiler_pv[:2])) ++ tOcO_i = cute.logical_divide( ++ tOcO, cute.make_layout((self.m_block_size, corr_tile_size))) ++ o_tmem_copy_atom = cute.make_copy_atom( ++ tcgen05.copy.Ld16x256bOp(tcgen05.copy.Repetition(8)), ++ self.pv_acc_dtype) ++ if has_work: ++ for qi_group in cutlass.range(num_q_groups, unroll=1): + self._epilogue_step( + qi_group, + group_tidx, +@@ -2851,7 +3166,7 @@ class SparseAttentionForwardNvfp4KvSm100: + q_batch_offset, + total_q, + False, +- stage, ++ 0, + ) - q_fp8 = inputs["q"].to(torch.float8_e4m3fn) -- k_q = _quantize_bf16_to_nvfp4_or_skip(k_source) -- v_q = _quantize_bf16_to_nvfp4_or_skip(v_source) -+ k_q, v_q = _quantize_kv_bf16_to_nvfp4(k_source, v_source) - fp8_max = torch.finfo(torch.float8_e4m3fn).max -- k_stage = _dequant_nvfp4_to_bf16(k_q, include_global_scale=False) -- v_stage = _dequant_nvfp4_to_bf16(v_q, include_global_scale=False) -+ # The block-scaled FP4 product is exactly representable in BF16. Apply -+ # the global scale in FP32, avoiding an extra BF16 rounding before FP8. -+ k_stage = _dequant_nvfp4_to_bf16(k_q, include_global_scale=False).float() * k_q.global_scale -+ v_stage = _dequant_nvfp4_to_bf16(v_q, include_global_scale=False).float() * v_q.global_scale - k_stage = k_stage.float().clamp(min=-fp8_max, max=fp8_max).to(torch.float8_e4m3fn) - v_stage = v_stage.float().clamp(min=-fp8_max, max=fp8_max).to(torch.float8_e4m3fn) -- k_global = float(k_q.global_scale.reshape(-1)[0].item()) -- v_global = float(v_q.global_scale.reshape(-1)[0].item()) + @cute.jit +@@ -2961,14 +3276,16 @@ class SparseAttentionForwardNvfp4KvSm100: + ): + slot = qi_group & Int32(1) + phase = (qi_group // Int32(2)) & Int32(1) ++ sm_meta = qi_group & Int32(self.sm_meta_stages - 1) ++ sm_phase = (qi_group // Int32(self.sm_meta_stages)) & Int32(1) + stage_base = slot * Int32(self.tmem_o_stage_stride) + corr_tile_size = 64 + sScale_slot = cute.make_tensor( +- sScale.iterator + slot * Int32(self.m_block_size * 2), ++ sScale.iterator + sm_meta * Int32(self.m_block_size * 2), + cute.make_layout(self.m_block_size * 2), + ) + sScale_temperature_slot = cute.make_tensor( +- sScaleTemperature.iterator + slot * Int32(self.m_block_size), ++ sScaleTemperature.iterator + sm_meta * Int32(self.m_block_size), + cute.make_layout(self.m_block_size), + ) + sSplitIdx_slot = cute.make_tensor( +@@ -2984,6 +3301,8 @@ class SparseAttentionForwardNvfp4KvSm100: + self.q_tokens_per_group) + + pipeline_o.consumer_wait_w_index_phase(slot, phase) ++ if const_expr(self.r2_store): ++ pipeline_sm_stats.consumer_wait_w_index_phase(sm_meta, sm_phase) + if const_expr(use_stats_barrier): + sm_stats_barrier.arrive_and_wait_w_index( + index=slot * Int32(self.warps_per_group) + warp_idx_in_wg) +@@ -3071,11 +3390,6 @@ class SparseAttentionForwardNvfp4KvSm100: + row_sum_val + if not is_zero_or_nan + else Float32(1.0)) +- if const_expr( +- self.q_dtype == cutlass.Float8E4M3FN +- and self.has_v_global_scale +- ): +- row_scale *= mVGlobalScale[0] + row_base_ptr = ( + flat_row * Int64(self.head_dim)) + o0 = tOrO_mn[r, c_base] +@@ -3133,11 +3447,6 @@ class SparseAttentionForwardNvfp4KvSm100: + row_sum_val + if not is_zero_or_nan + else Float32(1.0)) +- if const_expr( +- self.q_dtype == cutlass.Float8E4M3FN +- and self.has_v_global_scale +- ): +- row_scale *= mVGlobalScale[0] + row_base_ptr = ( + flat_row * Int64(self.head_dim)) + o0 = tOrO_mn[r, c_base] +@@ -3211,11 +3520,6 @@ class SparseAttentionForwardNvfp4KvSm100: + if not is_zero_or_nan + else Float32(1.0) + ) +- if const_expr( +- self.q_dtype == cutlass.Float8E4M3FN +- and self.has_v_global_scale +- ): +- row_scale *= mVGlobalScale[0] + row_base_ptr = flat_row * Int64(self.head_dim) + o0 = tOrO_mn[r, c_base] + o1 = tOrO_mn[r, c_base + Int32(1)] +@@ -3301,5 +3605,5 @@ class SparseAttentionForwardNvfp4KvSm100: + lse_temperature_cur) + epilogue_barrier.arrive_and_wait_w_index(index=Int32(softmax_stage)) + +- pipeline_sm_stats.consumer_release_w_index(slot) ++ pipeline_sm_stats.consumer_release_w_index(sm_meta) + pipeline_o.consumer_release_w_index(slot) +diff --git a/python/fmha_sm100/cute/src/sm100/fwd/combine.py b/python/fmha_sm100/cute/src/sm100/fwd/combine.py +index b9e6bbb..fa18fab 100644 +--- a/python/fmha_sm100/cute/src/sm100/fwd/combine.py ++++ b/python/fmha_sm100/cute/src/sm100/fwd/combine.py +@@ -27,6 +27,7 @@ from src.common.seqlen_info import SeqlenInfo + from cutlass.cute import FastDivmodDivisor + + from src.common.pack_gqa import PackGQAComb ++from src.common import mxfp8_epi + from src.common.tma_utils import ( + stg128_fake_col_to_real_col, + stg128_fp8_fake_col_to_real_col, +@@ -47,6 +48,7 @@ class SparseAttentionForwardCombine: + stages: int = 4, + use_pdl: bool = False, + min_blocks_per_mp: int = 0, ++ write_bf16: bool = True, + ): + """ + Forward combine kernel for split attention computation. +@@ -72,6 +74,10 @@ class SparseAttentionForwardCombine: + self.stages = stages + self.use_pdl = use_pdl + self.min_blocks_per_mp = min_blocks_per_mp ++ # MXFP8 epilogue (Host, CTX (b)): the final O also written as MXFP8 (E4M3 + K32 UE8M0 scales, swizzled ++ # 128x4) for the o_proj GEMM, bitwise mxfp8_quantize(O_bf16.view(total_q, nheads * head_dim), True). ++ # write_bf16=False skips the bf16 O store (only when nothing else reads it). ++ self.write_bf16 = write_bf16 + self.use_stg128_half_layout = dtype_partial in (cutlass.BFloat16, cutlass.Float16) + self.use_stg128_fp8_layout = dtype_partial is cutlass.Float8E4M3FN + +@@ -256,6 +262,8 @@ class SparseAttentionForwardCombine: + mSplitCounts: Optional[cute.Tensor] = None, + mOutputScale: Optional[cute.Tensor] = None, + qhead_per_kvhead: Int32 = Int32(1), ++ mOq: Optional[cute.Tensor] = None, ++ mSFq: Optional[cute.Tensor] = None, + # Always keep stream as the last parameter (EnvStream: obtained implicitly via TVM FFI). + stream: cuda.CUstream = None, + ): +@@ -432,6 +440,8 @@ class SparseAttentionForwardCombine: + mSplitCounts, + mOutputScale, + qhead_per_kvhead, ++ mOq, ++ mSFq, + SharedStorage, + self.smem_layout_lse, + self.smem_layout_o, +@@ -480,6 +490,8 @@ class SparseAttentionForwardCombine: + mSplitCounts: Optional[cute.Tensor], + mOutputScale: Optional[cute.Tensor], + qhead_per_kvhead: Int32, ++ mOq: Optional[cute.Tensor], ++ mSFq: Optional[cute.Tensor], + SharedStorage: cutlass.Constexpr, + smem_layout_lse: cute.Layout | cute.ComposedLayout, + smem_layout_o: cute.Layout | cute.ComposedLayout, +@@ -1110,19 +1122,94 @@ class SparseAttentionForwardCombine: + if const_expr(self.is_even_k) or tOpO_store[k]: + cute.autovec_copy(tOsO_store[None, m, k], rO[None, m, k]) + +- # Write bf16 to GMEM using gmem_tiled_copy_O (same as original FA Step 7) +- for m in cutlass.range(num_store_rows, unroll_full=True): +- row_local = tOcO_store[0, m, 0][0] +- idx = m_block * self.tile_m + row_local +- if idx < max_idx: +- m_idx, head_idx = self.decode_flat_row_idx(idx, head_divmod) +- mO_cur_copy = cute.tiled_divide( +- mO_cur[m_idx, None, head_idx], (elems_per_store,) +- ) +- for k in cutlass.range(cute.size(tOcO_store, mode=[2]), unroll_full=True): +- k_idx = tOcO_store[0, 0, k][1] // elems_per_store +- if const_expr(self.is_even_k) or tOpO_store[k]: +- cute.copy(gmem_thr_copy_O, rO[None, m, k], mO_cur_copy[None, k_idx]) ++ if const_expr(self.write_bf16): ++ # Write bf16 to GMEM using gmem_tiled_copy_O (same as original FA Step 7) ++ for m in cutlass.range(num_store_rows, unroll_full=True): ++ row_local = tOcO_store[0, m, 0][0] ++ idx = m_block * self.tile_m + row_local ++ if idx < max_idx: ++ m_idx, head_idx = self.decode_flat_row_idx(idx, head_divmod) ++ mO_cur_copy = cute.tiled_divide( ++ mO_cur[m_idx, None, head_idx], (elems_per_store,) ++ ) ++ for k in cutlass.range(cute.size(tOcO_store, mode=[2]), unroll_full=True): ++ k_idx = tOcO_store[0, 0, k][1] // elems_per_store ++ if const_expr(self.is_even_k) or tOpO_store[k]: ++ cute.copy(gmem_thr_copy_O, rO[None, m, k], mO_cur_copy[None, k_idx]) ++ ++ if const_expr(mOq is not None): ++ self.quant_rows_mxfp8( ++ rO, tOcO_store, mOq, mSFq, m_block, max_idx, offset, head_divmod, num_store_rows ++ ) ++ ++ @cute.jit ++ def quant_rows_mxfp8( ++ self, ++ rO: cute.Tensor, ++ tOcO_store: cute.Tensor, ++ mOq: cute.Tensor, ++ mSFq: cute.Tensor, ++ m_block: Int32, ++ max_idx: Int32, ++ offset: Int32, ++ head_divmod: FastDivmodDivisor, ++ num_store_rows: cutlass.Constexpr[int], ++ ): ++ """The tile's final O rows as MXFP8 for the o_proj GEMM, from the bf16 registers 7b read out of sO_perm (one ++ SMEM pass). 7b's copy gives each thread 8 consecutive real columns of a row and 16 consecutive lanes per row ++ (k_block 128), the stock quantize_mxfp8_rows mapping: 4 lanes per K32 block, so amax / scale / E4M3 are ++ bitwise mxfp8_quantize of the bf16 output. mOq: uint8 [total_q, nheads * head_dim]; mSFq: uint8 swizzled ++ 128x4 scales (padding rows zeroed by the caller).""" ++ assert cute.size(tOcO_store, mode=[0]) == 8 and cute.size(tOcO_store, mode=[2]) == 1 ++ num_head = Int32(mOq.shape[1] // self.head_dim) ++ col0 = tOcO_store[0, 0, 0][1] ++ lane_block = col0 // 8 ++ for m in cutlass.range_constexpr(num_store_rows): ++ row_local = tOcO_store[0, m, 0][0] ++ idx = m_block * self.tile_m + row_local ++ vals = cute.make_rmem_tensor((8,), Float32) ++ for i in cutlass.range_constexpr(8): ++ vals[i] = rO[i, m, 0].to(Float32) ++ vmax = mxfp8_epi.fabs_f32(vals[0]) ++ for i in cutlass.range_constexpr(1, 8): ++ vmax = mxfp8_epi.fmax_f32(vmax, mxfp8_epi.fabs_f32(vals[i])) ++ # amax over the 4 lanes of a K32 block (consecutive lanes of one warp, one row). ++ vmax = mxfp8_epi.fmax_f32(vmax, cute.arch.shuffle_sync_bfly(vmax, offset=1)) ++ vmax = mxfp8_epi.fmax_f32(vmax, cute.arch.shuffle_sync_bfly(vmax, offset=2)) ++ sf_bits = mxfp8_epi.ue8m0_round_up(vmax * mxfp8_epi.rcp_approx_ftz(Float32(448.0))) ++ out_scale = Float32(0.0) ++ if vmax != Float32(0.0): ++ out_scale = mxfp8_epi.rcp_approx_ftz(mxfp8_epi.ue8m0_to_f32(sf_bits)) ++ if idx < max_idx: ++ m_idx, head_idx = self.decode_flat_row_idx(idx, head_divmod) ++ tok = offset + m_idx ++ q0 = utils.cvt_fp8x4_e4m3_f32( ++ vals[0] * out_scale, vals[1] * out_scale, vals[2] * out_scale, vals[3] * out_scale ++ ) ++ q1 = utils.cvt_fp8x4_e4m3_f32( ++ vals[4] * out_scale, vals[5] * out_scale, vals[6] * out_scale, vals[7] * out_scale ++ ) ++ qp = cute.make_ptr( ++ dtype=cutlass.Int32, ++ value=mOq.iterator.toint() ++ + Int64(tok) * Int64(mOq.shape[1]) ++ + Int64(head_idx * self.head_dim + col0), ++ mem_space=mOq.iterator.memspace, ++ assumed_align=8, ++ ) ++ qt = cute.make_tensor(qp, cute.make_layout((2,), stride=(1,))) ++ qt[0] = q0 ++ qt[1] = q1 ++ if lane_block % 4 == 0: ++ k_idx = head_idx * (self.head_dim // 32) + lane_block // 4 ++ sf_off = mxfp8_epi.sf_offset_128x4(tok, k_idx, num_head * (self.head_dim // 128)) ++ sp = cute.make_ptr( ++ dtype=cutlass.Uint8, ++ value=mSFq.iterator.toint() + Int64(sf_off), ++ mem_space=mSFq.iterator.memspace, ++ assumed_align=1, ++ ) ++ cute.make_tensor(sp, cute.make_layout((1,), stride=(1,)))[0] = cutlass.Uint8(sf_bits) - if paged: - k_ref_chunks = [] -@@ -2315,20 +2760,19 @@ def test_sparse_atten_nvfp4_kv_fp8_q_matches_block_scaled_fp8_reference( - q_lens=inputs["q_lens"], - k_lens=inputs["k_lens"], - blk_kv=inputs["blk_kv"], -- softmax_scale=inputs["softmax_scale"] * k_global, -+ softmax_scale=inputs["softmax_scale"], - causal=causal, - upcast=True, - seqused_k=inputs["seqused_k"] if paged else None, - p_dtype=torch.float8_e4m3fn, + @cute.jit + def load_O_partial( +@@ -1210,6 +1297,9 @@ def combine( + split_counts=None, + output_scale=None, + use_pdl=False, ++ o_fp8=None, ++ sf_out=None, ++ write_bf16=True, + ): + """K2: merge sparse forward split partials into the final output. + +@@ -1245,7 +1335,28 @@ def combine( + provided, the final O accumulator is multiplied once before store. + use_pdl: When True, wait on PDL dependencies from the producer K1 + kernel. When False, launch without PDL waits. ++ o_fp8, sf_out: Optional MXFP8 copy of the final O for the o_proj GEMM (Host, CTX (b)): ++ o_fp8 uint8/float8_e4m3fn [total_q, head_q * dim] and sf_out uint8 1-D swizzled 128x4 K32 UE8M0 ++ scales of [total_q, head_q * dim]; bitwise mxfp8_quantize(o_out.view(total_q, -1), True). The ++ caller zeroes sf_out's padding rows (total_q .. pad128). Varlen + use_pdl only. ++ write_bf16: False skips the bf16 o_out store (only valid with o_fp8 and no other reader of o_out). + """ ++ emit_mxfp8 = o_fp8 is not None ++ if (o_fp8 is None) != (sf_out is None): ++ raise ValueError("o_fp8 and sf_out must be given together") ++ if not write_bf16 and not emit_mxfp8: ++ raise ValueError("write_bf16=False requires the MXFP8 output") ++ if emit_mxfp8: ++ if cu_seqlens is None or not use_pdl or o_out.ndim != 3: ++ raise ValueError("the MXFP8 combine epilogue supports the varlen use_pdl path only") ++ if o_out.dtype != torch.bfloat16 or o_partial_fake.shape[-1] != 128: ++ raise ValueError("the MXFP8 combine epilogue needs a bf16 output and head_dim 128") ++ o_fp8 = o_fp8.view(torch.uint8) ++ if o_fp8.shape != (o_out.shape[0], o_out.shape[1] * o_out.shape[2]) or not o_fp8.is_contiguous(): ++ raise ValueError(f"o_fp8 must be contiguous [total_q, head_q * dim], got {tuple(o_fp8.shape)}") ++ rows_padded = (o_out.shape[0] + 127) // 128 * 128 ++ if sf_out.dtype != torch.uint8 or sf_out.numel() < rows_padded * o_fp8.shape[1] // 32: ++ raise ValueError("sf_out must be uint8 with the padded 128x4 swizzled size") + D = o_partial_fake.shape[-1] + num_splits = o_partial_fake.shape[0] + return_temperature_lse = ( +@@ -1352,6 +1463,8 @@ def combine( + has_output_scale, + use_pdl, + min_blocks_per_mp, ++ emit_mxfp8, ++ write_bf16, ) -- out_ref = out_ref * v_global + if key not in _combine_compile_cache: + from src.common.aot_cache import try_load_aot, save_aot +@@ -1371,6 +1484,7 @@ def combine( + topk=num_splits, + use_pdl=use_pdl, + min_blocks_per_mp=min_blocks_per_mp, ++ write_bf16=write_bf16, + # stages=2 halves per-block SMEM (168 KB -> 103 KB) -> 2 blocks/SM, + # theoretical occupancy 12.5% -> 25%. NCU DRAM throughput 76.35% + # -> 88.64%. Runtime latency within noise (kernel already at HBM +@@ -1452,6 +1566,16 @@ def combine( + if has_output_scale + else None + ) ++ mOq = ( ++ make_fake_tensor(cutlass.Uint8, (cute.sym_int64(), cute.sym_int64()), divisibility=16, leading_dim=1) ++ if emit_mxfp8 ++ else None ++ ) ++ mSFq = ( ++ make_fake_tensor(cutlass.Uint8, (cute.sym_int64(),), divisibility=4, leading_dim=0) ++ if emit_mxfp8 ++ else None ++ ) + stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) + + _combine_compile_cache[key] = cute.compile( +@@ -1474,6 +1598,8 @@ def combine( + mSplitCounts, + mOutputScale, + Int32(qheadperkv), ++ mOq, ++ mSFq, + stream, + options="--enable-tvm-ffi", + ) +@@ -1495,4 +1621,6 @@ def combine( + split_counts, + output_scale, + qheadperkv, ++ o_fp8, ++ sf_out, + ) +diff --git a/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py b/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py +index 8ccc2cb..daf0e74 100644 +--- a/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py ++++ b/python/fmha_sm100/cute/src/sm100/fwd_decode/atten_fwd.py +@@ -424,7 +424,13 @@ class SparseDecodeAttentionForwardSm100: + self.tile_scheduler_cls = DecodeTileScheduler + grid = DecodeTileScheduler.get_grid_shape(tile_sched_params) - out, lse = sparse_atten_nvfp4_kv_func( - q_fp8, - k_q.data, - v_q.data, -- k_q.scale_128x4, -- v_q.scale_128x4, -+ k_q.scale, -+ v_q.scale, - k_q.global_scale, - v_q.global_scale, - inputs["k2q_row_ptr"], -@@ -2366,8 +2810,14 @@ def test_sparse_atten_nvfp4_kv_fp8_q_without_global_scale_matches_reference() -> - q2k_pattern=Q2KPattern.UNIFORM, - ) - q_fp8 = inputs["q"].to(torch.float8_e4m3fn) -- k_q = _make_synthetic_nvfp4_tensor(tuple(inputs["k"].shape)) -- v_q = _make_synthetic_nvfp4_tensor(tuple(inputs["v"].shape)) -+ k_q = _make_synthetic_nvfp4_tensor( -+ tuple(inputs["k"].shape), -+ layout=NVFP4_K_SCALE_LAYOUT, -+ ) -+ v_q = _make_synthetic_nvfp4_tensor( -+ tuple(inputs["v"].shape), -+ layout=NVFP4_V_SCALE_LAYOUT, -+ ) - fp8_max = torch.finfo(torch.float8_e4m3fn).max - k_ref = _dequant_nvfp4_to_bf16( - k_q, -@@ -2395,8 +2845,8 @@ def test_sparse_atten_nvfp4_kv_fp8_q_without_global_scale_matches_reference() -> - q_fp8, - k_q.data, - v_q.data, -- k_q.scale_128x4, -- v_q.scale_128x4, -+ k_q.scale, -+ v_q.scale, - None, - None, - inputs["k2q_row_ptr"], -@@ -2560,10 +3010,13 @@ def test_sparse_decode_page_fp8_forward(kv_tokens: int) -> None: +- clc_response_size = self.sched_stages * 4 if self.use_clc_scheduler else 0 ++ # One CLC response record per scheduler stage. A response is a 16B ++ # opaque record that `cute.arch.clc_response` reads back with a ++ # 128-bit `universal_copy`, so each slot must be 16B aligned. cute ++ # derives a MemRange's alignment from its element width, so the range ++ # is typed Int128 rather than 4 x Int32 (which only guarantees 4B and ++ # makes the copy fail the `cute.copy` verifier). ++ clc_response_size = self.sched_stages if self.use_clc_scheduler else 0 + clc_mbar_size = self.sched_stages * 2 if self.use_clc_scheduler else 0 - out, lse = _run_sparse_decode_page_fp8(fn, inputs) - out_ref, lse_ref = _decode_paged_dense_reference(inputs) -+ out_ref_exact, _ = _decode_paged_dense_reference(inputs, p_dtype=None) - assert out.dtype == torch.bfloat16 - assert out.shape == inputs["q"].shape - assert lse.shape == inputs["q"].shape[:2] -- _assert_fp8_forward_close(out, out_ref, lse, lse_ref) -+ _assert_fp8_forward_close( -+ out, out_ref, lse, lse_ref, out_ref_unquantized_p=out_ref_exact -+ ) + # ------------------------------------------------------------------ +@@ -455,7 +461,7 @@ class SparseDecodeAttentionForwardSm100: + tmem_dealloc_mbar_ptr: Int64 + tmem_holding_buf: Int32 + clc_mbar_ptr: cute.struct.MemRange[cutlass.Int64, clc_mbar_size] +- clc_response: cute.struct.MemRange[Int32, clc_response_size] ++ clc_response: cute.struct.MemRange[cutlass.Int128, clc_response_size] + sQ: cute.struct.Align[ + cute.struct.MemRange[self.q_dtype, cute.cosize(sQ_layout)], + self.buffer_align_bytes, +@@ -1536,8 +1542,8 @@ class SparseDecodeAttentionForwardSm100: + tOtO1_t2r_i = tOtO1_t2r[None, 0, 0, col_pass_idx] + tOsO_r2s_i = tOsO_s2r[None, 0, 0, col_pass_idx] + frg_shape = tOcO_t2r[None, 0, 0, col_pass_idx].shape +- tOrO0_frg = cute.make_fragment(frg_shape, self.pv_acc_dtype) +- tOrO1_frg = cute.make_fragment(frg_shape, self.pv_acc_dtype) ++ tOrO0_frg = cute.make_rmem_tensor(frg_shape, self.pv_acc_dtype) ++ tOrO1_frg = cute.make_rmem_tensor(frg_shape, self.pv_acc_dtype) + is_zero_output = ( + scale0 == Float32(0.0) and scale1 == Float32(0.0) + ) +@@ -1600,8 +1606,7 @@ class SparseDecodeAttentionForwardSm100: + frg_count: cutlass.Constexpr[int] = self.head_dim // corr_tile_size + for fi in cutlass.range_constexpr(frg_count): +- tOrO_frg = cute.make_fragment( +- tOrO_t2r_shape, self.pv_acc_dtype) ++ tOrO_frg = cute.make_rmem_tensor(tOrO_t2r_shape, self.pv_acc_dtype) + tOtO_t2r_i = cute.make_tensor( + tOtO_t2r.iterator + fi * corr_tile_size, + tOtO_t2r.layout, +@@ -1708,6 +1713,11 @@ class SparseDecodeAttentionForwardSm100: + pipeline.PipelineUserType.Consumer, self.kv_stage) + phase_s0 = Int32(0) + phase_s1 = Int32(0) ++ # pipeline_o_acc producer phases. Producers start at phase 1 so the ++ # very first acquire passes trivially (same convention as ++ # ``corr_epi_producer_phase`` in correction_loop). ++ o_acc_producer_phase0 = Int32(1) ++ o_acc_producer_phase1 = Int32(1) - def test_sparse_decode_page_fp8_forward_forced_split_kv_tile_aligned_partial() -> None: -@@ -2596,7 +3049,10 @@ def test_sparse_decode_page_fp8_forward_forced_split_kv_tile_aligned_partial() - - return_softmax_lse=True, - ) - out_ref, lse_ref = _decode_paged_dense_reference(inputs) -- _assert_fp8_forward_close(out, out_ref, lse, lse_ref) -+ out_ref_exact, _ = _decode_paged_dense_reference(inputs, p_dtype=None) -+ _assert_fp8_forward_close( -+ out, out_ref, lse, lse_ref, out_ref_unquantized_p=out_ref_exact -+ ) + work_tile = tile_scheduler.initial_work_tile_info() + while work_tile.is_valid_tile: +@@ -1727,6 +1737,52 @@ class SparseDecodeAttentionForwardSm100: + block_iter_count_mma = ( + page_count_mma + Int32(1)) & ~Int32(1) ++ # --------------------------------------------------------- ++ # Tile-level O-accumulator acquire. ++ # ++ # The MMA is the pipeline_o_acc producer but used to ++ # ``producer_commit`` without ever calling producer_acquire, ++ # so nothing bounded how far ahead of the correction warp it ++ # could run *across work tiles*. That matters because the ++ # softmax->correction stats mailbox (row_sum / row_max / ++ # acc_scale) lives in the first two columns of the S ++ # accumulator, TMEM S[stage][:, 0:2] (see the ++ # ``tStS_vec_layout`` compositions in softmax_loop and ++ # correction_loop). The first QK GEMM of the *next* work ++ # tile overwrites S[stage] wholesale and therefore destroys ++ # the stats the correction warp is about to read. ++ # ++ # The only thing that previously ordered that overwrite was ++ # the borrowed pipeline_s_p_o credit chain, whose depth is ++ # ``block_iter_count // 2`` acquires per tile. With ++ # block_iter_count == 2 (per-split chunk of 1 or 2 pages) ++ # that depth is 1, and the license to clobber S[stage] in ++ # tile N+1 comes from tile N-1's correction release -- a ++ # full tile stale. The MMA then races the correction warp ++ # for the tile-N stats and wins often enough to corrupt ++ # ~50% of the partial rows (negative/garbage row_sum -> ++ # log2(neg) -> NaN LSE_partial -> garbage after combine). ++ # ++ # pipeline_o_acc already has exactly the right semantics -- ++ # the correction warp releases it (correction_loop, right ++ # after it has read the final stats and run the epilogue ++ # combine) -- it was simply never waited on. Acquiring it ++ # here, before the first QK of the tile, makes the producer ++ # side of pipeline_o_acc well formed (1 acquire + 1 commit ++ # per stage per tile against 1 wait + 1 release on the ++ # consumer side) and bounds the MMA to at most one tile ++ # ahead of the correction warp for every chunk size. ++ # --------------------------------------------------------- ++ if block_iter_count_mma > Int32(0): ++ pipeline_o_acc.producer_acquire_w_index_phase( ++ Int32(0), o_acc_producer_phase0) ++ pipeline_o_acc.producer_acquire_w_index_phase( ++ Int32(1), o_acc_producer_phase1) ++ o_acc_producer_phase0 = ( ++ o_acc_producer_phase0 ^ Int32(1)) ++ o_acc_producer_phase1 = ( ++ o_acc_producer_phase1 ^ Int32(1)) ++ + pipeline_q.consumer_wait_w_index_phase( + Int32(0), mma_q_consumer_phase) + mma_q_consumer_phase = mma_q_consumer_phase ^ Int32(1) +@@ -1899,7 +1955,7 @@ class SparseDecodeAttentionForwardSm100: + tmem_load_atom_pre: cute.CopyAtom, + tmem_store_atom_pre: cute.CopyAtom, + tmem_store_vec_atom_pre: cute.CopyAtom, +- thr_mma_qk_pre: cute.core.ThrMma, ++ thr_mma_qk_pre: cute.ThrMma, + pipeline_s_p_o: pipeline.PipelineAsync, + pipeline_p_lastsplit: pipeline.PipelineAsync, + pipeline_sm_stats: pipeline.PipelineAsync, +diff --git a/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py b/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py +index 599dace..f29b5b0 100644 +--- a/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py ++++ b/python/fmha_sm100/cute/src/sm100/fwd_decode/tile_scheduler.py +@@ -179,8 +179,10 @@ class DecodeTileScheduler: + ) -> WorkTileInfo: + # CLC responses are 16B opaque records. The scheduler warp can query + # the next stage before all consumer warps have read the current one, +- # so each pipeline stage needs its own response slot. +- response_ptr = self._clc_response_ptr + response_stage * Int32(4) ++ # so each pipeline stage needs its own response slot. The slot ++ # array is typed Int128 in SharedStorage, so the stage index is also ++ # the element index and the 16B alignment survives the offset. ++ response_ptr = self._clc_response_ptr + response_stage + m_idx, n_idx, l_idx, is_valid = cute.arch.clc_response( + response_ptr, loc=loc, ip=ip) + cute.arch.fence_proxy("async.shared", space="cta") +@@ -239,7 +241,7 @@ class DecodeTileScheduler: + ): + if const_expr(self.params.scheduling_mode == SchedulingMode.CLC): + assert mbarrier_addr is not None +- response_ptr = self._clc_response_ptr + response_stage * Int32(4) ++ response_ptr = self._clc_response_ptr + response_stage + with cute.arch.elect_one(): + cute.arch.issue_clc_query( + mbarrier_addr, response_ptr, loc=loc, ip=ip) +diff --git a/python/fmha_sm100/cute/test_sparse_atten.py b/python/fmha_sm100/cute/test_sparse_atten.py +index 21c777e..fa48c96 100644 +--- a/python/fmha_sm100/cute/test_sparse_atten.py ++++ b/python/fmha_sm100/cute/test_sparse_atten.py +@@ -19,9 +19,11 @@ from __future__ import annotations - # --------------------------------------------------------------------------- -@@ -2943,10 +3399,12 @@ def _build_sparse_nvfp4_kv_benchmark_context( - raise ValueError(f"Unsupported NVFP4 KV benchmark Q dtype: {q_dtype}") - k_q = _make_synthetic_nvfp4_tensor( - tuple(k_source.shape), -+ layout=NVFP4_K_SCALE_LAYOUT, - global_scale_value=0.75, - ) - v_q = _make_synthetic_nvfp4_tensor( - tuple(v_source.shape), -+ layout=NVFP4_V_SCALE_LAYOUT, - global_scale_value=1.25, - ) - k_bf16 = _dequant_nvfp4_to_bf16(k_q) -@@ -2990,8 +3448,8 @@ def _build_sparse_nvfp4_kv_benchmark_context( - q, - k_q.data, - v_q.data, -- k_q.scale_128x4, -- v_q.scale_128x4, -+ k_q.scale, -+ v_q.scale, - k_q.global_scale, - v_q.global_scale, - k2q_row_ptr, -diff --git a/python/fmha_sm100/jit.py b/python/fmha_sm100/jit.py ---- a/python/fmha_sm100/jit.py -+++ b/python/fmha_sm100/jit.py -@@ -1,4 +1,5 @@ - # SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax -+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES - # SPDX-License-Identifier: MIT + import argparse + import math ++import os + import sys + import types + from contextlib import contextmanager ++from pathlib import Path + from typing import Optional - """Per-variant lazy JIT compilation for FMHA varlen kernels. -@@ -6,11 +7,12 @@ - Each FMHA variant (dtype x tile x sparse x page x split_kv x pack_factor) is compiled - independently on first use and cached to ~/.cache/minfer/fmha_sm100/. + import pytest +@@ -61,6 +63,78 @@ DECODE_DIM = 128 + DECODE_KV_TOKEN_SWEEP = tuple(2**exp for exp in range(3, 21)) --To recompile after kernel changes: scripts/clear_fmha_cache.sh -+Source changes select a new cache automatically; prewarm using the same sources. - """ - import itertools - import fcntl -+import hashlib - import logging - import os - import shutil -@@ -22,11 +24,18 @@ ++def test_prepare_paged_hnd_input_keeps_aligned_outer_page_stride() -> None: ++ pages, roles, heads, page_size, head_dim = 5, 3, 2, 128, 128 ++ pool = torch.empty( ++ pages, ++ roles, ++ heads, ++ page_size, ++ head_dim, ++ dtype=torch.float8_e4m3fn, ++ device="cuda", ++ ) ++ view = pool[:, 1] ++ ++ assert not view.is_contiguous() ++ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size) ++ assert prepared.data_ptr() == view.data_ptr() ++ assert prepared.stride() == view.stride() ++ ++ ++def test_prepare_paged_hnd_input_materializes_unpacked_tokens() -> None: ++ pages, heads, page_size, head_dim = 5, 2, 128, 128 ++ storage = torch.arange( ++ pages * heads * page_size * 2 * head_dim, ++ dtype=torch.int32, ++ device="cuda", ++ ).remainder(16).to(torch.float8_e4m3fn).reshape(pages, heads, page_size * 2, head_dim) ++ view = storage[:, :, ::2, :] ++ ++ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size) ++ assert prepared.is_contiguous() ++ assert prepared.data_ptr() != view.data_ptr() ++ torch.testing.assert_close(prepared, view, rtol=0, atol=0) ++ ++ ++def test_prepare_paged_hnd_input_materializes_unaligned_outer_stride() -> None: ++ pages, heads, page_size, head_dim = 5, 2, 128, 128 ++ outer_stride = heads * page_size * head_dim + 1 ++ storage = torch.arange( ++ pages * outer_stride, ++ dtype=torch.int32, ++ device="cuda", ++ ).remainder(16).to(torch.float8_e4m3fn) ++ view = storage.as_strided( ++ (pages, heads, page_size, head_dim), ++ (outer_stride, page_size * head_dim, head_dim, 1), ++ ) ++ ++ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size) ++ assert prepared.is_contiguous() ++ assert prepared.data_ptr() != view.data_ptr() ++ torch.testing.assert_close(prepared, view, rtol=0, atol=0) ++ ++ ++def test_prepare_paged_hnd_input_defers_page_size_validation() -> None: ++ pages, roles, heads, page_size, head_dim = 5, 2, 2, 128, 128 ++ pool = torch.empty( ++ pages, ++ roles, ++ heads, ++ page_size, ++ head_dim, ++ dtype=torch.float8_e4m3fn, ++ device="cuda", ++ ) ++ view = pool[:, 0] ++ ++ prepared = sparse_interface._prepare_paged_hnd_input(view, page_size // 2) ++ assert prepared.data_ptr() == view.data_ptr() ++ with pytest.raises(ValueError, match="page_size == blk_kv"): ++ sparse_interface._prepare_paged_kv_for_tma(prepared, prepared, page_size // 2) ++ ++ + @contextmanager + def _nvtx_range(message: str): + torch.cuda.nvtx.range_push(message) +@@ -435,12 +509,116 @@ def _install_flash_attn3_stub_for_te_import() -> None: + sys.modules.setdefault("flash_attn_3.flash_attn_interface", interface) - logger = logging.getLogger(__name__) -+# Kernel sources and CUTLASS headers are shipped inside the package directory -+# so that JIT compilation works from both editable and wheel installs. -+_PACKAGE_DIR = Path(__file__).resolve().parent -+_FMHA_VARLEN_DIR = _PACKAGE_DIR / "csrc" -+_CUTLASS_DIR = _PACKAGE_DIR / "cutlass" -+_CUTLASS_INCLUDE = _CUTLASS_DIR / "include" -+_CUTLASS_UTIL_INCLUDE = _CUTLASS_DIR / "tools" / "util" / "include" ++# The kernel reads exactly one scale-factor layout pair, unconditionally: K ++# linear (`t*S + s`) and V in the 4x4 token-quad swizzle ++# (`(t//4)*(4*S) + 4*s + (t%4)`). There is no third option, no runtime flag and ++# no 128x4 path left anywhere in the branch. ++NVFP4_K_SCALE_LAYOUT = "linear" ++NVFP4_V_SCALE_LAYOUT = "swizzle4x4" + + - def _compute_cache_base(): - explicit = os.environ.get("MINFER_FMHA_CACHE_DIR") -- if explicit: -- return Path(explicit) -- base = Path(os.path.expanduser("~/.cache/minfer/fmha_sm100")) -+ base = Path(explicit) if explicit else Path(os.path.expanduser("~/.cache/minfer/fmha_sm100")) - # Different build configs get separate cache dirs to avoid conflicts - suffix = "" - if os.environ.get("GPU_TRACE") is not None: -@@ -35,9 +44,27 @@ - suffix += "_sm_timing" - if os.environ.get("FMHA_GMEM_CHECK") is not None: - suffix += "_gmem_check" -- if suffix: -+ if suffix and not explicit: - base = base.parent / (base.name + suffix) -- return base ++def _pack_synthetic_nvfp4_scale( ++ logical: torch.Tensor, ++ *, ++ layout: str, ++) -> torch.Tensor: ++ """Pack a *logical* block-scale array into the bytes the kernel reads. + -+ # Hash templates, bindings and headers together; jit.py also covers changes -+ # to dispatch and compiler flags. Use relative names so installs share keys. -+ digest = hashlib.sha256() -+ sources = sorted(path for path in _FMHA_VARLEN_DIR.rglob("*") if path.is_file()) -+ sources.append(_PACKAGE_DIR / "jit.py") -+ for path in sources: -+ content = path.read_bytes() -+ digest.update(path.relative_to(_PACKAGE_DIR).as_posix().encode() + b"\0") -+ digest.update(len(content).to_bytes(8, "little")) -+ digest.update(content) -+ # An explicit cache root must also isolate instrumented and normal binaries. -+ digest.update(suffix.encode()) -+ cache_base = base / ("sources_sha256_" + digest.hexdigest()) -+ logger.info( -+ "Using FMHA cache %s (source/build fingerprint; changed sources or " -+ "diagnostic modes require recompilation)", cache_base, ++ ``logical`` is indexed exactly like the interface's scale argument: ++ ``[num_pages, Hkv, page_size, S]`` when paged and ``[total_k, Hkv, S]`` ++ when flat. The result has the same shape and the same bytes, permuted ++ within each region. ++ ++ Only the *within-region* permutation comes from ++ ``quantize.pack_nvfp4_scale``. The region decomposition is re-derived here ++ from the kernel on purpose, so that a silent change of region on either ++ side surfaces as a failure rather than as agreement: ++ ++ * paged -- a region is one ``(page, head)`` pair covering ``page_size`` ++ tokens (``src/sm100/fwd/atten_fwd_nvfp4_kv.py::_scale_region_base``). ++ * flat -- a region is ``R`` consecutive global tokens of a single KV ++ head, laid out head-minor, with ``R = 1`` for ``"linear"`` and ++ ``R = 4`` for ``"swizzle4x4"`` ++ (``..._scale_region_base_flat``). ``R = 4`` requires ++ ``total_k % 4 == 0``. Flat is a test-only geometry with no production ++ producer, so it is not an ABI. ++ ++ ``"linear"`` is ``t*S + s``, i.e. plain row-major over ``[tokens, S]``, and ++ is therefore the identity for both geometries. ++ """ ++ ++ if layout == NVFP4_K_SCALE_LAYOUT: ++ return logical.contiguous() ++ if layout != NVFP4_V_SCALE_LAYOUT: ++ raise ValueError(f"unknown NVFP4 scale layout {layout!r}") ++ ++ from quantize import pack_nvfp4_scale ++ ++ if logical.ndim == 4: ++ num_pages, head_kv, page_size, scale_cols = (int(d) for d in logical.shape) ++ regions = logical.reshape(num_pages * head_kv, page_size, scale_cols) ++ packed = pack_nvfp4_scale( ++ regions.contiguous(), ++ page_size=page_size, ++ scale_cols=scale_cols, ++ layout=layout, ++ ) ++ return packed.reshape(num_pages, head_kv, page_size, scale_cols).contiguous() ++ ++ if logical.ndim != 3: ++ raise ValueError( ++ "logical NVFP4 scales must be rank-4 [num_pages, Hkv, page_size, S] " ++ f"or rank-3 [total_k, Hkv, S], got shape {tuple(logical.shape)}" ++ ) ++ total_k, head_kv, scale_cols = (int(d) for d in logical.shape) ++ if total_k % 4 != 0: ++ raise ValueError( ++ "the flat V swizzle tiles tokens in quads, so total_k must be a " ++ f"multiple of 4, got {total_k}" ++ ) ++ regions = ( ++ logical.reshape(total_k // 4, 4, head_kv, scale_cols) ++ .permute(0, 2, 1, 3) ++ .reshape(total_k // 4 * head_kv, 4, scale_cols) ++ .contiguous() + ) -+ return cache_base - - - CACHE_BASE = _compute_cache_base() -@@ -55,13 +82,6 @@ - os.close(fd) - - --# Kernel sources and CUTLASS headers are shipped inside the package directory --# so that JIT compilation works from both editable and wheel installs. --_PACKAGE_DIR = Path(__file__).resolve().parent --_FMHA_VARLEN_DIR = _PACKAGE_DIR / "csrc" --_CUTLASS_DIR = _PACKAGE_DIR / "cutlass" --_CUTLASS_INCLUDE = _CUTLASS_DIR / "include" --_CUTLASS_UTIL_INCLUDE = _CUTLASS_DIR / "tools" / "util" / "include" ++ packed = pack_nvfp4_scale( ++ regions, ++ page_size=4, ++ scale_cols=scale_cols, ++ layout=layout, ++ ) ++ return packed.reshape(total_k, head_kv, scale_cols).contiguous() ++ ++ + def _make_synthetic_nvfp4_tensor( + shape: tuple[int, ...], + *, ++ layout: str, + global_scale_value: float = 1.0, ++ generator: Optional[torch.Generator] = None, + ) -> object: +- """Create deterministic packed NVFP4 data with unit block/global scales.""" ++ """Create deterministic packed NVFP4 data with *varying* block scales. ++ ++ The block scales must vary for these tests to mean anything: with every ++ scale byte set to the same value, permuting the whole scale array leaves ++ the dequantized result bit-identical, so a wrong scale-layout decode in the ++ kernel is undetectable. Varying scales make the layout observable. ++ ++ Bytes 0x30..0x3E are positive E4M3 values in [0.5, 1.875] -- no NaN, zero ++ or denormal -- so the reference stays well conditioned. ++ ++ The scales are drawn in *logical* ``[..., S]`` order and only then packed, ++ so the same seed produces the same logical scale for a given ++ ``(token, scale_col)`` under every layout. Filling the *physical* array ++ with random bytes instead -- which is what the 128x4 version of this helper ++ did -- would make the logical scales a permutation of each other and no two ++ layouts would ever agree. ++ ++ Pass ``generator=`` when the draw must be independent of how many global ++ RNG draws the surrounding input builder happened to make; the golden gate ++ below depends on that. ++ """ - _PACK_FACTORS = [1,2,4,6,8,16] - # _PACK_FACTORS = [1, 6] -@@ -199,6 +219,9 @@ - "--expt-relaxed-constexpr", "--expt-extended-lambda", - "-gencode=arch=compute_100a,code=sm_100a", - "-gencode=arch=compute_103a,code=sm_103a", -+ # SM100-family image so the rest of the family can load these kernels; -+ # sm_100a/sm_103a are arch-conditional and outrank it on those devices. -+ "-gencode=arch=compute_100f,code=sm_100f", - "-static-global-template-stub=false", - "-DFLASHINFER_ENABLE_BF16", - "-DFLASHINFER_ENABLE_FP8_E4M3", -diff --git a/python/fmha_sm100/sparse.py b/python/fmha_sm100/sparse.py -index 7006fcd..9a09324 100644 ---- a/python/fmha_sm100/sparse.py -+++ b/python/fmha_sm100/sparse.py -@@ -79,11 +79,13 @@ from fp4_indexer_interface import fp4_indexer_block_scores # noqa: E402 - # (cute/quantize.py). - from quantize import ( # noqa: E402 - Nvfp4QuantizedTensor, -- dequantize_nvfp4_128x4_to_bf16, -+ dequantize_nvfp4_to_bf16, - nvfp4_global_scale_from_amax, -- quantize_bf16_to_nvfp4_128x4, -- quantize_kv_bf16_to_nvfp4_128x4, -- swizzle_nvfp4_scale_to_128x4, -+ nvfp4_scale_linear_offset, -+ nvfp4_scale_swizzle4x4_offset, -+ pack_nvfp4_scale, -+ quantize_bf16_to_nvfp4, -+ quantize_kv_bf16_to_nvfp4, - ) + from quantize import Nvfp4QuantizedTensor - __all__ = [ -@@ -98,9 +100,11 @@ __all__ = [ - "SparseK2qCsrBuilderSm100", - # nvfp4 quantization helpers - "Nvfp4QuantizedTensor", -- "quantize_bf16_to_nvfp4_128x4", -- "quantize_kv_bf16_to_nvfp4_128x4", -- "dequantize_nvfp4_128x4_to_bf16", -- "swizzle_nvfp4_scale_to_128x4", -+ "quantize_bf16_to_nvfp4", -+ "quantize_kv_bf16_to_nvfp4", -+ "dequantize_nvfp4_to_bf16", -+ "pack_nvfp4_scale", -+ "nvfp4_scale_linear_offset", -+ "nvfp4_scale_swizzle4x4_offset", - "nvfp4_global_scale_from_amax", - ] -diff --git a/python/fmha_sm100/sparse_fmha_adapter.py b/python/fmha_sm100/sparse_fmha_adapter.py -index 306b416..a564d47 100644 ---- a/python/fmha_sm100/sparse_fmha_adapter.py -+++ b/python/fmha_sm100/sparse_fmha_adapter.py -@@ -129,11 +129,19 @@ def sparse_fmha_plan( - batch = qo_segment_lens.shape[0] - gpu_device = torch.device('cuda') +@@ -448,21 +626,26 @@ def _make_synthetic_nvfp4_tensor( + raise ValueError("NVFP4 synthetic shape requires D divisible by 16") + rows = math.prod(int(dim) for dim in shape[:-1]) + scale_cols = int(shape[-1]) // 16 +- padded_rows = ((rows + 127) // 128) * 128 +- padded_cols = ((scale_cols + 3) // 4) * 4 ++ draw = {} if generator is None else {"generator": generator} + data = torch.randint( + 0, + 256, + (*shape[:-1], shape[-1] // 2), + device="cuda", + dtype=torch.uint8, ++ **draw, + ) +- scale_128x4 = torch.full( +- (padded_rows, padded_cols), +- 0x38, ++ # Drawn as rank-2 [rows, S] and reshaped, not drawn in the final rank: the ++ # golden capture script draws it that way, and only an identical draw makes ++ # the two comparable. ++ logical_scale = torch.randint( ++ 0x30, ++ 0x3F, ++ (rows, scale_cols), + device="cuda", + dtype=torch.uint8, +- ) ++ **draw, ++ ).reshape(*shape[:-1], scale_cols) + global_scale = torch.full( + (1,), + float(global_scale_value), +@@ -471,27 +654,62 @@ def _make_synthetic_nvfp4_tensor( + ) + return Nvfp4QuantizedTensor( + data=data, +- scale_128x4=scale_128x4, ++ scale=_pack_synthetic_nvfp4_scale(logical_scale, layout=layout), + global_scale=global_scale, + logical_scale_shape=(rows, scale_cols), +- original_shape=shape, ++ original_shape=tuple(shape), ++ layout=layout, + ) -+ # Stage the host lengths to the device once, asynchronously, and read every -+ # scalar below from the host copy. Planning runs on the critical path of -+ # input preparation, where a blocking copy or a device .item() would drain -+ # the CUDA queue. -+ qo_lens_gpu = qo_segment_lens.to(torch.int32).to(gpu_device, non_blocking=True) -+ kv_lens_host = kv_segment_lens.to(torch.int32) -+ kv_lens_gpu = kv_lens_host.to(gpu_device, non_blocking=True) -+ - cu_seqlens_q = torch.zeros(batch + 1, dtype=torch.int32, device=gpu_device) -- cu_seqlens_q[1:] = torch.cumsum(qo_segment_lens.to(torch.int32).to(gpu_device), dim=0) -+ cu_seqlens_q[1:] = torch.cumsum(qo_lens_gpu, dim=0) - cu_seqlens_k = torch.zeros(batch + 1, dtype=torch.int32, device=gpu_device) -- cu_seqlens_k[1:] = torch.cumsum(kv_segment_lens.to(torch.int32).to(gpu_device), dim=0) -+ cu_seqlens_k[1:] = torch.cumsum(kv_lens_gpu, dim=0) +-def _quantize_bf16_to_nvfp4_or_skip(x: torch.Tensor) -> object: ++def _quantize_bf16_to_nvfp4_with_layout(x: torch.Tensor, layout: str) -> object: ++ """Quantize one tensor to NVFP4 under an explicitly chosen SF layout. ++ ++ Used both for the correct layout and -- by the negative controls -- for the ++ wrong one. The kernel has no layout flag, so packing on the host with the ++ wrong ``layout=`` is the only way to build a mismatched input. ++ """ ++ + _install_flash_attn3_stub_for_te_import() +- from quantize import quantize_bf16_to_nvfp4_128x4 ++ from quantize import quantize_bf16_to_nvfp4 - max_seqlen_q = int(qo_segment_lens.max().item()) - max_seqlen_k = int(kv_segment_lens.max().item()) -@@ -144,11 +152,12 @@ def sparse_fmha_plan( - total_rows = sum((int(kl) + blk_kv - 1) // blk_kv for kl in kv_lens) +- try: +- return quantize_bf16_to_nvfp4_128x4(x) +- except RuntimeError as exc: +- pytest.skip(str(exc)) ++ return quantize_bf16_to_nvfp4(x, layout=layout) ++ ++ ++def _quantize_kv_bf16_to_nvfp4(k: torch.Tensor, v: torch.Tensor) -> tuple[object, object]: ++ """Quantize a BF16 K/V pair for the NVFP4 KV path. ++ ++ K is packed linear and V with the 4x4 token-quad swizzle, which is the one ++ layout pair the kernel reads. ++ ++ This deliberately does not skip on error. It used to swallow any ++ ``RuntimeError`` from the quantizer and call ``pytest.skip``, which turned a ++ missing Transformer Engine into 141 green-looking skips and silently removed ++ *all* NVFP4 accuracy coverage on machines that have the hardware -- and would ++ equally have hidden a genuine quantizer bug. The quantizer now has a ++ dependency-free PyTorch backend, so there is nothing left to be unavailable ++ and a raised error here is a real defect. ++ """ ++ ++ _install_flash_attn3_stub_for_te_import() ++ from quantize import quantize_kv_bf16_to_nvfp4 ++ ++ return quantize_kv_bf16_to_nvfp4(k, v) - if qo_offset is not None: -- seqused_k = (qo_segment_lens + qo_offset).to(torch.int32).to(gpu_device) -+ seqused_k = (qo_segment_lens + qo_offset).to(torch.int32).to(gpu_device, non_blocking=True) - else: -- seqused_k = kv_segment_lens.to(torch.int32).to(gpu_device) -+ seqused_k = kv_lens_gpu.clone() -- total_q = int(cu_seqlens_q[-1].item()) -+ # Equals cu_seqlens_q[-1], read on the host. -+ total_q = int(qo_segment_lens.sum()) - qhead_per_kv = num_qo_heads // num_kv_heads if num_kv_heads > 0 else 1 + def _dequant_nvfp4_to_bf16(qx: object, *, include_global_scale: bool = True) -> torch.Tensor: +- from quantize import dequantize_nvfp4_128x4_to_bf16 ++ """Reference dequantization. ++ ++ Layout-independent by construction: it reads ``qx.layout`` and undoes ++ whatever packing produced ``qx.scale``, so the same logical block scales ++ give the same BF16 K/V no matter how the FP4 kernel addresses the bytes. ++ That is what lets the BF16 reference stand as an absolute gate across the ++ layout change. ++ """ ++ ++ from quantize import dequantize_nvfp4_to_bf16 - target_q_per_cta = SPARSE_SCHEDULE_MODEL.balanced_target_q_per_cta( -@@ -169,11 +178,14 @@ def sparse_fmha_plan( +- return dequantize_nvfp4_128x4_to_bf16( ++ return dequantize_nvfp4_to_bf16( + qx, + include_global_scale=include_global_scale, ) - - return { -- "qo_segment_lens": qo_segment_lens, -+ "qo_segment_lens": qo_lens_gpu, - "cu_seqlens_q": cu_seqlens_q, - "qo_segment_offsets": cu_seqlens_q, - "cu_seqlens_k": cu_seqlens_k, -- "kv_segment_lens": kv_segment_lens.to(torch.int32).to(gpu_device), -+ # Host tensor: only the page-table builder consumes it, and it reads -+ # per-request page counts on the host. Kernels take the lengths from -+ # cu_seqlens_k and seqused_k. -+ "kv_segment_lens": kv_lens_host, - "seqused_k": seqused_k, - "max_seqlen_q": max_seqlen_q, - "max_seqlen_k": max_seqlen_k, -@@ -228,23 +240,83 @@ def _build_page_table( - page_size: int, - batch: int, - ) -> torch.Tensor: -- """Flat kv_indices → page_table [batch, max_pages_per_seq].""" -- kv_lens = kv_segment_lens.tolist() -- pages_per_batch = [(int(kl) + page_size - 1) // page_size for kl in kv_lens] -- max_pages = max(pages_per_batch) -- total = batch * max_pages -- buf = torch.zeros(total + 4, dtype=torch.int32, device=kv_indices.device) -- shift = ((-buf.data_ptr()) % 16) // 4 -- page_table = buf[shift : shift + total].view(batch, max_pages) -+ """Flat kv_indices → page_table [batch, max_pages_per_seq]. +@@ -1130,7 +1348,16 @@ def _decode_paged_dense_reference( + inputs: dict[str, object], + *, + chunk_tokens: int = 8192, ++ p_dtype: torch.dtype | None = torch.float8_e4m3fn, + ) -> tuple[torch.Tensor, torch.Tensor]: ++ """Reference decode attention. + -+ Each request's pages are a contiguous run of kv_indices, so the padded table -+ is kv_indices[start[b] + col] masked to the request's page count. One gather -+ builds it: a copy per request would dominate host time once the batch is -+ wide. ++ ``p_dtype`` selects the rounding applied to unnormalized P. The default ++ (e4m3) models the kernel. ``p_dtype=None`` skips that rounding entirely ++ and yields the same reference with its own P-quantization noise removed; ++ ``_assert_fp8_forward_close`` uses the difference of the two as a measured ++ noise floor. See the derivation in that function. + """ -+ lens = kv_segment_lens if kv_segment_lens.device.type == "cpu" else kv_segment_lens.cpu() -+ pages = (lens.to(torch.int64) + (page_size - 1)) // page_size -+ max_pages = int(pages.max()) -+ starts = torch.cumsum(pages, 0) - pages -+ # Both row descriptors travel in a single host-to-device copy. -+ meta = torch.stack((pages, starts)).to(kv_indices.device, non_blocking=True) -+ pages_dev = meta[0].unsqueeze(1) -+ starts_dev = meta[1].unsqueeze(1) + q = inputs["q"].float() + k_paged = inputs["k_paged"] + v_paged = inputs["v_paged"] +@@ -1231,7 +1458,11 @@ def _decode_paged_dense_reference( + # normalized probabilities here would model a different + # rounding point and overstate the kernel error for short-KV + # decode rows. +- p_unnorm = exp_scores.to(torch.float8_e4m3fn).float() ++ p_unnorm = ( ++ exp_scores ++ if p_dtype is None ++ else exp_scores.to(p_dtype).float() ++ ) + out_cur += torch.einsum("hst,td->shd", p_unnorm, v_chunk) + out_cur = out_cur / safe_row_sum.transpose(0, 1).unsqueeze(-1) + +@@ -1342,18 +1573,167 @@ def _assert_fp8_forward_close( + lse: torch.Tensor, + lse_ref: torch.Tensor, + partial_is_fp8: bool = False, ++ out_ref_unquantized_p: torch.Tensor | None = None, + ) -> None: ++ out_ref_f = out_ref.float() + out_ref_bf16 = out_ref.to(torch.bfloat16).float() +- bf16_floor = (out_ref_bf16 - out_ref.float()).abs().max().item() +- kernel_diff = (out.float() - out_ref_bf16).abs().max().item() +- # QK/LSE should be tight. O additionally includes P(e4m3) @ V(e4m3) +- # with hardware FP8 MMA accumulation, so allow the observed PV rounding +- # envelope up through topK=32 rather than a bf16-only floor. +- # With fp8 O_partial, each split additionally quantizes the partial output +- # to e4m3 before combine; this adds another ~6% relative error per split +- # and pushes the worst-case |diff| up to ~0.5 on the standard cases. +- floor = 5.0e-1 if partial_is_fp8 else 1.25e-1 +- assert kernel_diff <= max(floor, 4.0 * bf16_floor) ++ bf16_err = out_ref_bf16 - out_ref_f ++ bf16_floor = bf16_err.abs().max().item() ++ bf16_rms_floor = bf16_err.pow(2).mean().sqrt().item() ++ diff = out.float() - out_ref_bf16 ++ kernel_diff = diff.abs().max().item() ++ diff_rms = diff.pow(2).mean().sqrt().item() ++ out_scale = out_ref_bf16.abs().max().item() ++ out_rms = out_ref_bf16.pow(2).mean().sqrt().item() ++ # QK/LSE should be tight. O additionally includes P(e4m3) @ V(e4m3) with ++ # hardware FP8 MMA accumulation, so it needs a slacker bound -- but that ++ # bound has to be RELATIVE to |O|. It used to be the bare constant 0.125 ++ # (0.5 with fp8 O_partial), which is not scale-invariant: it silently gets ++ # stricter as the data grows. Making the synthetic NVFP4 block scales vary ++ # over [0.5, 1.875] instead of being pinned at 1.0 raised max|O| by 1.75x ++ # and raised |diff| by the same factor at *constant* relative error ++ # (measured 1.4-1.9% of max|O| in every scale window from constant-0x38 to ++ # 0x30-0x3E), and that alone flipped the test to failing. A relative bound ++ # would not have moved. ++ # ++ # Error model for the constant. P is rounded to E4M3, which carries 3 ++ # explicit mantissa bits, so its round-to-nearest relative error is at most ++ # 2**-4. The kernel and the reference arrive at P by different roundings, ++ # so any P entry may land one E4M3 step away; O = sum_j P_j V_j / sum_j P_j ++ # is a convex combination of V rows, so that carries into O as the same ++ # relative perturbation. With fp8 O_partial every split additionally ++ # re-quantizes the partial output to E4M3 before the combine, which ++ # empirically costs ~4x more (measured max 12.4% vs 4.3% relative) -- the ++ # same 4x the two old constants encoded, now expressed relatively. ++ # ++ # Calibration: 561 measurements over the fp8 and NVFP4 test set give a ++ # worst observed relative error of 4.35% (441 bf16-O_partial cases) and ++ # 12.38% (120 fp8-O_partial cases), i.e. 1.4x and 2.0x of headroom below ++ # the bounds used here. The 4 * bf16_floor term is the reference's own ++ # bf16 storage floor; bf16 keeps 8 significand bits, so it is bounded by ++ # 4 * 2**-8 * max|O| = 1.6% * max|O| and is scale-invariant too. The ++ # headroom figures above count only the rtol term, so they are lower ++ # bounds on the real margin. ++ # ++ # The rtol term above is *only* valid while the reference's own P entries ++ # stay inside E4M3's normal range. They do not, for long-KV decode. The ++ # reference normalizes P by the GLOBAL row max, so p_j = exp(s_j - max_j ++ # s_j) covers (0, 1]; as the KV length N grows the row max grows like ++ # sqrt(2 ln N) and an ever larger share of p_j falls below E4M3's smallest ++ # normal 2**-6, where the rounding error is an ABSOLUTE half-ulp of 2**-10 ++ # rather than a relative 2**-4. Measured on the decode sweep, the ++ # subnormal share of the reference's P goes 0.9% (N=8) -> 34% (N=8192) -> ++ # 74% (N=1048576). Meanwhile max|O| shrinks like 1/sqrt(N) (O is a convex ++ # combination of random V rows), so that absolute noise shows up as a ++ # relative error that climbs with N -- entirely on the reference's side. ++ # ++ # The kernel does not have this problem: it normalizes P against a ++ # per-tile running max (`rescale_threshold = 4.0` in ++ # src/sm100/fwd_decode/atten_fwd.py), never against a 1M-token global max. ++ # Measured against the same reference evaluated with an *unquantized* P, ++ # rms|kernel - exact| / rms|exact| is FLAT at 2.7% over N = 8192 .. ++ # 1048576, while rms|ref - exact| / rms|exact| climbs 2.68% -> 3.79% and ++ # max|ref - exact| / max|O| climbs 3.97% -> 12.74%. At N = 1048576 the ++ # kernel is closer to the unquantized answer (6.9%) than the reference is ++ # (12.7%). A bound that charges the reference's own quantization noise to ++ # the kernel is mis-modelled, not a kernel defect. ++ # ++ # So: when the caller can supply the same reference computed without the ++ # E4M3 P rounding, subtract the two to get that noise directly and admit ++ # it into the tolerance. This is measured from the *inputs*, not from the ++ # kernel, so it cannot be inflated by a broken kernel. Callers that do ++ # not supply it (all prefill/NVFP4 sites) keep exactly the previous bound. ++ e4m3_relative_ulp = 2.0**-4 ++ rtol = 4.0 * e4m3_relative_ulp if partial_is_fp8 else e4m3_relative_ulp ++ if out_ref_unquantized_p is None: ++ ref_noise_max = 0.0 ++ ref_noise_rms = 0.0 ++ else: ++ ref_noise = out_ref_f - out_ref_unquantized_p.float() ++ ref_noise_max = ref_noise.abs().max().item() ++ ref_noise_rms = ref_noise.pow(2).mean().sqrt().item() + -+ col = torch.arange(max_pages, device=kv_indices.device, dtype=torch.int64).unsqueeze(0) -+ mask = col < pages_dev -+ # Padded columns run past the end of a request's run, so clamp the gather -+ # index into range and zero them afterwards. -+ src = (starts_dev + col).clamp_(max=max(kv_indices.numel() - 1, 0)) -+ page_table = kv_indices.index_select(0, src.reshape(-1)).to(torch.int32) -+ page_table = page_table.view(batch, max_pages).masked_fill_(~mask, 0) - assert page_table.data_ptr() % 16 == 0, ( -- f"_build_page_table failed to align: buf=0x{buf.data_ptr():x} " -- f"shift={shift} page_table=0x{page_table.data_ptr():x}" -+ f"_build_page_table failed to align: page_table=0x{page_table.data_ptr():x}" ++ # Triangle inequality through the unquantized-P reference: ++ # |out - out_ref| <= |out - exact| + |exact - out_ref|. ++ # The second leg is ref_noise. The first leg is the kernel's own E4M3 P ++ # rounding, which is of the same class and (per the measurements above) ++ # never coarser, so it is charged the same quantity -- hence the factor 2. ++ tol = 4.0 * bf16_floor + rtol * out_scale + 2.0 * ref_noise_max ++ assert kernel_diff <= tol, ( ++ f"max|out - out_ref| = {kernel_diff:.6g} exceeds {tol:.6g} " ++ f"(= 4 * bf16_floor {bf16_floor:.6g} + rtol {rtol:.6g} " ++ f"* max|out_ref| {out_scale:.6g} + 2 * ref_quant_noise " ++ f"{ref_noise_max:.6g}); relative error " ++ f"{kernel_diff / max(out_scale, 1e-30):.4%}" + ) -+ return page_table -+ -+ -+def _version_token(tensor: torch.Tensor): -+ """Version counter for `tensor`, or None if it does not track one. -+ -+ Inference tensors have no version counter, so this is None on the serving -+ path and the caller falls back to identity checks alone. -+ """ -+ return None if torch.is_inference(tensor) else tensor._version -+ + -+def _page_table_for_plan( -+ plan_info: dict, -+ kv_indices: torch.Tensor, -+ kv_segment_lens: torch.Tensor, -+ page_size: int, -+ batch: int, -+) -> torch.Tensor: -+ """Return this plan's page table, building it at most once per step. ++ # The same model evaluated in RMS instead of at the single worst element. ++ # rms <= max elementwise, so the same relative constants are conservative ++ # here; this is the coarse net for "the kernel got noisier everywhere", ++ # which a max over millions of elements reports only weakly. ++ rms_tol = 4.0 * bf16_rms_floor + rtol * out_rms + 2.0 * ref_noise_rms ++ assert diff_rms <= rms_tol, ( ++ f"rms(out - out_ref) = {diff_rms:.6g} exceeds {rms_tol:.6g} " ++ f"(= 4 * bf16_rms_floor {bf16_rms_floor:.6g} + rtol {rtol:.6g} " ++ f"* rms|out_ref| {out_rms:.6g} + 2 * ref_quant_noise_rms " ++ f"{ref_noise_rms:.6g}); ratio {diff_rms / max(out_rms, 1e-30):.4%}" ++ ) + -+ Every sparse layer of a step runs the same plan over the same kv_indices -+ buffer, so they all build a byte-identical table. Cache it on the plan and -+ reuse it while the inputs look unchanged. ++ # Both bounds above are set by the quantization NOISE, which is a few ++ # percent for any E4M3 attention kernel and grows with N on the reference ++ # side. On their own they would accept a several-percent systematic ++ # corruption at large N, i.e. they would be close to vacuous exactly where ++ # the old absolute constant already was. The two projections below are ++ # what keep the criterion sharp: they are insensitive to zero-mean noise ++ # (it averages down by sqrt(n_elem)) but respond linearly to a systematic ++ # error. ++ # ++ # gain_err = / ++ # ++ # is exactly eps for a corruption out -> (1 + eps) * out. For a correct ++ # kernel it is not zero, because round-to-nearest on the E4M3 grid is only ++ # unbiased to FIRST order in the relative ulp; writing the residual as ++ # sum_j e_j p_j / sum_j p_j^2 with |e_j| <= rtol * p_j, the surviving ++ # systematic part is second order, O(rtol**2). Measured: the kernel's own ++ # projection (against the unquantized-P reference) is flat at -6.2e-4 .. ++ # -7.2e-4 across N = 1024 .. 1048576 = 0.16 .. 0.18 * rtol**2, and over ++ # 141 prefill/NVFP4 measurements |gain_err| <= 9.7e-5 = 0.025 * rtol**2. ++ # The reference's own projection is what grows with N (+4.6e-5 at N=1024 ++ # -> +9.1e-4 at N=1048576), so it enters through ref_noise like the terms ++ # above. The 8 * (statistical null sd) term covers small tensors, where ++ # the projection of a genuinely zero-mean residual fluctuates. ++ n_elem = diff.numel() ++ ref_energy = (out_ref_bf16 * out_ref_bf16).sum().item() ++ gain_err = (diff * out_ref_bf16).sum().item() / ref_energy if ref_energy > 0 else 0.0 ++ gain_null_sd = diff_rms / (math.sqrt(n_elem) * out_rms) if out_rms > 0 else 0.0 ++ ref_gain_noise = 0.0 ++ if out_ref_unquantized_p is not None and ref_energy > 0: ++ ref_gain_noise = abs( ++ (ref_noise * out_ref_bf16).sum().item() / ref_energy ++ ) ++ gain_tol = rtol * rtol + 2.0 * ref_gain_noise + 8.0 * gain_null_sd ++ assert abs(gain_err) <= gain_tol, ( ++ f" / = {gain_err:.6g} " ++ f"exceeds {gain_tol:.6g} (= rtol**2 {rtol * rtol:.6g} + 2 * " ++ f"ref_gain_noise {ref_gain_noise:.6g} + 8 * null_sd " ++ f"{gain_null_sd:.6g}); the kernel output is systematically scaled" ++ ) + -+ The cache holds a reference to kv_segment_lens so identity comparison is -+ sound: a live object's id cannot be recycled. A caller that rebuilds its -+ plan or restages these lengths therefore gets a fresh table. Version -+ counters add a content check where tensors track one. -+ """ -+ cached = plan_info.get("_page_table_cache") -+ if cached is not None: -+ lens, ptr, numel, versions, geometry, page_table = cached -+ if ( -+ lens is kv_segment_lens -+ and ptr == kv_indices.data_ptr() -+ and numel == kv_indices.numel() -+ and geometry == (page_size, batch) -+ and versions -+ == (_version_token(kv_indices), _version_token(kv_segment_lens)) -+ ): -+ return page_table -+ page_table = _build_page_table(kv_indices, kv_segment_lens, page_size, batch) -+ plan_info["_page_table_cache"] = ( -+ kv_segment_lens, -+ kv_indices.data_ptr(), -+ kv_indices.numel(), -+ (_version_token(kv_indices), _version_token(kv_segment_lens)), -+ (page_size, batch), -+ page_table, - ) -- offset = 0 -- for b in range(batch): -- n = pages_per_batch[b] -- page_table[b, :n] = kv_indices[offset : offset + n].to(torch.int32) -- offset += n - return page_table - - -@@ -351,8 +423,8 @@ def sparse_fmha( - if is_paged: - - if kv_indices is not None: -- page_table = _build_page_table( -- kv_indices, kv_segment_lens, page_size, batch, -+ page_table = _page_table_for_plan( -+ plan_info, kv_indices, kv_segment_lens, page_size, batch, - ) ++ # Companion projection onto the constant vector: catches an additive ++ # offset, which the gain statistic cannot see when out_ref is zero-mean. ++ # Its null is diff_rms / sqrt(n_elem); over the 160 fp8/NVFP4 measurements ++ # the observed |mean| never exceeded 2.38 of those sd, so 8 is >3x the ++ # worst observation. The gain_tol * |mean(out_ref)| term keeps the two ++ # checks from double-counting when out_ref does have a nonzero mean. ++ mean_err = diff.mean().item() ++ mean_ref = out_ref_bf16.mean().item() ++ mean_tol = 8.0 * diff_rms / math.sqrt(n_elem) + gain_tol * abs(mean_ref) ++ assert abs(mean_err) <= mean_tol, ( ++ f"mean(out - out_ref) = {mean_err:.6g} exceeds {mean_tol:.6g} " ++ f"(= 8 * null_sd {diff_rms / math.sqrt(n_elem):.6g} + gain_tol " ++ f"{gain_tol:.6g} * |mean(out_ref)| {abs(mean_ref):.6g}); the kernel " ++ f"output carries a systematic offset" ++ ) - # build_k2q_csr(return_schedule=True) builds schedule using hardware SM count internally -@@ -382,6 +454,17 @@ def sparse_fmha( + finite = lse_ref.isfinite() + if finite.any(): +@@ -1786,6 +2166,74 @@ def test_sparse_page_atten( - softmax_scale = sm_scale if sm_scale is not None else q.shape[-1] ** -0.5 + _assert_forward_close(out, out_ref, out_pt.float(), lse, lse_ref) -+ # Hand the caller's buffer to the kernel when its layout already matches -+ # what `combine` produces, so the result does not have to be copied into -+ # place afterwards. Anything else falls back to allocate-then-copy. -+ writable_out = ( -+ out is not None -+ and out.is_contiguous() -+ and out.dtype == torch.bfloat16 -+ and out.device == q.device -+ and tuple(out.shape) == tuple(q.shape) ++ ++def test_sparse_page_atten_strided_outer_page_matches_packed() -> None: ++ inputs = _build_paged_inputs( ++ batch=1, ++ seqlen_q=2048, ++ seqlen_kv=2048, ++ head_kv=2, ++ qhead_per_kv=16, ++ dim=128, ++ topk=16, ++ blk_kv=128, ++ causal=True, ++ page_size=128, ++ seqused_trim=0, ++ dtype=torch.float8_e4m3fn, ++ ) ++ k_packed = inputs["k_paged"].detach().clone() ++ v_packed = inputs["v_paged"].detach().clone() ++ pool = torch.empty( ++ k_packed.shape[0], ++ 4, ++ *k_packed.shape[1:], ++ dtype=k_packed.dtype, ++ device=k_packed.device, + ) ++ k_strided = pool[:, 1] ++ v_strided = pool[:, 3] ++ k_strided.copy_(k_packed) ++ v_strided.copy_(v_packed) + - # print(q.shape, k.shape) - result = sparse_atten_func( - q, k, v, -@@ -398,9 +481,10 @@ def sparse_fmha( - seqused_k=seqused_k, - schedule=schedule, - usable_SM_count=usable_SM_count, -+ out=out if writable_out else None, - ) - -- if out is not None: -+ if out is not None and not writable_out: - out.copy_(result) - return out, None - return result, None -diff --git a/python/fmha_sm100/csrc/fmha_sm100_params.h b/python/fmha_sm100/csrc/fmha_sm100_params.h ---- a/python/fmha_sm100/csrc/fmha_sm100_params.h -+++ b/python/fmha_sm100/csrc/fmha_sm100_params.h -@@ -1,4 +1,5 @@ - // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax -+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES - // SPDX-License-Identifier: MIT - - #pragma once -@@ -54,6 +55,9 @@ - int max_k_tiles; - int* kv_block_indexes_ptr; - int kv_block_num; -+ int64_t kv_block_stride_n = 0; -+ int64_t kv_block_stride_h = 0; -+ int64_t kv_block_stride_b = 1; - int pack_factor = 1; - int h_r_original = 0; - int q_stride_n_original = 0; -diff --git a/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja b/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja ---- a/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja -+++ b/python/fmha_sm100/csrc/fmha_sm100_variant_run.cu.jinja -@@ -1,9 +1,11 @@ - // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax -+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES - // SPDX-License-Identifier: MIT ++ assert not k_strided.is_contiguous() ++ assert not v_strided.is_contiguous() ++ assert ( ++ sparse_interface._prepare_paged_hnd_input(k_strided, inputs["blk_kv"]).data_ptr() ++ == k_strided.data_ptr() ++ ) ++ assert ( ++ sparse_interface._prepare_paged_hnd_input(v_strided, inputs["blk_kv"]).data_ptr() ++ == v_strided.data_ptr() ++ ) ++ ++ def run(k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: ++ return sparse_atten_func( ++ inputs["q"], ++ k, ++ v, ++ inputs["k2q_row_ptr"], ++ inputs["k2q_q_indices"], ++ 16, ++ blk_kv=inputs["blk_kv"], ++ causal=True, ++ softmax_scale=inputs["softmax_scale"], ++ return_softmax_lse=True, ++ cu_seqlens_q=inputs["cu_seqlens_q"], ++ cu_seqlens_k=inputs["cu_seqlens_k"], ++ max_seqlen_q=inputs["max_seqlen_q"], ++ max_seqlen_k=inputs["max_seqlen_k"], ++ page_table=inputs["page_table"], ++ seqused_k=inputs["seqused_k"], ++ schedule=inputs["schedule"], ++ ) ++ ++ packed_out, packed_lse = run(k_packed, v_packed) ++ strided_out, strided_lse = run(k_strided, v_strided) ++ torch.testing.assert_close(strided_out, packed_out, rtol=0, atol=0) ++ torch.testing.assert_close(strided_lse, packed_lse, rtol=0, atol=0) ++ ++ + @pytest.mark.parametrize("paged", [False, True]) + @pytest.mark.parametrize("causal", [True]) + @pytest.mark.parametrize("batch", [3]) +@@ -1857,8 +2305,7 @@ def test_sparse_atten_nvfp4_kv_matches_dequantized_bf16( + k_source = inputs["k"] + v_source = inputs["v"] - // Auto-generated per-variant FMHA run binding: {{ variant_name }} - #include "fmha_sm100_params.h" - #include "tvm_ffi_utils.h" -+#include - #include - #include +- k_q = _quantize_bf16_to_nvfp4_or_skip(k_source) +- v_q = _quantize_bf16_to_nvfp4_or_skip(v_source) ++ k_q, v_q = _quantize_kv_bf16_to_nvfp4(k_source, v_source) + k_deq = _dequant_nvfp4_to_bf16(k_q) + v_deq = _dequant_nvfp4_to_bf16(v_q) -@@ -121,9 +123,25 @@ - params.max_score_ptr = max_score_ptr; - params.max_k_tiles = static_cast(max_k_tiles); - params.kv_block_indexes_ptr = kv_block_indexes_ptr; -- params.kv_block_num = maybe_kv_block_indexes.has_value() -- ? static_cast(maybe_kv_block_indexes.value().size(2)) -- : 0; -+ params.kv_block_num = 0; -+ if (maybe_kv_block_indexes.has_value()) { -+ auto const selector = maybe_kv_block_indexes.value(); -+ CHECK_CUDA(selector); -+ CHECK_DEVICE(selector, q); -+ CHECK_INPUT_TYPE(selector, dl_int32); -+ CHECK_DIM(3, selector); -+ TVM_FFI_ICHECK_EQ(selector.size(0), q.size(0)); -+ TVM_FFI_ICHECK_EQ(selector.size(1), num_kv_heads); -+ TVM_FFI_ICHECK_GT(selector.size(2), 0); -+ TVM_FFI_ICHECK_LE(selector.size(2), INT_MAX); -+ for (int dim = 0; dim < 3; ++dim) { -+ TVM_FFI_ICHECK_GE(selector.stride(dim), 0); -+ } -+ params.kv_block_num = static_cast(selector.size(2)); -+ params.kv_block_stride_n = selector.stride(0); -+ params.kv_block_stride_h = selector.stride(1); -+ params.kv_block_stride_b = selector.stride(2); -+ } +@@ -1886,8 +2333,8 @@ def test_sparse_atten_nvfp4_kv_matches_dequantized_bf16( + inputs["q"], + k_q.data, + v_q.data, +- k_q.scale_128x4, +- v_q.scale_128x4, ++ k_q.scale, ++ v_q.scale, + k_q.global_scale, + v_q.global_scale, + inputs["k2q_row_ptr"], +@@ -2184,8 +2631,7 @@ def test_sparse_atten_nvfp4_kv_te_quantized_flat_smoke() -> None: + dtype=torch.bfloat16, + q2k_pattern=Q2KPattern.UNIFORM, + ) +- k_q = _quantize_bf16_to_nvfp4_or_skip(inputs["k"]) +- v_q = _quantize_bf16_to_nvfp4_or_skip(inputs["v"]) ++ k_q, v_q = _quantize_kv_bf16_to_nvfp4(inputs["k"], inputs["v"]) + k_deq = _dequant_nvfp4_to_bf16(k_q) + v_deq = _dequant_nvfp4_to_bf16(v_q) - params.pack_factor = static_cast(pack_factor); - params.num_ctas = static_cast(packed_work_range.size(0)); -@@ -187,10 +205,18 @@ - ? static_cast(maybe_max_score.value().size(0) - * maybe_max_score.value().size(1) - * maybe_max_score.value().size(2)) : 0; -- params.gmem_bounds.kv_block_indexes_numel = maybe_kv_block_indexes.has_value() -- ? static_cast(maybe_kv_block_indexes.value().size(0) -- * maybe_kv_block_indexes.value().size(1) -- * maybe_kv_block_indexes.value().size(2)) : 0; -+ // A sliced head-major view can span more storage than its logical numel. -+ // TensorView::data_ptr() already includes the view's storage offset. -+ params.gmem_bounds.kv_block_indexes_span = 0; -+ if (maybe_kv_block_indexes.has_value()) { -+ auto const selector = maybe_kv_block_indexes.value(); -+ if (selector.size(0) > 0 && selector.size(1) > 0) { -+ params.gmem_bounds.kv_block_indexes_span = -+ (selector.size(0) - 1) * params.kv_block_stride_n -+ + (selector.size(1) - 1) * params.kv_block_stride_h -+ + (selector.size(2) - 1) * params.kv_block_stride_b + 1; -+ } -+ } - params.gmem_bounds.split_kv_size = maybe_kv_tile_begin_indices.has_value() - ? static_cast(maybe_kv_tile_begin_indices.value().size(0)) : 0; - params.gmem_bounds.qo_offsets_size = maybe_qo_offsets.has_value() -diff --git a/python/fmha_sm100/csrc/fmha_sm100_inst.jinja b/python/fmha_sm100/csrc/fmha_sm100_inst.jinja ---- a/python/fmha_sm100/csrc/fmha_sm100_inst.jinja -+++ b/python/fmha_sm100/csrc/fmha_sm100_inst.jinja -@@ -1,4 +1,5 @@ - // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax -+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES - // SPDX-License-Identifier: MIT +@@ -2211,8 +2657,8 @@ def test_sparse_atten_nvfp4_kv_te_quantized_flat_smoke() -> None: + inputs["q"], + k_q.data, + v_q.data, +- k_q.scale_128x4, +- v_q.scale_128x4, ++ k_q.scale, ++ v_q.scale, + k_q.global_scale, + v_q.global_scale, + inputs["k2q_row_ptr"], +@@ -2237,7 +2683,7 @@ def test_sparse_atten_nvfp4_kv_te_quantized_flat_smoke() -> None: + @pytest.mark.parametrize("paged", [False, True]) + @pytest.mark.parametrize("qhead_per_kv", [1, 2, 4, 8, 16]) + @pytest.mark.parametrize("topk", [4, 8]) +-def test_sparse_atten_nvfp4_kv_fp8_q_matches_block_scaled_fp8_reference( ++def test_sparse_atten_nvfp4_kv_fp8_q_matches_calibrated_fp8_reference( + topk: int, + qhead_per_kv: int, + paged: bool, +@@ -2280,15 +2726,14 @@ def test_sparse_atten_nvfp4_kv_fp8_q_matches_block_scaled_fp8_reference( + v_source = inputs["v"] - // Auto-generated FMHA variant: {{ variant_name }} -@@ -28,12 +29,14 @@ + q_fp8 = inputs["q"].to(torch.float8_e4m3fn) +- k_q = _quantize_bf16_to_nvfp4_or_skip(k_source) +- v_q = _quantize_bf16_to_nvfp4_or_skip(v_source) ++ k_q, v_q = _quantize_kv_bf16_to_nvfp4(k_source, v_source) + fp8_max = torch.finfo(torch.float8_e4m3fn).max +- k_stage = _dequant_nvfp4_to_bf16(k_q, include_global_scale=False) +- v_stage = _dequant_nvfp4_to_bf16(v_q, include_global_scale=False) ++ # The block-scaled FP4 product is exactly representable in BF16. Apply ++ # the global scale in FP32, avoiding an extra BF16 rounding before FP8. ++ k_stage = _dequant_nvfp4_to_bf16(k_q, include_global_scale=False).float() * k_q.global_scale ++ v_stage = _dequant_nvfp4_to_bf16(v_q, include_global_scale=False).float() * v_q.global_scale + k_stage = k_stage.float().clamp(min=-fp8_max, max=fp8_max).to(torch.float8_e4m3fn) + v_stage = v_stage.float().clamp(min=-fp8_max, max=fp8_max).to(torch.float8_e4m3fn) +- k_global = float(k_q.global_scale.reshape(-1)[0].item()) +- v_global = float(v_q.global_scale.reshape(-1)[0].item()) - using ActiveMaskType = {% if pack_factor is defined and pack_factor > 1 %}PackedCausalMask<{{ pack_factor }}>{% else %}CausalMask{% endif %}; + if paged: + k_ref_chunks = [] +@@ -2315,20 +2760,19 @@ def test_sparse_atten_nvfp4_kv_fp8_q_matches_block_scaled_fp8_reference( + q_lens=inputs["q_lens"], + k_lens=inputs["k_lens"], + blk_kv=inputs["blk_kv"], +- softmax_scale=inputs["softmax_scale"] * k_global, ++ softmax_scale=inputs["softmax_scale"], + causal=causal, + upcast=True, + seqused_k=inputs["seqused_k"] if paged else None, + p_dtype=torch.float8_e4m3fn, + ) +- out_ref = out_ref * v_global -- return run_fmha_fwd( -+ cutlass::fmha::collective::SparseAttnMode::{{ sparse_mode }}, -+ decltype(unit_selector_column)::value>( - p.workspace_buffer_ptr, - static_cast(p.q_ptr), - static_cast(p.k_ptr), -@@ -58,6 +61,7 @@ - p.kv_indices_ptr, p.kv_page_indptr_ptr, p.total_page_num, - p.max_score_ptr, p.max_k_tiles, - p.kv_block_indexes_ptr, p.kv_block_num, -+ p.kv_block_stride_n, p.kv_block_stride_h, p.kv_block_stride_b, - p.pack_factor, p.q_stride_n_original, p.q_stride_h_original, p.h_r_original, - flashinfer::PackGQAUnpackParams{p.max_score_direct_ptr, p.total_qo_len_orig, - p.o_direct_ptr, p.num_qo_heads_orig, -@@ -67,4 +71,13 @@ - #endif - }, - p.num_ctas); -+ }; -+{% if dtype_in == "nv_bfloat16" and page_size > 0 and sparse_mode == "Sparse" %} -+ // The selector layout is host metadata; capture the matching existing kernel -+ // specialization without copying the selector or reading device values. -+ if (p.kv_block_stride_b == 1) { -+ return run(cute::true_type{}); -+ } -+{% endif %} -+ return run(cute::false_type{}); - } -diff --git a/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh b/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh ---- a/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh -+++ b/python/fmha_sm100/csrc/include/fmha_cutlass_sm100.cuh -@@ -1,3 +1,4 @@ -+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES - /* - * Copyright (c) 2023 by FlashInfer team. - * -@@ -57,7 +58,8 @@ - bool SingleSoftmaxWarpGroup = false, - int KVPageSize = -1, - cutlass::fmha::collective::SparseAttnMode kSparseAttnMode = -- cutlass::fmha::collective::SparseAttnMode::Off> -+ cutlass::fmha::collective::SparseAttnMode::Off, -+ bool UnitSelectorColumn = false> - struct FwdRunner { - using Element = DTypeIn; - using ElementAccumulatorQK = float; -@@ -89,7 +91,8 @@ + out, lse = sparse_atten_nvfp4_kv_func( + q_fp8, + k_q.data, + v_q.data, +- k_q.scale_128x4, +- v_q.scale_128x4, ++ k_q.scale, ++ v_q.scale, + k_q.global_scale, + v_q.global_scale, + inputs["k2q_row_ptr"], +@@ -2366,8 +2810,14 @@ def test_sparse_atten_nvfp4_kv_fp8_q_without_global_scale_matches_reference() -> + q2k_pattern=Q2KPattern.UNIFORM, + ) + q_fp8 = inputs["q"].to(torch.float8_e4m3fn) +- k_q = _make_synthetic_nvfp4_tensor(tuple(inputs["k"].shape)) +- v_q = _make_synthetic_nvfp4_tensor(tuple(inputs["v"].shape)) ++ k_q = _make_synthetic_nvfp4_tensor( ++ tuple(inputs["k"].shape), ++ layout=NVFP4_K_SCALE_LAYOUT, ++ ) ++ v_q = _make_synthetic_nvfp4_tensor( ++ tuple(inputs["v"].shape), ++ layout=NVFP4_V_SCALE_LAYOUT, ++ ) + fp8_max = torch.finfo(torch.float8_e4m3fn).max + k_ref = _dequant_nvfp4_to_bf16( + k_q, +@@ -2395,8 +2845,8 @@ def test_sparse_atten_nvfp4_kv_fp8_q_without_global_scale_matches_reference() -> + q_fp8, + k_q.data, + v_q.data, +- k_q.scale_128x4, +- v_q.scale_128x4, ++ k_q.scale, ++ v_q.scale, + None, + None, + inputs["k2q_row_ptr"], +@@ -2560,10 +3010,13 @@ def test_sparse_decode_page_fp8_forward(kv_tokens: int) -> None: - using Mainloop = cutlass::fmha::collective::Sm100FmhaFwdMainloopTmaWarpspecialized< - Element, ElementAccumulatorQK, ElementAccumulatorPV, TileShapeQK, TileShapePV, StrideQ, -- StrideK, StrideV, ActiveMask, ThreadShape, IsSplitKV, KVPageSize, kSparseAttnMode>; -+ StrideK, StrideV, ActiveMask, ThreadShape, IsSplitKV, KVPageSize, kSparseAttnMode, -+ UnitSelectorColumn>; - using Epilogue = cutlass::fmha::collective::Sm100FmhaFwdEpilogueTmaWarpspecialized< - ElementOut, ElementAccumulatorPV, typename Mainloop::TileShapePV, NumQStages, IsSplitKV, bNeedOutput, kPackFactor>; - using Operation = -@@ -126,6 +129,9 @@ - int max_k_tiles = 0, - int* kv_block_indexes = nullptr, - int kv_block_num = 0, -+ int64_t kv_block_stride_n = 0, -+ int64_t kv_block_stride_h = 0, -+ int64_t kv_block_stride_b = 1, - int pack_factor = 1, - int q_stride_n_original = 0, - int q_stride_h_original = 0, -@@ -223,11 +229,28 @@ - if constexpr (IsSplitKV) { - arguments = { - {problem_shape, -- {{q, layout_Q, k, layout_K, v, layout_V, kv_indices, kv_page_indptr, kv_block_indexes, kv_block_num, --#ifdef FMHA_GMEM_BOUNDS_CHECK -- pack_gqa.gmem_bounds.kv_page_indptr_size, pack_gqa.gmem_bounds.kv_indices_size, pack_gqa.gmem_bounds.kv_block_indexes_numel, --#endif -- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, -+ {{.ptr_Q = q, -+ .layout_Q = layout_Q, -+ .ptr_K = k, -+ .layout_K = layout_K, -+ .ptr_V = v, -+ .layout_V = layout_V, -+ .kv_indices = kv_indices, -+ .kv_page_indptr = kv_page_indptr, -+ .kv_block_indexes = kv_block_indexes, -+ .kv_block_num = kv_block_num, -+ .kv_block_stride_n = kv_block_stride_n, -+ .kv_block_stride_h = kv_block_stride_h, -+ .kv_block_stride_b = kv_block_stride_b, -+#ifdef FMHA_GMEM_BOUNDS_CHECK -+ .kv_page_indptr_size = pack_gqa.gmem_bounds.kv_page_indptr_size, -+ .kv_indices_size = pack_gqa.gmem_bounds.kv_indices_size, -+ .kv_block_indexes_span = pack_gqa.gmem_bounds.kv_block_indexes_span, -+#endif -+ .pack_factor = pack_factor, -+ .q_stride_n_original = q_stride_n_original, -+ .q_stride_h_original = q_stride_h_original, -+ .h_r_original = h_r_original}, - sm_scale, q_scale, k_scale, v_scale, o_scale}, - epi_args, - sched_args, -@@ -244,11 +267,28 @@ - } else { - arguments = { - problem_shape, -- {{q, layout_Q, k, layout_K, v, layout_V, kv_indices, kv_page_indptr, kv_block_indexes, kv_block_num, --#ifdef FMHA_GMEM_BOUNDS_CHECK -- pack_gqa.gmem_bounds.kv_page_indptr_size, pack_gqa.gmem_bounds.kv_indices_size, pack_gqa.gmem_bounds.kv_block_indexes_numel, --#endif -- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, -+ {{.ptr_Q = q, -+ .layout_Q = layout_Q, -+ .ptr_K = k, -+ .layout_K = layout_K, -+ .ptr_V = v, -+ .layout_V = layout_V, -+ .kv_indices = kv_indices, -+ .kv_page_indptr = kv_page_indptr, -+ .kv_block_indexes = kv_block_indexes, -+ .kv_block_num = kv_block_num, -+ .kv_block_stride_n = kv_block_stride_n, -+ .kv_block_stride_h = kv_block_stride_h, -+ .kv_block_stride_b = kv_block_stride_b, -+#ifdef FMHA_GMEM_BOUNDS_CHECK -+ .kv_page_indptr_size = pack_gqa.gmem_bounds.kv_page_indptr_size, -+ .kv_indices_size = pack_gqa.gmem_bounds.kv_indices_size, -+ .kv_block_indexes_span = pack_gqa.gmem_bounds.kv_block_indexes_span, -+#endif -+ .pack_factor = pack_factor, -+ .q_stride_n_original = q_stride_n_original, -+ .q_stride_h_original = q_stride_h_original, -+ .h_r_original = h_r_original}, - sm_scale, q_scale, k_scale, v_scale, o_scale}, - epi_args, - sched_args, -@@ -343,8 +383,28 @@ - if constexpr (IsSplitKV) { - arguments = { - {problem_shape, -- {{q, layout_Q, k, layout_K, v, layout_V, nullptr, nullptr, nullptr, 0, -- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, -+ {{.ptr_Q = q, -+ .layout_Q = layout_Q, -+ .ptr_K = k, -+ .layout_K = layout_K, -+ .ptr_V = v, -+ .layout_V = layout_V, -+ .kv_indices = nullptr, -+ .kv_page_indptr = nullptr, -+ .kv_block_indexes = nullptr, -+ .kv_block_num = 0, -+ .kv_block_stride_n = 0, -+ .kv_block_stride_h = 0, -+ .kv_block_stride_b = 1, -+#ifdef FMHA_GMEM_BOUNDS_CHECK -+ .kv_page_indptr_size = 0, -+ .kv_indices_size = 0, -+ .kv_block_indexes_span = 0, -+#endif -+ .pack_factor = pack_factor, -+ .q_stride_n_original = q_stride_n_original, -+ .q_stride_h_original = q_stride_h_original, -+ .h_r_original = h_r_original}, - sm_scale, q_scale, k_scale, v_scale, o_scale}, - epi_args, - sched_args, -@@ -361,8 +421,28 @@ - } else { - arguments = { - problem_shape, -- {{q, layout_Q, k, layout_K, v, layout_V, nullptr, nullptr, nullptr, 0, -- pack_factor, q_stride_n_original, q_stride_h_original, h_r_original}, -+ {{.ptr_Q = q, -+ .layout_Q = layout_Q, -+ .ptr_K = k, -+ .layout_K = layout_K, -+ .ptr_V = v, -+ .layout_V = layout_V, -+ .kv_indices = nullptr, -+ .kv_page_indptr = nullptr, -+ .kv_block_indexes = nullptr, -+ .kv_block_num = 0, -+ .kv_block_stride_n = 0, -+ .kv_block_stride_h = 0, -+ .kv_block_stride_b = 1, -+#ifdef FMHA_GMEM_BOUNDS_CHECK -+ .kv_page_indptr_size = 0, -+ .kv_indices_size = 0, -+ .kv_block_indexes_span = 0, -+#endif -+ .pack_factor = pack_factor, -+ .q_stride_n_original = q_stride_n_original, -+ .q_stride_h_original = q_stride_h_original, -+ .h_r_original = h_r_original}, - sm_scale, q_scale, k_scale, v_scale, o_scale}, - epi_args, - sched_args, -@@ -412,7 +492,8 @@ - bool SingleSoftmaxWarpGroup = false, - int KVPageSize = -1, - cutlass::fmha::collective::SparseAttnMode kSparseAttnMode = -- cutlass::fmha::collective::SparseAttnMode::Off> -+ cutlass::fmha::collective::SparseAttnMode::Off, -+ bool UnitSelectorColumn = false> - cudaError_t run_fmha_fwd(void* workspace_buffer, DTypeIn* q, DTypeIn* k, DTypeIn* v, - IdType* qo_segment_lens, IdType* kv_segment_lens, - IdType* qo_segment_offsets, IdType* kv_segment_offsets, -@@ -436,6 +517,9 @@ - int max_k_tiles = 0, - int* kv_block_indexes = nullptr, - int kv_block_num = 0, -+ int64_t kv_block_stride_n = 0, -+ int64_t kv_block_stride_h = 0, -+ int64_t kv_block_stride_b = 1, - int pack_factor = 1, - int q_stride_n_original = 0, - int q_stride_h_original = 0, -@@ -443,7 +527,8 @@ - PackGQAUnpackParams pack_gqa = {}, - int num_ctas = 0) { - return FwdRunner::run( -+ ThreadShape, IsSplitKV, SingleSoftmaxWarpGroup, KVPageSize, kSparseAttnMode, -+ UnitSelectorColumn>::run( - workspace_buffer, q, k, v, qo_segment_lens, kv_segment_lens, - qo_segment_offsets, kv_segment_offsets, packed_work_range, - packed_work_info, o, mask_mode_code, sm_scale, -@@ -455,6 +540,7 @@ - kv_indices, kv_page_indptr, total_page_num, - maybe_max_score, max_k_tiles, - kv_block_indexes, kv_block_num, -+ kv_block_stride_n, kv_block_stride_h, kv_block_stride_b, - pack_factor, q_stride_n_original, q_stride_h_original, h_r_original, - pack_gqa, num_ctas); - } -diff --git a/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp b/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp ---- a/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp -+++ b/python/fmha_sm100/csrc/include/sm100_fmha_load_tma_warpspecialized.hpp -@@ -1,5 +1,5 @@ - /*************************************************************************************************** -- * Copyright (c) 2024 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -+ * Copyright (c) 2024 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without -@@ -64,7 +64,8 @@ - template -+ SparseAttnMode kSparseAttnMode = SparseAttnMode::Off, -+ bool UnitSelectorColumn = false> - struct Sm100FmhaLoadTmaWarpspecialized { - // P0: OnlyScore mode never reads V — skip every V slot in the KV pipeline. - // mma() gates the matching wait_V/release_V under `kNeedOutput` so producer -@@ -112,10 +113,13 @@ - int* kv_page_indptr = nullptr; - int* kv_block_indexes = nullptr; - int kv_block_num = 0; -+ int64_t kv_block_stride_n = 0; -+ int64_t kv_block_stride_h = 0; -+ int64_t kv_block_stride_b = 1; - #ifdef FMHA_GMEM_BOUNDS_CHECK - int kv_page_indptr_size = 0; - int kv_indices_size = 0; -- int kv_block_indexes_numel = 0; -+ int64_t kv_block_indexes_span = 0; - #endif - int pack_factor = 1; - int q_stride_n_original = 0; -@@ -148,10 +152,13 @@ - int* kv_page_indptr = nullptr; - int* kv_block_indexes = nullptr; - int kv_block_num = 0; -+ int64_t kv_block_stride_n = 0; -+ int64_t kv_block_stride_h = 0; -+ int64_t kv_block_stride_b = 1; - #ifdef FMHA_GMEM_BOUNDS_CHECK - int kv_page_indptr_size = 0; - int kv_indices_size = 0; -- int kv_block_indexes_numel = 0; -+ int64_t kv_block_indexes_span = 0; - #endif - const Element* ptr_Q_orig = nullptr; - int q_stride_n_orig = 0; -@@ -218,8 +225,9 @@ + out, lse = _run_sparse_decode_page_fp8(fn, inputs) + out_ref, lse_ref = _decode_paged_dense_reference(inputs) ++ out_ref_exact, _ = _decode_paged_dense_reference(inputs, p_dtype=None) + assert out.dtype == torch.bfloat16 + assert out.shape == inputs["q"].shape + assert lse.shape == inputs["q"].shape[:2] +- _assert_fp8_forward_close(out, out_ref, lse, lse_ref) ++ _assert_fp8_forward_close( ++ out, out_ref, lse, lse_ref, out_ref_unquantized_p=out_ref_exact ++ ) + + + def test_sparse_decode_page_fp8_forward_forced_split_kv_tile_aligned_partial() -> None: +@@ -2596,7 +3049,10 @@ def test_sparse_decode_page_fp8_forward_forced_split_kv_tile_aligned_partial() - + return_softmax_lse=True, + ) + out_ref, lse_ref = _decode_paged_dense_reference(inputs) +- _assert_fp8_forward_close(out, out_ref, lse, lse_ref) ++ out_ref_exact, _ = _decode_paged_dense_reference(inputs, p_dtype=None) ++ _assert_fp8_forward_close( ++ out, out_ref, lse, lse_ref, out_ref_unquantized_p=out_ref_exact ++ ) + + + # --------------------------------------------------------------------------- +@@ -2943,10 +3399,12 @@ def _build_sparse_nvfp4_kv_benchmark_context( + raise ValueError(f"Unsupported NVFP4 KV benchmark Q dtype: {q_dtype}") + k_q = _make_synthetic_nvfp4_tensor( + tuple(k_source.shape), ++ layout=NVFP4_K_SCALE_LAYOUT, + global_scale_value=0.75, + ) + v_q = _make_synthetic_nvfp4_tensor( + tuple(v_source.shape), ++ layout=NVFP4_V_SCALE_LAYOUT, + global_scale_value=1.25, + ) + k_bf16 = _dequant_nvfp4_to_bf16(k_q) +@@ -2990,8 +3448,8 @@ def _build_sparse_nvfp4_kv_benchmark_context( + q, + k_q.data, + v_q.data, +- k_q.scale_128x4, +- v_q.scale_128x4, ++ k_q.scale, ++ v_q.scale, + k_q.global_scale, + v_q.global_scale, + k2q_row_ptr, +diff --git a/python/fmha_sm100/jit.py b/python/fmha_sm100/jit.py +index fa63a02..2d2aa2b 100644 +--- a/python/fmha_sm100/jit.py ++++ b/python/fmha_sm100/jit.py +@@ -1,4 +1,5 @@ + # SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax ++# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES + # SPDX-License-Identifier: MIT - Params p{tma_load_Q, layout_Q, tma_load_K, layout_K, tma_load_V, layout_V, - args.kv_indices, args.kv_page_indptr, args.kv_block_indexes, args.kv_block_num, -+ args.kv_block_stride_n, args.kv_block_stride_h, args.kv_block_stride_b, - #ifdef FMHA_GMEM_BOUNDS_CHECK -- args.kv_page_indptr_size, args.kv_indices_size, args.kv_block_indexes_numel, -+ args.kv_page_indptr_size, args.kv_indices_size, args.kv_block_indexes_span, - #endif - args.ptr_Q, args.q_stride_n_original, args.q_stride_h_original, args.h_r_original, - tma_desc_q_pack}; -@@ -525,11 +533,10 @@ - constexpr int effective_tile_kv = get<1>(TileShapeQK{}); - constexpr int tiles_per_page = KVPageSize / effective_tile_kv; + """Per-variant lazy JIT compilation for FMHA varlen kernels. +@@ -6,11 +7,12 @@ + Each FMHA variant (dtype x tile x sparse x page x split_kv x pack_factor) is compiled + independently on first use and cached to ~/.cache/minfer/fmha_sm100/. -- int kv_block_offset = 0; -+ int64_t kv_block_offset = 0; - if constexpr (kSparseAttnMode == SparseAttnMode::Sparse) { -- int num_kv_heads_val = get<3, 0, 1>(params_problem_shape); -- kv_block_offset = batch_idx * num_kv_heads_val * params.kv_block_num -- + kv_head_idx * params.kv_block_num; -+ kv_block_offset = batch_idx * params.kv_block_stride_n -+ + kv_head_idx * params.kv_block_stride_h; - } +-To recompile after kernel changes: scripts/clear_fmha_cache.sh ++Source changes select a new cache automatically; prewarm using the same sources. + """ - // Keep full 4D tensor (page_size, D, H_kv, P) — select head at copy time -@@ -549,7 +556,12 @@ - int page_for_lookup; - if constexpr (kSparseAttnMode == SparseAttnMode::Sparse) { - int sparse_idx = (logical_page < params.kv_block_num) -- ? __ldg(¶ms.kv_block_indexes[kv_block_offset + logical_page]) -+ ? (UnitSelectorColumn -+ ? KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, -+ kv_block_offset + logical_page, params.kv_block_indexes_span) -+ : KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, -+ kv_block_offset + logical_page * params.kv_block_stride_b, -+ params.kv_block_indexes_span)) - : -1; - page_for_lookup = (sparse_idx >= 0) ? sparse_idx : 0; - } else { -@@ -573,7 +585,12 @@ - int page_for_lookup; - if constexpr (kSparseAttnMode == SparseAttnMode::Sparse) { - int sparse_idx = (logical_page < params.kv_block_num) -- ? __ldg(¶ms.kv_block_indexes[kv_block_offset + logical_page]) -+ ? (UnitSelectorColumn -+ ? KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, -+ kv_block_offset + logical_page, params.kv_block_indexes_span) -+ : KV_BLOCK_INDEX_LOAD(params.kv_block_indexes, -+ kv_block_offset + logical_page * params.kv_block_stride_b, -+ params.kv_block_indexes_span)) - : -1; - page_for_lookup = (sparse_idx >= 0) ? sparse_idx : 0; - } else { -diff --git a/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp b/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp ---- a/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp -+++ b/python/fmha_sm100/csrc/include/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp -@@ -1,5 +1,5 @@ - /*************************************************************************************************** -- * Copyright (c) 2024 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -+ * Copyright (c) 2024 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without -@@ -158,7 +158,8 @@ - class ThreadShape = Shape<_2, _1, _1>, - bool IsSplitKV_ = false, - int KVPageSize_ = -1, -- SparseAttnMode kSparseAttnMode = SparseAttnMode::Off> -+ SparseAttnMode kSparseAttnMode = SparseAttnMode::Off, -+ bool UnitSelectorColumn = false> - struct Sm100FmhaFwdMainloopTmaWarpspecialized { - static constexpr bool IsSplitKV = IsSplitKV_; - static constexpr int KVPageSize = KVPageSize_; -@@ -376,7 +377,7 @@ - using Load = Sm100FmhaLoadTmaWarpspecialized; -+ kSparseAttnMode, UnitSelectorColumn>; - using LayoutQ = typename Load::LayoutQ; - using LayoutK = typename Load::LayoutK; - using LayoutV = typename Load::LayoutV; -@@ -1131,14 +1132,13 @@ - int skip_count, real_masked_count, unmasked_count; - int effective_end; + import itertools + import fcntl ++import hashlib + import logging + import os + import shutil +@@ -22,11 +24,54 @@ import jinja2 + + logger = logging.getLogger(__name__) + ++# Kernel sources and CUTLASS headers are shipped inside the package directory ++# so that JIT compilation works from both editable and wheel installs. ++_PACKAGE_DIR = Path(__file__).resolve().parent ++_FMHA_VARLEN_DIR = _PACKAGE_DIR / "csrc" ++_CUTLASS_DIR = _PACKAGE_DIR / "cutlass" ++_CUTLASS_INCLUDE = _CUTLASS_DIR / "include" ++_CUTLASS_UTIL_INCLUDE = _CUTLASS_DIR / "tools" / "util" / "include" ++ ++ ++def _device_is_sm107() -> bool: ++ """Whether the current CUDA device is SM107 (compute capability 10.7).""" ++ import torch ++ ++ return torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 7) ++ ++ ++_proxy_modes_cache = None ++ ++ ++def _proxy_modes(): ++ """(keep correction chain, single S buffer) for the OnlyScore K-split kernels (the MSA indexer proxy). ++ ++ By default they skip the per-tile softmax -> correction -> MMA handshake (kSkipPerTileCorrection in ++ sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp) and double-buffer S in the O TMEM columns (kSDoubleBuf, which ++ requires the skip); TLLM_FMHA_PROXY_CORRECTION_CHAIN=1 / TLLM_FMHA_PROXY_S_DOUBLE_BUFFER=0 keep the stock ++ behaviour, each in its own cache directory. Both are SM107-only: every other device compiles the stock mainloop ++ (the kill knobs' defines and cache directory). Resolved on first use, not at import, so importing this module ++ never initializes CUDA (a parent that later forks workers must not hold a CUDA context). ++ """ ++ global _proxy_modes_cache ++ if _proxy_modes_cache is None: ++ sm107 = _device_is_sm107() ++ chain = os.environ.get("TLLM_FMHA_PROXY_CORRECTION_CHAIN", "0") == "1" or not sm107 ++ single_s = os.environ.get("TLLM_FMHA_PROXY_S_DOUBLE_BUFFER", "1") == "0" or not sm107 ++ logger.warning( ++ "fmha_sm100: OnlyScore K-split per-tile correction handshake %s (TLLM_FMHA_PROXY_CORRECTION_CHAIN=%s), " ++ "S double buffer %s (TLLM_FMHA_PROXY_S_DOUBLE_BUFFER=%s)%s", ++ "kept" if chain else "skipped", "1" if chain else "0", ++ "off" if (single_s or chain) else "on", "0" if single_s else "1", ++ "" if sm107 else "; stock mainloop, the device is not SM107", ++ ) ++ _proxy_modes_cache = (chain, single_s) ++ return _proxy_modes_cache ++ ++ + def _compute_cache_base(): + explicit = os.environ.get("MINFER_FMHA_CACHE_DIR") +- if explicit: +- return Path(explicit) +- base = Path(os.path.expanduser("~/.cache/minfer/fmha_sm100")) ++ base = Path(explicit) if explicit else Path(os.path.expanduser("~/.cache/minfer/fmha_sm100")) + # Different build configs get separate cache dirs to avoid conflicts + suffix = "" + if os.environ.get("GPU_TRACE") is not None: +@@ -35,12 +80,58 @@ def _compute_cache_base(): + suffix += "_sm_timing" + if os.environ.get("FMHA_GMEM_CHECK") is not None: + suffix += "_gmem_check" +- if suffix: ++ proxy_chain, proxy_single_s = _proxy_modes() ++ if proxy_chain: ++ suffix += "_proxy_correction_chain" ++ if proxy_single_s: ++ suffix += "_proxy_single_s" ++ if suffix and not explicit: + base = base.parent / (base.name + suffix) +- return base ++ ++ # Hash templates, bindings and headers together; jit.py also covers changes ++ # to dispatch and compiler flags. Use relative names so installs share keys. ++ digest = hashlib.sha256() ++ sources = sorted(path for path in _FMHA_VARLEN_DIR.rglob("*") if path.is_file()) ++ sources.append(_PACKAGE_DIR / "jit.py") ++ for path in sources: ++ content = path.read_bytes() ++ digest.update(path.relative_to(_PACKAGE_DIR).as_posix().encode() + b"\0") ++ digest.update(len(content).to_bytes(8, "little")) ++ digest.update(content) ++ # An explicit cache root must also isolate instrumented and normal binaries. ++ digest.update(suffix.encode()) ++ cache_base = base / ("sources_sha256_" + digest.hexdigest()) ++ logger.info( ++ "Using FMHA cache %s (source/build fingerprint; changed sources or " ++ "diagnostic modes require recompilation)", cache_base, ++ ) ++ return cache_base + + +-CACHE_BASE = _compute_cache_base() ++class _LazyCacheBase: ++ """The cache root, computed on first use: its suffix depends on the device (see _proxy_modes).""" ++ ++ _path = None ++ ++ def _resolve(self) -> Path: ++ if self._path is None: ++ self._path = _compute_cache_base() ++ return self._path ++ ++ def __truediv__(self, other): ++ return self._resolve() / other ++ ++ def __fspath__(self): ++ return str(self._resolve()) ++ ++ def __str__(self): ++ return str(self._resolve()) ++ ++ def __getattr__(self, name): ++ return getattr(self._resolve(), name) ++ ++ ++CACHE_BASE = _LazyCacheBase() + + + def _acquire_file_lock(lock_path): +@@ -55,13 +146,6 @@ def _release_file_lock(fd): + os.close(fd) + + +-# Kernel sources and CUTLASS headers are shipped inside the package directory +-# so that JIT compilation works from both editable and wheel installs. +-_PACKAGE_DIR = Path(__file__).resolve().parent +-_FMHA_VARLEN_DIR = _PACKAGE_DIR / "csrc" +-_CUTLASS_DIR = _PACKAGE_DIR / "cutlass" +-_CUTLASS_INCLUDE = _CUTLASS_DIR / "include" +-_CUTLASS_UTIL_INCLUDE = _CUTLASS_DIR / "tools" / "util" / "include" + + _PACK_FACTORS = [1,2,4,6,8,16] + # _PACK_FACTORS = [1, 6] +@@ -187,7 +271,8 @@ def _get_cuda_home(): + raise RuntimeError("Cannot find CUDA toolkit. Set CUDA_HOME.") + + +-_ALL_VARIANTS_SO = CACHE_BASE / "_all_variants" / "all_variants.so" ++def _all_variants_so() -> Path: ++ return CACHE_BASE / "_all_variants" / "all_variants.so" + + def _get_nvcc_flags(cache_dir, fmha=True): + tvm_include = _get_tvm_ffi_include() +@@ -199,6 +284,9 @@ def _get_nvcc_flags(cache_dir, fmha=True): + "--expt-relaxed-constexpr", "--expt-extended-lambda", + "-gencode=arch=compute_100a,code=sm_100a", + "-gencode=arch=compute_103a,code=sm_103a", ++ # SM100-family image so the rest of the family can load these kernels; ++ # sm_100a/sm_103a are arch-conditional and outrank it on those devices. ++ "-gencode=arch=compute_100f,code=sm_100f", + "-static-global-template-stub=false", + "-DFLASHINFER_ENABLE_BF16", + "-DFLASHINFER_ENABLE_FP8_E4M3", +@@ -225,6 +313,11 @@ def _get_nvcc_flags(cache_dir, fmha=True): + nvcc_flags.append("-DSM_TIMING_ENABLED") + if os.environ.get("FMHA_GMEM_CHECK") is not None: + nvcc_flags.append("-DFMHA_GMEM_BOUNDS_CHECK") ++ proxy_chain, proxy_single_s = _proxy_modes() ++ if proxy_chain: ++ nvcc_flags.append("-DFMHA_ONLYSCORE_PER_TILE_CORRECTION") ++ if proxy_single_s: ++ nvcc_flags.append("-DFMHA_ONLYSCORE_SINGLE_S") + return " ".join(nvcc_flags) + + class _VariantWrapper: +@@ -257,9 +350,10 @@ class FMHAVariantManager: + def _ensure_all_module(self): + if not self._all_module_checked: + self._all_module_checked = True +- if _ALL_VARIANTS_SO.exists(): ++ all_variants_so = _all_variants_so() ++ if all_variants_so.exists(): + import tvm_ffi +- self._all_module = tvm_ffi.load_module(str(_ALL_VARIANTS_SO)) ++ self._all_module = tvm_ffi.load_module(str(all_variants_so)) + + def get_variant(self, dtype_code, qo_tile_size, single_wg, + sparse_mode, page_size, split_kv, pack_factor): +diff --git a/python/fmha_sm100/sparse.py b/python/fmha_sm100/sparse.py +index 7006fcd..9a09324 100644 +--- a/python/fmha_sm100/sparse.py ++++ b/python/fmha_sm100/sparse.py +@@ -79,11 +79,13 @@ from fp4_indexer_interface import fp4_indexer_block_scores # noqa: E402 + # (cute/quantize.py). + from quantize import ( # noqa: E402 + Nvfp4QuantizedTensor, +- dequantize_nvfp4_128x4_to_bf16, ++ dequantize_nvfp4_to_bf16, + nvfp4_global_scale_from_amax, +- quantize_bf16_to_nvfp4_128x4, +- quantize_kv_bf16_to_nvfp4_128x4, +- swizzle_nvfp4_scale_to_128x4, ++ nvfp4_scale_linear_offset, ++ nvfp4_scale_swizzle4x4_offset, ++ pack_nvfp4_scale, ++ quantize_bf16_to_nvfp4, ++ quantize_kv_bf16_to_nvfp4, + ) + + __all__ = [ +@@ -98,9 +100,11 @@ __all__ = [ + "SparseK2qCsrBuilderSm100", + # nvfp4 quantization helpers + "Nvfp4QuantizedTensor", +- "quantize_bf16_to_nvfp4_128x4", +- "quantize_kv_bf16_to_nvfp4_128x4", +- "dequantize_nvfp4_128x4_to_bf16", +- "swizzle_nvfp4_scale_to_128x4", ++ "quantize_bf16_to_nvfp4", ++ "quantize_kv_bf16_to_nvfp4", ++ "dequantize_nvfp4_to_bf16", ++ "pack_nvfp4_scale", ++ "nvfp4_scale_linear_offset", ++ "nvfp4_scale_swizzle4x4_offset", + "nvfp4_global_scale_from_amax", + ] +diff --git a/python/fmha_sm100/sparse_fmha_adapter.py b/python/fmha_sm100/sparse_fmha_adapter.py +index 306b416..a564d47 100644 +--- a/python/fmha_sm100/sparse_fmha_adapter.py ++++ b/python/fmha_sm100/sparse_fmha_adapter.py +@@ -129,11 +129,19 @@ def sparse_fmha_plan( + batch = qo_segment_lens.shape[0] + gpu_device = torch.device('cuda') + ++ # Stage the host lengths to the device once, asynchronously, and read every ++ # scalar below from the host copy. Planning runs on the critical path of ++ # input preparation, where a blocking copy or a device .item() would drain ++ # the CUDA queue. ++ qo_lens_gpu = qo_segment_lens.to(torch.int32).to(gpu_device, non_blocking=True) ++ kv_lens_host = kv_segment_lens.to(torch.int32) ++ kv_lens_gpu = kv_lens_host.to(gpu_device, non_blocking=True) ++ + cu_seqlens_q = torch.zeros(batch + 1, dtype=torch.int32, device=gpu_device) +- cu_seqlens_q[1:] = torch.cumsum(qo_segment_lens.to(torch.int32).to(gpu_device), dim=0) ++ cu_seqlens_q[1:] = torch.cumsum(qo_lens_gpu, dim=0) -- int kbi_off_s = 0; -+ int64_t kbi_off_s = 0; - if constexpr (kNeedSparse) { - int h_r_s = get<3, 0, 0>(problem_shape); -- int num_kv_heads_s = get<3, 0, 1>(problem_shape); - int kv_head_idx_s = get<2, 0>(blk_coord) / h_r_s; - int batch_idx_s = get<2, 1>(blk_coord); -- kbi_off_s = batch_idx_s * num_kv_heads_s * params.load.kv_block_num -- + kv_head_idx_s * params.load.kv_block_num; -+ kbi_off_s = batch_idx_s * params.load.kv_block_stride_n -+ + kv_head_idx_s * params.load.kv_block_stride_h; - } + cu_seqlens_k = torch.zeros(batch + 1, dtype=torch.int32, device=gpu_device) +- cu_seqlens_k[1:] = torch.cumsum(kv_segment_lens.to(torch.int32).to(gpu_device), dim=0) ++ cu_seqlens_k[1:] = torch.cumsum(kv_lens_gpu, dim=0) - if constexpr (kNeedSparse) { -@@ -1154,7 +1154,12 @@ + max_seqlen_q = int(qo_segment_lens.max().item()) + max_seqlen_k = int(kv_segment_lens.max().item()) +@@ -144,11 +152,12 @@ def sparse_fmha_plan( + total_rows = sum((int(kl) + blk_kv - 1) // blk_kv for kl in kv_lens) - // Count padding blocks (backward scan for -1) - int valid_blks = params.load.kv_block_num; -- while (valid_blks > 0 && __ldg(¶ms.load.kv_block_indexes[kbi_off_s + valid_blks - 1]) < 0) -+ while (valid_blks > 0 && (UnitSelectorColumn -+ ? KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, -+ kbi_off_s + valid_blks - 1, params.load.kv_block_indexes_span) -+ : KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, -+ kbi_off_s + (valid_blks - 1) * params.load.kv_block_stride_b, -+ params.load.kv_block_indexes_span)) < 0) - valid_blks--; + if qo_offset is not None: +- seqused_k = (qo_segment_lens + qo_offset).to(torch.int32).to(gpu_device) ++ seqused_k = (qo_segment_lens + qo_offset).to(torch.int32).to(gpu_device, non_blocking=True) + else: +- seqused_k = kv_segment_lens.to(torch.int32).to(gpu_device) ++ seqused_k = kv_lens_gpu.clone() - int valid_tiles = (valid_blks * KVPageSize + full_tile_kv - 1) / full_tile_kv; -@@ -1223,7 +1228,12 @@ - cS = domain_offset(make_coord(q_s, INT_MAX / 2), cS_base); - return false; - } -- int pos = __ldg(¶ms.load.kv_block_indexes[kbi_off_s + page_idx]); -+ int pos = UnitSelectorColumn -+ ? KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, -+ kbi_off_s + page_idx, params.load.kv_block_indexes_span) -+ : KV_BLOCK_INDEX_LOAD(params.load.kv_block_indexes, -+ kbi_off_s + page_idx * params.load.kv_block_stride_b, -+ params.load.kv_block_indexes_span); - if (pos < 0) { - cS = domain_offset(make_coord(q_s, INT_MAX / 2), cS_base); - return false; -diff --git a/python/fmha_sm100/csrc/gmem_bounds_check.h b/python/fmha_sm100/csrc/gmem_bounds_check.h ---- a/python/fmha_sm100/csrc/gmem_bounds_check.h -+++ b/python/fmha_sm100/csrc/gmem_bounds_check.h -@@ -1,4 +1,5 @@ - // SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax -+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES - // SPDX-License-Identifier: MIT +- total_q = int(cu_seqlens_q[-1].item()) ++ # Equals cu_seqlens_q[-1], read on the host. ++ total_q = int(qo_segment_lens.sum()) + qhead_per_kv = num_qo_heads // num_kv_heads if num_kv_heads > 0 else 1 - #pragma once -@@ -9,6 +10,7 @@ - #ifdef FMHA_GMEM_BOUNDS_CHECK + target_q_per_cta = SPARSE_SCHEDULE_MODEL.balanced_target_q_per_cta( +@@ -169,11 +178,14 @@ def sparse_fmha_plan( + ) - #include -+#include + return { +- "qo_segment_lens": qo_segment_lens, ++ "qo_segment_lens": qo_lens_gpu, + "cu_seqlens_q": cu_seqlens_q, + "qo_segment_offsets": cu_seqlens_q, + "cu_seqlens_k": cu_seqlens_k, +- "kv_segment_lens": kv_segment_lens.to(torch.int32).to(gpu_device), ++ # Host tensor: only the page-table builder consumes it, and it reads ++ # per-request page counts on the host. Kernels take the lengths from ++ # cu_seqlens_k and seqused_k. ++ "kv_segment_lens": kv_lens_host, + "seqused_k": seqused_k, + "max_seqlen_q": max_seqlen_q, + "max_seqlen_k": max_seqlen_k, +@@ -228,23 +240,83 @@ def _build_page_table( + page_size: int, + batch: int, + ) -> torch.Tensor: +- """Flat kv_indices → page_table [batch, max_pages_per_seq].""" +- kv_lens = kv_segment_lens.tolist() +- pages_per_batch = [(int(kl) + page_size - 1) // page_size for kl in kv_lens] +- max_pages = max(pages_per_batch) +- total = batch * max_pages +- buf = torch.zeros(total + 4, dtype=torch.int32, device=kv_indices.device) +- shift = ((-buf.data_ptr()) % 16) // 4 +- page_table = buf[shift : shift + total].view(batch, max_pages) ++ """Flat kv_indices → page_table [batch, max_pages_per_seq]. ++ ++ Each request's pages are a contiguous run of kv_indices, so the padded table ++ is kv_indices[start[b] + col] masked to the request's page count. One gather ++ builds it: a copy per request would dominate host time once the batch is ++ wide. ++ """ ++ lens = kv_segment_lens if kv_segment_lens.device.type == "cpu" else kv_segment_lens.cpu() ++ pages = (lens.to(torch.int64) + (page_size - 1)) // page_size ++ max_pages = int(pages.max()) ++ starts = torch.cumsum(pages, 0) - pages ++ # Both row descriptors travel in a single host-to-device copy. ++ meta = torch.stack((pages, starts)).to(kv_indices.device, non_blocking=True) ++ pages_dev = meta[0].unsqueeze(1) ++ starts_dev = meta[1].unsqueeze(1) ++ ++ col = torch.arange(max_pages, device=kv_indices.device, dtype=torch.int64).unsqueeze(0) ++ mask = col < pages_dev ++ # Padded columns run past the end of a request's run, so clamp the gather ++ # index into range and zero them afterwards. ++ src = (starts_dev + col).clamp_(max=max(kv_indices.numel() - 1, 0)) ++ page_table = kv_indices.index_select(0, src.reshape(-1)).to(torch.int32) ++ page_table = page_table.view(batch, max_pages).masked_fill_(~mask, 0) + assert page_table.data_ptr() % 16 == 0, ( +- f"_build_page_table failed to align: buf=0x{buf.data_ptr():x} " +- f"shift={shift} page_table=0x{page_table.data_ptr():x}" ++ f"_build_page_table failed to align: page_table=0x{page_table.data_ptr():x}" ++ ) ++ return page_table ++ ++ ++def _version_token(tensor: torch.Tensor): ++ """Version counter for `tensor`, or None if it does not track one. ++ ++ Inference tensors have no version counter, so this is None on the serving ++ path and the caller falls back to identity checks alone. ++ """ ++ return None if torch.is_inference(tensor) else tensor._version ++ ++ ++def _page_table_for_plan( ++ plan_info: dict, ++ kv_indices: torch.Tensor, ++ kv_segment_lens: torch.Tensor, ++ page_size: int, ++ batch: int, ++) -> torch.Tensor: ++ """Return this plan's page table, building it at most once per step. ++ ++ Every sparse layer of a step runs the same plan over the same kv_indices ++ buffer, so they all build a byte-identical table. Cache it on the plan and ++ reuse it while the inputs look unchanged. ++ ++ The cache holds a reference to kv_segment_lens so identity comparison is ++ sound: a live object's id cannot be recycled. A caller that rebuilds its ++ plan or restages these lengths therefore gets a fresh table. Version ++ counters add a content check where tensors track one. ++ """ ++ cached = plan_info.get("_page_table_cache") ++ if cached is not None: ++ lens, ptr, numel, versions, geometry, page_table = cached ++ if ( ++ lens is kv_segment_lens ++ and ptr == kv_indices.data_ptr() ++ and numel == kv_indices.numel() ++ and geometry == (page_size, batch) ++ and versions ++ == (_version_token(kv_indices), _version_token(kv_segment_lens)) ++ ): ++ return page_table ++ page_table = _build_page_table(kv_indices, kv_segment_lens, page_size, batch) ++ plan_info["_page_table_cache"] = ( ++ kv_segment_lens, ++ kv_indices.data_ptr(), ++ kv_indices.numel(), ++ (_version_token(kv_indices), _version_token(kv_segment_lens)), ++ (page_size, batch), ++ page_table, + ) +- offset = 0 +- for b in range(batch): +- n = pages_per_batch[b] +- page_table[b, :n] = kv_indices[offset : offset + n].to(torch.int32) +- offset += n + return page_table - struct GmemBounds { - int packed_work_range_size; -@@ -19,17 +21,17 @@ - int kv_page_indptr_size; - int kv_indices_size; - int max_score_numel; -- int kv_block_indexes_numel; -+ int64_t kv_block_indexes_span; - int split_kv_size; - int qo_offsets_size; - }; - template - __device__ __forceinline__ T gmem_load_checked( -- const T* base, int idx, int size, const char* name) { -+ const T* base, int64_t idx, int64_t size, const char* name) { - if (__builtin_expect(idx < 0 || idx >= size, 0)) { -- printf("GMEM-OOB-LOAD [%s] idx=%d size=%d blk=(%d,%d,%d) thr=%d\n", -- name, idx, size, blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x); -+ printf("GMEM-OOB-LOAD [%s] idx=%lld size=%lld blk=(%d,%d,%d) thr=%d\n", -+ name, static_cast(idx), static_cast(size), blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x); - return T(0); - } - return base[idx]; -@@ -82,6 +84,7 @@ - // Macros for paged KV reads - #define KV_INDPTR_LOAD(ptr, idx, sz) gmem_load_checked((ptr), (idx), (sz), "kv_page_indptr") - #define KV_INDICES_LOAD(ptr, idx, sz) gmem_load_checked((ptr), (idx), (sz), "kv_indices") -+#define KV_BLOCK_INDEX_LOAD(ptr, idx, sz) gmem_load_checked((ptr), (idx), (sz), "kv_block_indexes") +@@ -351,8 +423,8 @@ def sparse_fmha( + if is_paged: - #else // FMHA_GMEM_BOUNDS_CHECK not defined + if kv_indices is not None: +- page_table = _build_page_table( +- kv_indices, kv_segment_lens, page_size, batch, ++ page_table = _page_table_for_plan( ++ plan_info, kv_indices, kv_segment_lens, page_size, batch, + ) -@@ -93,5 +96,6 @@ - #define SEG_LEN_LOAD(vl, idx, sz) (vl).segment_lens[(idx)] - #define KV_INDPTR_LOAD(ptr, idx, sz) __ldg(&(ptr)[(idx)]) - #define KV_INDICES_LOAD(ptr, idx, sz) __ldg(&(ptr)[(idx)]) -+#define KV_BLOCK_INDEX_LOAD(ptr, idx, sz) __ldg(&(ptr)[(idx)]) + # build_k2q_csr(return_schedule=True) builds schedule using hardware SM count internally +@@ -382,6 +454,17 @@ def sparse_fmha( - #endif // FMHA_GMEM_BOUNDS_CHECK + softmax_scale = sm_scale if sm_scale is not None else q.shape[-1] ** -0.5 + ++ # Hand the caller's buffer to the kernel when its layout already matches ++ # what `combine` produces, so the result does not have to be copied into ++ # place afterwards. Anything else falls back to allocate-then-copy. ++ writable_out = ( ++ out is not None ++ and out.is_contiguous() ++ and out.dtype == torch.bfloat16 ++ and out.device == q.device ++ and tuple(out.shape) == tuple(q.shape) ++ ) ++ + # print(q.shape, k.shape) + result = sparse_atten_func( + q, k, v, +@@ -398,9 +481,10 @@ def sparse_fmha( + seqused_k=seqused_k, + schedule=schedule, + usable_SM_count=usable_SM_count, ++ out=out if writable_out else None, + ) + +- if out is not None: ++ if out is not None and not writable_out: + out.copy_(result) + return out, None + return result, None diff --git a/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu b/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu index ea217d465be1..cf8370c245ed 100644 --- a/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu +++ b/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu @@ -347,6 +347,107 @@ __global__ void rms_norm_kernel(AllReduceParams params) #endif } +//! rms_norm_kernel for rows that one CTA covers in a single pass (blockDim.x * kPackedSize >= hidden_size, no smem), +//! made persistent: each CTA walks rows blockIdx.x, blockIdx.x + gridDim.x, ... with the same thread -> element mapping +//! and block_reduce_sum tree as rms_norm_kernel, so the output is bitwise the same. The next row's inputs are loaded +//! before this row's reduction and the weight stays in registers, which keeps more bytes in flight per thread. +template +__global__ void rms_norm_rows_kernel(AllReduceParams params) +{ + static constexpr int kPackedSize = details::kBytesPerAccess / sizeof(T); + using PackedStruct = typename PackedOn16Bytes::Type; + + T const* bias_buffer = reinterpret_cast(params.fusion_params.bias_buffer); + T const* residual_buffer = reinterpret_cast(params.fusion_params.residual_buffer); + T const* weight_buffer = reinterpret_cast(params.fusion_params.weight_buffer); + T* local_final_output_buffer = reinterpret_cast(params.local_output_buffer_ptr); + T* intermediate_buffer = reinterpret_cast(params.fusion_params.intermediate_buffer); + + int const hidden = params.fusion_params.hidden_size; + int const rows = params.elts_total / hidden; + int const offset = threadIdx.x * kPackedSize; + bool const active = offset < hidden; + +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) && (__CUDA_ARCH__ < 1200)) + cudaGridDependencySynchronize(); +#endif + + PackedStruct weight_vec, bias_vec; + if (active) + { + if constexpr (Affine) + { + weight_vec.packed = *reinterpret_cast(weight_buffer + offset); + } + if constexpr (Bias) + { + bias_vec.packed = *reinterpret_cast(bias_buffer + offset); + } + } + PackedStruct inter_vec, residual_vec; + int row = blockIdx.x; + if (active && row < rows) + { + inter_vec.packed + = *reinterpret_cast(intermediate_buffer + static_cast(row) * hidden + offset); + if constexpr (Residual) + { + residual_vec.packed + = *reinterpret_cast(residual_buffer + static_cast(row) * hidden + offset); + } + } + for (; row < rows; row += gridDim.x) + { + int64_t const rowOffset = static_cast(row) * hidden + offset; + int const next = row + gridDim.x; + PackedStruct next_inter_vec, next_residual_vec; + if (active && next < rows) + { + next_inter_vec.packed + = *reinterpret_cast(intermediate_buffer + static_cast(next) * hidden + offset); + if constexpr (Residual) + { + next_residual_vec.packed + = *reinterpret_cast(residual_buffer + static_cast(next) * hidden + offset); + } + } + float acc = 0.f; + if (active) + { + if constexpr (Bias) + { + inter_vec.packed = add128b(inter_vec, bias_vec); + } + if constexpr (Residual) + { + inter_vec.packed = add128b(inter_vec, residual_vec); + *reinterpret_cast(intermediate_buffer + rowOffset) = inter_vec.packed; + } + acc = accumulate(acc, inter_vec); + } + acc = block_reduce_sum(acc); + float denom = rsqrtf(acc / hidden + params.fusion_params.eps); + if (active) + { + PackedStruct out_vec; + out_vec.packed = rms_norm(denom, inter_vec, weight_vec); + *reinterpret_cast(local_final_output_buffer + rowOffset) = out_vec.packed; + } + // block_reduce_sum's shared memory is written again by the next row. + __syncthreads(); + inter_vec.packed = next_inter_vec.packed; + residual_vec.packed = next_residual_vec.packed; + } +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) && (__CUDA_ARCH__ < 1200)) + cudaTriggerProgrammaticLaunchCompletion(); +#endif +} + +// Kill switch for the SM107 rms_norm_rows_kernel path of rms_norm_kernel_launcher, and the fewest rows it takes: +// below that the per-row kernel is as fast, so decode-sized steps keep it. +constexpr bool kRmsNormRowsSm107 = true; +constexpr int kRmsNormRowsSm107MinRows = 1024; + template __global__ void rms_pre_post_norm_kernel(AllReduceParams params) // for gemma2 pre residual + post residual norm { @@ -495,6 +596,24 @@ void rms_norm_kernel_launcher(AllReduceParams& params, cudaStream_t stream, AllR } else { + // SM107: a single-pass RMSNorm over many rows runs persistent (rms_norm_rows_kernel, bitwise the same). + if (kRmsNormRowsSm107 && fusionOp == AllReduceFusionOp::RESIDUAL_RMS_NORM && cta_num >= kRmsNormRowsSm107MinRows + && tensorrt_llm::common::getSMVersion() == 107) + { + static int const multiProcessorCount = tensorrt_llm::common::getMultiProcessorCount(); + cudaLaunchConfig_t kernelConfig = {0}; + kernelConfig.gridDim = std::min(cta_num, multiProcessorCount); + kernelConfig.blockDim = cta_size; + kernelConfig.dynamicSmemBytes = 0; + kernelConfig.stream = stream; + cudaLaunchAttribute attribute[1]; + attribute[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attribute[0].val.programmaticStreamSerializationAllowed = tensorrt_llm::common::getEnvEnablePDL(); + kernelConfig.attrs = attribute; + kernelConfig.numAttrs = 1; + TLLM_CUDA_CHECK(cudaLaunchKernelEx(&kernelConfig, rms_norm_rows_kernel, params)); + return; + } if (tensorrt_llm::common::getEnvEnablePDL()) { TLLM_LOG_DEBUG("Enable PDL in rms_norm_kernel"); diff --git a/cpp/tensorrt_llm/kernels/fusedQKNormRopeKernel.cu b/cpp/tensorrt_llm/kernels/fusedQKNormRopeKernel.cu index 9138604a9ba5..7ecf17075f17 100644 --- a/cpp/tensorrt_llm/kernels/fusedQKNormRopeKernel.cu +++ b/cpp/tensorrt_llm/kernels/fusedQKNormRopeKernel.cu @@ -860,6 +860,192 @@ __global__ void minimaxM3Nvfp4QKVIndexerNormRopeKVInsertKernel(__nv_bfloat16 con *reinterpret_cast(kvDataCache + dataOffset) = packedFp4; } +// minimaxM3Nvfp4QKVIndexerNormRopeKVInsertKernel for long chunks: one warp per (head slot, kTokens consecutive +// tokens) instead of one per (token, head slot). The norm weight is loaded once per warp and every token's input row, +// position id and cache slot are loaded before any token is processed; each token then runs the exact per-element +// code of the per-token kernel, so the outputs are bitwise the same. +template +__global__ void minimaxM3Nvfp4QKVIndexerNormRopeKVInsertRowsKernel(__nv_bfloat16 const* packedInput, + __nv_fp8_e4m3* qOutput, __nv_fp8_e4m3* indexQOutput, uint8_t* kvDataCache, uint8_t* kvScaleCache, + __nv_fp8_e4m3* indexKCache, int const* outCacheLoc, float const* kvQuantScale, int64_t dataPageStride, + int64_t dataPlaneStride, int64_t dataHeadStride, int64_t dataTokenStride, int64_t scalePageStride, + int64_t scalePlaneStride, int64_t scaleHeadStride, int64_t indexPageStride, int64_t indexTokenStride, + int64_t numPages, int numTokens, int numHeadsQ, int numHeadsKV, int numHeadsIndex, float eps, + __nv_bfloat16 const* qWeight, __nv_bfloat16 const* kWeight, __nv_bfloat16 const* indexQWeight, + __nv_bfloat16 const* indexKWeight, float const* rotaryCosSin, int const* positionIds) +{ + int const warpsPerBlock = blockDim.x / 32; + int const warpId = threadIdx.x / 32; + int const laneId = threadIdx.x % 32; + int const globalWarp = blockIdx.x * warpsPerBlock + warpId; + int const totalHeads = numHeadsQ + 2 * numHeadsKV + numHeadsIndex + 1; + int const tokenBase = (globalWarp / totalHeads) * kTokens; + int const localHead = globalWarp % totalHeads; + if (tokenBase >= numTokens) + { + return; + } + + int const kBegin = numHeadsQ; + int const vBegin = kBegin + numHeadsKV; + int const indexQBegin = vBegin + numHeadsKV; + int const indexKHead = indexQBegin + numHeadsIndex; + bool const isQ = localHead < kBegin; + bool const isK = localHead >= kBegin && localHead < vBegin; + bool const isV = localHead >= vBegin && localHead < indexQBegin; + bool const isIndexQ = localHead >= indexQBegin && localHead < indexKHead; + bool const isIndexK = localHead == indexKHead; + bool const toCache = !isQ && !isIndexQ; + + constexpr int kVecSize = kMinimaxM3ElemsPerThread * sizeof(__nv_bfloat16) / 4; + using VecT = typename tensorrt_llm::common::packed_as::type; +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) + cudaGridDependencySynchronize(); +#endif + float weights[kMinimaxM3ElemsPerThread]; + if (!isV) + { + auto const* normWeight = isQ ? qWeight : (isK ? kWeight : (isIndexQ ? indexQWeight : indexKWeight)); +#pragma unroll + for (int i = 0; i < kMinimaxM3ElemsPerThread; ++i) + { + weights[i] = __bfloat162float(normWeight[laneId * kMinimaxM3ElemsPerThread + i]); + } + } + VecT packedRows[kTokens]; + int positions[kTokens]; + int slots[kTokens]; +#pragma unroll + for (int t = 0; t < kTokens; ++t) + { + int const tokenIdx = tokenBase + t; + if (tokenIdx < numTokens) + { + int64_t const inputOffset = (static_cast(tokenIdx) * totalHeads + localHead) * kMinimaxM3HeadDim + + laneId * kMinimaxM3ElemsPerThread; + packedRows[t] = *reinterpret_cast(packedInput + inputOffset); + positions[t] = (!isV && laneId == 0) ? positionIds[tokenIdx] : 0; + slots[t] = (toCache && laneId == 0) ? outCacheLoc[tokenIdx] : 0; + } + } + +#pragma unroll + for (int t = 0; t < kTokens; ++t) + { + int const tokenIdx = tokenBase + t; + if (tokenIdx >= numTokens) + { + break; + } + float elements[kMinimaxM3ElemsPerThread]; + float sumSquares = 0.0F; +#pragma unroll + for (int pair = 0; pair < kVecSize; ++pair) + { + float2 const values = __bfloat1622float2( + *reinterpret_cast<__nv_bfloat162 const*>(reinterpret_cast(&packedRows[t]) + pair)); + elements[2 * pair] = values.x; + elements[2 * pair + 1] = values.y; + if (!isV) + { + sumSquares += values.x * values.x + values.y * values.y; + } + } + + if (!isV) + { + sumSquares = tensorrt_llm::common::warpReduceSum(sumSquares); + float const rmsReciprocal = rsqrtf(sumSquares / static_cast(kMinimaxM3HeadDim) + eps); +#pragma unroll + for (int i = 0; i < kMinimaxM3ElemsPerThread; ++i) + { + elements[i] *= rmsReciprocal * (1.0F + weights[i]); + } + + __syncwarp(); + constexpr int kPairOffset = (kMinimaxM3RotaryDim / 2) / kMinimaxM3ElemsPerThread; + int const positionId = __shfl_sync(0xffffffff, positions[t], 0); + int64_t const ropeRow = static_cast(positionId) * kMinimaxM3RotaryDim; +#pragma unroll + for (int i = 0; i < kMinimaxM3ElemsPerThread; ++i) + { + int const dim = laneId * kMinimaxM3ElemsPerThread + i; + float paired = __shfl_xor_sync(0xffffffff, elements[i], kPairOffset); + if (dim < kMinimaxM3RotaryDim) + { + bool const firstHalf = dim < kMinimaxM3RotaryDim / 2; + if (firstHalf) + { + paired = -paired; + } + int const coefficient = firstHalf ? dim : dim - kMinimaxM3RotaryDim / 2; + float const cosine = rotaryCosSin[ropeRow + coefficient]; + float const sine = rotaryCosSin[ropeRow + kMinimaxM3RotaryDim / 2 + coefficient]; + elements[i] = elements[i] * cosine + paired * sine; + } + } + __syncwarp(); + } + + if (isQ) + { + int64_t const outputOffset = (static_cast(tokenIdx) * numHeadsQ + localHead) * kMinimaxM3HeadDim + + laneId * kMinimaxM3ElemsPerThread; + storeFp8HeadElements64(qOutput, outputOffset, elements); + continue; + } + if (isIndexQ) + { + int const head = localHead - indexQBegin; + int64_t const outputOffset = (static_cast(tokenIdx) * numHeadsIndex + head) * kMinimaxM3HeadDim + + laneId * kMinimaxM3ElemsPerThread; + storeFp8HeadElements64(indexQOutput, outputOffset, elements); + continue; + } + + int const slot = __shfl_sync(0xffffffff, slots[t], 0); + if (slot < 0) + { + continue; + } + int const page = slot / kMinimaxM3PageSize; + if (page >= numPages) + { + continue; + } + int const withinPage = slot & (kMinimaxM3PageSize - 1); + if (isIndexK) + { + int64_t const outputOffset = static_cast(page) * indexPageStride + + static_cast(withinPage) * indexTokenStride + laneId * kMinimaxM3ElemsPerThread; + storeFp8HeadElements64(indexKCache, outputOffset, elements); + continue; + } + + int const head = isK ? localHead - kBegin : localHead - vBegin; + int const plane = isV ? 1 : 0; + int const scaleColumn = laneId / 4; + int64_t const scaleWithinPage = isV + ? static_cast(withinPage / 4) * 32 + static_cast(scaleColumn) * 4 + withinPage % 4 + : static_cast(withinPage) * 8 + scaleColumn; + int64_t const scaleOffset = static_cast(page) * scalePageStride + + static_cast(plane) * scalePlaneStride + static_cast(head) * scaleHeadStride + + scaleWithinPage; + uint8_t* scaleOut = laneId % 4 == 0 ? kvScaleCache + scaleOffset : nullptr; + uint16_t const packedFp4 = quantizeMinimaxM3Fp4x4(elements, kvQuantScale[isV ? 2 : 1], scaleOut); + int64_t const dataOffset = static_cast(page) * dataPageStride + + static_cast(plane) * dataPlaneStride + static_cast(head) * dataHeadStride + + static_cast(withinPage) * dataTokenStride + laneId * 2; + *reinterpret_cast(kvDataCache + dataOffset) = packedFp4; + } +} + +// Kill switch for the SM107 rows producer of launchMinimaxM3Nvfp4QKVIndexerNormRopeKVInsert, the fewest tokens it +// takes (shorter steps keep the per-token kernel) and its tokens per warp. +constexpr bool kNvfp4ProducerRowsSm107 = true; +constexpr int kNvfp4ProducerRowsSm107MinTokens = 1024; +constexpr int kNvfp4ProducerRowsTokens = 4; + } // namespace // Borrowed from @@ -1049,7 +1235,11 @@ void launchMinimaxM3Nvfp4QKVIndexerNormRopeKVInsert(void const* packed_input, vo constexpr int kBlockSize = 256; constexpr int kWarpsPerBlock = kBlockSize / 32; int const slotsPerToken = num_heads_q + 2 * num_heads_kv + num_heads_index + 1; - int const totalWarps = num_tokens * slotsPerToken; + // SM107: long chunks run the rows producer (several tokens per warp, bitwise the same outputs). + bool const rows + = kNvfp4ProducerRowsSm107 && num_tokens >= kNvfp4ProducerRowsSm107MinTokens && common::getSMVersion() == 107; + int const tokensPerWarp = rows ? kNvfp4ProducerRowsTokens : 1; + int const totalWarps = common::divUp(num_tokens, tokensPerWarp) * slotsPerToken; int const gridSize = common::divUp(totalWarps, kWarpsPerBlock); cudaLaunchConfig_t config{}; config.gridDim = gridSize; @@ -1061,7 +1251,9 @@ void launchMinimaxM3Nvfp4QKVIndexerNormRopeKVInsert(void const* packed_input, vo attrs[0].val.programmaticStreamSerializationAllowed = common::getEnvEnablePDL(); config.numAttrs = 1; config.attrs = attrs; - TLLM_CUDA_CHECK(cudaLaunchKernelEx(&config, minimaxM3Nvfp4QKVIndexerNormRopeKVInsertKernel, + TLLM_CUDA_CHECK(cudaLaunchKernelEx(&config, + rows ? minimaxM3Nvfp4QKVIndexerNormRopeKVInsertRowsKernel + : minimaxM3Nvfp4QKVIndexerNormRopeKVInsertKernel, static_cast<__nv_bfloat16 const*>(packed_input), static_cast<__nv_fp8_e4m3*>(q_output), static_cast<__nv_fp8_e4m3*>(index_q_output), static_cast(kv_data_cache), static_cast(kv_scale_cache), static_cast<__nv_fp8_e4m3*>(index_k_cache), out_cache_loc, diff --git a/cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.cu b/cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.cu new file mode 100644 index 000000000000..c851266f3754 --- /dev/null +++ b/cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.cu @@ -0,0 +1,542 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Prefill top-16 block select over head-major scores [num_kv_heads, num_blocks, total_q] with unit query stride. +// +// One CTA per (KV head, 8 consecutive queries). The 8 queries of one block are one 32-byte sector, so the CTA reads +// each sector it needs exactly once, as two 16-byte loads. The tile's rows are staged in shared memory as ordered keys +// of the forced scores. A long tile's key rows fill most of shared memory, so one CTA runs per SM; its loads then come +// from extra staging warps (kWideThreads from kWideMinBlocks blocks), which exit before the selection. Each of the +// first 8 warps then selects one row: +// - the 32 lane-stride group minima are sorted in the warp and the 16th of them bounds the row's 16th smallest key, +// so every key at or below that bound is a candidate; the candidates (compacted in ascending block order) are +// ranked exactly by (key, block); +// - a row with more than kMaxCand candidates (heavy ties) falls back to an exact 4 x 8-bit radix select. +// Ordering is the descending ordered key of the float bits used by minimax_m3_select_blocks, ties to the smaller +// block, so the result is the same top-16 set. + +#include "tensorrt_llm/kernels/minimaxM3/selectPrefillTile.h" + +#include "tensorrt_llm/common/cudaUtils.h" +#include "tensorrt_llm/common/envUtils.h" +#include "tensorrt_llm/common/logger.h" + +#include +#include +#include +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace kernels +{ + +namespace +{ +constexpr int kTopK = 16; +constexpr int kTileQ = 8; +constexpr int kThreads = kTileQ * 32; +// From this many blocks on, the tile is staged by kWideThreads threads with kWideUnroll blocks in flight each. +constexpr int kWideMinBlocks = 2600; +constexpr int kWideThreads = 1024; +constexpr int kWideUnroll = 4; +constexpr uint32_t kFull = 0xFFFFFFFFu; +constexpr float kInitScore = 1.0e30f; +constexpr float kLocalScore = 1.0e29f; +constexpr uint32_t kNegInfKey = 0xFF800000u; +// Per-warp scratch: the radix histogram (256 bins) or the candidate list (keys then blocks). +constexpr int kMaxCand = 256; +constexpr int kWarpScratch = 2 * kMaxCand; +// Blocks each thread has in flight while staging a narrow tile. +constexpr int kStageUnroll = 8; + +__device__ __forceinline__ uint32_t orderedKey(float x) +{ + uint32_t const bits = __float_as_uint(x); + return (bits & 0x80000000u) ? bits : (~bits & 0x7fffffffu); +} + +// Row pitch in keys: >= num_blocks and == 4 (mod 32), so the staging writes of +// 8 rows x 4 consecutive blocks per warp hit 32 distinct banks. +__host__ __device__ __forceinline__ int rowPitch(int numBlocks) +{ + int p = (numBlocks + 31) / 32 * 32 + 4; + return p; +} + +// kNt staging threads with kUnroll blocks in flight each; warps 0 .. kTileQ - 1 select. kIlp builds each row's 32 +// stride-class minima while staging (a staging thread only ever sees one class) and issues the candidate scan's +// shared-memory loads four at a time; the minima, the bound and every decision are the same as the scalar scans'. +template +__global__ void __launch_bounds__(kNt) selectPrefillTileKernel(float const* __restrict__ scores, int64_t headStride, + int64_t blockStride, int32_t const* __restrict__ nValid, int32_t* __restrict__ out, int64_t outQueryStride, + int64_t outHeadStride, int numBlocks, int totalQ, int initBlocks, int localBlocks) +{ + extern __shared__ uint32_t smem[]; + __shared__ uint32_t sClassMin[kTileQ * 32]; // [row][b % 32] (kIlp) + int const pitch = rowPitch(numBlocks); + uint32_t* keys = smem; // [kTileQ][pitch] + uint32_t* hist = smem + kTileQ * pitch; // [kTileQ][kWarpScratch] + + int const head = blockIdx.y; + int const q0 = blockIdx.x * kTileQ; + int const tid = threadIdx.x; + int const warp = tid / 32; + int const lane = tid % 32; + +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) + cudaGridDependencySynchronize(); +#endif + + // ---- stage: thread loads queries 4 * jh .. 4 * jh + 3 of block b = tid / 2 + (kNt / 2) * i as one float4 ---- + { + int const jh = tid % 2; + int rowEnd[4]; + int64_t localStart[4]; + int tileEnd = 0; +#pragma unroll + for (int c = 0; c < 4; ++c) + { + int const q = q0 + 4 * jh + c; + rowEnd[c] = 0; + localStart[c] = 0; + if (q < totalQ) + { + int const raw = nValid[q]; + rowEnd[c] = max(0, min(raw, numBlocks)); + localStart[c] = max(static_cast(raw) - localBlocks, static_cast(0)); + } + tileEnd = max(tileEnd, rowEnd[c]); + } + tileEnd = max(tileEnd, __shfl_xor_sync(kFull, tileEnd, 1)); + if constexpr (kIlp) + { + if (tid < kTileQ * 32) + { + sClassMin[tid] = 0xFFFFFFFFu; + } + } + __shared__ int sTileEnd[kNt / 32]; + if (lane == 0) + { + sTileEnd[warp] = tileEnd; + } + __syncthreads(); + tileEnd = 0; +#pragma unroll + for (int w = 0; w < kNt / 32; ++w) + { + tileEnd = max(tileEnd, sTileEnd[w]); + } + // Two threads read a tile's 8 queries of one block, one aligned 32-byte sector, when the base and the + // strides keep 16-byte alignment; otherwise, and for a partial last tile, they read one float at a time. + bool const fullVec = (reinterpret_cast(scores) & 15) == 0 && ((headStride | blockStride) & 3) == 0 + && (q0 + 4 * jh + 3) < totalQ; + float const* base = scores + static_cast(head) * headStride + q0 + 4 * jh; + constexpr int kBlocksPerIter = kNt / 2; + static_assert(kBlocksPerIter % 32 == 0, "a staging thread stays in one stride class b % 32"); + uint32_t classMin[4] = {0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; + for (int b0 = tid / 2; b0 < tileEnd; b0 += kBlocksPerIter * kUnroll) + { + float4 v[kUnroll]; +#pragma unroll + for (int u = 0; u < kUnroll; ++u) + { + int const b = b0 + u * kBlocksPerIter; + float4 x = make_float4(0.f, 0.f, 0.f, 0.f); + if (b < tileEnd) + { + float const* p = base + static_cast(b) * blockStride; + if (fullVec) + { + x = __ldg(reinterpret_cast(p)); + } + else + { + x.x = b < rowEnd[0] ? __ldg(p) : 0.f; + x.y = b < rowEnd[1] ? __ldg(p + 1) : 0.f; + x.z = b < rowEnd[2] ? __ldg(p + 2) : 0.f; + x.w = b < rowEnd[3] ? __ldg(p + 3) : 0.f; + } + } + v[u] = x; + } +#pragma unroll + for (int u = 0; u < kUnroll; ++u) + { + int const b = b0 + u * kBlocksPerIter; + if (b < tileEnd) + { + float const vals[4] = {v[u].x, v[u].y, v[u].z, v[u].w}; +#pragma unroll + for (int c = 0; c < 4; ++c) + { + uint32_t key = kNegInfKey; + if (b < rowEnd[c]) + { + float s = vals[c]; + if (b < initBlocks) + { + s = kInitScore; + } + if (b >= localStart[c]) + { + s = kLocalScore; + } + key = orderedKey(s); + if constexpr (kIlp) + { + classMin[c] = min(classMin[c], key); + } + } + keys[(4 * jh + c) * pitch + b] = key; + } + } + } + } + if constexpr (kIlp) + { + int const cls = (tid / 2) % 32; +#pragma unroll + for (int c = 0; c < 4; ++c) + { + if (classMin[c] != 0xFFFFFFFFu) + { + atomicMin(&sClassMin[(4 * jh + c) * 32 + cls], classMin[c]); + } + } + } + } + __syncthreads(); + if (warp >= kTileQ) + { + return; + } + + // ---- select: warp w owns query q0 + w ---- + int const q = q0 + warp; + if (q >= totalQ) + { + return; + } + int const raw = nValid[q]; + int const len = max(0, min(raw, numBlocks)); + uint32_t const* row = keys + warp * pitch; + uint32_t* h = hist + warp * kWarpScratch; + int32_t* dst = out + static_cast(q) * outQueryStride + static_cast(head) * outHeadStride; + + // Threshold key K and how many keys equal to K to take (tieTake). Keys < K are all in. + if (len > kTopK) + { + // Fast path. Group g = lanes' stride classes b % 32: each lane's best (smallest) key. + // T = the 16th smallest of the 32 group bests, so at least 16 keys are <= T and the + // row's 16th smallest key is <= T: every top-16 key (and every key tied with one) is a + // candidate. Candidates are compacted in ascending block order and ranked exactly. + uint32_t best = 0xFFFFFFFFu; + bool const any = lane < len; + if constexpr (kIlp) + { + best = sClassMin[warp * 32 + lane]; + } + else + { + for (int b = lane; b < len; b += 32) + { + best = min(best, row[b]); + } + } + // Ascending bitonic sort of the 32 group bests; empty groups sort last. + uint32_t v = any ? best : 0xFFFFFFFFu; + bool vEmpty = !any; +#pragma unroll + for (int size = 2; size <= 32; size *= 2) + { +#pragma unroll + for (int stride = size / 2; stride > 0; stride /= 2) + { + uint32_t const pv = __shfl_xor_sync(kFull, v, stride); + bool const pe = __shfl_xor_sync(kFull, vEmpty, stride); + bool const up = ((lane & size) == 0) == ((lane & stride) == 0); + // order: (empty, value); smaller first when 'up' + bool const pLess = (!pe && vEmpty) || (pe == vEmpty && pv < v); + bool const pGreater = (pe && !vEmpty) || (pe == vEmpty && pv > v); + if ((up && pLess) || (!up && pGreater)) + { + v = pv; + vEmpty = pe; + } + } + } + uint32_t const bound = __shfl_sync(kFull, v, kTopK - 1); + uint32_t* candKey = h; + uint32_t* candBlk = h + kMaxCand; + int nCand = 0; + int cb0 = 0; + if constexpr (kIlp) + { + for (; cb0 + 128 <= len; cb0 += 128) + { + uint32_t k[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) + { + k[j] = row[cb0 + 32 * j + lane]; + } +#pragma unroll + for (int j = 0; j < 4; ++j) + { + bool const c = k[j] <= bound; + uint32_t const m = __ballot_sync(kFull, c); + int const slot = nCand + __popc(m & ((1u << lane) - 1u)); + if (c && slot < kMaxCand) + { + candKey[slot] = k[j]; + candBlk[slot] = static_cast(cb0 + 32 * j + lane); + } + nCand += __popc(m); + } + } + } + for (int b0 = cb0; b0 < len; b0 += 32) + { + int const b = b0 + lane; + bool const c = b < len && row[b] <= bound; + uint32_t const m = __ballot_sync(kFull, c); + int const slot = nCand + __popc(m & ((1u << lane) - 1u)); + if (c && slot < kMaxCand) + { + candKey[slot] = row[b]; + candBlk[slot] = static_cast(b); + } + nCand += __popc(m); + } + __syncwarp(); + if (nCand <= kMaxCand) + { + // Exact rank by (key, block); candidates are already in ascending block order, so a + // second ballot compaction of the rank < 16 ones writes the output ascending. + int written = 0; + for (int i0 = 0; i0 < nCand; i0 += 32) + { + int const i = i0 + lane; + bool sel = false; + uint32_t k = 0xFFFFFFFFu; + uint32_t blk = 0; + if (i < nCand) + { + k = candKey[i]; + blk = candBlk[i]; + int rank = 0; + for (int jdx = 0; jdx < nCand; ++jdx) + { + uint32_t const kj = candKey[jdx]; + rank += (kj < k) || (kj == k && jdx < i); + } + sel = rank < kTopK; + } + uint32_t const m = __ballot_sync(kFull, sel && k != kNegInfKey); + int const slot = written + __popc(m & ((1u << lane) - 1u)); + if (sel && k != kNegInfKey) + { + dst[slot] = static_cast(blk); + } + written += __popc(m); + } + for (int r = written + lane; r < kTopK; r += 32) + { + dst[r] = -1; + } + return; + } + __syncwarp(); + } + + uint32_t thresh = 0xFFFFFFFFu; + int tieTake = kTopK; + if (len > kTopK) + { + uint32_t prefix = 0; + int remaining = kTopK; // rank (1-based) of the wanted key among keys matching prefix +#pragma unroll 1 + for (int pass = 0; pass < 4; ++pass) + { + int const shift = 24 - 8 * pass; + uint32_t const hiMask = pass == 0 ? 0u : (0xFFFFFFFFu << (shift + 8)); + for (int i = lane; i < 256; i += 32) + { + h[i] = 0; + } + __syncwarp(); + for (int b0 = 0; b0 < len; b0 += 32) + { + int const b = b0 + lane; + bool const active = b < len; + uint32_t const k = active ? row[b] : 0u; + bool const match = active && ((k & hiMask) == prefix); + uint32_t const digit = (k >> shift) & 0xFFu; + uint32_t const m = __ballot_sync(kFull, match); + if (match) + { + uint32_t const peers = __match_any_sync(m, digit); + if ((__ffs(peers) - 1) == lane) + { + atomicAdd(&h[digit], static_cast(__popc(peers))); + } + } + } + __syncwarp(); + // Find the digit holding the remaining-th smallest key: each lane owns 8 bins. + uint32_t c[8]; + uint32_t local = 0; +#pragma unroll + for (int i = 0; i < 8; ++i) + { + c[i] = h[lane * 8 + i]; + local += c[i]; + } + uint32_t incl = local; +#pragma unroll + for (int o = 1; o < 32; o *= 2) + { + uint32_t const v = __shfl_up_sync(kFull, incl, o); + if (lane >= o) + { + incl += v; + } + } + uint32_t const excl = incl - local; + bool const mine = excl < static_cast(remaining) && incl >= static_cast(remaining); + uint32_t const owner = __ballot_sync(kFull, mine); + int const ownerLane = __ffs(owner) - 1; + int digitSel = 0; + uint32_t below = 0; + if (lane == ownerLane) + { + uint32_t acc = excl; +#pragma unroll + for (int i = 0; i < 8; ++i) + { + if (acc + c[i] >= static_cast(remaining)) + { + digitSel = lane * 8 + i; + below = acc; + break; + } + acc += c[i]; + } + } + digitSel = __shfl_sync(kFull, digitSel, ownerLane); + below = __shfl_sync(kFull, below, ownerLane); + prefix |= static_cast(digitSel) << shift; + remaining -= static_cast(below); + __syncwarp(); + } + thresh = prefix; + tieTake = remaining; // keys equal to thresh to take, smallest blocks first + } + + // ---- collect in ascending block order ---- + // len <= 16: every valid block is a pick (thresh = max, tieTake = 16 covers all). + int count = 0; + int ties = 0; + for (int b0 = 0; b0 < len && count < kTopK; b0 += 32) + { + int const b = b0 + lane; + bool const active = b < len; + uint32_t const k = active ? row[b] : 0xFFFFFFFFu; + bool const strict = active && (len <= kTopK || k < thresh); + bool const tie = active && len > kTopK && k == thresh; + uint32_t const tieMask = __ballot_sync(kFull, tie); + int const tieRank = ties + __popc(tieMask & ((1u << lane) - 1u)); + bool const take = strict || (tie && tieRank < tieTake); + uint32_t const takeMask = __ballot_sync(kFull, take); + int const slot = count + __popc(takeMask & ((1u << lane) - 1u)); + if (take && slot < kTopK) + { + dst[slot] = (k == kNegInfKey) ? -1 : b; + } + count += __popc(takeMask); + ties += __popc(tieMask); + } + __syncwarp(); + // Picks forced to -inf were written as -1 in place; compact the valid ids to the front, -1 tail. + if (lane == 0) + { + int32_t ids[kTopK]; + int n = 0; + int const picks = min(count, kTopK); + for (int i = 0; i < picks; ++i) + { + int32_t const v = dst[i]; + if (v >= 0) + { + ids[n++] = v; + } + } + for (int i = 0; i < kTopK; ++i) + { + dst[i] = i < n ? ids[i] : -1; + } + } +} +} // namespace + +cudaError_t invokeMinimaxM3SelectPrefillTile(float const* scores, int64_t headStride, int64_t blockStride, + int32_t const* nValidBlocks, int32_t* out, int64_t outQueryStride, int64_t outHeadStride, int32_t numKvHeads, + int32_t numBlocks, int32_t totalQ, int32_t initBlocks, int32_t localBlocks, cudaStream_t stream) +{ + if (totalQ == 0 || numKvHeads == 0) + { + return cudaSuccess; + } + if (numBlocks > kMinimaxM3SelectPrefillTileMaxBlocks) + { + return cudaErrorInvalidValue; + } + // TRTLLM_M3_SELECT_TILE_V2=1 keeps the previous launch: 256 threads for every tile, one load at a time per scan. + static bool const v2Only = common::getBoolEnv("TRTLLM_M3_SELECT_TILE_V2"); + static std::once_flag logged; + std::call_once(logged, + [] + { + TLLM_LOG_INFO(v2Only + ? "minimaxM3SelectPrefillTile: staging reads each block's sector as two 16-byte loads" + : "minimaxM3SelectPrefillTile: v4, stride-class minima while staging, 4-wide candidate " + "scan and 1024 staging threads from 2600 blocks"); + }); + size_t const smemBytes + = (static_cast(kTileQ) * rowPitch(numBlocks) + kTileQ * kWarpScratch) * sizeof(uint32_t); + bool const wide = !v2Only && numBlocks >= kWideMinBlocks; + auto kernel = v2Only ? selectPrefillTileKernel + : wide ? selectPrefillTileKernel + : selectPrefillTileKernel; + cudaError_t err + = cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, static_cast(smemBytes)); + if (err != cudaSuccess) + { + return err; + } + dim3 const grid((totalQ + kTileQ - 1) / kTileQ, numKvHeads); + common::launchWithPdlWhenEnabled("minimaxM3SelectPrefillTile", kernel, grid, dim3(wide ? kWideThreads : kThreads), + smemBytes, stream, scores, headStride, blockStride, nValidBlocks, out, outQueryStride, outHeadStride, numBlocks, + totalQ, initBlocks, localBlocks); + return cudaGetLastError(); +} + +} // namespace kernels + +TRTLLM_NAMESPACE_END diff --git a/cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.h b/cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.h new file mode 100644 index 000000000000..3505ff81cddc --- /dev/null +++ b/cpp/tensorrt_llm/kernels/minimaxM3/selectPrefillTile.h @@ -0,0 +1,48 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "tensorrt_llm/common/config.h" + +#include +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace kernels +{ + +//! Largest row (blocks per query) the prefill tile select stages in shared memory: 8 query rows of keys plus the +//! per-warp scratch stay under 200 KB. +constexpr int32_t kMinimaxM3SelectPrefillTileMaxBlocks = 5856; + +//! MiniMax-M3 top-16 block select for prefill: per-KV-head scores [numKvHeads, numBlocks, totalQ] with unit query +//! stride, one CTA per (KV head, 8 consecutive queries) so every 32-byte sector of the scores is read once. +//! +//! Same contract as minimax_m3_select_blocks: per (query, head) row the clamp(nValidBlocks[query], 0, numBlocks) +//! leading blocks; the last localBlocks of them (counted from the unclamped count) forced to 1e29 and the first +//! initBlocks to 1e30, local winning; ranked by the descending ordered key of the float bits (NaN above +inf, +0 above +//! -0, negative NaN below -inf), ties to the smaller block; picks whose forced score is -inf emitted as -1; ascending +//! ids with -1 tail padding. Writes out[query * outQueryStride + head * outHeadStride + 0..15]. +cudaError_t invokeMinimaxM3SelectPrefillTile(float const* scores, int64_t headStride, int64_t blockStride, + int32_t const* nValidBlocks, int32_t* out, int64_t outQueryStride, int64_t outHeadStride, int32_t numKvHeads, + int32_t numBlocks, int32_t totalQ, int32_t initBlocks, int32_t localBlocks, cudaStream_t stream); + +} // namespace kernels + +TRTLLM_NAMESPACE_END diff --git a/cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.cu b/cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.cu new file mode 100644 index 000000000000..04cb557b9c1e --- /dev/null +++ b/cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.cu @@ -0,0 +1,232 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.h" +#include "tensorrt_llm/kernels/quantization.cuh" + +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace kernels::minimaxM3Sm107Tp2 +{ +namespace +{ + +constexpr int kPackedSize = 8; // BF16 elements per 16-byte access, = CVT_ELTS_PER_THREAD +constexpr int kWarpSize = 32; + +union PackedBf16 +{ + int4 packed; + __nv_bfloat162 unpacked[4]; +}; + +// The helpers below are customAllReduceKernels.cu's (reduce_fusion::warp_reduce_sum / block_reduce_sum, +// accumulate, rms_norm, add128b): the same arithmetic in the same order, so the norm is bitwise +// rms_norm_rows_kernel's. +__device__ __forceinline__ float warpReduceSum(float val) +{ + val += __shfl_xor_sync(~0, val, 16); + val += __shfl_xor_sync(~0, val, 8); + val += __shfl_xor_sync(~0, val, 4); + val += __shfl_xor_sync(~0, val, 2); + val += __shfl_xor_sync(~0, val, 1); + return val; +} + +__device__ __forceinline__ float blockReduceSum(float val) +{ + __shared__ float smem[kWarpSize]; + int const laneId = threadIdx.x % kWarpSize; + int const warpId = threadIdx.x / kWarpSize; + int const warpNum = blockDim.x / kWarpSize; + val = warpReduceSum(val); + if (laneId == 0) + { + smem[warpId] = val; + } + __syncthreads(); + val = laneId < warpNum ? smem[laneId] : 0.f; + val = warpReduceSum(val); + return val; +} + +__device__ __forceinline__ int4 add128b(PackedBf16& a, PackedBf16& b) +{ + PackedBf16 c; + c.unpacked[0] = a.unpacked[0] + b.unpacked[0]; + c.unpacked[1] = a.unpacked[1] + b.unpacked[1]; + c.unpacked[2] = a.unpacked[2] + b.unpacked[2]; + c.unpacked[3] = a.unpacked[3] + b.unpacked[3]; + return c.packed; +} + +__device__ __forceinline__ float accumulate(float acc, PackedBf16& vec) +{ +#pragma unroll + for (int i = 0; i < kPackedSize; ++i) + { + float v = static_cast(reinterpret_cast<__nv_bfloat16*>(vec.unpacked)[i]); + acc += v * v; + } + return acc; +} + +__device__ __forceinline__ int4 rmsNorm(float denom, PackedBf16& vec, PackedBf16& weight) +{ + PackedBf16 ret; +#pragma unroll + for (int i = 0; i < kPackedSize; ++i) + { + float v1 = static_cast(reinterpret_cast<__nv_bfloat16*>(vec.unpacked)[i]); + float v2 = static_cast(reinterpret_cast<__nv_bfloat16*>(weight.unpacked)[i]); + reinterpret_cast<__nv_bfloat16*>(ret.unpacked)[i] = static_cast<__nv_bfloat16>(v1 * denom * v2); + } + return ret.packed; +} + +//! rms_norm_rows_kernel (persistent rows, next row prefetched, +//! one 8-element chunk per thread) whose per-row output also goes through quantize_mxfp8_rows' per-element math +//! (cvt_warp_fp16_to_mxfp8, swizzled K32 scales) while it is still in registers. The scale rows that pad +//! the row count to a multiple of 128 are zero-filled, as quantize_mxfp8_rows does. +template +__global__ void ctxResidualRmsNormMxfp8Kernel(__nv_bfloat16* inter, __nv_bfloat16 const* residual, + __nv_bfloat16 const* weight, __nv_bfloat16* normOut, uint64_t* qOut, uint32_t* sfOut, uint32_t* fp4Out, + uint32_t* fp4SfOut, float const* fp4GlobalScale, int rows, int hidden, float eps) +{ +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 1000) + static constexpr int kThreadsPerSf = 32 / CVT_ELTS_PER_THREAD; + int const colIdx = threadIdx.x; + int const offset = colIdx * kPackedSize; + int const colThreads = hidden / kPackedSize; + std::optional const batchIdx = 0; + std::optional const numRows = rows; + + cudaGridDependencySynchronize(); + + // quantize_with_block_size's per-tensor scale (SFScaleVal) for the NVFP4 copy. + float const fp4SfScale = kFp4 ? fp4GlobalScale[0] : 1.0f; + PackedBf16 weightVec; + weightVec.packed = *reinterpret_cast(weight + offset); + PackedBf16 interVec, residualVec; + int row = blockIdx.x; + if (row < rows) + { + interVec.packed = *reinterpret_cast(inter + static_cast(row) * hidden + offset); + residualVec.packed = *reinterpret_cast(residual + static_cast(row) * hidden + offset); + } + for (; row < rows; row += gridDim.x) + { + int64_t const rowOffset = static_cast(row) * hidden + offset; + int const next = row + gridDim.x; + PackedBf16 nextInterVec, nextResidualVec; + if (next < rows) + { + nextInterVec.packed = *reinterpret_cast(inter + static_cast(next) * hidden + offset); + nextResidualVec.packed + = *reinterpret_cast(residual + static_cast(next) * hidden + offset); + } + interVec.packed = add128b(interVec, residualVec); + *reinterpret_cast(inter + rowOffset) = interVec.packed; + float acc = accumulate(0.f, interVec); + acc = blockReduceSum(acc); + float const denom = rsqrtf(acc / hidden + eps); + PackedBf16 outVec; + outVec.packed = rmsNorm(denom, interVec, weightVec); + if constexpr (kWriteNorm) + { + *reinterpret_cast(normOut + rowOffset) = outVec.packed; + } + PackedVec<__nv_bfloat16> quantIn; + *reinterpret_cast(&quantIn) = outVec.packed; + auto sf = cvt_quant_get_sf_out_offset( + batchIdx, row, colIdx, numRows, hidden / 32, sfOut, QuantizationSFLayout::SWIZZLED); + qOut[static_cast(row) * colThreads + colIdx] = cvt_warp_fp16_to_mxfp8<__nv_bfloat16, 32>(quantIn, sf); + if constexpr (kFp4) + { + // fp4_quantize(norm, globalScale, 16, ue8m0 = false, swizzled = false): E2M1 x 8 per thread, E4M3 scale per + // 16 elements in the linear layout (no row padding). + PackedVec<__nv_bfloat16> fp4In; + *reinterpret_cast(&fp4In) = outVec.packed; + auto sf4 = cvt_quant_get_sf_out_offset( + batchIdx, row, colIdx, numRows, hidden / 16, fp4SfOut, QuantizationSFLayout::LINEAR); + fp4Out[static_cast(row) * colThreads + colIdx] + = cvt_warp_fp16_to_fp4<__nv_bfloat16, 16, false>(fp4In, fp4SfScale, sf4); + } + // blockReduceSum's shared memory is written again by the next row. + __syncthreads(); + interVec.packed = nextInterVec.packed; + residualVec.packed = nextResidualVec.packed; + } + int const paddedRows = (rows + 127) / 128 * 128; + for (int padRow = rows + blockIdx.x; padRow < paddedRows; padRow += gridDim.x) + { + auto sf = cvt_quant_get_sf_out_offset( + batchIdx, padRow, colIdx, numRows, hidden / 32, sfOut, QuantizationSFLayout::SWIZZLED); + cvt_store_replicated_sf<1>(sf, 0x00); + } + // Every thread's stores are visible before any thread reports PDL completion (as in quantize_mxfp8_rows). + __threadfence(); + __syncthreads(); + cudaTriggerProgrammaticLaunchCompletion(); +#endif +} + +} // namespace + +void invokeCtxResidualRmsNormMxfp8(__nv_bfloat16* inter, __nv_bfloat16 const* residual, __nv_bfloat16 const* weight, + __nv_bfloat16* normOut, uint64_t* qOut, uint32_t* sfOut, uint32_t* fp4Out, uint32_t* fp4SfOut, + float const* fp4GlobalScale, int rows, int hidden, float eps, bool enablePdl, cudaStream_t stream) +{ + static int const multiProcessorCount = [] + { + int device = 0; + int count = 0; + cudaGetDevice(&device); + cudaDeviceGetAttribute(&count, cudaDevAttrMultiProcessorCount, device); + return count; + }(); + cudaLaunchConfig_t config = {0}; + config.gridDim = std::max(1, std::min(rows, multiProcessorCount)); + config.blockDim = hidden / kPackedSize; + config.dynamicSmemBytes = 0; + config.stream = stream; + cudaLaunchAttribute attribute[1]; + attribute[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attribute[0].val.programmaticStreamSerializationAllowed = enablePdl; + config.attrs = attribute; + config.numAttrs = 1; + auto launch = [&](auto kernel) + { + cudaLaunchKernelEx(&config, kernel, inter, residual, weight, normOut, qOut, sfOut, fp4Out, fp4SfOut, + fp4GlobalScale, rows, hidden, eps); + }; + bool const fp4 = fp4Out != nullptr; + if (normOut != nullptr) + { + fp4 ? launch(ctxResidualRmsNormMxfp8Kernel) : launch(ctxResidualRmsNormMxfp8Kernel); + } + else + { + fp4 ? launch(ctxResidualRmsNormMxfp8Kernel) : launch(ctxResidualRmsNormMxfp8Kernel); + } +} + +} // namespace kernels::minimaxM3Sm107Tp2 + +TRTLLM_NAMESPACE_END diff --git a/cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.h b/cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.h new file mode 100644 index 000000000000..999d51a92d48 --- /dev/null +++ b/cpp/tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.h @@ -0,0 +1,43 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "tensorrt_llm/common/config.h" +#include +#include +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace kernels::minimaxM3Sm107Tp2 +{ + +//! MiniMax-M3 CTX prefill: the residual add + RMSNorm of the all-reduce's RESIDUAL_RMS_NORM epilogue +//! (rms_norm_rows_kernel, bitwise the same) fused with the MXFP8 quantization of its output that the next MXFP8 +//! linear performs (quantize_mxfp8_rows: K32 UE8M0 scales, swizzled 128x4 layout, bitwise the same). +//! In place: `inter` (the all-reduce output) becomes `inter + residual`, as in the stock epilogue. +//! normOut may be null (the BF16 norm output is then not written). With fp4Out (and fp4SfOut / fp4GlobalScale) set, +//! it also writes fp4_quantize(norm, globalScale, 16, ue8m0 = false, swizzled = false) of the same rows. +//! hidden % 256 == 0, hidden / 8 <= 1024. +void invokeCtxResidualRmsNormMxfp8(__nv_bfloat16* inter, __nv_bfloat16 const* residual, __nv_bfloat16 const* weight, + __nv_bfloat16* normOut, uint64_t* qOut, uint32_t* sfOut, uint32_t* fp4Out, uint32_t* fp4SfOut, + float const* fp4GlobalScale, int rows, int hidden, float eps, bool enablePdl, cudaStream_t stream); + +} // namespace kernels::minimaxM3Sm107Tp2 + +TRTLLM_NAMESPACE_END diff --git a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp new file mode 100644 index 000000000000..57277019ac09 --- /dev/null +++ b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp @@ -0,0 +1,81 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tensorrt_llm/kernels/minimaxM3/selectPrefillTile.h" + +#include +#include +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace torch_ext +{ + +//! Prefill top-16 block select over per-KV-head scores with unit query stride, into a caller-owned table. +//! +//! @param scores Float32 CUDA tensor [num_kv_heads, num_blocks, total_q] with stride(2) == 1. +//! @param nValidBlocks Contiguous int32 CUDA tensor with at least total_q elements. +//! @param out Int32 CUDA tensor of logical shape [total_q, num_kv_heads, 16] with unit stride in the last dim (a +//! head-major backing is a permuted view). Every entry is written. +void minimaxM3SelectPrefillTile(torch::Tensor const& scores, torch::Tensor const& nValidBlocks, torch::Tensor& out, + int64_t initBlocks, int64_t localBlocks) +{ + TORCH_CHECK(scores.is_cuda() && scores.scalar_type() == torch::kFloat32 && scores.dim() == 3, + "minimax_m3_select_prefill_tile: scores must be a 3-D float32 CUDA tensor [num_kv_heads, num_blocks, total_q]"); + TORCH_CHECK(scores.stride(2) == 1, "minimax_m3_select_prefill_tile: scores must have unit query stride"); + TORCH_CHECK(nValidBlocks.is_cuda() && nValidBlocks.scalar_type() == torch::kInt32 && nValidBlocks.is_contiguous() + && nValidBlocks.numel() >= scores.size(2), + "minimax_m3_select_prefill_tile: n_valid_blocks must be contiguous int32 CUDA with at least total_q elements"); + int64_t const numKvHeads = scores.size(0); + int64_t const numBlocks = scores.size(1); + int64_t const totalQ = scores.size(2); + TORCH_CHECK(numBlocks <= tensorrt_llm::kernels::kMinimaxM3SelectPrefillTileMaxBlocks, + "minimax_m3_select_prefill_tile supports at most ", tensorrt_llm::kernels::kMinimaxM3SelectPrefillTileMaxBlocks, + " blocks, got ", numBlocks); + TORCH_CHECK(out.is_cuda() && out.scalar_type() == torch::kInt32 && out.dim() == 3 && out.size(0) == totalQ + && out.size(1) == numKvHeads && out.size(2) == 16 && out.stride(2) == 1, + "minimax_m3_select_prefill_tile: out must be int32 [total_q, num_kv_heads, 16] with unit last-dim stride"); + + c10::cuda::CUDAGuard const deviceGuard{scores.device()}; + auto const stream = at::cuda::getCurrentCUDAStream(scores.get_device()); + cudaError_t const err = tensorrt_llm::kernels::invokeMinimaxM3SelectPrefillTile(scores.data_ptr(), + scores.stride(0), scores.stride(1), nValidBlocks.data_ptr(), out.data_ptr(), out.stride(0), + out.stride(1), static_cast(numKvHeads), static_cast(numBlocks), static_cast(totalQ), + static_cast(initBlocks), static_cast(localBlocks), stream); + if (err != cudaSuccess) + { + cudaGetLastError(); + TORCH_CHECK(false, "minimax_m3_select_prefill_tile launch failed: ", cudaGetErrorString(err)); + } +} + +} // namespace torch_ext + +TRTLLM_NAMESPACE_END + +TORCH_LIBRARY_FRAGMENT(trtllm, m) +{ + m.def( + "minimax_m3_select_prefill_tile(Tensor scores, Tensor n_valid_blocks, Tensor(a!) out, int init_blocks, " + "int local_blocks) -> ()"); +} + +TORCH_LIBRARY_IMPL(trtllm, CUDA, m) +{ + m.impl("minimax_m3_select_prefill_tile", &tensorrt_llm::torch_ext::minimaxM3SelectPrefillTile); +} diff --git a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp new file mode 100644 index 000000000000..d534ab7e977f --- /dev/null +++ b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp @@ -0,0 +1,101 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tensorrt_llm/kernels/minimaxM3Sm107Tp2/ctxResidualRmsNormMxfp8.h" + +#include +#include +#include + +#include +#include +#include +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace torch_ext +{ + +//! Residual add + RMSNorm of an all-reduce output (in place: inter becomes inter + residual), with the MXFP8 +//! quantization of the normalized rows in the same pass. Returns (norm_out, mxfp8, sf, fp4, fp4_sf) where mxfp8 / sf +//! match mxfp8_quantize(norm_out, swizzled=True) bit for bit (mxfp8 [rows, hidden] Float8_e4m3fn, a 1-D UINT8 scale +//! tensor of the swizzled 128x4 layout). With fp4GlobalScale, fp4 / fp4_sf match +//! fp4_quantize(norm_out, fp4GlobalScale, 16, sf_use_ue8m0=False, is_sf_swizzled=False) bit for bit (fp4 [rows, +//! hidden / 2] UINT8, a 1-D UINT8 linear scale tensor of rows * hidden / 16); otherwise both are empty. norm_out is +//! empty when writeNorm is false. +std::tuple minimaxM3CtxResidualRmsNormMxfp8( + torch::Tensor& inter, torch::Tensor const& residual, torch::Tensor const& weight, double eps, bool writeNorm, + std::optional const& fp4GlobalScale) +{ + TORCH_CHECK(inter.is_cuda() && inter.is_contiguous() && inter.scalar_type() == at::kBFloat16 && inter.dim() >= 2); + TORCH_CHECK( + residual.is_contiguous() && residual.scalar_type() == at::kBFloat16 && residual.sizes() == inter.sizes()); + int64_t const hidden = inter.size(-1); + int64_t const rows = inter.numel() / hidden; + TORCH_CHECK(weight.is_contiguous() && weight.scalar_type() == at::kBFloat16 && weight.numel() == hidden); + TORCH_CHECK(hidden % 256 == 0 && hidden / 8 <= 1024, "hidden must be a multiple of 256 and at most 8192"); + at::cuda::CUDAGuard const guard(inter.device()); + auto const opts = inter.options(); + torch::Tensor normOut = writeNorm ? torch::empty_like(inter) : torch::empty({0}, opts); + torch::Tensor qOut = torch::empty(inter.sizes(), opts.dtype(at::ScalarType::Float8_e4m3fn)); + int64_t const sfSize = (rows + 127) / 128 * 128 * ((hidden / 32 + 3) / 4 * 4); + torch::Tensor sfOut = torch::empty({sfSize}, opts.dtype(at::ScalarType::Byte)); + bool const fp4 = fp4GlobalScale.has_value(); + if (fp4) + { + TORCH_CHECK( + fp4GlobalScale->is_cuda() && fp4GlobalScale->scalar_type() == at::kFloat && fp4GlobalScale->numel() == 1); + } + std::vector fp4Shape(inter.sizes().begin(), inter.sizes().end()); + fp4Shape.back() = hidden / 2; + torch::Tensor fp4Out = fp4 ? torch::empty(fp4Shape, opts.dtype(at::ScalarType::Byte)) : torch::empty({0}, opts); + torch::Tensor fp4SfOut + = fp4 ? torch::empty({rows * (hidden / 16)}, opts.dtype(at::ScalarType::Byte)) : torch::empty({0}, opts); + // Read once per process, so eager and captured launches agree; unset or anything but "1" keeps PDL off. + static bool const enablePdl = []() + { + char const* pdl = std::getenv("TRTLLM_ENABLE_PDL"); + return pdl != nullptr && pdl[0] == '1'; + }(); + tensorrt_llm::kernels::minimaxM3Sm107Tp2::invokeCtxResidualRmsNormMxfp8( + reinterpret_cast<__nv_bfloat16*>(inter.data_ptr()), reinterpret_cast<__nv_bfloat16 const*>(residual.data_ptr()), + reinterpret_cast<__nv_bfloat16 const*>(weight.data_ptr()), + writeNorm ? reinterpret_cast<__nv_bfloat16*>(normOut.data_ptr()) : nullptr, + reinterpret_cast(qOut.data_ptr()), reinterpret_cast(sfOut.data_ptr()), + fp4 ? reinterpret_cast(fp4Out.data_ptr()) : nullptr, + fp4 ? reinterpret_cast(fp4SfOut.data_ptr()) : nullptr, + fp4 ? fp4GlobalScale->data_ptr() : nullptr, static_cast(rows), static_cast(hidden), + static_cast(eps), enablePdl, at::cuda::getCurrentCUDAStream(inter.get_device())); + return {normOut, qOut, sfOut, fp4Out, fp4SfOut}; +} + +} // namespace torch_ext + +TRTLLM_NAMESPACE_END + +TORCH_LIBRARY_FRAGMENT(trtllm, m) +{ + m.def( + "minimax_m3_ctx_residual_rmsnorm_mxfp8(Tensor(a!) inter, Tensor residual, Tensor weight, float eps, " + "bool write_norm, Tensor? fp4_global_scale=None) -> (Tensor, Tensor, Tensor, Tensor, Tensor)"); +} + +TORCH_LIBRARY_IMPL(trtllm, CUDA, m) +{ + m.impl("minimax_m3_ctx_residual_rmsnorm_mxfp8", &tensorrt_llm::torch_ext::minimaxM3CtxResidualRmsNormMxfp8); +} diff --git a/cpp/tensorrt_llm/thop/mxfp8Gemm.cpp b/cpp/tensorrt_llm/thop/mxfp8Gemm.cpp index 576f88a1f833..a481f8d0120c 100644 --- a/cpp/tensorrt_llm/thop/mxfp8Gemm.cpp +++ b/cpp/tensorrt_llm/thop/mxfp8Gemm.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include #include @@ -59,10 +60,41 @@ int getMxfp8SmVersion() return smVersion; } +// SM107 only: context chunks of a cached-prefix turn have M below kMxfp8LargeMMin. Exact-M cache keys +// leave those M values untuned, and the default config runs at about half the speed of the best tactic +// on SM107. These buckets give them tuned tactics. Every compiled tactic gives bitwise-identical +// results, so bucketing changes speed only. Set to false to keep exact-M keys on SM107 as well. +constexpr bool kMxfp8Sm107SmallMBuckets = true; +constexpr int64_t kMxfp8Sm107SmallMBucketList[] = {8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, kMxfp8LargeMMin - 1}; + +bool useMxfp8SmallMBuckets() +{ + return kMxfp8Sm107SmallMBuckets && getMxfp8SmVersion() == 107; +} + +std::vector getMxfp8SmallMBuckets() +{ + if (!useMxfp8SmallMBuckets()) + { + return {}; + } + return {std::begin(kMxfp8Sm107SmallMBucketList), std::end(kMxfp8Sm107SmallMBucketList)}; +} + int64_t getMxfp8TuningBucket(int64_t const m) { if (m < kMxfp8LargeMMin) { + if (useMxfp8SmallMBuckets()) + { + for (int64_t const bucket : kMxfp8Sm107SmallMBucketList) + { + if (m <= bucket) + { + return bucket; + } + } + } return m; } if (m <= kMxfp8M8kBucket) @@ -286,6 +318,12 @@ class MXFP8GemmRunner : public torch::CustomClassHolder return entry.has_value() ? entry->tactic : kMxfp8TacticCacheMiss; } + //! Returns the small-M tuning buckets of this GPU, empty unless SM107 small-M bucketing is enabled. + std::vector getSmallMTuningBuckets() const + { + return getMxfp8SmallMBuckets(); + } + //! Removes every registered MXFP8 serving tactic. void clearTacticCache() const { @@ -322,6 +360,7 @@ TORCH_LIBRARY_FRAGMENT(trtllm, m) .def("get_num_configs", &tensorrt_llm::torch_ext::MXFP8GemmRunner::getNumConfigs) .def("register_tactic", &tensorrt_llm::torch_ext::MXFP8GemmRunner::registerTactic) .def("get_cached_tactic", &tensorrt_llm::torch_ext::MXFP8GemmRunner::getCachedTactic) + .def("get_small_m_tuning_buckets", &tensorrt_llm::torch_ext::MXFP8GemmRunner::getSmallMTuningBuckets) .def("clear_tactic_cache", &tensorrt_llm::torch_ext::MXFP8GemmRunner::clearTacticCache); m.def( diff --git a/examples/minimax_m3/rubin/README.md b/examples/minimax_m3/rubin/README.md new file mode 100644 index 000000000000..9c5d3425e812 --- /dev/null +++ b/examples/minimax_m3/rubin/README.md @@ -0,0 +1,70 @@ + + +# MiniMax-M3 on Rubin (SM107): disaggregated serving + +| File | Role | +|---|---| +| `ctx_agentx_c24.yaml` | Context worker for multi-turn agentic traffic (AgentX, 24 concurrent conversations). | +| `fp4_moe_tactics_tp2ctx_v1.json` | FP4 MoE tactic table for the TP2/EP2 context worker (`TLLM_FP4_MOE_TACTIC_TABLE`). | +| `setup_fa4.sh` (applies `3rdparty/patches/fa4_fp8_rescale0.patch`) | FA4 for the FP8 dense-layer prefill; prepend its directory to `PYTHONPATH` in every context worker. | + +## FP8 dense prefill on FA4 + +On SM107 the dense layers' FP8 prefill runs FA4 (`flash_attn.cute`, from +flash-attn-4 4.0.0b19) when the installed FA4 carries `3rdparty/patches/fa4_fp8_rescale0.patch`. +That one-line change makes the FP8 forward rescale the row maximum on every increase, +so the softmax numerators stay within E4M3 range. `bash setup_fa4.sh ` makes a +patched copy of the installed package (site-packages is left unchanged); prepend +`` to `PYTHONPATH`. Without the change the dense layers keep fmha_sm100 and +log `FA4 lacks the FP8 rescale_threshold 0.0 change`. Set +`TRTLLM_MSA_DISABLE_DENSE_FA4=1` to keep fmha_sm100 deliberately. + +## Agentic multi-turn traffic + +Each turn of an agentic conversation resends the previous turn's prompt plus a +short suffix, so time to first token and context-worker throughput depend on how +much of that prefix is still cached. Measured with AgentX at 24 concurrent +conversations on 1 x TP2 context + 4 x TP2 generation workers, this setup reached +a 97.4% prefix hit rate on the context worker. + +Context worker: `ctx_agentx_c24.yaml`. + +- **One KV pool.** TP2 attention instead of attention DP keeps every conversation + in a single pool, so a conversation's prefix is never on the other rank. +- **Capacity.** `free_gpu_memory_fraction: 0.95` and a 100 GiB per-rank host tier + (`host_cache_size`, KV cache manager V2). GPU-evicted blocks move to host memory + and are copied back on the next turn instead of being recomputed. Size the host + tier from the node's free host memory, and keep at least 25% of it free. +- **`block_reuse_config.policy: per_conversation`.** Reuse is tracked per + conversation id. +- **`enable_tokenization_cache: true`.** Repeated prompt prefixes are not + re-tokenized. +- **`max_num_tokens: 16384`.** This is the prefill chunk. +- **`enable_iter_perf_stats: true`.** The per-iteration KV statistics then include + host-tier traffic. +- **Append reserve.** Set `TLLM_CTX_APPEND_RESERVE=8064`. Each iteration then chunks + the first context request against `max_num_tokens - 8064`, so short follow-up + turns run in the same iteration as a long cold prefill instead of waiting for it. + The leftover budget goes to the shortest uncached request first + (`TLLM_CTX_APPEND_RESERVE_SJF=0` keeps arrival order). The reserve is held back + only while another context request is waiting. It applies only when + `max_num_tokens > 2 * R`. +- **Deterministic MoE tactics.** Set `TLLM_FP4_MOE_TACTIC_TABLE` to + `fp4_moe_tactics_tp2ctx_v1.json`. The FP4 MoE runner then uses the tabled tactic + for each token bucket instead of a per-start autotuned one, so two server starts + produce identical prefill output. Each entry is the tactic autotuning chose most + often, so speed is unchanged. The table only applies to MoE shape `4,3072,64,0` + (TP2/EP2). + +Generation workers (TP2 MiniMax-M3 decode workers) need: + +- `tensor_parallel_size: 2`. +- `enable_block_reuse: true`, `use_kv_cache_manager_v2: true` and + `block_reuse_config.policy: per_conversation`, so a conversation's next turn + only transfers the new suffix from the context worker. + +Disaggregated router: `type: conversation`. Each conversation stays on the same +generation worker, so that worker's cached prefix is reused. diff --git a/examples/minimax_m3/rubin/agg/README.md b/examples/minimax_m3/rubin/agg/README.md new file mode 100644 index 000000000000..554d308ddc85 --- /dev/null +++ b/examples/minimax_m3/rubin/agg/README.md @@ -0,0 +1,49 @@ + + +# MiniMax-M3 on Rubin (SM107): aggregated TP2 serving + +One TP2 engine per pair of GPUs serves both prefill and decode, for multi-turn +agentic traffic (AgentX). Pick the configuration by concurrency: + +| File | Concurrent conversations | Requests per engine | +|---|---|---| +| `agg_c14.yaml` | 14 | 2 | +| `agg_c20.yaml` | 20 | 3 | +| `agg_c46.yaml` | 46 | 14 | +| `agg_c56.yaml` | 56 | 24 | + +Source `agg_env.sh` in every worker, set `speculative_model` to the +MiniMax-M3 Eagle3 drafter checkpoint, and prepend the `setup_fa4.sh` directory +(`../README.md`) to `PYTHONPATH`. + +## Decode target + +`modeling_v2: require` builds the MiniMax-M3 sm_107 TP2 modeling_v2 target +(`minimax_m3_nvfp4__sm_107__tp2`) for every configuration: it runs decode steps +of 1 to 192 verify rows (up to 48 requests with three drafts), and its prefill +steps of at least 4096 context rows take the built-in model's context path. + +## Scheduling and memory + +- **Batch wait.** `batch_wait_timeout_iters` holds a new context request for up + to N iterations so it joins a fuller step: 32 at 46 conversations, 8 at 56. +- **CUDA graphs.** `agg_c56.yaml` captures every batch size 1..24, so a step is + never padded to the next captured size. +- **KV capacity.** `free_gpu_memory_fraction: 0.97` and an explicit per-rank + host tier (`host_cache_size`, KV cache manager V2): 295 GiB at 14 / 20 + conversations, 355 GiB at 46 / 56. Size it from the node's free host memory + (at most a quarter per GPU), and keep the host tier on the GPU's local NUMA + node: pages that spill to the remote node stall the copy-back. +- **Prefill.** Breakable prefill CUDA graphs captured up to 4096 tokens, and + 16k-token chunks. + +## Launch layout at 56 conversations + +Put the two ranks of an engine on different CPU sockets (for example GPUs 0 +and 2 on a four-GPU node), bind each rank's memory to its GPU's NUMA node with +`numactl -m `, and set `TLLM_NUMA_AWARE_WORKER_AFFINITY=1` so each rank's +worker threads run on its GPU's local CPUs. Do not use `numactl --cpunodebind`: +TensorRT-LLM resets the CPU affinity unless `TLLM_NUMA_AWARE_WORKER_AFFINITY=1`. diff --git a/examples/minimax_m3/rubin/agg/agg_c14.yaml b/examples/minimax_m3/rubin/agg/agg_c14.yaml new file mode 100644 index 000000000000..3005b16ca74c --- /dev/null +++ b/examples/minimax_m3/rubin/agg/agg_c14.yaml @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# MiniMax-M3 aggregated TP2 serving on Rubin (SM107), 14 concurrent agentic +# conversations: at most 2 requests per engine (the tp2 target). Use with +# agg_env.sh (README.md). +tensor_parallel_size: 2 +pipeline_parallel_size: 1 +moe_expert_parallel_size: 1 +enable_attention_dp: false +max_batch_size: 2 +max_num_tokens: 16384 +max_seq_len: 1048576 +enable_chunked_prefill: true +disable_overlap_scheduler: false +cuda_graph_config: + batch_sizes: [1, 2] + enable_padding: true +kv_cache_config: + dtype: nvfp4 + tokens_per_block: 128 + use_kv_cache_manager_v2: true + enable_block_reuse: true + block_reuse_config: {policy: per_conversation} + host_cache_size: 316753838080 + disk_cache_size: 0 + free_gpu_memory_fraction: 0.9 + avg_seq_len: 220000 +moe_config: {backend: TRTLLM, use_low_precision_moe_combine: true} +allreduce_strategy: AUTO +scheduler_config: {capacity_scheduler_policy: MAX_UTILIZATION} +sparse_attention_config: {algorithm: minimax_m3, implementation: msa, indexer_kv_dtype: fp8, sparse_disable_index_value: true, + fuse_qkv_index_projection: true} +speculative_config: {speculative_model: /path/to/minimax-m3-eagle3, decoding_type: Eagle3, max_draft_len: 3, + advanced_sampling_mode: no_topk} +stream_interval: 20 +reasoning_parser: minimax_m3 +trust_remote_code: true +num_postprocess_workers: 4 +enable_autotuner: true +enable_tokenization_cache: true +print_iter_log: true +enable_iter_perf_stats: true +return_perf_metrics: false +prefill_cuda_graph_backend: breakable +prefill_capture_num_tokens: [32, 64, 128, 256, 512, 768, 1024, 1536, 2048, 3072, 4096] +modeling_v2: require diff --git a/examples/minimax_m3/rubin/agg/agg_c20.yaml b/examples/minimax_m3/rubin/agg/agg_c20.yaml new file mode 100644 index 000000000000..a2b99ecaeb0e --- /dev/null +++ b/examples/minimax_m3/rubin/agg/agg_c20.yaml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# MiniMax-M3 aggregated TP2 serving on Rubin (SM107), 20 concurrent agentic +# conversations: at most 3 requests per engine. Use with agg_env.sh (README.md). +tensor_parallel_size: 2 +pipeline_parallel_size: 1 +moe_expert_parallel_size: 1 +enable_attention_dp: false +max_batch_size: 3 +max_num_tokens: 16384 +max_seq_len: 1048576 +enable_chunked_prefill: true +disable_overlap_scheduler: false +cuda_graph_config: + batch_sizes: [1, 2, 3] + enable_padding: true +kv_cache_config: + dtype: nvfp4 + tokens_per_block: 128 + use_kv_cache_manager_v2: true + enable_block_reuse: true + block_reuse_config: {policy: per_conversation} + host_cache_size: 316753838080 + disk_cache_size: 0 + free_gpu_memory_fraction: 0.9 + avg_seq_len: 220000 +moe_config: {backend: TRTLLM, use_low_precision_moe_combine: true} +allreduce_strategy: AUTO +scheduler_config: {capacity_scheduler_policy: MAX_UTILIZATION} +sparse_attention_config: {algorithm: minimax_m3, implementation: msa, indexer_kv_dtype: fp8, sparse_disable_index_value: true, + fuse_qkv_index_projection: true} +speculative_config: {speculative_model: /path/to/minimax-m3-eagle3, decoding_type: Eagle3, max_draft_len: 3, + advanced_sampling_mode: no_topk} +stream_interval: 20 +reasoning_parser: minimax_m3 +trust_remote_code: true +num_postprocess_workers: 4 +enable_autotuner: true +enable_tokenization_cache: true +print_iter_log: true +enable_iter_perf_stats: true +return_perf_metrics: false +prefill_cuda_graph_backend: breakable +prefill_capture_num_tokens: [32, 64, 128, 256, 512, 768, 1024, 1536, 2048, 3072, 4096] +modeling_v2: require diff --git a/examples/minimax_m3/rubin/agg/agg_c46.yaml b/examples/minimax_m3/rubin/agg/agg_c46.yaml new file mode 100644 index 000000000000..b7b320978b5b --- /dev/null +++ b/examples/minimax_m3/rubin/agg/agg_c46.yaml @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# MiniMax-M3 aggregated TP2 serving on Rubin (SM107), 46 concurrent agentic +# conversations: at most 14 requests per engine, a +# 32-iteration batch wait and a 355 GiB per-rank host KV tier. Use with +# agg_env.sh (README.md). +tensor_parallel_size: 2 +pipeline_parallel_size: 1 +moe_expert_parallel_size: 1 +enable_attention_dp: false +max_batch_size: 14 +max_num_tokens: 16384 +max_seq_len: 1048576 +enable_chunked_prefill: true +disable_overlap_scheduler: false +cuda_graph_config: + batch_sizes: [1, 2, 3, 4, 6, 8, 12, 14] + enable_padding: true +kv_cache_config: + dtype: nvfp4 + tokens_per_block: 128 + use_kv_cache_manager_v2: true + enable_block_reuse: true + block_reuse_config: {policy: per_conversation} + host_cache_size: 381178347520 + disk_cache_size: 0 + free_gpu_memory_fraction: 0.97 + avg_seq_len: 220000 +moe_config: {backend: TRTLLM, use_low_precision_moe_combine: true} +allreduce_strategy: AUTO +scheduler_config: {capacity_scheduler_policy: MAX_UTILIZATION} +sparse_attention_config: {algorithm: minimax_m3, implementation: msa, indexer_kv_dtype: fp8, sparse_disable_index_value: true, + fuse_qkv_index_projection: true} +speculative_config: {speculative_model: /path/to/minimax-m3-eagle3, decoding_type: Eagle3, max_draft_len: 3, + advanced_sampling_mode: no_topk} +stream_interval: 20 +reasoning_parser: minimax_m3 +trust_remote_code: true +num_postprocess_workers: 4 +enable_autotuner: true +enable_tokenization_cache: true +print_iter_log: true +enable_iter_perf_stats: true +return_perf_metrics: false +prefill_cuda_graph_backend: breakable +prefill_capture_num_tokens: [32, 64, 128, 256, 512, 768, 1024, 1536, 2048, 3072, 4096] +modeling_v2: require +batch_wait_timeout_iters: 32 +batch_wait_max_tokens_ratio: 1.0 diff --git a/examples/minimax_m3/rubin/agg/agg_c56.yaml b/examples/minimax_m3/rubin/agg/agg_c56.yaml new file mode 100644 index 000000000000..479e0eb75ed4 --- /dev/null +++ b/examples/minimax_m3/rubin/agg/agg_c56.yaml @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# MiniMax-M3 aggregated TP2 serving on Rubin (SM107), 56 concurrent agentic +# conversations: at most 24 requests per engine, an +# 8-iteration batch wait, CUDA graphs for every batch size 1..24 and a 355 GiB +# per-rank host KV tier. Launch it on one GPU per CPU socket (README.md). +tensor_parallel_size: 2 +pipeline_parallel_size: 1 +moe_expert_parallel_size: 1 +enable_attention_dp: false +max_batch_size: 24 +max_num_tokens: 16384 +max_seq_len: 1048576 +enable_chunked_prefill: true +disable_overlap_scheduler: false +cuda_graph_config: + batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] + enable_padding: true +kv_cache_config: + dtype: nvfp4 + tokens_per_block: 128 + use_kv_cache_manager_v2: true + enable_block_reuse: true + block_reuse_config: {policy: per_conversation} + host_cache_size: 381178347520 + disk_cache_size: 0 + free_gpu_memory_fraction: 0.97 + avg_seq_len: 220000 +moe_config: {backend: TRTLLM, use_low_precision_moe_combine: true} +allreduce_strategy: AUTO +scheduler_config: {capacity_scheduler_policy: MAX_UTILIZATION} +sparse_attention_config: {algorithm: minimax_m3, implementation: msa, indexer_kv_dtype: fp8, sparse_disable_index_value: true, + fuse_qkv_index_projection: true} +speculative_config: {speculative_model: /path/to/minimax-m3-eagle3, decoding_type: Eagle3, max_draft_len: 3, + advanced_sampling_mode: no_topk} +stream_interval: 20 +reasoning_parser: minimax_m3 +trust_remote_code: true +num_postprocess_workers: 4 +enable_autotuner: true +enable_tokenization_cache: true +print_iter_log: true +enable_iter_perf_stats: true +return_perf_metrics: false +prefill_cuda_graph_backend: breakable +prefill_capture_num_tokens: [32, 64, 128, 256, 512, 768, 1024, 1536, 2048, 3072, 4096] +modeling_v2: require +batch_wait_timeout_iters: 8 +batch_wait_max_tokens_ratio: 1.0 diff --git a/examples/minimax_m3/rubin/agg/agg_env.sh b/examples/minimax_m3/rubin/agg/agg_env.sh new file mode 100644 index 000000000000..eaae281bd797 --- /dev/null +++ b/examples/minimax_m3/rubin/agg/agg_env.sh @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Environment for MiniMax-M3 aggregated TP2 serving on Rubin (SM107), shared by +# agg_c14.yaml / agg_c20.yaml / agg_c46.yaml / agg_c56.yaml. Source it in every +# worker: `source agg_env.sh` (README.md). + +# Prefix token cache for multi-turn traffic: each turn resends the previous turn's prompt. +export TLLM_PREFIX_TOKEN_CACHE_ENTRIES=2048 +export TLLM_PREFIX_TOKEN_CACHE_MAX_CHARS=1073741824 + +# Context-path items that the aggregated deployment keeps off: the dense-MLP SwiGLU + MXFP8 producer, the CLC GEMM, +# the shared-expert fold into the MoE finalize, the drafter's last-row context attention and the fused embedding +# gather. +export TRTLLM_CTX_SWIGLU_MXFP8=0 +export TRTLLM_CTX_CLC_GEMM=0 +export TLLM_M3_MOE_FOLD_SHARED=0 +export TRTLLM_CTX_DRAFTER_LAST_ROW=0 +export TRTLLM_CTX_DRAFTER_LAST_ROW_DECODE=0 +export TRTLLM_CTX_EMBEDDING_GATHER=0 +# Legacy-model items the aggregated deployment keeps off: the drafter's dead-row skip and the generation router_tc. +export TRTLLM_CTX_DRAFTER_DEAD_ROWS=0 +export TRTLLM_M3_ROUTER_TC_GEN=0 + +# NCCL all-reduce with 64 CTAs. +export NCCL_MIN_CTAS=64 +export NCCL_MAX_CTAS=64 + +# The all-reduce autotuner leaves NCCL_SYMMETRIC out, so no symmetric window is pre-allocated (more KV cache). +export TRTLLM_AR_TUNE_NCCL_SYMMETRIC=0 diff --git a/examples/minimax_m3/rubin/ctx_agentx_c24.yaml b/examples/minimax_m3/rubin/ctx_agentx_c24.yaml new file mode 100644 index 000000000000..0c8af573e1b1 --- /dev/null +++ b/examples/minimax_m3/rubin/ctx_agentx_c24.yaml @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# MiniMax-M3 context worker on Rubin (SM107) for multi-turn agentic traffic +# (AgentX, 24 concurrent conversations), where most of each prompt is the +# previous turn's prefix. It keeps that prefix resident: +# - TP2 attention (no attention DP), so one KV pool holds every conversation; +# - 95% of free GPU memory for KV, and a 100 GiB per-rank host tier that +# evicted blocks move to instead of being dropped (KV cache manager V2); +# - per_conversation block reuse, paired with the conversation router and +# generation workers' reuse settings (see README.md); +# - 16k-token prefill chunks and the tokenization cache. +# Export TLLM_FP4_MOE_TACTIC_TABLE=/fp4_moe_tactics_tp2ctx_v1.json in +# this worker to pin the FP4 MoE tactics (output independent of per-start +# autotuning), and prepend the setup_fa4.sh directory to PYTHONPATH (README.md). +tensor_parallel_size: 2 +moe_expert_parallel_size: 2 +enable_attention_dp: false +trust_remote_code: true +max_seq_len: 1048576 +max_batch_size: 32 +max_num_tokens: 16384 +enable_chunked_prefill: true +disable_overlap_scheduler: true +cuda_graph_config: null +enable_tokenization_cache: true +enable_iter_perf_stats: true +scheduler_config: + capacity_scheduler_policy: GUARANTEED_NO_EVICT +kv_cache_config: + dtype: nvfp4 + tokens_per_block: 128 + use_kv_cache_manager_v2: true + enable_block_reuse: true + block_reuse_config: + policy: per_conversation + free_gpu_memory_fraction: 0.95 + host_cache_size: 107374182400 +cache_transceiver_config: + backend: NIXL +moe_config: + backend: TRTLLM +sparse_attention_config: + algorithm: minimax_m3 + implementation: msa + indexer_kv_dtype: fp8 + fuse_qkv_index_projection: true +speculative_config: + decoding_type: Eagle3 + max_draft_len: 3 + speculative_model: /path/to/minimax-m3-eagle3 diff --git a/examples/minimax_m3/rubin/fp4_moe_tactics_tp2ctx_v1.json b/examples/minimax_m3/rubin/fp4_moe_tactics_tp2ctx_v1.json new file mode 100644 index 000000000000..11e945b8a4ee --- /dev/null +++ b/examples/minimax_m3/rubin/fp4_moe_tactics_tp2ctx_v1.json @@ -0,0 +1,64 @@ +{ + "4,3072,64,0": { + "1": [ + 8, + 346 + ], + "1024": [ + 128, + 22 + ], + "128": [ + 16, + 206 + ], + "16": [ + 8, + 147 + ], + "16384": [ + 256, + 7 + ], + "2": [ + 8, + 346 + ], + "2048": [ + 128, + 23 + ], + "256": [ + 16, + 192 + ], + "32": [ + 8, + 108 + ], + "4": [ + 8, + 317 + ], + "4096": [ + 128, + 22 + ], + "512": [ + 128, + 22 + ], + "64": [ + 16, + 232 + ], + "8": [ + 8, + 147 + ], + "8192": [ + 256, + 7 + ] + } +} diff --git a/examples/minimax_m3/rubin/setup_fa4.sh b/examples/minimax_m3/rubin/setup_fa4.sh new file mode 100755 index 000000000000..8282f015eb97 --- /dev/null +++ b/examples/minimax_m3/rubin/setup_fa4.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Prepare the FA4 (flash_attn.cute) copy that MiniMax-M3's FP8 dense prefill uses on SM107. +# +# Usage: bash setup_fa4.sh /absolute/path/to/new/fa4-dir +# +# Copies the installed flash_attn package (flash-attn-4 4.0.0b19) into a new directory and applies +# 3rdparty/patches/fa4_fp8_rescale0.patch: for FP8 queries the forward rescales the row max on every increase +# (rescale_threshold 0.0 instead of 4.0), so P stays within E4M3 range. Prepend the directory to +# PYTHONPATH in every worker. Without the change the dense prefill keeps fmha_sm100 and logs +# "FA4 lacks the FP8 rescale_threshold 0.0 change". +set -euo pipefail + +readonly BASE_SHA256="7d5f2baf8b9c9e28aade1591f6fd9353e16956a7b9b12e8bd00577fdab7f61e3" +readonly PATCHED_SHA256="418c2d40442b7e336b5877bb19d55205b7582e548c8536b2a64e82430156f190" +readonly PATCH_SHA256="66988cec21ec806ec04f6d6a8105ba71d3dd8b77d87376aa7a0a5616321c5d8d" + +fa4_destination="${1:?Supply a new directory for the patched FA4 copy}" +script_directory="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" + +if [[ -e "${fa4_destination}" ]]; then + echo "Destination already exists: ${fa4_destination}" >&2 + exit 1 +fi +package_directory="$(python3 -c 'import os, flash_attn; print(os.path.dirname(flash_attn.__file__))')" +target="flash_attn/cute/flash_fwd_sm100.py" +actual_sha256="$(sha256sum "${package_directory}/cute/flash_fwd_sm100.py" | cut -d ' ' -f 1)" +if [[ "${actual_sha256}" != "${BASE_SHA256}" ]]; then + echo "Unexpected ${target} SHA256 ${actual_sha256}; expected ${BASE_SHA256} (flash-attn-4 4.0.0b19)" >&2 + exit 1 +fi + +patch_file="${script_directory}/../../../3rdparty/patches/fa4_fp8_rescale0.patch" +actual_sha256="$(sha256sum "${patch_file}" | cut -d ' ' -f 1)" +if [[ "${actual_sha256}" != "${PATCH_SHA256}" ]]; then + echo "Unexpected patch SHA256 ${actual_sha256}; expected ${PATCH_SHA256}" >&2 + exit 1 +fi + +mkdir -p "${fa4_destination}" +cp -R "${package_directory}" "${fa4_destination}/flash_attn" +find "${fa4_destination}/flash_attn" -name __pycache__ -prune -exec rm -rf {} + +patch -d "${fa4_destination}" -p1 --forward --quiet < "${patch_file}" +actual_sha256="$(sha256sum "${fa4_destination}/${target}" | cut -d ' ' -f 1)" +if [[ "${actual_sha256}" != "${PATCHED_SHA256}" ]]; then + echo "Unexpected patched SHA256 ${actual_sha256}; expected ${PATCHED_SHA256}" >&2 + exit 1 +fi +echo "FA4 is ready; prepend ${fa4_destination} to PYTHONPATH in every worker." diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py index 15926f7e5259..df3034830b78 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py @@ -1662,6 +1662,18 @@ def _router_logits(core, i: int, h: torch.Tensor) -> torch.Tensor: return m3_fp32_linear(h, core.w[f"l{i}_router"]) +def _context_router_logits(core, i: int, h: torch.Tensor) -> torch.Tensor: + """The router logits of a step with context rows past ``ROUTER_TC_GEN``'s rows: the built-in gate's context-step + arithmetic, the fixed-tile TF32 router (``torch.ops.trtllm.router_gemm_tf32`` over the TF32-rounded weight, its + row-count-independent tile and K order; TRTLLM_CTX_ROUTER_TF32_FIXED=0 is the kill), else the fp32 router.""" + w_tf32 = core.router_w_tf32.get(i) + if w_tf32 is not None and h.dtype == torch.bfloat16 and h.dim() == 2 and h.is_contiguous(): + taken("router_gemm_tf32", h.shape[0], "fixed-tile TF32 context router") + _record("router_gemm_tf32", h.shape[0]) + return torch.ops.trtllm.router_gemm_tf32(h, w_tf32) + return _router_logits(core, i, h) + + def _decode_router_logits(core, i: int, h: torch.Tensor) -> torch.Tensor: """The router logits of a pure generation step on the generic layer: ``ROUTER_TC_GEN``'s rows take the TF32 tensor-core router when the device co-schedules 16-CTA clusters (decided at prebuild); every other step the fp32 @@ -1794,6 +1806,220 @@ def _split_chunk(rows: int, num_chunks: int) -> List[int]: return _modeling_support._split_chunk(_SUPPORT_TARGET, rows, num_chunks) +# -------------------------------------------------------------------------------------------------------------------- +# The built-in MiniMax-M3 CTX stack on prefill-sized steps with context rows +# -------------------------------------------------------------------------------------------------------------------- + +# A step with context rows of at least CTX_STACK_MIN_ROWS rows (the layer input's rows: context chunks + generation +# rows) runs the CTX path of the built-in MiniMax-M3 model (modeling_minimaxm3) in the same order, each item behind its +# own kill switch and row gate there: +# * sparse layers: the fused QKV-index MXFP8 GEMM with the NVFP4 producer in its epilogue (TRTLLM_CTX_QKV_FUSED), then +# the attention core with the combine writing the o_proj input as MXFP8 (TRTLLM_CTX_P5A_COMBINE_MXFP8); +# * every boundary of at least the CTX norm's rows: the all-reduce, then residual + RMSNorm emitting the next linear's +# MXFP8 input and, before the MoE, the routed experts' NVFP4 input (TRTLLM_CTX_NORM_MXFP8 / TRTLLM_CTX_NORM_FP4); +# * the MoE at those rows: the fixed-tile TF32 router, the runner's own finalize, then the shared + routed add. +# Below CTX_STACK_MIN_ROWS the step keeps this target's generic path. Kill constant: False runs every step there. +# Only eager steps: a breakable prefill graph's captured buckets run the generic path, as the stack never runs inside a +# capture. The CTX norm (and the MoE hand-off it feeds) starts at CTX_NORM_MIN_ROWS rows, the built-in +# ``_CTX_NORM_MXFP8_MIN_ROWS``. +CTX_STACK = True +CTX_STACK_MIN_ROWS = 4096 +CTX_NORM_MIN_ROWS = 8192 +CTX_STACK_PATH = "m3_ctx_stack" + + +def _ctx_stack_step(step: dict, rows: int) -> bool: + """Whether this step takes the built-in CTX stack: an eager step with context rows and at least + ``CTX_STACK_MIN_ROWS`` rows.""" + return ( + CTX_STACK + and rows >= CTX_STACK_MIN_ROWS + and int(step["num_contexts"]) > 0 + and not is_in_breakable_cuda_graph() + ) + + +def _ctx_norm_rows(x: torch.Tensor) -> bool: + """Whether a boundary of ``x`` in an eager step reaches the CTX norm's rows.""" + return ( + CTX_STACK + and x.dim() == 2 + and x.shape[0] >= CTX_NORM_MIN_ROWS + and not is_in_breakable_cuda_graph() + ) + + +def _ctx_prequant_linear(core, x: torch.Tensor, wk: str, sk: str, low_m_gemm: bool) -> torch.Tensor: + """``_linear`` that first takes the built-in prequantized MXFP8 slot for ``x`` (the CTX norm's or the combine's + MXFP8 copy of it), then runs the GEMM ``m3_mxfp8_linear`` runs after its own quantize; otherwise ``_linear``. + + This is the built-in MXFP8 linear with its CTX CLC GEMM off (TRTLLM_CTX_CLC_GEMM=0, as the aggregated deployment + runs); the built-in dense MLP's SwiGLU + MXFP8 producer is likewise off there (TRTLLM_CTX_SWIGLU_MXFP8=0).""" + from tensorrt_llm._torch.modules.linear import take_prequantized_mxfp8 + + x = x.contiguous() + mode = _mx_mode(core.mxfp8) + prequant = None if mode.decode_graph else take_prequantized_mxfp8(x) + if prequant is None: + return _linear(core, x, wk, sk, low_m_gemm)[0] + act, act_scale = prequant + w, s = core.w[wk], core.w[sk] + _record("m3_mxfp8_gemm_prequant", tuple(w.shape), x.shape[0]) + if mode.flashinfer: + return torch.ops.trtllm.flashinfer_mm_mxfp8(act, act_scale, w, s, torch.bfloat16) + gemm = ( + torch.ops.trtllm.mxfp8_mxfp8_gemm_autotuned + if mode.native_tuning + else torch.ops.trtllm.mxfp8_mxfp8_gemm + ) + return gemm(act, act_scale, w, s, core.mx_alpha, torch.bfloat16) + + +def _ctx_fp4_input_scale(core, i: int, rows: int) -> Optional[torch.Tensor]: + """The routed experts' NVFP4 fc31 input scale when the CTX norm's NVFP4 output can stand in for their own quantize + (one runner call, as the built-in ``MiniMaxM3MoE.fp4_input_scale``); None otherwise.""" + if rows > core.moe_max_num_tokens: + return None + scale = core.moe[i].fc31_input_scale + if scale.dtype != torch.float32 or scale.numel() != 1: + return None + return scale + + +def _ctx_reduce_norm( + core, x: torch.Tensor, residual: torch.Tensor, norm_w: torch.Tensor, moe_layer=None +): + """The built-in CTX boundary (``MiniMaxM3DecoderLayer._reduce_norm_mxfp8``): the plain all-reduce, then one kernel + for the residual add + RMSNorm that also writes the next linear's MXFP8 input into the prequantized slot and, + before MoE layer ``moe_layer``, the routed experts' NVFP4 input. Returns ``(normed, updated residual, nvfp4)`` + (``nvfp4`` = (packed e2m1, linear block scales) or None), or None where the built-in keeps the stock boundary.""" + from tensorrt_llm._torch.models import modeling_minimaxm3 as builtin + from tensorrt_llm._torch.modules.linear import ctx_eager_only, set_prequantized_mxfp8 + + rows, hidden = x.shape[0], x.shape[1] + if ( + not builtin._CTX_NORM_MXFP8 + or rows < builtin._CTX_NORM_MXFP8_MIN_ROWS + or hidden % 256 != 0 + or hidden // 8 > 1024 + or x.dtype != torch.bfloat16 + or not ctx_eager_only() + or not hasattr(torch.ops.trtllm, "minimax_m3_ctx_residual_rmsnorm_mxfp8") + ): + return None + reduced = m3_allreduce(x, core.allreduce, AllReduceParams(fusion_op=AllReduceFusionOp.NONE)) + fp4_scale = None + if moe_layer is not None and builtin._CTX_NORM_FP4 and builtin._ctx_norm_op_has_fp4(): + fp4_scale = _ctx_fp4_input_scale(core, moe_layer, rows) + if fp4_scale is None: + outs = torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8( + reduced, residual, norm_w, core.rms_eps, True + ) + else: + outs = torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8( + reduced, residual, norm_w, core.rms_eps, True, fp4_scale + ) + normed, act, act_scale = outs[:3] + set_prequantized_mxfp8(normed, act, act_scale, tag="ctx_norm") + _record("m3_ctx_norm", rows, fp4_scale is not None) + taken( + CTX_STACK_PATH, + rows, + "CTX norm + MXFP8" + (" + NVFP4 MoE input" if fp4_scale is not None else ""), + ) + return normed, reduced, ((outs[3], outs[4]) if fp4_scale is not None else None) + + +def _ctx_fused_qkv(core, i: int, hidden: torch.Tensor, position_ids, step: dict): + """The built-in fused QKV-index MXFP8 GEMM with the NVFP4 producer in its epilogue + (``MiniMaxM3Attention._ctx_fused_qkv_gemm_producer``) over this target's packed QKV weight and caches: Q / index-Q + (FP8) out, K / V / index-K written. None where the built-in declines (its row gate, the tuning pass, a cache the + kernel's alignment contract does not take); the caller then runs the projection + producer.""" + from tensorrt_llm._torch.models import modeling_minimaxm3 as builtin + from tensorrt_llm._torch.modules.linear import ctx_eager_only, take_prequantized_mxfp8 + + rows = int(hidden.shape[0]) + manager = step["kv_cache_manager"] + if ( + not builtin._CTX_QKV_FUSED + or not ctx_eager_only() + or hidden.dim() != 2 + or not hidden.is_contiguous() + or hidden.dtype != torch.bfloat16 + or not builtin._ctx_qkv_fused_takes_rows(rows) + or builtin._autotuner_tuning() + or position_ids is None + or manager is None + or not _nvfp4_layer(manager, i) + ): + return None + buffers = manager.get_buffers(i, kv_layout="HND") + scale_buffers = manager.get_block_scale_buffers(i, kv_layout="HND") + index_k_cache = step["msa_idx_k_cache"](i) + out_cache_loc = step["msa_out_cache_loc"] + kv_quant_scale = core.inv_kv_scales[i] + cos_sin = core.rotary_cos_sin + # The checks the built-in caller makes and the runner's own argument asserts do not: the RoPE table (64 rotary + # dims, fp32), the NVFP4 KV quant scale, and an index-K cache with the main pool's pages. + if ( + buffers is None + or scale_buffers is None + or not _nvfp4_fused_write_layout(buffers, scale_buffers, core.kv_heads) + or index_k_cache.shape[0] != buffers.shape[0] + or not kv_quant_scale.is_cuda + or kv_quant_scale.dtype != torch.float32 + or kv_quant_scale.numel() < 3 + or not kv_quant_scale.is_contiguous() + or not cos_sin.is_cuda + or cos_sin.dtype != torch.float32 + or not cos_sin.is_contiguous() + or cos_sin.dim() != 3 + or tuple(cos_sin.shape[1:]) != (2, 32) + or out_cache_loc is None + or out_cache_loc.dtype != torch.int32 + or not out_cache_loc.is_contiguous() + or out_cache_loc.numel() < rows + ): + return None + w = core.w + runner = builtin._ctx_qkv_fused_runner(core.heads, core.kv_heads, core.index_heads) + q = hidden.new_empty((rows, core.heads, core.head_dim), dtype=torch.float8_e4m3fn) + index_q = hidden.new_empty((rows, core.index_heads, core.head_dim), dtype=torch.float8_e4m3fn) + prequant = take_prequantized_mxfp8(hidden) + act, act_scale = ( + prequant if prequant is not None else torch.ops.trtllm.mxfp8_quantize(hidden, True) + ) + try: + args = runner.make_args( + act.view(rows, -1), + act_scale, + w[f"l{i}_qkv_w"], + w[f"l{i}_qkv_s"], + core.mx_alpha, + q, + index_q, + buffers.view(torch.uint8), + scale_buffers, + index_k_cache, + out_cache_loc[:rows], + kv_quant_scale, + cos_sin, + position_ids.reshape(-1).contiguous().to(torch.int32), + torch.cat( + (w[f"l{i}_q_norm"], w[f"l{i}_k_norm"], w[f"l{i}_idx_q_norm"], w[f"l{i}_idx_k_norm"]) + ), + core.rms_eps, + ) + except AssertionError: + # A cache geometry outside the kernel's alignment contract: the caller's projection + producer (the MXFP8 + # activation taken here is quantized again there, bitwise the same). + return None + runner.run_args(args) + _record("m3_ctx_fused_qkv", rows) + taken(CTX_STACK_PATH, rows, "fused QKV GEMM + producer") + return q.flatten(1), index_q.flatten(1) + + # -------------------------------------------------------------------------------------------------------------------- # Attention # -------------------------------------------------------------------------------------------------------------------- @@ -2247,6 +2473,7 @@ def __init__(self, model_config: ModelConfig[PretrainedConfig]) -> None: self.mapping = mapping # Whether the 9..16-row generation router takes the TF32 tensor-core kernel (set by prebuild_kernels). self.router_tc_cluster16 = False + self.router_w_tf32: Dict[int, torch.Tensor] = {} self.vocab_size = cfg.vocab_size d = _weights.MODEL_WEIGHTS.dims(self) self.num_layers = d.num_layers @@ -2424,6 +2651,19 @@ def post_load_weights(self) -> None: ) for i in sorted(self.moe_layers) } + # The fixed-tile TF32 context router's TF32-rounded weights (_context_router_logits), as the built-in gate + # builds them after every weight load; none under its kill (TRTLLM_CTX_ROUTER_TF32_FIXED=0). + from tensorrt_llm._torch.models.modeling_minimaxm3 import _CTX_ROUTER_TF32_FIXED + from tensorrt_llm._torch.moe.fused_moe.router_gemm_tf32 import prepare_router_weight_tf32 + + self.router_w_tf32 = ( + { + i: prepare_router_weight_tf32(self.w[f"l{i}_router"].float()) + for i in sorted(self.moe_layers) + } + if _CTX_ROUTER_TF32_FIXED + else {} + ) self._build_embed_owners() self.prebuild_kernels() self._prefill = PrefillTarget(self) @@ -3004,12 +3244,21 @@ def forward( return hidden def _swiglu_mlp( - self, h: torch.Tensor, prefix: str, low_m_gemm: bool, dense: bool = False + self, + h: torch.Tensor, + prefix: str, + low_m_gemm: bool, + dense: bool = False, + prequant: bool = False, ) -> torch.Tensor: """A gated MXFP8 MLP (the dense MLP, the shared expert): gate_up, SwiGLU-OAI (the dense MLP's on this target's - C++ op, ``_dense_swiglu``), down, no reduction.""" + C++ op, ``_dense_swiglu``), down, no reduction. ``prequant``: the gate_up takes the CTX norm's MXFP8 copy of + ``h`` (the built-in CTX stack).""" core = self.core - gu, _ = _linear(core, h, f"{prefix}_gu_w", f"{prefix}_gu_s", low_m_gemm) + if prequant: + gu = _ctx_prequant_linear(core, h, f"{prefix}_gu_w", f"{prefix}_gu_s", low_m_gemm) + else: + gu, _ = _linear(core, h, f"{prefix}_gu_w", f"{prefix}_gu_s", low_m_gemm) if dense: act = _dense_swiglu(core, gu) else: @@ -3055,14 +3304,48 @@ def _routed(self, i: int, h: torch.Tensor): if fused is not None: logits, x_fp4, x_sf = fused return _routed_experts(core, i, x_fp4, x_sf, logits, True) - return self._routed_chunks(i, h, _router_logits(core, i, h)) + return self._routed_chunks(i, h, _context_router_logits(core, i, h)) + + def _ctx_moe(self, i: int, h: torch.Tensor, nvfp4: Optional[tuple]) -> torch.Tensor: + """The built-in MoE forward of a CTX-stack step (``MiniMaxM3MoE.forward``, the shared expert not folded): the + fixed-tile TF32 router; the routed experts on the CTX norm's NVFP4 input (``nvfp4``) in one runner call, else on + the bf16 activation in the MoE scheduler's chunks, each finalized by the runner; the shared expert beside them + (its gate_up on the CTX norm's MXFP8 copy); then the shared + routed add.""" + core = self.core - def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): + def _routed(): + logits = _context_router_logits(core, i, h) + if nvfp4 is not None: + return _routed_experts(core, i, nvfp4[0], nvfp4[1], logits, True) + return self._routed_chunks(i, h, logits) + + routed_out, shared_out = maybe_execute_in_parallel( + _routed, + lambda: self._swiglu_mlp(h, f"l{i}_sh", False, prequant=True), + core.moe_events[i][0], + core.moe_events[i][1], + None if flashinfer_mxfp8_autotune_active() else core.aux_stream_moe, + disable_on_compile=True, + ) + taken(CTX_STACK_PATH, h.shape[0], "built-in MoE forward") + return shared_out.add_(routed_out) + + def _moe( + self, + i: int, + h: torch.Tensor, + *, + return_parts: bool, + ctx: bool = False, + ctx_nvfp4: Optional[tuple] = None, + ): """The MoE block of layer ``i`` without its reduction. Returns ``(out, routed)``: with ``return_parts`` the shared and routed parts (routed None when the engine folded the shared expert in), else their sum in - ``out``.""" + ``out``. ``ctx``: a CTX-stack step at the CTX norm's rows, the built-in MoE forward (``_ctx_moe``).""" core = self.core rows = h.shape[0] if h.dim() == 2 else 0 + if ctx and not return_parts and h.dim() == 2: + return self._ctx_moe(i, h, ctx_nvfp4), None if ( h.dim() == 2 and h.dtype == torch.bfloat16 @@ -3077,7 +3360,9 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): return folded, None if not return_parts and _triton_finalize_rows(core, h): routed_parts, shared_out = maybe_execute_in_parallel( - lambda: _routed_experts(core, i, h, None, _router_logits(core, i, h), False), + lambda: _routed_experts( + core, i, h, None, _context_router_logits(core, i, h), False + ), lambda: self._swiglu_mlp(h, f"l{i}_sh", False), core.moe_events[i][0], core.moe_events[i][1], @@ -3112,6 +3397,20 @@ def _generic_boundary(self, x, x2, residual, norm_w): x = x.add_(x2) return _native_allreduce_norm(core, x, residual, norm_w) + def _boundary(self, i: int, x, x2, residual, capture_layer: bool = False): + """The boundary of layer ``i`` into the next layer's input norm (the final norm after the last layer). At the + CTX norm's rows a boundary into a next decoder layer is the built-in CTX one (the next QKV takes its MXFP8 + copy), on the shared + routed sum; otherwise ``_generic_boundary``. An Eagle3 capture layer keeps the generic + boundary, as the built-in turns its post-feed-forward fusion off there.""" + core = self.core + if i != core.num_layers - 1 and not capture_layer and _ctx_norm_rows(x): + if x2 is not None: + x, x2 = x.add_(x2), None + fused = _ctx_reduce_norm(core, x, residual, _next_norm(core, i)) + if fused is not None: + return fused[0], fused[1] + return self._generic_boundary(x, x2, residual, _next_norm(core, i)) + def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, capture): """Layer ``i`` in its generic form: input norm (first layer without the fused embedding), attention, the attention boundary, the MoE (or the dense MLP) and the boundary into the next layer's input norm, every @@ -3122,7 +3421,18 @@ def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, ca residual = hidden hidden = flashinfer_rmsnorm(hidden, core.w[f"l{i}_in_norm"], core.rms_eps) hidden, _ = self._attention(i, position_ids, hidden, step) - if _can_mc(hidden): + moe_layer = i in core.moe_layers + ctx_norm = ( + _ctx_reduce_norm( + core, hidden, residual, core.w[f"l{i}_post_norm"], i if moe_layer else None + ) + if _ctx_norm_rows(hidden) + else None + ) + ctx_nvfp4 = None + if ctx_norm is not None: + hidden, residual, ctx_nvfp4 = ctx_norm + elif _can_mc(hidden): fused = _mc_allreduce_norm(core, hidden, None, residual, core.w[f"l{i}_post_norm"]) hidden, residual = ( fused @@ -3133,21 +3443,34 @@ def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, ca hidden, residual = _native_allreduce_norm( core, hidden, residual, core.w[f"l{i}_post_norm"] ) - if i in core.moe_layers: + if moe_layer: # Row ranges at this dispatch: 9..48 rows take the decode target's generic MC finalize boundary (as the agg # canon's generic layer does on every step, context rows included: the MoE unfinalized, its finalize + # shared expert in the multicast all-reduce + residual + next norm); the CTX stack starts at 4096 rows. - folded = core._decode._generic_mc_finalize(i, hidden, residual, _next_norm(core, i)) + folded = ( + core._decode._generic_mc_finalize(i, hidden, residual, _next_norm(core, i)) + if ctx_norm is None + else None + ) if folded is not None: if spec_metadata is not None and spec_metadata.is_layer_capture(i): capture(spec_metadata, i, folded[1], None) return folded - out, routed = self._moe(i, hidden, return_parts=_can_mc(hidden, folded=True)) + out, routed = self._moe( + i, + hidden, + return_parts=_can_mc(hidden, folded=True), + ctx=_ctx_stack_step(step, hidden.shape[0]) and _ctx_norm_rows(hidden), + ctx_nvfp4=ctx_nvfp4, + ) else: - out = self._swiglu_mlp(hidden, f"l{i}_mlp", True, dense=True) + out = self._swiglu_mlp( + hidden, f"l{i}_mlp", True, dense=True, prequant=ctx_norm is not None + ) routed = None - normed, updated = self._generic_boundary(out, routed, residual, _next_norm(core, i)) - if spec_metadata is not None and spec_metadata.is_layer_capture(i): + capture_layer = spec_metadata is not None and spec_metadata.is_layer_capture(i) + normed, updated = self._boundary(i, out, routed, residual, capture_layer) + if capture_layer: capture(spec_metadata, i, updated, None) return normed, updated @@ -3174,8 +3497,10 @@ def _attention(self, i: int, position_ids, hidden, step): "(fuse_qkv_index_projection)" ) return self._unfused_sparse_attention(i, position_ids, hidden, step) - packed, _ = _linear(core, hidden, f"l{i}_qkv_w", f"l{i}_qkv_s", True) if is_in_breakable_cuda_graph(): + # A captured bucket: the projection is captured, the producer + core run in the eager boundary. The CTX + # stack never runs here (``_ctx_stack_step`` is eager-only). + packed, _ = _linear(core, hidden, f"l{i}_qkv_w", f"l{i}_qkv_s", True) output = packed.new_empty( (packed.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16 ) @@ -3183,6 +3508,18 @@ def _attention(self, i: int, position_ids, hidden, step): packed, position_ids, None, None, None, None, output, self._bcg_key, i ) return _linear(core, output, f"l{i}_o_w", f"l{i}_o_s", True) + ctx = _ctx_stack_step(step, hidden.shape[0]) + if ctx: + from tensorrt_llm._torch.models import modeling_minimaxm3 as builtin + + horizontal = _ctx_fused_qkv(core, i, hidden, position_ids, step) + if horizontal is not None: + q, idx_q = horizontal + if builtin._CTX_P5A_COMBINE_MXFP8: + return self._ctx_core_then_o_proj(i, q, idx_q, step, "p5a"), False + o = self._attention_core(i, q, None, None, idx_q, step) + return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) + packed, _ = _linear(core, hidden, f"l{i}_qkv_w", f"l{i}_qkv_s", True) horizontal = _sparse_qkv_producer( core, i, @@ -3198,9 +3535,32 @@ def _attention(self, i: int, position_ids, hidden, step): "pool with an FP8 index-K cache)" ) q, idx_q = horizontal + if ctx: + return self._ctx_core_then_o_proj(i, q, idx_q, step, "horizontal"), False o = self._attention_core(i, q, None, None, idx_q, step) return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) + def _ctx_core_then_o_proj(self, i: int, q, idx_q, step: dict, site: str) -> torch.Tensor: + """The sparse attention core, then its o_proj, as the built-in ``MiniMaxM3Attention._core_then_o_proj``: in + eager prefill the core's NVFP4 combine may also write the o_proj input as MXFP8 into the prequantized slot + (msa_combine_mxfp8), which the o_proj takes. Not armed while compiling, nor on a padded step (the combine covers + only the live rows).""" + from tensorrt_llm._torch.attention.backends.fmha import msa_combine_mxfp8 + from tensorrt_llm._torch.modules.linear import ctx_eager_only + + core = self.core + padded = getattr(step["metadata"], "padded_num_tokens", None) is not None + if not ctx_eager_only() or padded: + o = self._attention_core(i, q, None, None, idx_q, step) + return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True)[0] + # The o_proj below reads its input only through the slot when the slot holds it (``_ctx_prequant_linear`` + # outside decode graphs), so the combine may skip its bf16 store. + with msa_combine_mxfp8.armed(site, not _mx_mode(core.mxfp8).decode_graph): + o = self._attention_core(i, q, None, None, idx_q, step) + out = _ctx_prequant_linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) + msa_combine_mxfp8.after_o_proj(o) + return out + def _unfused_sparse_attention(self, i: int, position_ids, hidden, step): """A sparse layer without the five-way projection (``fuse_qkv_index_projection=False``): the QKV projection and its fused norm + RoPE (FP8 q/k/v into an FP8 cache) on the current stream, the BF16 index projection and diff --git a/tensorrt_llm/_torch/attention/backends/fmha/drafter_last_row.py b/tensorrt_llm/_torch/attention/backends/fmha/drafter_last_row.py new file mode 100644 index 000000000000..64b3211acd5e --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/fmha/drafter_last_row.py @@ -0,0 +1,306 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Context-phase FMHA of a one-layer Eagle3 drafter that attends only each sequence's last row. + +At a context step the one-model Eagle3 loop reads the drafter's first pass at one row per context request, its last +row (``last_tokens_idx``), so the attention outputs of all other context rows are dead. Their K/V are not: the stock +context preprocess (RoPE, quantization and the KV-cache append) still runs for every row, so the drafter KV cache is +the stock one. Only the attention itself runs with one query per sequence, at the end of that sequence's KV, on the +trtllm-gen split-KV decode kernel (one query row per sequence attends to its whole KV, as a decode row does), or on +the context kernel at one query row when _DECODE_KERNEL is False. The other output rows are zeros, which keeps them +finite through the rest of the drafter layer. +""" + +import dataclasses +import math +import os +from typing import TYPE_CHECKING, Optional + +import torch + +from tensorrt_llm._utils import mpi_rank +from tensorrt_llm.logger import logger + +from .flashinfer_trtllm_gen import FlashInferTrtllmGenFmha, _get_bmm1_scale_log2 +from .interface import FmhaPhase +from .phased import FmhaParams + +# The last rows run on the split-KV decode kernel (the context kernel gives one query row a single CTA per head group, +# so a long KV is read by a handful of CTAs). Kill: TRTLLM_CTX_DRAFTER_LAST_ROW_DECODE=0 in the deployment env (read +# once at import) runs them on the context kernel. +_DECODE_KERNEL = os.environ.get("TRTLLM_CTX_DRAFTER_LAST_ROW_DECODE", "1") == "1" + +# Before the last rows attend, the K and V rows at and past each sequence's kv_len on its partial last page are zeroed: +# both kernels read that page whole, and a NaN code there turns the masked 0 * NaN into NaN output. Those slots hold no +# token of the sequence yet and are rewritten when it grows into them. Only on a KV cache whose partial last pages are +# private (see _v_tail_zero_safe). Kill: TRTLLM_CTX_DRAFTER_KV_TAIL_ZERO=0 in the deployment env (read once at import). +_KV_TAIL_ZERO = os.environ.get("TRTLLM_CTX_DRAFTER_KV_TAIL_ZERO", "1") == "1" + +# Calls at which the taken line is logged. +_LOG_AT_CALLS = frozenset(10**i for i in range(7)) + +if TYPE_CHECKING: + from tensorrt_llm._torch.attention.backends.interface import AttentionForwardArgs + from tensorrt_llm._torch.attention.backends.trtllm import ( + TrtllmAttention, + TrtllmAttentionMetadata, + ) + + +def _bmm1_scale_log2(bmm1_scale) -> Optional[torch.Tensor]: + """The decode kernel's log2 softmax scale for a context-preprocess ``bmm1_scale``: its second entry when it carries + one, else ``bmm1_scale * log2(e)`` rounded once to FP32 (as the trtllm-gen launcher derives it).""" + if not isinstance(bmm1_scale, torch.Tensor): + return None + if bmm1_scale.numel() >= 2: + return _get_bmm1_scale_log2(bmm1_scale) + return (bmm1_scale[:1].double() * math.log2(math.e)).float() + + +class DrafterLastRowContextFmha(FlashInferTrtllmGenFmha): + """The FlashInfer trtllm-gen context path with the attention run on the last row of each sequence only. + + Serves the context phase alone, so a mixed step composes it with the stock generation library through + ``CombinedFmha``. Install it only on the attention of a drafter whose context outputs are read at the last row + of each sequence and nowhere else. + """ + + def __init__(self, attn: "TrtllmAttention"): + super().__init__(attn) + # Separate log-once state per outcome, so a warmup "taken" does not hide a later "not taken"; the taken + # count is logged at 1, 10, 100, ... calls so a log proves engagement past warmup. + self._logged_not_taken = False + self._num_taken = 0 + self._kv_tail_safe: Optional[bool] = None + + def _kv_tail_zero(self, meta: "TrtllmAttentionMetadata") -> bool: + """Whether this step zeroes the partial last pages' tails (``_KV_TAIL_ZERO`` on a private-page cache).""" + if not _KV_TAIL_ZERO: + return False + if self._kv_tail_safe is None: + self._kv_tail_safe = _v_tail_zero_safe(meta.kv_cache_manager) + if not self._kv_tail_safe: + logger.warning( + "drafter_ctx_last_row: this KV cache can share a partially reused page without copying it; the " + "partial last pages' K/V tails are not zeroed" + ) + return self._kv_tail_safe + + @classmethod + def _is_available(cls, attn: "TrtllmAttention") -> bool: + return bool(getattr(attn, _MARK, False)) + + def _is_supported( + self, + q: torch.Tensor, + k: Optional[torch.Tensor], + v: Optional[torch.Tensor], + metadata: "TrtllmAttentionMetadata", + forward_args: "AttentionForwardArgs", + *, + phase: Optional[FmhaPhase] = None, + ) -> bool: + if phase is not FmhaPhase.CONTEXT: + return False + supported, reason = self._is_supported_with_reason( + q, k, v, self.attn, metadata, forward_args, phase=phase + ) + if not supported and not self._logged_not_taken: + self._logged_not_taken = True + logger.info( + f"[M3 dispatch] rank {mpi_rank()}: drafter_ctx_last_row not taken: {reason}" + ) + return supported + + def _run_context_attention( + self, + params: FmhaParams, + q_processed: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + kv_scale_pool: Optional[torch.Tensor], + fmha_workspace: torch.Tensor, + cu_q_seqlens: torch.Tensor, + cu_kv_seqlens: torch.Tensor, + max_q_len: int, + max_kv_len: int, + window_left: int, + bmm1_scale, + bmm2_scale, + causal: bool, + ) -> None: + if params.is_cross or not causal: + super()._run_context_attention( + params, + q_processed, + kv_pool, + block_tables, + kv_scale_pool, + fmha_workspace, + cu_q_seqlens, + cu_kv_seqlens, + max_q_len, + max_kv_len, + window_left, + bmm1_scale, + bmm2_scale, + causal, + ) + return + batch = params.batch_size + if self._kv_tail_zero(params.meta): + _zero_kv_tails(kv_pool, block_tables, params.sequence_lengths, batch) + logger.info_once( + f"[CTX] drafter_kv_tail_zero taken (seqs={batch}, pages={2 * batch})", + key="minimax_m3_drafter_kv_tail_zero", + ) + last_rows = cu_q_seqlens[1 : batch + 1].to(torch.long) - 1 + q_last = q_processed.index_select(0, last_rows) + out_last = params.output.new_empty((batch,) + tuple(params.output.shape[1:])) + self._num_taken += 1 + if self._num_taken in _LOG_AT_CALLS: + logger.info( + f"[M3 dispatch] rank {mpi_rank()}: drafter_ctx_last_row taken at {params.num_tokens} rows, " + f"{batch} sequences, {'decode' if _DECODE_KERNEL else 'context'} kernel " + f"(call {self._num_taken})" + ) + if _DECODE_KERNEL: + import flashinfer + + flashinfer.decode.trtllm_batch_decode_with_kv_cache( + query=q_last, + kv_cache=(kv_pool, kv_pool), + workspace_buffer=fmha_workspace, + block_tables=block_tables, + seq_lens=params.sequence_lengths, + max_seq_len=max_kv_len, + bmm1_scale=bmm1_scale, + bmm2_scale=bmm2_scale, + window_left=window_left, + out=out_last, + sinks=params.fwd.attention_sinks, + kv_layout=self._layout, + enable_pdl=self._enable_pdl, + backend="trtllm-gen", + q_len_per_req=1, + kv_cache_sf=(kv_scale_pool, kv_scale_pool) if kv_scale_pool is not None else None, + uses_shared_paged_kv_idx=self.USE_SHARED_PAGED_KV_IDX, + bmm1_scale_log2=_bmm1_scale_log2(bmm1_scale), + multi_ctas_kv_counter_buffer=self._get_multi_ctas_kv_counter_buffer(), + ) + params.output.zero_() + params.output.index_copy_(0, last_rows, out_last) + return + params_last = dataclasses.replace(params, output=out_last) + super()._run_context_attention( + params_last, + q_last, + kv_pool, + block_tables, + kv_scale_pool, + fmha_workspace, + torch.arange(batch + 1, dtype=cu_q_seqlens.dtype, device=cu_q_seqlens.device), + cu_kv_seqlens, + 1, + max_kv_len, + window_left, + bmm1_scale, + bmm2_scale, + causal, + ) + params.output.zero_() + params.output.index_copy_(0, last_rows, out_last) + + +_MARK = "_drafter_ctx_last_row" + + +def _v_tail_zero_safe(kv_cache_manager) -> bool: + """Whether every row's partial last page is its own, so zeroing past kv_len cannot touch another row's tokens. + + True without block reuse or partial reuse, or when a partially matched block is copied on reuse: + KVCacheManagerV2 always copies it, and KVCacheManager does with copy_on_partial_reuse. + """ + from tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2 import KVCacheManagerV2 + + if not getattr(kv_cache_manager, "enable_block_reuse", True) or not getattr( + kv_cache_manager, "enable_partial_reuse", True + ): + return True + if isinstance(kv_cache_manager, KVCacheManagerV2): + return True + return bool(getattr(kv_cache_manager, "copy_on_partial_reuse", False)) + + +def _zero_kv_tails( + kv_pool: torch.Tensor, block_tables: torch.Tensor, kv_lens: torch.Tensor, batch: int +) -> None: + """Zero the K and V rows at and past each sequence's kv_len on its partial last page, on the device (no host sync). + + kv_pool is the flat sub-block pool [blocks, kv_heads, page, d]; block_tables[b, 0 / 1, i] the K / V sub-block of + sequence b's page i; kv_lens the sequences' K/V lengths. A sequence whose last page is full is left as it is. + """ + page_size = int(kv_pool.shape[2]) + kv = kv_lens[:batch].to(torch.long) + last = torch.div(kv - 1, page_size, rounding_mode="floor").clamp_min(0) + blocks = ( + block_tables[:batch].to(torch.long).gather(2, last.view(-1, 1, 1).expand(-1, 2, 1)).view(-1) + ) + first_free = (kv % page_size).repeat_interleave(2) + past = (torch.arange(page_size, device=kv_pool.device)[None, :] >= first_free[:, None]) & ( + first_free[:, None] > 0 + ) + pool = kv_pool.view(torch.uint8) + pages = pool[blocks] + pages.masked_fill_(past[:, None, :, None], 0) + pool[blocks] = pages + + +def mark_drafter_last_row_attention(draft_model: torch.nn.Module) -> int: + """Make ``DrafterLastRowContextFmha`` available on the attention backend of a one-layer ``draft_model``. + + The FMHA registry lists the library first; it is available only on a backend marked here, so every FmhaManager the + backend builds (one per quant-config update) has it. A drafter with more layers is left alone: there every + context row's output feeds the next layer's K/V. Returns the number of backends marked (0 or 1). + """ + from tensorrt_llm._torch.attention.backends.trtllm import TrtllmAttention + + backends = [ + backend + for backend in (getattr(module, "attn", None) for module in draft_model.modules()) + if isinstance(backend, TrtllmAttention) + ] + if len(backends) != 1: + logger.info( + f"drafter_ctx_last_row not enabled: the drafter has {len(backends)} attention layers" + ) + return 0 + backend = backends[0] + setattr(backend, _MARK, True) + manager = getattr(backend, "_fmha_manager", None) + if manager is not None and not any( + isinstance(lib, DrafterLastRowContextFmha) for lib in manager.fmha_libs + ): + from .manager import FmhaManager + + backend._fmha_manager = FmhaManager(backend) + logger.info( + "drafter_ctx_last_row enabled ahead of " + f"{[type(lib).__name__ for lib in backend._fmha_manager.fmha_libs[1:]]}" + ) + return 1 + + +__all__ = ["DrafterLastRowContextFmha", "mark_drafter_last_row_attention"] diff --git a/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py b/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py index bab3490c85bb..6178b16bd3e4 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py @@ -1032,28 +1032,21 @@ def run_context( if params.is_cross else AttentionMaskType(fwd.mask_type) == AttentionMaskType.causal ) - flashinfer.prefill.trtllm_batch_context_with_kv_cache( - query=q_processed, - kv_cache=(kv_pool, kv_pool), - workspace_buffer=fmha_workspace, - block_tables=block_tables, - seq_lens=params.sequence_lengths, - max_q_len=max_q_len, - max_kv_len=max_kv_len, - bmm1_scale=ctx_bmm1_scale, - bmm2_scale=ctx_bmm2_scale, - batch_size=params.batch_size, - cum_seq_lens_q=cu_q_seqlens, - cum_seq_lens_kv=cu_kv_seqlens, - window_left=window_left, - out=params.output, - kv_layout=self._layout, - enable_pdl=self._enable_pdl, - sinks=fwd.attention_sinks, - kv_cache_sf=(kv_scale_pool, kv_scale_pool) if kv_scale_pool is not None else None, - uses_shared_paged_kv_idx=self.USE_SHARED_PAGED_KV_IDX, - causal=causal, - multi_ctas_kv_counter_buffer=self._get_multi_ctas_kv_counter_buffer(), + self._run_context_attention( + params, + q_processed, + kv_pool, + block_tables, + kv_scale_pool, + fmha_workspace, + cu_q_seqlens, + cu_kv_seqlens, + max_q_len, + max_kv_len, + window_left, + ctx_bmm1_scale, + ctx_bmm2_scale, + causal, ) if params.is_cross: @@ -1099,6 +1092,48 @@ def run_context( self._multi_processor_count, # multi_processor_count ) + def _run_context_attention( + self, + params: FmhaParams, + q_processed: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + kv_scale_pool: Optional[torch.Tensor], + fmha_workspace: torch.Tensor, + cu_q_seqlens: torch.Tensor, + cu_kv_seqlens: torch.Tensor, + max_q_len: int, + max_kv_len: int, + window_left: int, + bmm1_scale, + bmm2_scale, + causal: bool, + ) -> None: + """The context attention of ``run_context``, between its preprocess and its postprocess.""" + flashinfer.prefill.trtllm_batch_context_with_kv_cache( + query=q_processed, + kv_cache=(kv_pool, kv_pool), + workspace_buffer=fmha_workspace, + block_tables=block_tables, + seq_lens=params.sequence_lengths, + max_q_len=max_q_len, + max_kv_len=max_kv_len, + bmm1_scale=bmm1_scale, + bmm2_scale=bmm2_scale, + batch_size=params.batch_size, + cum_seq_lens_q=cu_q_seqlens, + cum_seq_lens_kv=cu_kv_seqlens, + window_left=window_left, + out=params.output, + kv_layout=self._layout, + enable_pdl=self._enable_pdl, + sinks=params.fwd.attention_sinks, + kv_cache_sf=(kv_scale_pool, kv_scale_pool) if kv_scale_pool is not None else None, + uses_shared_paged_kv_idx=self.USE_SHARED_PAGED_KV_IDX, + causal=causal, + multi_ctas_kv_counter_buffer=self._get_multi_ctas_kv_counter_buffer(), + ) + def run_generation( self, params: FmhaParams, diff --git a/tensorrt_llm/_torch/attention/backends/fmha/msa_combine_mxfp8.py b/tensorrt_llm/_torch/attention/backends/fmha/msa_combine_mxfp8.py new file mode 100644 index 000000000000..36e59acb2c3c --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/fmha/msa_combine_mxfp8.py @@ -0,0 +1,162 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 CTX: the NVFP4 sparse prefill's combine also writes the o_proj input as MXFP8. + +The combine's epilogue quantizes the final bf16 attention output it is about to store (fmha_sm100 combine +``o_fp8=`` / ``sf_out=``), bitwise ``mxfp8_quantize(o, True)``, and hands the pair to the o_proj through the MXFP8 +prequant slot (modules.linear.set_prequantized_mxfp8), so the o_proj skips its own activation quantize. + +It engages only where the slot is certainly consumed by an eager o_proj on exactly the combine's rows: +- the attention module armed it (``armed()``) around an eager attention core that is followed by its o_proj; +- a pure context step (no generation rows: the combine then covers every row of the o_proj input); +- the in-place SM107 combine path (the combine writes the o_proj input buffer itself) and an fmha_sm100 that + accepts ``o_fp8``. +The bf16 output is still written (``write_bf16=True``), so a slot that is not consumed only costs the extra stores; +it is logged once as a miss (``after_o_proj``). Kill switch: TRTLLM_CTX_COMBINE_MXFP8=0. +""" + +from __future__ import annotations + +import contextlib +import inspect +import os +from typing import Any, Optional + +import torch + +from tensorrt_llm.logger import logger + +ENABLED = os.environ.get("TRTLLM_CTX_COMBINE_MXFP8", "1") != "0" +# Skip the bf16 store too (the o_proj reads only the MXFP8 pair). On by default (mega2; kill: =0). Only where +# o_proj_takes_slot() proved the o_proj consumes the slot; a pair it then does not take raises (its bf16 input was +# never written). +SKIP_BF16 = os.environ.get("TRTLLM_CTX_COMBINE_MXFP8_SKIP_BF16", "1") != "0" +_ENGAGEMENT = "combine MXFP8 o_proj input taken" +_ENGAGEMENT_SKIP = "combine MXFP8 o_proj input taken (bf16 store skipped)" + +_armed: list = [None] # the arming call site's tag (slot audit), None when not armed +_skip_ok: list = [False] # the armed o_proj consumes the slot, so the bf16 store may be skipped +_pending: list = [None] # the slot entry this module set and the o_proj has not consumed yet +_takes: dict = {} + + +def _sparse_takes_o_fp8(sparse: Any) -> bool: + # Keyed on the function itself (held by the dict), not id(sparse): a freed object's id can be reused. + func = sparse.sparse_atten_nvfp4_kv_func + if func not in _takes: + params = inspect.signature(func).parameters + _takes[func] = all(name in params for name in ("o_fp8", "sf_out", "write_bf16")) + return _takes[func] + + +def o_proj_takes_slot(o_proj: Any) -> bool: + """Whether ``o_proj`` reads its input only through the MXFP8 slot when the slot holds it: an MXFP8 CUTLASS + linear outside the decode-graph FlashInfer path (MXFP8LinearMethod.apply). Its LoRA layer (every attention + o_proj has one) reads the input only when the call passes lora_params, which _core_then_o_proj never does.""" + from tensorrt_llm._torch.modules import linear + + method = getattr(o_proj, "quant_method", None) + return ( + isinstance(method, linear.MXFP8LinearMethod) + and bool(getattr(method, "use_cutlass", False)) + and not linear._FLASHINFER_MXFP8_DECODE_GRAPH_CAPTURE_ACTIVE.get() + ) + + +@contextlib.contextmanager +def armed(site: str = "sparse", skip_bf16_ok: bool = False): + """Arm the fold for the attention core run inside the block (its o_proj follows, eagerly).""" + previous = _armed[0], _skip_ok[0] + _armed[0] = site if ENABLED else None + _skip_ok[0] = SKIP_BF16 and skip_bf16_ok + try: + yield + finally: + _armed[0], _skip_ok[0] = previous + + +def combine_kwargs(sparse: Any, out: torch.Tensor, metadata: Any, in_place: bool) -> Optional[dict]: + """The fmha_sm100 combine's MXFP8 outputs for ``out`` [total_q, heads, 128] when the fold engages, else None.""" + site = _armed[0] + if site is None: + return None + if not in_place: + return _decline(site, "not_in_place") + if getattr(metadata, "num_generations", 1) != 0: + # mixed step: the generation rows of the o_proj input come from the decode kernel + return _decline(site, "mixed_step") + if ( + out.dim() != 3 + or out.shape[-1] != 128 + or out.dtype != torch.bfloat16 + or not out.is_contiguous() + ): + return _decline(site, "layout") + if not _sparse_takes_o_fp8(sparse): + return _decline(site, "no_o_fp8") + rows, cols = out.shape[0], out.shape[1] * out.shape[2] + padded_rows = (rows + 127) // 128 * 128 + o_fp8 = torch.empty((rows, cols), dtype=torch.float8_e4m3fn, device=out.device) + sf = torch.empty((padded_rows * cols // 32,), dtype=torch.uint8, device=out.device) + if padded_rows != rows: + # The last 128-row scale tile holds the padding rows; the kernel writes every real row's scales in it. + tile = 128 * cols // 32 + sf[-tile:].zero_() + return {"o_fp8": o_fp8, "sf_out": sf, "write_bf16": not _skip_ok[0]} + + +def _decline(site: str, reason: str) -> None: + """Count an armed call the fold declined (in the MXFP8 slot audit, as its own tag's set count).""" + from tensorrt_llm._torch.modules import linear + + linear._prequantized_mxfp8_stats(f"combine_{site}_declined_{reason}")[0] += 1 + return None + + +def publish(out: torch.Tensor, kwargs: dict) -> None: + """Hand the combine's MXFP8 pair to the next MXFP8 linear (the o_proj) for the input ``out`` rows.""" + from tensorrt_llm._torch.modules import linear + + source = out.view(out.shape[0], -1) + linear.set_prequantized_mxfp8( + source, kwargs["o_fp8"], kwargs["sf_out"], tag=f"combine_{_armed[0]}" + ) + _pending[0] = (source, linear._PREQUANTIZED_MXFP8_TAKES[0], not kwargs["write_bf16"]) + + +def after_o_proj(o_proj_input: Optional[torch.Tensor] = None) -> None: + """The o_proj ran: log the engagement only if it took the pair this module published (a take on mismatched + storage or shape drops the entry and quantizes the bf16 output instead).""" + pending = _pending[0] + if pending is None: + return + _pending[0] = None + source, takes_before, bf16_skipped = pending + from tensorrt_llm._torch.modules import linear + + entry = linear._PREQUANTIZED_MXFP8[0] + if entry is not None and entry[0] is source: + linear._PREQUANTIZED_MXFP8[0] = None + linear._prequantized_mxfp8_stats(entry[3])[3] += 1 + if linear._PREQUANTIZED_MXFP8_TAKES[0] != takes_before: + logger.info_once(f"[M3 CTX] {_ENGAGEMENT}", key="minimax_m3_ctx_combine_mxfp8_taken") + if bf16_skipped: + logger.info_once( + f"[M3 CTX] {_ENGAGEMENT_SKIP}", key="minimax_m3_ctx_combine_mxfp8_skip_taken" + ) + return + if bf16_skipped: + raise RuntimeError( + "MiniMax-M3 CTX: the o_proj did not take the combine's MXFP8 pair and its bf16 input was not written " + f"(published {tuple(source.shape)}; TRTLLM_CTX_COMBINE_MXFP8_SKIP_BF16=0 keeps the bf16 store)" + ) + seen = ( + "none" + if o_proj_input is None + else f"{tuple(o_proj_input.shape)} @{o_proj_input.data_ptr():#x}" + ) + logger.warning_once( + "[M3 CTX] combine MXFP8 o_proj input not consumed by the o_proj (it quantized the bf16 output): " + f"published {tuple(source.shape)} @{source.data_ptr():#x}, o_proj input {seen}", + key="minimax_m3_ctx_combine_mxfp8_missed", + ) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py b/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py index bc1301e57c1b..e101d930fd1d 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py @@ -21,13 +21,84 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Optional +import functools +import os +from typing import TYPE_CHECKING, Any, Optional import torch +import triton +import triton.language as tl + +from tensorrt_llm._utils import get_sm_version, mpi_rank, prefer_pinned +from tensorrt_llm.logger import logger from .interface import FmhaPhase from .phased import FmhaParams, PhasedFmha +# SM107: the NVFP4 sparse prefill's combine writes the layer's attention output buffer directly instead of a fresh +# tensor that is then copied over (same kernel, same values). Kill switch: False restores the copy. +_SM107_NVFP4_SPARSE_OUT_IN_PLACE = os.environ.get("TRTLLM_MSA_NVFP4_OUT_IN_PLACE", "1") == "1" + +# FP8 dense prefill (MiniMax-M3's dense layers) runs FA4 (flash_attn.cute) over the paged FP8 cache in place of +# fmha_sm100, about 1.6x faster at long context. The image's FA4 carries rescale_threshold 0.0 for FP8, so the +# row max is refreshed on every increase and P stays <= 2^8 (FA4's FP8 offset), inside E4M3's 448, instead of the +# lazy rescale that lets P saturate. Deterministic, and inside fmha_sm100's own 16-seed fp64 error band (numerics +# rule 1b). An FA4 without that change is never used. Kill switch: TRTLLM_MSA_DISABLE_DENSE_FA4=1 restores +# fmha_sm100. +_DENSE_PREFILL_FA4 = os.environ.get("TRTLLM_MSA_DISABLE_DENSE_FA4", "0") != "1" +# The FA4 shape this path serves: TMA page loads need the page to equal FA4's 128-wide n tile. +_DENSE_FA4_HEAD_DIM = 128 +_DENSE_FA4_PAGE_SIZE = 128 +# FA4 loads whole V pages and masks only the scores, so P @ V still multiplies the rows past kv_len on a partial +# last page by zero: finite stale bytes add nothing, but an FP8 NaN byte (0x7F / 0xFF) left in a recycled page +# turns the tile's output NaN. Zeroing those rows first leaves every finite result bitwise unchanged. Kill switch: +# TRTLLM_MSA_DENSE_FA4_V_TAIL_ZERO=0. +_DENSE_FA4_V_TAIL_ZERO = os.environ.get("TRTLLM_MSA_DENSE_FA4_V_TAIL_ZERO", "1") != "0" +# What the patched flash_fwd_sm100 holds for the FP8 rescale threshold. +_DENSE_FA4_PATCH_MARKER = "0.0 if const_expr(self.q_dtype.width == 8) else" +# SM107: the FP8-KV prefill's E4M3 query is cast from the strided query rows of the fused QKV output by one Triton pass +# (row by row, 16-byte accesses) instead of the aten dtype-converting copy, whose strided path runs at ~1.2 TB/s. The +# cast rounds to nearest even and saturates to +-448: the bits of the aten cast wherever that is finite. Kill: +# TRTLLM_CTX_Q_E4M3_ROWS=0 in the deployment env (read once at import) restores the aten cast. +_SM107_Q_E4M3_ROWS = os.environ.get("TRTLLM_CTX_Q_E4M3_ROWS", "1") == "1" +_SM107_Q_E4M3_ROWS_LOGGED = [] + + +@triton.jit +def _rows_to_e4m3_kernel(x_ptr, y_ptr, row_stride, width, BLOCK: tl.constexpr): + row = tl.program_id(0).to(tl.int64) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + mask = cols < width + x = tl.load(x_ptr + row * row_stride + cols, mask=mask) + tl.store(y_ptr + row * width + cols, x.to(tl.float32).to(tl.float8e4nv), mask=mask) + + +def _q_to_e4m3(q: torch.Tensor) -> torch.Tensor: + """``q.to(torch.float8_e4m3fn)`` (contiguous); BF16 ``[rows, heads, head_dim]`` views whose rows are + contiguous take the Triton row cast.""" + if not ( + _SM107_Q_E4M3_ROWS + and q.is_cuda + and q.dtype == torch.bfloat16 + and q.dim() == 3 + and q.stride(2) == 1 + and q.stride(1) == q.shape[2] + and q.shape[0] > 0 + and get_sm_version() == 107 + ): + return q.to(torch.float8_e4m3fn) + rows, width = q.shape[0], q.shape[1] * q.shape[2] + out = torch.empty(q.shape, dtype=torch.float8_e4m3fn, device=q.device) + if not _SM107_Q_E4M3_ROWS_LOGGED: + _SM107_Q_E4M3_ROWS_LOGGED.append(True) + logger.info(f"[M3 dispatch] rank {mpi_rank()}: q_e4m3_rows taken at {rows} rows") + block = 1024 + _rows_to_e4m3_kernel[(rows, triton.cdiv(width, block))]( + q, out, q.stride(0), width, BLOCK=block, num_warps=4 + ) + return out + + if TYPE_CHECKING: from tensorrt_llm._torch.attention.backends.interface import AttentionForwardArgs from tensorrt_llm._torch.attention.backends.trtllm import ( @@ -155,6 +226,160 @@ def _aligned_nvfp4_dequant_scales( return k_global_scale, v_global_scale +def _nvfp4_sparse_out_kwargs(sparse: Any, out: torch.Tensor) -> dict[str, torch.Tensor]: + """``out=`` for sparse_atten_nvfp4_kv_func when its combine can write ``out`` in place (see the kill switch).""" + if ( + not _SM107_NVFP4_SPARSE_OUT_IN_PLACE + or get_sm_version() != 107 + or out.dtype != torch.bfloat16 + or not out.is_contiguous() + or not _nvfp4_sparse_takes_out(sparse) + ): + return {} + logger.info_once( + "MSA NVFP4 sparse prefill: combine writes the attention output in place (SM107)", + key="minimax_m3_sm107_nvfp4_sparse_out_in_place", + ) + return {"out": out} + + +def _nvfp4_sparse_takes_out(sparse: Any) -> bool: + """Whether the installed fmha_sm100 sparse_atten_nvfp4_kv_func accepts ``out`` (resolved once).""" + takes = getattr(_nvfp4_sparse_takes_out, "_cached", None) + if takes is None: + import inspect + + takes = "out" in inspect.signature(sparse.sparse_atten_nvfp4_kv_func).parameters + _nvfp4_sparse_takes_out._cached = takes + return takes + + +# Every sparse layer of a step builds its k2q CSR with the same sizes, so the +# non-identity build keeps one set of buffers keyed on the full step shape (reallocated when any size +# changes) and calls the fmha_sm100 extension directly, skipping the two Python validation layers and +# their six allocations. Same kernels in the same order on the same stream, and the stock builder also +# hands the kernels torch.empty buffers, so the CSR and schedule are unchanged. Eager only: a capturing +# stream takes the stock builder, and so does any stream other than the one the buffers were first built on +# (stream order is what keeps a step's later build from overwriting buffers an earlier attention still reads). +# SM107 only. Kill switch: TRTLLM_MSA_K2Q_WS=0. +_K2Q_WS = os.environ.get("TRTLLM_MSA_K2Q_WS", "1") != "0" +_K2Q_WS_BLK_KV = 128 +_K2Q_WS_TOPK = (4, 8, 16, 32) +_k2q_ws: Optional[tuple] = None # (key, q2k, row_ptr, q_idx, schedule) +_k2q_ws_stream: Optional[int] = None # the CUDA stream the buffers belong to + + +def _k2q_csr_ws( + kv_block_indexes: torch.Tensor, + cu_q: torch.Tensor, + cu_kv: torch.Tensor, + page_size: int, + *, + max_seqlen_k: int, + max_seqlen_q: int, + total_rows: int, + qhead_per_kv: int, +) -> Optional[tuple]: + """(k2q_row_ptr, k2q_q_indices, schedule) from per-shape buffers, or None for the stock builder.""" + global _k2q_ws, _k2q_ws_stream + total_q, head_kv, topk = (int(v) for v in kv_block_indexes.shape) + if ( + not _K2Q_WS + or get_sm_version() != 107 + or page_size != _K2Q_WS_BLK_KV + or topk not in _K2Q_WS_TOPK + or kv_block_indexes.dtype != torch.int32 + or total_q == 0 + or head_kv == 0 + or total_rows <= 0 + or torch.cuda.is_current_stream_capturing() + ): + return None + import sys + + utils = sys.modules.get("sparse_index_utils") + sched_mod = sys.modules.get("src.sm100.prepare_scheduler") + if utils is None or sched_mod is None: + return None + stream = torch.cuda.current_stream(kv_block_indexes.device).cuda_stream + if _k2q_ws_stream is not None and stream != _k2q_ws_stream: + return None + builder = utils._K2Q_CSR_BUILDER + max_kv_blocks = (max(max_seqlen_k, _K2Q_WS_BLK_KV) + _K2Q_WS_BLK_KV - 1) // _K2Q_WS_BLK_KV + device = kv_block_indexes.device + key = ( + device.index, + head_kv, + total_q, + topk, + total_rows, + max_kv_blocks, + max_seqlen_q, + qhead_per_kv, + ) + if _k2q_ws is None or _k2q_ws[0] != key: + model = sched_mod.SPARSE_SCHEDULE_MODEL + target = model.balanced_target_q_per_cta( + total_q=total_q, + topk=topk, + blk_kv=_K2Q_WS_BLK_KV, + head_kv=head_kv, + qhead_per_kv=qhead_per_kv, + device=device, + ) + capacity = model.flat_schedule_capacity( + total_rows=total_rows, + total_q=total_q, + topk=topk, + head_kv=head_kv, + target_q_per_cta=target, + ) + q_idx = torch.empty((head_kv, total_q * topk), dtype=torch.int32, device=device) + schedule = sched_mod.SparseAttentionSchedule( + enabled=True, + scheduler_metadata=torch.empty((capacity, 6), dtype=torch.int32, device=device), + work_count=torch.empty((1,), dtype=torch.int32, device=device), + qsplit_indices=torch.empty_like(q_idx), + split_counts=torch.empty((total_q, head_kv), dtype=torch.int32, device=device), + target_q_per_cta=target, + ) + q2k = torch.empty((head_kv, total_q, topk), dtype=torch.int32, device=device) + row_ptr = torch.empty((head_kv, total_rows + 1), dtype=torch.int32, device=device) + _k2q_ws = (key, q2k, row_ptr, q_idx, schedule) + _k2q_ws_stream = stream + _, q2k_buf, row_ptr, q_idx, schedule = _k2q_ws + # The indexer's storage is already head-major on pure-context steps, where the stock .contiguous() is a + # no-op; only a strided (mixed-step) view is copied, into the reused buffer. + q2k = kv_block_indexes.permute(1, 0, 2) + if not q2k.is_contiguous(): + q2k = q2k_buf.copy_(q2k) + builder._ensure_loaded() + with torch.cuda.nvtx.range("SparseK2qCsr_Pipeline"): + builder._run_with_schedule( + q2k, + cu_q, + cu_kv, + row_ptr, + q_idx, + schedule.scheduler_metadata, + schedule.work_count, + schedule.qsplit_indices, + schedule.split_counts, + topk, + _K2Q_WS_BLK_KV, + total_rows, + max_kv_blocks, + schedule.target_q_per_cta, + schedule.work_capacity, + max_seqlen_q, + ) + logger.info_once( + "MSA NVFP4 sparse prefill: k2q CSR build reuses per-shape buffers (TRTLLM_MSA_K2Q_WS)", + key="minimax_m3_msa_k2q_ws", + ) + return row_ptr, q_idx, schedule + + def run_msa_nvfp4_sparse_gqa( q: torch.Tensor, k_paged: torch.Tensor, @@ -245,6 +470,23 @@ def run_msa_nvfp4_sparse_gqa( and cached[1] == csr_key ): k2q_row_ptr, k2q_q_indices, schedule = cached[2] + elif ( + identity is None + and ( + built := _k2q_csr_ws( + kv_block_indexes, + cu_q, + cu_kv, + page_size, + max_seqlen_k=max_kv_len, + max_seqlen_q=max_q_len, + total_rows=total_k_rows, + qhead_per_kv=int(q.shape[1]) // int(k_paged.shape[1]), + ) + ) + is not None + ): + k2q_row_ptr, k2q_q_indices, schedule = built else: q2k = kv_block_indexes.permute(1, 0, 2).contiguous() k2q_row_ptr, k2q_q_indices, schedule = sparse.build_k2q_csr( @@ -261,6 +503,11 @@ def run_msa_nvfp4_sparse_gqa( ) if identity is not None: metadata._msa_identity_csr = (identity, csr_key, (k2q_row_ptr, k2q_q_indices, schedule)) + from .msa_combine_mxfp8 import combine_kwargs, publish + + out_kwargs = _nvfp4_sparse_out_kwargs(sparse, out) + # Host CTX (b): the combine also writes the o_proj input as MXFP8 when the attention module armed it. + mxfp8_kwargs = combine_kwargs(sparse, out, metadata, in_place=bool(out_kwargs)) result = sparse.sparse_atten_nvfp4_kv_func( q, k_paged.view(torch.uint8), @@ -284,8 +531,190 @@ def run_msa_nvfp4_sparse_gqa( page_table=metadata.msa_block_table[:batch], seqused_k=metadata.msa_seq_lens_cuda[:batch], schedule=schedule, + **out_kwargs, + **(mxfp8_kwargs or {}), + ) + if result is not out: + out.copy_(result) + if mxfp8_kwargs is not None: + publish(out, mxfp8_kwargs) + + +@functools.lru_cache(maxsize=None) +def _dense_fa4_forward(): + """Return FA4's forward entry point, or None where the path is off or the FA4 lacks the FP8 rescale change.""" + if not _DENSE_PREFILL_FA4: + return None + try: + import inspect + + from ..sparse.minimax_m3.kernels.msa_utils import _install_msa_cutlass_compatibility + + # flash_attn.cute (via quack) still names cute.core.ThrMma / ThrCopy, which this CUTLASS DSL moved to the + # top level. The MSA import path installs those aliases; install them here too, so the import does not + # depend on fmha_sm100 having been loaded first. + _install_msa_cutlass_compatibility() + from flash_attn.cute import flash_fwd_sm100 + from flash_attn.cute.interface import _flash_attn_fwd + except Exception as exc: # noqa: BLE001 - any import failure keeps fmha_sm100 + logger.warning(f"MiniMax-M3 dense prefill: FA4 unavailable ({exc!r}); keeping fmha_sm100") + return None + if _DENSE_FA4_PATCH_MARKER not in inspect.getsource(flash_fwd_sm100): + logger.warning( + "MiniMax-M3 dense prefill: FA4 lacks the FP8 rescale_threshold 0.0 change; keeping fmha_sm100" + ) + return None + return _flash_attn_fwd + + +def dense_prefill_fa4_enabled(use_fp8: bool, head_dim: int, page_size: int) -> bool: + """Whether FP8 dense prefill runs FA4 rather than fmha_sm100. + + prepare() asks too, to skip the dense fmha_sm100 plan the FA4 path never reads. + """ + return ( + use_fp8 + and head_dim == _DENSE_FA4_HEAD_DIM + and page_size == _DENSE_FA4_PAGE_SIZE + # Rubin only: FA4 rounds differently from fmha_sm100 (deterministic, not bitwise), so other SM10x keep it. + and get_sm_version() == 107 + and _dense_fa4_forward() is not None + ) + + +def _v_tail_zero_safe(kv_cache_manager: Any) -> bool: + """Whether every row's partial last page is its own, so zeroing past kv_len cannot touch another row's tokens. + + True without block reuse or partial reuse, or when a partially matched block is copied on reuse: + KVCacheManagerV2 always copies it, and KVCacheManager does with copy_on_partial_reuse. + """ + from tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2 import KVCacheManagerV2 + + if not getattr(kv_cache_manager, "enable_block_reuse", True) or not getattr( + kv_cache_manager, "enable_partial_reuse", True + ): + return True + if isinstance(kv_cache_manager, KVCacheManagerV2): + return True + return bool(getattr(kv_cache_manager, "copy_on_partial_reuse", False)) + + +def _zero_partial_page_v_tail( + v_paged: torch.Tensor, page_table: torch.Tensor, kv_rows: torch.Tensor +) -> None: + """Zero the V rows at and past each row's kv_len on its partial last page. + + v_paged is the cache's HND V [pages, heads, page, d]; page_table the rows' block table; kv_rows the host + kv_len per row. Those slots hold no token of the row yet and are rewritten when the sequence grows into them. + """ + page_size = int(v_paged.shape[2]) + tails = [(row, n) for row, n in enumerate(kv_rows.tolist()) if n % page_size] + if not tails: + return + host = torch.empty(3, len(tails), dtype=torch.int64, pin_memory=prefer_pinned()) + for i, (row, n) in enumerate(tails): + host[0, i] = row + host[1, i] = n // page_size + host[2, i] = n % page_size + dev = host.to(v_paged.device, non_blocking=True) + pages = page_table[dev[0], dev[1]].long() + v_bytes = v_paged.view(torch.uint8) + tail_pages = v_bytes[pages] + past = torch.arange(page_size, device=v_paged.device)[None, :] >= dev[2][:, None] + tail_pages.masked_fill_(past[:, None, :, None], 0) + v_bytes[pages] = tail_pages + + +_dense_fa4_warm: set = set() + + +def _run_dense_fa4( + q_view: torch.Tensor, + k_paged: torch.Tensor, + v_paged: torch.Tensor, + metadata: "TrtllmAttentionMetadata", + *, + row_first: int, + num_rows: int, + sm_scale: float, + out_view: torch.Tensor, +) -> bool: + """Run FP8 dense causal prefill with FA4 into out_view; False (nothing run) where it cannot serve the rows. + + K/V are the cache's HND pages viewed as FA4's (pages, page, heads, d), so nothing is gathered. Each row + attends its first kv_len tokens through the 2-D block table, with its queries the last qo_len of them + (FA4's bottom-right causal, the same alignment as the qo_offset = kv_len - qo_len the plans take). + """ + qo_lens = metadata.msa_qo_lens_cpu + kv_lens = metadata.msa_kv_lens_cpu + if qo_lens is None or kv_lens is None or out_view.dtype != torch.bfloat16: + return False + if _DENSE_FA4_V_TAIL_ZERO and not _v_tail_zero_safe(metadata.kv_cache_manager): + logger.warning_once( + "MiniMax-M3 dense prefill: FA4 needs a private partial last page to zero its V tail, but this KV cache " + "can share a partially reused page without copying it; keeping fmha_sm100 " + "(TRTLLM_MSA_DENSE_FA4_V_TAIL_ZERO=0 runs FA4 without the zeroing)", + key="minimax_m3_dense_prefill_fa4_v_tail_unsafe", + ) + return False + qo_rows = qo_lens[row_first : row_first + num_rows] + kv_rows = kv_lens[row_first : row_first + num_rows] + # One pinned host staging for both length tensors: cu_seqlens_q then seqused_k. + host = torch.empty(2 * num_rows + 1, dtype=torch.int32, pin_memory=prefer_pinned()) + host[0] = 0 + torch.cumsum(qo_rows, 0, dtype=torch.int32, out=host[1 : num_rows + 1]) + if int(host[num_rows]) != int(q_view.shape[0]): + return False + host[num_rows + 1 :].copy_(kv_rows) + lens = host.to(q_view.device, non_blocking=True) + max_seqlen_q = int(qo_rows.max()) + fwd = _dense_fa4_forward() + k = k_paged.permute(0, 2, 1, 3) + v = v_paged.permute(0, 2, 1, 3) + num_kv_heads = int(k_paged.shape[1]) + warm_key = (int(q_view.shape[1]), num_kv_heads, q_view.device.index) + if warm_key not in _dense_fa4_warm: + # FA4 compiles per variant on first use, and the variant depends on whether a row's packed queries + # (max_seqlen_q x the GQA group) fill more than one 128-row tile. The first call is the server warmup, + # so compile both there, on one-token requests over the first page, rather than in a served step. + group = int(q_view.shape[1]) // num_kv_heads + for rows_q in (1, 128 // group + 1): + fwd( + q_view.new_zeros(rows_q, q_view.shape[1], q_view.shape[2]), + k, + v, + cu_seqlens_q=torch.tensor([0, rows_q], dtype=torch.int32, device=q_view.device), + seqused_k=torch.tensor([rows_q], dtype=torch.int32, device=q_view.device), + max_seqlen_q=rows_q, + page_table=torch.zeros(1, 1, dtype=torch.int32, device=q_view.device), + softmax_scale=sm_scale, + causal=True, + ) + _dense_fa4_warm.add(warm_key) + logger.info_once( + "MiniMax-M3 dense prefill: FA4 (flash_attn.cute, FP8 P without lazy rescale) over the paged FP8 KV cache", + key="minimax_m3_dense_prefill_fa4", ) - out.copy_(result) + page_table = metadata.msa_block_table[row_first : row_first + num_rows] + if _DENSE_FA4_V_TAIL_ZERO: + _zero_partial_page_v_tail(v_paged, page_table, kv_rows) + logger.info_once( + "MiniMax-M3 dense prefill: FA4 V tail past kv_len zeroed on partial pages", + key="minimax_m3_dense_prefill_fa4_v_tail", + ) + fwd( + q_view, + k, + v, + cu_seqlens_q=lens[: num_rows + 1], + seqused_k=lens[num_rows + 1 :], + max_seqlen_q=max_seqlen_q, + page_table=page_table, + softmax_scale=sm_scale, + causal=True, + out=out_view, + ) + return True def run_msa_prefill_gqa( @@ -350,7 +779,7 @@ def run_msa_prefill_gqa( # KV-cache scales, so the scale is 1.0 and this is a plain E4M3 cast. use_fp8 = k_paged.dtype == torch.float8_e4m3fn if use_fp8: - q_view = q_view.to(torch.float8_e4m3fn) + q_view = _q_to_e4m3(q_view) def rows_of(lens: Optional[torch.Tensor]) -> Optional[torch.Tensor]: """Narrow a per-request host length tensor to this phase's rows. @@ -362,6 +791,22 @@ def rows_of(lens: Optional[torch.Tensor]) -> Optional[torch.Tensor]: return None return lens[row_first : row_first + num_rows] + if ( + kv_block_indexes is None + and dense_prefill_fa4_enabled(use_fp8, head_dim, int(k_paged.shape[2])) + and _run_dense_fa4( + q_view, + k_paged, + v_paged, + metadata, + row_first=row_first, + num_rows=num_rows, + sm_scale=sm_scale, + out_view=out_view, + ) + ): + return + run_msa_sparse_gqa( q_view, k_paged, @@ -454,4 +899,9 @@ def run_context(self, params: FmhaParams) -> None: ) -__all__ = ["MsaPrefillFmha", "run_msa_prefill_gqa", "run_msa_sparse_gqa"] +__all__ = [ + "MsaPrefillFmha", + "dense_prefill_fa4_enabled", + "run_msa_prefill_gqa", + "run_msa_sparse_gqa", +] diff --git a/tensorrt_llm/_torch/attention/backends/fmha/registry.py b/tensorrt_llm/_torch/attention/backends/fmha/registry.py index f9d666243a14..6542d561bde0 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/registry.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/registry.py @@ -34,6 +34,7 @@ def init_fmha_libs() -> dict[str, "FmhaCls"]: scope, so backends can import trtllm attention classes at module scope without an import cycle. """ + from .drafter_last_row import DrafterLastRowContextFmha from .flashinfer_sparse_mla import FlashInferSparseMlaFmha from .gqa_decode import ( GqaDecodeFmha, @@ -48,6 +49,9 @@ def init_fmha_libs() -> dict[str, "FmhaCls"]: from .prims_ts_sparse_mla import PrimsTSSparseMlaFmha return { + # Available only on the attention backend a model marks with + # mark_drafter_last_row_attention, ahead of the libraries it shortens. + "drafter_last_row": DrafterLastRowContextFmha, "fp4_mla": Fp4MlaFmha, "triton_custom_mask": TritonCustomMaskFmha, "cute_dsl_mla": CuteDslMlaFmha, diff --git a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/kernels/msa_utils.py b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/kernels/msa_utils.py index 774c21d88126..86fe47736fd9 100644 --- a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/kernels/msa_utils.py +++ b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/kernels/msa_utils.py @@ -6,13 +6,14 @@ import functools import importlib.util +import os import types from typing import Optional, Tuple import torch from tensorrt_llm._torch.attention.backends.interface import AttentionInputType -from tensorrt_llm._utils import is_sm_100f, maybe_pin_memory +from tensorrt_llm._utils import get_sm_version, is_sm_100f, maybe_pin_memory from .paged_cache import write_kv_slots @@ -225,6 +226,45 @@ def build_kv_page_indices( return maybe_pin_memory(block_ids_cpu[row, col].to(torch.int32)) +# per_token_valid_blocks runs on every step's metadata preparation: the same integer arithmetic as one NumPy pass +# instead of about a dozen small CPU torch ops (the same int64 values, returned as a torch.long tensor). +# SM107 only. Kill switch: TRTLLM_MSA_PTVB_NUMPY=0. +_PER_TOKEN_VALID_BLOCKS_NUMPY = os.environ.get("TRTLLM_MSA_PTVB_NUMPY", "1") != "0" +_PER_TOKEN_VALID_BLOCKS_NUMPY_LOGGED = False + + +def _per_token_valid_blocks_numpy( + qo_lens_cpu: torch.Tensor, + kv_lens_cpu: torch.Tensor, + qo_offset_cpu: Optional[torch.Tensor], + *, + causal: bool, + block_size: int, +) -> torch.Tensor: + import numpy as np + + qo = qo_lens_cpu.numpy().astype(np.int64) + total = int(qo.sum()) + if total == 0: + return torch.zeros(0, dtype=torch.long) + kv = kv_lens_cpu.numpy().astype(np.int64) + batch_row = np.repeat(np.arange(qo.shape[0], dtype=np.int64), qo) + starts = np.zeros(qo.shape[0], dtype=np.int64) + if qo.shape[0] > 1: + starts[1:] = np.cumsum(qo)[:-1] + kv_per = kv[batch_row] + if causal: + intra = np.arange(total, dtype=np.int64) - starts[batch_row] + if qo_offset_cpu is not None: + off = qo_offset_cpu.numpy().astype(np.int64)[batch_row] + else: + off = (kv - qo)[batch_row] + eff = np.minimum(off + intra + 1, kv_per) + else: + eff = kv_per + return torch.from_numpy((eff + block_size - 1) // block_size) + + def per_token_valid_blocks( qo_lens_cpu: torch.Tensor, kv_lens_cpu: torch.Tensor, @@ -238,6 +278,18 @@ def per_token_valid_blocks( Expands per-request lengths and offsets to a per-token vector so block selection can honour each query token's own causal extent. """ + if _PER_TOKEN_VALID_BLOCKS_NUMPY and get_sm_version() == 107: + global _PER_TOKEN_VALID_BLOCKS_NUMPY_LOGGED + if not _PER_TOKEN_VALID_BLOCKS_NUMPY_LOGGED: + _PER_TOKEN_VALID_BLOCKS_NUMPY_LOGGED = True + from tensorrt_llm.logger import logger + + logger.info( + "MSA per_token_valid_blocks: NumPy pass engaged (kill TRTLLM_MSA_PTVB_NUMPY=0)" + ) + return _per_token_valid_blocks_numpy( + qo_lens_cpu, kv_lens_cpu, qo_offset_cpu, causal=causal, block_size=block_size + ) qo = qo_lens_cpu.to(torch.long) kv = kv_lens_cpu.to(torch.long) batch = int(qo.shape[0]) diff --git a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py index 73e492fd2649..9cc31b6d5ce4 100644 --- a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py +++ b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py @@ -31,6 +31,8 @@ from __future__ import annotations +import functools +import os from dataclasses import dataclass from typing import NamedTuple, Optional, Tuple @@ -41,7 +43,7 @@ from tensorrt_llm._torch.pyexecutor import h2d_cache, step_inputs from tensorrt_llm._torch.pyexecutor.h2d_cache import copy_h2d_if_changed, copy_h2d_pool_shared from tensorrt_llm._torch.pyexecutor.runtime_hooks import MsaRuntimePolicy -from tensorrt_llm._utils import maybe_pin_memory +from tensorrt_llm._utils import get_sm_version, maybe_pin_memory, mpi_rank from tensorrt_llm.bindings import DataType from tensorrt_llm.logger import logger from tensorrt_llm.models.modeling_utils import QuantConfig @@ -66,6 +68,12 @@ ) from .msa_indexer import MsaIndexer, cutedsl_score_runner, segmented_proxy_plan +# The short-prefill identity table is materialized with a plain copy, so the sparse prefill that follows the layer's +# producer (which can trigger its dependents before its last Q/KV stores) never starts before those stores land. +# Bitwise the same table. SM107 only (the producer is). Kill switch: TRTLLM_MSA_IDENTITY_SERIALIZE=0 returns the +# expanded view. +_IDENTITY_SERIALIZE = os.environ.get("TRTLLM_MSA_IDENTITY_SERIALIZE", "1") != "0" + def _cache_device(meta) -> torch.device: """Device hosting the paged KV buffers, else the current CUDA device.""" @@ -131,6 +139,125 @@ def _fill_unused_slots(buf: torch.Tensor, start: int) -> None: h2d_cache.fill_tail_pool_shared(buf, start, -1) +# SM107: run the indexer proxy (the fmha_sm100 max-score pass) as rows of at most +# _PROXY_SEGMENT_TOKENS query tokens planned with fmha_sm100's own split-KV choice, instead of +# one row per request and one split. The proxy writes one max score per (index head, key tile, +# query token) and no attention output, and each token's scores depend only on that token's +# query and its causal key range. Cutting a request's chunk into consecutive rows of the same +# sequence and splitting their key ranges across CTAs therefore gives bitwise-identical scores, +# while a chunk over a long cached prefix spreads across the GPU instead of a few CTAs (rows +# longer than the 128-token query tile cannot be split at all). False keeps one row per request +# and num_kv_splits=1. +_SM107_PROXY_AUTO_KV_SPLITS = True +# fmha_sm100's 128-token query tile, the largest that admits split-KV. +_PROXY_SEGMENT_TOKENS = 128 + + +def _proxy_segmented() -> bool: + """Whether this GPU runs the prefill indexer proxy segmented and split.""" + if _SM107_PROXY_AUTO_KV_SPLITS and get_sm_version() == 107: + logger.info_once( + "MSA indexer proxy: segmented rows with planner-chosen split-KV (SM107)", + key="msa_proxy_auto_kv_splits", + ) + return True + return False + + +# SM107: a proxy plan over at most _PROXY_FEW_ROWS_MAX_ROWS rows (small chunks appended to a long +# cached prefix) asks for SM count // rows key splits instead of the planner's choice, which stops at +# 64 and leaves every CTA a long serial key range (165k cached: 175 -> 20 us per layer). The proxy +# writes one max score per key tile, so any key split gives bitwise-identical scores. False keeps the +# planner's choice. +_SM107_PROXY_FEW_ROWS_KV_SPLITS = True +_PROXY_FEW_ROWS_MAX_ROWS = 4 + + +@functools.lru_cache(maxsize=None) +def _sm_count(device_index: int) -> int: + return torch.cuda.get_device_properties(device_index).multi_processor_count + + +def proxy_kv_splits(num_rows: int, device: torch.device) -> int: + """num_kv_splits for a proxy plan over num_rows rows: -1 (the planner's choice) unless SM107 few-row.""" + if ( + not _SM107_PROXY_FEW_ROWS_KV_SPLITS + or get_sm_version() != 107 + or num_rows > _PROXY_FEW_ROWS_MAX_ROWS + ): + return -1 + splits = max(1, _sm_count(device.index or 0) // max(num_rows, 1)) + logger.info_once( + f"[M3 dispatch] rank {mpi_rank()}: proxy_few_rows_kv_splits taken at {num_rows} rows", + key="msa_proxy_few_rows_kv_splits", + ) + return splits + + +def proxy_segment_rows( + qo_lens_cpu: torch.Tensor, + kv_lens_cpu: torch.Tensor, + qo_offset_cpu: torch.Tensor, + segment_tokens: int, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Cut each request's query rows into consecutive rows of at most segment_tokens. + + Segment j of a request covers its query tokens [j * segment_tokens, end) and keeps the + causal key range those tokens see: the request's kv_len shortened by the tokens after the + segment, and its qo_offset advanced to the segment's first token. Requests with no query + tokens contribute no rows. Returns host int32 (qo_lens, kv_lens, qo_offset) and the int64 + source request of every segment, in token order. + """ + seg_qo, seg_kv, seg_off, seg_src = [], [], [], [] + for row, (q, kv, off) in enumerate( + zip(qo_lens_cpu.tolist(), kv_lens_cpu.tolist(), qo_offset_cpu.tolist()) + ): + for start in range(0, q, segment_tokens): + end = min(start + segment_tokens, q) + seg_qo.append(end - start) + seg_kv.append(kv - (q - end)) + seg_off.append(off + start) + seg_src.append(row) + as_i32 = lambda values: torch.tensor(values, dtype=torch.int32) # noqa: E731 + return ( + as_i32(seg_qo), + as_i32(seg_kv), + as_i32(seg_off), + torch.tensor(seg_src, dtype=torch.long), + ) + + +def proxy_segment_page_ranges( + kv_lens_cpu: torch.Tensor, seg_kv: torch.Tensor, seg_src: torch.Tensor, page_size: int +) -> Tuple[torch.Tensor, torch.Tensor]: + """Locate each segment's pages in the flat per-request page table (build_kv_page_indices). + + Request r's pages start at the sum of the earlier requests' page counts, and a segment + needs the first ceil(seg_kv / page_size) of them. Returns host int64 (starts, counts). + """ + pages = ((kv_lens_cpu.to(torch.long) + (page_size - 1)) // page_size).clamp_(min=0) + request_start = torch.cumsum(pages, 0) - pages + counts = (seg_kv.to(torch.long) + (page_size - 1)) // page_size + return request_start.index_select(0, seg_src), counts + + +def gather_page_ranges( + flat: torch.Tensor, starts: torch.Tensor, counts: torch.Tensor, total: int, out: torch.Tensor +) -> None: + """Write the concatenation of flat[start : start + count] for every range to out[:total]. + + Runs on flat's device with no host synchronization: the index is expanded on the device + from the per-range starts and counts, so only those two short vectors are copied over. + """ + device = flat.device + starts = maybe_pin_memory(starts).to(device, non_blocking=True) + counts = maybe_pin_memory(counts).to(device, non_blocking=True) + range_first = torch.cumsum(counts, 0) - counts + index = torch.repeat_interleave(starts - range_first, counts, output_size=total) + index += torch.arange(total, device=device) + torch.index_select(flat, 0, index, out=out[:total]) + + class MsaDecodeSpan(NamedTuple): """Generation rows served by MiniMax-M3's dedicated decode kernels. @@ -187,6 +314,12 @@ class MiniMaxM3MsaSparseAttentionMetadata(TrtllmAttentionMetadata): dict[int, tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]] ] = None msa_kv_indices: Optional[torch.Tensor] = None + # The flattened page table of this step's segmented proxy rows (see proxy_segment_rows): + # one copy of a request's page prefix per segment. Staged only on steps whose proxy plan + # is segmented; _msa_proxy_segments holds those rows for _build_step_plans. + msa_proxy_kv_indices: Optional[torch.Tensor] = None + _msa_proxy_segments: Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = None + _msa_proxy_segmented_plan: bool = False msa_max_score: Optional[torch.Tensor] = None msa_n_valid_blocks: Optional[torch.Tensor] = None # Decode-step preparation the model opted into (RuntimeHooks.msa). @@ -324,6 +457,13 @@ def as_pinned_int32(lens: torch.Tensor) -> torch.Tensor: # The attention plans cover the context rows; the proxy plan covers # whatever rows the CuTe DSL scorer did not take. See _msa_attn_plan_rows # and _msa_proxy_plan_rows. + @property + def msa_proxy_page_table(self) -> Optional[torch.Tensor]: + """The flattened page table the indexer proxy plan of this step indexes.""" + if self._msa_proxy_segmented_plan: + return self.msa_proxy_kv_indices + return self.msa_kv_indices + @property def msa_prefill_proxy_plan(self) -> Optional[tuple]: """Prebuilt indexer proxy plan for this step's fmha_sm100 rows.""" @@ -507,6 +647,17 @@ def _create_msa_buffers(self) -> None: dtype=torch.int32, capture_graph=capture_graph, ) + if _proxy_segmented(): + # Every segment repeats its request's page prefix: at most one segment per + # _PROXY_SEGMENT_TOKENS new tokens plus one partial segment per request. + max_segments = -(-max_num_tokens // _PROXY_SEGMENT_TOKENS) + max_num_sequences + self.msa_proxy_kv_indices = self.get_empty( + buffers, + (max_segments * max_blocks_per_seq,), + cache_name="msa_proxy_kv_indices", + dtype=torch.int32, + capture_graph=capture_graph, + ) self.msa_block_table = self.get_empty( buffers, (max_num_sequences, max_blocks_per_seq), @@ -1088,7 +1239,9 @@ def _build_step_plans(self) -> None: # flag. use_fp8 = self._msa_main_kv_is_fp8() - def plan_for(rows: Optional[Tuple[int, int]], **plan_kwargs) -> Optional[tuple]: + def plan_for( + rows: Optional[Tuple[int, int]], num_kv_splits: int = 1, **plan_kwargs + ) -> Optional[tuple]: """Plan one site over the given rows, or None where it has none. Slicing keeps the length tensors' pinned backing, so a single-phase @@ -1103,7 +1256,7 @@ def plan_for(rows: Optional[Tuple[int, int]], **plan_kwargs) -> Optional[tuple]: kv_lens_cpu if whole else kv_lens_cpu[first:last], qo_offset=qo_offset_cpu if whole else qo_offset_cpu[first:last], page_size=page_size, - num_kv_splits=1, + num_kv_splits=num_kv_splits, causal=True, **plan_kwargs, ) @@ -1123,23 +1276,39 @@ def plan_for(rows: Optional[Tuple[int, int]], **plan_kwargs) -> Optional[tuple]: # A short pure-prefill step selects every valid block, so it needs none. # Otherwise its rows are a batch prefix, so their pages prefix msa_kv_indices. proxy_rows = None if short_prefill else self._msa_proxy_plan_rows() - segmented = proxy_rows is not None and segmented_proxy_plan( - fmha_sm100, - qo_lens_cpu[: proxy_rows[1]], - qo_offset_cpu[: proxy_rows[1]], - num_index_heads=num_index_heads, - page_size=page_size, - kv_indices=self.msa_kv_indices, - ) - if segmented: - self._msa_prefill_proxy_plan, self._msa_prefill_proxy_kv_indices = segmented - else: - self._msa_prefill_proxy_plan = plan_for( - proxy_rows, - num_qo_heads=num_index_heads, - num_kv_heads=1, + segments = None if short_prefill else self._msa_proxy_segments + self._msa_proxy_segmented_plan = segments is not None + if segments is not None: + seg_qo, seg_kv, seg_off = segments + self._msa_prefill_proxy_plan = fmha_sm100.fmha_sm100_plan( + seg_qo, seg_kv, qo_offset=seg_off, page_size=page_size, + num_kv_splits=proxy_kv_splits(int(seg_qo.shape[0]), _cache_device(self)), + causal=True, num_qo_heads=num_index_heads, num_kv_heads=1, output_maxscore=True, ) + self._msa_prefill_proxy_kv_indices = self.msa_proxy_kv_indices + else: + segmented = proxy_rows is not None and segmented_proxy_plan( + fmha_sm100, + qo_lens_cpu[: proxy_rows[1]], + qo_offset_cpu[: proxy_rows[1]], + num_index_heads=num_index_heads, + page_size=page_size, + kv_indices=self.msa_kv_indices, + ) + if segmented: + self._msa_prefill_proxy_plan, self._msa_prefill_proxy_kv_indices = segmented + else: + self._msa_prefill_proxy_plan = plan_for( + proxy_rows, + num_kv_splits=( + proxy_kv_splits(proxy_rows[1] - proxy_rows[0], _cache_device(self)) + if proxy_rows is not None and self.msa_proxy_kv_indices is not None else 1 + ), + num_qo_heads=num_index_heads, + num_kv_heads=1, + output_maxscore=True, + ) attn_rows = self._msa_attn_plan_rows() # Sparse layers: kv_block_num=topk limits attention to top-k blocks. # NVFP4 sparse layers run the MSA CSR kernel, which takes no plan. @@ -1150,9 +1319,16 @@ def plan_for(rows: Optional[Tuple[int, int]], **plan_kwargs) -> Optional[tuple]: kv_block_num=params.topk, use_fp8_kvcache=use_fp8, ) - # Dense layers: no kv_block_num, so the full page table is attended. + # Dense layers: no kv_block_num, so the full page table is attended. FP8 dense prefill on FA4 reads no + # plan, so none is built. + from tensorrt_llm._torch.attention.backends.fmha.msa_prefill import ( + dense_prefill_fa4_enabled, + ) + self._msa_prefill_dense_plan = plan_for( - attn_rows, + None + if dense_prefill_fa4_enabled(use_fp8, MSA_REQUIRED_HEAD_DIM, page_size) + else attn_rows, num_qo_heads=num_q_heads, num_kv_heads=num_kv_heads, use_fp8_kvcache=use_fp8, @@ -1169,6 +1345,47 @@ def plan_for(rows: Optional[Tuple[int, int]], **plan_kwargs) -> Optional[tuple]: table = torch.where(ar[None, :] < dev_buf[:total_q, None], ar[None, :], -1) self._msa_prefill_identity = table + def _stage_proxy_segments(self, page_size: int, needs_flat_page_table: bool) -> None: + """Stage the segmented proxy rows and their page table, where they change anything. + + Only on SM107 (see _SM107_PROXY_AUTO_KV_SPLITS) and only when some proxy row has more + query tokens than one segment: otherwise the segments are the requests themselves and + the plain page table already serves the proxy. + + The segmented page table is gathered on the device from msa_kv_indices, which the + caller has just staged. Segmented steps have context rows, so they are never a replay + of a captured decode graph and no step-input pack defers that copy past this gather. + """ + self._msa_proxy_segments = None + if self.msa_proxy_kv_indices is None or not needs_flat_page_table: + return + rows = self._msa_proxy_plan_rows() + if rows is None: + return + first, last = rows + qo_lens = self.msa_qo_lens_cpu[first:last] + if int(qo_lens.max()) <= _PROXY_SEGMENT_TOKENS: + return + # Proxy rows are always a batch prefix, so they index msa_kv_indices from its start. + assert first == 0, "the indexer proxy covers a prefix of the batch" + kv_lens = self.msa_kv_lens_cpu[first:last] + seg_qo, seg_kv, seg_off, seg_src = proxy_segment_rows( + qo_lens, kv_lens, self.msa_qo_offset_cpu[first:last], _PROXY_SEGMENT_TOKENS + ) + starts, counts = proxy_segment_page_ranges(kv_lens, seg_kv, seg_src, page_size) + total = int(counts.sum()) + if total > self.msa_proxy_kv_indices.shape[0]: + raise ValueError( + f"MSA proxy kv_indices buffer ({self.msa_proxy_kv_indices.shape[0]}) is " + f"smaller than the step's segmented page count ({total})." + ) + gather_page_ranges(self.msa_kv_indices, starts, counts, total, self.msa_proxy_kv_indices) + self._msa_proxy_segments = ( + maybe_pin_memory(seg_qo), + maybe_pin_memory(seg_kv), + maybe_pin_memory(seg_off), + ) + def _build_msa_fields(self) -> None: """Populate the MSA cache-write buffers for this step. @@ -1178,6 +1395,7 @@ def _build_msa_fields(self) -> None: decoding the inputs for on_update_kv_lens are staged as well. """ self._msa_fields_ready = False + self._msa_proxy_segments = None # Set again below once this step's live slots are staged; until then the forward fills nothing. self._msa_tail_start = None if not self._msa_buffers_ready: @@ -1264,6 +1482,7 @@ def _build_msa_fields(self) -> None: _fill_unused_slots(self.msa_out_cache_loc, total_new_tokens) if kv_indices is not None: step_inputs.copy_(self.msa_kv_indices[: int(kv_indices.shape[0])], kv_indices) + self._stage_proxy_segments(page_size, needs_flat_page_table) # 2-D page table and per-request length for the decode kernels, # from the same host block ids the flat page table was built from. @@ -1692,7 +1911,14 @@ def run_indexer( if span is None and identity is not None and int(identity.shape[0]) == num_tokens: # Short pure-prefill step: every token selects all its valid blocks (staged once per step). num_kv_heads = int(self.indexer.config.num_kv_heads) - return identity.unsqueeze(1).expand(num_tokens, num_kv_heads, int(identity.shape[1])) + table = identity.unsqueeze(1).expand(num_tokens, num_kv_heads, int(identity.shape[1])) + if not _IDENTITY_SERIALIZE or get_sm_version() != 107: + return table + logger.info_once( + f"[CTX] identity_serialize taken T={num_tokens}", + key="minimax_m3_identity_serialize", + ) + return table.contiguous() block_table = None seq_lens_cuda = None decode_query_len = None diff --git a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py index 6e9813d62e72..9f7fe6d98826 100644 --- a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py +++ b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py @@ -15,12 +15,15 @@ import functools from types import ModuleType +import os from typing import TYPE_CHECKING, Optional import torch from tensorrt_llm._torch.attention.backends.fmha.utils import get_multi_processor_count_for_device from tensorrt_llm._utils import async_tensor_h2d +from tensorrt_llm._utils import get_sm_version +from tensorrt_llm.logger import logger from .kernels.msa_utils import ( MSA_REQUIRED_HEAD_DIM, @@ -33,6 +36,22 @@ if TYPE_CHECKING: from .common import MiniMaxM3SparseConfig +# SM107: take the top-16 of prefill steps with the tile select (minimax_m3_select_prefill_tile), which reads each +# 32-byte sector of the head-major scores once for 8 queries; the in-tree selector reads one score per sector per +# pass. Same top-16 set (see the op). Kill switch: False keeps every step on minimax_m3_select_blocks. +_SM107_TILE_SELECT = os.environ.get("TRTLLM_MSA_TILE_SELECT", "1") == "1" +# Below this many query rows the in-tree selector's one-CTA-per-row grid is at least as fast. +_SM107_TILE_SELECT_MIN_Q = 256 +# The op's shared-memory bound (kMinimaxM3SelectPrefillTileMaxBlocks). +_SM107_TILE_SELECT_MAX_BLOCKS = 5856 +# The prefill proxy scores into an unfilled buffer: fmha_sm100 would allocate it with torch.full(-inf), but its +# OnlyScore kernel writes every [head, block, token] with block below the token's causal block count (masked rows of a +# tile as -inf), and the selectors read only those. +# mega1: OFF by default (fmha_sm100's -inf fill, stock) while the random-first-token CTX bug is root-caused: with +# recycled buffers an entry the kernel does not write would hold the previous request's scores. +# TRTLLM_MSA_PROXY_NO_FILL=1 re-enables the unfilled buffer. +_PROXY_SCORES_NO_FILL = os.environ.get("TRTLLM_MSA_PROXY_NO_FILL", "0") == "1" + @functools.lru_cache(maxsize=1) def cutedsl_score_runner(): @@ -104,6 +123,24 @@ def _cutedsl_score( return True +def _unfilled_max_score(plan: tuple, idx_q: torch.Tensor) -> Optional[torch.Tensor]: + """The proxy's [num_index_heads, max_k_tiles, total_q] float32 max-score buffer, unfilled. + + Shaped from the plan as fmha_sm100 shapes its own; None when the plan does not carry that geometry (a step split + into decode and prefill parts), which keeps fmha_sm100's allocation. + """ + info = plan[3] if isinstance(plan, tuple) and len(plan) > 3 else None + if not isinstance(info, dict): + return None + max_k_tiles = int(info.get("max_k_tiles", -1)) + num_heads = int(info.get("orig_num_qo_heads", 0)) + if max_k_tiles <= 0 or num_heads <= 0: + return None + return torch.empty( + (num_heads, max_k_tiles, int(idx_q.shape[0])), dtype=torch.float32, device=idx_q.device + ) + + def _proxy_max_score( idx_q: torch.Tensor, idx_k_paged: torch.Tensor, @@ -329,6 +366,42 @@ def _combined_topk_table( return out +def _tile_select( + max_score_kv: torch.Tensor, + n_valid_blocks: torch.Tensor, + init_blocks: int, + local_blocks: int, +) -> Optional[torch.Tensor]: + """Top-16 table from the SM107 prefill tile select, or None outside its gate or shapes. + + Returns the same head-major backed [total_q, num_kv_heads, 16] int32 table as + select_blocks_from_maxscore(..., head_major_output=True). + """ + if not _SM107_TILE_SELECT or get_sm_version() != 107: + return None + if ( + max_score_kv.dtype != torch.float32 + or max_score_kv.dim() != 3 + or max_score_kv.stride(2) != 1 + or max_score_kv.shape[2] < _SM107_TILE_SELECT_MIN_Q + or max_score_kv.shape[1] > _SM107_TILE_SELECT_MAX_BLOCKS + ): + return None + num_kv_heads, _, total_q = max_score_kv.shape + out = torch.empty( + (num_kv_heads, total_q, MSA_REQUIRED_TOPK), dtype=torch.int32, device=max_score_kv.device + ).permute(1, 0, 2) + nvb = n_valid_blocks.to(device=max_score_kv.device, dtype=torch.int32).contiguous() + torch.ops.trtllm.minimax_m3_select_prefill_tile( + max_score_kv, nvb, out, init_blocks, local_blocks + ) + logger.info_once( + "MSA prefill select: tile select, 8 queries per CTA (SM107)", + key="minimax_m3_sm107_tile_select", + ) + return out + + def _group_max_reduce( max_score: torch.Tensor, config: "MiniMaxM3SparseConfig", @@ -511,6 +584,13 @@ def _proxy_scores( causal=True, ) fmha_sm100 = require_msa_module() + if max_score is None and _PROXY_SCORES_NO_FILL: + max_score = _unfilled_max_score(proxy_plan, idx_q) + if max_score is not None: + logger.info_once( + "MSA indexer proxy: scores into an unfilled max-score buffer", + key="minimax_m3_proxy_scores_no_fill", + ) _, scores = fmha_sm100.fmha_sm100( idx_q, idx_k_paged, @@ -535,8 +615,14 @@ def _select( decode kernel reads the table head-major and takes every generation row, while fmha_sm100 reads whatever strides it is handed. """ + max_score_kv = _group_max_reduce(max_score, self.config) + table = _tile_select( + max_score_kv, n_valid_blocks, self.config.init_blocks, self.config.local_blocks + ) + if table is not None: + return table return select_blocks_from_maxscore( - _group_max_reduce(max_score, self.config), + max_score_kv, topk=MSA_REQUIRED_TOPK, n_valid_blocks=n_valid_blocks, init_blocks=self.config.init_blocks, diff --git a/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py b/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py index fd33db505c05..371010f06a40 100644 --- a/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py @@ -592,6 +592,28 @@ def _(packed, kv_data_cache, kv_scale_cache, index_k_cache, out_cache_loc, packed.new_empty((num_tokens, num_heads_index, head_dim), dtype=torch.float8_e4m3fn)) + # Here, not in modeling_v2's minimax_m3/fake_ops.py: the built-in modeling_minimaxm3 also calls this op and does not import fake_ops. + @torch.library.register_fake( + "trtllm::minimax_m3_ctx_residual_rmsnorm_mxfp8") + def _(inter, residual, weight, eps, write_norm, fp4_global_scale=None): + """(norm_out, mxfp8, swizzled UE8M0 scales, fp4, fp4 linear scales); the fp4 pair and an unwritten norm_out + are empty.""" + del residual, weight, eps + hidden = inter.shape[-1] + rows = inter.numel() // hidden + norm_out = torch.empty_like(inter) if write_norm else inter.new_empty( + (0, )) + mxfp8 = inter.new_empty(inter.shape, dtype=torch.float8_e4m3fn) + sf_size = (rows + 127) // 128 * 128 * ((hidden // 32 + 3) // 4 * 4) + sf = inter.new_empty((sf_size, ), dtype=torch.uint8) + if fp4_global_scale is None: + return norm_out, mxfp8, sf, inter.new_empty((0, )), inter.new_empty( + (0, )) + fp4 = inter.new_empty((*inter.shape[:-1], hidden // 2), + dtype=torch.uint8) + fp4_sf = inter.new_empty((rows * (hidden // 16), ), dtype=torch.uint8) + return norm_out, mxfp8, sf, fp4, fp4_sf + @torch.library.register_fake("trtllm::userbuffers_allreduce_finalize") def _(input, force_applying_finalize): return torch.empty_like(input) diff --git a/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py b/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py index ea4cc0c8b4a7..0643c71c8897 100644 --- a/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py @@ -17643,8 +17643,12 @@ def __init__( tile_size: int, output_dtype: torch.dtype, scaling_vector_size: int = 16, - sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN): + sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN, + store_permuted: bool = False): super().__init__() + # store_permuted: FC2 stores bf16(alpha * acc) at each permuted row of c [m, n] instead of the + # fused scatter-add finalize (deterministic route; the finalize runs separately in fixed order). + self.store_permuted = store_permuted self.num_experts = num_experts self.top_k = top_k self.num_local_experts = num_local_experts @@ -17677,6 +17681,7 @@ def unique_id(self): self.tile_size, self.output_dtype, self.scaling_vector_size, + self.store_permuted, ) + _rubin_sf_dtype_key(self.sf_dtype) @staticmethod @@ -17786,7 +17791,8 @@ def get_tuning_config(self) -> TuningConfig: functools.partial( fp4_scale_infer_shape, sf_vec_size=self.scaling_vector_size)), - ConstraintSpec(5, 0, helper.infer_shape_num_tokens), + ConstraintSpec(5, 0, helper.infer_shape_max_num_permuted_tokens + if self.store_permuted else helper.infer_shape_num_tokens), ConstraintSpec(6, 0, helper.infer_shape_max_num_tiles), ConstraintSpec(7, 0, @@ -17831,6 +17837,8 @@ def forward(self, inputs: List[torch.Tensor], assert c.dim() == 2 num_tokens = c.size(0) assert c.size(1) == n or c.size(1) == n * 2 + if self.store_permuted: + assert num_tokens == m, "store_permuted: c is [permuted rows, n]" num_tiles = m // self.tile_size assert tile_idx_to_group_idx.dtype == torch.int32 @@ -17843,7 +17851,8 @@ def forward(self, inputs: List[torch.Tensor], assert num_non_exiting_tiles.numel() == 1 assert token_final_scales.dtype == torch.float32 assert token_final_scales.dim() == 2 - assert token_final_scales.size() == (num_tokens, self.top_k) + if not self.store_permuted: + assert token_final_scales.size() == (num_tokens, self.top_k) locality_domain_id = get_current_locality_domain() locality_domain_half_gemm = locality_domain_id is not None @@ -17923,7 +17932,7 @@ def forward(self, inputs: List[torch.Tensor], cache_key = (self.scaling_vector_size, self.sf_dtype, self.tile_size, self.top_k, mma_tiler, mma_inst_shape, cluster_shape_mn, raster_along_m, - locality_domain_half_gemm, max_active_clusters) + locality_domain_half_gemm, max_active_clusters, self.store_permuted) if cache_key not in self.__class__.kernel_cache: gemm = self.__class__.kernel_class( sf_vec_size=self.scaling_vector_size, @@ -17932,6 +17941,7 @@ def forward(self, inputs: List[torch.Tensor], cluster_shape_mn=cluster_shape_mn, raster_along_m=raster_along_m, topK=self.top_k, + store_permuted=self.store_permuted, ) compiled_gemm = cute.compile( gemm.wrapper, @@ -18036,6 +18046,60 @@ def cute_dsl_nvfp4_grouped_gemm_finalize_inplace_rubin( runner(inputs, tactic=best_tactic) + @torch.library.custom_op( + "trtllm::cute_dsl_nvfp4_grouped_gemm_store_rubin", + mutates_args=("output", ), + device_types="cuda") + def cute_dsl_nvfp4_grouped_gemm_store_rubin( + input: torch.Tensor, + weight: torch.Tensor, + input_scale: torch.Tensor, + weight_scale: torch.Tensor, + alpha: torch.Tensor, + output: torch.Tensor, + tile_idx_to_group_idx: torch.Tensor, + tile_idx_to_mn_limit: torch.Tensor, + permuted_idx_to_expanded_idx: torch.Tensor, + num_non_exiting_tiles: torch.Tensor, + token_final_scales: torch.Tensor, + num_experts: int, + top_k: int, + num_local_experts: int, + local_expert_offset: int, + tile_size: int, + output_dtype: torch.dtype, + scaling_vector_size: int = 16, + precomputed_tactic: Optional[str] = None, + ) -> None: + """(rule 1b, deterministic) The FC2 grouped GEMM storing bf16(alpha * acc) per permuted row into output + [m, n] (no token scale, no scatter-add); a fixed-order finalize then sums the top-k rows per token.""" + tuner = AutoTuner.get() + runner = Sm107BlockScaledContiguousGroupedGemmFinalizeFusionRunner( + num_experts, + top_k, + num_local_experts, + local_expert_offset, + tile_size, + output_dtype, + scaling_vector_size, + store_permuted=True) + inputs = [ + input, weight, input_scale, weight_scale, alpha, output, + tile_idx_to_group_idx, tile_idx_to_mn_limit, + permuted_idx_to_expanded_idx, num_non_exiting_tiles, + token_final_scales + ] + if precomputed_tactic is None: + _, best_tactic = tuner.choose_one( + "trtllm::cute_dsl_nvfp4_grouped_gemm_store_rubin", + [runner], + runner.get_tuning_config(), + inputs, + ) + else: + best_tactic = ast.literal_eval(precomputed_tactic) + runner(inputs, tactic=best_tactic) + @torch.library.custom_op( "trtllm::cute_dsl_nvfp4_grouped_gemm_finalize_rubin", mutates_args=(), diff --git a/tensorrt_llm/_torch/custom_ops/torch_custom_ops.py b/tensorrt_llm/_torch/custom_ops/torch_custom_ops.py index 672c9b9f20e8..87acbcf55df8 100644 --- a/tensorrt_llm/_torch/custom_ops/torch_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/torch_custom_ops.py @@ -593,9 +593,27 @@ def _( _FLASHINFER_MXFP8_GEMM_AUTOTUNED_OP = ( "trtllm::flashinfer_mxfp8_gemm_autotuned::gemm") +_MXFP8_SMALL_M_BUCKETS: Optional[tuple[int, ...]] = None + + +def _get_mxfp8_small_m_buckets() -> tuple[int, ...]: + """Return the native runner's small-M tuning buckets (empty except on SM107).""" + global _MXFP8_SMALL_M_BUCKETS + if _MXFP8_SMALL_M_BUCKETS is None: + try: + runner = torch.classes.trtllm.MXFP8GemmRunner(torch.bfloat16) + except RuntimeError: + # No CUDA device or no native MXFP8 runner: keep exact-M profiles. + return () + _MXFP8_SMALL_M_BUCKETS = tuple(runner.get_small_m_tuning_buckets()) + return _MXFP8_SMALL_M_BUCKETS + def _map_to_mxfp8_large_m_bucket(num_tokens: int) -> int: - """Map known large-M bands to stable native autotuning profiles.""" + """Map known large-M bands, and small-M bands where the GPU has them, to native autotuning profiles.""" + small_buckets = _get_mxfp8_small_m_buckets() + if small_buckets and num_tokens <= small_buckets[-1]: + return next(bucket for bucket in small_buckets if num_tokens <= bucket) for (lower_bound, upper_bound), bucket in zip(MXFP8GemmRunner._LARGE_M_BANDS, MXFP8GemmRunner._LARGE_M_BUCKETS): @@ -607,8 +625,8 @@ def _map_to_mxfp8_large_m_bucket(num_tokens: int) -> int: def _get_mxfp8_large_m_tuning_buckets(max_num_tokens: int) -> tuple[int, ...]: """Return large-M profiles reachable by the configured token limit.""" mapped_max = _map_to_mxfp8_large_m_bucket(max_num_tokens) - return tuple(bucket for bucket in MXFP8GemmRunner._LARGE_M_BUCKETS - if bucket <= mapped_max) + return tuple(bucket for bucket in _get_mxfp8_small_m_buckets() + + MXFP8GemmRunner._LARGE_M_BUCKETS if bucket <= mapped_max) def _mxfp8_scale_infer_shape(input_shapes: List[List[int]]) -> int: diff --git a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py index 9b30a008fa6b..19e70f4b3c3b 100644 --- a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import json import os from dataclasses import dataclass, replace from functools import lru_cache @@ -706,6 +707,52 @@ def lookup_tactic( return [int(tactic[0]), int(tactic[1])] +FP4_MOE_TACTIC_TABLE_ENV = "TLLM_FP4_MOE_TACTIC_TABLE" +# Read once at import, so eager steps and CUDA-graph capture see the same table. +_FP4_MOE_TACTIC_TABLE_PATH = os.environ.get(FP4_MOE_TACTIC_TABLE_ENV) + + +@lru_cache(maxsize=None) +def _load_fp4_moe_tactic_table(path: str) -> dict: + """Load an opt-in FP4 MoE tactic table. + + JSON layout: ``{",,,": + {"": [tile_n, config], ...}, ...}``. The outer key is + ``FP4BlockScaleMoERunner.unique_id()``, so a table only applies to the MoE + shape it was built for. + """ + with open(path) as f: + raw = json.load(f) + return { + shape: { + int(bucket): list(tactic) + for bucket, tactic in buckets.items() + } + for shape, buckets in raw.items() + } + + +def _pinned_fp4_moe_tactic(kernel_runner: "FP4BlockScaleMoERunner", + num_tokens: int) -> Optional[List[int]]: + """Return the pinned tactic for this runner shape and token count, if any. + + Off unless ``TLLM_FP4_MOE_TACTIC_TABLE`` named a table at import. The token count is + mapped with the runner's own tuning-bucket rule, so a pinned entry replaces + exactly the autotuner's choice for that bucket. Pinning the same table on + every rank and server start makes the MoE output independent of per-start + autotuning, whose near-tie choices are not all bitwise-equivalent. + """ + path = _FP4_MOE_TACTIC_TABLE_PATH + if not path: + return None + shape_key = ",".join(str(v) for v in kernel_runner.unique_id()) + buckets = _load_fp4_moe_tactic_table(path).get(shape_key) + if not buckets: + return None + spec = kernel_runner.tuning_config.dynamic_tensor_specs[0] + return buckets.get(spec.map_to_tuning_buckets(num_tokens)) + + @torch.library.custom_op("trtllm::fp4_block_scale_moe_runner", mutates_args=()) def fp4_block_scale_moe_runner( routing_logits: Optional[torch.Tensor], @@ -840,6 +887,9 @@ def fp4_block_scale_moe_runner( tuning_config_with_hook, input_tensors_for_tuner, ) + pinned_tactic = _pinned_fp4_moe_tactic(kernel_runner, hidden_states.shape[0]) + if pinned_tactic is not None: + best_tactic = pinned_tactic result = kernel_runner( input_tensors, tactic=[-1, -1] if best_tactic == -1 else best_tactic, diff --git a/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/__init__.py b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/__init__.py new file mode 100644 index 000000000000..52a7a9daf028 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/clc_tile_scheduler.py b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/clc_tile_scheduler.py new file mode 100644 index 000000000000..b7e09877c83e --- /dev/null +++ b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/clc_tile_scheduler.py @@ -0,0 +1,559 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import inspect +from typing import Any, Optional, Tuple + +import cutlass +import cutlass.cute as cute +from cutlass._mlir import ir +from cutlass.cutlass_dsl import ( + Boolean, + Int32, + Integer, + dsl_user_op, + extract_mlir_values, + new_from_mlir_values, +) +from cutlass.utils.static_persistent_tile_scheduler import WorkTileInfo + + +class ClcDynamicPersistentTileSchedulerParams: + """A class to represent parameters for a dynamic persistent tile scheduler. + + This class is designed to manage and compute the layout of clusters and tiles + in a batched gemm problem. + + :ivar cluster_shape_mn: Shape of the cluster in (m, n) dimensions (K dimension cta count must be 1). + :type cluster_shape_mn: tuple + """ + + @dsl_user_op + def __init__( + self, + problem_shape_ntile_mnl: cute.Shape, + cluster_shape_mnk: cute.Shape, + swizzle_size: int = 1, + raster_along_m: bool = True, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> None: + """ + Initializes the ClcDynamicPersistentTileSchedulerParams with the given parameters. + + :param problem_shape_ntile_mnl: The shape of the problem in terms of + number of CTA (Cooperative Thread Array) in (m, n, l) dimensions. + :type problem_shape_ntile_mnl: cute.Shape + :param cluster_shape_mnk: The shape of the cluster in (m, n) dimensions. + :type cluster_shape_mnk: cute.Shape + :param swizzle_size: Swizzling size in the unit of cluster. 1 means no swizzle + :type swizzle_size: int + :param raster_along_m: Rasterization order of clusters. Only used when swizzle_size > 1. + True means along M, false means along N. + :type raster_along_m: bool + + :raises ValueError: If cluster_shape_k is not 1. + """ + + if cluster_shape_mnk[2] != 1: # type: ignore[index] + raise ValueError(f"unsupported cluster_shape_k {cluster_shape_mnk[2]}") # type: ignore[index] + if swizzle_size < 1: + raise ValueError(f"expect swizzle_size >= 1, but get {swizzle_size}") + + self.problem_shape_ntile_mnl = problem_shape_ntile_mnl + # cluster_shape_mnk is kept for reconstruction + self._cluster_shape_mnk = cluster_shape_mnk + self.cluster_shape_mn = cluster_shape_mnk[:2] # type: ignore[index] + self.swizzle_size = swizzle_size + self._raster_along_m = raster_along_m + self.cluster_shape_major_fdd = None + self.cluster_shape_minor_fdd = None + self._loc = loc + + # By default, we follow m major (col-major) raster order, so make a col-major layout + self.problem_layout_ncluster_mnl = cute.make_layout( + cute.ceil_div( + self.problem_shape_ntile_mnl, + cluster_shape_mnk[:2], # type: ignore[index] + loc=loc, + ip=ip, + ), + loc=loc, + ip=ip, + ) + + # Apply swizzle if swizzle_size > 1 + if swizzle_size > 1: + problem_shape_ncluster_mnl = cute.round_up( + self.problem_layout_ncluster_mnl.shape, + (1, swizzle_size, 1) if raster_along_m else (swizzle_size, 1, 1), + ) + + if raster_along_m: + self.problem_layout_ncluster_mnl = cute.make_layout( + ( + problem_shape_ncluster_mnl[0], # type: ignore[index] + (swizzle_size, problem_shape_ncluster_mnl[1] // swizzle_size), # type: ignore[index, operator] + problem_shape_ncluster_mnl[2], # type: ignore[index] + ), + stride=( + swizzle_size, + (1, swizzle_size * problem_shape_ncluster_mnl[0]), # type: ignore[index] + problem_shape_ncluster_mnl[0] * problem_shape_ncluster_mnl[1], # type: ignore[index, operator] + ), + loc=loc, + ip=ip, + ) + else: + self.problem_layout_ncluster_mnl = cute.make_layout( + ( + (swizzle_size, problem_shape_ncluster_mnl[0] // swizzle_size), # type: ignore[index, operator] + problem_shape_ncluster_mnl[1], # type: ignore[index] + problem_shape_ncluster_mnl[2], # type: ignore[index] + ), + stride=( + (1, swizzle_size * problem_shape_ncluster_mnl[1]), # type: ignore[index] + swizzle_size, + problem_shape_ncluster_mnl[0] * problem_shape_ncluster_mnl[1], # type: ignore[index, operator] + ), + loc=loc, + ip=ip, + ) + elif not raster_along_m: + cluster_count_major = self.problem_layout_ncluster_mnl.shape[1] + cluster_count_minor = self.problem_layout_ncluster_mnl.shape[0] + self.cluster_shape_major_fdd = cute.fast_divmod_create_divisor( + cluster_count_major, loc=loc, ip=ip + ) + self.cluster_shape_minor_fdd = cute.fast_divmod_create_divisor( + cluster_count_minor, loc=loc, ip=ip + ) + + def __extract_mlir_values__(self) -> list[ir.Value]: + values, self._values_pos = [], [] + for obj in [ + self.problem_shape_ntile_mnl, + self._cluster_shape_mnk, + self.swizzle_size, + self._raster_along_m, + ]: + obj_values = extract_mlir_values(obj) + values += obj_values + self._values_pos.append(len(obj_values)) + + # Add FastDivmod divisors to MLIR values for Host->Device transfer + # Only add non-None values to avoid MLIR type errors + fastdivmod_values = [] + fastdivmod_indices = [] # Track which FastDivmod objects are present + + for i, (fdd_name, fdd_obj) in enumerate( + [ + ("cluster_shape_major_fdd", self.cluster_shape_major_fdd), + ("cluster_shape_minor_fdd", self.cluster_shape_minor_fdd), + ] + ): + if fdd_obj is not None: + # Extract MLIR values from FastDivmodDivisor objects + fdd_values = extract_mlir_values(fdd_obj) + fastdivmod_values.extend(fdd_values) + fastdivmod_indices.append(i) + + values += fastdivmod_values + self._values_pos.append( + len(fastdivmod_indices) + ) # Store count of FastDivmod objects, not values + self._fastdivmod_indices = fastdivmod_indices # Store for reconstruction + + return values + + def __new_from_mlir_values__( + self, values: list[ir.Value] + ) -> "ClcDynamicPersistentTileSchedulerParams": + obj_list = [] + values_copy = list(values) # Make a copy to avoid modifying original + + # Reconstruct original objects from MLIR values + for obj, n_items in zip( + [ + self.problem_shape_ntile_mnl, + self._cluster_shape_mnk, + self.swizzle_size, + self._raster_along_m, + ], + self._values_pos[:-1], # Exclude FastDivmod count + ): + obj_list.append(new_from_mlir_values(obj, values_copy[:n_items])) + values_copy = values_copy[n_items:] + + new_params = ClcDynamicPersistentTileSchedulerParams(*(tuple(obj_list)), loc=self._loc) + + # Restore FastDivmod divisors from remaining values + fdd_names = [ + "cluster_shape_major_fdd", + "cluster_shape_minor_fdd", + ] + + if hasattr(self, "_fastdivmod_indices") and len(self._fastdivmod_indices) > 0: + # Override the FastDivmod divisors created by __init__ with reconstructed ones + for j, original_index in enumerate(self._fastdivmod_indices): + fdd_name = fdd_names[original_index] + # Get the original FastDivmodDivisor object + original_fdd = getattr(self, fdd_name) + if original_fdd is not None and j < len(values_copy): + # Each FastDivmodDivisor has 1 MLIR value + reconstructed_fdd = new_from_mlir_values(original_fdd, [values_copy[j]]) + setattr(new_params, fdd_name, reconstructed_fdd) + + return new_params + + @dsl_user_op + def get_grid_shape( + self, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> Tuple[Integer, Integer, Integer]: + """ + Computes the grid shape based on the problem shape and cluster shape. + + :return: the grid is the CTA numbers that has aligned with cluster shape. + """ + + problem_ceiling_cta_mnl = cute.round_up( + self.problem_shape_ntile_mnl, self._cluster_shape_mnk + ) + + if self.swizzle_size == 1 and self._raster_along_m: + return problem_ceiling_cta_mnl # type: ignore[return-value] + elif self.swizzle_size > 1: + # The swizzled layout spans the cluster counts rounded up to the + # swizzle size; launch every cluster of it (the padding tiles + # fall outside the problem and are skipped by the kernel), or the + # linear indices past the true count would never be decoded. + return ( + *self.cluster_shape_mn, + cute.size(self.problem_layout_ncluster_mnl.shape, loc=loc, ip=ip), + ) + else: + # If swizzling is enabled or raster_along_n, + # we are going to map from a linear idx to tile id manually. + num_problem_cta_count = cute.size(problem_ceiling_cta_mnl, loc=loc, ip=ip) + num_ctas_per_cluster = cute.size(self.cluster_shape_mn, loc=loc, ip=ip) + return ( + *self.cluster_shape_mn, + num_problem_cta_count // num_ctas_per_cluster, + ) + + +# Set explicit signature for Sphinx documentation to avoid issues with @dsl_user_op decorator +ClcDynamicPersistentTileSchedulerParams.__init__.__signature__ = inspect.Signature( # type: ignore[attr-defined] + [ + inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD), + ] +) + + +class ClcDynamicPersistentTileScheduler: + """A scheduler for dynamic persistent tile execution in CUTLASS/CuTe kernels. + + :ivar params: Tile schedule related params, including cluster shape. + :type params: ClcDynamicPersistentTileSchedulerParams + :ivar cta_id_in_cluster: ID of the CTA within its cluster + :type cta_id_in_cluster: cute.Coord + :ivar _num_tiles_executed: Counter for executed tiles + :type _num_tiles_executed: Int32 + """ + + def __init__( + self, + params: ClcDynamicPersistentTileSchedulerParams, + cta_id_in_cluster: cute.Coord, + num_tiles_executed: Int32, + clc_response_ptr: cute.Pointer, + block_idx: Tuple[Integer, Integer, Integer], + insert_fence: bool = True, + ): + """ + Initializes the ClcDynamicPersistentTileScheduler with the given parameters. + + :param params: Tile schedule related params, including cluster shape. + :type params: ClcDynamicPersistentTileSchedulerParams + :param cta_id_in_cluster: ID of the CTA within its cluster. + :type cta_id_in_cluster: cute.Coord + :param num_tiles_executed: Counter for executed tiles. + :type num_tiles_executed: Int32 + :param clc_response_ptr: Pointer of the clc rsponse. + :type clc_response_ptr: cute.Pointer + :param block_idx: The block index. + :type block_idx: Tuple[Integer, Integer, Integer] + :param insert_fence: Whether to insert a fence to ensure generic-async proxy order. + CLC issue is in async proxy while loading the response from shared memory is in + generic proxy. A cross-proxy fence is needed to ensure producer's next issue + won't race with consumer's current loading. Therefore the scheduler inserts a + fence by default after loading the response. + Developers may insert the fence in pipeline acquire/release functions. In that case, + the fence here can be omitted. + :type insert_fence: bool + """ + self.params = params + self.cta_id_in_cluster = cta_id_in_cluster + self._num_tiles_executed = num_tiles_executed + self._clc_response_ptr = clc_response_ptr + self._block_idx = block_idx + self.insert_fence = insert_fence + + def __extract_mlir_values__(self) -> list[ir.Value]: + values = extract_mlir_values(self.cta_id_in_cluster) + values.extend(extract_mlir_values(self._num_tiles_executed)) + values.extend(extract_mlir_values(self._clc_response_ptr)) + values.extend(extract_mlir_values(self._block_idx)) + return values + + def __new_from_mlir_values__( + self, values: list[ir.Value] + ) -> "ClcDynamicPersistentTileScheduler": + assert len(values) == 8 + new_cta_id_in_cluster = new_from_mlir_values(self.cta_id_in_cluster, values[0:3]) + new_num_tiles_executed = new_from_mlir_values(self._num_tiles_executed, [values[3]]) + new_clc_response_ptr = new_from_mlir_values(self._clc_response_ptr, [values[4]]) + new_block_idx = new_from_mlir_values(self._block_idx, values[5:8]) + return ClcDynamicPersistentTileScheduler( + self.params, + new_cta_id_in_cluster, + new_num_tiles_executed, + new_clc_response_ptr, + new_block_idx, + ) + + @dsl_user_op + @staticmethod + def create( + params: ClcDynamicPersistentTileSchedulerParams, + block_idx: Tuple[Integer, Integer, Integer], + grid_dim: Tuple[Integer, Integer, Integer], + clc_response_ptr: cute.Pointer, + insert_fence: bool = True, + physical_cluster_shape_mn: Optional[Tuple[int, int]] = None, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> "ClcDynamicPersistentTileScheduler": + """Initialize the dynamic persistent tile scheduler. + + :param params: Parameters for the persistent + tile scheduler. + :type params: ClcDynamicPersistentTileSchedulerParams + :param block_idx: The 3d block index in the format (bidx, bidy, bidz). + :type block_idx: Tuple[Integer, Integer, Integer] + :param grid_dim: The 3d grid dimensions for kernel launch. + :type grid_dim: Tuple[Integer, Integer, Integer] + + :return: A ClcDynamicPersistentTileScheduler object. + :rtype: ClcDynamicPersistentTileScheduler + """ + params = params + + bidx, bidy, bidz = block_idx + + # CTA id in the cluster. This is a PHYSICAL property: it must + # be taken modulo the cluster the hardware actually formed, which + # under mixed CGA is not the params (preferred) shape. A + # fallback body passes physical_cluster_shape_mn so it can keep + # decoding with the preferred params (see _swizzle_and_rasterize) + # while offsetting by its own shape. + cluster_mn = ( + params.cluster_shape_mn + if physical_cluster_shape_mn is None + else physical_cluster_shape_mn + ) + cta_id_in_cluster = ( + Int32(bidx % cluster_mn[0]), + Int32(bidy % cluster_mn[1]), + Int32(0), + ) + + # Initialize number of tiles executed to zero + num_tiles_executed = Int32(0) + # Initialize clc response pointer + clc_response_ptr = clc_response_ptr + # The block index + block_idx = block_idx + + return ClcDynamicPersistentTileScheduler( + params, + cta_id_in_cluster, + num_tiles_executed, + clc_response_ptr, + block_idx, + insert_fence, + ) + + # called by host + @dsl_user_op + def get_grid_shape( + params: ClcDynamicPersistentTileSchedulerParams, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> Tuple[Integer, Integer, Integer]: + """Calculates the grid shape to be launched on GPU using problem shape, + threadblock shape, and active cluster size. + + :param params: Parameters for grid shape calculation. + :type params: ClcDynamicPersistentTileSchedulerParams + + :return: The calculated 3d grid shape. + :rtype: Tuple[Integer, Integer, Integer] + """ + + return params.get_grid_shape(loc=loc, ip=ip) + + @cute.jit + def _swizzle_and_rasterize( + self, + x_idx: Int32, + y_idx: Int32, + z_idx: Int32, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> Tuple[Int32, Int32, Int32]: + """Swizzle and rasterize the given coordinates for leader CTA of the cluster. + + x_idx / y_idx are the leader's offsets INSIDE the params cluster + footprint and z_idx selects the footprint. The upstream version + dropped x_idx / y_idx on the two z-form paths, which is sound only + when every launched cluster fills the footprint (then they are + provably 0). MIXED CGA breaks that: a z slice that cannot form the + preferred cluster is tiled by several smaller fallback clusters + whose leaders differ ONLY in x/y, so dropping them aliases them all + onto the same tiles and orphans the rest (silicon: intermittent + 256-row zero blocks and out-of-bounds tile ids). Adding the offsets + back is a no-op for the non-mixed case. + """ + if cutlass.const_expr(self.params.swizzle_size == 1): + if cutlass.const_expr(self.params._raster_along_m): + return x_idx, y_idx, z_idx + else: + # Decode linear index using FastDivmod objects. + # First, get cluster_major using cluster_shape_major_fdd + cluster_minor_batch, cluster_major = divmod( # type: ignore[operator] + z_idx, self.params.cluster_shape_major_fdd + ) + # Then decode cluster_minor_batch to get cluster_minor and batch_l using FastDivmod + batch_l, cluster_minor = divmod( + cluster_minor_batch, self.params.cluster_shape_minor_fdd + ) + cluster_m = cluster_minor + cluster_n = cluster_major + + return ( + cluster_m * self.params.cluster_shape_mn[0] + x_idx, + cluster_n * self.params.cluster_shape_mn[1] + y_idx, + batch_l, + ) + else: + cluster_coord = self.params.problem_layout_ncluster_mnl.get_flat_coord( + z_idx, loc=loc, ip=ip + ) + return ( + cluster_coord[0] * self.params.cluster_shape_mn[0] + x_idx, + cluster_coord[1] * self.params.cluster_shape_mn[1] + y_idx, + cluster_coord[2], + ) + + @dsl_user_op + def work_tile_info_from_clc_response( + self, + result_addr: cute.Pointer, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> WorkTileInfo: + """ + Simulates parsing CLC response data in Python. + result_addr: 16-byte response data (simulating shared memory access) + """ + m_idx, n_idx, l_idx, vld = cute.arch.clc_response(result_addr, loc=loc, ip=ip) + + # Cross-proxy fence to ensure generic proxy access are seen by later + # async proxy operations. + if self.insert_fence: + cute.arch.fence_proxy("async.shared", space="cta", loc=loc, ip=ip) + + m_idx, n_idx, l_idx = self._swizzle_and_rasterize(m_idx, n_idx, l_idx, loc=loc, ip=ip) + cta_idx_in_cluster, cta_idy_in_cluster, _ = self.cta_id_in_cluster # type: ignore[misc] + cur_tile_coord = (m_idx + cta_idx_in_cluster, n_idx + cta_idy_in_cluster, l_idx) + + return WorkTileInfo(cur_tile_coord, vld) + + @dsl_user_op + @cute.jit + def get_current_work( + self, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> WorkTileInfo: + smem_addr = self._clc_response_ptr + work_tile = self.work_tile_info_from_clc_response(smem_addr, loc=loc, ip=ip) + return work_tile + + @dsl_user_op + @cute.jit + def initial_work_tile_info(self, *, loc: Any = None, ip: Any = None) -> WorkTileInfo: + bidx, bidy, bidz = self._block_idx + # Subtract cta_id_in_cluster from block_idx because swizzle_and_rasterize expects coordinates to be + # those of the leader CTA in the cluster. + cta_idx_in_cluster, cta_idy_in_cluster, _ = self.cta_id_in_cluster # type: ignore[misc] + m_idx = bidx - cta_idx_in_cluster + n_idx = bidy - cta_idy_in_cluster + l_idx = bidz + m_idx, n_idx, l_idx = self._swizzle_and_rasterize(m_idx, n_idx, l_idx, loc=loc, ip=ip) + cur_tile_coord = (m_idx + cta_idx_in_cluster, n_idx + cta_idy_in_cluster, l_idx) + return WorkTileInfo(cur_tile_coord, Boolean(True)) + + @dsl_user_op + @cute.jit + def advance_to_next_work( + self, + mbarrier_addr: cute.Pointer, + *, + loc: Optional[ir.Location] = None, + ip: Optional[ir.InsertionPoint] = None, + ) -> None: + # Query new work tile + with cute.arch.elect_one(): + cute.arch.issue_clc_query(mbarrier_addr, self._clc_response_ptr, loc=loc, ip=ip) + self._num_tiles_executed += Int32(1) + + @property + @cute.jit + def num_tiles_executed(self) -> Int32: + return self._num_tiles_executed diff --git a/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/kernel.py b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/kernel.py new file mode 100644 index 000000000000..5e313ef413a7 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/kernel.py @@ -0,0 +1,1996 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# ruff: noqa: E501,E731,E741 + +"""SM107 persistent MXFP8 QKV GEMM fused with the MiniMax-M3 QKV-index producer. + +Per output row m (token) and 128-wide head slot h of the packed +[q (Hq) | K (Hkv) | V (Hkv) | index-q (Hi) | index-K (1)] projection:: + + x = bf16_rn(alpha * (act[m, :] @ weight[h*128:(h+1)*128, :].T)) + # MXFP8 block-scaled GEMM (E4M3 operands, UE8M0 K32 + # scales), FP32 accumulation; x is re-read as fp32 + V : no norm, no rope + otherwise: RMSNorm with the per-slot-type bf16 weight w (1 + w + scaling) over the 128 dims, then NeoX RoPE on dims 0..63 + with (cos, sin) = rotary_cos_sin[position_ids[m]] + q -> E4M3 q_out[m, h, :] + index-q -> E4M3 index_q_out[m, h - first index-q slot, :] + index-K -> E4M3 paged index-K cache row out_cache_loc[m] + K, V -> NVFP4 (16-element E4M3 block scales, second-level scale + kv_quant_scale[1] / [2]) into the paged HND K/V caches + +Every floating-point step after the GEMM is the op sequence that +``minimaxM3Nvfp4QKVIndexerNormRopeKVInsert{,Rows}Kernel`` compiles to, so +the outputs are bitwise those of running that producer on this kernel's +own bf16 GEMM output (``debug_gemm_out=True`` writes that bf16 tensor +instead of the producer outputs): + +* sum of squares per 4-dim lane group l: fma(x0, x0, x1*x1) + + fma(x2, x2, x3*x3), then the xor-butterfly 16, 8, 4, 2, 1 over the 32 + lane partials, replayed in-thread; +* inv_rms = rsqrt.approx.f32(fma(sum, 1/128, eps)); +* e = x * (inv_rms * (1 + w)); +* rope: out = fma(+-paired, sin, e * cos), paired = e[d ^ 32], negated for + d < 32; +* E4M3 via cvt.rn.satfinite.e4m3x2.f32; NVFP4 via the bf16-rounded + values, the 16-element abs-max, scale = sl * (max * 0x3E2AAAAB), its + E4M3 encoding, output scale rcp.approx.ftz(e4m3(scale) * + rcp.approx.ftz(sl)) (0 for an all-zero group) and + cvt.rn.satfinite.e2m1x2.f32. + +Schedule: a persistent warp-specialized SM107 block-scaled GEMM (CLC tile +scheduler; warps 0-3 epilogue, 4 MMA, 5 TMA, 6 scheduler, 7 idle). One +work tile is (``mma_m`` rows, ``heads_per_tile`` head slots of 128 +columns); ``mma_m=256`` runs the 2-CTA MMA with each CTA of the pair +owning 128 rows. A tile wider than one MMA (N > ``mma_n``) issues its N +sets back to back per k-block with A held in the operand collector. The +accumulator has as many TMEM stages as fit (``num_acc_stage``) so the +epilogue of one tile overlaps the mainloop of the next. ``epi_wgs`` +epilogue warpgroups split a tile's heads between them, so with a single +accumulator stage the MMA of the next tile waits for only one warpgroup's +share of producer math. Each epilogue thread owns one tile row (one +token) and whole 128-column heads, so the row reduction needs no +shuffles. Rows >= M and head slots past the last are +never stored; cache stores are skipped for out_cache_loc < 0 or +page >= num_pages. + +Defaults (4 head slots per tile, 2-CTA M256, A reused across two N256 +MMAs, one epilogue warpgroup) are the fastest measured on SM107 at +M=8192..16384: SMEM operand reads per SM, not L2, bound the mainloop, so +wider tiles win; a second epilogue warpgroup caps the epilogue at 208 +registers and runs slower. +""" + +from __future__ import annotations + +import os +from typing import NamedTuple, Tuple + +import cuda.bindings.driver as cuda_driver +import cutlass +import cutlass.cute as cute +import cutlass.pipeline as pipeline +import cutlass.utils as utils +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.utils.blockscaled_layout as blockscaled_utils +import cutlass.utils.rubin_helpers as sm107_utils +from cutlass._mlir.dialects import llvm as _llvm +from cutlass._mlir.dialects import nvvm +from cutlass._mlir.extras import types as _T +from cutlass.cute.nvgpu import OperandMajorMode, cpasync, tcgen05 +from cutlass.cute.nvgpu.tcgen05.mma import CollectorOp +from cutlass.cutlass_dsl import dsl_user_op +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait +from cutlass.utils.gemm import sm100 as gemm_sm100 + +from .clc_tile_scheduler import ( + ClcDynamicPersistentTileScheduler, + ClcDynamicPersistentTileSchedulerParams, +) + +HEAD_DIM = 128 +ROTARY_DIM = 64 +PAGE_SIZE = 128 +# float32(rcp.approx.ftz(6.0f)) as the producer's compiled FMUL immediate. +RCP_SIX_BITS = 0x3E2AAAAB + + +# --------------------------------------------------------------------------- +# Inline-PTX helpers. Every float op is an explicitly rounded PTX op so that +# neither LLVM nor ptxas contracts or reassociates it. +# --------------------------------------------------------------------------- + + +def _asm(res_type, args, text, constraints, side_effects, loc, ip): + return _llvm.inline_asm( + res_type, + [a.ir_value(loc=loc, ip=ip) for a in args], + text, + constraints, + has_side_effects=side_effects, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _fma_rn(a, b, c, *, loc=None, ip=None): + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Float32(a), cutlass.Float32(b), cutlass.Float32(c)], + "fma.rn.f32 $0, $1, $2, $3;", + "=f,f,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _mul_rn(a, b, *, loc=None, ip=None): + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Float32(a), cutlass.Float32(b)], + "mul.rn.f32 $0, $1, $2;", + "=f,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _add_rn(a, b, *, loc=None, ip=None): + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Float32(a), cutlass.Float32(b)], + "add.rn.f32 $0, $1, $2;", + "=f,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _rsqrt_approx(x, *, loc=None, ip=None): + """rsqrtf without fast-math: rsqrt.approx.f32 (denormal-preserving).""" + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Float32(x)], + "rsqrt.approx.f32 $0, $1;", + "=f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _rcp_approx_ftz(x, *, loc=None, ip=None): + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Float32(x)], + "rcp.approx.ftz.f32 $0, $1;", + "=f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _absmax(acc, v, *, loc=None, ip=None): + """fmaxf(acc, fabsf(v)) (max.f32 ignores a NaN operand like fmaxf).""" + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Float32(acc), cutlass.Float32(v)], + "{\n\t.reg .f32 a;\n\tabs.f32 a, $2;\n\tmax.f32 $0, $1, a;\n\t}", + "=f,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _bf16x2_rn(lo, hi, *, loc=None, ip=None): + """bf16_rn(lo) | bf16_rn(hi) << 16.""" + return cutlass.Int32( + _asm( + _T.i32(), + [cutlass.Float32(hi), cutlass.Float32(lo)], + "cvt.rn.bf16x2.f32 $0, $1, $2;", + "=r,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _e4m3x4(v0, v1, v2, v3, *, loc=None, ip=None): + """Four f32 to E4M3 (RN, satfinite), v0 in the low byte.""" + return cutlass.Int32( + _asm( + _T.i32(), + [cutlass.Float32(v) for v in (v0, v1, v2, v3)], + "{\n\t.reg .b16 lo, hi;\n\tcvt.rn.satfinite.e4m3x2.f32 lo, $2, $1;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 hi, $4, $3;\n\tmov.b32 $0, {lo, hi};\n\t}", + "=r,f,f,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _e4m3_byte(x, *, loc=None, ip=None): + """__nv_fp8_e4m3(x).__x: cvt.rn.satfinite.e4m3x2.f32 of (0, x), low byte.""" + return cutlass.Int32( + _asm( + _T.i32(), + [cutlass.Float32(x)], + "{\n\t.reg .b16 h;\n\t.reg .f32 z;\n\tmov.f32 z, 0f00000000;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 h, z, $1;\n\tcvt.u32.u16 $0, h;\n\t" + "and.b32 $0, $0, 255;\n\t}", + "=r,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _e4m3_byte_to_f32(b, *, loc=None, ip=None): + """static_cast(__nv_fp8_e4m3) of the byte b (exact).""" + return cutlass.Float32( + _asm( + _T.f32(), + [cutlass.Int32(b)], + "{\n\t.reg .b16 h, lo, hi;\n\t.reg .b32 r;\n\tcvt.u16.u32 h, $1;\n\t" + "cvt.rn.f16x2.e4m3x2 r, h;\n\tmov.b32 {lo, hi}, r;\n\tcvt.f32.f16 $0, lo;\n\t}", + "=f,r", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _e2m1x8(v, *, loc=None, ip=None): + """fp32_vec_to_e2m1 of eight f32: element 2i in the low nibble of byte i.""" + return cutlass.Int32( + _asm( + _T.i32(), + [cutlass.Float32(x) for x in v], + "{\n\t.reg .b8 byte0, byte1, byte2, byte3;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 byte0, $2, $1;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 byte1, $4, $3;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 byte2, $6, $5;\n\t" + "cvt.rn.satfinite.e2m1x2.f32 byte3, $8, $7;\n\t" + "mov.b32 $0, {byte0, byte1, byte2, byte3};\n\t}", + "=r,f,f,f,f,f,f,f,f", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _ldg_v4_f32(addr, *, loc=None, ip=None): + out = _asm( + _llvm.StructType.get_literal([_T.f32()] * 4), + [cutlass.Int64(addr)], + "ld.global.nc.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,l", + False, + loc, + ip, + ) + return [ + cutlass.Float32(_llvm.extractvalue(_T.f32(), out, [i], loc=loc, ip=ip)) for i in range(4) + ] + + +@dsl_user_op +def _ldg_s32(addr, *, loc=None, ip=None): + return cutlass.Int32( + _asm( + _T.i32(), + [cutlass.Int64(addr)], + "ld.global.nc.s32 $0, [$1];", + "=r,l", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _ldg_u16(addr, *, loc=None, ip=None): + return cutlass.Int32( + _asm( + _T.i32(), + [cutlass.Int64(addr)], + "{\n\t.reg .b16 h;\n\tld.global.nc.b16 h, [$1];\n\tcvt.u32.u16 $0, h;\n\t}", + "=r,l", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _stg_v4(addr, w0, w1, w2, w3, *, loc=None, ip=None): + _asm( + None, + [cutlass.Int64(addr)] + [cutlass.Int32(w) for w in (w0, w1, w2, w3)], + "st.global.v4.b32 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + True, + loc, + ip, + ) + + +@dsl_user_op +def _stg_v2(addr, w0, w1, *, loc=None, ip=None): + _asm( + None, + [cutlass.Int64(addr), cutlass.Int32(w0), cutlass.Int32(w1)], + "st.global.v2.b32 [$0], {$1, $2};", + "l,r,r", + True, + loc, + ip, + ) + + +@dsl_user_op +def _stg_u8(addr, w, *, loc=None, ip=None): + _asm( + None, + [cutlass.Int64(addr), cutlass.Int32(w)], + "st.global.u8 [$0], $1;", + "l,r", + True, + loc, + ip, + ) + + +@dsl_user_op +def _sts_f32(addr, v, *, loc=None, ip=None): + _asm( + None, + [cutlass.Int32(addr), cutlass.Float32(v)], + "st.shared.f32 [$0], $1;", + "r,f", + True, + loc, + ip, + ) + + +@dsl_user_op +def _lds_v4_f32(addr, *, loc=None, ip=None): + out = _asm( + _llvm.StructType.get_literal([_T.f32()] * 4), + [cutlass.Int32(addr)], + "ld.shared.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,r", + True, + loc, + ip, + ) + return [ + cutlass.Float32(_llvm.extractvalue(_T.f32(), out, [i], loc=loc, ip=ip)) for i in range(4) + ] + + +def _lo_f32(w): + """The bf16 in the low half of w, as fp32.""" + return (w << cutlass.Int32(16)).bitcast(cutlass.Float32) + + +def _hi_f32(w): + """The bf16 in the high half of w, as fp32.""" + return (w & cutlass.Int32(-65536)).bitcast(cutlass.Float32) + + +class S2TCopyBundle(NamedTuple): + """Tiled copy + partitioned tensors for one SMEM-to-TMEM SF copy.""" + + tiled_copy: cute.TiledCopy + sSF_compact: cute.Tensor + tSF_compact: cute.Tensor + + +class M3QkvGemmNormRopeKvInsert: + """Persistent SM107 MXFP8 QKV GEMM with the M3 producer as its epilogue.""" + + def __init__( + self, + *, + num_heads_q: int = 32, + num_heads_kv: int = 2, + num_heads_index: int = 2, + heads_per_tile: int = 4, + mma_m: int = 256, + mma_n: int | None = None, + num_acc_stage: int | None = None, + cluster_shape_mn: Tuple[int, int] | None = None, + swizzle_size: int = 1, + raster_along_m: bool = True, + debug_gemm_out: bool = False, + enable_pdl: bool = True, + epi_wgs: int = 1, + ): + if mma_m not in (128, 256): + raise ValueError("mma_m must be 128 (1-CTA) or 256 (2-CTA pair)") + if heads_per_tile not in (1, 2, 3, 4): + raise ValueError("heads_per_tile must be 1..4") + self.num_heads_q = int(num_heads_q) + self.num_heads_kv = int(num_heads_kv) + self.num_heads_index = int(num_heads_index) + self.k_begin = self.num_heads_q + self.v_begin = self.k_begin + self.num_heads_kv + self.iq_begin = self.v_begin + self.num_heads_kv + self.ik_slot = self.iq_begin + self.num_heads_index + self.num_slots = self.ik_slot + 1 + self.n_total = self.num_slots * HEAD_DIM + + self.heads_per_tile = int(heads_per_tile) + self.tile_n = HEAD_DIM * self.heads_per_tile + inst_n = min(self.tile_n, 256) if mma_n is None else int(mma_n) + if inst_n not in (128, 256) or self.tile_n % inst_n: + raise ValueError("mma_n must be 128 or 256 and divide the tile N") + self.n_sets = self.tile_n // inst_n + self.mma_inst_shape = (mma_m, inst_n, 64) + self.mma_tiler = (mma_m, self.tile_n, 128) + self.use_2cta_instrs = mma_m == 256 + self.cta_group = tcgen05.CtaGroup.TWO if self.use_2cta_instrs else tcgen05.CtaGroup.ONE + self.atom_thr_size = 2 if self.use_2cta_instrs else 1 + + if cluster_shape_mn is None: + cluster_shape_mn = (self.atom_thr_size, 1) + self.cluster_shape_mn = tuple(cluster_shape_mn) + cm, cn = self.cluster_shape_mn + if cm < 1 or cn < 1 or (cm & (cm - 1)) or (cn & (cn - 1)) or cm * cn > 16: + raise ValueError("cluster dims must be powers of two, <= 16 CTAs") + if cm % self.atom_thr_size: + raise ValueError("a 2-CTA MMA needs an even cluster M") + self.swizzle_size = int(swizzle_size) + self.raster_along_m = bool(raster_along_m) + self.debug_gemm_out = bool(debug_gemm_out) + self.enable_pdl = bool(enable_pdl) + if epi_wgs not in (1, 2) or self.heads_per_tile % epi_wgs: + raise ValueError("epi_wgs must be 1 or 2 and divide heads_per_tile") + self.epi_wgs = int(epi_wgs) + self.heads_per_wg = self.heads_per_tile // self.epi_wgs + + self.acc_dtype = cutlass.Float32 + self.sf_vec_size = 32 + self.occupancy = 1 + # Warpgroup g of the epilogue is warps 4g..4g+3 (TMEM lane quadrant + # = warp % 4); the MMA / TMA / scheduler / idle warps follow. + num_epi_warps = 4 * self.epi_wgs + self.epilog_warp_id = tuple(range(num_epi_warps)) + self.mma_warp_id = num_epi_warps + self.tma_warp_id = num_epi_warps + 1 + self.sched_warp_id = num_epi_warps + 2 + self.pad_warp_id = num_epi_warps + 3 + self.threads_per_warp = 32 + self.threads_per_cta = 32 * (num_epi_warps + 4) + self.epilog_reg_count = 256 if self.epi_wgs == 1 else 208 + self.mainloop_reg_count = 88 + self.num_clc_stage = 1 + self.num_clc_response_bytes = 16 + self.epilog_sync_barrier = pipeline.NamedBarrier( + barrier_id=1, num_threads=32 * len(self.epilog_warp_id) + ) + self.tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=2, num_threads=32 * (1 + len(self.epilog_warp_id)) + ) + self.arch = "sm_107" + self.smem_capacity = utils.get_smem_capacity_in_bytes(self.arch) + self.num_tmem_alloc_cols = cute.arch.get_max_tmem_alloc_cols(self.arch) + self.requested_acc_stage = num_acc_stage + self.epi_chunk = 32 + self.chunks_per_head = HEAD_DIM // self.epi_chunk + + # ------------------------------------------------------------------ + def _make_tiled_mmas(self): + def make(a_op, b_op): + mma = sm107_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + self.sf_vec_size, + self.cta_group, + self.mma_inst_shape, + a_collector_op=a_op, + b_collector_op=b_op, + atom_layout_mnk=(1, 1, 1), + permutation_mnk=(1, 1, 1), + ) + mma.set(tcgen05.Field.NEGATE_A, False) + mma.set(tcgen05.Field.NEGATE_B, False) + return mma + + # A stays in the collector across the tile's N sets of one k-block. + if self.n_sets == 1: + tiled_mma_first = make(CollectorOp.DISCARD, CollectorOp.DISCARD) + tiled_mma_mid = tiled_mma_first + tiled_mma_last = tiled_mma_first + else: + tiled_mma_first = make(CollectorOp.FILL, CollectorOp.DISCARD) + tiled_mma_mid = make(CollectorOp.USE, CollectorOp.DISCARD) + tiled_mma_last = make(CollectorOp.LASTUSE, CollectorOp.DISCARD) + tiled_mma_sfb = sm107_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + self.sf_vec_size, + tcgen05.CtaGroup.ONE, + self.mma_inst_shape_sfb, + a_collector_op=CollectorOp.DISCARD, + b_collector_op=CollectorOp.DISCARD, + ) + tiled_mma_sfb.set(tcgen05.Field.NEGATE_A, False) + tiled_mma_sfb.set(tcgen05.Field.NEGATE_B, False) + return (tiled_mma_first, tiled_mma_mid, tiled_mma_last), tiled_mma_sfb + + def _cluster_layouts(self, tiled_mma, tiled_mma_sfb): + vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), (tiled_mma.thr_id.shape,) + ) + sfb_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), + (tiled_mma_sfb.thr_id.shape,), + ) + is_a_mcast = cute.size(vmnk.shape[2]) > 1 + is_b_mcast = cute.size(vmnk.shape[1]) > 1 + return vmnk, sfb_vmnk, is_a_mcast, is_b_mcast + + def _setup_attributes(self): + self.mma_inst_shape_sfb = ( + self.mma_inst_shape[0] // self.atom_thr_size, + cute.round_up(self.mma_inst_shape[1], 128), + self.mma_inst_shape[2], + ) + self.mma_tiler_sfb = ( + self.mma_inst_shape_sfb[0], + self.mma_tiler[1], + self.mma_tiler[2], + ) + (tiled_mma, _, _), _ = self._make_tiled_mmas() + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + a_one = sm100_utils.make_smem_layout_a(tiled_mma, self.mma_tiler, self.a_dtype, 1) + b_one = sm100_utils.make_smem_layout_b(tiled_mma, self.mma_tiler, self.b_dtype, 1) + sfa_one = blockscaled_utils.make_smem_layout_sfa( + tiled_mma, self.mma_tiler, self.sf_vec_size, 1 + ) + sfb_one = blockscaled_utils.make_smem_layout_sfb( + tiled_mma, self.mma_tiler, self.sf_vec_size, 1 + ) + stage_bytes = ( + cute.size_in_bytes(self.a_dtype, a_one) + + cute.size_in_bytes(self.b_dtype, b_one) + + cute.size_in_bytes(self.sf_dtype, sfa_one) + + cute.size_in_bytes(self.sf_dtype, sfb_one) + ) + # barriers, CLC response, (1 + w) table (4 x 128 fp32) and slack + helpers_bytes = 1024 + 4 * HEAD_DIM * 4 + 1024 + self.num_ab_stage = (self.smem_capacity // self.occupancy - helpers_bytes) // stage_bytes + + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, self.mma_tiler, self.a_dtype, self.num_ab_stage + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, self.mma_tiler, self.b_dtype, self.num_ab_stage + ) + self.sfa_smem_layout_staged = blockscaled_utils.make_smem_layout_sfa( + tiled_mma, self.mma_tiler, self.sf_vec_size, self.num_ab_stage + ) + self.sfb_smem_layout_staged = blockscaled_utils.make_smem_layout_sfb( + tiled_mma, self.mma_tiler, self.sf_vec_size, self.num_ab_stage + ) + self.tCtSFA_layout = blockscaled_utils.make_tmem_layout_sfa( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(self.sfa_smem_layout_staged, (None, None, None, 0)), + ) + self.tCtSFB_layout = blockscaled_utils.make_tmem_layout_sfb( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(self.sfb_smem_layout_staged, (None, None, None, 0)), + ) + self.num_sfa_tmem_cols = ( + cute.cosize(cute.recast_layout(32, self.sf_dtype.width, self.tCtSFA_layout)) + & 0x0000FFFF + ) + self.num_sfb_tmem_cols = ( + cute.cosize(cute.recast_layout(32, self.sf_dtype.width, self.tCtSFB_layout)) + & 0x0000FFFF + ) + sf_cols = self.num_sfa_tmem_cols + self.num_sfb_tmem_cols + max_acc_stage = (self.num_tmem_alloc_cols - sf_cols) // self.tile_n + if self.requested_acc_stage is None: + self.num_acc_stage = max(1, min(4, max_acc_stage)) + else: + self.num_acc_stage = int(self.requested_acc_stage) + if self.num_acc_stage < 1 or self.num_acc_stage > max_acc_stage: + raise ValueError( + f"num_acc_stage={self.num_acc_stage} does not fit TMEM " + f"(max {max_acc_stage} for tile_n={self.tile_n})" + ) + self.num_accumulator_tmem_cols = self.tile_n * self.num_acc_stage + if os.environ.get("CUTE_DSL_DUMP_STAGES"): + print( + f"[stages] num_ab_stage={self.num_ab_stage} stage_bytes={stage_bytes} " + f"num_acc_stage={self.num_acc_stage} sf_cols={sf_cols}", + flush=True, + ) + + # ------------------------------------------------------------------ + @cute.jit + def __call__( + self, + activation: cute.Tensor, # (M, K) e4m3 + activation_sf: cute.Tensor, # 1-D swizzled UE8M0 K32 + weight: cute.Tensor, # (N, K) e4m3 + weight_sf: cute.Tensor, # 1-D swizzled UE8M0 K32 + alpha: cute.Tensor, # (1,) f32 + q_out: cute.Tensor, # (M * Hq * 128,) u8 (E4M3 bytes) + index_q_out: cute.Tensor, # (M * Hi * 128,) u8 + kv_data_cache: cute.Tensor, # u8, flat + kv_scale_cache: cute.Tensor, # u8, flat + index_k_cache: cute.Tensor, # u8 (E4M3 bytes), flat + out_cache_loc: cute.Tensor, # (>= M,) i32 + kv_quant_scale: cute.Tensor, # (3,) f32 + rotary_cos_sin: cute.Tensor, # (max_pos * 64,) f32 + position_ids: cute.Tensor, # (M,) i32 + norm_weights: cute.Tensor, # (4 * 128,) bf16: q, K, index-q, index-K + gemm_out: cute.Tensor, # (M * N,) bf16, debug only + data_page_stride: cutlass.Int64, + data_plane_stride: cutlass.Int64, + data_head_stride: cutlass.Int64, + data_token_stride: cutlass.Int64, + scale_page_stride: cutlass.Int64, + scale_plane_stride: cutlass.Int64, + scale_head_stride: cutlass.Int64, + index_page_stride: cutlass.Int64, + index_token_stride: cutlass.Int64, + num_pages: cutlass.Int64, + eps: cutlass.Float32, + stream: cuda_driver.CUstream, + ): + self.a_dtype = activation.element_type + self.b_dtype = weight.element_type + self.sf_dtype = activation_sf.element_type + self.a_major_mode = OperandMajorMode.K + self.b_major_mode = OperandMajorMode.K + + m = activation.shape[0] + k = activation.shape[1] + n = weight.shape[0] + + self._setup_attributes() + tiled_mmas, tiled_mma_sfb = self._make_tiled_mmas() + tiled_mma = tiled_mmas[0] + + a_tensor = cute.make_tensor( + activation.iterator, cute.make_ordered_layout((m, k, 1), order=(1, 0, 2)) + ) + b_tensor = cute.make_tensor( + weight.iterator, cute.make_ordered_layout((n, k, 1), order=(1, 0, 2)) + ) + sfa_tensor = cute.make_tensor( + activation_sf.iterator, + blockscaled_utils.tile_atom_to_shape_SF(a_tensor.shape, self.sf_vec_size), + ) + sfb_tensor = cute.make_tensor( + weight_sf.iterator, + blockscaled_utils.tile_atom_to_shape_SF(b_tensor.shape, self.sf_vec_size), + ) + tma_atoms, tma_tensors = self._make_tma_atoms( + tiled_mma, tiled_mma_sfb, a_tensor, b_tensor, sfa_tensor, sfb_tensor + ) + + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + sfa_smem_layout = cute.slice_(self.sfa_smem_layout_staged, (None, None, None, 0)) + sfb_smem_layout = cute.slice_(self.sfb_smem_layout_staged, (None, None, None, 0)) + self.num_tma_load_bytes = ( + cute.size_in_bytes(self.a_dtype, a_smem_layout) + + cute.size_in_bytes(self.sf_dtype, sfa_smem_layout) + + cute.size_in_bytes(self.b_dtype, b_smem_layout) + + cute.size_in_bytes(self.sf_dtype, sfb_smem_layout) + ) * self.atom_thr_size + + num_ctas_mnl = ( + cute.ceil_div(m, self.cta_tile_shape_mnk[0]), + (self.num_slots + self.heads_per_tile - 1) // self.heads_per_tile, + 1, + ) + tile_sched_params = ClcDynamicPersistentTileSchedulerParams( + num_ctas_mnl, + (*self.cluster_shape_mn, 1), + self.swizzle_size, + self.raster_along_m, + ) + grid = ClcDynamicPersistentTileScheduler.get_grid_shape(tile_sched_params) + + self.buffer_align_bytes = 1024 + + @cute.struct + class SharedStorage: + ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + ab_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + acc_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + acc_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + clc_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_clc_stage * 2] + clc_response: cute.struct.Align[ + cute.struct.MemRange[cutlass.Int32, self.num_clc_stage * 4], 16 + ] + sOnePlusW: cute.struct.Align[cute.struct.MemRange[cutlass.Float32, 4 * HEAD_DIM], 16] + tmem_dealloc_mbar: cutlass.Int64 + tmem_holding_buf: cutlass.Int32 + sA: cute.struct.Align[ + cute.struct.MemRange[self.a_dtype, cute.cosize(self.a_smem_layout_staged.outer)], + self.buffer_align_bytes, + ] + sB: cute.struct.Align[ + cute.struct.MemRange[self.b_dtype, cute.cosize(self.b_smem_layout_staged.outer)], + self.buffer_align_bytes, + ] + sSFA: cute.struct.Align[ + cute.struct.MemRange[self.sf_dtype, cute.cosize(self.sfa_smem_layout_staged)], + self.buffer_align_bytes, + ] + sSFB: cute.struct.Align[ + cute.struct.MemRange[self.sf_dtype, cute.cosize(self.sfb_smem_layout_staged)], + self.buffer_align_bytes, + ] + + self.shared_storage = SharedStorage + + self.kernel( + tiled_mmas[0], + tiled_mmas[1], + tiled_mmas[2], + tiled_mma_sfb, + tma_atoms, + tma_tensors, + alpha, + q_out, + index_q_out, + kv_data_cache, + kv_scale_cache, + index_k_cache, + out_cache_loc, + kv_quant_scale, + rotary_cos_sin, + position_ids, + norm_weights, + gemm_out, + ( + data_page_stride, + data_plane_stride, + data_head_stride, + data_token_stride, + scale_page_stride, + scale_plane_stride, + scale_head_stride, + index_page_stride, + index_token_stride, + ), + num_pages, + tile_sched_params, + (m, n), + eps, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + min_blocks_per_mp=1, + smem_merge_branch_allocs=True, + ) + return + + @cute.jit + def _make_tma_atoms(self, tiled_mma, tiled_mma_sfb, a_tensor, b_tensor, sfa_tensor, sfb_tensor): + vmnk, sfb_vmnk, _, _ = self._cluster_layouts(tiled_mma, tiled_mma_sfb) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + sfa_smem_layout = cute.slice_(self.sfa_smem_layout_staged, (None, None, None, 0)) + sfb_smem_layout = cute.slice_(self.sfb_smem_layout_staged, (None, None, None, 0)) + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + sm100_utils.cluster_shape_to_tma_atom_A(self.cluster_shape_mn, tiled_mma.thr_id), + a_tensor, + a_smem_layout, + self.mma_tiler, + tiled_mma, + vmnk.shape, + ) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + sm100_utils.cluster_shape_to_tma_atom_B(self.cluster_shape_mn, tiled_mma.thr_id), + b_tensor, + b_smem_layout, + self.mma_tiler, + tiled_mma, + vmnk.shape, + ) + tma_atom_sfa, tma_tensor_sfa = cute.nvgpu.make_tiled_tma_atom_A( + sm100_utils.cluster_shape_to_tma_atom_A(self.cluster_shape_mn, tiled_mma.thr_id), + sfa_tensor, + sfa_smem_layout, + self.mma_tiler, + tiled_mma, + vmnk.shape, + internal_type=cutlass.Int16, + ) + tma_atom_sfb, tma_tensor_sfb = cute.nvgpu.make_tiled_tma_atom_B( + sm100_utils.cluster_shape_to_tma_atom_SFB(self.cluster_shape_mn, tiled_mma.thr_id), + sfb_tensor, + sfb_smem_layout, + self.mma_tiler_sfb, + tiled_mma_sfb, + sfb_vmnk.shape, + internal_type=cutlass.Int16, + ) + return ( + (tma_atom_a, tma_atom_b, tma_atom_sfa, tma_atom_sfb), + (tma_tensor_a, tma_tensor_b, tma_tensor_sfa, tma_tensor_sfb), + ) + + # ------------------------------------------------------------------ + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tiled_mma_mid: cute.TiledMma, + tiled_mma_last: cute.TiledMma, + tiled_mma_sfb: cute.TiledMma, + tma_atoms: Tuple, + tma_tensors: Tuple, + alpha: cute.Tensor, + q_out: cute.Tensor, + index_q_out: cute.Tensor, + kv_data_cache: cute.Tensor, + kv_scale_cache: cute.Tensor, + index_k_cache: cute.Tensor, + out_cache_loc: cute.Tensor, + kv_quant_scale: cute.Tensor, + rotary_cos_sin: cute.Tensor, + position_ids: cute.Tensor, + norm_weights: cute.Tensor, + gemm_out: cute.Tensor, + cache_strides: Tuple, + num_pages: cutlass.Int64, + tile_sched_params: ClcDynamicPersistentTileSchedulerParams, + problem_mn: Tuple, + eps: cutlass.Float32, + ): + self._setup_attributes() + tma_atom_a, tma_atom_b, tma_atom_sfa, tma_atom_sfb = tma_atoms + mA_mkl, mB_nkl, mSFA_mkl, mSFB_nkl = tma_tensors + m, n = problem_mn + m_i32 = cutlass.Int32(m) + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + + ( + cluster_layout_vmnk, + cluster_layout_sfb_vmnk, + is_a_mcast, + is_b_mcast, + ) = self._cluster_layouts(tiled_mma, tiled_mma_sfb) + + if warp_idx == self.tma_warp_id: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_sfa) + cpasync.prefetch_descriptor(tma_atom_sfb) + + bidx, bidy, bidz = cute.arch.block_idx() + mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape) + is_leader_cta = mma_tile_coord_v == 0 + cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) + block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord(cta_rank_in_cluster) + block_in_cluster_coord_sfb_vmnk = cluster_layout_sfb_vmnk.get_flat_coord( + cta_rank_in_cluster + ) + tidx, _, _ = cute.arch.thread_idx() + + smem = utils.SmemAllocator() + storage = smem.allocate(self.shared_storage) + + num_mcast_ctas_a = cute.size(cluster_layout_vmnk.shape[2]) + num_mcast_ctas_b = cute.size(cluster_layout_vmnk.shape[1]) + num_tma_producers = num_mcast_ctas_a + num_mcast_ctas_b - 1 + ab_pipeline = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), + num_stages=self.num_ab_stage, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, num_tma_producers), + tx_count=self.num_tma_load_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + acc_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), + num_stages=self.num_acc_stage, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup( + pipeline.Agent.Thread, 32 * len(self.epilog_warp_id) * self.atom_thr_size + ), + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + cluster_size = cute.size(cluster_layout_vmnk.shape) + num_clc_consumer_threads = 32 * (1 + cluster_size * (1 + len(self.epilog_warp_id) + 1)) + clc_pipeline = pipeline.PipelineClcFetchAsync.create( + barrier_storage=storage.clc_mbar_ptr.data_ptr(), + num_stages=self.num_clc_stage, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_clc_consumer_threads + ), + tx_count=self.num_clc_response_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + tmem = utils.TmemAllocator( + storage.tmem_holding_buf.ptr, + barrier_for_retrieve=self.tmem_alloc_barrier, + allocator_warp_id=self.epilog_warp_id[0], + is_two_cta=self.use_2cta_instrs, + two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr, + arch=self.arch, + ) + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + + sA = storage.sA.get_tensor( + self.a_smem_layout_staged.outer, swizzle=self.a_smem_layout_staged.inner + ) + sB = storage.sB.get_tensor( + self.b_smem_layout_staged.outer, swizzle=self.b_smem_layout_staged.inner + ) + sSFA = storage.sSFA.get_tensor(self.sfa_smem_layout_staged) + sSFB = storage.sSFB.get_tensor(self.sfb_smem_layout_staged) + + a_full_mcast_mask = None + b_full_mcast_mask = None + sfa_full_mcast_mask = None + sfb_full_mcast_mask = None + if cutlass.const_expr(is_a_mcast or is_b_mcast or self.use_2cta_instrs): + a_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + b_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1 + ) + sfa_full_mcast_mask = a_full_mcast_mask + sfb_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_sfb_vmnk, block_in_cluster_coord_sfb_vmnk, mcast_mode=1 + ) + + gA_mkl = cute.local_tile( + mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + gSFA_mkl = cute.local_tile( + mSFA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + gSFB_nkl = cute.local_tile( + mSFB_nkl, cute.slice_(self.mma_tiler_sfb, (0, None, None)), (None, None, None) + ) + k_tile_cnt = cute.size(gA_mkl, mode=[3]) + + thr_mma = tiled_mma.get_slice(mma_tile_coord_v) + thr_mma_sfb = tiled_mma_sfb.get_slice(mma_tile_coord_v) + tCgA = thr_mma.partition_A(gA_mkl) + tCgB = thr_mma.partition_B(gB_nkl) + tCgSFA = thr_mma.partition_A(gSFA_mkl) + tCgSFB = thr_mma_sfb.partition_B(gSFB_nkl) + + a_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + block_in_cluster_coord_vmnk[2], + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + b_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + block_in_cluster_coord_vmnk[1], + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + tAsSFA, tAgSFA = cpasync.tma_partition( + tma_atom_sfa, + block_in_cluster_coord_vmnk[2], + a_cta_layout, + cute.group_modes(sSFA, 0, 3), + cute.group_modes(tCgSFA, 0, 3), + ) + tAsSFA = cute.filter_zeros(tAsSFA) + tAgSFA = cute.filter_zeros(tAgSFA) + sfb_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_sfb_vmnk, (0, None, 0, 0)).shape + ) + tBsSFB, tBgSFB = cpasync.tma_partition( + tma_atom_sfb, + block_in_cluster_coord_sfb_vmnk[1], + sfb_cta_layout, + cute.group_modes(sSFB, 0, 3), + cute.group_modes(tCgSFB, 0, 3), + ) + tBsSFB = cute.filter_zeros(tBsSFB) + tBgSFB = cute.filter_zeros(tBgSFB) + + tCrA = tiled_mma.make_fragment_A(sA) + tCrB = tiled_mma.make_fragment_B(sB) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C(cute.append(acc_shape, self.num_acc_stage)) + + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + + clc_response_ptr = storage.clc_response.data_ptr() + clc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_clc_stage + ) + is_first_cta_in_cluster = cta_rank_in_cluster == 0 + tile_sched = ClcDynamicPersistentTileScheduler.create( + tile_sched_params, + cute.arch.block_idx(), + cute.arch.grid_dim(), + clc_response_ptr, + physical_cluster_shape_mn=self.cluster_shape_mn, + ) + work_tile = tile_sched.initial_work_tile_info() + + # ============================================================== + # Epilogue warps + # ============================================================== + if warp_idx < self.mma_warp_id: + cute.arch.setmaxregister_increase(self.epilog_reg_count) + if cutlass.const_expr(self.enable_pdl): + cute.arch.griddepcontrol_wait() + tmem.allocate(self.num_tmem_alloc_cols) + tmem.wait_for_alloc() + acc_tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + + s_w_addr = cutlass.Int32(storage.sOnePlusW.data_ptr().toint()) + if cutlass.const_expr(not self.debug_gemm_out): + # (1 + w) per (slot type, dim), as the producer's FADD. + nw_addr = norm_weights.iterator.toint().to(cutlass.Int64) + for r in cutlass.range_constexpr(4 // self.epi_wgs): + j = tidx + cutlass.Int32(32 * len(self.epilog_warp_id) * r) + w_bits = _ldg_u16(nw_addr + j.to(cutlass.Int64) * cutlass.Int64(2)) + w_f = (w_bits << cutlass.Int32(16)).bitcast(cutlass.Float32) + _sts_f32(s_w_addr + j * cutlass.Int32(4), _add_rn(w_f, cutlass.Float32(1.0))) + self.epilog_sync_barrier.arrive_and_wait() + + alpha_v = alpha[0] + sl_k = kv_quant_scale[1] + sl_v = kv_quant_scale[2] + rcp_six = cutlass.Int32(RCP_SIX_BITS).bitcast(cutlass.Float32) + ( + data_page_stride, + data_plane_stride, + data_head_stride, + data_token_stride, + scale_page_stride, + scale_plane_stride, + scale_head_stride, + index_page_stride, + index_token_stride, + ) = cache_strides + q_addr = q_out.iterator.toint().to(cutlass.Int64) + iq_addr = index_q_out.iterator.toint().to(cutlass.Int64) + kvd_addr = kv_data_cache.iterator.toint().to(cutlass.Int64) + kvs_addr = kv_scale_cache.iterator.toint().to(cutlass.Int64) + ik_addr = index_k_cache.iterator.toint().to(cutlass.Int64) + cs_addr = rotary_cos_sin.iterator.toint().to(cutlass.Int64) + pos_addr = position_ids.iterator.toint().to(cutlass.Int64) + loc_addr = out_cache_loc.iterator.toint().to(cutlass.Int64) + g_addr = gemm_out.iterator.toint().to(cutlass.Int64) + + # TMEM -> register copy: thread t owns tile row t, 32 columns per load. + tCtAcc_all = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout) + tCtAcc_x = gemm_sm100.transform_partitioned_tensor_layout(tCtAcc_all) + epi_tile = (self.cta_tile_shape_mnk[0], self.epi_chunk) + tAcc_epi = cute.flat_divide(tCtAcc_x, epi_tile) + copy_atom_t2r = cute.make_copy_atom( + tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(self.epi_chunk)), + self.acc_dtype, + ) + tiled_copy_t2r = tcgen05.make_tmem_copy(copy_atom_t2r, tAcc_epi[(None, None, 0, 0, 0)]) + row_in_cta = tidx % cutlass.Int32(128) + epi_wg = cute.arch.make_warp_uniform(warp_idx // cutlass.Int32(4)) + thr_copy_t2r = tiled_copy_t2r.get_slice(row_in_cta) + tTR_tAcc = thr_copy_t2r.partition_S(tAcc_epi) + cC = cute.make_identity_tensor(epi_tile) + tTR_cC = thr_copy_t2r.partition_D(cC) + tTR_rAcc = cute.make_rmem_tensor(tTR_cC.shape, self.acc_dtype) + tTR_rAcc_flat = cute.make_tensor(tTR_rAcc.iterator, cute.make_layout((self.epi_chunk,))) + + acc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_acc_stage + ) + + while work_tile.is_valid_tile: + cur_tile_coord = work_tile.tile_idx + row = cur_tile_coord[0] * cutlass.Int32(self.cta_tile_shape_mnk[0]) + row_in_cta + head0 = cur_tile_coord[1] * cutlass.Int32(self.heads_per_tile) + row_ok = row < m_i32 + row_c = cutlass.Int32(cutlass.select_(row_ok, row, m_i32 - cutlass.Int32(1))) + row64 = row_c.to(cutlass.Int64) + + if cutlass.const_expr(not self.debug_gemm_out): + position = _ldg_s32(pos_addr + row64 * cutlass.Int64(4)) + slot = _ldg_s32(loc_addr + row64 * cutlass.Int64(4)) + cs_row = cs_addr + position.to(cutlass.Int64) * cutlass.Int64(ROTARY_DIM * 4) + cs = [] + for qd in cutlass.range_constexpr(ROTARY_DIM // 4): + cs.extend(_ldg_v4_f32(cs_row + cutlass.Int64(16 * qd))) + slot_ok = slot >= cutlass.Int32(0) + slot_c = cutlass.Int32(cutlass.select_(slot_ok, slot, 0)) + page = (slot_c // cutlass.Int32(PAGE_SIZE)).to(cutlass.Int64) + within = (slot_c & cutlass.Int32(PAGE_SIZE - 1)).to(cutlass.Int64) + cache_ok = row_ok & slot_ok & (page < num_pages) + + acc_pipeline.consumer_wait(acc_consumer_state) + + def load_head(h): + # TMEM -> registers, bf16_rn(alpha * acc) packed in pairs. + words = [] + for c in cutlass.range_constexpr(self.chunks_per_head): + cute.copy( + tiled_copy_t2r, + tTR_tAcc[ + ( + None, + None, + None, + 0, + h * cutlass.Int32(self.chunks_per_head) + cutlass.Int32(c), + acc_consumer_state.index, + ) + ], + tTR_rAcc, + ) + for p in cutlass.range_constexpr(self.epi_chunk // 2): + a0, a1 = cute.arch.mul_packed_f32x2( + (tTR_rAcc_flat[2 * p], tTR_rAcc_flat[2 * p + 1]), + (alpha_v, alpha_v), + ) + words.append(_bf16x2_rn(a0, a1)) + return words + + def release_acc(): + cute.arch.fence_view_async_tmem_load() + nvvm.tcgen05_fence(nvvm.Tcgen05FenceKind.BEFORE_THREAD_SYNC) + acc_pipeline.consumer_release(acc_consumer_state) + + for hl in cutlass.range_constexpr(self.heads_per_wg): + h = epi_wg * cutlass.Int32(self.heads_per_wg) + cutlass.Int32(hl) + head = head0 + h + words = load_head(h) + if cutlass.const_expr(hl == self.heads_per_wg - 1): + release_acc() + + if cutlass.const_expr(self.debug_gemm_out): + if row_ok & (head < cutlass.Int32(self.num_slots)): + base = g_addr + ( + row64 * cutlass.Int64(self.n_total) + + head.to(cutlass.Int64) * cutlass.Int64(HEAD_DIM) + ) * cutlass.Int64(2) + for v in cutlass.range_constexpr(HEAD_DIM // 8): + _stg_v4( + base + cutlass.Int64(16 * v), + words[4 * v], + words[4 * v + 1], + words[4 * v + 2], + words[4 * v + 3], + ) + else: + valid = head < cutlass.Int32(self.num_slots) + is_v = (head >= cutlass.Int32(self.v_begin)) & ( + head < cutlass.Int32(self.iq_begin) + ) + not_v = (head < cutlass.Int32(self.v_begin)) | ( + head >= cutlass.Int32(self.iq_begin) + ) + if valid & is_v: + dw, sb = self._nvfp4_pack(self._unpack(words), False, sl_v, rcp_six) + if cache_ok: + self._store_kv( + dw, + sb, + False, + kvd_addr, + kvs_addr, + (head - cutlass.Int32(self.v_begin)).to(cutlass.Int64), + page, + within, + cache_strides, + ) + if valid & not_v: + e = self._norm_rope(words, head, cs, s_w_addr, eps) + if (head >= cutlass.Int32(self.k_begin)) & ( + head < cutlass.Int32(self.v_begin) + ): + dw, sb = self._nvfp4_pack(e, True, sl_k, rcp_six) + if cache_ok: + self._store_kv( + dw, + sb, + True, + kvd_addr, + kvs_addr, + (head - cutlass.Int32(self.k_begin)).to(cutlass.Int64), + page, + within, + cache_strides, + ) + else: + packed = [] + for i in cutlass.range_constexpr(HEAD_DIM // 4): + packed.append( + _e4m3x4(e[4 * i], e[4 * i + 1], e[4 * i + 2], e[4 * i + 3]) + ) + is_q = head < cutlass.Int32(self.k_begin) + is_iq = head < cutlass.Int32(self.ik_slot) + q_dst = q_addr + ( + row64 * cutlass.Int64(self.num_heads_q) + head.to(cutlass.Int64) + ) * cutlass.Int64(HEAD_DIM) + iq_dst = iq_addr + ( + row64 * cutlass.Int64(self.num_heads_index) + + (head - cutlass.Int32(self.iq_begin)).to(cutlass.Int64) + ) * cutlass.Int64(HEAD_DIM) + ik_dst = ( + ik_addr + page * index_page_stride + within * index_token_stride + ) + dst = cutlass.Int64( + cutlass.select_( + is_q, + q_dst, + cutlass.Int64(cutlass.select_(is_iq, iq_dst, ik_dst)), + ) + ) + ok = cutlass.Boolean(cutlass.select_(is_iq, row_ok, cache_ok)) + if ok: + for v in cutlass.range_constexpr(HEAD_DIM // 16): + _stg_v4( + dst + cutlass.Int64(16 * v), + packed[4 * v], + packed[4 * v + 1], + packed[4 * v + 2], + packed[4 * v + 3], + ) + + acc_consumer_state.advance() + clc_pipeline.consumer_wait(clc_consumer_state) + work_tile = tile_sched.get_current_work() + clc_pipeline.consumer_release(clc_consumer_state) + clc_consumer_state.advance() + + tmem.relinquish_alloc_permit() + # Every epilogue warp is done reading TMEM before the allocator frees it. + self.epilog_sync_barrier.arrive_and_wait() + tmem.free(acc_tmem_ptr) + + # ============================================================== + # TMA warp + # ============================================================== + if warp_idx == self.tma_warp_id: + cute.arch.setmaxregister_decrease(self.mainloop_reg_count) + if cutlass.const_expr(self.enable_pdl): + cute.arch.griddepcontrol_wait() + a_cache_policy = cutlass.Int64(0x14F0000000000000) # L2 evict_last + ab_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_ab_stage + ) + while work_tile.is_valid_tile: + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_m = cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape) + n_tile = cur_tile_coord[1] + tAgA_slice = tAgA[(None, mma_tile_coord_m, None, 0)] + tBgB_slice = tBgB[(None, n_tile, None, 0)] + tAgSFA_slice = tAgSFA[(None, mma_tile_coord_m, None, 0)] + tBgSFB_slice = tBgSFB[(None, n_tile, None, 0)] + + ab_producer_state.reset_count() + peek_ab_empty_status = cutlass.Boolean(1) + if ab_producer_state.count < k_tile_cnt: + peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state) + for k_tile in cutlass.range(0, k_tile_cnt, 1, unroll=1): + ab_pipeline.producer_acquire(ab_producer_state, peek_ab_empty_status) + tma_bar = ab_pipeline.producer_get_barrier(ab_producer_state) + cute.copy( + tma_atom_a, + tAgA_slice[(None, ab_producer_state.count)], + tAsA[(None, ab_producer_state.index)], + tma_bar_ptr=tma_bar, + mcast_mask=a_full_mcast_mask, + cache_policy=a_cache_policy, + ) + cute.copy( + tma_atom_sfa, + tAgSFA_slice[(None, ab_producer_state.count)], + tAsSFA[(None, ab_producer_state.index)], + tma_bar_ptr=tma_bar, + mcast_mask=sfa_full_mcast_mask, + cache_policy=a_cache_policy, + ) + cute.copy( + tma_atom_b, + tBgB_slice[(None, ab_producer_state.count)], + tBsB[(None, ab_producer_state.index)], + tma_bar_ptr=tma_bar, + mcast_mask=b_full_mcast_mask, + ) + cute.copy( + tma_atom_sfb, + tBgSFB_slice[(None, ab_producer_state.count)], + tBsSFB[(None, ab_producer_state.index)], + tma_bar_ptr=tma_bar, + mcast_mask=sfb_full_mcast_mask, + ) + ab_producer_state.advance() + peek_ab_empty_status = cutlass.Boolean(1) + if ab_producer_state.count < k_tile_cnt: + peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state) + clc_pipeline.consumer_wait(clc_consumer_state) + work_tile = tile_sched.get_current_work() + clc_pipeline.consumer_release(clc_consumer_state) + clc_consumer_state.advance() + if cutlass.const_expr(self.enable_pdl): + cute.arch.griddepcontrol_launch_dependents() + ab_pipeline.producer_tail(ab_producer_state) + + # ============================================================== + # MMA warp + # ============================================================== + if warp_idx == self.mma_warp_id: + cute.arch.setmaxregister_decrease(self.mainloop_reg_count) + tmem.wait_for_alloc() + acc_tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout) + sfa_tmem_ptr = cute.recast_ptr( + acc_tmem_ptr + self.num_accumulator_tmem_cols, dtype=self.sf_dtype + ) + tCtSFA = cute.make_tensor(sfa_tmem_ptr, self.tCtSFA_layout) + sfb_tmem_ptr = cute.recast_ptr( + acc_tmem_ptr + self.num_accumulator_tmem_cols + self.num_sfa_tmem_cols, + dtype=self.sf_dtype, + ) + tCtSFB = cute.make_tensor(sfb_tmem_ptr, self.tCtSFB_layout) + + sfa_s2t = self._mainloop_s2t_copy_and_partition(sSFA, tCtSFA) + sfb_s2t = self._mainloop_s2t_copy_and_partition(sSFB, tCtSFB) + + ab_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_ab_stage + ) + acc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_acc_stage + ) + while work_tile.is_valid_tile: + ab_consumer_state.reset_count() + peek_ab_full_status = cutlass.Boolean(1) + if ab_consumer_state.count < k_tile_cnt and is_leader_cta: + peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_consumer_state) + if is_leader_cta: + acc_pipeline.producer_acquire(acc_producer_state) + tCtAcc_stage = tCtAcc_base[(None, None, None, acc_producer_state.index)] + + for k_tile in cutlass.range(0, k_tile_cnt, 1, unroll=1): + if is_leader_cta: + ab_pipeline.consumer_wait(ab_consumer_state, peek_ab_full_status) + self._mainloop_s2t_copies(ab_consumer_state.index, sfa_s2t, sfb_s2t) + num_kblocks = cute.size(tCrA, mode=[2]) + for k_block in cutlass.range(num_kblocks, unroll_full=True): + a_kblk_crd = (None, 0, k_block, ab_consumer_state.index) + sfa_kblk_crd = (None, 0, k_block) + for n_set in cutlass.range_constexpr(self.n_sets): + b_kblk_crd = (None, n_set, k_block, ab_consumer_state.index) + sfb_kblk_crd = (None, n_set, k_block) + tCtAcc_set = tCtAcc_stage[(None, 0, n_set)] + mma_op = ( + tiled_mma + if n_set == 0 + else ( + tiled_mma_last + if n_set == self.n_sets - 1 + else tiled_mma_mid + ) + ) + mma_op.set(tcgen05.Field.ACCUMULATE, k_tile != 0 or k_block != 0) + cute.gemm( + mma_op, + tCtAcc_set, + [tCrA[a_kblk_crd], tCtSFA[sfa_kblk_crd]], + [tCrB[b_kblk_crd], tCtSFB[sfb_kblk_crd]], + tCtAcc_set, + ) + ab_pipeline.consumer_release(ab_consumer_state) + ab_consumer_state.advance() + peek_ab_full_status = cutlass.Boolean(1) + if ab_consumer_state.count < k_tile_cnt: + if is_leader_cta: + peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_consumer_state) + if is_leader_cta: + acc_pipeline.producer_commit(acc_producer_state) + acc_producer_state.advance() + clc_pipeline.consumer_wait(clc_consumer_state) + work_tile = tile_sched.get_current_work() + clc_pipeline.consumer_release(clc_consumer_state) + clc_consumer_state.advance() + acc_pipeline.producer_tail(acc_producer_state) + + # ============================================================== + # CLC scheduler warp + # ============================================================== + if warp_idx == self.sched_warp_id: + cute.arch.setmaxregister_decrease(self.mainloop_reg_count) + if is_first_cta_in_cluster: + clc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.ProducerConsumer, self.num_clc_stage + ) + while work_tile.is_valid_tile: + clc_pipeline.producer_acquire(clc_producer_state) + mbarrier_addr = clc_pipeline.producer_get_barrier(clc_producer_state) + tile_sched.advance_to_next_work(mbarrier_addr) + clc_producer_state.advance() + clc_pipeline.consumer_wait(clc_consumer_state) + work_tile = tile_sched.get_current_work() + clc_pipeline.consumer_release(clc_consumer_state) + clc_consumer_state.advance() + clc_pipeline.producer_tail(clc_producer_state) + + if warp_idx == self.pad_warp_id: + cute.arch.setmaxregister_decrease(self.mainloop_reg_count) + + # ------------------------------------------------------------------ + # Straight-line epilogue helpers (plain Python: traced inline, no + # dynamic control flow inside). + # ------------------------------------------------------------------ + @staticmethod + def _unpack(words): + x = [] + for w in words: + x.append(_lo_f32(w)) + x.append(_hi_f32(w)) + return x + + def _norm_rope(self, words, head, cs, s_w_addr, eps): + """RMSNorm (1 + w) + NeoX rope of one head row in the producer's op order.""" + x = self._unpack(words) + # Lane partials: (0 + fma(x0, x0, x1*x1)) + fma(x2, x2, x3*x3); the + # leading 0 + is exact (the partial is never -0). + q = [] + for l in range(32): + yy0, yy1 = cute.arch.mul_packed_f32x2( + (x[4 * l + 1], x[4 * l + 3]), (x[4 * l + 1], x[4 * l + 3]) + ) + q.append( + cute.arch.fma_packed_f32x2( + (x[4 * l], x[4 * l + 2]), (x[4 * l], x[4 * l + 2]), (yy0, yy1) + ) + ) + lane = [] + for l in range(16): + s0, s1 = cute.arch.add_packed_f32x2( + (q[2 * l][0], q[2 * l + 1][0]), (q[2 * l][1], q[2 * l + 1][1]) + ) + lane.append(s0) + lane.append(s1) + # warpReduceSum (xor 16, 8, 4, 2, 1) as computed by lane 0. + half = 16 + while half > 1: + nxt = [] + for l in range(half // 2): + a0, a1 = cute.arch.add_packed_f32x2( + (lane[2 * l], lane[2 * l + 1]), (lane[2 * l + half], lane[2 * l + 1 + half]) + ) + nxt.append(a0) + nxt.append(a1) + lane = nxt + half //= 2 + total = _add_rn(lane[0], lane[1]) + inv_rms = _rsqrt_approx(_fma_rn(total, cutlass.Float32(1.0 / HEAD_DIM), eps)) + + is_q = head < cutlass.Int32(self.k_begin) + is_k = head < cutlass.Int32(self.v_begin) + is_iq = head < cutlass.Int32(self.ik_slot) + w_type = cutlass.Int32( + cutlass.select_( + is_q, + cutlass.Int32(0), + cutlass.Int32( + cutlass.select_( + is_k, + cutlass.Int32(1), + cutlass.Int32(cutlass.select_(is_iq, cutlass.Int32(2), cutlass.Int32(3))), + ) + ), + ) + ) + w_base = s_w_addr + w_type * cutlass.Int32(HEAD_DIM * 4) + e = [] + for qd in range(HEAD_DIM // 4): + opw = _lds_v4_f32(w_base + cutlass.Int32(16 * qd)) + t0, t1 = cute.arch.mul_packed_f32x2((inv_rms, inv_rms), (opw[0], opw[1])) + t2, t3 = cute.arch.mul_packed_f32x2((inv_rms, inv_rms), (opw[2], opw[3])) + e0, e1 = cute.arch.mul_packed_f32x2((x[4 * qd], x[4 * qd + 1]), (t0, t1)) + e2, e3 = cute.arch.mul_packed_f32x2((x[4 * qd + 2], x[4 * qd + 3]), (t2, t3)) + e.extend([e0, e1, e2, e3]) + half_rot = ROTARY_DIM // 2 + out = list(e) + for d in range(half_rot): + cos_v = cs[d] + sin_v = cs[half_rot + d] + lo = e[d] + hi = e[d + half_rot] + m0, m1 = cute.arch.mul_packed_f32x2((lo, hi), (cos_v, cos_v)) + r0, r1 = cute.arch.fma_packed_f32x2((-hi, lo), (sin_v, sin_v), (m0, m1)) + out[d] = r0 + out[d + half_rot] = r1 + return out + + @staticmethod + def _nvfp4_pack(vals, round_bf16, second_level, rcp_six): + """quantizeMinimaxM3Fp4x4 over 8 groups of 16: (16 data words, 8 scale bytes).""" + if round_bf16: + v = [] + for i in range(HEAD_DIM // 2): + w = _bf16x2_rn(vals[2 * i], vals[2 * i + 1]) + v.append(_lo_f32(w)) + v.append(_hi_f32(w)) + else: + v = vals + rcp_sl = _rcp_approx_ftz(second_level) + data_words = [] + scale_bytes = [] + for g in range(HEAD_DIM // 16): + amax = cutlass.Float32(0.0) + for i in range(16): + amax = _absmax(amax, v[16 * g + i]) + enc = _e4m3_byte(_mul_rn(second_level, _mul_rn(amax, rcp_six))) + out_scale = _rcp_approx_ftz(_mul_rn(_e4m3_byte_to_f32(enc), rcp_sl)) + out_scale = cutlass.Float32( + cutlass.select_(amax != cutlass.Float32(0.0), out_scale, cutlass.Float32(0.0)) + ) + qv = [] + for i in range(8): + p0, p1 = cute.arch.mul_packed_f32x2( + (v[16 * g + 2 * i], v[16 * g + 2 * i + 1]), (out_scale, out_scale) + ) + qv.append(p0) + qv.append(p1) + data_words.append(_e2m1x8(qv[0:8])) + data_words.append(_e2m1x8(qv[8:16])) + scale_bytes.append(enc) + return data_words, scale_bytes + + @staticmethod + def _store_kv( + data_words, scale_bytes, is_k, kvd_addr, kvs_addr, head_kv, page, within, cache_strides + ): + ( + data_page_stride, + data_plane_stride, + data_head_stride, + data_token_stride, + scale_page_stride, + scale_plane_stride, + scale_head_stride, + _, + _, + ) = cache_strides + plane = cutlass.Int64(0 if is_k else 1) + data_dst = ( + kvd_addr + + page * data_page_stride + + plane * data_plane_stride + + head_kv * data_head_stride + + within * data_token_stride + ) + for i in range(4): + _stg_v4( + data_dst + cutlass.Int64(16 * i), + data_words[4 * i], + data_words[4 * i + 1], + data_words[4 * i + 2], + data_words[4 * i + 3], + ) + scale_base = ( + kvs_addr + + page * scale_page_stride + + plane * scale_plane_stride + + head_kv * scale_head_stride + ) + if is_k: + # K: the 8 group scales of a token are contiguous. + words = [] + for wi in range(2): + b = scale_bytes[4 * wi : 4 * wi + 4] + words.append( + b[0] + | (b[1] << cutlass.Int32(8)) + | (b[2] << cutlass.Int32(16)) + | (b[3] << cutlass.Int32(24)) + ) + _stg_v2(scale_base + within * cutlass.Int64(8), words[0], words[1]) + else: + # V: four tokens interleaved per 32-byte group block. + vbase = ( + scale_base + + (within // cutlass.Int64(4)) * cutlass.Int64(32) + + (within % cutlass.Int64(4)) + ) + for g in range(HEAD_DIM // 16): + _stg_u8(vbase + cutlass.Int64(4 * g), scale_bytes[g]) + + # ------------------------------------------------------------------ + @cute.jit + def _mainloop_s2t_copy_and_partition(self, sSF: cute.Tensor, tSF: cute.Tensor) -> S2TCopyBundle: + tCsSF_compact = cute.filter_zeros(sSF) + tCtSF_compact = cute.filter_zeros(tSF) + copy_atom_s2t = cute.make_copy_atom(tcgen05.Cp4x32x128bOp(self.cta_group), self.sf_dtype) + tiled_copy_s2t = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSF_compact) + thr_copy_s2t = tiled_copy_s2t.get_slice(0) + + def append_mn_broadcast_mode(smem_layout: cute.Layout): + mn_dim = cute.get(smem_layout, mode=[0, 0]) + mn_dim = cute.append(mn_dim, cute.make_layout((4), stride=(0))) + layout = cute.append(cute.group_modes(mn_dim, 0), cute.get(smem_layout, mode=[0, 1])) + layout = cute.append(cute.group_modes(layout, 0), cute.get(smem_layout, mode=[1])) + layout = cute.append(layout, cute.get(smem_layout, mode=[2])) + layout = cute.append(layout, cute.get(smem_layout, mode=[3])) + return layout + + tCsSF_compact_bcast = cute.make_tensor( + tCsSF_compact.iterator, append_mn_broadcast_mode(tCsSF_compact.layout) + ) + tCsSF_compact_s2t_ = thr_copy_s2t.partition_S(tCsSF_compact_bcast) + tCsSF_compact_s2t = tcgen05.get_s2t_smem_desc_tensor(tiled_copy_s2t, tCsSF_compact_s2t_) + tCtSF_compact_s2t = thr_copy_s2t.partition_D(tCtSF_compact) + return S2TCopyBundle(tiled_copy_s2t, tCsSF_compact_s2t, tCtSF_compact_s2t) + + @cute.jit + def _mainloop_s2t_copies(self, stage_idx, sfa_s2t_bundle, sfb_s2t_bundle): + s2t_stage_coord = (None, None, None, None, stage_idx) + cute.copy( + sfa_s2t_bundle.tiled_copy, + sfa_s2t_bundle.sSF_compact[s2t_stage_coord], + sfa_s2t_bundle.tSF_compact, + ) + cute.copy( + sfb_s2t_bundle.tiled_copy, + sfb_s2t_bundle.sSF_compact[s2t_stage_coord], + sfb_s2t_bundle.tSF_compact, + ) + + +# --------------------------------------------------------------------------- +# Host side +# --------------------------------------------------------------------------- + +_COMPILE_CACHE: dict = {} + + +def compile( + *, + num_heads_q: int = 32, + num_heads_kv: int = 2, + num_heads_index: int = 2, + heads_per_tile: int = 4, + mma_m: int = 256, + mma_n: int | None = None, + num_acc_stage: int | None = None, + cluster_shape_mn: Tuple[int, int] | None = None, + swizzle_size: int = 1, + raster_along_m: bool = True, + debug_gemm_out: bool = False, + enable_pdl: bool = True, + epi_wgs: int = 1, +): + """Compile one handle serving every M (and any cache geometry).""" + arch = os.environ.get("CUTE_DSL_ARCH") + if arch is not None and arch != "sm_107a": + raise RuntimeError("requires CUTE_DSL_ARCH=sm_107a") + key = ( + num_heads_q, + num_heads_kv, + num_heads_index, + heads_per_tile, + mma_m, + mma_n, + num_acc_stage, + None if cluster_shape_mn is None else tuple(cluster_shape_mn), + swizzle_size, + raster_along_m, + debug_gemm_out, + enable_pdl, + epi_wgs, + ) + if key in _COMPILE_CACHE: + return _COMPILE_CACHE[key] + op = M3QkvGemmNormRopeKvInsert( + num_heads_q=num_heads_q, + num_heads_kv=num_heads_kv, + num_heads_index=num_heads_index, + heads_per_tile=heads_per_tile, + mma_m=mma_m, + mma_n=mma_n, + num_acc_stage=num_acc_stage, + cluster_shape_mn=cluster_shape_mn, + swizzle_size=swizzle_size, + raster_along_m=raster_along_m, + debug_gemm_out=debug_gemm_out, + enable_pdl=enable_pdl, + epi_wgs=epi_wgs, + ) + + from cutlass.cute.runtime import make_fake_compact_tensor, make_fake_stream + + def sym(): + return cute.sym_int64() + + sym_m, sym_k = sym(), sym() + fake_act = make_fake_compact_tensor( + cutlass.Float8E4M3FN, (sym_m, sym_k), stride_order=(1, 0), assumed_align=16 + ) + fake_w = make_fake_compact_tensor( + cutlass.Float8E4M3FN, (op.n_total, sym_k), stride_order=(1, 0), assumed_align=16 + ) + fake_asf = make_fake_compact_tensor(cutlass.Float8E8M0FNU, (sym(),), assumed_align=16) + fake_wsf = make_fake_compact_tensor(cutlass.Float8E8M0FNU, (sym(),), assumed_align=16) + fake_alpha = make_fake_compact_tensor(cutlass.Float32, (1,), assumed_align=4) + fake_q = make_fake_compact_tensor(cutlass.Uint8, (sym(),), assumed_align=16) + fake_iq = make_fake_compact_tensor(cutlass.Uint8, (sym(),), assumed_align=16) + fake_kvd = make_fake_compact_tensor(cutlass.Uint8, (sym(),), assumed_align=16) + fake_kvs = make_fake_compact_tensor(cutlass.Uint8, (sym(),), assumed_align=8) + fake_ik = make_fake_compact_tensor(cutlass.Uint8, (sym(),), assumed_align=16) + fake_loc = make_fake_compact_tensor(cutlass.Int32, (sym(),), assumed_align=4) + fake_kvq = make_fake_compact_tensor(cutlass.Float32, (sym(),), assumed_align=4) + fake_cs = make_fake_compact_tensor(cutlass.Float32, (sym(),), assumed_align=16) + fake_pos = make_fake_compact_tensor(cutlass.Int32, (sym(),), assumed_align=4) + fake_nw = make_fake_compact_tensor(cutlass.BFloat16, (4 * HEAD_DIM,), assumed_align=16) + fake_g = make_fake_compact_tensor(cutlass.BFloat16, (sym(),), assumed_align=16) + compiled = cute.compile( + op, + fake_act, + fake_asf, + fake_w, + fake_wsf, + fake_alpha, + fake_q, + fake_iq, + fake_kvd, + fake_kvs, + fake_ik, + fake_loc, + fake_kvq, + fake_cs, + fake_pos, + fake_nw, + fake_g, + *(cutlass.Int64(0) for _ in range(9)), + cutlass.Int64(0), + cutlass.Float32(1e-6), + make_fake_stream(), + options="--enable-tvm-ffi", + ) + _COMPILE_CACHE[key] = (op, compiled) + return _COMPILE_CACHE[key] + + +def _cache_strides(kv_data_cache, kv_scale_cache, index_k_cache): + """(data page, plane, head, token; scale page, plane, head; index page, token) strides in bytes.""" + return ( + int(kv_data_cache.stride(0)), + int(kv_data_cache.stride(1)), + int(kv_data_cache.stride(2)), + int(kv_data_cache.stride(3)), + int(kv_scale_cache.stride(0)), + int(kv_scale_cache.stride(1)), + int(kv_scale_cache.stride(2)), + int(index_k_cache.stride(0)), + int(index_k_cache.stride(2)), + ) + + +class M3QkvFusedRunner: + """Torch-callable wrapper: builds the TVM-FFI dlpack arguments once per call. + + Tensors (all CUDA, contiguous unless noted): + act e4m3 [M, K], act_sf / weight_sf 1-D swizzled UE8M0 K32 scales + (``torch.ops.trtllm.mxfp8_quantize(x, True)``), weight e4m3 [N, K], + alpha fp32 [1], q_out e4m3 [M, Hq, 128], index_q_out e4m3 [M, Hi, 128], + kv_data_cache uint8 [P, 2, Hkv, 128, 64], kv_scale_cache uint8 + [P, 2, Hkv, 128, 8], index_k_cache e4m3 [P, 1, 128, 128] (strided + pools allowed as long as rows stay contiguous and 16-byte aligned), + out_cache_loc int32 [>= M], kv_quant_scale fp32 [3], rotary_cos_sin + fp32 [max_pos, 2, 32], position_ids int32 [M], norm weights bf16 [128] + each (or one pre-concatenated [4 * 128] q|K|index-q|index-K tensor). + ``debug_gemm_out=True`` handles write only the bf16 GEMM output to + ``gemm_out`` [M, N] and leave every producer output untouched. + """ + + def __init__(self, **cfg): + self.op, self.compiled = compile(**cfg) + self.debug = bool(cfg.get("debug_gemm_out", False)) + + def make_args( + self, + act, + act_sf, + weight, + weight_sf, + alpha, + q_out, + index_q_out, + kv_data_cache, + kv_scale_cache, + index_k_cache, + out_cache_loc, + kv_quant_scale, + rotary_cos_sin, + position_ids, + norm_weights, + eps, + gemm_out=None, + ): + import torch + from cutlass.cute.runtime import from_dlpack + + op = self.op + assert act.dim() == 2 and weight.shape == (op.n_total, act.shape[1]) + assert act.shape[1] % 128 == 0 + m = act.shape[0] + assert q_out.shape == (m, op.num_heads_q, HEAD_DIM) + assert index_q_out.shape == (m, op.num_heads_index, HEAD_DIM) + assert kv_data_cache.dim() == 5 and kv_data_cache.shape[1:] == ( + 2, + op.num_heads_kv, + PAGE_SIZE, + HEAD_DIM // 2, + ) + assert kv_scale_cache.dim() == 5 and kv_scale_cache.shape[1:] == ( + 2, + op.num_heads_kv, + PAGE_SIZE, + HEAD_DIM // 16, + ) + assert index_k_cache.dim() == 4 and index_k_cache.shape[1:] == (1, PAGE_SIZE, HEAD_DIM) + assert kv_data_cache.stride(4) == 1 and kv_data_cache.stride(3) == HEAD_DIM // 2 + assert kv_scale_cache.stride(4) == 1 and kv_scale_cache.stride(3) == HEAD_DIM // 16 + assert index_k_cache.stride(3) == 1 and index_k_cache.stride(2) == HEAD_DIM + strides = _cache_strides(kv_data_cache, kv_scale_cache, index_k_cache) + assert all(s % 16 == 0 for s in strides[0:4] + strides[7:9]), strides + assert all(s % 8 == 0 for s in strides[4:7]), strides + for t, al in ((kv_data_cache, 16), (kv_scale_cache, 8), (index_k_cache, 16)): + assert t.data_ptr() % al == 0 + if isinstance(norm_weights, (list, tuple)): + norm_weights = torch.cat([w.reshape(-1) for w in norm_weights]) + assert norm_weights.dtype == torch.bfloat16 and norm_weights.numel() == 4 * HEAD_DIM + if gemm_out is None: + assert not self.debug + gemm_out = torch.empty(8, dtype=torch.bfloat16, device=act.device) + else: + assert gemm_out.shape == (m, op.n_total) and gemm_out.dtype == torch.bfloat16 + + def dl(t, al=16): + return from_dlpack(t, assumed_align=al, enable_tvm_ffi=True) + + def flat_u8(t): + return t.view(torch.uint8) if t.dtype != torch.uint8 else t + + # Caches are passed as flat byte views spanning their storage extent. + def span_u8(t): + base = flat_u8(t) + extent = 1 + sum((s - 1) * st for s, st in zip(base.shape, base.stride())) + return torch.as_strided(base, (extent,), (1,)) + + return ( + dl(act), + dl(act_sf.view(torch.float8_e8m0fnu).reshape(-1)), + dl(weight), + dl(weight_sf.view(torch.float8_e8m0fnu).reshape(-1)), + dl(alpha, 4), + dl(flat_u8(q_out).reshape(-1)), + dl(flat_u8(index_q_out).reshape(-1)), + dl(span_u8(kv_data_cache)), + dl(span_u8(kv_scale_cache), 8), + dl(span_u8(index_k_cache)), + dl(out_cache_loc, 4), + dl(kv_quant_scale, 4), + dl(rotary_cos_sin.reshape(-1)), + dl(position_ids, 4), + dl(norm_weights.reshape(-1)), + dl(gemm_out.reshape(-1)), + *strides, + int(kv_data_cache.shape[0]), + float(eps), + ) + + def run_args(self, args, stream=None): + import torch + + if stream is None: + stream = torch.cuda.current_stream().cuda_stream + self.compiled(*args, cuda_driver.CUstream(stream)) + + def __call__(self, *tensors, **kw): + self.run_args(self.make_args(*tensors, **kw)) diff --git a/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py new file mode 100644 index 000000000000..b6c7445524d2 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py @@ -0,0 +1,229 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Plain MXFP8 x MXFP8 -> bf16 GEMM on the fused QKV kernel's persistent CLC mainloop. + +``out[m, n] = bf16_rn(alpha * sum_k act[m, k] * weight[n, k])`` with E4M3 +operands and UE8M0 K32 block scales in the swizzled layout of +``torch.ops.trtllm.mxfp8_quantize(x, True)`` (the layout ``MXFP8LinearMethod`` +stores for ``weight_scale``), FP32 accumulation. + +This is the ``debug_gemm_out=True`` handle of ``M3QkvGemmNormRopeKvInsert`` +with N mapped onto its head slots: ``n = (num_heads_q + 2 * 2 + 2 + 1) * 128``. +In that mode the kernel reads only the four TMA operands (act, act_sf, +weight, weight_sf), ``alpha[0]`` and ``kv_quant_scale[1:3]`` (two scalar loads +that feed only the producer branch), and stores only ``gemm_out``. Every +other producer tensor (Q / index-Q outputs, caches, cache locations, RoPE +table, positions, norm weights) is turned into an address and never +dereferenced, so one set of tiny per-device dummies serves every call and M. +""" + +from __future__ import annotations + +from typing import Dict, Tuple + +import torch + +from .kernel import HEAD_DIM, M3QkvFusedRunner + +NUM_HEADS_KV = 2 +NUM_HEADS_INDEX = 2 +# K, V, index-q head slots plus the single index-K slot of the head map. +NUM_FIXED_SLOTS = 2 * NUM_HEADS_KV + NUM_HEADS_INDEX + 1 +SF_VEC_SIZE = 32 +# Weight-side DLPack arguments kept per runner; the cache holds the tensors, so a key's pointer cannot be reused. +_MAX_CACHED_WEIGHTS = 1024 + + +def num_heads_q_for(n: int) -> int: + """The head-slot count that makes the fused kernel's packed N equal ``n``.""" + if n % HEAD_DIM: + raise ValueError(f"N={n} is not a multiple of {HEAD_DIM}") + num_heads_q = n // HEAD_DIM - NUM_FIXED_SLOTS + if num_heads_q < 1: + raise ValueError(f"N={n} is too small for the head-slot map") + return num_heads_q + + +def _pad_up(x: int, m: int) -> int: + return (x + m - 1) // m * m + + +def swizzled_sf_numel(rows: int, k: int) -> int: + """Bytes of a swizzled UE8M0 K32 scale tensor (rows padded to 128, K blocks to 4).""" + return _pad_up(rows, 128) * _pad_up(k // SF_VEC_SIZE, 4) + + +def _dl(t: torch.Tensor, align: int = 16): + from cutlass.cute.runtime import from_dlpack + + return from_dlpack(t, assumed_align=align, enable_tvm_ffi=True) + + +_DUMMY_ARGS: Dict[torch.device, Tuple] = {} + + +def _dummy_producer_args(device: torch.device) -> Tuple: + """DLPack arguments for the producer slots the GEMM-only handle never dereferences. + + Order: q_out, index_q_out, kv_data_cache, kv_scale_cache, index_k_cache, + out_cache_loc, kv_quant_scale, rotary_cos_sin, position_ids, norm_weights. + ``kv_quant_scale`` holds three finite fp32 values since the kernel loads + [1] and [2] ahead of the (compiled-out) producer branch. ``norm_weights`` + has the 4 x 128 extent the compiled signature fixes. + """ + args = _DUMMY_ARGS.get(device) + if args is None: + u8 = torch.zeros(16, dtype=torch.uint8, device=device) + i32 = torch.zeros(4, dtype=torch.int32, device=device) + f32 = torch.ones(4, dtype=torch.float32, device=device) + nw = torch.zeros(4 * HEAD_DIM, dtype=torch.bfloat16, device=device) + args = ( + _dl(u8), + _dl(u8), + _dl(u8), + _dl(u8, 8), + _dl(u8), + _dl(i32, 4), + _dl(f32, 4), + _dl(f32), + _dl(i32, 4), + _dl(nw), + (u8, i32, f32, nw), # keeps the storage alive + ) + _DUMMY_ARGS[device] = args + return args[:10] + + +# Cache strides (9), num_pages, eps: unused by the GEMM-only handle. +_TAIL_ARGS = (0,) * 9 + (0, 0.0) + + +class M3ClcMxfp8Gemm: + """One compiled GEMM-only handle for a fixed N (any M, any K that is a multiple of 128).""" + + def __init__(self, n: int, heads_per_tile: int = 4, **cfg): + self.n = int(n) + self.heads_per_tile = int(heads_per_tile) + self.runner = M3QkvFusedRunner( + num_heads_q=num_heads_q_for(self.n), + num_heads_kv=NUM_HEADS_KV, + num_heads_index=NUM_HEADS_INDEX, + heads_per_tile=self.heads_per_tile, + debug_gemm_out=True, + **cfg, + ) + assert self.runner.op.n_total == self.n + self._weight_args: Dict[Tuple, Tuple] = {} + + def check(self, act, act_sf, weight, weight_sf, alpha) -> str: + """Why these tensors do not fit the kernel's contract, or "" when they do.""" + if weight.dim() != 2 or weight.shape[0] != self.n: + return f"weight shape {tuple(weight.shape)} is not [{self.n}, K]" + k = weight.shape[1] + if act.dim() != 2 or act.shape[1] != k: + return f"activation shape {tuple(act.shape)} does not match K={k}" + if k % 128: + return f"K={k} is not a multiple of 128" + if act.dtype != torch.float8_e4m3fn or weight.dtype != torch.float8_e4m3fn: + return f"operand dtypes {act.dtype}/{weight.dtype} are not float8_e4m3fn" + if act_sf.dtype not in (torch.uint8, torch.float8_e8m0fnu) or weight_sf.dtype not in ( + torch.uint8, + torch.float8_e8m0fnu, + ): + return f"scale dtypes {act_sf.dtype}/{weight_sf.dtype} are not UE8M0 bytes" + if not ( + act.is_contiguous() + and weight.is_contiguous() + and act_sf.is_contiguous() + and weight_sf.is_contiguous() + ): + return "non-contiguous operand or scale" + need = swizzled_sf_numel(act.shape[0], k) + if act_sf.numel() < need: + return ( + f"activation scales hold {act_sf.numel()} bytes, the swizzled layout needs {need}" + ) + need = swizzled_sf_numel(self.n, k) + if weight_sf.numel() < need: + return f"weight scales hold {weight_sf.numel()} bytes, the swizzled layout needs {need}" + if alpha.dtype != torch.float32 or alpha.numel() != 1 or alpha.dim() != 1: + return "alpha is not a 1-element fp32 vector" + for name, t, al in ( + ("act", act, 16), + ("act_sf", act_sf, 16), + ("weight", weight, 16), + ("weight_sf", weight_sf, 16), + ("alpha", alpha, 4), + ): + if t.data_ptr() % al: + return f"{name} is not {al}-byte aligned" + devices = {t.device for t in (act, act_sf, weight, weight_sf, alpha)} + if len(devices) != 1 or next(iter(devices)).type != "cuda": + return "operands are not on one CUDA device" + return "" + + def _weight_dl(self, weight, weight_sf, alpha) -> Tuple: + key = ( + weight.data_ptr(), + tuple(weight.shape), + weight_sf.data_ptr(), + weight_sf.numel(), + alpha.data_ptr(), + ) + cached = self._weight_args.get(key) + if cached is None: + if len(self._weight_args) >= _MAX_CACHED_WEIGHTS: + self._weight_args.clear() + cached = ( + _dl(weight), + _dl(weight_sf.view(torch.float8_e8m0fnu).reshape(-1)), + _dl(alpha, 4), + (weight, weight_sf, alpha), + ) + self._weight_args[key] = cached + return cached[:3] + + def make_args(self, act, act_sf, weight, weight_sf, alpha, gemm_out) -> Tuple: + """TVM-FFI arguments for one call; callers validate with ``check`` first.""" + assert gemm_out.shape == (act.shape[0], self.n) and gemm_out.dtype == torch.bfloat16 + assert gemm_out.is_contiguous() and gemm_out.data_ptr() % 16 == 0 + w_dl, wsf_dl, alpha_dl = self._weight_dl(weight, weight_sf, alpha) + return ( + _dl(act), + _dl(act_sf.view(torch.float8_e8m0fnu).reshape(-1)), + w_dl, + wsf_dl, + alpha_dl, + *_dummy_producer_args(act.device), + _dl(gemm_out.view(-1)), + *_TAIL_ARGS, + ) + + def run_args(self, args, stream=None) -> None: + self.runner.run_args(args, stream) + + def __call__(self, act, act_sf, weight, weight_sf, alpha, out=None) -> torch.Tensor: + reason = self.check(act, act_sf, weight, weight_sf, alpha) + assert not reason, reason + if out is None: + out = torch.empty((act.shape[0], self.n), dtype=torch.bfloat16, device=act.device) + self.run_args(self.make_args(act, act_sf, weight, weight_sf, alpha, out)) + return out + + +_GEMMS: Dict[Tuple[int, int], M3ClcMxfp8Gemm] = {} + + +def get_gemm(n: int, heads_per_tile: int) -> M3ClcMxfp8Gemm: + """The cached handle for (N, heads per tile); compiles on first use.""" + key = (int(n), int(heads_per_tile)) + gemm = _GEMMS.get(key) + if gemm is None: + gemm = M3ClcMxfp8Gemm(n, heads_per_tile=heads_per_tile) + _GEMMS[key] = gemm + return gemm + + +def m3_clc_mxfp8_gemm(act, act_sf, weight, weight_sf, alpha, out=None, heads_per_tile: int = 4): + """``bf16_rn(alpha * act @ weight.T)`` for MXFP8 operands with swizzled UE8M0 K32 scales.""" + return get_gemm(weight.shape[0], heads_per_tile)(act, act_sf, weight, weight_sf, alpha, out) diff --git a/tensorrt_llm/_torch/models/modeling_minimaxm3.py b/tensorrt_llm/_torch/models/modeling_minimaxm3.py index 9b7466d7f71b..dc42198d128c 100644 --- a/tensorrt_llm/_torch/models/modeling_minimaxm3.py +++ b/tensorrt_llm/_torch/models/modeling_minimaxm3.py @@ -26,11 +26,13 @@ from typing import Mapping as TMapping import torch +import triton +import triton.language as tl from torch import nn from torch.nn.attention import SDPBackend, sdpa_kernel from transformers import PretrainedConfig -from tensorrt_llm._utils import get_sm_version +from tensorrt_llm._utils import get_sm_version, mpi_rank from tensorrt_llm.bindings import DataType from tensorrt_llm.functional import AllReduceStrategy, PositionEmbeddingType from tensorrt_llm.logger import logger @@ -59,6 +61,8 @@ from ..attention.backends.sparse.params import SparseBackendForwardArgs from ..attention.backends.trtllm import TrtllmAttention from ..distributed import AllReduce, AllReduceFusionOp, AllReduceParams, MiniMaxAllReduceRMS +from ..flashinfer_utils import get_env_enable_pdl +from ..modules import linear as linear_module from ..modules.decoder_layer import DecoderLayer from ..modules.embedding import Embedding from ..modules.gated_mlp import GatedMLP @@ -68,19 +72,29 @@ WeightMode, WeightsLoadingConfig, copy_weight, + ctx_eager_only, load_weight_shard, + prequantized_mxfp8_pending, + set_prequantized_mxfp8, ) -from ..modules.multi_stream_utils import maybe_execute_in_parallel +from ..modules.multi_stream_utils import do_multi_stream, maybe_execute_in_parallel from ..modules.rms_norm import RMSNorm +from ..modules.swiglu import swiglu_mxfp8 from ..moe.fused_moe import MiniMaxM3MoeRoutingMethod, SwigluBiasActivation, create_moe from ..peft.lora.ownership import DecoderLoraOwner from ..pyexecutor.breakable_cuda_graph import eager_on_graph, is_in_breakable_cuda_graph from ..speculative import SpecMetadata -from ..utils import AuxStreamType, EventType, get_model_extra_attrs, is_torch_compiling +from ..utils import ( + AuxStreamType, + EventType, + Fp4QuantizedTensor, + get_model_extra_attrs, + is_torch_compiling, +) from .checkpoints.base_weight_mapper import BaseWeightMapper from .checkpoints.hf.minimaxm3_weight_mapper import MINIMAX_M3_PARAMS_MAP, MiniMaxM3HfWeightMapper from .checkpoints.hf.weight_mapper import convert_compressed_tensors_nvfp4_weights -from .modeling_speculative import SpecDecOneEngineForCausalLM +from .modeling_speculative import Eagle3DecoderLayer, Eagle3ForCausalLM, SpecDecOneEngineForCausalLM from .modeling_utils import ( DecoderModel, ModelConfig, @@ -93,6 +107,20 @@ _DENSE_SDPA_BACKENDS = [SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH] +_FOLD_LOGGED = False +_FOLD_CALLS_LOGGED = False +_FOLD_CALLS_SEEN: set = set() + + +def _fold_shared_backend(experts: nn.Module) -> bool: + """Whether ``experts`` runs the SM107 CuteDSL deterministic FC2, the only finalize that takes the shared-output + residual (the GEN decode targets override MiniMaxM3MoE.forward and use the TRTLLM backend: never this path).""" + from ..moe.fused_moe.cutedsl.grouped_gemm import nvfp4 as _cute_moe + + backend = getattr(experts, "backend", experts) + return _cute_moe._RUBIN_DETERMINISTIC_FC2 and isinstance(backend, _cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl) + + def _moe_routed_output_is_global(experts: nn.Module) -> bool: """Return whether the MoE layer hands back an already-combined routed output. @@ -102,6 +130,54 @@ def _moe_routed_output_is_global(experts: nn.Module) -> bool: return getattr(experts, "returns_global_routed_output", False) +# CTX prefill: fuse the boundary RMSNorm with the next MXFP8 linear's activation quantization (bitwise the same as +# the stock two-kernel path). TRTLLM_CTX_NORM_MXFP8=0 is the kill switch. +_CTX_NORM_MXFP8 = os.environ.get("TRTLLM_CTX_NORM_MXFP8", "1") == "1" +_CTX_NORM_MXFP8_MIN_ROWS = 8192 +_CTX_NORM_MXFP8_LOGGED = False +# The same kernel at the pre-MoE norm also emits the routed experts' NVFP4 fc31 input (bitwise fp4_quantize(norm, +# fc31_input_scale, 16, ue8m0=False, swizzled=False), the backend's own quantize_input). TRTLLM_CTX_NORM_FP4=0 is the +# kill switch. +_CTX_NORM_FP4 = os.environ.get("TRTLLM_CTX_NORM_FP4", "1") == "1" +_CTX_NORM_FP4_LOGGED = False +# CTX prefill: the shared + routed add folded into the routed experts' finalize. The TRTLLM-gen NVFP4 runner returns +# its unfinalized output (do_finalize=False) and one pass sums each token's top-k rows in the kernel's own order and +# weights, then adds the shared output with the ATen add_'s rounding: bitwise the same as finalize + add_, one fewer +# full read-modify-write of the hidden states. TLLM_M3_MOE_FOLD_SHARED=0 is the kill switch. +_FOLD_SHARED_INTO_FINALIZE = os.environ.get("TLLM_M3_MOE_FOLD_SHARED", "1") == "1" +# (diagnostic) With the fold on two streams, the main stream waits for the shared expert before the routed compute. +_FOLD_WAIT_UPFRONT = os.environ.get("TLLM_M3_MOE_FOLD_WAIT_UPFRONT", "0") == "1" +_FOLD_SHARED_LOGGED = False + + +def fold_shared_into_finalize(unfinalized, shared_output: torch.Tensor, top_k: int) -> torch.Tensor: + """Finalize a TRTLLM-gen ``do_finalize=False`` triple ``(gemm2_output, expert_weights, + expanded_idx_to_permuted_idx)`` with the shared expert's output added: equal bit for bit to the runner's own + finalize followed by ``shared_output.add_(routed)``. Returns a new [num_tokens, hidden] tensor.""" + from ..moe.fused_moe.unpermute_residual import unpermute_residual + + gemm2_output, expert_weights, expanded_idx_to_permuted_idx = unfinalized + num_tokens, hidden = shared_output.shape + out = torch.empty((num_tokens, hidden), dtype=shared_output.dtype, device=shared_output.device) + return unpermute_residual( + gemm2_output, + out, + expanded_idx_to_permuted_idx.view(num_tokens, top_k), + expert_weights.view(num_tokens, top_k), + shared_output.contiguous(), + ) + + +def _ctx_norm_op_has_fp4() -> bool: + """Whether the installed fused norm op takes fp4_global_scale (resolved once).""" + has = getattr(_ctx_norm_op_has_fp4, "_cached", None) + if has is None: + op = getattr(torch.ops.trtllm, "minimax_m3_ctx_residual_rmsnorm_mxfp8", None) + has = op is not None and "fp4_global_scale" in str(op.default._schema) + _ctx_norm_op_has_fp4._cached = has + return has + + class MiniMaxM3QKVIndexerLinear(Linear): """Five-way MiniMax-M3 projection with vLLM-compatible TP sharding. @@ -487,6 +563,70 @@ def _minimax_m3_swiglu_oai(gate_up: torch.Tensor, *, alpha: float, limit: float) return gate * torch.sigmoid(alpha * gate) * (up + 1.0) +# CTX prefill: the SwiGLU-OAI activation of the dense / shared-expert MLPs also quantizes its output for the MXFP8 +# down_proj in the same pass (bitwise mxfp8_quantize of the stock BF16 activation); the BF16 activation is not written. +# TRTLLM_CTX_SWIGLU_MXFP8=0 is the kill switch. +_CTX_SWIGLU_MXFP8 = os.environ.get("TRTLLM_CTX_SWIGLU_MXFP8", "1") == "1" +_CTX_SWIGLU_MXFP8_LOGGED = False + + +class _SwigluOaiMLP(GatedMLP): + """GatedMLP whose prefill-sized activation hands the MXFP8 down_proj a pre-quantized input.""" + + def _swiglu_mxfp8_eligible(self, x: torch.Tensor, has_lora: bool) -> bool: + from ..modules.linear import MXFP8LinearMethod + + method = getattr(self.down_proj, "quant_method", None) + return ( + _CTX_SWIGLU_MXFP8 + and get_sm_version() == 107 + and not has_lora + and self.activation == torch.nn.functional.silu + and x.dim() == 2 + and x.shape[0] >= _CTX_NORM_MXFP8_MIN_ROWS + and x.dtype == torch.bfloat16 + and x.shape[-1] % 256 == 0 + and ctx_eager_only() + and isinstance(method, MXFP8LinearMethod) + and getattr(method, "use_cutlass", False) + ) + + def _apply_activation(self, x, *, has_lora: bool = False): + if not self._swiglu_mxfp8_eligible(x, has_lora): + return super()._apply_activation(x, has_lora=has_lora) + act_e4m3, act_sf = swiglu_mxfp8( + x, + swiglu_limit=self.swiglu_limit, + swiglu_alpha=self.swiglu_alpha, + swiglu_beta=self.swiglu_beta, + ) + # Stands in for the BF16 activation: down_proj takes the MXFP8 pair keyed on it and never reads it. + placeholder = torch.empty(act_e4m3.shape, dtype=x.dtype, device=x.device) + set_prequantized_mxfp8(placeholder, act_e4m3, act_sf, tag="ctx_swiglu") + self._swiglu_mxfp8_source = placeholder + self._swiglu_mxfp8_takes = linear_module._PREQUANTIZED_MXFP8_TAKES[0] + global _CTX_SWIGLU_MXFP8_LOGGED + if not _CTX_SWIGLU_MXFP8_LOGGED: + _CTX_SWIGLU_MXFP8_LOGGED = True + logger.info(f"MiniMax-M3 CTX SwiGLU+MXFP8 fused path taken (rows {x.shape[0]})") + return placeholder + + def forward(self, *args, **kwargs): + self._swiglu_mxfp8_source = None + output = super().forward(*args, **kwargs) + source, self._swiglu_mxfp8_source = self._swiglu_mxfp8_source, None + # The placeholder is never written: down_proj must have TAKEN the pair (a dropped entry would quantize it). + # The take count is snapshotted when the pair is set, after gate_up's own take of the norm slot. + if source is not None and ( + prequantized_mxfp8_pending(source) + or linear_module._PREQUANTIZED_MXFP8_TAKES[0] == self._swiglu_mxfp8_takes + ): + raise RuntimeError( + "MiniMax-M3 SwiGLU+MXFP8: down_proj did not consume the pre-quantized activation" + ) + return output + + def _build_swiglu_oai_dense_mlp( model_config: "ModelConfig[PretrainedConfig]", intermediate_size: int, @@ -527,7 +667,7 @@ def _build_swiglu_oai_dense_mlp( # the fused silu_and_mul kernel runs it in one launch with an optional fp8 # epilogue. Mirrors the routed-expert SwigluBias path; the math lives in # _minimax_m3_swiglu_oai. - return GatedMLP( + return _SwigluOaiMLP( hidden_size=config.hidden_size, intermediate_size=intermediate_size, bias=False, @@ -573,6 +713,321 @@ def split_router_weight_bf16( return torch.cat(pieces, dim=1).contiguous() +# SM107: from this many tokens the router input is cast to float32 by one vectorized Triton pass instead of the +# aten dtype-converting copy (its unrolled path runs at ~2 TB/s). The cast is exact, so the result is bitwise the same. +_SM107_ROUTER_FP32_CAST = True +_SM107_ROUTER_FP32_CAST_MIN_TOKENS = 2048 +_SM107_ROUTER_FP32_CAST_LOGGED = [] + + +@triton.jit +def _bf16_to_fp32_kernel(x_ptr, y_ptr, numel, BLOCK: tl.constexpr): + offs = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK) + mask = offs < numel + tl.store(y_ptr + offs, tl.load(x_ptr + offs, mask=mask).to(tl.float32), mask=mask) + + +@torch.library.custom_op("trtllm::minimax_m3_router_input_fp32", mutates_args=()) +def minimax_m3_router_input_fp32(hidden_states: torch.Tensor) -> torch.Tensor: + """``hidden_states.to(torch.float32)``; large contiguous BF16 inputs take the Triton cast.""" + if ( + hidden_states.dtype != torch.bfloat16 + or hidden_states.shape[0] < _SM107_ROUTER_FP32_CAST_MIN_TOKENS + or not hidden_states.is_contiguous() + ): + return hidden_states.to(torch.float32) + out = torch.empty(hidden_states.shape, dtype=torch.float32, device=hidden_states.device) + if not _SM107_ROUTER_FP32_CAST_LOGGED: + _SM107_ROUTER_FP32_CAST_LOGGED.append(True) + logger.info( + f"[M3 dispatch] rank {mpi_rank()}: router_fp32_cast taken at {hidden_states.shape[0]} rows" + ) + numel = hidden_states.numel() + block = 8192 + _bf16_to_fp32_kernel[(triton.cdiv(numel, block),)]( + hidden_states, out, numel, BLOCK=block, num_warps=8 + ) + return out + + +@minimax_m3_router_input_fp32.register_fake +def _minimax_m3_router_input_fp32_fake(hidden_states: torch.Tensor) -> torch.Tensor: + return hidden_states.new_empty(hidden_states.shape, dtype=torch.float32) + + +# CTX prefill (SM107, NVFP4 sparse layers): one CuTe DSL kernel runs the QKV-index MXFP8 GEMM and the horizontal +# producer (per-head RMSNorm, RoPE, FP8 Q / index-Q, NVFP4 K/V + scales, FP8 index-K paged inserts) in its epilogue, +# bitwise the stock producer applied to its own BF16 GEMM output. TRTLLM_CTX_QKV_FUSED=0 is the kill switch. +_CTX_QKV_FUSED = os.environ.get("TRTLLM_CTX_QKV_FUSED", "1") == "1" +_CTX_QKV_FUSED_MIN_ROWS = 1024 +# A layer whose QKV the fused producer above took runs its attention core and o_proj through _core_then_o_proj, so the +# NVFP4 combine can also hand the o_proj its MXFP8 input (msa_combine_mxfp8, slot tag "p5a"); same o_proj input values. +# Kill switch: TRTLLM_CTX_P5A_COMBINE_MXFP8=0 calls the o_proj on the BF16 core output. +_CTX_P5A_COMBINE_MXFP8 = os.environ.get("TRTLLM_CTX_P5A_COMBINE_MXFP8", "1") == "1" + + +def _ctx_qkv_fused_takes_rows(rows: int) -> bool: + """Whether a step of rows QKV rows is large enough for the fused QKV GEMM + producer (eager and breakable alike).""" + return rows > _CTX_QKV_FUSED_MIN_ROWS + + +# Breakable prefill CUDA graphs capture the stock qkv_proj, so a captured bucket M > _CTX_QKV_FUSED_MIN_ROWS +# would run the stock QKV GEMM where an eager step of the same real rows takes the fused producer above +# (rule-1b different). For those buckets the QKV projection and producer run instead in an eager break on the +# live rows, i.e. exactly the eager path, so the captured step is bitwise the eager one. Buckets +# <= _CTX_QKV_FUSED_MIN_ROWS keep the captured stock projection (an eager or piecewise-compiled step of +# <= 1024 rows does not take the fused producer either). TRTLLM_CTX_BCG_P5A=0 is the kill switch. +_CTX_BCG_P5A = os.environ.get("TRTLLM_CTX_BCG_P5A", "1") == "1" + + +_BCG_EAGER_QKV_LOGGED: set = set() +_CTX_QKV_FUSED_YIELD_LOGGED = False + + +def _autotuner_tuning() -> bool: + """Whether the AutoTuner warmup pass is running. The fused QKV producer stays out of it, so the stock MXFP8 QKV + GEMM profiles its shape there: the steps the producer does not take (captured buckets, < 1024 rows) otherwise run + that GEMM on the CUTLASS runner's untuned default tactic.""" + from ..autotuner import AutoTuner + + global _CTX_QKV_FUSED_YIELD_LOGGED + tuning = AutoTuner.get().is_tuning_mode + if tuning and not _CTX_QKV_FUSED_YIELD_LOGGED: + _CTX_QKV_FUSED_YIELD_LOGGED = True + logger.info("[CTX R3] fused QKV yields to AutoTuner tuning pass; plain QKV GEMM tuned") + return tuning + + +def _log_bcg_eager_qkv_once(captured_rows: int) -> None: + if captured_rows not in _BCG_EAGER_QKV_LOGGED: + _BCG_EAGER_QKV_LOGGED.add(captured_rows) + logger.info( + f"[M3 CTX] breakable bucket {captured_rows}: eager QKV + fused producer on live rows" + ) + + +def _bcg_bucket_takes_eager_qkv(captured_rows: int) -> bool: + """Whether a breakable-graph bucket of captured_rows runs the QKV in the eager break (decided at capture).""" + return ( + _CTX_BCG_P5A + and _CTX_QKV_FUSED + and get_sm_version() == 107 + and _ctx_qkv_fused_takes_rows(captured_rows) + ) + + +_CTX_QKV_FUSED_RUNNERS: Dict[Tuple[int, int, int], Any] = {} +_CTX_QKV_FUSED_LOGGED = False + + +def _ctx_qkv_fused_runner(num_heads_q: int, num_heads_kv: int, num_heads_index: int): + """The compiled fused QKV runner for one per-rank head geometry (compiled on first use, outside capture).""" + key = (num_heads_q, num_heads_kv, num_heads_index) + runner = _CTX_QKV_FUSED_RUNNERS.get(key) + if runner is None: + from ..kernels.rubin.m3_qkv_fusion.kernel import M3QkvFusedRunner + + runner = M3QkvFusedRunner( + num_heads_q=num_heads_q, num_heads_kv=num_heads_kv, num_heads_index=num_heads_index + ) + _CTX_QKV_FUSED_RUNNERS[key] = runner + return runner + + +# CTX prefill router: a fixed-tile TF32 tensor-core GEMM (router_gemm_tf32) reads the BF16 hidden states directly +# against the TF32-rounded weight. Its tile and K order depend on the row count only through its split-K cap (8192 +# rows), so a token's logits are the same in every chunk size on either side of the cap (cuBLAS picks an M-dependent +# algorithm at every M), and it replaces the fp32 cast + linear. Same +# TF32 class as the cuBLAS path it replaces (the container enables TF32). TRTLLM_CTX_ROUTER_TF32_FIXED=0 is the kill +# switch. +_CTX_ROUTER_TF32_FIXED = os.environ.get("TRTLLM_CTX_ROUTER_TF32_FIXED", "1") == "1" +_CTX_ROUTER_TF32_LOGGED = False +# Pure generation steps (no context rows) keep the stock router below: the fixed-tile kernel runs a 128-row tile with a +# serial K loop, so a decode batch pays its full ~70 us per layer, which the stock cuBLAS path does in ~13 us. Context +# steps keep the fixed tile at every size, so a prefill token's logits stay independent of its chunk. +# Kill switch: TRTLLM_M3_ROUTER_TF32_IN_GEN=1 keeps the fixed tile in generation steps too. +_ROUTER_TF32_IN_GEN = os.environ.get("TRTLLM_M3_ROUTER_TF32_IN_GEN", "0") == "1" +# SM107 generation steps of 9..16 rows (TP2 GEN batch 4 with 3 drafts) run the stock router as a cuBLAS TF32 +# split-K GEMM + splitKreduce (~9.8 us/call standalone); the TF32 tensor-core router (minimax_m3_router_tc, 16-CTA +# clusters only, one reduction order) takes 2.9-3.5 us/call (GEMM-AR 796203) and is closer to the fp32 product +# (max |dlogit| 1.7e-6 vs 6.7e-5 for cuBLAS TF32). Rule 1b: top-4 sets may change near ties (1 / 10,240 random rows). +# Devices that cannot co-schedule 16-CTA clusters keep the stock router. Rule-1b gates passed (GSM McNemar greedy +# p 0.839 / sampled p 0.424; natural AL at 9..16 rows dAL +0.002). Kill switch: TRTLLM_M3_ROUTER_TC_GEN=0. +_ROUTER_TC_GEN = os.environ.get("TRTLLM_M3_ROUTER_TC_GEN", "1") == "1" +_ROUTER_TC_GEN_MIN_ROWS = 9 +# The router_tc launch also emits the routed experts' NVFP4 input (packed e2m1 + linear block scales, bit-identical to +# fp4_quantize(x, fc31_input_scale, 16, False, False)), which MiniMaxM3MoE hands to the experts in place of their own +# quantize_input. Default OFF with the router above; enable with TRTLLM_M3_ROUTER_TC_FP4_MOE=1 (needs +# TRTLLM_M3_ROUTER_TC_GEN=1). Off: the experts quantize again; the router is unchanged. +_ROUTER_TC_FP4_MOE = os.environ.get("TRTLLM_M3_ROUTER_TC_FP4_MOE", "0") == "1" +_ROUTER_TC_FP4_MOE_LOGGED = False +_ROUTER_TC_GEN_MAX_ROWS = 16 +_ROUTER_TC_GEN_OK: Dict[ + int, bool +] = {} # hidden size -> 16-CTA clusters available (device-static; decided once) + + +def _router_tc_gen_ok(hidden_size: int) -> bool: + ok = _ROUTER_TC_GEN_OK.get(hidden_size) + if ok is None: + ok = _ROUTER_TC_GEN_OK[hidden_size] = bool( + torch.ops.trtllm.minimax_m3_router_tc_cluster16(hidden_size) + ) + if ok: + logger.info( + f"[M3 Gate] rank {mpi_rank()}: TF32 tensor-core router engaged for " + f"{_ROUTER_TC_GEN_MIN_ROWS}..{_ROUTER_TC_GEN_MAX_ROWS}-row generation steps (16-CTA clusters)" + ) + else: + logger.info( + f"[M3 Gate] rank {mpi_rank()}: TF32 tensor-core router not used: this device cannot co-schedule " + "16-CTA clusters (stock router)" + ) + return ok + + +# SM107: the one-model Eagle3 drafter reads its first pass at context steps only at each context request's last row, +# so its context attention runs that row alone (DrafterLastRowContextFmha); every row still gets RoPE and its K/V +# appended to the drafter KV cache. Kill: TRTLLM_CTX_DRAFTER_LAST_ROW=0 in the deployment env (read once at import) +# runs the stock context attention over all rows. +_SM107_DRAFTER_CTX_LAST_ROW = os.environ.get("TRTLLM_CTX_DRAFTER_LAST_ROW", "1") == "1" + +# SM107: at a context step the same drafter layer runs its o_proj (with its all-reduce) and its MLP only on the rows the +# Eagle3 loop reads (each context request's last row, every generation row); the other rows' outputs are zeros. Every +# row still gets its QKV, RoPE and K/V append. Kill: TRTLLM_CTX_DRAFTER_DEAD_ROWS=0 in the deployment env (read once at +# import) runs both over all rows. +_SM107_DRAFTER_CTX_DEAD_ROWS = os.environ.get("TRTLLM_CTX_DRAFTER_DEAD_ROWS", "1") == "1" +_SM107_DRAFTER_CTX_DEAD_ROWS_LOGGED = [] + + +def _drafter_live_rows(attn_metadata, rows: int) -> Optional[torch.Tensor]: + """The rows of a drafter pass the Eagle3 loop reads, or None on a step without context requests.""" + num_contexts = int(attn_metadata.num_contexts) + if num_contexts == 0: + return None + num_ctx_tokens = int(attn_metadata.num_ctx_tokens) + if rows - num_ctx_tokens + num_contexts >= rows: + return None + last_rows = ( + torch.cumsum(attn_metadata.seq_lens_cuda[:num_contexts], dim=0, dtype=torch.long) - 1 + ) + gen_rows = torch.arange(num_ctx_tokens, rows, dtype=torch.long, device=last_rows.device) + return torch.cat([last_rows, gen_rows]) + + +def _rows_only(module: torch.nn.Module, live: List[Optional[torch.Tensor]]) -> None: + """Run ``module`` (rows in, rows out) only on the rows in ``live[0]`` while set; other output rows are zeros.""" + module_forward = module.forward + + def forward(x, *args, **kwargs): + rows = live[0] + if rows is None: + return module_forward(x, *args, **kwargs) + y = module_forward(x.index_select(0, rows), *args, **kwargs) + out = y.new_zeros((x.shape[0], y.shape[1])) + return out.index_copy_(0, rows, y) + + module.forward = forward + + +def mark_drafter_dead_rows(draft_model: torch.nn.Module) -> int: + """Skip the dead context rows of a one-layer Eagle3 drafter's o_proj and MLP (``_SM107_DRAFTER_CTX_DEAD_ROWS``). + + A drafter with more layers is left alone: there every row's output feeds the next layer. Returns the number of + layers marked (0 or 1).""" + layers = [m for m in draft_model.modules() if isinstance(m, Eagle3DecoderLayer)] + if len(layers) != 1: + logger.info(f"drafter_ctx_dead_rows not enabled: the drafter has {len(layers)} layers") + return 0 + layer = layers[0] + live: List[Optional[torch.Tensor]] = [None] + _rows_only(layer.self_attn.o_proj, live) + _rows_only(layer.mlp, live) + layer_forward = layer.forward + + def forward(position_ids, embeds, hidden_states, attn_metadata, spec_metadata): + live[0] = _drafter_live_rows(attn_metadata, hidden_states.shape[0]) + if live[0] is not None and not _SM107_DRAFTER_CTX_DEAD_ROWS_LOGGED: + _SM107_DRAFTER_CTX_DEAD_ROWS_LOGGED.append(True) + logger.info( + f"[M3 dispatch] rank {mpi_rank()}: drafter_ctx_dead_rows taken at " + f"{live[0].shape[0]} of {hidden_states.shape[0]} rows" + ) + try: + return layer_forward(position_ids, embeds, hidden_states, attn_metadata, spec_metadata) + finally: + live[0] = None + + layer.forward = forward + logger.info("drafter_ctx_dead_rows enabled on the drafter's o_proj and MLP") + return 1 + + +# SM107: the token embedding (full vocabulary on every rank) is one Triton gather that writes a token's row, or zeros +# for an id outside the vocabulary, instead of the aten gather followed by the broadcast masked_fill of the whole +# output (~270 us per 16K-token chunk). The same bits. Kill: TRTLLM_CTX_EMBEDDING_GATHER=0 in the deployment env (read +# once at import) runs the stock Embedding forward. +_SM107_EMBEDDING_GATHER = os.environ.get("TRTLLM_CTX_EMBEDDING_GATHER", "1") == "1" +_SM107_EMBEDDING_GATHER_LOGGED = [] + + +@triton.jit +def _embedding_gather_kernel(ids_ptr, weight_ptr, out_ptr, vocab, hidden, BLOCK: tl.constexpr): + row = tl.program_id(0).to(tl.int64) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + mask = cols < hidden + token = tl.load(ids_ptr + row).to(tl.int64) + valid = (token >= 0) & (token < vocab) + values = tl.load(weight_ptr + token * hidden + cols, mask=mask & valid, other=0.0) + tl.store(out_ptr + row * hidden + cols, values, mask=mask) + + +@torch.library.custom_op("trtllm::minimax_m3_embedding_gather", mutates_args=()) +def minimax_m3_embedding_gather(input_ids: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + """``F.embedding(ids, weight)`` with the rows of ids outside ``[0, weight.shape[0])`` zeroed.""" + hidden = weight.shape[1] + # The kernel reads the ids as one dense row; a strided view (e.g. ids[::2]) is copied first. + ids = input_ids.reshape(-1).contiguous() + out = torch.empty((ids.shape[0], hidden), dtype=weight.dtype, device=weight.device) + if ids.shape[0] > 0: + if not _SM107_EMBEDDING_GATHER_LOGGED: + _SM107_EMBEDDING_GATHER_LOGGED.append(True) + logger.info( + f"[M3 dispatch] rank {mpi_rank()}: embedding_gather taken at {ids.shape[0]} rows" + ) + block = 1024 + _embedding_gather_kernel[(ids.shape[0], triton.cdiv(hidden, block))]( + ids, weight, out, weight.shape[0], hidden, BLOCK=block, num_warps=4 + ) + return out.view(*input_ids.shape, hidden) + + +@minimax_m3_embedding_gather.register_fake +def _minimax_m3_embedding_gather_fake( + input_ids: torch.Tensor, weight: torch.Tensor +) -> torch.Tensor: + return weight.new_empty((*input_ids.shape, weight.shape[1])) + + +class MiniMaxM3Embedding(Embedding): + """The token embedding; on SM107 without vocabulary parallelism, one fused gather (minimax_m3_embedding_gather).""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._sm107_gather = _SM107_EMBEDDING_GATHER and get_sm_version() == 107 + + def forward(self, input): + if ( + self._sm107_gather + and self.tp_size == 1 + and input.is_cuda + and self.weight.dim() == 2 + and self.weight.is_contiguous() + ): + return minimax_m3_embedding_gather(input, self.weight) + return super().forward(input) + + class MiniMaxM3Gate(nn.Module): """MiniMax-M3 router gate: float32 sigmoid scoring + per-expert bias correction. @@ -608,17 +1063,73 @@ def __init__( # tensor-core GEMM on BF16 inputs; built by ``load_weights``, else None. self.register_buffer("split_weight", None, persistent=False) - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - """FP32 router logits ``hidden_states @ weight.t()``. + self._sm107_fp32_cast = _SM107_ROUTER_FP32_CAST and get_sm_version() == 107 + self._weight_tf32: Optional[torch.Tensor] = None + # SM107 generation steps of 9..16 rows: the TF32 tensor-core router (16-CTA clusters, see _router_tc_gen_ok). + self._router_tc_gen = ( + _ROUTER_TC_GEN + and get_sm_version() == 107 + and num_experts == 128 + and hidden_size % 1024 == 0 + ) - BF16 inputs with a split weight run one BF16 tensor-core GEMM over the - replicated input and the BF16 terms of the weight, with FP32 accumulation - and output. Otherwise the router runs in fp32 to match SGLang: cublas_mm - always computes with CUBLAS_COMPUTE_32F, whereas F.linear follows torch's - fp32 matmul precision, which is TF32 under TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1 - (set in the NGC PyTorch based containers) and then flips near-tied top-k - choices. - """ + def cache_tf32_weight(self) -> None: + """Build the TF32-rounded weight copy for the fixed-tile router (after every weight load).""" + self._weight_tf32 = None + if _CTX_ROUTER_TF32_FIXED and self._sm107_fp32_cast: + from ..moe.fused_moe.router_gemm_tf32 import prepare_router_weight_tf32 + + self._weight_tf32 = prepare_router_weight_tf32(self.weight.float()) + if self._router_tc_gen: + # Decide the TF32 tensor-core router at load time (cluster query + its log), never inside a CUDA-graph + # capture of a 9..16-row bucket; a device without 16-CTA clusters keeps the stock router. + self._router_tc_gen = _router_tc_gen_ok(self.hidden_size) + + def router_tc_applies(self, hidden_states: torch.Tensor, generation_only: bool) -> bool: + """Whether forward() takes the TF32 tensor-core router (9..16-row generation steps on SM107).""" + return ( + generation_only + and not is_torch_compiling() + and self._router_tc_gen + and _ROUTER_TC_GEN_MIN_ROWS <= hidden_states.shape[0] <= _ROUTER_TC_GEN_MAX_ROWS + and hidden_states.dtype == torch.bfloat16 + and hidden_states.dim() == 2 + and hidden_states.stride(1) == 1 + and (hidden_states.stride(0) * 2) % 16 == 0 + and _router_tc_gen_ok(self.hidden_size) + ) + + def router_tc_with_fp4( + self, hidden_states: torch.Tensor, fp4_scale: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """forward()'s router_tc logits plus the NVFP4 activation of the same launch: (logits, packed e2m1 [M, K / 2], + linear block scales [M * K / 16]); only where router_tc_applies().""" + logits, q, sf = torch.ops.trtllm.minimax_m3_router_tc( + hidden_states, self.weight, fp4_scale, get_env_enable_pdl() + ) + return logits, q, sf + + def forward(self, hidden_states: torch.Tensor, generation_only: bool = False) -> torch.Tensor: + if ( + self._weight_tf32 is not None + and not (generation_only and not _ROUTER_TF32_IN_GEN) + and hidden_states.dtype == torch.bfloat16 + and hidden_states.dim() == 2 + and hidden_states.is_contiguous() + ): + global _CTX_ROUTER_TF32_LOGGED + if not _CTX_ROUTER_TF32_LOGGED and not is_torch_compiling(): + _CTX_ROUTER_TF32_LOGGED = True + logger.info("[M3 Gate] fixed-tile TF32 router engaged") + return torch.ops.trtllm.router_gemm_tf32(hidden_states, self._weight_tf32) + if self.router_tc_applies(hidden_states, generation_only): + return torch.ops.trtllm.minimax_m3_router_tc( + hidden_states, self.weight, None, get_env_enable_pdl() + )[0] + if self._weight_tf32 is not None and generation_only and not is_torch_compiling(): + logger.info_once( + "[M3 Gate] stock router (generation_only)", key="m3_router_stock_generation_only" + ) if self.split_weight is not None and hidden_states.dtype == torch.bfloat16: terms = self.split_weight.shape[1] // self.hidden_size return torch.ops.trtllm.cublas_mm( @@ -828,6 +1339,103 @@ def __init__( # ``maybe_execute_in_parallel`` runs fn0/fn1 sequentially. self.aux_stream = aux_stream_dict[AuxStreamType.MoeShared] self.event_dict = {key: torch.cuda.Event() for key in [EventType.Main, EventType.MoeShared]} + # One-shot (norm output, Fp4QuantizedTensor) from the fused pre-MoE norm; see fp4_input_scale. + self._prequantized_fp4 = None + + def fp4_input_scale(self, num_rows: int) -> Optional[torch.Tensor]: + """The routed experts' NVFP4 fc31 input scale when a pre-quantized input can stand in for quantize_input. + + Only for a single-chunk, non-DP, non-fused-comm forward of the TRT-LLM-op NVFP4 TRTLLM-gen leaf (no AWQ + pre-scale, no hidden padding) or CuteDSL backend: there quantize_input is exactly fp4_quantize(x, + fc31_input_scale, 16, False, False) and passes an unswizzled Fp4QuantizedTensor through unchanged. + """ + from ..moe.fused_moe import CuteDslFusedMoE + from ..moe.fused_moe.trtllm_gen.trtllm_nvfp4 import TrtllmTrtllmGenNvfp4Impl + + experts = self.experts + backend = getattr(experts, "backend", None) + if ( + backend is None + or self.routed_output_is_global + or getattr(experts, "use_dp", False) + or getattr(experts, "enable_dwdp", False) + or num_rows > getattr(experts, "moe_max_num_tokens", 0) + or getattr(backend, "lora_params", None) is not None + ): + return None + if type(backend) is TrtllmTrtllmGenNvfp4Impl: + w = getattr(backend, "w3_w1_weight", None) + if ( + getattr(experts, "use_flashinfer", False) + or getattr(backend, "fc31_act_scale", None) is not None + or w is None + or w.shape[-1] * 2 != self.hidden_dim + ): + return None + elif not (isinstance(backend, CuteDslFusedMoE) and getattr(backend, "has_nvfp4", False)): + return None + if getattr(backend, "scaling_vector_size", None) != 16: + return None + scale = getattr(backend, "fc31_input_scale", None) + if ( + not isinstance(scale, torch.Tensor) + or scale.dtype != torch.float32 + or scale.numel() != 1 + ): + return None + return scale + + def cutedsl_fold_ok(self) -> bool: + """Whether this forward offers the shared output to the CuteDSL deterministic finalize (see + _FOLD_SHARED_INTO_FINALIZE): eager, an aux stream, and no token dispatch (no attention DP, no MoE + communication), so the finalize rows are this rank's own tokens.""" + return ( + _FOLD_SHARED_INTO_FINALIZE + and _fold_shared_backend(self.experts) + and self.aux_stream is not None + and not self.routed_output_is_global + and not self.use_dp + and getattr(self.experts, "comm", None) is None + and not is_torch_compiling() + and ctx_eager_only() + ) + + def fold_shared_ok(self, hidden_states: torch.Tensor, lora_params: Optional[dict]) -> bool: + """Whether this forward can fold the shared add into the routed finalize (see _FOLD_SHARED_INTO_FINALIZE): + eager, a shared expert, the TRT-LLM-op NVFP4 TRTLLM-gen leaf with no hidden padding, a single chunk, no + communication strategy (so ``do_finalize=False`` hands back the runner's own triple), routing inside the kernel + (with precomputed top-k the runner finalizes with the caller's weights and leaves the triple's + ``expert_weights`` unwritten), no DP / DWDP / LoRA.""" + from ..moe.fused_moe.trtllm_gen.trtllm_nvfp4 import TrtllmTrtllmGenNvfp4Impl + + if ( + not _FOLD_SHARED_INTO_FINALIZE + or get_sm_version() != 107 + or self.shared_experts is None + or lora_params + or not ctx_eager_only() + ): + return False + experts = self.experts + backend = getattr(experts, "backend", None) + w = getattr(backend, "w3_w1_weight", None) + return ( + type(backend) is TrtllmTrtllmGenNvfp4Impl + and backend.supports_unfinalized_output() + and not backend._routes_outside_the_kernel() + and getattr(experts, "comm", None) is None + and getattr(experts, "unfinalized_combine_fn", None) is None + and not getattr(experts, "use_flashinfer", False) + and not getattr(experts, "apply_router_weight_on_input", False) + and not self.routed_output_is_global + and not getattr(experts, "use_dp", False) + and not getattr(experts, "enable_dwdp", False) + and hidden_states.dim() == 2 + and hidden_states.dtype == torch.bfloat16 + and hidden_states.shape[0] <= getattr(experts, "moe_max_num_tokens", 0) + and w is not None + and w.shape[-1] * 2 == self.hidden_dim + ) def forward( self, @@ -836,16 +1444,57 @@ def forward( final_all_reduce_params: Optional[AllReduceParams] = None, lora_params: Optional[dict] = None, ) -> torch.Tensor: + global _FOLD_SHARED_LOGGED all_rank_num_tokens = attn_metadata.all_rank_num_tokens + prequantized = None + if ctx_eager_only(): + prequantized, self._prequantized_fp4 = self._prequantized_fp4, None + experts_input, output_dtype = hidden_states, None + if prequantized is not None and prequantized[0] is hidden_states and not lora_params: + experts_input, output_dtype = prequantized[1], hidden_states.dtype + logger.info_once( + "MiniMax-M3 CTX NVFP4 MoE input consumed from the fused norm", + key="m3_ctx_norm_fp4_consumed", + ) + + fold = self.fold_shared_ok(hidden_states, lora_params) def _compute_routed_output(): - router_logits = self.gate(hidden_states) + global _ROUTER_TC_FP4_MOE_LOGGED + generation_only = getattr(attn_metadata, "num_contexts", 1) == 0 + routed_input, routed_dtype = experts_input, output_dtype + fp4_scale = None + if ( + _ROUTER_TC_FP4_MOE + and experts_input is hidden_states + and not lora_params + and self.gate.router_tc_applies(hidden_states, generation_only) + ): + fp4_scale = self.fp4_input_scale(hidden_states.shape[0]) + if fp4_scale is None: + router_logits = self.gate(hidden_states, generation_only=generation_only) + else: + # One router_tc launch gives the logits and the experts' NVFP4 input (what quantize_input computes). + router_logits, q, sf = self.gate.router_tc_with_fp4(hidden_states, fp4_scale) + routed_input = Fp4QuantizedTensor( + q, sf, is_sf_swizzled=False, unquantized_hidden_states=hidden_states + ) + routed_dtype = hidden_states.dtype + if not _ROUTER_TC_FP4_MOE_LOGGED: + _ROUTER_TC_FP4_MOE_LOGGED = True + logger.info( + f"[M3 MoE] rank {mpi_rank()}: NVFP4 MoE input from the TF32 tensor-core router " + f"({_ROUTER_TC_GEN_MIN_ROWS}..{_ROUTER_TC_GEN_MAX_ROWS}-row generation steps)" + ) + kwargs = {"do_finalize": False} if fold else {} return self.experts( - hidden_states, + routed_input, router_logits, all_rank_num_tokens=all_rank_num_tokens, use_dp_padding=False, + output_dtype=routed_dtype, lora_params=lora_params, + **kwargs, ) def _compute_shared_output(): @@ -854,6 +1503,63 @@ def _compute_shared_output(): if self.shared_experts is None: routed_output = _compute_routed_output() result = routed_output + elif self.cutedsl_fold_ok(): + # (bitwise) The shared expert runs on the aux stream and its output is offered to the routed MoE's + # deterministic finalize, which adds it while un-permuting (one pass instead of a separate bf16 add) and + # waits on it only right before the finalize. A backend that does not take it leaves ``consumed`` False + # and the add runs here as before. Kill: TLLM_M3_MOE_FOLD_SHARED=0. + from ..moe.fused_moe.cutedsl.grouped_gemm import nvfp4 as _cute_moe + + if do_multi_stream(): + main_ev = self.event_dict[EventType.Main] + # A fresh event per offer: no re-record aliasing between the record and the finalize wait. + shared_ev = torch.cuda.Event() + main_ev.record() + with torch.cuda.stream(self.aux_stream): + main_ev.wait() + shared_output = _compute_shared_output() + shared_ev.record() + # As in maybe_execute_in_parallel: graph capture owns the lifetime (and cudaMallocAsync rejects it). + if not torch.cuda.is_current_stream_capturing(): + shared_output.record_stream(torch.cuda.current_stream()) + else: + # Eager (no multi-stream, as maybe_execute_in_parallel): the shared expert runs on this stream before + # the routed compute, never concurrently with it; only the add is folded. + shared_output = _compute_shared_output() + shared_ev = None + holder = _cute_moe.offer_finalize_residual(shared_output, shared_ev) + if shared_ev is not None and _FOLD_WAIT_UPFRONT: + # (diagnostic) main waits for the shared expert BEFORE the routed compute: no overlap, same arithmetic + torch.cuda.current_stream().wait_event(shared_ev) + try: + routed_output = _compute_routed_output() + finally: + _cute_moe.clear_finalize_residual() + global _FOLD_CALLS_LOGGED + if not _FOLD_CALLS_LOGGED or holder.calls != 1: + # (diagnostic) det-finalize calls between this layer's offer and clear (expected 1); logged once, and + # again (once) the first time it is not 1 -- a value != 1 means the pairing guard skipped extra calls + key = "ok" if holder.calls == 1 else "multi" + if key not in _FOLD_CALLS_SEEN: + _FOLD_CALLS_SEEN.add(key) + _FOLD_CALLS_LOGGED = True + logger.info( + f"[M3 MoE fold] det-finalize calls this layer/forward = {holder.calls} " + f"(tokens {shared_output.shape[0]}, consumed {holder.consumed})" + ) + if holder.consumed: + global _FOLD_LOGGED + if not _FOLD_LOGGED: + _FOLD_LOGGED = True + logger.info( + "[M3 MoE] shared expert folded into the CuteDSL deterministic finalize " + "(TLLM_M3_MOE_FOLD_SHARED)" + ) + result = routed_output + else: + if shared_ev is not None: + torch.cuda.current_stream().wait_event(shared_ev) + result = shared_output.add_(routed_output) else: routed_output, shared_output = maybe_execute_in_parallel( _compute_routed_output, @@ -870,9 +1576,20 @@ def _compute_shared_output(): shared_output, all_reduce_params=final_all_reduce_params ) return shared_output.add_(routed_output) - # In-place add into ``shared_output`` to avoid allocating a temporary - # (matches DeepSeekV3 / GLM convention). - result = shared_output.add_(routed_output) + if fold: + # The runner's unfinalized triple: finalize + the shared add in one pass (bitwise finalize + add_). + result = fold_shared_into_finalize( + routed_output, shared_output, self.experts.routing_method.top_k + ) + if not _FOLD_SHARED_LOGGED: + _FOLD_SHARED_LOGGED = True + logger.info( + "[M3 MoE] shared expert folded into the TRTLLM-gen finalize (TLLM_M3_MOE_FOLD_SHARED)" + ) + else: + # In-place add into ``shared_output`` to avoid allocating a temporary + # (matches DeepSeekV3 / GLM convention). + result = shared_output.add_(routed_output) if self.allreduce is not None and not self.routed_output_is_global: result = self.allreduce(result, all_reduce_params=final_all_reduce_params) @@ -985,12 +1702,18 @@ def minimax_m3_fused_sparse_qkv_producer( ) -> Tuple[torch.Tensor, torch.Tensor]: """Capture projection, norm, RoPE and FP8/NVFP4 cache insertion together.""" attn_metadata, attn_layer = _extract_minimax_m3_attention_extra_attrs(layer_idx) + cache_tensors = (kv_cache, index_k_cache, kv_scale_cache, out_cache_loc) + result = attn_layer._fused_fp8_qkv_indexer_norm_rope_kv_insert( + None, position_ids, attn_metadata, cache_tensors=cache_tensors, hidden_states=hidden_states + ) + if result is not None: + return result packed = attn_layer.qkv_proj(hidden_states) result = attn_layer._fused_fp8_qkv_indexer_norm_rope_kv_insert( packed, position_ids, attn_metadata, - cache_tensors=(kv_cache, index_k_cache, kv_scale_cache, out_cache_loc), + cache_tensors=cache_tensors, ) if result is None: raise RuntimeError("MiniMax-M3 piecewise graph requires the fused sparse QKV producer.") @@ -1096,6 +1819,44 @@ def minimax_m3_attn_custom_op_inplace( maybe_bcg_minimax_m3_attn_custom_op_inplace = eager_on_graph(minimax_m3_attn_custom_op_inplace) +def _minimax_m3_eager_qkv_attn_inplace( + hidden_states: torch.Tensor, + position_ids: Optional[torch.Tensor], + layer_idx: str, + output: torch.Tensor, +) -> None: + """Eager-path QKV projection + producer + attention on the live rows of a breakable-graph step. + + Runs exactly what an eager step of the same live rows runs (the fused QKV GEMM + producer when it applies, else + qkv_proj + the horizontal producer), so the captured step is bitwise the eager one. Pad rows of output are left as + the buffer supplied them (nothing reads them; see _dispatch_attention_over_live_tokens). + """ + attn_metadata, attn_layer = _extract_minimax_m3_attention_extra_attrs(layer_idx) + num_tokens = int(attn_metadata.num_tokens) + live_hidden = hidden_states[:num_tokens] + live_positions = position_ids[..., :num_tokens] if position_ids is not None else None + horizontal = attn_layer._fused_fp8_qkv_indexer_norm_rope_kv_insert( + None, live_positions, attn_metadata, hidden_states=live_hidden + ) + if horizontal is None: + horizontal = attn_layer._fused_fp8_qkv_indexer_norm_rope_kv_insert( + attn_layer.qkv_proj(live_hidden), live_positions, attn_metadata + ) + if horizontal is None: + raise RuntimeError( + "MiniMax-M3 fused horizontal producer is required inside the breakable eager QKV boundary for layer " + f"{layer_idx}, but its runtime geometry or cache layout was unsupported." + ) + q, idx_q = horizontal + _dispatch_attention_over_live_tokens( + attn_layer, q, None, None, idx_q, None, attn_metadata, output + ) + _log_bcg_eager_qkv_once(int(hidden_states.shape[0])) + + +maybe_bcg_minimax_m3_eager_qkv_attn_inplace = eager_on_graph(_minimax_m3_eager_qkv_attn_inplace) + + class MiniMaxM3Attention(Attention): """M3 attention: dense (layers 0-2) or sparse (layers 3-59). @@ -1548,9 +2309,13 @@ def _fused_fp8_qkv_indexer_norm_rope_kv_insert( cache_tensors: Optional[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], torch.Tensor] ] = None, + hidden_states: Optional[torch.Tensor] = None, ) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: """Run the vLLM-style horizontal producer for every sparse batch. + With ``hidden_states`` (``packed`` None) only the fused SM107 QKV GEMM + producer kernel is tried; None + means the caller projects with ``qkv_proj`` and calls again with ``packed``. + The CUDA kernel is token-major and batch-type agnostic: per-token positions and cache slots cover pure prefill, mixed aggregate batches, and CUDA-graph decode. FP8 caches receive FP8 K/V directly. NVFP4 @@ -1566,8 +2331,10 @@ def _fused_fp8_qkv_indexer_norm_rope_kv_insert( return None rope = self.pos_embd_params.rope if self.pos_embd_params is not None else None rotary_dim = int(rope.dim) if rope is not None else 0 + source = packed if packed is not None else hidden_states if ( - packed.dtype != torch.bfloat16 + source is None + or source.dtype != torch.bfloat16 or position_ids is None or self.head_dim != 128 or self.sparse_index_dim != 128 @@ -1609,7 +2376,7 @@ def _fused_fp8_qkv_indexer_norm_rope_kv_insert( out_cache_loc = getattr(attn_metadata, "msa_out_cache_loc", None) else: buffers, index_k_cache, scale_buffers, out_cache_loc = cache_tensors - num_tokens = int(packed.shape[0]) + num_tokens = int(source.shape[0]) layer_uses_nvfp4 = scale_buffers is not None kv_quant_scale = getattr(self.qkv_proj, "inv_kv_scales", None) if layer_uses_nvfp4 else None if layer_uses_nvfp4: @@ -1691,6 +2458,19 @@ def _fused_fp8_qkv_indexer_norm_rope_kv_insert( rotary_cos_sin, position_ids.reshape(-1).contiguous().to(torch.int32), ) + if packed is None: + if not layer_uses_nvfp4: + return None + return self._ctx_fused_qkv_gemm_producer( + hidden_states, + buffers, + scale_buffers, + index_k_cache, + kv_quant_scale, + common_args, + norm_weights, + norm_eps, + ) if layer_uses_nvfp4: q, index_q = torch.ops.trtllm.minimax_m3_nvfp4_qkv_indexer_norm_rope_kv_insert( packed.contiguous(), @@ -1710,6 +2490,86 @@ def _fused_fp8_qkv_indexer_norm_rope_kv_insert( ) return q.flatten(1), index_q.flatten(1) + def _ctx_fused_qkv_gemm_producer( + self, + hidden_states: torch.Tensor, + buffers: torch.Tensor, + scale_buffers: torch.Tensor, + index_k_cache: torch.Tensor, + kv_quant_scale: torch.Tensor, + common_args: tuple, + norm_weights: Tuple[torch.Tensor, ...], + norm_eps: float, + ) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: + """The QKV-index MXFP8 GEMM with the NVFP4 producer in its epilogue (see _CTX_QKV_FUSED), or None.""" + from ..modules.linear import MXFP8LinearMethod, take_prequantized_mxfp8 + + proj = self.qkv_proj + method = getattr(proj, "quant_method", None) + num_tokens = int(hidden_states.shape[0]) + n_total = ( + self.num_heads + 2 * self.num_key_value_heads + self.sparse_num_index_heads + 1 + ) * 128 + if ( + not _CTX_QKV_FUSED + or not ctx_eager_only() + or get_sm_version() != 107 + or hidden_states.dim() != 2 + or not hidden_states.is_contiguous() + or not _ctx_qkv_fused_takes_rows(num_tokens) + or not isinstance(method, MXFP8LinearMethod) + or not getattr(method, "use_cutlass", False) + or getattr(proj, "bias", None) is not None + or tuple(proj.weight.shape) != (n_total, hidden_states.shape[1]) + or _autotuner_tuning() + ): + return None + runner = _ctx_qkv_fused_runner( + self.num_heads, self.num_key_value_heads, self.sparse_num_index_heads + ) + q = hidden_states.new_empty( + (num_tokens, self.num_heads, self.head_dim), dtype=torch.float8_e4m3fn + ) + index_q = hidden_states.new_empty( + (num_tokens, self.sparse_num_index_heads, self.head_dim), dtype=torch.float8_e4m3fn + ) + out_cache_loc, *_, rotary_cos_sin, position_ids = common_args + prequantized = take_prequantized_mxfp8(hidden_states) + act, act_sf = ( + prequantized + if prequantized is not None + else torch.ops.trtllm.mxfp8_quantize(hidden_states, True) + ) + try: + args = runner.make_args( + act.view(num_tokens, -1), + act_sf, + proj.weight, + proj.weight_scale, + proj._mxfp8_alpha, + q, + index_q, + buffers.view(torch.uint8), + scale_buffers, + index_k_cache, + out_cache_loc, + kv_quant_scale, + rotary_cos_sin, + position_ids, + torch.cat(norm_weights), + norm_eps, + ) + except AssertionError: + # A cache geometry outside the kernel's alignment contract: the caller runs the stock projection + + # producer (the MXFP8 activation it already took is re-quantized there, bitwise the same). + return None + runner.run_args(args) + global _CTX_QKV_FUSED_LOGGED + if not _CTX_QKV_FUSED_LOGGED: + _CTX_QKV_FUSED_LOGGED = True + logger.info(f"MiniMax-M3 CTX fused QKV GEMM + producer taken (rows {num_tokens})") + return q.flatten(1), index_q.flatten(1) + def _expect_fused_qk_norm_rope(self, position_ids: Optional[torch.Tensor]) -> bool: """Whether the fused kernel is expected to run instead of the fallback. @@ -2242,6 +3102,22 @@ def _sparse_forward( ) o = self._forward_attention_core(q, None, None, idx_q, None, attn_metadata) return self.o_proj(o, all_reduce_params=all_reduce_params) + if ( + self.register_to_config + and not is_torch_compiling() + and is_in_breakable_cuda_graph() + and _bcg_bucket_takes_eager_qkv(int(hidden_states.shape[0])) + ): + # Captured bucket > 1024 rows: the eager path's QKV (fused producer) on the live rows, + # in an eager break. + output = hidden_states.new_empty( + (hidden_states.shape[0], self.num_heads * self.head_dim), + dtype=self.attn_activation_dtype, + ) + maybe_bcg_minimax_m3_eager_qkv_attn_inplace( + hidden_states, position_ids, self.layer_idx_str, output + ) + return self.o_proj(output, all_reduce_params=all_reduce_params) if self.register_to_config and (is_torch_compiling() or is_in_breakable_cuda_graph()): # Keep the projection in the captured segment while hiding # its shape-specializing MXFP8 internals behind a symbolic @@ -2269,14 +3145,34 @@ def _sparse_forward( output, ) return self.o_proj(output, all_reduce_params=all_reduce_params) - packed = self.qkv_proj(hidden_states) horizontal = self._fused_fp8_qkv_indexer_norm_rope_kv_insert( - packed, position_ids, attn_metadata + None, position_ids, attn_metadata, hidden_states=hidden_states ) if horizontal is not None: q, idx_q = horizontal + if _CTX_P5A_COMBINE_MXFP8: + return self._core_then_o_proj( + lambda: self._forward_attention_core( + q, None, None, idx_q, None, attn_metadata + ), + all_reduce_params, + site="p5a", + padded=getattr(attn_metadata, "padded_num_tokens", None) is not None, + ) o = self._forward_attention_core(q, None, None, idx_q, None, attn_metadata) return self.o_proj(o, all_reduce_params=all_reduce_params) + packed = self.qkv_proj(hidden_states) + horizontal = self._fused_fp8_qkv_indexer_norm_rope_kv_insert( + packed, position_ids, attn_metadata + ) + if horizontal is not None: + q, idx_q = horizontal + return self._core_then_o_proj( + lambda: self._forward_attention_core(q, None, None, idx_q, None, attn_metadata), + all_reduce_params, + site="horizontal", + padded=getattr(attn_metadata, "padded_num_tokens", None) is not None, + ) main_size = self.q_size + 2 * self.kv_size packed_qkv, packed_idx_qk = packed.split( [main_size, self.index_q_size + self.index_k_size], dim=-1 @@ -2364,12 +3260,35 @@ def _index_norm_rope(): disable_on_compile=True, ) - o = self._forward_attention_core(q, k, v, idx_q, idx_k, attn_metadata) # all_reduce_params lets the decoder defer the o_proj output AllReduce so # it can be fused with post_attention_layernorm (RESIDUAL_RMS_NORM). # Passing None preserves the standalone o_proj reduction used by the # single-GPU, attention-DP, and fusion-disabled paths. - return self.o_proj(o, all_reduce_params=all_reduce_params) + return self._core_then_o_proj( + lambda: self._forward_attention_core(q, k, v, idx_q, idx_k, attn_metadata), + all_reduce_params, + site="general", + padded=getattr(attn_metadata, "padded_num_tokens", None) is not None, + ) + + def _core_then_o_proj(self, core, all_reduce_params, site, padded=False): + """The sparse attention core, then its o_proj. In eager prefill the core's NVFP4 combine may also write the + o_proj input as MXFP8 into the prequant slot (msa_combine_mxfp8, TRTLLM_CTX_COMBINE_MXFP8); the o_proj takes + it. Never armed while compiling (the slot is not taken there), nor on a padded step (an eager breakable-graph + warmup or fallback step): the combine covers only the live rows while the o_proj input carries the pad rows, + so the slot would not be taken and, with the bf16 store skipped, the o_proj input would be unwritten.""" + if not ctx_eager_only() or padded: + return self.o_proj(core(), all_reduce_params=all_reduce_params) + from ..attention.backends.fmha import msa_combine_mxfp8 + + skip_bf16_ok = msa_combine_mxfp8.SKIP_BF16 and msa_combine_mxfp8.o_proj_takes_slot( + self.o_proj + ) + with msa_combine_mxfp8.armed(site, skip_bf16_ok): + o = core() + out = self.o_proj(o, all_reduce_params=all_reduce_params) + msa_combine_mxfp8.after_o_proj(o) + return out def _triton_sparse_attention_core( self, @@ -2641,6 +3560,7 @@ def _apply_pre_feed_forward_norm( self, hidden_states: torch.Tensor, residual: torch.Tensor, + moe: Optional[MiniMaxM3MoE] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: """AllReduce(+residual+RMSNorm) between attention and the feed-forward. @@ -2649,6 +3569,11 @@ def _apply_pre_feed_forward_norm( add+RMSNorm and the attention already reduced its own output. """ if self.pre_feed_forward_fusion: + fused = self._reduce_norm_mxfp8( + hidden_states, residual, self.post_attention_layernorm, moe=moe + ) + if fused is not None: + return fused return self.allreduce( hidden_states, all_reduce_params=AllReduceParams( @@ -2661,6 +3586,73 @@ def _apply_pre_feed_forward_norm( ) return self.post_attention_layernorm(hidden_states, residual) + def _reduce_norm_mxfp8( + self, + hidden_states: torch.Tensor, + residual: torch.Tensor, + norm: RMSNorm, + moe: Optional[MiniMaxM3MoE] = None, + ) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: + """Prefill-sized boundary AllReduce + residual RMSNorm that also emits the MXFP8 copy of the norm output. + + The plain AllReduce is followed by one kernel that does the RESIDUAL_RMS_NORM epilogue's residual add + + RMSNorm (the same arithmetic as the stock SM107 rows kernel) and the next MXFP8 linear's activation + quantization; the MXFP8 pair waits in a one-entry slot for that linear. Only for rows at or above + _CTX_NORM_MXFP8_MIN_ROWS, where the stock AUTO strategy reduces with NCCL and normalizes with that same + rows kernel; returns None (stock path) otherwise. With moe (the pre-MoE norm), the same kernel also writes + the routed experts' NVFP4 input, handed to moe as a one-shot Fp4QuantizedTensor. + """ + if ( + not _CTX_NORM_MXFP8 + or get_sm_version() != 107 + or hidden_states.dim() != 2 + or hidden_states.shape[0] < _CTX_NORM_MXFP8_MIN_ROWS + # The kernel's geometry: whole 256-element MXFP8 groups per thread block of at most 1024 threads. + or hidden_states.shape[1] % 256 != 0 + or hidden_states.shape[1] // 8 > 1024 + or hidden_states.dtype != torch.bfloat16 + or not ctx_eager_only() + or not hasattr(torch.ops.trtllm, "minimax_m3_ctx_residual_rmsnorm_mxfp8") + ): + return None + reduced = self.allreduce( + hidden_states, + all_reduce_params=AllReduceParams(fusion_op=AllReduceFusionOp.NONE), + ) + fp4_scale = None + if moe is not None and _CTX_NORM_FP4 and _ctx_norm_op_has_fp4(): + fp4_scale = moe.fp4_input_scale(hidden_states.shape[0]) + if fp4_scale is None: + outs = torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8( + reduced, residual, norm.weight, norm.variance_epsilon, True + ) + else: + outs = torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8( + reduced, residual, norm.weight, norm.variance_epsilon, True, fp4_scale + ) + normed, act_e4m3, act_sf = outs[:3] + set_prequantized_mxfp8(normed, act_e4m3, act_sf, tag="ctx_norm") + if fp4_scale is not None: + moe._prequantized_fp4 = ( + normed, + Fp4QuantizedTensor( + outs[3], outs[4], is_sf_swizzled=False, unquantized_hidden_states=normed + ), + ) + global _CTX_NORM_FP4_LOGGED + if not _CTX_NORM_FP4_LOGGED: + _CTX_NORM_FP4_LOGGED = True + logger.info( + f"MiniMax-M3 CTX norm+NVFP4 MoE input fused path taken (rows {hidden_states.shape[0]})" + ) + global _CTX_NORM_MXFP8_LOGGED + if not _CTX_NORM_MXFP8_LOGGED: + _CTX_NORM_MXFP8_LOGGED = True + logger.info( + f"MiniMax-M3 CTX norm+MXFP8 fused path taken (rows {hidden_states.shape[0]})" + ) + return normed, reduced + def _apply_next_layer_layernorm( self, hidden_states: torch.Tensor, @@ -2679,6 +3671,11 @@ def _apply_next_layer_layernorm( if self.next_layer_layernorm is None: return hidden_states, residual if self.post_feed_forward_fusion: + fused = None + if getattr(self, "next_layer_norm_feeds_mxfp8", False): + fused = self._reduce_norm_mxfp8(hidden_states, residual, self.next_layer_layernorm) + if fused is not None: + return fused return self.allreduce( hidden_states, all_reduce_params=AllReduceParams( @@ -2710,7 +3707,9 @@ def forward_MoE( spec_metadata: Optional[SpecMetadata] = None, lora_params: Optional[dict] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: - hidden_states, residual = self._apply_pre_feed_forward_norm(hidden_states, residual) + hidden_states, residual = self._apply_pre_feed_forward_norm( + hidden_states, residual, moe=self.block_sparse_moe + ) hidden_states = self.block_sparse_moe( hidden_states, @@ -2768,7 +3767,7 @@ def __init__(self, model_config: "ModelConfig[PretrainedConfig]"): AuxStreamType.MoeChunkingOverlap: torch.cuda.Stream(), } - self.embed_tokens = Embedding( + self.embed_tokens = MiniMaxM3Embedding( config.vocab_size, config.hidden_size, dtype=config.torch_dtype, @@ -2967,6 +3966,22 @@ def __init__(self, model_config: "ModelConfig[PretrainedConfig]"): # representation while the target remains NVFP4. model_config.extra_attrs["draft_kv_cache_quant_algo_override"] = QuantAlgo.FP8 super().__init__(MiniMaxM3Model(model_config), model_config) + if ( + _SM107_DRAFTER_CTX_LAST_ROW + and get_sm_version() == 107 + and self.draft_model is not None + and isinstance(self.draft_model, Eagle3ForCausalLM) + ): + from ..attention.backends.fmha.drafter_last_row import mark_drafter_last_row_attention + + mark_drafter_last_row_attention(self.draft_model) + if ( + _SM107_DRAFTER_CTX_DEAD_ROWS + and get_sm_version() == 107 + and self.draft_model is not None + and isinstance(self.draft_model, Eagle3ForCausalLM) + ): + mark_drafter_dead_rows(self.draft_model) def load_weights( self, @@ -3011,6 +4026,13 @@ def load_weights( attention.attn, attention.qkv_proj.kv_scales, refresh=True ) + def cache_derived_state(self) -> None: + """Rebuild the routers' TF32 weight copies from the loaded fp32 weights.""" + super().cache_derived_state() + for module in self.modules(): + if isinstance(module, MiniMaxM3Gate): + module.cache_tf32_weight() + def setup_aliases(self) -> None: """Chain each decoder layer's next_layer_layernorm for POST fusion. @@ -3027,6 +4049,8 @@ def setup_aliases(self) -> None: layer.next_layer_layernorm = self.model.norm else: layer.next_layer_layernorm = layers[idx + 1].input_layernorm + # Only a next decoder layer's QKV consumes an MXFP8 copy of the boundary norm (not lm_head). + layer.next_layer_norm_feeds_mxfp8 = idx != num_layers - 1 def _strip_language_model_prefix( diff --git a/tensorrt_llm/_torch/modules/linear.py b/tensorrt_llm/_torch/modules/linear.py index 59536d3ee885..6fc6ec391b71 100644 --- a/tensorrt_llm/_torch/modules/linear.py +++ b/tensorrt_llm/_torch/modules/linear.py @@ -52,6 +52,7 @@ unswizzle_sf) from .low_m_gemm import (_should_apply_low_m_gemm, apply_low_m_gemm, low_m_gemm_dispatcher) +from .m3_ctx_clc_gemm import ctx_clc_gemm_enabled, try_ctx_clc_mxfp8_gemm class WeightMode(str, enum.Enum): @@ -3600,6 +3601,84 @@ def flashinfer_mxfp8_decode_graph_capture() -> Iterator[None]: _FLASHINFER_MXFP8_DECODE_GRAPH_CAPTURE_ACTIVE.reset(token) +# One pending MXFP8 activation produced by a fused norm + quantize kernel for the very next MXFP8 linear that +# consumes its BF16 output (MiniMax-M3 CTX prefill). The slot holds the BF16 tensor itself, so its memory can't be +# reused for another tensor while the entry is pending; a consumer takes the entry only on the same storage and +# shape, and any other input quantizes as usual. +_PREQUANTIZED_MXFP8: list = [None] +# Number of entries a consumer actually took (a producer can tell a take from a drop on mismatch). +_PREQUANTIZED_MXFP8_TAKES: list = [0] +# Per producer tag: [set, taken, dropped on mismatch, unconsumed (overwritten or cleared before any take)]. TRTLLM_MXFP8_SLOT_AUDIT=N logs +# them every N sets (diagnostic; counting itself is host-side integer adds only). +_PREQUANTIZED_MXFP8_STATS: dict = {} +_PREQUANTIZED_MXFP8_AUDIT = int(os.environ.get("TRTLLM_MXFP8_SLOT_AUDIT", "0")) +_PREQUANTIZED_MXFP8_SETS: list = [0] + + +def ctx_eager_only() -> bool: + """True only in eager execution: neither the compile-dispatch flag nor a Dynamo trace. The CTX slots and + the CLC GEMM dispatch compare data pointers, which Dynamo cannot trace.""" + return not (is_torch_compiling() or torch.compiler.is_compiling()) + + +def _prequantized_mxfp8_stats(tag: str) -> list: + stats = _PREQUANTIZED_MXFP8_STATS.get(tag) + if stats is None: + stats = _PREQUANTIZED_MXFP8_STATS[tag] = [0, 0, 0, 0] + return stats + + +def set_prequantized_mxfp8(source: torch.Tensor, + act_e4m3: torch.Tensor, + act_sf: torch.Tensor, + tag: str = "untagged") -> None: + pending = _PREQUANTIZED_MXFP8[0] + if pending is not None: + _prequantized_mxfp8_stats(pending[3])[3] += 1 + # The producing stream: a take on another stream (the MoE shared expert's aux stream) records its use of the pair. + _PREQUANTIZED_MXFP8[0] = (source, act_e4m3, act_sf, tag, + torch.cuda.current_stream(act_e4m3.device)) + _prequantized_mxfp8_stats(tag)[0] += 1 + _PREQUANTIZED_MXFP8_SETS[0] += 1 + if _PREQUANTIZED_MXFP8_AUDIT and _PREQUANTIZED_MXFP8_SETS[ + 0] % _PREQUANTIZED_MXFP8_AUDIT == 0: + logger.info("[MXFP8 slot audit] " + " ".join( + f"{t}: set={s[0]} taken={s[1]} dropped={s[2]} unconsumed={s[3]}" + for t, s in sorted(_PREQUANTIZED_MXFP8_STATS.items()))) + + +def prequantized_mxfp8_pending(source: torch.Tensor) -> bool: + """Whether the slot still holds the entry set for ``source`` (no MXFP8 linear consumed it).""" + entry = _PREQUANTIZED_MXFP8[0] + return entry is not None and entry[0] is source + + +def take_prequantized_mxfp8(input: torch.Tensor): + """The pre-quantized pair for ``input`` if it is the slot's source; the slot only serves the next MXFP8 linear, + so an entry for any other input is dropped. Never taken while compiling (eager prefill only).""" + if not ctx_eager_only(): + return None + entry = _PREQUANTIZED_MXFP8[0] + if entry is None: + return None + _PREQUANTIZED_MXFP8[0] = None + source, act_e4m3, act_sf, tag, producer = entry + if (input.data_ptr() != source.data_ptr() + or input.numel() != source.numel() + or input.shape[-1] != source.shape[-1]): + _prequantized_mxfp8_stats(tag)[2] += 1 + return None + _PREQUANTIZED_MXFP8_TAKES[0] += 1 + _prequantized_mxfp8_stats(tag)[1] += 1 + consumer = torch.cuda.current_stream(act_e4m3.device) + if consumer != producer and not torch.cuda.is_current_stream_capturing(): + # The pair was allocated on the producing stream: without this the allocator could hand its memory to a new + # tensor there while the consuming stream's GEMM still reads it. + act_e4m3.record_stream(consumer) + act_sf.record_stream(consumer) + return act_e4m3.view(input.shape), act_sf + + class MXFP8LinearMethod(LinearMethodBase): """MXFP8 weights (e4m3 + UE8M0 1x32) x dynamic MXFP8 activations (W8A8). @@ -3794,7 +3873,10 @@ def apply(self, module: Linear, input: torch.Tensor, else: # Dynamic MXFP8 activation quantization (swizzled SF layout), # then the CUTLASS block-scaled e4m3xe4m3 GEMM. - act_e4m3, act_sf = torch.ops.trtllm.mxfp8_quantize(input, True) + prequantized = take_prequantized_mxfp8(input) + act_e4m3, act_sf = (prequantized if prequantized is not None + else torch.ops.trtllm.mxfp8_quantize( + input, True)) use_flashinfer = self.backend == "flashinfer" or ( self.backend == "auto" and not is_torch_compiling() and (_FLASHINFER_MXFP8_AUTOTUNE_ACTIVE.get() or @@ -3811,17 +3893,26 @@ def apply(self, module: Linear, input: torch.Tensor, module.dtype, ) else: - gemm = (torch.ops.trtllm.mxfp8_mxfp8_gemm_autotuned - if self.needs_native_autotune else - torch.ops.trtllm.mxfp8_mxfp8_gemm) - output = gemm( - act_e4m3, - act_sf, - module.weight, - module.weight_scale, - module._mxfp8_alpha, - module.dtype, - ) + output = None + if ctx_eager_only() and ctx_clc_gemm_enabled(): + # SM107 CTX prefill shapes at >= 1024 rows (eager): see m3_ctx_clc_gemm. + output = try_ctx_clc_mxfp8_gemm(act_e4m3, act_sf, + module.weight, + module.weight_scale, + module._mxfp8_alpha, + module.dtype) + if output is None: + gemm = (torch.ops.trtllm.mxfp8_mxfp8_gemm_autotuned + if self.needs_native_autotune else + torch.ops.trtllm.mxfp8_mxfp8_gemm) + output = gemm( + act_e4m3, + act_sf, + module.weight, + module.weight_scale, + module._mxfp8_alpha, + module.dtype, + ) if bias is not None: output = output + bias else: diff --git a/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py b/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py new file mode 100644 index 000000000000..8c59c5fc7a4b --- /dev/null +++ b/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py @@ -0,0 +1,190 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""CTX prefill MXFP8 GEMM on the SM107 CuTe DSL persistent CLC mainloop (MiniMax-M3). + +For the (N, K) shapes in ``_CTX_CLC_GEMM_SHAPES`` at >= ``_CTX_CLC_GEMM_MIN_ROWS`` +rows on SM107, ``MXFP8LinearMethod.apply`` runs the GEMM on the m3_qkv_fusion +kernel's GEMM-only handle instead of the CUTLASS ``mxfp8_mxfp8_gemm``. It +consumes the same E4M3 activation / swizzled UE8M0 scales and the module's +weight / swizzled weight scales / alpha. The result is deterministic but not +bitwise the CUTLASS result (different K-reduction order inside the MMA +pipeline). ``TRTLLM_CTX_CLC_GEMM=0`` is the kill switch. + +Engagement is decided in eager execution only: under torch.compile M is +symbolic, and the compiled graph keeps the CUTLASS op unchanged. CTX chunks +above the piecewise CUDA-graph buckets run eagerly. +""" + +from __future__ import annotations + +import os +from typing import Dict, Optional, Tuple + +import torch + +from tensorrt_llm.logger import logger + +from ..._utils import get_sm_version +from ..cute_dsl_utils import IS_CUTLASS_DSL_RUBIN_AVAILABLE + +_CTX_CLC_GEMM = os.environ.get("TRTLLM_CTX_CLC_GEMM", "1") != "0" +_CTX_CLC_GEMM_MIN_ROWS = 1024 +# At and above this many rows the wider (4 heads = 512 columns) tile wins. +_CTX_CLC_GEMM_WIDE_ROWS = 12288 +# (N, K) -> (heads per tile below _CTX_CLC_GEMM_WIDE_ROWS rows, at or above it); all 2-CTA M256. +_CTX_CLC_GEMM_SHAPES: Dict[Tuple[int, int], Tuple[int, int]] = { + (6144, 4096): (2, 2), # o_proj + (3072, 6144): (2, 4), # shared expert gate_up + (12288, 6144): (2, 4), # dense MLP gate_up + (6144, 6144): (2, 4), # dense MLP down +} + +_platform_ok: Optional[bool] = None +_failed: Dict[Tuple[int, int], str] = {} +# Each (N, heads per tile) handle compiles on first use, and a narrow-tile variant is first needed only by a chunk of +# fewer than _CTX_CLC_GEMM_WIDE_ROWS rows, usually a long prompt's last chunk, inside a served request. The first take +# (the warmup) therefore builds every variant. Kill switch: TRTLLM_CTX_CLC_GEMM_PRECOMPILE=0 compiles each on first use. +_PRECOMPILE = os.environ.get("TRTLLM_CTX_CLC_GEMM_PRECOMPILE", "1") != "0" +_precompiled = [False] + + +def ctx_clc_gemm_enabled() -> bool: + """Kill switch and platform: SM107 with the Rubin CuTe DSL helpers importable.""" + global _platform_ok + if not _CTX_CLC_GEMM: + return False + if _platform_ok is None: + _platform_ok = bool(IS_CUTLASS_DSL_RUBIN_AVAILABLE) and get_sm_version() == 107 + return _platform_ok + + +def ctx_clc_heads_per_tile(m: int, n: int, k: int) -> Optional[int]: + """The tile width for an eligible (M, N, K), or None when the shape stays on CUTLASS.""" + hpts = _CTX_CLC_GEMM_SHAPES.get((n, k)) + if hpts is None or m < _CTX_CLC_GEMM_MIN_ROWS: + return None + return hpts[1] if m >= _CTX_CLC_GEMM_WIDE_ROWS else hpts[0] + + +def _get_gemm(n: int, heads_per_tile: int): + from ..kernels.rubin.m3_qkv_fusion.plain_gemm import get_gemm + + return get_gemm(n, heads_per_tile) + + +def _precompile_all() -> None: + """Build every (N, heads per tile) handle of _CTX_CLC_GEMM_SHAPES; a failure is recorded as on first use.""" + _precompiled[0] = True + for (n, k), hpts in _CTX_CLC_GEMM_SHAPES.items(): + for hpt in sorted(set(hpts)): + if (n, hpt) in _failed: + continue + try: + _get_gemm(n, hpt) + except Exception as exc: # noqa: BLE001 (a DSL compile failure must leave serving on CUTLASS) + _failed[(n, hpt)] = f"{type(exc).__name__}: {exc}" + _skip(n, k, hpt, f"compile failed ({_failed[(n, hpt)]})") + logger.info_once( + f"MiniMax-M3 CTX CLC MXFP8 GEMM: {len(_CTX_CLC_GEMM_SHAPES)} shapes precompiled for every tile width", + key="m3_ctx_clc_gemm_precompiled", + ) + + +def _skip(n: int, k: int, hpt: int, reason: str) -> None: + logger.warning_once( + f"MiniMax-M3 CTX CLC MXFP8 GEMM not taken (N={n}, K={k}, hpt={hpt}): {reason}; using CUTLASS", + key=f"m3_ctx_clc_gemm_skip_{n}_{k}_{hpt}", + ) + + +def _clc_gemm_impl( + act: torch.Tensor, + act_sf: torch.Tensor, + weight: torch.Tensor, + weight_sf: torch.Tensor, + alpha: torch.Tensor, + heads_per_tile: int, +) -> torch.Tensor: + gemm = _get_gemm(weight.shape[0], heads_per_tile) + out = torch.empty((act.shape[0], weight.shape[0]), dtype=torch.bfloat16, device=act.device) + gemm.run_args(gemm.make_args(act, act_sf, weight, weight_sf, alpha, out)) + return out + + +@torch.library.custom_op("trtllm::m3_ctx_clc_mxfp8_gemm", mutates_args=()) +def m3_ctx_clc_mxfp8_gemm( + act: torch.Tensor, + act_sf: torch.Tensor, + weight: torch.Tensor, + weight_sf: torch.Tensor, + alpha: torch.Tensor, + heads_per_tile: int, +) -> torch.Tensor: + """bf16 ``alpha * act @ weight.T`` for MXFP8 operands with swizzled UE8M0 K32 scales (SM107 CLC mainloop). + + The caller validates the operands (``try_ctx_clc_mxfp8_gemm``); an invalid layout raises AssertionError. + """ + gemm = _get_gemm(weight.shape[0], heads_per_tile) + reason = gemm.check(act, act_sf, weight, weight_sf, alpha) + assert not reason, reason + return _clc_gemm_impl(act, act_sf, weight, weight_sf, alpha, heads_per_tile) + + +@m3_ctx_clc_mxfp8_gemm.register_fake +def _( + act: torch.Tensor, + act_sf: torch.Tensor, + weight: torch.Tensor, + weight_sf: torch.Tensor, + alpha: torch.Tensor, + heads_per_tile: int, +) -> torch.Tensor: + return act.new_empty((act.shape[0], weight.shape[0]), dtype=torch.bfloat16) + + +def try_ctx_clc_mxfp8_gemm( + act: torch.Tensor, + act_sf: torch.Tensor, + weight: torch.Tensor, + weight_sf: torch.Tensor, + alpha: torch.Tensor, + out_dtype: torch.dtype, +) -> Optional[torch.Tensor]: + """The CLC GEMM output for an eligible eager CTX call, or None for the caller's CUTLASS path. + + Call only from eager code (M must be a concrete row count) after ``ctx_clc_gemm_enabled()``. + """ + m = act.shape[0] if act.dim() == 2 else -1 + n, k = weight.shape[0], weight.shape[-1] + hpt = ctx_clc_heads_per_tile(m, n, k) + if hpt is None: + return None + if _PRECOMPILE and not _precompiled[0]: + _precompile_all() + key = (n, hpt) + if key in _failed: + return None + if out_dtype != torch.bfloat16: + _skip(n, k, hpt, f"output dtype {out_dtype} is not bfloat16") + return None + try: + gemm = _get_gemm(n, hpt) + except Exception as exc: # noqa: BLE001 (a DSL compile failure must leave serving on CUTLASS) + _failed[key] = f"{type(exc).__name__}: {exc}" + _skip(n, k, hpt, f"compile failed ({_failed[key]})") + return None + reason = gemm.check(act, act_sf, weight, weight_sf, alpha) + if reason: + _skip(n, k, hpt, reason) + return None + try: + # Direct call: in eager the custom-op dispatch would only add host time per GEMM. + out = _clc_gemm_impl(act, act_sf, weight, weight_sf, alpha, hpt) + except AssertionError as exc: + _skip(n, k, hpt, f"assertion {exc}") + return None + logger.info_once( + f"MiniMax-M3 CTX CLC MXFP8 GEMM taken (N={n}, K={k}, hpt={hpt})", + key=f"m3_ctx_clc_gemm_taken_{n}_{k}_{hpt}", + ) + return out diff --git a/tensorrt_llm/_torch/modules/swiglu.py b/tensorrt_llm/_torch/modules/swiglu.py index d68012d9af84..33bdd9a7c7c2 100644 --- a/tensorrt_llm/_torch/modules/swiglu.py +++ b/tensorrt_llm/_torch/modules/swiglu.py @@ -96,6 +96,125 @@ def silu_and_mul_2in_kernel(o_ptr, o_scale_ptr, gate_ptr, up_ptr, n_elements, tl.store(o_ptr + offsets, result, mask=mask) +@triton.jit +def _rcp_approx_ftz(x): + return tl.inline_asm_elementwise("rcp.approx.ftz.f32 $0, $1;", + "=f,f", [x], + dtype=tl.float32, + is_pure=True, + pack=1) + + +@triton.jit +def _ue8m0_round_up(x): + # __nv_cvt_float_to_e8m0(x, __NV_SATFINITE, cudaRoundPosInf): the low byte of the packed pair. + return tl.inline_asm_elementwise("cvt.rp.satfinite.ue8m0x2.f32 $0, $1, $1;", + "=h,f", [x], + dtype=tl.int16, + is_pure=True, + pack=1) & 0xFF + + +@triton.jit +def _e4m3_rn_satfinite(x): + # The packed pair's low byte holds the second operand. + return tl.inline_asm_elementwise("cvt.rn.satfinite.e4m3x2.f32 $0, $1, $1;", + "=h,f", [x], + dtype=tl.int16, + is_pure=True, + pack=1) & 0xFF + + +# `rows` is only a mask bound, so it is not specialized: a chunk's row count would otherwise pick a second compiled +# variant (rows % 16 != 0) that the 16-aligned warmup chunks never build. +@triton.jit(do_not_specialize=["rows"]) +def silu_and_mul_mxfp8_kernel(q_ptr, sf_ptr, x_ptr, x_stride, rows, d, + num_sf_cols, swiglu_limit: tl.constexpr, + swiglu_alpha: tl.constexpr, + swiglu_beta: tl.constexpr, + BLOCK_SIZE: tl.constexpr, ROWS: tl.constexpr, + HAS_SWIGLU_LIMIT: tl.constexpr) -> None: + """silu_and_mul_kernel's math (BF16 result) followed by mxfp8_quantize(result, swizzled=True) of the same + ROWS x BLOCK_SIZE tile: K32 UE8M0 scales in the 128x4 swizzled layout, E4M3 values, both bitwise those of the + CUDA quantizer (cvt_warp_fp16_to_mxfp8). Rows from `rows` up to the 128-row padding write zero scales only.""" + NUM_GROUPS: tl.constexpr = BLOCK_SIZE // 32 + i = tl.program_id(axis=0).to(tl.int64) * ROWS + tl.arange(0, ROWS).to( + tl.int64)[:, None] + offsets = tl.program_id(axis=1) * BLOCK_SIZE + tl.arange( + 0, BLOCK_SIZE)[None, :] + mask = (offsets < d) & (i < rows) + a = tl.load(x_ptr + x_stride * i + offsets, mask=mask, + other=0.0).to(tl.float32) + b = tl.load(x_ptr + x_stride * i + offsets + d, mask=mask, + other=0.0).to(tl.float32) + if HAS_SWIGLU_LIMIT: + a = tl.minimum(a, swiglu_limit) + b = tl.clamp(b, -swiglu_limit, swiglu_limit) + result = a * tl.sigmoid(swiglu_alpha * a) * (b + swiglu_beta) + v = tl.reshape( + result.to(tl.bfloat16).to(tl.float32), (ROWS, NUM_GROUPS, 32)) + vec_max = tl.max(tl.abs(v), axis=2) + sf_bits = _ue8m0_round_up( + vec_max * _rcp_approx_ftz(tl.full( + (ROWS, NUM_GROUPS), 448.0, tl.float32))) + sf_value = tl.where(sf_bits == 0, 0x00400000, sf_bits.to(tl.int32) << 23) + sf_value = tl.where(sf_bits == 0xFF, 0x7FFFFFFF, sf_value) + out_scale = tl.where(vec_max != 0.0, + _rcp_approx_ftz(sf_value.to(tl.float32, bitcast=True)), + 0.0) + q = _e4m3_rn_satfinite(v * out_scale[:, :, None]).to(tl.uint8) + tl.store(q_ptr + d * i + offsets, + tl.reshape(q, (ROWS, BLOCK_SIZE)), + mask=mask) + # 128x4 swizzled scale offset of (row i, scale column k). + k = tl.program_id(axis=1) * NUM_GROUPS + tl.arange(0, NUM_GROUPS)[None, :] + sf_off = ((i // 128) * ((num_sf_cols + 3) // 4) * 512 + (k // 4) * 512 + + (i % 32) * 16 + ((i % 128) // 32) * 4 + (k % 4)) + sf_out = tl.where(i < rows, sf_bits, 0).to(tl.uint8) + tl.store(sf_ptr + sf_off, sf_out, mask=k < (d // 32)) + + +def swiglu_mxfp8(x: torch.Tensor, + swiglu_limit: Optional[float] = None, + swiglu_alpha: Optional[float] = None, + swiglu_beta: Optional[float] = None, + block_size: Optional[int] = None, + rows_per_program: int = 4, + num_warps: int = 2): + """swiglu(x) quantized for an MXFP8 consumer in one pass: returns (e4m3 [rows, d], 1-D UINT8 swizzled scales), + bitwise mxfp8_quantize(swiglu(x), True). d must be a multiple of 128 (whole 4-column scale tiles). The default + tile (512 columns x 4 rows, 2 warps) is the fastest of a 36-config sweep on SM107 at 16K x 1536 / 6144.""" + rows, n = x.shape + d = n // 2 + assert n % 2 == 0 and d % 128 == 0 and x.stride( + -1) == 1 and 128 % rows_per_program == 0 + num_sf_cols = d // 32 + padded_rows = (rows + 127) // 128 * 128 + q = torch.empty((rows, d), dtype=torch.float8_e4m3fn, device=x.device) + sf = torch.empty((padded_rows * num_sf_cols, ), + dtype=torch.uint8, + device=x.device) + block = block_size or next(b for b in (512, 256, 128) if d % b == 0) + silu_and_mul_mxfp8_kernel[( + padded_rows // rows_per_program, triton.cdiv(d, block))]( + q_ptr=q.view(torch.uint8), + sf_ptr=sf, + x_ptr=x, + x_stride=x.stride(0), + rows=rows, + d=d, + num_sf_cols=num_sf_cols, + swiglu_limit=swiglu_limit or 0.0, + swiglu_alpha=swiglu_alpha if swiglu_alpha is not None else 1.0, + swiglu_beta=swiglu_beta if swiglu_beta is not None else 0.0, + BLOCK_SIZE=block, + ROWS=rows_per_program, + HAS_SWIGLU_LIMIT=swiglu_limit is not None and swiglu_limit > 0.0, + num_warps=num_warps, + ) + return q, sf + + def swiglu(x, quant_scale: Optional[torch.Tensor] = None, quant_type=None, diff --git a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/eligibility.py b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/eligibility.py index fa33218935c2..8dd2bb195180 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/eligibility.py +++ b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/eligibility.py @@ -31,6 +31,7 @@ def check_grouped_gemm_leaf( p: MoEProblem, d: MoEDeployment, *leaf_gates: MoEEligibility | None, + allow_swiglu_oai: bool = False, ) -> MoEEligibility: """Run the family gates in order, then the leaf's own, and admit. @@ -42,7 +43,7 @@ def check_grouped_gemm_leaf( check_quant_matches_identity(cls, p), check_sm(cls, d), check_dtype(cls, p), - check_grouped_gemm_shared(cls, p, d), + check_grouped_gemm_shared(cls, p, d, allow_swiglu_oai=allow_swiglu_oai), *leaf_gates, ): if verdict is not None: @@ -50,7 +51,9 @@ def check_grouped_gemm_leaf( return MoEEligibility.ok() -def check_grouped_gemm_shared(cls: type, p: MoEProblem, d: MoEDeployment) -> MoEEligibility | None: +def check_grouped_gemm_shared( + cls: type, p: MoEProblem, d: MoEDeployment, *, allow_swiglu_oai: bool = False +) -> MoEEligibility | None: """Gates both grouped-GEMM leaves share, or ``None`` to admit.""" sm_version = d.env.sm @@ -60,7 +63,7 @@ def check_grouped_gemm_shared(cls: type, p: MoEProblem, d: MoEDeployment) -> MoE f"{cls.__name__} on SM107 requires Rubin support in CuTe DSL", ) - if p.swiglu_gptoss_style: + if p.swiglu_gptoss_style and not allow_swiglu_oai: return _reject( MoERejectReason.ACTIVATION_UNSUPPORTED, f"{cls.__name__} does not support swiglu_gptoss_style (bias/swiglu with custom alpha/beta/limit)", diff --git a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py index 1561dcb70d13..317346299252 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py +++ b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py @@ -19,6 +19,7 @@ import torch from tensorrt_llm._utils import get_sm_version +from tensorrt_llm.logger import logger from .....autotuner import AutoTuner from .....cute_dsl_utils import IS_CUTLASS_DSL_RUBIN_AVAILABLE @@ -65,6 +66,41 @@ _DISABLE_DIRECT_DEEP_EP_METADATA_ENV = "TRTLLM_DISABLE_CUTEDSL_DEEP_EP_DIRECT_METADATA" +# (rule 1b) Rubin CuteDSL NVFP4 MoE: FC2 as a plain grouped GEMM per permuted row + a fixed-order unpermute instead +# of the fused scatter-add finalize (bf16 atomics, run-to-run order dependent). Kill: TLLM_CUTEDSL_MOE_DETERMINISTIC=0. +_RUBIN_DETERMINISTIC_FC2 = os.environ.get("TLLM_CUTEDSL_MOE_DETERMINISTIC", + "1") == "1" +_DETERMINISTIC_FC2_LOGGED = False + + +class FinalizeResidual: + """A one-shot residual (e.g. a MoE's shared-expert output, [tokens, hidden] bf16) for the deterministic Rubin + finalize to add while it un-permutes: bitwise ``residual.add_(routed_output)``. ``event`` (recorded on the stream + that produced it) is waited on right before the finalize; ``consumed`` tells the caller to skip its own add.""" + + def __init__(self, residual: torch.Tensor, event=None): + self.residual = residual + self.event = event + self.consumed = False + self.calls = 0 # det-finalize calls seen since the offer: only the FIRST may consume (pairing guard) + + +_FINALIZE_RESIDUAL: list[FinalizeResidual] = [] + + +def offer_finalize_residual(residual: torch.Tensor, + event=None) -> FinalizeResidual: + """Offer ``residual`` to the next deterministic Rubin FC2 finalize on this thread (cleared by the caller).""" + _FINALIZE_RESIDUAL.clear() + holder = FinalizeResidual(residual, event) + _FINALIZE_RESIDUAL.append(holder) + return holder + + +def clear_finalize_residual() -> None: + _FINALIZE_RESIDUAL.clear() + + @register_moe_impl class TrtllmCutedslGroupedGemmNvfp4Impl(CuteDslFusedMoEBase): """``trtllm.cutedsl.grouped_gemm.nvfp4``: CuteDSL NVFP4 grouped GEMM. @@ -98,7 +134,7 @@ class TrtllmCutedslGroupedGemmNvfp4Impl(CuteDslFusedMoEBase): # and the epilogue has no "clamp absent" branch, so an absent clamp is # +inf, not None. activation_support = MoEActivationSupport( - kinds=frozenset({ActivationType.Swiglu, ActivationType.Relu2, ActivationType.SiTu}), + kinds=frozenset({ActivationType.Swiglu, ActivationType.Relu2, ActivationType.SiTu, ActivationType.SwigluBias}), alpha_beta=ActivationParamShape.UNIFORM_SCALAR, limit=ActivationParamShape.UNIFORM_SCALAR, limit_when_absent=float("inf"), @@ -109,7 +145,13 @@ def can_implement(cls, p: MoEProblem, d: MoEDeployment) -> MoEEligibility: # process_weights_after_loading() unswizzles the FC1 block scales, # which asserts 128-row tiles; without this gate an unaligned shard # dies mid weight load with a bare swizzle error. - return check_grouped_gemm_leaf(cls, p, d, nvfp4_fc1_row_alignment_rejection(p, d)) + return check_grouped_gemm_leaf( + cls, p, d, nvfp4_fc1_row_alignment_rejection(p, d), + allow_swiglu_oai=( + p.activation == ActivationType.SwigluBias.name and not p.bias + and d.env.sm == 107 and _RUBIN_DETERMINISTIC_FC2 + ), + ) def _init_format_state(self) -> None: # Opt-out for adapter-free DeepEP metadata; see @@ -465,7 +507,15 @@ def run_moe_nvfp4_impl( ) = sort_outputs has_aux_streams = self._has_moe_output_memset_aux_stream() - if self.use_fused_finalize and has_aux_streams: + # The deterministic Rubin FC2 overwrites every output row (moe_unpermute_inplace): no zeroed output needed. + deterministic_fc2 = use_rubin and _RUBIN_DETERMINISTIC_FC2 and not use_count_native_expert_metadata + if use_rubin and not _RUBIN_DETERMINISTIC_FC2: + logger.warning_once( + "CuteDSL NVFP4 MoE on SM107 with TLLM_CUTEDSL_MOE_DETERMINISTIC=0: the FC2 finalize uses bf16 " + "atomics (run-to-run order dependent). Debug only; select moe_config.backend TRTLLM instead.", + key="cutedsl_moe_nondeterministic_sm107", + ) + if self.use_fused_finalize and has_aux_streams and not deterministic_fc2: memset_stream = self._moe_output_memset_run_stream() self.event_dict[EventType.Main].record() moe_output.record_stream(memset_stream) @@ -541,13 +591,81 @@ def run_moe_nvfp4_impl( if self.activation_type == ActivationType.Swiglu: gather_act_kwargs["swiglu_limit_scalar"] = self.act_clamp + # SwiGLU-OAI (SwigluBias): gate scale and linear offset use the + # activation kernel's constant slots; the clamp uses the SwiGLU limit. + if self.activation_type == ActivationType.SwigluBias: + gather_act_kwargs["situ_beta"] = self.act_alpha + gather_act_kwargs["situ_linear_beta"] = self.act_beta + gather_act_kwargs["swiglu_limit_scalar"] = self.act_clamp + # Join the async input quantization (quantize_input_async): x/x_sf were # produced on the aux stream and are first read here, after moe_sort # ran on the main stream in parallel with the quantization. self._join_pending_x_ready() x, x_sf = gather_act_op(**gather_act_kwargs) - if self.use_fused_finalize: + if deterministic_fc2: + global _DETERMINISTIC_FC2_LOGGED + if not _DETERMINISTIC_FC2_LOGGED: + _DETERMINISTIC_FC2_LOGGED = True + logger.info( + "[CuteDSL MoE] deterministic FC2 engaged (grouped store + fixed-order finalize; " + f"activation={self.activation_type.name}; TLLM_CUTEDSL_MOE_DETERMINISTIC)" + ) + # (rule 1b) Deterministic FC2 on Rubin: the grouped GEMM stores bf16(alpha * acc) per permuted row + # (no scatter-add atomics), then moe_unpermute_inplace sums each token's top-k rows in fixed index + # order with the token scales. Same run-to-run output; kill: TLLM_CUTEDSL_MOE_DETERMINISTIC=0. + fc2_rows = torch.empty(x.shape[0], + weight_view.w2_weight.shape[1], + dtype=output_dtype, + device=x.device) + torch.ops.trtllm.cute_dsl_nvfp4_grouped_gemm_store_rubin( + input=x.view(torch.float4_e2m1fn_x2), + weight=weight_view.w2_weight.view(torch.float4_e2m1fn_x2), + input_scale=x_sf.view(torch.uint8), + weight_scale=weight_view.fc2_weight_scale.view(torch.uint8), + alpha=weight_view.fc2_global_scale, + output=fc2_rows, + tile_idx_to_group_idx=tile_idx_to_expert_idx, + tile_idx_to_mn_limit=tile_idx_to_mn_limit, + permuted_idx_to_expanded_idx=permuted_idx_to_expanded_idx, + num_non_exiting_tiles=num_non_exiting_tiles, + token_final_scales=token_final_scales, + num_experts=self.num_slots, + top_k=effective_top_k, + num_local_experts=esp, + local_expert_offset=slot_start, + tile_size=tile_size, + output_dtype=output_dtype, + ) + holder = _FINALIZE_RESIDUAL[0] if _FINALIZE_RESIDUAL else None + if holder is not None: + holder.calls += 1 + if (holder is not None and not holder.consumed and holder.calls == 1 + and holder.residual.shape == moe_output.shape + and holder.residual.dtype == moe_output.dtype + and moe_output.dtype == torch.bfloat16): + # The shared + routed add folded into the finalize (bitwise; kill TLLM_M3_MOE_FOLD_SHARED=0). + from ...unpermute_residual import unpermute_residual + if holder.event is not None: + torch.cuda.current_stream().wait_event(holder.event) + if not (torch.compiler.is_compiling() + or torch.cuda.is_current_stream_capturing()): + holder.residual.record_stream(torch.cuda.current_stream()) + unpermute_residual( + fc2_rows, moe_output, + expanded_idx_to_permuted_idx.view(moe_output.shape[0], -1), + token_final_scales, holder.residual.contiguous()) + holder.consumed = True + _FINALIZE_RESIDUAL.clear() + else: + torch.ops.trtllm.moe_unpermute_inplace( + permuted_input=fc2_rows, + output=moe_output, + expanded_idx_to_permuted_idx=expanded_idx_to_permuted_idx, + topk_scales=token_final_scales, + ) + elif self.use_fused_finalize: if has_aux_streams: self.event_dict[EventType.MoeOutputMemset].wait() elif use_count_native_expert_metadata: diff --git a/tensorrt_llm/_torch/moe/fused_moe/router_gemm_tf32.py b/tensorrt_llm/_torch/moe/fused_moe/router_gemm_tf32.py new file mode 100644 index 000000000000..3b36a2bfc8e8 --- /dev/null +++ b/tensorrt_llm/_torch/moe/fused_moe/router_gemm_tf32.py @@ -0,0 +1,169 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Batch-invariant TF32 router GEMM for prefill: logits[M, N] = x[M, K] (bfloat16) @ w[N, K]^T in float32. + +The stock router (fp32 ``F.linear`` with TF32 allowed by the NGC environment) lets cuBLAS pick a kernel, tile and +split-K factor by M, so a token's logits, and through near-ties its experts, depend on the chunk size. This kernel +runs ONE fixed tile and K order for every M, so each output row is a function of its own input row: bitwise +identical for any M on the same side of the split-K cap below (SPLITK_MAX_M), and run to run. Same precision +class as stock: the router weight is rounded to TF32 +once at load with round-to-nearest (``prepare_router_weight_tf32``, bit-identical to ``cvt.rna.tf32.f32``, the +same rounding as stock's TF32 path), the bfloat16 input is exact in TF32, and products accumulate in float32. +Reads the bfloat16 hidden states directly (no float32 copy). + +K is split into SPLIT_K fixed slices: one CTA per (row block, slice) accumulates its slice in the single-pass +kernel's 32-wide chunk order into a float32 partial, and a second kernel sums the partials in slice order. The tile +and the split are fixed for every M, so each row still depends only on its own input row; the K-parallel grid keeps +the GEMM off a 192-step serial chain per CTA (63 -> 17.5 us/call at 2048 rows on SM107). Up to SPLITK_MAX_M rows +only: above it the float32 partials' round trip (SPLIT_K x M x N) eats the gain (no in-model gain on 16K-row chunks), +so larger steps keep the single-pass kernel, bitwise as before; rows are M-invariant within each side of the cap +(the breakable prefill graphs' padded buckets, <= 4096 rows, are all below it). Across the cap the K reduction order +changes, so a token's logits (and, at near-ties, its experts) can differ between a chunk of <= SPLITK_MAX_M rows and +a larger one. Kill: +TRTLLM_CTX_ROUTER_TF32_SPLITK=0 runs the single-pass kernel at every M.""" + +import os + +import torch +import triton +import triton.language as tl + +from tensorrt_llm.logger import logger + +# (BLOCK_M, BLOCK_K, num_warps, num_stages): one config for every M (no autotune by M; changing it changes bits). +CFG = (128, 32, 4, 4) +# K slices of the split kernel and the row block of its fixed-order reduction (part of the bits, as CFG is). +SPLIT_K = 8 +REDUCE_BLOCK_M = 32 +SPLITK = os.environ.get("TRTLLM_CTX_ROUTER_TF32_SPLITK", "1") == "1" +# Largest M the split kernel takes (larger steps run the single-pass kernel). +SPLITK_MAX_M = 8192 + + +def prepare_router_weight_tf32(w: torch.Tensor) -> torch.Tensor: + """float32 router weight [N, K] -> TF32-rounded (round to nearest, ties away; Inf / NaN kept), float32 storage.""" + bits = w.detach().float().contiguous().view(torch.int32) + rounded = (bits + 0x1000) & ~0x1FFF + finite = (bits & 0x7F800000) != 0x7F800000 + return torch.where(finite, rounded, bits).view(torch.float32).contiguous() + + +@triton.jit( + do_not_specialize=["M"] +) # one binary for every M (no M == 1 / M % 16 variants, no JIT at capture) +def _router_gemm_tf32_kernel( + x_ptr, w_ptr, out_ptr, M, K: tl.constexpr, N: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_K: tl.constexpr, +): # fmt: skip + rm = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + rn = tl.arange(0, N) + rk = tl.arange(0, BLOCK_K) + mask = rm < M + acc = tl.zeros((BLOCK_M, N), dtype=tl.float32) + for k0 in range(0, K, BLOCK_K): # one K order for every M + a = tl.load( + x_ptr + rm[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=mask[:, None], other=0.0 + ) + b = tl.load(w_ptr + rn[None, :] * K + (k0 + rk)[:, None]) + acc = tl.dot(a.to(tl.float32), b, acc, input_precision="tf32", out_dtype=tl.float32) + tl.store(out_ptr + rm[:, None].to(tl.int64) * N + rn[None, :], acc, mask=mask[:, None]) + + +@triton.jit(do_not_specialize=["M"]) +def _router_gemm_tf32_partial_kernel( + x_ptr, p_ptr, w_ptr, M, K: tl.constexpr, N: tl.constexpr, KS: tl.constexpr, BLOCK_M: tl.constexpr, + BLOCK_K: tl.constexpr, +): # fmt: skip + rm = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + s = tl.program_id(1) + rn = tl.arange(0, N) + rk = tl.arange(0, BLOCK_K) + mask = rm < M + acc = tl.zeros((BLOCK_M, N), dtype=tl.float32) + for k0 in range(s * KS, (s + 1) * KS, BLOCK_K): # the single-pass chunk order, within slice s + a = tl.load( + x_ptr + rm[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=mask[:, None], other=0.0 + ) + b = tl.load(w_ptr + rn[None, :] * K + (k0 + rk)[:, None]) + acc = tl.dot(a.to(tl.float32), b, acc, input_precision="tf32", out_dtype=tl.float32) + tl.store(p_ptr + (s * M + rm[:, None]).to(tl.int64) * N + rn[None, :], acc, mask=mask[:, None]) + + +@triton.jit(do_not_specialize=["M"]) +def _router_gemm_tf32_reduce_kernel( + p_ptr, out_ptr, M, N: tl.constexpr, S: tl.constexpr, BLOCK_M: tl.constexpr +): + rm = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + rn = tl.arange(0, N) + mask = rm < M + acc = tl.zeros((BLOCK_M, N), dtype=tl.float32) + for s in tl.static_range(S): # slice order: fixed for every M + acc += tl.load( + p_ptr + (s * M + rm[:, None]).to(tl.int64) * N + rn[None, :], + mask=mask[:, None], + other=0.0, + ) + tl.store(out_ptr + rm[:, None].to(tl.int64) * N + rn[None, :], acc, mask=mask[:, None]) + + +def _split_k(x: torch.Tensor, w_tf32: torch.Tensor, out: torch.Tensor) -> None: + block_m, block_k, warps, stages = CFG + M, K = x.shape + N = w_tf32.shape[0] + part = torch.empty((SPLIT_K, M, N), dtype=torch.float32, device=x.device) + _router_gemm_tf32_partial_kernel[(triton.cdiv(M, block_m), SPLIT_K)]( + x, + part, + w_tf32, + M, + K, + N, + K // SPLIT_K, + BLOCK_M=block_m, + BLOCK_K=block_k, + num_warps=warps, + num_stages=stages, + ) + _router_gemm_tf32_reduce_kernel[(triton.cdiv(M, REDUCE_BLOCK_M),)]( + part, out, M, N, SPLIT_K, BLOCK_M=REDUCE_BLOCK_M, num_warps=4 + ) + + +@torch.library.custom_op("trtllm::router_gemm_tf32", mutates_args=()) +def router_gemm_tf32(x: torch.Tensor, w_tf32: torch.Tensor) -> torch.Tensor: + """float32 logits [M, N] = x [M, K] (bfloat16) @ w_tf32 [N, K]^T; ``w_tf32`` from prepare_router_weight_tf32.""" + block_m, block_k, warps, stages = CFG + assert x.dtype == torch.bfloat16 and x.dim() == 2 and x.is_contiguous(), ( + "x: contiguous bfloat16 [M, K]" + ) + assert ( + w_tf32.dtype == torch.float32 and w_tf32.is_contiguous() and w_tf32.shape[1] == x.shape[1] + ) + M, K = x.shape + N = w_tf32.shape[0] + assert K % block_k == 0 and N & (N - 1) == 0 and N <= 256, (K, N) + out = torch.empty((M, N), dtype=torch.float32, device=x.device) + if 0 < M <= SPLITK_MAX_M and SPLITK and K % (SPLIT_K * block_k) == 0: + _split_k(x, w_tf32, out) + logger.info_once( + f"TF32 prefill router: split-K ({SPLIT_K} slices) taken (kill TRTLLM_CTX_ROUTER_TF32_SPLITK=0)", + key="router_gemm_tf32_splitk", + ) + elif M: + _router_gemm_tf32_kernel[(triton.cdiv(M, block_m),)]( + x, + w_tf32, + out, + M, + K, + N, + BLOCK_M=block_m, + BLOCK_K=block_k, + num_warps=warps, + num_stages=stages, + ) + return out + + +@router_gemm_tf32.register_fake +def _(x: torch.Tensor, w_tf32: torch.Tensor) -> torch.Tensor: + return x.new_empty((x.shape[0], w_tf32.shape[0]), dtype=torch.float32) diff --git a/tensorrt_llm/_torch/moe/fused_moe/unpermute_residual.py b/tensorrt_llm/_torch/moe/fused_moe/unpermute_residual.py new file mode 100644 index 000000000000..47faba6ceee4 --- /dev/null +++ b/tensorrt_llm/_torch/moe/fused_moe/unpermute_residual.py @@ -0,0 +1,77 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""(rule 1b, bitwise) moe_unpermute with an optional residual: the shared-expert output folded into the routed MoE's +fixed-order finalize. Per token t and hidden column c, in the top-k order of expanded_idx_to_permuted_idx exactly as +the C++ moe_unpermute_inplace (cute_dsl moeUnpermuteKernel) does it: + + acc = 0; for k in 0..top_k-1: if p = e2p[t, k] >= 0: acc = fma(float(rows[p, c]), float(scales[t, k]), acc) + out = bf16_rn(acc) # = moe_unpermute's output + out = bf16_rn(float(out) + float(res[t, c])) # = shared_output.add_(routed_output) + +so the output is bitwise moe_unpermute_inplace followed by the ATen bf16 add (``fma`` is the contraction nvcc applies +to the C++ ``acc += float(x) * float(s)``; ``contract=False`` is the separately rounded form, kept for the test).""" + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _unpermute_residual_kernel( + rows_ptr, out_ptr, e2p_ptr, scales_ptr, res_ptr, hidden, TOP_K: tl.constexpr, BLOCK: tl.constexpr, + HAS_RES: tl.constexpr, CONTRACT: tl.constexpr, +): # fmt: skip + t = tl.program_id(0) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + mask = cols < hidden + acc = tl.zeros((BLOCK,), dtype=tl.float32) + for k in tl.static_range(TOP_K): + p = tl.load(e2p_ptr + t * TOP_K + k) + s = tl.load(scales_ptr + t * TOP_K + k).to(tl.float32) + x = tl.load(rows_ptr + p.to(tl.int64) * hidden + cols, mask=mask & (p >= 0), other=0.0).to( + tl.float32 + ) + if CONTRACT: + upd = tl.fma(x, s, acc) + else: + upd = acc + x * s + acc = tl.where(p >= 0, upd, acc) + out = acc.to(tl.bfloat16) + if HAS_RES: + r = tl.load(res_ptr + t.to(tl.int64) * hidden + cols, mask=mask, other=0.0).to(tl.float32) + out = (out.to(tl.float32) + r).to(tl.bfloat16) + tl.store(out_ptr + t.to(tl.int64) * hidden + cols, out, mask=mask) + + +# (BLOCK, num_warps): tuned on SM107 at the M3 CTX shape (784698: 54.7 / 97.6 us at 8K / 16K local tokens vs 58.5 / +# 102.1 at (1024, 2), copy floor 49.3 / 94.0; bitwise in every config). +_CFG = (2048, 4) + + +def unpermute_residual( + permuted_rows: torch.Tensor, + output: torch.Tensor, + expanded_idx_to_permuted_idx: torch.Tensor, + topk_scales: torch.Tensor, + residual: torch.Tensor = None, + contract: bool = True, +) -> torch.Tensor: + """output [T, H] bf16 = moe_unpermute(permuted_rows [M, H], e2p [T * top_k], topk_scales [T, top_k]) (+ residual + [T, H] bf16, rounded as the ATen add). Returns ``output``.""" + t, hidden = output.shape + top_k = topk_scales.shape[1] + assert permuted_rows.dtype == output.dtype == torch.bfloat16 and permuted_rows.is_contiguous() + assert output.is_contiguous() and expanded_idx_to_permuted_idx.numel() == t * top_k + if residual is not None: + assert ( + residual.shape == output.shape + and residual.dtype == torch.bfloat16 + and residual.is_contiguous() + ) + block, warps = _CFG + _unpermute_residual_kernel[(t, triton.cdiv(hidden, block))]( + permuted_rows, output, expanded_idx_to_permuted_idx, topk_scales.contiguous(), + residual if residual is not None else output, hidden, TOP_K=top_k, BLOCK=block, + HAS_RES=residual is not None, CONTRACT=contract, num_warps=warps, + ) # fmt: skip + return output diff --git a/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_gather_grouped_blockscaled_gemm_act_fusion.py b/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_gather_grouped_blockscaled_gemm_act_fusion.py index 66c4961dda69..9662d5e0f33f 100644 --- a/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_gather_grouped_blockscaled_gemm_act_fusion.py +++ b/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_gather_grouped_blockscaled_gemm_act_fusion.py @@ -169,6 +169,8 @@ def silu_f32( SUPPORTED_ACTIVATION_TYPES = ( ActivationType.Swiglu, + # SwiGLU-OAI (gpt-oss / MiniMax): run as Swiglu with gate scale / linear offset (see __init__). + ActivationType.SwigluBias, ActivationType.SiTu, ActivationType.Relu2, ) @@ -294,6 +296,8 @@ def __init__( situ_beta: Optional[float] = None, situ_linear_beta: Optional[float] = None, swiglu_limit: float = float("inf"), + swiglu_gate_scale: float = 1.0, + swiglu_linear_offset: float = 0.0, ): self.a_path = a_path # locality domain half-GEMM: two partitions write their N-half into a shared @@ -302,6 +306,17 @@ def __init__( self.sf_vec_size = sf_vec_size self.topk = topk self.activation_type = validate_activation_type(activation_type) + if self.activation_type == ActivationType.SwigluBias: + # SwigluBias reaches the kernel through the SiTU constant slots (the MoE ``act_alpha`` / ``act_beta`` + # of ``SwigluBiasActivation.constants()``): situ_beta = gate sigmoid scale, situ_linear_beta = linear + # offset; the clamp stays ``swiglu_limit``. The epilogue is the SwiGLU one with those two constants. + if situ_beta is None or situ_linear_beta is None: + raise ValueError( + "ActivationType.SwigluBias requires its gate scale and linear offset" + ) + swiglu_gate_scale, swiglu_linear_offset = float(situ_beta), float(situ_linear_beta) + situ_beta = situ_linear_beta = None + self.activation_type = ActivationType.Swiglu if self.activation_type == ActivationType.SiTu: if situ_beta is None or situ_linear_beta is None: raise ValueError( @@ -331,6 +346,16 @@ def __init__( "swiglu_limit applies to ActivationType.Swiglu only; " f"got {self.activation_type.name} with swiglu_limit={self.swiglu_limit}." ) + # SwiGLU-OAI (gpt-oss / MiniMax ``SwigluBias``, in the dequantized domain): ``(clip(up) + offset) * + # g * sigmoid(scale * g)`` with ``g = min(gate, limit)``. The defaults (1, 0) are plain SwiGLU and generate + # the same code as before. + self.swiglu_gate_scale = float(swiglu_gate_scale) + self.swiglu_linear_offset = float(swiglu_linear_offset) + self.has_swiglu_oai = self.swiglu_gate_scale != 1.0 or self.swiglu_linear_offset != 0.0 + if self.has_swiglu_oai and self.activation_type != ActivationType.Swiglu: + raise ValueError( + "swiglu_gate_scale / swiglu_linear_offset apply to ActivationType.Swiglu only" + ) self.is_gated = is_gated_activation(self.activation_type) if locality_domain_half_gemm and not self.is_gated: raise ValueError("Rubin locality domain half-GEMM currently supports SwiGLU only") @@ -3497,9 +3522,12 @@ def _apply_swiglu_epilogue( fclip_xorsign(acc_vec_up_alpha[0], self.swiglu_limit), fclip_xorsign(acc_vec_up_alpha[1], self.swiglu_limit), ) + neg_log2e_scaled = -LOG2_E + if cutlass.const_expr(self.has_swiglu_oai): + neg_log2e_scaled = cutlass.Float32(-1.4426950408889634 * self.swiglu_gate_scale) tCompute_log2e = cute.arch.mul_packed_f32x2( (acc_vec_gate_alpha[0], acc_vec_gate_alpha[1]), - (-LOG2_E, -LOG2_E), + (neg_log2e_scaled, neg_log2e_scaled), ) ( tCompute[i], @@ -3520,6 +3548,14 @@ def _apply_swiglu_epilogue( (tCompute[i], tCompute[i + 1]), (acc_vec_gate_alpha[0], acc_vec_gate_alpha[1]), ) + if cutlass.const_expr(self.has_swiglu_oai): + acc_vec_up_alpha = cute.arch.add_packed_f32x2( + (acc_vec_up_alpha[0], acc_vec_up_alpha[1]), + ( + cutlass.Float32(self.swiglu_linear_offset), + cutlass.Float32(self.swiglu_linear_offset), + ), + ) ( tCompute[i], tCompute[i + 1], @@ -3534,7 +3570,18 @@ def _apply_swiglu_epilogue( if cutlass.const_expr(self.has_swiglu_limit): acc_vec_gate_alpha = fmin(acc_vec_gate_alpha, self.swiglu_limit, nan=True) acc_vec_up_alpha = fclip_xorsign(acc_vec_up_alpha, self.swiglu_limit) - tCompute[i] = acc_vec_up_alpha * silu_f32(acc_vec_gate_alpha, fastmath=True) + if cutlass.const_expr(self.has_swiglu_oai): + tCompute[i] = ( + acc_vec_up_alpha + cutlass.Float32(self.swiglu_linear_offset) + ) * ( + acc_vec_gate_alpha + * sigmoid_f32( + acc_vec_gate_alpha * cutlass.Float32(self.swiglu_gate_scale), + fastmath=True, + ) + ) + else: + tCompute[i] = acc_vec_up_alpha * silu_f32(acc_vec_gate_alpha, fastmath=True) @cute.jit def _apply_situ_epilogue( diff --git a/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_grouped_blockscaled_gemm_finalize_fusion.py b/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_grouped_blockscaled_gemm_finalize_fusion.py index f3397527412c..dcbce3a1a11b 100644 --- a/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_grouped_blockscaled_gemm_finalize_fusion.py +++ b/tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_grouped_blockscaled_gemm_finalize_fusion.py @@ -99,6 +99,24 @@ def blk_reduce_bf16(dst_gemm, src_smem, size, loc=None, ip=None): ) +@dsl_user_op +def blk_store_b16(dst_gemm, src_smem, size, loc=None, ip=None): + """Plain bulk store (no reduction) of a 16-bit row segment, cp.async.bulk (store_permuted mode).""" + llvm.inline_asm( + None, + [ + dst_gemm.iterator.llvm_ptr, + src_smem.iterator.llvm_ptr, + size.ir_value(), + ], + "cp.async.bulk.global.shared::cta.bulk_group [$0], [$1], $2;", + "l,l,r", + has_side_effects=True, + loc=loc, + ip=ip, + ) + + @dsl_user_op def blk_reduce_fp32(dst_gemm, src_smem, size, loc=None, ip=None): """Block reduce for FP32 using cp.reduce.async.bulk.""" @@ -171,7 +189,12 @@ def __init__( cluster_shape_mn: Tuple[int, int], raster_along_m: bool = False, topK: int = 1, + store_permuted: bool = False, ): + """store_permuted: instead of the fused finalize (scatter-add of token_scale * alpha * acc into the token + row, bf16 atomics: run-to-run order dependent), store bf16(alpha * acc) at the permuted row of c [m, n], + for a separate fixed-order finalize (deterministic, rule 1b).""" + self.store_permuted = store_permuted self.sf_vec_size = sf_vec_size self.acc_dtype = cutlass.Float32 self.mma_inst_shape = mma_inst_shape @@ -1588,10 +1611,11 @@ def kernel( token_idx = cutlass.Int32(0) alpha_val_iter = alpha_val if is_valid_row: - token_idx = expanded_idx // self.topK - topk_idx = expanded_idx % self.topK - token_scale = token_final_scales[(token_idx, topk_idx)] - alpha_val_iter = alpha_val * token_scale + if cutlass.const_expr(not self.store_permuted): + token_idx = expanded_idx // self.topK + topk_idx = expanded_idx % self.topK + token_scale = token_final_scales[(token_idx, topk_idx)] + alpha_val_iter = alpha_val * token_scale for n_iter_idx in cutlass.range(n_subtile_cnt): # Load accumulator from tensor memory buffer to register @@ -1630,13 +1654,21 @@ def kernel( if is_valid_row: expanded_idx = permuted_idx_to_expanded_idx[permuted_row] token_idx = expanded_idx // self.topK + if cutlass.const_expr(self.store_permuted): + token_idx = permuted_row coord_n = mma_tile_coord_mnl[1] * self.cta_tile_shape_mnk[1] scatter_out_offset = cute.domain_offset((token_idx, coord_n, 0), c) # sC row index: m_iter_idx * 128 + epi_tidx sC_row = m_iter_idx * 128 + epi_tidx - if cutlass.const_expr(self.c_dtype == cutlass.BFloat16): + if cutlass.const_expr(self.store_permuted): + blk_store_b16( + scatter_out_offset, + sC[sC_row, None, 0], + cutlass.Int32(self.copy_size), + ) + elif cutlass.const_expr(self.c_dtype == cutlass.BFloat16): blk_reduce_bf16( scatter_out_offset, sC[sC_row, None, 0], diff --git a/tensorrt_llm/_torch/pyexecutor/resource_manager.py b/tensorrt_llm/_torch/pyexecutor/resource_manager.py index a21bc9eaec98..16c4807d69fc 100644 --- a/tensorrt_llm/_torch/pyexecutor/resource_manager.py +++ b/tensorrt_llm/_torch/pyexecutor/resource_manager.py @@ -896,6 +896,7 @@ def append_to_kv_heads_per_layer(num_kv_heads_per_layer: List[int], self.max_blocks_per_seq = self.impl.max_blocks_per_seq self.enable_block_reuse = kv_cache_config.enable_block_reuse self.enable_partial_reuse = kv_cache_config.enable_partial_reuse + self.copy_on_partial_reuse = kv_cache_config.copy_on_partial_reuse # Keep unused block offsets as safe block index 0. self.host_kv_cache_block_offsets = torch.zeros( self.num_pools, diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py index 3e9fc60e7e30..0516079f4fdc 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py @@ -15,6 +15,7 @@ import enum import os +import time from collections import Counter from typing import Callable, Optional @@ -339,6 +340,54 @@ def __init__( # per batch, and those left in the batch being scheduled. self._inforward_snapshot_rows = kv_cache_manager.inforward_snapshot_rows self._inforward_snapshot_rows_left = 0 + # Append reserve for chunked context (opt-in: TLLM_CTX_APPEND_RESERVE=R tokens; unset or 0 disables). + # The first context request of each iteration is chunked against + # max_num_tokens - R, so R tokens stay free for short context requests + # (agentic appends) in the same iteration instead of waiting for the + # whole long prefill. The cold chunk boundaries depend only on the + # request and the config, so scheduling stays deterministic. Applies + # only when max_num_tokens > 2 * R. + self._ctx_append_reserve = int(os.environ.get("TLLM_CTX_APPEND_RESERVE", "0") or 0) + if ( + self._ctx_append_reserve > 0 + and max_num_tokens is not None + and max_num_tokens > 2 * self._ctx_append_reserve + ): + logger.info( + f"KVCacheV2Scheduler: context append reserve {self._ctx_append_reserve} tokens " + f"(first context chunk <= {max_num_tokens - self._ctx_append_reserve})" + ) + else: + self._ctx_append_reserve = 0 + self._ctx_append_reserve_logged = 0 + # Adaptive reserve (on with the reserve; TLLM_CTX_APPEND_RESERVE_ADAPTIVE=0 falls back to the fixed + # reserve): hold the reserve back only in iterations where another context request is + # waiting behind the first one, so an idle cold prompt keeps full + # max_num_tokens chunks. Its chunk sizes then depend on load, which is + # value-neutral only if the forward is invariant to chunk size. + self._ctx_append_reserve_adaptive = self._ctx_append_reserve > 0 and ( + os.environ.get("TLLM_CTX_APPEND_RESERVE_ADAPTIVE", "1") == "1" + ) + self._ctx_append_reserve_active = True + if self._ctx_append_reserve_adaptive: + logger.info("KVCacheV2Scheduler: context append reserve is adaptive") + # Shortest-first reserve (on with the reserve; TLLM_CTX_APPEND_RESERVE_SJF=0 keeps arrival order): the first + # context request keeps its arrival-order place and its max_num_tokens - R chunk, and the requests behind it + # compete for the leftover budget shortest-uncached-first, so a short append is not starved behind a second + # long prefill. Like the adaptive reserve, this makes chunk boundaries load-dependent. + self._ctx_append_reserve_sjf = self._ctx_append_reserve > 0 and ( + os.environ.get("TLLM_CTX_APPEND_RESERVE_SJF", "1") == "1" + ) + self._ctx_append_reserve_sjf_logged = 0 + # The sort key is each request's uncached token count, probed against the reuse tree; it is memoized per + # request and re-probed every TLLM_CTX_APPEND_RESERVE_SJF_REPROBE scheduler passes (it only orders requests). + self._ctx_append_reserve_sjf_reprobe = max( + 1, int(os.environ.get("TLLM_CTX_APPEND_RESERVE_SJF_REPROBE", "8") or 1) + ) + self._ctx_append_reserve_sjf_pass = 0 + self._uncached_context_memo: dict[int, tuple[int, int]] = {} + if self._ctx_append_reserve_sjf: + logger.info("KVCacheV2Scheduler: context append reserve is shortest-first") # Registered by PyExecutor; see set_async_transfer_manager. self._async_transfer_manager = None @@ -743,6 +792,18 @@ def preempt_for_pages(req: LlmRequest) -> bool: # Only context-only batches take Mamba snapshots inside the forward. self._inforward_snapshot_rows_left = 0 if scheduled_gen else self._inforward_snapshot_rows + if self._ctx_append_reserve_adaptive: + self._ctx_append_reserve_active = ( + sum(1 for req in pending_ctx if req.state_value == self._context_init_state_value) + > 1 + ) + if ( + self._ctx_append_reserve_sjf + and self._ctx_append_reserve_active + and len(pending_ctx) > 2 + ): + self._order_reserve_shortest_first(pending_ctx) + if self._ctx_shortest_first and len(pending_ctx) > 1: pending_ctx = self._order_ctx_shortest_first(pending_ctx) starved_ctx: RequestList = [] @@ -1440,12 +1501,89 @@ def _preempt_for_resume( """ return self.has_cp_helix and not req.is_first_context_chunk and preempt_for_pages(req) + def _order_reserve_shortest_first(self, pending_ctx: RequestList) -> None: + """Reorder ``pending_ctx`` in place for the append reserve. + + The first request keeps its place. Started context requests (continuations holding pages) follow in arrival + order, so a new short request never pushes a started prefill toward page preemption. Not-yet-started requests + come last, shortest uncached first. + """ + start = time.perf_counter() + self._ctx_append_reserve_sjf_pass += 1 + rest = pending_ctx[1:] + unstarted = [req for req in rest if self._is_unstarted_context(req)] + started = [req for req in rest if not self._is_unstarted_context(req)] + if len(unstarted) > 1: + unstarted.sort(key=self._uncached_context_tokens) + pending_ctx[1:] = started + unstarted + live = {req.py_request_id for req in unstarted} + for request_id in [rid for rid in self._uncached_context_memo if rid not in live]: + del self._uncached_context_memo[request_id] + if self._ctx_append_reserve_sjf_logged < 3: + self._ctx_append_reserve_sjf_logged += 1 + logger.info( + f"[ctx-reserve-sjf] taken: {len(started)} started + {len(unstarted)} new context requests behind " + f"the first, new ones shortest first ({(time.perf_counter() - start) * 1e6:.0f} us)" + ) + + def _is_unstarted_context(self, req: LlmRequest) -> bool: + return req.state_value == self._context_init_state_value and req.is_first_context_chunk + + def _uncached_context_tokens(self, req: LlmRequest) -> int: + """Context tokens a not-yet-started ``req`` still has to compute: its length minus the reuse depth that + ``_prepare_context_pair`` would claim (the joint draft/target minimum when a draft pool is paired), probed + without claiming pages. Memoized per request for ``_ctx_append_reserve_sjf_reprobe`` passes.""" + memo = self._uncached_context_memo.get(req.py_request_id) + if ( + memo is not None + and self._ctx_append_reserve_sjf_pass - memo[1] < self._ctx_append_reserve_sjf_reprobe + ): + return memo[0] + if self._joint_draft_manager is not None: + reuse = self._reuse_claim_limit(req) + else: + probe = getattr(self.kv_cache_manager, "probe_context_reuse", None) + reuse = probe(req) if probe is not None else None + uncached = max(0, req.context_remaining_length - (reuse or 0)) + self._uncached_context_memo[req.py_request_id] = ( + uncached, + self._ctx_append_reserve_sjf_pass, + ) + return uncached + def _try_schedule_context_chunked( self, req: LlmRequest, budget: BudgetTracker, preempt_for_pages: Callable[[LlmRequest], bool], token_cap: Optional[int] = None, + ) -> tuple[ScheduleAction, int, bool]: + """Chunk a context request, holding back the append reserve for the first one. + + See ``_ctx_append_reserve`` in ``__init__``. + """ + reserve = self._ctx_append_reserve if self._ctx_append_reserve_active else 0 + if not reserve or budget.num_tokens != 0 or budget.max_num_tokens is None: + return self._try_schedule_context_chunked_impl(req, budget, preempt_for_pages) + full = budget.max_num_tokens + budget.max_num_tokens = full - reserve + try: + result = self._try_schedule_context_chunked_impl(req, budget, preempt_for_pages) + finally: + budget.max_num_tokens = full + if self._ctx_append_reserve_logged < 3 and result[0] is ScheduleAction.SCHEDULED: + self._ctx_append_reserve_logged += 1 + logger.info( + f"[ctx-reserve] taken: first ctx chunk {result[1]} tokens " + f"(budget {full} - reserve {reserve})" + ) + return result + + def _try_schedule_context_chunked_impl( + self, + req: LlmRequest, + budget: BudgetTracker, + preempt_for_pages: Callable[[LlmRequest], bool], ) -> tuple[ScheduleAction, int, bool]: """FCFS interleaved chunking for a single context request. diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index 2e816594cd1f..b81776109860 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -109,6 +109,7 @@ l0_cpu: - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/spec/test_modeling_v2_m3_wide_draft_logits.py - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_draft_attention_bcg_route.py - unittest/_torch/attention/test_fallback_fmha_extra_page_sizes.py + - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_ctx_stack_route.py - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_dense_backend_library_order - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_fp8_indexer_rejects_different_qk_norm_epsilons - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_moe_reduces_only_local_terms @@ -144,6 +145,13 @@ l0_cpu: # what runs it. - unittest/_torch/misc/test_xgrammar_structural_tag.py - unittest/_torch/misc/test_grammar_matcher.py + - unittest/_torch/models/test_minimax_m3.py::test_bcg_bucket_takes_eager_qkv + - unittest/_torch/models/test_minimax_m3.py::test_bcg_bucket_keeps_captured_qkv_off_rubin + - unittest/_torch/models/test_minimax_m3.py::test_swiglu_mxfp8_engages_on_sm107_only + - unittest/_torch/models/test_minimax_m3.py::test_shared_fold_into_trtllm_gen_finalize_is_sm107_only + - unittest/_torch/models/test_minimax_m3.py::test_fused_qkv_rows_agree_between_eager_and_breakable + - unittest/_torch/models/test_minimax_m3.py::test_ctx_boundary_norm_declines_off_rubin_and_off_geometry + - unittest/_torch/models/test_minimax_m3.py::test_cutedsl_shared_fold_only_without_token_dispatch - unittest/_torch/models/checkpoints - unittest/_torch/modules - unittest/_torch/moe @@ -156,6 +164,7 @@ l0_cpu: - unittest/_torch/speculative/test_spec_slot_pool_sizing.py - unittest/_torch/flashinfer/test_flashinfer_cubin_pool.py - unittest/_torch/test_custom_config_registration.py + - unittest/_torch/misc/test_fp4_moe_tactic_table.py - unittest/_torch/test_hf_quant_config.py - unittest/_torch/test_mmap_utils.py - unittest/_torch/test_connector.py diff --git a/tests/unittest/_torch/attention/fmha/test_msa_combine_mxfp8.py b/tests/unittest/_torch/attention/fmha/test_msa_combine_mxfp8.py new file mode 100644 index 000000000000..ef93b2a59c9a --- /dev/null +++ b/tests/unittest/_torch/attention/fmha/test_msa_combine_mxfp8.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 CTX: when the NVFP4 sparse prefill's combine writes the o_proj input as MXFP8 (msa_combine_mxfp8).""" + +from types import SimpleNamespace + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.fmha import msa_combine_mxfp8 as m +from tensorrt_llm._torch.modules import linear + +pytestmark = pytest.mark.cpu_only + + +@pytest.fixture(autouse=True) +def _one_stream(monkeypatch): + # The slot records its producing stream; on CPU tensors every set and take is on one stream. + stream = object() + monkeypatch.setattr(torch.cuda, "current_stream", lambda device=None: stream) + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + + +class _Sparse: + def sparse_atten_nvfp4_kv_func(self, q, *, out=None, o_fp8=None, sf_out=None, write_bf16=True): + pass + + +class _OldSparse: + def sparse_atten_nvfp4_kv_func(self, q, *, out=None): + pass + + +def _out(rows=200, heads=32): + return torch.zeros((rows, heads, 128), dtype=torch.bfloat16) + + +CTX = SimpleNamespace(num_generations=0) + + +def test_engages_only_when_armed_pure_context_in_place_and_supported(monkeypatch): + monkeypatch.setattr(m, "ENABLED", True) + out = _out() + assert m.combine_kwargs(_Sparse(), out, CTX, in_place=True) is None, "not armed" + with m.armed(): + kw = m.combine_kwargs(_Sparse(), out, CTX, in_place=True) + assert kw is not None and kw["write_bf16"] is True + assert kw["o_fp8"].shape == (200, 32 * 128) and kw["o_fp8"].dtype == torch.float8_e4m3fn + assert kw["sf_out"].numel() == 256 * 32 * 128 // 32 + assert int(kw["sf_out"][-128 * 32 * 128 // 32 :].sum()) == 0, "padding tile zeroed" + assert ( + m.combine_kwargs(_Sparse(), out, SimpleNamespace(num_generations=3), in_place=True) + is None + ) + assert m.combine_kwargs(_Sparse(), out, CTX, in_place=False) is None + assert m.combine_kwargs(_OldSparse(), out, CTX, in_place=True) is None + assert m.combine_kwargs(_Sparse(), out.view(200, -1), CTX, in_place=True) is None + assert m.combine_kwargs(_Sparse(), _out().float(), CTX, in_place=True) is None + assert m.combine_kwargs(_Sparse(), out, CTX, in_place=True) is None, "disarmed on exit" + + +def test_kill_switch(monkeypatch): + monkeypatch.setattr(m, "ENABLED", False) + with m.armed(): + assert m.combine_kwargs(_Sparse(), _out(), CTX, in_place=True) is None + + +class _Log: + def __init__(self): + self.info, self.warning = [], [] + + def info_once(self, msg, key=None): + self.info.append(msg) + + def warning_once(self, msg, key=None): + self.warning.append(msg) + + +def _publish(monkeypatch): + monkeypatch.setattr(m, "ENABLED", True) + log = _Log() + monkeypatch.setattr(m, "logger", log) + out = _out() + with m.armed(): + kw = m.combine_kwargs(_Sparse(), out, CTX, in_place=True) + m.publish(out, kw) + return out, kw, log + + +def test_engagement_is_logged_only_when_the_o_proj_takes_the_pair(monkeypatch): + out, kw, log = _publish(monkeypatch) + assert not log.info, "publishing alone is not engagement" + o = out.view(200, -1) # the o_proj input: same storage and shape + act, sf = linear.take_prequantized_mxfp8(o) + assert act.data_ptr() == kw["o_fp8"].data_ptr() and sf is kw["sf_out"] + m.after_o_proj(o) + assert linear._PREQUANTIZED_MXFP8[0] is None + assert log.info == ["[M3 CTX] combine MXFP8 o_proj input taken"] and not log.warning + + +def test_a_take_on_mismatched_rows_is_a_miss(monkeypatch): + out, _, log = _publish(monkeypatch) + padded = torch.zeros((256, 32 * 128), dtype=torch.bfloat16) # e.g. a padded o_proj input + assert linear.take_prequantized_mxfp8(padded) is None, "dropped, the o_proj quantizes" + m.after_o_proj(padded) + assert not log.info and len(log.warning) == 1 and "not consumed" in log.warning[0] + + +def test_a_pair_the_o_proj_never_looked_at_is_cleared_and_a_miss(monkeypatch): + _, _, log = _publish(monkeypatch) + m.after_o_proj() + assert linear._PREQUANTIZED_MXFP8[0] is None + assert not log.info and len(log.warning) == 1 + + +def test_slot_audit_counts_takes_drops_unconsumed_and_declines(monkeypatch): + monkeypatch.setattr(linear, "_PREQUANTIZED_MXFP8_STATS", {}) + monkeypatch.setattr(m, "ENABLED", True) + monkeypatch.setattr(m, "logger", _Log()) + out = _out() + o = out.view(200, -1) + for take_input in (o, torch.zeros((256, 32 * 128), dtype=torch.bfloat16), None): + with m.armed("general"): + kw = m.combine_kwargs(_Sparse(), out, CTX, in_place=True) + m.publish(out, kw) + if take_input is not None: + linear.take_prequantized_mxfp8(take_input) + m.after_o_proj(take_input) + with m.armed("general"): + assert ( + m.combine_kwargs(_Sparse(), out, SimpleNamespace(num_generations=1), in_place=True) + is None + ) + assert m.combine_kwargs(_Sparse(), out, CTX, in_place=False) is None + stats = linear._PREQUANTIZED_MXFP8_STATS + assert stats["combine_general"] == [3, 1, 1, 1] # set, taken, dropped, unconsumed + assert stats["combine_general_declined_mixed_step"][0] == 1 + assert stats["combine_general_declined_not_in_place"][0] == 1 + + +def _mxfp8_o_proj(use_cutlass=True, lora=None): + method = object.__new__(linear.MXFP8LinearMethod) + method.use_cutlass = use_cutlass + return SimpleNamespace(quant_method=method, lora=lora) + + +def test_o_proj_takes_slot_only_for_an_mxfp8_cutlass_linear(): + assert m.o_proj_takes_slot(_mxfp8_o_proj()) + assert not m.o_proj_takes_slot(_mxfp8_o_proj(use_cutlass=False)) + assert m.o_proj_takes_slot(_mxfp8_o_proj(lora=object())), ( + "a LoRA layer reads only when lora_params are passed" + ) + assert not m.o_proj_takes_slot(SimpleNamespace(quant_method=object(), lora=None)) + + +def test_bf16_skip_only_when_enabled_and_proven(monkeypatch): + monkeypatch.setattr(m, "ENABLED", True) + out = _out() + for skip, ok, expect_write in ((False, True, True), (True, False, True), (True, True, False)): + monkeypatch.setattr(m, "SKIP_BF16", skip) + with m.armed("general", skip_bf16_ok=ok): + assert ( + m.combine_kwargs(_Sparse(), out, CTX, in_place=True)["write_bf16"] is expect_write + ) + + +def test_bf16_skipped_pair_not_taken_raises(monkeypatch): + monkeypatch.setattr(m, "ENABLED", True) + monkeypatch.setattr(m, "SKIP_BF16", True) + monkeypatch.setattr(m, "logger", _Log()) + out = _out() + with m.armed("general", skip_bf16_ok=True): + kw = m.combine_kwargs(_Sparse(), out, CTX, in_place=True) + m.publish(out, kw) + with pytest.raises(RuntimeError, match="bf16 input was not written"): + m.after_o_proj(torch.zeros((256, 32 * 128), dtype=torch.bfloat16)) + # Taken: no raise. + with m.armed("general", skip_bf16_ok=True): + kw = m.combine_kwargs(_Sparse(), out, CTX, in_place=True) + m.publish(out, kw) + o = out.view(200, -1) + assert linear.take_prequantized_mxfp8(o) is not None + m.after_o_proj(o) + assert "[M3 CTX] combine MXFP8 o_proj input taken (bf16 store skipped)" in m.logger.info diff --git a/tests/unittest/_torch/attention/sparse/msa/test_fmha_sm107_gates.py b/tests/unittest/_torch/attention/sparse/msa/test_fmha_sm107_gates.py new file mode 100644 index 000000000000..91adb76710b2 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_fmha_sm107_gates.py @@ -0,0 +1,172 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The fmha_sm100 MiniMax-M3 performance paths engage on SM107 only (3rdparty/patches/msa_strided_paged_kv.patch). + +SM107 runs the sm_100 builds, so every gate is a runtime check of the device capability, resolved once on the host: +the plan side stream and the deferred split-decision read (api.py), the indexer R2 store +(cute/src/sm100/fwd/atten_fwd_nvfp4_kv.py + the AOT fingerprint in cute/src/common/aot_cache.py), the proxy's skipped +correction chain / S double buffer (jit.py defines) and the k2q CSR build's scratch arena (cute/src/sm100/build_k2q_csr, +host C++). SM100 / SM103 keep the stock fmha_sm100. The jit.py / aot_cache.py cells load the installed files with a +stand-in torch, and the k2q cell reads the installed source, so they run without a GPU. +""" + +import importlib.util +import inspect +import os +import sys +import types + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.msa_utils import ( + msa_package_available, +) + + +@pytest.fixture +def api(): + # Installs the CuTe aliases the packaged MSA sources still reference, then reports importability. + if not msa_package_available(): + pytest.skip("fmha_sm100 (MSA) is not installed") + return pytest.importorskip("fmha_sm100.api") + + +def _fmha_sm100_dir() -> str: + spec = importlib.util.find_spec("fmha_sm100") + if spec is None or not spec.submodule_search_locations: + pytest.skip("fmha_sm100 (MSA) is not installed") + return list(spec.submodule_search_locations)[0] + + +class _Bound: + def __init__(self, **arguments): + self.arguments = arguments + + +def _side_stream_eligible_args(): + lens = torch.tensor([16, 32], dtype=torch.int32) # host tensors: the side stream may read them + return _Bound( + device=0, qo_segment_lens=lens, kv_segment_lens=lens, qo_offset=None, kv_block_num=-1 + ) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "cc, expected", [((10, 0), False), ((10, 3), False), ((10, 7), True), ((12, 0), False)] +) +def test_plan_side_stream_engages_on_sm107_only(api, monkeypatch, cc, expected): + monkeypatch.setattr(api, "_SS_CC", {0: cc}) + # The eligibility check also asks whether a CUDA graph is being captured; no GPU is needed for that here. + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + assert api._ss_eligible(_side_stream_eligible_args()) is expected + + +@pytest.mark.cpu_only +def test_plan_side_stream_resolves_the_capability_once(api, monkeypatch): + calls = [] + + def fake_capability(idx): + calls.append(idx) + return (10, 7) + + monkeypatch.setattr(api, "_SS_CC", {}) + monkeypatch.setattr(torch.cuda, "get_device_capability", fake_capability) + for _ in range(5): + assert api._ss_is_sm107(0) + assert calls == [0] + + +@pytest.mark.cpu_only +def test_plan_side_stream_kill_env_name_unchanged(api): + assert '"TLLM_FMHA_PLAN_SIDE_STREAM", "1"' in inspect.getsource(api) + + +def _load_with_capability(monkeypatch, root: str, cap: tuple, calls: list): + """jit.py and aot_cache.py from the installed package, with a stand-in torch reporting ``cap``.""" + + def capability(*_): + calls.append(cap) + return cap + + cuda = types.SimpleNamespace(is_available=lambda: True, get_device_capability=capability) + monkeypatch.setitem(sys.modules, "torch", types.SimpleNamespace(cuda=cuda)) + monkeypatch.setitem(sys.modules, "jinja2", types.ModuleType("jinja2")) + cutlass = types.ModuleType("cutlass") + cutlass.cute = types.ModuleType("cutlass.cute") + monkeypatch.setitem(sys.modules, "cutlass", cutlass) + monkeypatch.setitem(sys.modules, "cutlass.cute", cutlass.cute) + modules = [] + for rel, name in (("jit.py", "_gate_jit"), ("cute/src/common/aot_cache.py", "_gate_aot_cache")): + spec = importlib.util.spec_from_file_location(name, os.path.join(root, rel)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + modules.append(module) + return modules + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("cap", [(10, 7), (10, 0), (10, 3)], ids=["sm107", "sm100", "sm103"]) +@pytest.mark.parametrize("chain, dbuf, r2kill", [("0", "1", "0"), ("1", "1", "1"), ("0", "0", "0")]) +def test_proxy_modes_and_r2_store_engage_on_sm107_only(monkeypatch, cap, chain, dbuf, r2kill): + root = _fmha_sm100_dir() + monkeypatch.setenv("TLLM_FMHA_PROXY_CORRECTION_CHAIN", chain) + monkeypatch.setenv("TLLM_FMHA_PROXY_S_DOUBLE_BUFFER", dbuf) + monkeypatch.setenv("TRTLLM_MSA_DISABLE_R2STORE", r2kill) + calls = [] + jit, aot = _load_with_capability(monkeypatch, root, cap, calls) + # Importing either module queries no device (no CUDA initialization before a worker fork). + assert calls == [] + sm107 = cap == (10, 7) + want_chain = chain == "1" or not sm107 + want_single = dbuf == "0" or not sm107 + jit._get_tvm_ffi_include = lambda: "/stub/tvm_ffi/include" # flags only; nothing is compiled + flags = jit._get_nvcc_flags(jit.CACHE_BASE) + assert tuple(jit._proxy_modes()) == (want_chain, want_single) + assert ("-DFMHA_ONLYSCORE_PER_TILE_CORRECTION" in flags) is want_chain + assert ("-DFMHA_ONLYSCORE_SINGLE_S" in flags) is want_single + assert aot.r2_store_enabled() is (sm107 and r2kill != "1") + + +def _k2q_csr_source() -> str: + path = os.path.join(_fmha_sm100_dir(), "cute/src/sm100/build_k2q_csr/build_k2q_csr.cu") + if not os.path.isfile(path): + pytest.skip("build_k2q_csr.cu is not installed") + with open(path) as f: + return f.read() + + +@pytest.mark.cpu_only +def test_k2q_scratch_arena_engages_on_sm107_only(): + # The k2q CSR build is host C++ compiled at first use, so its gate is checked in the installed source: the arena + # takes the runtime SM107 check, and the other devices keep the stock allocations. + src = _k2q_csr_source() + sm107 = src.index("sm107_state = (cc_major == 10 && cc_minor == 7) ? 1 : 2;") + arena = src.index("if (is_sm107 && k2q_arena_enabled()) {") + assert sm107 < arena + assert "row_counts = torch::zeros({H, total_rows}, opts);" in src + assert 'std::getenv("FMHA_K2Q_WS_ARENA")' in src + + +@pytest.mark.cpu_only +def test_deferred_split_read_engages_on_sm107_only(api): + # The adaptive plan defers its split-decision read only where _ss_is_sm107 holds (the capability check the side + # stream uses, covered above); SM100 / SM103 read plan_cost immediately. + src = inspect.getsource(api) + assert ( + "defer = _PLAN_DEFER_READ and _ss_is_sm107(device) and not torch.cuda.is_current_stream_capturing()" + in src + ) + assert '"TLLM_FMHA_PLAN_DEFER_READ", "1"' in src diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py new file mode 100644 index 000000000000..962b4808701d --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py @@ -0,0 +1,176 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 FP8 dense prefill on FA4 (msa_prefill._run_dense_fa4). + +Runs run_msa_prefill_gqa's dense branch over a shuffled paged FP8 pool for a batch of context rows, with FA4 and +with its kill switch (fmha_sm100), and checks FA4 engages, is deterministic, and stays within fmha_sm100's error +against an fp64 reference. +""" + +import math +from unittest.mock import create_autospec + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.fmha import msa_prefill +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import ( + MiniMaxM3KVCacheManagerV2, + MiniMaxM3MsaSparseAttention, +) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.msa_utils import ( + msa_package_available, +) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.msa_backend import ( + MiniMaxM3MsaSparseAttentionMetadata, +) + +HEAD_DIM, PAGE, NUM_HEADS, NUM_KV_HEADS = 128, 128, 32, 2 + + +def _fa4_ready() -> bool: + # FA4 dense prefill engages on SM107 only (other SM10x keep fmha_sm100; see the _arch CPU test). + if not torch.cuda.is_available() or torch.cuda.get_device_capability() != (10, 7): + return False + return msa_package_available() and msa_prefill._dense_fa4_forward() is not None + + +pytestmark = pytest.mark.skipif( + not _fa4_ready(), reason="requires SM107, fmha_sm100 and FA4 with the FP8 rescale change" +) + + +def _case(seed: int, rows: list, outlier: bool): + """A batch whose rows (qo_len, kv_len) own shuffled pages of one [slots, 2, kv_heads, page, d] FP8 pool.""" + g = torch.Generator(device="cuda").manual_seed(seed) + pages_per_row = [math.ceil(kv / PAGE) for _, kv in rows] + slots = sum(pages_per_row) + 11 + pool = torch.randn(slots, 2, NUM_KV_HEADS, PAGE, HEAD_DIM, device="cuda", generator=g) * 0.5 + num_tokens = sum(qo for qo, _ in rows) + q = torch.randn(num_tokens, NUM_HEADS * HEAD_DIM, device="cuda", generator=g) * 0.5 + if outlier: + q.view(num_tokens, NUM_HEADS, HEAD_DIM)[:, :, 3] *= 12.0 + pool[:, 0, :, :, 3] *= 12.0 + pool[::5, 1] *= 8.0 + pool = pool.clamp(-448, 448).to(torch.float8_e4m3fn) + q = q.to(torch.bfloat16) + perm = torch.randperm(slots, device="cuda", generator=g).to(torch.int32) + table = torch.full((len(rows), max(pages_per_row) + 3), 7, dtype=torch.int32, device="cuda") + flat, start = [], 0 + for i, n in enumerate(pages_per_row): + table[i, :n] = perm[start : start + n] + flat.append(perm[start : start + n]) + start += n + qo_lens = torch.tensor([qo for qo, _ in rows], dtype=torch.int32) + kv_lens = torch.tensor([kv for _, kv in rows], dtype=torch.int32) + kv_cache_manager = create_autospec(MiniMaxM3KVCacheManagerV2, instance=True) + kv_cache_manager.get_buffers.return_value = pool + kv_cache_manager.is_nvfp4_layer.return_value = False + metadata = create_autospec(MiniMaxM3MsaSparseAttentionMetadata, instance=True) + metadata.kv_cache_manager = kv_cache_manager + metadata.msa_qo_lens_cpu = qo_lens + metadata.msa_kv_lens_cpu = kv_lens + metadata.msa_qo_offset_cpu = kv_lens - qo_lens + metadata.msa_block_table = table + metadata.msa_kv_indices = torch.cat(flat) + return q, pool, metadata, flat + + +def _reference(q, pool, rows, flat): + outs, tok = [], 0 + for (qo, kv), pages in zip(rows, flat): + k = pool[pages.long(), 0].permute(1, 0, 2, 3).reshape(NUM_KV_HEADS, -1, HEAD_DIM)[:, :kv] + v = pool[pages.long(), 1].permute(1, 0, 2, 3).reshape(NUM_KV_HEADS, -1, HEAD_DIM)[:, :kv] + group = NUM_HEADS // NUM_KV_HEADS + k = k.double().repeat_interleave(group, 0) + v = v.double().repeat_interleave(group, 0) + qd = ( + q[tok : tok + qo] + .view(qo, NUM_HEADS, HEAD_DIM) + .to(torch.float8_e4m3fn) + .double() + .permute(1, 0, 2) + ) + s = torch.einsum("htd,hkd->htk", qd, k) * HEAD_DIM**-0.5 + mask = ( + torch.arange(kv, device="cuda")[None, :] + > (kv - qo + torch.arange(qo, device="cuda"))[:, None] + ) + p = torch.softmax(s.masked_fill(mask[None], float("-inf")), -1) + outs.append(torch.einsum("htk,hkd->htd", p, v).permute(1, 0, 2)) + tok += qo + return torch.cat(outs) + + +def _run(q, metadata, row_first, num_rows): + attn = create_autospec(MiniMaxM3MsaSparseAttention, instance=True) + attn.head_dim, attn.num_heads, attn.layer_idx, attn.q_scaling = HEAD_DIM, NUM_HEADS, 0, 1.0 + out = torch.full_like(q, float("nan")) + msa_prefill.run_msa_prefill_gqa( + attn, + q, + metadata, + out, + kv_block_indexes=None, + plan=None, + row_first=row_first, + num_rows=num_rows, + ) + torch.cuda.synchronize() + return out.view(-1, NUM_HEADS, HEAD_DIM) + + +def _max_err(x, ref): + return float((x.double() - ref).abs().max()) + + +# A long chunked prefill, a fresh prompt, a short tail whose packed queries fit one 128-row tile, and a chunk +# ending mid-page. +ROWS = [(300, 2_000), (257, 257), (5, 900), (64, 640)] + + +@pytest.mark.parametrize("outlier", [False, True], ids=["randn", "outlier"]) +def test_dense_prefill_fa4_matches_fmha_sm100_band( + monkeypatch: pytest.MonkeyPatch, outlier: bool +) -> None: + q_all, pool, metadata, flat = _case(1234 + outlier, ROWS, outlier) + q, row_first, served = q_all, 0, ROWS + ref = _reference(q, pool, served, flat) + + calls = [] + real = msa_prefill._dense_fa4_forward() + + def spy(*args, **kwargs): + calls.append(kwargs.get("out") is not None) + return real(*args, **kwargs) + + monkeypatch.setattr(msa_prefill, "_dense_fa4_forward", lambda: spy) + fa4 = _run(q, metadata, row_first, len(served)) + fa4_again = _run(q, metadata, row_first, len(served)) + assert any(calls), "FA4 did not serve the dense prefill" + assert torch.equal(fa4.view(torch.int16), fa4_again.view(torch.int16)), ( + "FA4 dense prefill is not deterministic" + ) + + monkeypatch.setattr(msa_prefill, "dense_prefill_fa4_enabled", lambda *_: False) + stock = _run(q, metadata, row_first, len(served)) + + assert torch.isfinite(fa4).all() + fa4_err, stock_err = _max_err(fa4, ref), _max_err(stock, ref) + # Rule 1b: FA4 rounds differently from fmha_sm100, so compare against fp64, not bitwise; a single BF16 + # output-rounding step is the allowance over fmha_sm100's own worst error. + assert fa4_err <= stock_err * 1.05 + 2.0**-9 * float(ref.abs().max()), (fa4_err, stock_err) + + +def test_dense_prefill_fa4_kill_switch(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(msa_prefill, "_DENSE_PREFILL_FA4", False) + msa_prefill._dense_fa4_forward.cache_clear() + try: + assert not msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, PAGE) + finally: + monkeypatch.undo() + msa_prefill._dense_fa4_forward.cache_clear() + monkeypatch.setattr(msa_prefill, "get_sm_version", lambda: 107) + assert msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, PAGE) + assert not msa_prefill.dense_prefill_fa4_enabled(False, HEAD_DIM, PAGE) + assert not msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, 64) diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4_arch.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4_arch.py new file mode 100644 index 000000000000..97ed5db02bf6 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4_arch.py @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 FP8 dense prefill: FA4 engages on SM107 only (CPU-level; FA4 itself is stubbed).""" + +import pytest + +from tensorrt_llm._torch.attention.backends.fmha import msa_prefill + +HEAD_DIM, PAGE = 128, 128 + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "sm, expected", [(107, True), (100, False), (103, False), (110, False), (90, False)] +) +def test_dense_prefill_fa4_engages_on_sm107_only( + monkeypatch: pytest.MonkeyPatch, sm: int, expected: bool +) -> None: + # FA4 is deterministic but not bitwise to fmha_sm100, so every other architecture keeps the stock dense prefill + # even with a usable FA4 installed. SM107 is the positive control. + monkeypatch.setattr(msa_prefill, "_dense_fa4_forward", lambda: object()) + monkeypatch.setattr(msa_prefill, "get_sm_version", lambda: sm) + assert msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, PAGE) is expected + + +@pytest.mark.cpu_only +def test_dense_prefill_fa4_needs_a_usable_fa4(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(msa_prefill, "_dense_fa4_forward", lambda: None) + monkeypatch.setattr(msa_prefill, "get_sm_version", lambda: 107) + assert not msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, PAGE) diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_proxy_nofill.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_proxy_nofill.py new file mode 100644 index 000000000000..9c3b3f6391fc --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_proxy_nofill.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 prefill indexer proxy: the max-score entries the selectors read are all written by the kernel, so the +unfilled buffer (msa_indexer._unfilled_max_score) gives the same scores and the same top-16 tables as fmha_sm100's +-inf-filled one.""" + +import math + +import pytest +import torch + +import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import msa_indexer +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.msa_utils import ( + require_msa_module, +) +from tensorrt_llm._utils import get_sm_version + +HEADS, DIM, PAGE, SEG = 2, 128, 128, 128 +SENTINEL = 0x7FC0BEEF # a NaN payload the kernel never writes + +sm107 = pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() != 107, reason="SM107 op" +) + + +def _inputs(cached, q, ties): + g = torch.Generator(device="cuda").manual_seed(cached + q + ties) + n_pages = math.ceil((cached + q) / PAGE) + idx_k = (torch.randn(n_pages + 8, 1, PAGE, DIM, device="cuda", generator=g) * 0.5).to( + torch.float8_e4m3fn + ) + idx_q = (torch.randn(q, HEADS, DIM, device="cuda", generator=g) * 0.5).to(torch.float8_e4m3fn) + if ties: + idx_q = ( + torch.randint(-2, 3, (q, HEADS, DIM), device="cuda", generator=g) + .float() + .to(torch.float8_e4m3fn) + ) + idx_k[: n_pages // 3] = 0 + pages = torch.randperm(n_pages + 8, device="cuda", generator=g)[:n_pages].to(torch.int32) + return idx_q, idx_k, pages + + +def _rows(cached, q, segmented): + if not segmented: + return [(0, q, cached + q)] + return [(s, min(SEG, q - s), cached + min(s + SEG, q)) for s in range(0, q, SEG)] + + +def _n_valid(rows, q): + nv = torch.empty(q, dtype=torch.int32) + for start, n, kv in rows: + t = torch.arange(n) + nv[start : start + n] = ((kv - n + t + 1 + PAGE - 1) // PAGE).to(torch.int32) + return nv.cuda() + + +def _select(scores, n_valid): + out = torch.empty((HEADS, scores.shape[2], 16), dtype=torch.int32, device="cuda").permute( + 1, 0, 2 + ) + torch.ops.trtllm.minimax_m3_select_prefill_tile(scores[:HEADS].contiguous(), n_valid, out, 0, 1) + return out + + +@sm107 +@pytest.mark.parametrize( + "cached,q,segmented,splits,ties", + [ + (165000, 512, False, 1, False), + (165000, 2000, True, -1, False), + (165000, 2000, True, -1, True), + (65000, 8192, True, 1, True), + (330000, 300, True, -1, False), + ], +) +def test_unfilled_proxy_scores_match_the_filled_ones(cached, q, segmented, splits, ties): + fmha = require_msa_module() + idx_q, idx_k, pages = _inputs(cached, q, ties) + rows = _rows(cached, q, segmented) + qo = torch.tensor([r[1] for r in rows], dtype=torch.int32) + kv = torch.tensor([r[2] for r in rows], dtype=torch.int32) + kv_idx = torch.cat([pages[: math.ceil(r[2] / PAGE)] for r in rows]) + plan = fmha.fmha_sm100_plan( + qo, + kv, + HEADS, + num_kv_heads=1, + qo_offset=kv - qo, + page_size=PAGE, + output_maxscore=True, + causal=True, + num_kv_splits=splits, + ) + + def proxy(max_score): + _, scores = fmha.fmha_sm100( + idx_q, + idx_k, + idx_k, + plan, + kv_indices=kv_idx, + output_o=False, + output_maxscore=True, + max_score=max_score, + sm_scale=DIM**-0.5, + ) + return scores + + filled = proxy(None) + buffer = msa_indexer._unfilled_max_score(plan, idx_q) + assert buffer is not None and buffer.shape == filled.shape + buffer.view(torch.int32).fill_(SENTINEL) + unfilled = proxy(buffer) + + n_valid = _n_valid(rows, q) + read = ( + torch.arange(filled.shape[1], device="cuda")[None, :, None] < n_valid[None, None, :] + ).expand(HEADS, -1, -1) + got = unfilled[:HEADS].view(torch.int32) + want = filled[:HEADS].view(torch.int32) + assert int(((got == SENTINEL) & read).sum()) == 0 + assert torch.equal(got[read], want[read]) + assert torch.equal(_select(unfilled, n_valid), _select(filled, n_valid)) diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_sparse_attn_decode.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_sparse_attn_decode.py index 07376d86d2d7..e4b8cf20374b 100644 --- a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_sparse_attn_decode.py +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_sparse_attn_decode.py @@ -1330,6 +1330,8 @@ def test_msa_jit_cache_tracks_sources_and_build_modes( build_script.write_text("compiler_flags = '-std=c++20'\n") monkeypatch.setattr(jit, "_PACKAGE_DIR", package) monkeypatch.setattr(jit, "_FMHA_VARLEN_DIR", csrc) + # Pin the SM107 default proxy modes; other devices add the kill knobs' directory suffix. + monkeypatch.setattr(jit, "_proxy_modes", lambda: (False, False)) for name in ("GPU_TRACE", "SM_TIMING", "FMHA_GMEM_CHECK"): monkeypatch.delenv(name, raising=False) cache_root = tmp_path / "cache" diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py new file mode 100644 index 000000000000..1a2dc6bb1032 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py @@ -0,0 +1,206 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 SM107 prefill tile select: same top-16 tables as minimax_m3_select_blocks, and its gate.""" + +import os +import subprocess +import sys + +import pytest +import torch + +import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import msa_indexer +from tensorrt_llm._utils import get_sm_version + +PAGE = 128 + +sm107 = pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() != 107, reason="SM107 op" +) + + +def _causal_valid(cached: int, total_q: int, device) -> torch.Tensor: + pos = cached + torch.arange(total_q, device=device) + 1 + return ((pos + PAGE - 1) // PAGE).to(torch.int32) + + +def _stock(scores, n_valid, init_blocks, local_blocks): + return torch.ops.trtllm.minimax_m3_select_blocks( + scores, n_valid, 16, init_blocks, local_blocks, True + ) + + +def _tile(scores, n_valid, init_blocks, local_blocks): + heads, _, total_q = scores.shape + out = torch.empty((heads, total_q, 16), dtype=torch.int32, device=scores.device).permute( + 1, 0, 2 + ) + torch.ops.trtllm.minimax_m3_select_prefill_tile(scores, n_valid, out, init_blocks, local_blocks) + return out + + +def _assert_same(scores, n_valid, init_blocks=0, local_blocks=1): + expected = _stock(scores, n_valid, init_blocks, local_blocks) + actual = _tile(scores, n_valid, init_blocks, local_blocks) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +@sm107 +@pytest.mark.parametrize( + "num_blocks,total_q,cached", + [ + (1408, 2000, 165000), + (640, 8192, 65000), + (2688, 512, 330000), + (1408, 1003, 160000), + (129, 300, 0), + (17, 24, 0), + (2688, 4096, 327680), + (4864, 1024, 606208), + (4864, 1001, 606000), + ], +) +def test_tile_select_matches_stock_random_causal(num_blocks, total_q, cached): + g = torch.Generator(device="cuda").manual_seed(num_blocks * 7 + total_q) + scores = torch.randn(4, num_blocks, total_q, device="cuda", generator=g) + n_valid = _causal_valid(cached, total_q, "cuda").clamp(max=num_blocks + 3) + _assert_same(scores, n_valid) + + +@sm107 +@pytest.mark.parametrize("init_blocks,local_blocks", [(0, 1), (2, 3), (0, 0)]) +def test_tile_select_matches_stock_mixed_valid_and_forcing(init_blocks, local_blocks): + g = torch.Generator(device="cuda").manual_seed(11) + scores = torch.randn(4, 1408, 512, device="cuda", generator=g) + n_valid = torch.randint(0, 1500, (512,), device="cuda", generator=g, dtype=torch.int32) + n_valid[:8] = torch.tensor( + [0, 1, 15, 16, 17, 1408, 1409, 5000], device="cuda", dtype=torch.int32 + ) + _assert_same(scores, n_valid, init_blocks, local_blocks) + + +@sm107 +@pytest.mark.parametrize("distinct", [3, 40]) +def test_tile_select_matches_stock_ties(distinct): + # Three distinct values put hundreds of candidates at the bound: the radix fallback. + g = torch.Generator(device="cuda").manual_seed(distinct) + scores = torch.randint(0, distinct, (4, 1408, 256), device="cuda", generator=g).float() + _assert_same(scores, _causal_valid(165000, 256, "cuda")) + + +@sm107 +def test_tile_select_matches_stock_nonfinite(): + # +inf, -inf, +NaN, +0 and -0. A negative NaN is left out: the contract ranks it below -inf, the in-tree + # selector's fp16 first pass does not, and the proxy max-scores never produce one. + g = torch.Generator(device="cuda").manual_seed(5) + scores = torch.randn(4, 1408, 256, device="cuda", generator=g) + m = torch.rand(scores.shape, device="cuda", generator=g) + scores[m < 0.002] = float("inf") + scores[(m >= 0.002) & (m < 0.004)] = float("nan") + scores[(m >= 0.004) & (m < 0.5)] = float("-inf") + scores[(m >= 0.5) & (m < 0.51)] = -0.0 + scores[(m >= 0.51) & (m < 0.52)] = 0.0 + _assert_same(scores, _causal_valid(165000, 256, "cuda")) + _assert_same( + torch.full((4, 200, 256), float("-inf"), device="cuda"), + torch.arange(256, device="cuda", dtype=torch.int32) % 200, + ) + + +@sm107 +def test_tile_select_strided_blocks_and_dispatch(): + g = torch.Generator(device="cuda").manual_seed(3) + full = torch.randn(4, 1408, 1024, device="cuda", generator=g) + scores = full[:, :, :700] # unit query stride, block stride 1024 + n_valid = _causal_valid(165000, 700, "cuda") + _assert_same(scores, n_valid) + table = msa_indexer._tile_select(scores, n_valid, 0, 1) + torch.testing.assert_close(table, _stock(scores, n_valid, 0, 1), rtol=0, atol=0) + assert table.permute(1, 0, 2).is_contiguous() + + +@sm107 +def test_tile_select_unaligned_base_and_strides(): + g = torch.Generator(device="cuda").manual_seed(4) + full = torch.randn(4, 1408, 1024, device="cuda", generator=g) + # A base one query in: 16-byte loads would be misaligned, so the rows are read one float at a time. + _assert_same(full[:, :, 1:701], _causal_valid(165000, 700, "cuda"), 2, 3) + # Odd block stride. + odd = torch.randn(4, 1408, 1027, device="cuda", generator=g)[:, :, :1024] + _assert_same(odd, _causal_valid(165000, 1024, "cuda"), 1, 2) + + +@sm107 +@pytest.mark.parametrize("distinct", [3, 40]) +@pytest.mark.parametrize("init_blocks,local_blocks", [(0, 1), (2, 1), (1, 2)]) +def test_tile_select_wide_tiles_ties_and_forcing(distinct, init_blocks, local_blocks): + # 4864 blocks: the tile is staged by the wide launch; heavy ties exercise the bound, the candidate cap and the + # radix fallback, with forced init / local blocks. + g = torch.Generator(device="cuda").manual_seed(distinct * 13 + init_blocks) + scores = torch.randint(0, distinct, (1, 4864, 512), device="cuda", generator=g).float() + _assert_same(scores, _causal_valid(606208, 512, "cuda"), init_blocks, local_blocks) + + +@sm107 +@pytest.mark.parametrize("num_blocks,cached", [(1408, 165000), (4864, 606208)]) +def test_tile_select_graph_replay_matches_eager(num_blocks, cached): + g = torch.Generator(device="cuda").manual_seed(num_blocks) + scores = torch.randn(1, num_blocks, 1024, device="cuda", generator=g) + n_valid = _causal_valid(cached, 1024, "cuda") + eager = _tile(scores, n_valid, 0, 1) + out = torch.full_like(eager, -7) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + torch.ops.trtllm.minimax_m3_select_prefill_tile(scores, n_valid, out, 0, 1) + out.fill_(-7) + graph.replay() + torch.cuda.synchronize() + assert torch.equal(out, eager) + + +_KILL_SNIPPET = """ +import sys, torch +import tensorrt_llm +g = torch.Generator(device="cuda").manual_seed(29) +scores = torch.randint(0, 40, (1, 4864, 512), device="cuda", generator=g).float() +pos = 606208 + torch.arange(512, device="cuda") + 1 +n_valid = ((pos + 127) // 128).to(torch.int32) +out = torch.empty((1, 512, 16), dtype=torch.int32, device="cuda").permute(1, 0, 2) +torch.ops.trtllm.minimax_m3_select_prefill_tile(scores, n_valid, out, 1, 2) +torch.save(out.cpu(), sys.argv[1]) +""" + + +@sm107 +def test_tile_select_v2_kill_switch_same_tables(tmp_path): + tables = {} + # The v2 launch is the default; TRTLLM_M3_SELECT_TILE_V2=0 opts in to the v4 launch. + for name, env in ( + ("v3", {"TRTLLM_M3_SELECT_TILE_V2": "0"}), + ("v2", {"TRTLLM_M3_SELECT_TILE_V2": "1"}), + ): + path = tmp_path / f"{name}.pt" + subprocess.run( + [sys.executable, "-c", _KILL_SNIPPET, str(path)], + env={**os.environ, **env}, + check=True, + ) + tables[name] = torch.load(path) + assert torch.equal(tables["v2"], tables["v3"]) + + +@pytest.mark.parametrize( + "sm_version,enabled,total_q,num_blocks", + [ + (103, True, 2000, 1408), + (107, False, 2000, 1408), + (107, True, 64, 1408), + (107, True, 2000, 6000), + ], +) +def test_tile_select_gate(monkeypatch, sm_version, enabled, total_q, num_blocks): + monkeypatch.setattr(msa_indexer, "get_sm_version", lambda: sm_version) + monkeypatch.setattr(msa_indexer, "_SM107_TILE_SELECT", enabled) + scores = torch.zeros(4, num_blocks, total_q) + assert msa_indexer._tile_select(scores, torch.ones(total_q, dtype=torch.int32), 0, 1) is None diff --git a/tests/unittest/_torch/attention/sparse/msa/test_msa_backend.py b/tests/unittest/_torch/attention/sparse/msa/test_msa_backend.py index 8e23a16240a1..e8eada42fa22 100644 --- a/tests/unittest/_torch/attention/sparse/msa/test_msa_backend.py +++ b/tests/unittest/_torch/attention/sparse/msa/test_msa_backend.py @@ -18,16 +18,21 @@ import pytest import torch +from tensorrt_llm._torch.attention.backends.fmha import msa_prefill from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import ( MiniMaxM3KVCacheManagerV2, MiniMaxM3MsaSparseAttention, ) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import ( + msa_backend as msa_backend_module, +) from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.msa_scatter import ( fused_write_layer_caches, fused_write_layer_caches_nvfp4, ) from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.msa_utils import ( MSA_REQUIRED_TOPK, + build_kv_page_indices, msa_paged_kv, ) from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.paged_cache import ( @@ -39,6 +44,9 @@ from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.msa_backend import ( MiniMaxM3MsaSparseAttentionMetadata, MsaDecodeSpan, + gather_page_ranges, + proxy_segment_page_ranges, + proxy_segment_rows, ) from tensorrt_llm._torch.attention.backends.sparse.registry import _resolve_minimax_m3_backend_cls from tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2 import KVCacheManagerV2 @@ -1459,6 +1467,9 @@ def test_nvfp4_step_plans_skip_the_sparse_attention_plan(monkeypatch, dtype): """NVFP4 sparse layers run the CSR kernel, so only FP8 caches plan sparse GQA.""" from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import msa_backend + # The dense layers plan fmha_sm100 here; with FA4 dense prefill (SM107) they plan nothing. + monkeypatch.setattr(msa_prefill, "dense_prefill_fa4_enabled", lambda *_: False) + planned = [] def fmha_sm100_plan(qo_lens, kv_lens, **kwargs): @@ -2424,3 +2435,48 @@ def test_nvfp4_scatter_writes_physical_p32_data_and_scale_layouts(): for backing in (k_backing, v_backing, ksf_backing, vsf_backing): assert torch.count_nonzero(backing[0]).item() == 0 assert torch.count_nonzero(backing[-1]).item() == 0 + + +@pytest.mark.parametrize( + "sm_version,enabled,expected", + [(107, True, True), (107, False, False), (103, True, False), (100, True, False)], +) +def test_proxy_segmented_only_on_sm107(monkeypatch, sm_version, enabled, expected): + """The segmented, split indexer proxy runs on SM107 only, behind its constant.""" + monkeypatch.setattr(msa_backend_module, "get_sm_version", lambda: sm_version) + monkeypatch.setattr(msa_backend_module, "_SM107_PROXY_AUTO_KV_SPLITS", enabled) + assert msa_backend_module._proxy_segmented() is expected + + +def test_proxy_segment_rows_keep_each_tokens_causal_range(): + """Segments tile each request's query tokens in order and keep every token's key range.""" + # A 300-token chunk over 1000 cached tokens, an empty row, and a 5-token chunk. + qo = torch.tensor([300, 0, 5], dtype=torch.int32) + kv = torch.tensor([1300, 40, 85], dtype=torch.int32) + off = kv - qo + seg_qo, seg_kv, seg_off, seg_src = proxy_segment_rows(qo, kv, off, 128) + assert seg_qo.tolist() == [128, 128, 44, 5] + assert seg_kv.tolist() == [1128, 1256, 1300, 85] + assert seg_off.tolist() == [1000, 1128, 1256, 80] + assert seg_src.tolist() == [0, 0, 0, 2] + assert seg_qo.dtype == seg_kv.dtype == seg_off.dtype == torch.int32 + # Each segment sees exactly its own tokens beyond its offset (causal key range kept). + assert (seg_kv - seg_off).tolist() == seg_qo.tolist() + assert int(seg_qo.sum()) == int(qo.sum()) + + +def test_proxy_segment_page_table_matches_per_segment_build(): + """The device-gathered segmented page table equals a per-segment host build.""" + page = 128 + qo = torch.tensor([300, 0, 5, 130], dtype=torch.int32) + kv = torch.tensor([1300, 40, 85, 600], dtype=torch.int32) + seg_qo, seg_kv, seg_off, seg_src = proxy_segment_rows(qo, kv, kv - qo, page) + block_ids = torch.randperm(4 * 16, dtype=torch.int32).view(4, 16) + flat = build_kv_page_indices(block_ids, kv, page) + expected = build_kv_page_indices(block_ids.index_select(0, seg_src), seg_kv, page) + starts, counts = proxy_segment_page_ranges(kv, seg_kv, seg_src, page) + total = int(counts.sum()) + out = torch.full((total + 7,), -1, dtype=flat.dtype) + gather_page_ranges(flat, starts, counts, total, out) + assert torch.equal(out[:total], expected) + assert (out[total:] == -1).all() diff --git a/tests/unittest/_torch/attention/sparse/msa/test_msa_k2q_ws_stream.py b/tests/unittest/_torch/attention/sparse/msa/test_msa_k2q_ws_stream.py new file mode 100644 index 000000000000..82b825c9d047 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_msa_k2q_ws_stream.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The k2q CSR build's reused buffers belong to one CUDA stream (TRTLLM_MSA_K2Q_WS): any other stream takes the +stock builder, so a build there cannot overwrite buffers an attention on the first stream still reads.""" + +import sys +from types import SimpleNamespace + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.fmha import msa_prefill + + +class _BuilderTaken(Exception): + """Raised where the reused-buffer build starts, so a test sees that it was taken.""" + + +class _Utils: + @property + def _K2Q_CSR_BUILDER(self): + raise _BuilderTaken + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "sm, current, owner, taken", + [(107, 7, 7, True), (107, 8, 7, False), (107, 8, None, True), (100, 8, None, False)], +) +def test_the_reused_buffers_serve_one_stream(monkeypatch, sm, current, owner, taken) -> None: + # SM107 only: other GPUs keep the stock builder. + monkeypatch.setattr(msa_prefill, "get_sm_version", lambda: sm) + monkeypatch.setattr(msa_prefill, "_K2Q_WS", True) + monkeypatch.setattr(msa_prefill, "_k2q_ws_stream", owner) + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + monkeypatch.setattr( + torch.cuda, "current_stream", lambda device=None: SimpleNamespace(cuda_stream=current) + ) + monkeypatch.setitem(sys.modules, "sparse_index_utils", _Utils()) + monkeypatch.setitem(sys.modules, "src.sm100.prepare_scheduler", SimpleNamespace()) + kv_block_indexes = torch.zeros((4, 2, 8), dtype=torch.int32) + cu = torch.zeros(2, dtype=torch.int32) + kwargs = dict(max_seqlen_k=512, max_seqlen_q=4, total_rows=16, qhead_per_kv=8) + try: + got = msa_prefill._k2q_csr_ws(kv_block_indexes, cu, cu, 128, **kwargs) + except _BuilderTaken: + got = "taken" + assert (got == "taken") if taken else got is None diff --git a/tests/unittest/_torch/attention/sparse/msa/test_msa_per_token_valid_blocks_numpy.py b/tests/unittest/_torch/attention/sparse/msa/test_msa_per_token_valid_blocks_numpy.py new file mode 100644 index 000000000000..effde183a724 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_msa_per_token_valid_blocks_numpy.py @@ -0,0 +1,76 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""per_token_valid_blocks: the NumPy pass returns the torch path's values bit for bit (TRTLLM_MSA_PTVB_NUMPY).""" + +import random + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels import msa_utils + + +def _both(monkeypatch, *args, **kwargs): + # The NumPy pass is SM107-only: these CPU checks pose as SM107 to compare the two paths. + monkeypatch.setattr(msa_utils, "get_sm_version", lambda: 107) + monkeypatch.setattr(msa_utils, "_PER_TOKEN_VALID_BLOCKS_NUMPY", False) + ref = msa_utils.per_token_valid_blocks(*args, **kwargs) + monkeypatch.setattr(msa_utils, "_PER_TOKEN_VALID_BLOCKS_NUMPY", True) + got = msa_utils.per_token_valid_blocks(*args, **kwargs) + return ref, got + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("dtype", [torch.int32, torch.int64]) +@pytest.mark.parametrize("causal", [True, False]) +@pytest.mark.parametrize("block_size", [64, 128]) +def test_numpy_pass_matches_torch_on_random_batches(monkeypatch, dtype, causal, block_size): + rng = random.Random(f"{dtype}-{causal}-{block_size}") + for _ in range(300): + batch = rng.randint(1, 64) + qo = [rng.choice([0, 1, 4, rng.randint(1, 4096)]) for _ in range(batch)] + kv = [q + rng.randint(0, 300_000) for q in qo] + offset = ( + None + if rng.random() < 0.3 + else torch.tensor([k - q for q, k in zip(qo, kv)], dtype=dtype) + ) + ref, got = _both( + monkeypatch, + torch.tensor(qo, dtype=dtype), + torch.tensor(kv, dtype=dtype), + offset, + causal=causal, + block_size=block_size, + ) + assert got.dtype == torch.long + assert torch.equal(ref, got), (qo, kv, offset) + + +@pytest.mark.cpu_only +def test_numpy_pass_takes_strided_inputs_and_empty_batches(monkeypatch): + qo = torch.arange(1, 41, dtype=torch.int32)[::2] + ref, got = _both(monkeypatch, qo, qo * 1000, None, causal=True, block_size=128) + assert torch.equal(ref, got) + zeros = torch.zeros(3, dtype=torch.int32) + ref, got = _both(monkeypatch, zeros, zeros + 5, None, causal=True, block_size=128) + assert ref.numel() == got.numel() == 0 and got.dtype == torch.long + + +@pytest.mark.cpu_only +def test_kill_env_name_unchanged(): + import inspect + + assert '"TRTLLM_MSA_PTVB_NUMPY", "1"' in inspect.getsource(msa_utils) diff --git a/tests/unittest/_torch/attention/sparse/msa/test_msa_prefill_nvfp4_out_in_place.py b/tests/unittest/_torch/attention/sparse/msa/test_msa_prefill_nvfp4_out_in_place.py new file mode 100644 index 000000000000..4b95916d63dd --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_msa_prefill_nvfp4_out_in_place.py @@ -0,0 +1,56 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate of the SM107 in-place output of the MiniMax-M3 NVFP4 sparse prefill (msa_prefill).""" + +import types + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.fmha import msa_prefill + + +def _sparse(takes_out: bool): + if takes_out: + + def fn(q, *, schedule=None, out=None): + return out + + else: + + def fn(q, *, schedule=None): + return q + + return types.SimpleNamespace(sparse_atten_nvfp4_kv_func=fn) + + +@pytest.fixture(autouse=True) +def _fresh_signature_cache(): + msa_prefill._nvfp4_sparse_takes_out.__dict__.pop("_cached", None) + yield + msa_prefill._nvfp4_sparse_takes_out.__dict__.pop("_cached", None) + + +@pytest.mark.parametrize( + "sm_version,enabled,takes_out,dtype,contiguous,expected", + [ + (107, True, True, torch.bfloat16, True, True), + (103, True, True, torch.bfloat16, True, False), + (107, False, True, torch.bfloat16, True, False), + (107, True, False, torch.bfloat16, True, False), + (107, True, True, torch.float16, True, False), + (107, True, True, torch.bfloat16, False, False), + ], +) +def test_out_in_place_gate( + monkeypatch, sm_version, enabled, takes_out, dtype, contiguous, expected +): + monkeypatch.setattr(msa_prefill, "get_sm_version", lambda: sm_version) + monkeypatch.setattr(msa_prefill, "_SM107_NVFP4_SPARSE_OUT_IN_PLACE", enabled) + out = torch.zeros(8, 4, 16, dtype=dtype) + if not contiguous: + out = torch.zeros(4, 8, 16, dtype=dtype).transpose(0, 1) + kwargs = msa_prefill._nvfp4_sparse_out_kwargs(_sparse(takes_out), out) + assert ("out" in kwargs) is expected + if expected: + assert kwargs["out"] is out diff --git a/tests/unittest/_torch/attention/sparse/msa/test_msa_proxy_few_rows_kv_splits.py b/tests/unittest/_torch/attention/sparse/msa/test_msa_proxy_few_rows_kv_splits.py new file mode 100644 index 000000000000..4574d23d96e5 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_msa_proxy_few_rows_kv_splits.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate of the SM107 few-row KV split count of the MiniMax-M3 indexer proxy plan.""" + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import msa_backend + + +@pytest.fixture(autouse=True) +def _sm_count(monkeypatch): + monkeypatch.setattr(msa_backend, "_sm_count", lambda device_index: 212) + + +@pytest.mark.parametrize( + "sm_version,enabled,num_rows,expected", + [ + (107, True, 1, 212), + (107, True, 2, 106), + (107, True, 4, 53), + (107, True, 5, -1), + (107, True, 128, -1), + (103, True, 1, -1), + (107, False, 1, -1), + ], +) +def test_proxy_kv_splits(monkeypatch, sm_version, enabled, num_rows, expected): + monkeypatch.setattr(msa_backend, "get_sm_version", lambda: sm_version) + monkeypatch.setattr(msa_backend, "_SM107_PROXY_FEW_ROWS_KV_SPLITS", enabled) + assert msa_backend.proxy_kv_splits(num_rows, torch.device("cuda", 0)) == expected diff --git a/tests/unittest/_torch/attention/test_drafter_kv_tail_zero.py b/tests/unittest/_torch/attention/test_drafter_kv_tail_zero.py new file mode 100644 index 000000000000..97410cef3ae3 --- /dev/null +++ b/tests/unittest/_torch/attention/test_drafter_kv_tail_zero.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate of the drafter last-row context FMHA's K/V tail zeroing (drafter_last_row._zero_kv_tails).""" + +import types + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.fmha import drafter_last_row + +PAGE, HEADS, D = 128, 4, 128 + + +def _pool_and_tables(kv_lens, seed=0): + """A flat FP8 sub-block pool filled with NaN-coded and random bytes, and a shuffled [batch, 2, pages] table.""" + g = torch.Generator(device="cuda").manual_seed(seed) + pages = [(n + PAGE - 1) // PAGE for n in kv_lens] + num_blocks = 2 * sum(pages) + 6 + raw = torch.randint( + 0, 256, (num_blocks, HEADS, PAGE, D), dtype=torch.uint8, device="cuda", generator=g + ) + raw[::3] = 0x7F + perm = torch.randperm(num_blocks, device="cuda", generator=g) + tables = torch.zeros(len(kv_lens), 2, max(pages), dtype=torch.int32, device="cuda") + used = 0 + for b, n in enumerate(pages): + tables[b, 0, :n] = perm[used : used + n] + tables[b, 1, :n] = perm[used + n : used + 2 * n] + used += 2 * n + return raw.view(torch.float8_e4m3fn), tables + + +@pytest.mark.parametrize( + "kv_lens", + [[16390], [16], [32, 128, 129], [1, 255, 256, 257], [16384, 6]], +) +def test_only_the_partial_last_pages_tails_are_zeroed(kv_lens): + pool, tables = _pool_and_tables(kv_lens) + before = pool.view(torch.uint8).clone() + lens = torch.tensor(kv_lens, dtype=torch.int32, device="cuda") + drafter_last_row._zero_kv_tails(pool, tables, lens, len(kv_lens)) + after = pool.view(torch.uint8) + + expected = before.clone() + for b, n in enumerate(kv_lens): + if n % PAGE: + for half in (0, 1): + expected[int(tables[b, half, (n - 1) // PAGE]), :, n % PAGE :, :] = 0 + assert torch.equal(after, expected) + for b, n in enumerate(kv_lens): + if n % PAGE: + for half in (0, 1): + tail = after[int(tables[b, half, (n - 1) // PAGE]), :, n % PAGE :, :] + assert int(((tail & 0x7F) == 0x7F).sum()) == 0 + + +def test_rows_past_batch_are_untouched(): + pool, tables = _pool_and_tables([100, 200]) + before = pool.view(torch.uint8).clone() + lens = torch.tensor([100, 200], dtype=torch.int32, device="cuda") + drafter_last_row._zero_kv_tails(pool, tables, lens, 1) + after = pool.view(torch.uint8) + second = [int(tables[1, h, 1]) for h in (0, 1)] + for blk in second: + assert torch.equal(after[blk], before[blk]) + + +@pytest.mark.parametrize( + "manager,safe", + [ + (types.SimpleNamespace(enable_block_reuse=False, enable_partial_reuse=True), True), + (types.SimpleNamespace(enable_block_reuse=True, enable_partial_reuse=False), True), + (types.SimpleNamespace(enable_block_reuse=True, enable_partial_reuse=True), False), + ( + types.SimpleNamespace( + enable_block_reuse=True, enable_partial_reuse=True, copy_on_partial_reuse=True + ), + True, + ), + ], +) +def test_tail_zeroing_needs_private_partial_pages(manager, safe): + assert drafter_last_row._v_tail_zero_safe(manager) is safe + + +def _library(monkeypatch, enabled=True): + monkeypatch.setattr(drafter_last_row, "_KV_TAIL_ZERO", enabled) + lib = drafter_last_row.DrafterLastRowContextFmha.__new__( + drafter_last_row.DrafterLastRowContextFmha + ) + lib._kv_tail_safe = None + return lib + + +def _zero_if_allowed(lib, manager, pool, tables, lens): + """The attention path's own gate: zero the tails only when the library allows it for this KV cache.""" + if lib._kv_tail_zero(types.SimpleNamespace(kv_cache_manager=manager)): + drafter_last_row._zero_kv_tails(pool, tables, lens, lens.shape[0]) + + +def test_a_shared_partial_page_declines_and_changes_no_byte(monkeypatch): + # Block and partial reuse on, no copy on partial reuse: the partial last page may belong to another request. + shared = types.SimpleNamespace(enable_block_reuse=True, enable_partial_reuse=True) + lib = _library(monkeypatch) + pool, tables = _pool_and_tables([16390, 16]) + before = pool.view(torch.uint8).clone() + lens = torch.tensor([16390, 16], dtype=torch.int32, device="cuda") + _zero_if_allowed(lib, shared, pool, tables, lens) + assert lib._kv_tail_safe is False + assert torch.equal(pool.view(torch.uint8), before) + + +def test_the_kill_switch_changes_no_byte(monkeypatch): + private = types.SimpleNamespace(enable_block_reuse=False, enable_partial_reuse=False) + lib = _library(monkeypatch, enabled=False) + pool, tables = _pool_and_tables([16390]) + before = pool.view(torch.uint8).clone() + _zero_if_allowed( + lib, private, pool, tables, torch.tensor([16390], dtype=torch.int32, device="cuda") + ) + assert torch.equal(pool.view(torch.uint8), before) + + +def test_a_private_cache_zeroes_through_the_gate(monkeypatch): + private = types.SimpleNamespace(enable_block_reuse=False, enable_partial_reuse=False) + lib = _library(monkeypatch) + pool, tables = _pool_and_tables([16390]) + _zero_if_allowed( + lib, private, pool, tables, torch.tensor([16390], dtype=torch.int32, device="cuda") + ) + for half in (0, 1): + assert ( + int( + pool.view(torch.uint8)[ + int(tables[0, half, 16389 // PAGE]), :, 16390 % PAGE : + ].count_nonzero() + ) + == 0 + ) diff --git a/tests/unittest/_torch/kernels/parallel/test_mxfp8_mxfp8_gemm.py b/tests/unittest/_torch/kernels/parallel/test_mxfp8_mxfp8_gemm.py index 13b2e935d4c0..ad36ceba50df 100644 --- a/tests/unittest/_torch/kernels/parallel/test_mxfp8_mxfp8_gemm.py +++ b/tests/unittest/_torch/kernels/parallel/test_mxfp8_mxfp8_gemm.py @@ -189,3 +189,52 @@ def test_mxfp8_native_tactic_cache_large_m_bucket_boundaries( assert runner.get_cached_tactic(upper_bound + 1, n, k) == -2 finally: runner.clear_tactic_cache() + + +@pytest.mark.skipif( + getSMVersion() != 107, + reason="MXFP8 small-M tuning buckets are SM107 only. Current SM is %d." % getSMVersion(), +) +def test_mxfp8_native_tactic_cache_sm107_small_m_buckets(): + """SM107 small-M buckets agree between C++ and Python and give warm-turn M values a tactic.""" + n, k = 10240, 6144 + runner = torch.classes.trtllm.MXFP8GemmRunner(torch.bfloat16) + buckets = tuple(runner.get_small_m_tuning_buckets()) + assert buckets == (8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 6552) + + try: + runner.clear_tactic_cache() + previous = 0 + for bucket in buckets: + runner.register_tactic(bucket, n, k, 3) + for m in (previous + 1, bucket): + assert _map_to_mxfp8_large_m_bucket(m) == bucket + assert runner.get_cached_tactic(m, n, k) == 3 + previous = bucket + assert _map_to_mxfp8_large_m_bucket(6553) == 8192 + assert runner.get_cached_tactic(6553, n, k) == -2 + finally: + runner.clear_tactic_cache() + + +@pytest.mark.skipif( + getSMVersion() != 107, + reason="MXFP8 small-M tuning buckets are SM107 only. Current SM is %d." % getSMVersion(), +) +@pytest.mark.parametrize("m", [6, 300, 2114, 6552]) +def test_mxfp8_mxfp8_sm107_tactics_bitwise_equal(m: int): + """Bucketing may pick any tactic for an M value, so every tactic must match the fallback bitwise.""" + torch.manual_seed(0) + n, k = 6144, 8192 + mat_a = torch.randn((m, k), device="cuda", dtype=torch.bfloat16) + mat_a[0] *= 3e3 + mat_a[min(1, m - 1)] = 0 + mat_b = torch.randn((n, k), device="cuda", dtype=torch.bfloat16) * 0.02 + fp8_a, a_block_sf = torch.ops.trtllm.mxfp8_quantize(mat_a, True) + fp8_b, b_block_sf = torch.ops.trtllm.mxfp8_quantize(mat_b, True) + global_scale = torch.ones((1,), device="cuda", dtype=torch.float32) + runner = torch.classes.trtllm.MXFP8GemmRunner(torch.bfloat16) + reference = runner.run_gemm(fp8_a, a_block_sf, fp8_b, b_block_sf, global_scale, -1) + for tactic in range(runner.get_num_configs()): + output = runner.run_gemm(fp8_a, a_block_sf, fp8_b, b_block_sf, global_scale, tactic) + torch.testing.assert_close(output, reference, rtol=0, atol=0) diff --git a/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py b/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py new file mode 100644 index 000000000000..de6346cee5f1 --- /dev/null +++ b/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py @@ -0,0 +1,456 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate for the SM107 CLC MXFP8 GEMM used for MiniMax-M3 CTX prefill GEMMs. + +The GEMM-only handle of the fused QKV kernel (``m3_qkv_fusion.plain_gemm``) +replaces CUTLASS ``mxfp8_mxfp8_gemm`` in ``MXFP8LinearMethod.apply`` for the +o_proj / shared gate_up / dense gate_up / dense down shapes at >= 1024 rows. +Per shape and M the gate checks: 3-run determinism, CUDA-graph replay == +eager, bitwise equality with the fused kernel's own ``debug_gemm_out`` output +(same mainloop, real producer tensors), and the fp64 error band against +CUTLASS. The dispatch test runs a real MXFP8 ``Linear`` and checks the +engagement log, the pre-quantized activation slot, and that the kill switch +gives CUTLASS's bytes. + +Also runnable as a script:: + + python3 test_m3_ctx_clc_gemm.py [--shapes o_proj,...] [--m 16384,1500] [--timing 16384,8192] [--no-dispatch] + +``M3QKV_PKG`` may name a directory holding an ``m3_qkv_fusion`` package to +gate instead of the in-tree one (kernel-level checks; the dispatch test and +the custom-op timings always use the importable ``tensorrt_llm``). +""" + +import argparse +import importlib +import os +import sys +import time + +import pytest +import torch + +# tensorrt_llm is imported inside the functions that need it, so that _pkg() first sets +# CUTE_DSL_ARCH (read by the CuTe DSL when it is imported) and puts any M3QKV_PKG on sys.path. + +HEAD_DIM = 128 +HEADS_KV, HEADS_INDEX = 2, 2 +# name -> (N, K, heads per tile below WIDE_ROWS rows, at or above it) +SHAPES = { + "o_proj": (6144, 4096, 2, 2), + "shared_gate_up": (3072, 6144, 2, 4), + "dense_gate_up": (12288, 6144, 2, 4), + "dense_down": (6144, 6144, 2, 4), +} +WIDE_ROWS = 12288 +MIN_ROWS = 1024 +M_LIST = (16384, 8192, 4096, 1024, 1500) + + +def _is_sm107(): + return torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 7) + + +pytestmark = pytest.mark.skipif(not _is_sm107(), reason="SM107 (Rubin) required") + + +def _pkg(): + """(kernel module, plain_gemm module), from M3QKV_PKG when set.""" + os.environ.setdefault("CUTE_DSL_ARCH", "sm_107a") + pkg = os.environ.get("M3QKV_PKG") + if pkg: + if pkg not in sys.path: + sys.path.insert(0, pkg) + base = "m3_qkv_fusion" + else: + base = "tensorrt_llm._torch.kernels.rubin.m3_qkv_fusion" + return importlib.import_module(base + ".kernel"), importlib.import_module(base + ".plain_gemm") + + +def _dispatch_module(): + """The in-model dispatcher (registers trtllm::m3_ctx_clc_mxfp8_gemm), or None if this tensorrt_llm lacks it.""" + try: + return importlib.import_module("tensorrt_llm._torch.modules.m3_ctx_clc_gemm") + except ImportError: + return None + + +def hpt_for(name, m): + _, _, narrow, wide = SHAPES[name] + return wide if m >= WIDE_ROWS else narrow + + +def _bits(t): + return t.view(torch.int16) + + +class Problem: + def __init__(self, n, k, m, seed=0): + import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) + + g = torch.Generator(device="cuda").manual_seed(seed) + self.n, self.k, self.m = n, k, m + x = torch.randn(m, k, device="cuda", generator=g, dtype=torch.bfloat16) + w = (torch.randn(n, k, device="cuda", generator=g) * 0.02).to(torch.bfloat16) + self.act, self.act_sf = torch.ops.trtllm.mxfp8_quantize(x, True) + self.act_lin_sf = torch.ops.trtllm.mxfp8_quantize(x, False)[1] + # Weight scales in the layout MXFP8LinearMethod stores: block_scale_interleave of the [N, K/32] scales. + self.weight, self.weight_lin_sf = torch.ops.trtllm.mxfp8_quantize(w, False) + self.weight_sf = torch.ops.trtllm.block_scale_interleave( + self.weight_lin_sf.view(torch.uint8).reshape(n, k // 32) + ).reshape(-1) + self.weight_quant_sf = torch.ops.trtllm.mxfp8_quantize(w, True)[1] + self.alpha = torch.ones(1, dtype=torch.float32, device="cuda") + + def cutlass(self): + return torch.ops.trtllm.mxfp8_mxfp8_gemm( + self.act, self.act_sf, self.weight, self.weight_sf, self.alpha, torch.bfloat16 + ) + + def fp64_err(self, out, rows_per_chunk=4096): + """(max, mean) |out - fp64 dequant reference|, in row chunks.""" + + def deq(v, sf_lin, r0, r1): + sf = sf_lin.view(torch.uint8).reshape(-1)[: v.shape[0] * (self.k // 32)] + sf = sf.reshape(v.shape[0], self.k // 32)[r0:r1] + scale = torch.exp2(sf.to(torch.float64) - 127.0) + vals = v[r0:r1].to(torch.float64).reshape(r1 - r0, self.k // 32, 32) + return (vals * scale[..., None]).reshape(r1 - r0, self.k) + + w64 = deq(self.weight, self.weight_lin_sf, 0, self.n) + e_max, e_sum = 0.0, 0.0 + for r0 in range(0, self.m, rows_per_chunk): + r1 = min(self.m, r0 + rows_per_chunk) + ref = deq(self.act, self.act_lin_sf, r0, r1) @ w64.T + e = (out[r0:r1].to(torch.float64) - ref).abs() + e_max = max(e_max, e.max().item()) + e_sum += e.sum().item() + return e_max, e_sum / (self.m * self.n) + + +def _debug_gemm_reference(kmod, prob, hpt): + """The fused kernel's debug_gemm_out output with real (small) producer tensors.""" + m, n = prob.m, prob.n + hq = n // HEAD_DIM - (2 * HEADS_KV + HEADS_INDEX + 1) + runner = kmod.M3QkvFusedRunner( + num_heads_q=hq, + num_heads_kv=HEADS_KV, + num_heads_index=HEADS_INDEX, + heads_per_tile=hpt, + debug_gemm_out=True, + ) + pages = (m + 127) // 128 + 2 + data = torch.zeros((pages, 2, HEADS_KV, 128, 64), dtype=torch.uint8, device="cuda") + scale = torch.zeros((pages, 2, HEADS_KV, 128, 8), dtype=torch.uint8, device="cuda") + index = torch.zeros((pages, 1, 128, 128), dtype=torch.uint8, device="cuda") + q = torch.zeros((m, hq, HEAD_DIM), dtype=torch.uint8, device="cuda") + iq = torch.zeros((m, HEADS_INDEX, HEAD_DIM), dtype=torch.uint8, device="cuda") + slots = torch.arange(m, dtype=torch.int32, device="cuda") + rope = torch.zeros((m + 8, 2, 32), dtype=torch.float32, device="cuda") + kvs = torch.tensor([1.0, 0.05, 0.03], dtype=torch.float32, device="cuda") + normw = torch.ones(4 * HEAD_DIM, dtype=torch.bfloat16, device="cuda") + g = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") + args = runner.make_args( + prob.act, + prob.act_sf, + prob.weight, + prob.weight_sf, + prob.alpha, + q.view(torch.float8_e4m3fn), + iq.view(torch.float8_e4m3fn), + data, + scale, + index.view(torch.float8_e4m3fn), + slots, + kvs, + rope, + slots, + normw, + 1e-6, + gemm_out=g, + ) + runner.run_args(args) + return g + + +def gate(name, m, log=print, hpt=None): + kmod, pg = _pkg() + n, k = SHAPES[name][:2] + hpt = hpt_for(name, m) if hpt is None else hpt + prob = Problem(n, k, m) + tag = f"GATE {name} N={n} K={k} M={m} hpt={hpt}" + layout_ok = torch.equal( + prob.weight_sf.view(torch.uint8).reshape(-1), + prob.weight_quant_sf.view(torch.uint8).reshape(-1), + ) + gemm = pg.get_gemm(n, hpt) + reason = gemm.check(prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha) + if reason: + log(f"{tag} INELIGIBLE: {reason}") + return False + + outs = [gemm(prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha) for _ in range(3)] + torch.cuda.synchronize() + det = all(torch.equal(_bits(outs[0]), _bits(o)) for o in outs[1:]) + + out = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") + args = gemm.make_args(prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha, out) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + gemm.run_args(args) # warm-up outside capture + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + gemm.run_args(args) + out.fill_(float("nan")) + graph.replay() + torch.cuda.synchronize() + graph_ok = torch.equal(_bits(out), _bits(outs[0])) + + dbg = _debug_gemm_reference(kmod, prob, hpt) + torch.cuda.synchronize() + dbg_ok = torch.equal(_bits(dbg), _bits(outs[0])) + + cut = prob.cutlass() + torch.cuda.synchronize() + same = (_bits(outs[0]) == _bits(cut)).float().mean().item() + c_max, c_mean = prob.fp64_err(outs[0]) + u_max, u_mean = prob.fp64_err(cut) + band_ok = c_max <= 1.5 * u_max and c_mean <= 1.1 * u_mean + finite = bool(torch.isfinite(outs[0].float()).all().item()) + log( + f"{tag} module_sf_layout==mxfp8_quantize(w,True)={'OK' if layout_ok else 'FAIL'} " + f"determinism(3)={'OK' if det else 'FAIL'} graph==eager={'OK' if graph_ok else 'FAIL'} " + f"==debug_gemm_out={'OK' if dbg_ok else 'FAIL'} finite={'OK' if finite else 'FAIL'}" + ) + log( + f"{tag} fp64 err clc max={c_max:.4e} mean={c_mean:.4e} | cutlass max={u_max:.4e} " + f"mean={u_mean:.4e} | bitwise==cutlass {same * 100:.4f}% | band={'OK' if band_ok else 'FAIL'}" + ) + return layout_ok and det and graph_ok and dbg_ok and band_ok and finite + + +def dispatch(log=print, name="o_proj"): + """MXFP8 Linear through the real loader: engagement, slot, threshold and kill switch.""" + mod = _dispatch_module() + if mod is None: + log("DISPATCH SKIP: tensorrt_llm._torch.modules.m3_ctx_clc_gemm not importable") + return True + from tensorrt_llm._torch.modules import linear as linear_module + from tensorrt_llm._torch.modules.linear import Linear, MXFP8LinearMethod + from tensorrt_llm.logger import logger as trt_logger + from tensorrt_llm.models.modeling_utils import QuantConfig + from tensorrt_llm.quantization.mode import QuantAlgo + + n, k = SHAPES[name][:2] + ok = all( + mod._CTX_CLC_GEMM_SHAPES.get((sn, sk)) == (a, b) for sn, sk, a, b in SHAPES.values() + ) and len(mod._CTX_CLC_GEMM_SHAPES) == len(SHAPES) + ok &= mod._CTX_CLC_GEMM_MIN_ROWS == MIN_ROWS and mod._CTX_CLC_GEMM_WIDE_ROWS == WIDE_ROWS + log(f"DISPATCH table matches gate shapes: {'OK' if ok else 'FAIL'}") + if not mod.ctx_clc_gemm_enabled(): + log(f"DISPATCH FAIL: not enabled (knob={mod._CTX_CLC_GEMM})") + return False + + g = torch.Generator(device="cuda").manual_seed(1) + w = (torch.randn(n, k, device="cuda", generator=g) * 0.02).to(torch.bfloat16) + w_e4m3, w_lin_sf = torch.ops.trtllm.mxfp8_quantize(w, False) + lin = Linear( + in_features=k, + out_features=n, + bias=False, + dtype=torch.bfloat16, + quant_config=QuantConfig(quant_algo=QuantAlgo.MXFP8, group_size=32), + ).cuda() + lin.load_weights( + [ + { + "weight": w_e4m3.cpu(), + "weight_scale_inv": w_lin_sf.view(torch.uint8).reshape(n, k // 32).cpu(), + } + ] + ) + assert isinstance(lin.quant_method, MXFP8LinearMethod) and lin.quant_method.use_cutlass + + def cutlass(act, act_sf): + return torch.ops.trtllm.mxfp8_mxfp8_gemm( + act, act_sf, lin.weight, lin.weight_scale, lin._mxfp8_alpha, torch.bfloat16 + ) + + # The in-model path always uses the importable package (not M3QKV_PKG). + pg = importlib.import_module("tensorrt_llm._torch.kernels.rubin.m3_qkv_fusion.plain_gemm") + for m in (2048, 1000): + hpt = hpt_for(name, m) + x = torch.randn(m, k, device="cuda", generator=g, dtype=torch.bfloat16) + act, act_sf = torch.ops.trtllm.mxfp8_quantize(x, True) + clc = pg.get_gemm(n, hpt)(act, act_sf, lin.weight, lin.weight_scale, lin._mxfp8_alpha) + ref_cut = cutlass(act, act_sf) + key = f"m3_ctx_clc_gemm_taken_{n}_{k}_{hpt}" + trt_logger._appeared_keys.discard(key) + got = lin(x) + engaged = key in trt_logger._appeared_keys + want = clc if m >= MIN_ROWS else ref_cut + res = torch.equal(_bits(got), _bits(want)) and engaged == (m >= MIN_ROWS) + log( + f"DISPATCH {name} M={m}: engaged={engaged} out=={'clc' if m >= MIN_ROWS else 'cutlass'} " + f"{'OK' if res else 'FAIL'}" + ) + ok &= res + + # The pre-quantized slot is consumed by the CLC path (same act / act_sf as CUTLASS would take). + linear_module.set_prequantized_mxfp8(x, act, act_sf) + got_slot = lin(x) + res = ( + torch.equal(_bits(got_slot), _bits(want)) + and linear_module._PREQUANTIZED_MXFP8[0] is None + ) + log(f"DISPATCH {name} M={m}: prequantized slot {'OK' if res else 'FAIL'}") + ok &= res + + # Kill switch: the unchanged CUTLASS call, bitwise. + saved = mod._CTX_CLC_GEMM, mod._platform_ok + mod._CTX_CLC_GEMM = False + try: + killed = lin(x) + finally: + mod._CTX_CLC_GEMM, mod._platform_ok = saved + res = torch.equal(_bits(killed), _bits(ref_cut)) + log(f"DISPATCH {name} M={m}: TRTLLM_CTX_CLC_GEMM=0 == cutlass {'OK' if res else 'FAIL'}") + ok &= res + + # The registered custom op (eager and compiled with a dynamic M) matches the direct call. + op_out = torch.ops.trtllm.m3_ctx_clc_mxfp8_gemm( + act, act_sf, lin.weight, lin.weight_scale, lin._mxfp8_alpha, hpt + ) + res = torch.equal(_bits(op_out), _bits(clc)) + if m == 2048: + compiled = torch.compile( + lambda a, s: torch.ops.trtllm.m3_ctx_clc_mxfp8_gemm( + a, s, lin.weight, lin.weight_scale, lin._mxfp8_alpha, hpt + ), + fullgraph=True, + dynamic=True, + ) + res &= torch.equal(_bits(compiled(act, act_sf)), _bits(clc)) + log( + f"DISPATCH {name} M={m}: custom op (eager{', compiled' if m == 2048 else ''}) {'OK' if res else 'FAIL'}" + ) + ok &= res + torch.cuda.synchronize() + return bool(ok) + + +def timing(name, m, log=print, reps=21, host_calls=100): + _, pg = _pkg() + from tensorrt_llm._torch.custom_ops.torch_custom_ops import MXFP8GemmRunner + + n, k = SHAPES[name][:2] + hpt = hpt_for(name, m) + prob = Problem(n, k, m) + flush = torch.empty(512 << 20, dtype=torch.uint8, device="cuda") + + def med(fn, cold=True): + fn() + torch.cuda.synchronize() + ts = [] + for _ in range(reps): + if cold: + flush.zero_() + e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + e0.record() + fn() + e1.record() + torch.cuda.synchronize() + ts.append(e0.elapsed_time(e1) * 1e3) + return sorted(ts)[reps // 2] + + def host(fn): + fn() + torch.cuda.synchronize() + t0 = time.perf_counter() + for _ in range(host_calls): + fn() + t1 = time.perf_counter() + torch.cuda.synchronize() + return (t1 - t0) * 1e6 / host_calls + + runner = MXFP8GemmRunner(torch.bfloat16) + inputs = [prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha] + best = None + for t in range(runner.mxfp8_gemm_runner.get_num_configs()): + try: + us = med(lambda t=t: runner(inputs=inputs, tactic=t)) + except Exception as exc: # noqa: BLE001 + log(f"TIME {name} M={m} cutlass tactic {t} failed: {type(exc).__name__}") + continue + if best is None or us < best[0]: + best = (us, t) + gemm = pg.get_gemm(n, hpt) + out = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") + args = gemm.make_args(prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha, out) + t_clc = med(lambda: gemm.run_args(args)) + t_clc_warm = med(lambda: gemm.run_args(args), cold=False) + log( + f"TIME {name} N={n} K={k} M={m} hpt={hpt}: cutlass_best t{best[1]}={best[0]:.1f} us | " + f"clc cold={t_clc:.1f} us warm={t_clc_warm:.1f} us | delta={best[0] - t_clc:+.1f} us " + f"({best[0] / t_clc:.3f}x)" + ) + + calls = { + "clc prebuilt args (run_args)": lambda: gemm.run_args(args), + "clc handle __call__ (check + make_args + run)": lambda: gemm( + prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha + ), + "cutlass mxfp8_mxfp8_gemm op": prob.cutlass, + } + mod = _dispatch_module() + if mod is not None: + calls["dispatcher try_ctx_clc_mxfp8_gemm (in-model path)"] = ( + lambda: mod.try_ctx_clc_mxfp8_gemm( + prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha, torch.bfloat16 + ) + ) + calls["custom op trtllm::m3_ctx_clc_mxfp8_gemm"] = ( + lambda: torch.ops.trtllm.m3_ctx_clc_mxfp8_gemm( + prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha, hpt + ) + ) + for label, fn in calls.items(): + log( + f"TIME {name} M={m} host/call {label}: {host(fn):.1f} us (wall of {host_calls} calls, no sync)" + ) + + +@pytest.mark.parametrize("m", M_LIST) +@pytest.mark.parametrize("name", list(SHAPES)) +def test_m3_ctx_clc_gemm_gate(name, m): + assert gate(name, m) + + +def test_m3_ctx_clc_gemm_dispatch(): + assert dispatch() + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--shapes", default=",".join(SHAPES)) + ap.add_argument("--m", default=",".join(str(v) for v in M_LIST)) + ap.add_argument("--hpt", type=int, default=None, help="override heads per tile in the gate") + ap.add_argument("--timing", default="", help="comma list of M for timing") + ap.add_argument("--no-gate", action="store_true") + ap.add_argument("--no-dispatch", action="store_true") + a = ap.parse_args() + names = [s for s in a.shapes.split(",") if s] + all_ok = True + plog = lambda s: print(s, flush=True) # noqa: E731 + if not a.no_gate: + for nm in names: + for mm in [int(v) for v in a.m.split(",") if v]: + all_ok &= gate(nm, mm, log=plog, hpt=a.hpt) + if not a.no_dispatch: + all_ok &= dispatch(log=plog) + for nm in names: + for mm in [int(v) for v in a.timing.split(",") if v]: + timing(nm, mm, log=plog) + print(f"GATE ALL {'PASS' if all_ok else 'FAIL'}", flush=True) diff --git a/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py b/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py new file mode 100644 index 000000000000..33de534fedfd --- /dev/null +++ b/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Numerics of the MiniMax-M3 CTX prefill's fused quantizers against the unfused ops they replace. + +- ``trtllm::minimax_m3_ctx_residual_rmsnorm_mxfp8``: the residual sum it writes back is the BF16 add of the two inputs; + its RMSNorm output is within a BF16 rounding of an fp64 reference (its row reduction order is the stock rows kernel's, + not torch's); its MXFP8 output and swizzled scales are bitwise ``mxfp8_quantize(norm, True)`` of that RMSNorm output, + and its NVFP4 output and linear scales bitwise ``fp4_quantize(norm, scale, 16, False, False)``. +- ``swiglu_mxfp8``: bitwise ``mxfp8_quantize(swiglu(x), True)``, with and without the SwiGLU-OAI clamp / alpha / beta. +""" + +import pytest +import torch + +from tensorrt_llm._torch.modules.swiglu import swiglu, swiglu_mxfp8 +from tensorrt_llm._utils import get_sm_version + +HIDDEN = 6144 +EPS = 1e-6 + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() < 100, + reason="MXFP8 quantization needs an SM100-family GPU", +) + + +def _bits(t: torch.Tensor) -> torch.Tensor: + return t.view(torch.uint8) if t.element_size() == 1 else t.view(torch.int16) + + +@pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() != 107, + reason="the CTX residual RMSNorm + MXFP8 op is built for SM107", +) +@pytest.mark.parametrize("rows", [8192, 8197, 16384]) +@pytest.mark.parametrize("fp4", [False, True], ids=["mxfp8", "mxfp8_nvfp4"]) +def test_ctx_residual_rmsnorm_mxfp8_matches_the_unfused_ops(rows: int, fp4: bool) -> None: + gen = torch.Generator(device="cuda").manual_seed(rows + fp4) + inter = torch.randn((rows, HIDDEN), generator=gen, device="cuda").to(torch.bfloat16) + residual = torch.randn((rows, HIDDEN), generator=gen, device="cuda").to(torch.bfloat16) + weight = (1.0 + 0.1 * torch.randn((HIDDEN,), generator=gen, device="cuda")).to(torch.bfloat16) + expected_sum = (inter.float() + residual.float()).to(torch.bfloat16) + scale = torch.tensor([448.0 * 6.0 / 8.0], dtype=torch.float32, device="cuda") + + args = (inter, residual, weight, EPS, True) + ((scale,) if fp4 else ()) + norm, q, sf, q4, sf4 = torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8(*args) + torch.cuda.synchronize() + + assert torch.equal(_bits(inter), _bits(expected_sum)), "the residual sum written back" + s = expected_sum.double() + ref = s * torch.rsqrt(s.pow(2).mean(-1, keepdim=True) + EPS) * weight.double() + torch.testing.assert_close(norm.double(), ref, rtol=2**-7, atol=1e-3) + + ref_q, ref_sf = torch.ops.trtllm.mxfp8_quantize(norm, True) + assert torch.equal(_bits(q), _bits(ref_q)), "MXFP8 values" + assert torch.equal(sf.view(-1), ref_sf.view(torch.uint8).view(-1)), "MXFP8 swizzled scales" + if fp4: + ref_q4, ref_sf4 = torch.ops.trtllm.fp4_quantize(norm, scale, 16, False, False) + assert torch.equal(q4.view(torch.uint8), ref_q4.view(torch.uint8)), "NVFP4 values" + assert torch.equal(sf4.view(-1), ref_sf4.view(torch.uint8).view(-1)), "NVFP4 linear scales" + else: + assert q4.numel() == 0 and sf4.numel() == 0 + + +@pytest.mark.parametrize("rows", [8192, 8197]) +@pytest.mark.parametrize("d", [1536, 6144]) +@pytest.mark.parametrize( + "limit, alpha, beta", [(7.0, 1.702, 1.0), (None, None, None)], ids=["oai", "plain"] +) +def test_swiglu_mxfp8_is_bitwise_the_quantized_swiglu( + rows: int, d: int, limit, alpha, beta +) -> None: + gen = torch.Generator(device="cuda").manual_seed(rows * d) + x = (4.0 * torch.randn((rows, 2 * d), generator=gen, device="cuda")).to(torch.bfloat16) + q, sf = swiglu_mxfp8(x, swiglu_limit=limit, swiglu_alpha=alpha, swiglu_beta=beta) + ref_q, ref_sf = torch.ops.trtllm.mxfp8_quantize( + swiglu(x, swiglu_limit=limit, swiglu_alpha=alpha, swiglu_beta=beta), True + ) + assert torch.equal(_bits(q), _bits(ref_q)), "MXFP8 values" + assert torch.equal(sf.view(-1), ref_sf.view(torch.uint8).view(-1)), "MXFP8 swizzled scales" diff --git a/tests/unittest/_torch/kernels/serial/test_m3_qkv_fusion.py b/tests/unittest/_torch/kernels/serial/test_m3_qkv_fusion.py new file mode 100644 index 000000000000..e131504f80fc --- /dev/null +++ b/tests/unittest/_torch/kernels/serial/test_m3_qkv_fusion.py @@ -0,0 +1,364 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate for the SM107 fused MiniMax-M3 QKV MXFP8 GEMM + producer epilogue. + +The fused kernel's debug handle writes its own bf16 GEMM output G; the stock +``minimax_m3_nvfp4_qkv_indexer_norm_rope_kv_insert`` producer run on G is the +reference, and the fused outputs (q, index-q, K/V NVFP4 data, K/V scales, +index-K) must match it bitwise, including the cache bytes it must not touch. + +Also runnable as a script (``python3 test_m3_qkv_fusion.py --m 16384,300 +--timing``); ``M3QKV_PKG`` may name a directory holding an ``m3_qkv_fusion`` +package to test instead of the in-tree one. +""" + +import argparse +import importlib +import os +import sys + +import pytest +import torch + +# tensorrt_llm is imported inside the functions that need it, so that _kernel_module() first sets +# CUTE_DSL_ARCH (read by the CuTe DSL when it is imported) and puts any M3QKV_PKG on sys.path. + +HEADS_Q, HEADS_KV, HEADS_INDEX, HEAD_DIM, K_DIM = 32, 2, 2, 128, 6144 +N_DIM = (HEADS_Q + 2 * HEADS_KV + HEADS_INDEX + 1) * HEAD_DIM +EPS = 1e-6 +SENTINEL_DATA, SENTINEL_SCALE, SENTINEL_INDEX, SENTINEL_Q = 0xA5, 0x5A, 0x3C, 0x77 + + +def _is_sm107(): + return torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 7) + + +pytestmark = pytest.mark.skipif(not _is_sm107(), reason="SM107 (Rubin) required") + + +def _kernel_module(): + os.environ.setdefault("CUTE_DSL_ARCH", "sm_107a") + pkg = os.environ.get("M3QKV_PKG") + if pkg: + sys.path.insert(0, pkg) + return importlib.import_module("m3_qkv_fusion.kernel") + return importlib.import_module("tensorrt_llm._torch.kernels.rubin.m3_qkv_fusion.kernel") + + +def _rope_cache(max_positions, rotary_dim=64, base=5_000_000.0): + positions = torch.arange(max_positions, dtype=torch.float32, device="cuda") + inv_freq = 1.0 / ( + base ** (torch.arange(0, rotary_dim, 2, dtype=torch.float32, device="cuda") / rotary_dim) + ) + freq = torch.outer(positions, inv_freq) + return torch.stack((freq.cos(), freq.sin()), dim=1).contiguous() + + +class Problem: + def __init__(self, m, seed=0): + import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) + + g = torch.Generator(device="cuda").manual_seed(seed) + self.m = m + x = torch.randn(m, K_DIM, device="cuda", generator=g, dtype=torch.bfloat16) + w = (torch.randn(N_DIM, K_DIM, device="cuda", generator=g) * 0.02).to(torch.bfloat16) + self.act, self.act_sf = torch.ops.trtllm.mxfp8_quantize(x, True) + self.weight, self.weight_sf = torch.ops.trtllm.mxfp8_quantize(w, True) + self.act_lin_sf = torch.ops.trtllm.mxfp8_quantize(x, False)[1] + self.weight_lin_sf = torch.ops.trtllm.mxfp8_quantize(w, False)[1] + self.alpha = torch.ones(1, dtype=torch.float32, device="cuda") + self.norm_w = [ + (torch.randn(HEAD_DIM, device="cuda", generator=g) * 0.2).to(torch.bfloat16) + for _ in range(4) + ] + self.norm_cat = torch.cat(self.norm_w) + max_pos = m + 4096 + self.rope = _rope_cache(max_pos) + self.positions = torch.randint( + 0, max_pos, (m,), device="cuda", generator=g, dtype=torch.int32 + ) + self.num_pages = (m + 127) // 128 + 2 + slots = torch.randperm(self.num_pages * 128, device="cuda", generator=g)[:m].to(torch.int32) + drop = torch.rand(m, device="cuda", generator=g) < 0.03 + slots[drop] = -1 + beyond = torch.rand(m, device="cuda", generator=g) < 0.01 + slots[beyond] = self.num_pages * 128 + 5 # page >= num_pages: skipped + self.slots = slots + self.kv_quant_scale = torch.tensor([1.0, 0.05, 0.03], dtype=torch.float32, device="cuda") + + def caches(self): + # Strided pools (every other page) like the producer's own test. + p = self.num_pages + data = torch.full( + (2 * p, 2, HEADS_KV, 128, 64), SENTINEL_DATA, dtype=torch.uint8, device="cuda" + )[::2] + scale = torch.full( + (2 * p, 2, HEADS_KV, 128, 8), SENTINEL_SCALE, dtype=torch.uint8, device="cuda" + )[::2] + index = torch.full((2 * p, 1, 128, 128), SENTINEL_INDEX, dtype=torch.uint8, device="cuda")[ + ::2 + ] + return data, scale, index.view(torch.float8_e4m3fn) + + def outputs(self): + q = torch.full((self.m, HEADS_Q, HEAD_DIM), SENTINEL_Q, dtype=torch.uint8, device="cuda") + iq = torch.full( + (self.m, HEADS_INDEX, HEAD_DIM), SENTINEL_Q, dtype=torch.uint8, device="cuda" + ) + return q.view(torch.float8_e4m3fn), iq.view(torch.float8_e4m3fn) + + def reference(self, gemm_bf16): + data, scale, index = self.caches() + q, iq = torch.ops.trtllm.minimax_m3_nvfp4_qkv_indexer_norm_rope_kv_insert( + gemm_bf16, + data, + scale, + index, + self.slots, + self.kv_quant_scale, + HEADS_Q, + HEADS_KV, + HEADS_INDEX, + HEAD_DIM, + 64, + EPS, + *self.norm_w, + self.rope, + self.positions, + ) + return q, iq, data, scale, index + + def fused_args(self, runner, outs, caches, gemm_out=None): + q, iq = outs + data, scale, index = caches + return runner.make_args( + self.act, + self.act_sf, + self.weight, + self.weight_sf, + self.alpha, + q, + iq, + data, + scale, + index, + self.slots, + self.kv_quant_scale, + self.rope, + self.positions, + self.norm_cat, + EPS, + gemm_out=gemm_out, + ) + + def run_fused(self, runner): + outs, caches = self.outputs(), self.caches() + runner.run_args(self.fused_args(runner, outs, caches)) + return (*outs, *caches) + + def run_debug(self, runner): + g = torch.empty(self.m, N_DIM, dtype=torch.bfloat16, device="cuda") + runner.run_args(self.fused_args(runner, self.outputs(), self.caches(), gemm_out=g)) + return g + + def fp64_reference(self): + def deq(v, sf_lin): + rows = v.shape[0] + sf = ( + sf_lin.view(torch.uint8) + .reshape(-1)[: rows * (K_DIM // 32)] + .reshape(rows, K_DIM // 32) + ) + scale = torch.exp2(sf.to(torch.float64) - 127.0) + return (v.to(torch.float64).reshape(rows, K_DIM // 32, 32) * scale[..., None]).reshape( + rows, K_DIM + ) + + return deq(self.act, self.act_lin_sf) @ deq(self.weight, self.weight_lin_sf).T + + +NAMES = ("q", "index_q", "kv_data", "kv_scale", "index_k") + + +def _bytes(t): + return t.view(torch.uint8) + + +def compare(got, ref): + res = {} + for name, a, b in zip(NAMES, got, ref): + a8, b8 = _bytes(a), _bytes(b) + res[name] = (torch.equal(a8, b8), int((a8 != b8).sum().item())) + return res + + +def gate(m, cfg, log=print): + k = _kernel_module() + prob = Problem(m) + fused = k.M3QkvFusedRunner(**cfg) + debug = k.M3QkvFusedRunner(**cfg, debug_gemm_out=True) + g = prob.run_debug(debug) + torch.cuda.synchronize() + ref = prob.reference(g) + got = prob.run_fused(fused) + torch.cuda.synchronize() + res = compare(got, ref) + ok = all(v[0] for v in res.values()) + log( + f"GATE m={m} bitwise " + + " ".join(f"{n}={'OK' if v[0] else f'DIFF({v[1]})'}" for n, v in res.items()) + ) + + runs = [prob.run_fused(fused) for _ in range(3)] + det = all(compare(r, got)[n][0] for r in runs for n in NAMES) + g2 = prob.run_debug(debug) + det = det and torch.equal(g.view(torch.int16), g2.view(torch.int16)) + log(f"GATE m={m} determinism(3 runs + debug)={'OK' if det else 'FAIL'}") + + outs, caches = prob.outputs(), prob.caches() + args = prob.fused_args(fused, outs, caches) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + fused.run_args(args) # warm-up outside capture + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + fused.run_args(args) + for t, v in zip((*outs, *caches), (0, 0, SENTINEL_DATA, SENTINEL_SCALE, SENTINEL_INDEX)): + _bytes(t).fill_(v) + graph.replay() + torch.cuda.synchronize() + gres = compare((*outs, *caches), got) + graph_ok = all(v[0] for v in gres.values()) + log(f"GATE m={m} cuda_graph_replay==eager={'OK' if graph_ok else 'FAIL ' + str(gres)}") + + ref64 = prob.fp64_reference() + cut = torch.ops.trtllm.mxfp8_mxfp8_gemm( + prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha, torch.bfloat16 + ) + e_f = (g.to(torch.float64) - ref64).abs() + e_c = (cut.to(torch.float64) - ref64).abs() + same = (g.view(torch.int16) == cut.view(torch.int16)).float().mean().item() + band_ok = ( + e_f.max().item() <= 1.5 * e_c.max().item() and e_f.mean().item() <= 1.1 * e_c.mean().item() + ) + log( + f"GATE m={m} fp64 err fused max={e_f.max().item():.4e} mean={e_f.mean().item():.4e} | " + f"cutlass max={e_c.max().item():.4e} mean={e_c.mean().item():.4e} | " + f"bitwise==cutlass {same * 100:.3f}% | band={'OK' if band_ok else 'FAIL'}" + ) + del ref64 + return ok and det and graph_ok and band_ok + + +def timing(m, cfgs, log=print, reps=21): + k = _kernel_module() + from tensorrt_llm._torch.custom_ops.torch_custom_ops import MXFP8GemmRunner + + prob = Problem(m) + log(f"TIME SMs={torch.cuda.get_device_properties(0).multi_processor_count}") + flush = torch.empty(512 << 20, dtype=torch.uint8, device="cuda") + + def med(fn, cold=True): + fn() + torch.cuda.synchronize() + ts = [] + for _ in range(reps): + if cold: + flush.zero_() + e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + e0.record() + fn() + e1.record() + torch.cuda.synchronize() + ts.append(e0.elapsed_time(e1) * 1e3) + return sorted(ts)[reps // 2] + + runner = MXFP8GemmRunner(torch.bfloat16) + inputs = [prob.act, prob.act_sf, prob.weight, prob.weight_sf, prob.alpha] + best = None + for t in range(runner.mxfp8_gemm_runner.get_num_configs()): + try: + us = med(lambda t=t: runner(inputs=inputs, tactic=t)) + except Exception as exc: # noqa: BLE001 + log(f"TIME m={m} cutlass tactic {t} failed: {type(exc).__name__}") + continue + if best is None or us < best[0]: + best = (us, t) + log(f"TIME m={m} cutlass_best tactic={best[1]} cold={best[0]:.1f} us") + g = runner(inputs=inputs, tactic=best[1]) + data, scale, index = prob.caches() + prod = lambda: torch.ops.trtllm.minimax_m3_nvfp4_qkv_indexer_norm_rope_kv_insert( # noqa: E731 + g, data, scale, index, prob.slots, prob.kv_quant_scale, HEADS_Q, HEADS_KV, HEADS_INDEX, + HEAD_DIM, 64, EPS, *prob.norm_w, prob.rope, prob.positions, + ) # fmt: skip + t_prod = med(prod) + both = lambda: (runner(inputs=inputs, tactic=best[1]), prod()) # noqa: E731 + t_both = med(both) + log( + f"TIME m={m} producer cold={t_prod:.1f} us; cutlass_best+producer back-to-back cold={t_both:.1f} us" + ) + for cfg in cfgs: + fused = k.M3QkvFusedRunner(**cfg) + args = prob.fused_args(fused, prob.outputs(), prob.caches()) + t_f = med(lambda: fused.run_args(args)) + t_w = med(lambda: fused.run_args(args), cold=False) + log( + f"TIME m={m} fused {cfg}: cold={t_f:.1f} us warm={t_w:.1f} us (vs {t_both:.1f}: {t_both / t_f:.3f}x)" + ) + if os.environ.get("M3QKV_TIME_DEBUG"): + dbg = k.M3QkvFusedRunner(**cfg, debug_gemm_out=True) + gout = torch.empty(m, N_DIM, dtype=torch.bfloat16, device="cuda") + dargs = prob.fused_args(dbg, prob.outputs(), prob.caches(), gemm_out=gout) + log(f"TIME m={m} debug-gemm-out {cfg}: cold={med(lambda: dbg.run_args(dargs)):.1f} us") + + +def _parse_cfg(text): + keys = { + "hpt": "heads_per_tile", + "acc": "num_acc_stage", + "cl": "cluster_shape_mn", + "pdl": "enable_pdl", + "rm": "raster_along_m", + "sw": "swizzle_size", + "mm": "mma_m", + "mn": "mma_n", + "ew": "epi_wgs", + } + cfg = {} + for item in filter(None, text.split(",")): + key, val = item.split("=") + if key == "cl": + cfg[keys[key]] = tuple(int(v) for v in val.split("x")) + elif key in ("pdl", "rm"): + cfg[keys[key]] = bool(int(val)) + else: + cfg[keys[key]] = int(val) + return cfg + + +@pytest.mark.parametrize("m", [16384, 8200, 1000, 300]) +def test_m3_qkv_fusion_bitwise(m): + assert gate(m, {}) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--m", default="16384,8200,1000,300") + ap.add_argument( + "--cfg", action="append", default=[], help="compile kwargs, e.g. hpt=2,cl=1x2,acc=2,pdl=0" + ) + ap.add_argument("--timing", default="", help="comma list of M for timing") + ap.add_argument("--no-gate", action="store_true") + a = ap.parse_args() + cfgs = [_parse_cfg(c) for c in a.cfg] or [{}] + all_ok = True + if not a.no_gate: + for mm in [int(v) for v in a.m.split(",") if v]: + for cfg in cfgs: + print(f"GATE cfg={cfg}", flush=True) + all_ok &= gate(mm, cfg, log=lambda s: print(s, flush=True)) + for mm in [int(v) for v in a.timing.split(",") if v]: + timing(mm, cfgs, log=lambda s: print(s, flush=True)) + print(f"GATE ALL {'PASS' if all_ok else 'FAIL'}", flush=True) diff --git a/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py b/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py new file mode 100644 index 000000000000..0794f563b940 --- /dev/null +++ b/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Opt-in FP4 MoE tactic table (TLLM_FP4_MOE_TACTIC_TABLE).""" + +import json +from types import SimpleNamespace + +import pytest + +from tensorrt_llm._torch.custom_ops import trtllm_gen_custom_ops as ops + +pytestmark = pytest.mark.cpu_only + + +def _runner(unique_id=(4, 3072, 64, 0), ep_size=2): + specs = ops.FP4BlockScaleMoERunner.get_dynamic_tensor_specs(ep_size) + return SimpleNamespace( + unique_id=lambda: unique_id, tuning_config=SimpleNamespace(dynamic_tensor_specs=specs) + ) + + +@pytest.fixture +def table(tmp_path, monkeypatch): + path = tmp_path / "fp4_moe_tactics.json" + path.write_text(json.dumps({"4,3072,64,0": {"1024": [128, 23], "8192": [256, 7]}})) + ops._load_fp4_moe_tactic_table.cache_clear() + monkeypatch.setattr(ops, "_FP4_MOE_TACTIC_TABLE_PATH", str(path)) + yield path + ops._load_fp4_moe_tactic_table.cache_clear() + + +def test_off_by_default(monkeypatch): + monkeypatch.setattr(ops, "_FP4_MOE_TACTIC_TABLE_PATH", None) + assert ops._pinned_fp4_moe_tactic(_runner(), 1761) is None + + +def test_pinned_tactic_uses_the_tuning_bucket(table): + # 1761 and 1160 rows both map to the 1024 tuning bucket. + assert ops._pinned_fp4_moe_tactic(_runner(), 1761) == [128, 23] + assert ops._pinned_fp4_moe_tactic(_runner(), 1160) == [128, 23] + assert ops._pinned_fp4_moe_tactic(_runner(), 8192) == [256, 7] + + +def test_unlisted_bucket_or_shape_keeps_the_tuner_choice(table): + assert ops._pinned_fp4_moe_tactic(_runner(), 300) is None + assert ops._pinned_fp4_moe_tactic(_runner(unique_id=(8, 3072, 64, 0)), 1761) is None + + +def test_table_path_is_resolved_at_import(table, monkeypatch): + # The environment is not re-read per call (CUDA-graph capture must see the same tactic as eager steps). + monkeypatch.delenv(ops.FP4_MOE_TACTIC_TABLE_ENV, raising=False) + assert ops._pinned_fp4_moe_tactic(_runner(), 1761) == [128, 23] diff --git a/tests/unittest/_torch/modeling/test_minimax_m3_router_fp32_cast.py b/tests/unittest/_torch/modeling/test_minimax_m3_router_fp32_cast.py new file mode 100644 index 000000000000..cff792fc35f4 --- /dev/null +++ b/tests/unittest/_torch/modeling/test_minimax_m3_router_fp32_cast.py @@ -0,0 +1,45 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 router input cast: the SM107 Triton path is bitwise ``.to(torch.float32)``, and its gate.""" + +import pytest +import torch + +from tensorrt_llm._torch.models import modeling_minimaxm3 as m3 + +cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA op") + + +def _bits(t: torch.Tensor) -> torch.Tensor: + return t.view(torch.int32) + + +@cuda +@pytest.mark.parametrize("tokens", [2048, 2049, 8192, 16384]) +def test_router_cast_bitwise(tokens): + g = torch.Generator(device="cuda").manual_seed(tokens) + x = torch.randn(tokens, 6144, device="cuda", generator=g).to(torch.bfloat16) + x[0, :6] = torch.tensor( + [float("inf"), float("-inf"), float("nan"), -0.0, 1e-40, -3e38], dtype=torch.bfloat16 + ) + out = m3.minimax_m3_router_input_fp32(x) + assert out.dtype == torch.float32 and out.shape == x.shape + assert torch.equal(_bits(out), _bits(x.to(torch.float32))) + + +@cuda +def test_router_cast_fallbacks(): + x = torch.randn(4096, 2 * 6144, device="cuda").to(torch.bfloat16) + for t in (x[:, :6144], x[:1024, :6144].contiguous(), x[:, :6144].half()): + out = m3.minimax_m3_router_input_fp32(t) + assert torch.equal(_bits(out), _bits(t.to(torch.float32))) + + +@pytest.mark.parametrize( + "sm_version,enabled,expected", [(107, True, True), (103, True, False), (107, False, False)] +) +def test_router_cast_gate(monkeypatch, sm_version, enabled, expected): + monkeypatch.setattr(m3, "get_sm_version", lambda: sm_version) + monkeypatch.setattr(m3, "_SM107_ROUTER_FP32_CAST", enabled) + gate = m3.MiniMaxM3Gate(hidden_size=64, num_experts=8, top_k=2, routed_scaling_factor=1.0) + assert gate._sm107_fp32_cast is expected diff --git a/tests/unittest/_torch/modeling/test_minimax_m3_router_tc_gen.py b/tests/unittest/_torch/modeling/test_minimax_m3_router_tc_gen.py new file mode 100644 index 000000000000..dc69a6f6aa2e --- /dev/null +++ b/tests/unittest/_torch/modeling/test_minimax_m3_router_tc_gen.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""SM107 generation-step router: the TF32 tensor-core router (minimax_m3_router_tc, 16-CTA clusters) at 9..16 rows. + +Checks on the device: the 16-CTA cluster query; router_tc against the stock router of these steps (fp32 linear under +cuBLAS TF32) within the documented rule-1b tolerance and against the fp32 product; eager == CUDA graph bitwise; the +NVFP4 activation payload (packed e2m1 and linear scales) bitwise vs fp4_quantize's unswizzled layout; +MiniMaxM3Gate.forward dispatch (9..16 generation rows take router_tc, 4 rows / context steps / the kill switch keep the +stock router). +""" + +import pytest +import torch + +import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) +from tensorrt_llm._torch._experimental.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp2.ops.moe.m3_router_tc import ( # noqa: E501 + tf32_rna, +) +from tensorrt_llm._torch.models import modeling_minimaxm3 as mm +from tensorrt_llm._utils import get_sm_version + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() != 107, reason="SM107 (Rubin) only" +) + +E, K = 128, 6144 + + +def _inputs(m, seed): + g = torch.Generator(device="cuda").manual_seed(seed) + w = (torch.randn(E, K, device="cuda", generator=g) * 0.02).float().contiguous() + x = (torch.randn(m, K, device="cuda", generator=g) * 0.5).to(torch.bfloat16).contiguous() + return x, w + + +def _stock(x, w): + prev = torch.backends.cuda.matmul.allow_tf32 + torch.backends.cuda.matmul.allow_tf32 = True + try: + return torch.nn.functional.linear(x.float(), w) + finally: + torch.backends.cuda.matmul.allow_tf32 = prev + + +def _fp32_exact(x, w): + prev = torch.backends.cuda.matmul.allow_tf32 + torch.backends.cuda.matmul.allow_tf32 = False + try: + return x.float() @ tf32_rna(w).t() + finally: + torch.backends.cuda.matmul.allow_tf32 = prev + + +def test_cluster16_query(): + assert isinstance(torch.ops.trtllm.minimax_m3_router_tc_cluster16(K), bool) + + +@pytest.mark.parametrize("m", [9, 12, 16]) +def test_router_tc_vs_stock_and_fp32(m): + if not torch.ops.trtllm.minimax_m3_router_tc_cluster16(K): + pytest.skip( + "this device cannot co-schedule 16-CTA clusters (the gate keeps the stock router)" + ) + x, w = _inputs(m, 1000 + m) + tc = torch.ops.trtllm.minimax_m3_router_tc(x, w, None, False)[0] + assert (tc - _fp32_exact(x, w)).abs().max().item() <= 1e-5 + stock = _stock(x, w) + assert (tc - stock).abs().max().item() <= 2e-4 + assert torch.equal(tc.argmax(-1), stock.argmax(-1)) + + +@pytest.mark.parametrize("m", [9, 16]) +def test_router_tc_eager_equals_graph_and_fp4_payload(m): + if not torch.ops.trtllm.minimax_m3_router_tc_cluster16(K): + pytest.skip("this device cannot co-schedule 16-CTA clusters") + x, w = _inputs(m, 2000 + m) + sf_scale = torch.tensor([448.0 * 6.0 / 8.0], device="cuda", dtype=torch.float32) + eager = torch.ops.trtllm.minimax_m3_router_tc(x, w, sf_scale, True) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = torch.ops.trtllm.minimax_m3_router_tc(x, w, sf_scale, True) + graph.replay() + torch.cuda.synchronize() + for a, b in zip(eager, out): + assert torch.equal(a, b) + # router_tc emits LINEAR (unswizzled) E4M3 scales [M, K / 16]: compare against fp4_quantize's linear layout, the one + # the MoE's pre-quantized input slot takes (the swizzled default pads M to 128 rows). + q, sf = torch.ops.trtllm.fp4_quantize(x, sf_scale, 16, False, False)[:2] + assert torch.equal(eager[1].contiguous().view(torch.uint8), q.contiguous().view(torch.uint8)) + assert eager[2].numel() == m * K // 16 + assert torch.equal( + eager[2].contiguous().view(torch.uint8).flatten(), + sf.contiguous().view(torch.uint8).flatten(), + ) + + +def test_gate_dispatch(monkeypatch): + if not torch.ops.trtllm.minimax_m3_router_tc_cluster16(K): + pytest.skip("this device cannot co-schedule 16-CTA clusters") + monkeypatch.setattr( + mm, "_ROUTER_TC_GEN", True + ) # default OFF until its gates pass: enable for the dispatch check + gate = mm.MiniMaxM3Gate(K, E, 4, 1.0).cuda() + x16, w = _inputs(16, 3000) + gate.weight.data.copy_(w) + tc = torch.ops.trtllm.minimax_m3_router_tc(x16, w, None, False)[0] + assert torch.equal(gate(x16, generation_only=True), tc) # 9..16 generation rows: router_tc + + def stock_path( + x, + ): # the gate's own stock router under the process's TF32 setting (same ops, same bits) + return torch.nn.functional.linear(mm.minimax_m3_router_input_fp32(x), w) + + x4 = x16[:4].contiguous() + assert torch.equal(gate(x4, generation_only=True), stock_path(x4)) # 4 rows: the stock router + assert torch.equal( + gate(x16, generation_only=False), stock_path(x16) + ) # context step: never router_tc + monkeypatch.setattr(mm, "_ROUTER_TC_GEN", False) + killed = mm.MiniMaxM3Gate(K, E, 4, 1.0).cuda() + killed.weight.data.copy_(w) + assert not killed._router_tc_gen + assert torch.equal( + killed(x16, generation_only=True), stock_path(x16) + ) # kill switch: the stock router diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py index 9e16b0a9fc2b..03510d0338f7 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py @@ -20,6 +20,12 @@ LAYERS = 4 +class _Rows(tuple): + """A tagged stand-in activation that has the row count the layer reads.""" + + shape = (2,) + + class _Spec: def __init__(self, layers): self.layers = set(layers) @@ -47,7 +53,7 @@ def layer(request, monkeypatch): monkeypatch.setattr( modeling, "_native_allreduce_norm", - lambda core, x, r, norm: (("normed", x, norm), ("updated", x, r)), + lambda core, x, r, norm: (_Rows(("normed", x, norm)), ("updated", x, r)), ) def boundary(self, x, x2, residual, norm_w): @@ -57,9 +63,10 @@ def boundary(self, x, x2, residual, norm_w): if request.param == "prefill": cls = modeling.PrefillTarget monkeypatch.setattr(cls, "_moe", lambda self, i, h, **k: (("moe", i), ("routed", i))) - monkeypatch.setattr( - cls, "_swiglu_mlp", lambda self, h, prefix, low_m, dense=False: ("mlp", prefix) - ) + monkeypatch.setattr(cls, "_swiglu_mlp", lambda self, h, prefix, low_m, **k: ("mlp", prefix)) + # The stand-in activations are not prefill-sized tensors: no boundary here takes the built-in CTX stack. + monkeypatch.setattr(modeling, "_ctx_norm_rows", lambda x: False) + monkeypatch.setattr(modeling, "_ctx_stack_step", lambda step, rows: False) else: cls = modeling.DecodeTarget monkeypatch.setattr( @@ -134,6 +141,8 @@ def mc_finalize(i, h, r, norm_w): _decode=SimpleNamespace(_generic_mc_finalize=mc_finalize), ) monkeypatch.setattr(modeling, "_can_mc", lambda x, folded=False: False) + # Stand-in activations: not a CTX-stack step. + monkeypatch.setattr(modeling, "_ctx_norm_rows", lambda x: False) monkeypatch.setattr( modeling, "_native_allreduce_norm", lambda core, x, r, norm: (("normed", x), ("upd", x, r)) ) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_ctx_stack_route.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_ctx_stack_route.py new file mode 100644 index 000000000000..faca82f1f345 --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_ctx_stack_route.py @@ -0,0 +1,167 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The prefill target's context steps and the built-in CTX stack (modeling.CTX_STACK). + +A step with context rows of at least CTX_STACK_MIN_ROWS rows takes the built-in CTX stack; a step without context rows +never does. Inside the stack the MoE runs the built-in forward only from the CTX norm's rows +(``_CTX_NORM_MXFP8_MIN_ROWS``), where that norm emits the NVFP4 MoE input; the boundary into the final norm is never +the CTX one. CTX_STACK=False routes nothing. + +CPU only: nothing here launches a kernel. +""" + +from types import SimpleNamespace + +import pytest +import torch + +from tensorrt_llm._torch._experimental.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp2 import ( + modeling, +) +from tensorrt_llm._torch.models import modeling_minimaxm3 as builtin + +pytestmark = pytest.mark.cpu_only + + +def test_the_ctx_stack_defaults() -> None: + # On by default from 4096 rows; the MoE hand-off and the CTX norm start at the norm's floor, above the stack's. + assert modeling.CTX_STACK is True + assert modeling.CTX_STACK_MIN_ROWS == 4096 + assert modeling.CTX_NORM_MIN_ROWS == builtin._CTX_NORM_MXFP8_MIN_ROWS == 8192 + + +@pytest.mark.parametrize( + "stack, num_contexts, rows, expected", + [ + (True, 1, 4096, True), + (True, 1, 4095, False), + (True, 2, 16384, True), + (True, 0, 16384, False), + (False, 1, 16384, False), + ], +) +def test_ctx_stack_step(monkeypatch, stack, num_contexts, rows, expected) -> None: + monkeypatch.setattr(modeling, "CTX_STACK", stack) + assert modeling._ctx_stack_step({"num_contexts": num_contexts}, rows) is expected + + +@pytest.mark.parametrize( + "stack, rows, expected", [(True, 8192, True), (True, 8191, False), (False, 8192, False)] +) +def test_ctx_norm_rows(monkeypatch, stack, rows, expected) -> None: + monkeypatch.setattr(modeling, "CTX_STACK", stack) + assert modeling._ctx_norm_rows(torch.empty((rows, 8))) is expected + + +class _TargetPathTaken(Exception): + """Raised where the target's own MoE path starts, so a test sees which way the step went.""" + + +class _Core: + def __getattr__(self, name): + raise _TargetPathTaken(name) + + +def _moe_route(rows: int, **kwargs) -> str: + """Which MoE forward ``PrefillTarget._moe`` takes for ``rows``: 'built-in' or 'target'.""" + calls = [] + target = SimpleNamespace( + core=_Core(), _ctx_moe=lambda i, h, nvfp4: calls.append((i, h, nvfp4)) or "built-in" + ) + hidden = torch.empty((rows, 8), dtype=torch.bfloat16) + try: + out, routed = modeling.PrefillTarget._moe(target, 3, hidden, **kwargs) + except _TargetPathTaken: + return "target" + assert routed is None and len(calls) == 1 and calls[0][1] is hidden + return out + + +def test_moe_hands_ctx_steps_to_the_built_in_forward() -> None: + assert _moe_route(16384, return_parts=False, ctx=True, ctx_nvfp4=None) == "built-in" + + +@pytest.mark.parametrize( + "kwargs", + [dict(return_parts=False, ctx=False), dict(return_parts=True, ctx=True)], + ids=["not_ctx", "parts"], +) +def test_moe_keeps_the_target_path(kwargs) -> None: + # A step outside the stack, or one whose boundary takes the shared and routed parts separately. + assert _moe_route(16384, **kwargs) == "target" + + +@pytest.mark.parametrize("rows, expected", [(16384, True), (16385, False)]) +def test_nvfp4_moe_input_only_for_one_runner_call(rows, expected) -> None: + # The CTX norm's NVFP4 output stands in for the experts' quantize only in one runner call (moe_max_num_tokens). + scale = torch.ones(1, dtype=torch.float32) + core = SimpleNamespace( + moe_max_num_tokens=16384, moe={3: SimpleNamespace(fc31_input_scale=scale)} + ) + got = modeling._ctx_fp4_input_scale(core, 3, rows) + assert (got is scale) if expected else got is None + + +def test_the_final_boundary_is_never_the_ctx_norm(monkeypatch) -> None: + # The last layer's boundary feeds the final norm (no next QKV takes an MXFP8 copy): the generic boundary. + reduced = [] + monkeypatch.setattr(modeling, "_ctx_reduce_norm", lambda *args: reduced.append(args)) + monkeypatch.setattr(modeling, "_next_norm", lambda core, i: None) + generic = [] + target = SimpleNamespace( + core=SimpleNamespace(num_layers=4), + _generic_boundary=lambda x, x2, residual, norm_w: generic.append(x) or ("n", "u"), + ) + x = torch.empty((16384, 8)) + assert modeling.PrefillTarget._boundary(target, 3, x, None, x) == ("n", "u") + assert reduced == [] and len(generic) == 1 + + +def test_no_ctx_stack_inside_a_breakable_graph(monkeypatch) -> None: + # A captured breakable-graph bucket (its 4096-row one included) runs the generic path, eager steps the stack. + monkeypatch.setattr(modeling, "is_in_breakable_cuda_graph", lambda: True) + assert modeling._ctx_stack_step({"num_contexts": 1}, 4096) is False + assert modeling._ctx_norm_rows(torch.empty((8192, 8))) is False + monkeypatch.setattr(modeling, "is_in_breakable_cuda_graph", lambda: False) + assert modeling._ctx_stack_step({"num_contexts": 1}, 4096) is True + assert modeling._ctx_norm_rows(torch.empty((8192, 8))) is True + + +def test_an_eagle3_capture_layer_keeps_the_generic_boundary(monkeypatch) -> None: + reduced = [] + monkeypatch.setattr(modeling, "_ctx_reduce_norm", lambda *args: reduced.append(args)) + monkeypatch.setattr(modeling, "_next_norm", lambda core, i: None) + generic = [] + target = SimpleNamespace( + core=SimpleNamespace(num_layers=8), + _generic_boundary=lambda x, x2, residual, norm_w: generic.append(x) or ("n", "u"), + ) + x = torch.empty((16384, 8)) + assert modeling.PrefillTarget._boundary(target, 3, x, None, x, True) == ("n", "u") + assert reduced == [] and len(generic) == 1 + + +def test_a_captured_4096_row_bucket_takes_the_breakable_boundary(monkeypatch) -> None: + # The 4096-row breakable bucket reaches CTX_STACK_MIN_ROWS, but inside a capture the sparse attention is the + # breakable path (captured projection + eager boundary): the CTX stack's fused QKV and armed core never run. + monkeypatch.setattr(modeling, "is_in_breakable_cuda_graph", lambda: True) + + def _ctx_called(*args, **kwargs): + raise AssertionError("the CTX stack ran inside a capture") + + monkeypatch.setattr(modeling, "_ctx_fused_qkv", _ctx_called) + rows = modeling.CTX_STACK_MIN_ROWS + packed = torch.empty((rows, 16), dtype=torch.bfloat16) + linears = [] + monkeypatch.setattr( + modeling, "_linear", lambda core, x, wk, sk, low_m: linears.append(wk) or (packed, False) + ) + eager = [] + monkeypatch.setattr(modeling, "_prefill_attention_eager", lambda *args: eager.append(args[-1])) + core = SimpleNamespace(sparse_layers={5}, fused_projection=True, heads=2, head_dim=4) + target = SimpleNamespace(core=core, _bcg_key="k", _ctx_core_then_o_proj=_ctx_called) + step = {"num_contexts": 1} + hidden = torch.empty((rows, 16), dtype=torch.bfloat16) + out, pushed = modeling.PrefillTarget._attention(target, 5, None, hidden, step) + assert out is packed and pushed is False + assert linears == ["l5_qkv_w", "l5_o_w"] and eager == [5] diff --git a/tests/unittest/_torch/models/test_minimax_m3.py b/tests/unittest/_torch/models/test_minimax_m3.py index 3ac45b512476..bacf92caeffd 100644 --- a/tests/unittest/_torch/models/test_minimax_m3.py +++ b/tests/unittest/_torch/models/test_minimax_m3.py @@ -23,7 +23,7 @@ import json import os from types import SimpleNamespace -from unittest.mock import Mock, create_autospec +from unittest.mock import Mock, call, create_autospec import pytest import torch @@ -86,13 +86,14 @@ ) from tensorrt_llm._torch.models.modeling_speculative import SpecDecOneEngineForCausalLM from tensorrt_llm._torch.models.modeling_utils import _load_weights_impl_v2 -from tensorrt_llm._torch.modules.linear import _load_kv_cache_scales +from tensorrt_llm._torch.modules.linear import MXFP8LinearMethod, _load_kv_cache_scales from tensorrt_llm._torch.modules.rms_norm import RMSNorm from tensorrt_llm._torch.moe.fused_moe.interface import MoESchedulerKind from tensorrt_llm._torch.moe.fused_moe.routing import ( MiniMaxM2MoeRoutingMethod, MiniMaxM3MoeRoutingMethod, ) +from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.trtllm_nvfp4 import TrtllmTrtllmGenNvfp4Impl from tensorrt_llm._torch.utils import AuxStreamType, EventType from tensorrt_llm.llmapi import MiniMaxM3SparseAttentionConfig, RocketSparseAttentionConfig from tensorrt_llm.mapping import Mapping @@ -219,7 +220,7 @@ def read_scales(): class _M3CompositionGate(nn.Module): - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + def forward(self, hidden_states: torch.Tensor, generation_only: bool = False) -> torch.Tensor: return hidden_states @@ -285,6 +286,7 @@ def test_minimax_m3_moe_reduces_only_local_terms( moe.allreduce = _M3CompositionAllReduce() moe.event_dict = {EventType.Main: None, EventType.MoeShared: None} moe.aux_stream = None + moe._prequantized_fp4 = None hidden_states = torch.ones((2, 4)) output = moe(hidden_states, SimpleNamespace(all_rank_num_tokens=None)) @@ -531,7 +533,7 @@ def maybe_capture_hidden_states(self, layer_idx, hidden_states, residual) -> Non layer = SimpleNamespace( layer_idx=25, - _apply_pre_feed_forward_norm=lambda hidden, residual: (hidden + 1, residual + 2), + _apply_pre_feed_forward_norm=lambda hidden, residual, moe=None: (hidden + 1, residual + 2), block_sparse_moe=lambda hidden, unused_metadata, **unused_kwargs: hidden + 3, _feed_forward_all_reduce_params=lambda: None, _apply_next_layer_layernorm=lambda hidden, residual: (hidden + 10, residual + 20), @@ -741,7 +743,7 @@ def test_piecewise_captures_horizontal_producer_before_attention( layer_idx=3, layer_idx_str="3", qkv_proj=Mock(return_value=packed), - _fused_fp8_qkv_indexer_norm_rope_kv_insert=Mock(return_value=(q, idx_q)), + _fused_fp8_qkv_indexer_norm_rope_kv_insert=Mock(side_effect=[None, (q, idx_q)]), _forward_attention_core=Mock(return_value=output), o_proj=lambda output, all_reduce_params: output, ) @@ -756,9 +758,12 @@ def test_piecewise_captures_horizontal_producer_before_attention( result = MiniMaxM3Attention._sparse_forward(layer, positions, hidden, metadata) assert result is output layer.qkv_proj.assert_called_once_with(hidden) - layer._fused_fp8_qkv_indexer_norm_rope_kv_insert.assert_called_once_with( - packed, positions, metadata, cache_tensors=(kv_cache, index_cache, scale_cache, slots) - ) + cache_tensors = (kv_cache, index_cache, scale_cache, slots) + # The fused QKV GEMM + producer is tried first on hidden_states; it declines here, so the packed projection runs. + assert layer._fused_fp8_qkv_indexer_norm_rope_kv_insert.call_args_list == [ + call(None, positions, metadata, cache_tensors=cache_tensors, hidden_states=hidden), + call(packed, positions, metadata, cache_tensors=cache_tensors), + ] layer._forward_attention_core.assert_called_once_with(q, None, None, idx_q, None, metadata) @@ -785,7 +790,8 @@ def test_piecewise_captured_producer_rejects_unavailable_fusion( "3", ) assert str(exc.value) == "MiniMax-M3 piecewise graph requires the fused sparse QKV producer." - layer._fused_fp8_qkv_indexer_norm_rope_kv_insert.assert_called_once() + # Tried on hidden_states (fused QKV GEMM + producer) and on the packed projection; both decline. + assert layer._fused_fp8_qkv_indexer_norm_rope_kv_insert.call_count == 2 @pytest.mark.cpu_only @@ -804,8 +810,11 @@ def producer( metadata: object, *, cache_tensors: tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, torch.Tensor], - ) -> tuple[torch.Tensor, torch.Tensor]: + hidden_states: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor] | None: """Emulate native cache writes using only the explicit tensor arguments.""" + if packed is None: + return None # no fused QKV GEMM + producer here: the op falls back to the packed projection kv_cache, index_cache, scale_cache, slots = cache_tensors # Deliberately use only the explicit caches, not the runtime metadata. valid = slots >= 0 @@ -945,6 +954,7 @@ def test_piecewise_unfused_indexer_keeps_cache_write_eager(monkeypatch: pytest.M aux_stream=None, _forward_attention_core=Mock(return_value=torch.empty((4, 128), dtype=torch.bfloat16)), o_proj=lambda output, all_reduce_params: output, + _core_then_o_proj=lambda core, all_reduce_params, site, padded=False: core(), ) monkeypatch.setattr(modeling_minimaxm3, "is_torch_compiling", lambda: True) monkeypatch.setattr( @@ -3107,3 +3117,166 @@ def test_minimax_m3_sdpa_dense_decode_matches_repeat_interleave_reference(num_kv ref = _dense_sdpa_decode_reference(q, k_ctx, v_ctx, seq_lens, num_kv_heads, head_dim) torch.testing.assert_close(output.float(), ref, atol=2e-2, rtol=2e-2) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "bcg_p5a, qkv_fused, rows, expected", + [ + (True, True, 1024, False), + (True, True, 1025, True), + (True, True, 1536, True), + (True, True, 2048, True), + (False, True, 2048, False), + (True, False, 2048, False), + ], +) +def test_bcg_bucket_takes_eager_qkv( + monkeypatch, bcg_p5a: bool, qkv_fused: bool, rows: int, expected: bool +) -> None: + # Breakable buckets above the fused-QKV row floor run the eager path's QKV in an eager break (bitwise the eager + # step); TRTLLM_CTX_BCG_P5A=0 or TRTLLM_CTX_QKV_FUSED=0 keeps the captured stock projection. + monkeypatch.setattr(modeling_minimaxm3, "_CTX_BCG_P5A", bcg_p5a) + monkeypatch.setattr(modeling_minimaxm3, "_CTX_QKV_FUSED", qkv_fused) + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: 107) + assert modeling_minimaxm3._bcg_bucket_takes_eager_qkv(rows) is expected + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("sm", [90, 100, 103, 110]) +def test_bcg_bucket_keeps_captured_qkv_off_rubin(monkeypatch, sm: int) -> None: + # Off SM107 the fused QKV GEMM never engages, so breakable buckets keep the captured stock projection. + monkeypatch.setattr(modeling_minimaxm3, "_CTX_BCG_P5A", True) + monkeypatch.setattr(modeling_minimaxm3, "_CTX_QKV_FUSED", True) + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: sm) + assert not modeling_minimaxm3._bcg_bucket_takes_eager_qkv(2048) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("rows", [1, 1023, 1024, 1025, 2048, 16384]) +def test_fused_qkv_rows_agree_between_eager_and_breakable(monkeypatch, rows: int) -> None: + # A breakable bucket runs the eager QKV exactly when an eager step of the same rows takes the fused QKV GEMM + + # producer, so a captured step is bitwise the eager one at every row count, including the 1024-row boundary. + monkeypatch.setattr(modeling_minimaxm3, "_CTX_BCG_P5A", True) + monkeypatch.setattr(modeling_minimaxm3, "_CTX_QKV_FUSED", True) + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: 107) + fused = modeling_minimaxm3._ctx_qkv_fused_takes_rows(rows) + assert modeling_minimaxm3._bcg_bucket_takes_eager_qkv(rows) is fused + assert fused is (rows > 1024) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("sm, expected", [(107, True), (103, False), (100, False), (90, False)]) +def test_swiglu_mxfp8_engages_on_sm107_only(monkeypatch, sm: int, expected: bool) -> None: + # The fused SwiGLU + MXFP8 quantize is SM107-only; other architectures keep the stock activation and quantize. + monkeypatch.setattr(modeling_minimaxm3, "_CTX_SWIGLU_MXFP8", True) + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: sm) + monkeypatch.setattr(modeling_minimaxm3, "ctx_eager_only", lambda: True) + method = MXFP8LinearMethod.__new__(MXFP8LinearMethod) + method.use_cutlass = True + mlp = SimpleNamespace( + activation=torch.nn.functional.silu, down_proj=SimpleNamespace(quant_method=method) + ) + x = torch.zeros((modeling_minimaxm3._CTX_NORM_MXFP8_MIN_ROWS, 3072), dtype=torch.bfloat16) + assert modeling_minimaxm3._SwigluOaiMLP._swiglu_mxfp8_eligible(mlp, x, False) is expected + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("sm, expected", [(107, True), (100, False), (103, False), (90, False)]) +def test_shared_fold_into_trtllm_gen_finalize_is_sm107_only( + monkeypatch, sm: int, expected: bool +) -> None: + # An otherwise eligible TRTLLM-gen NVFP4 MoE: the fold engages on SM107 (positive control) and, elsewhere, the + # shared expert keeps its separate add after the finalize. + monkeypatch.setattr(modeling_minimaxm3, "_FOLD_SHARED_INTO_FINALIZE", True) + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: sm) + monkeypatch.setattr(modeling_minimaxm3, "ctx_eager_only", lambda: True) + hidden = 64 + backend = TrtllmTrtllmGenNvfp4Impl.__new__(TrtllmTrtllmGenNvfp4Impl) + backend.supports_unfinalized_output = lambda: True + backend._routes_outside_the_kernel = lambda: False + backend.w3_w1_weight = torch.empty((4, 2 * hidden, hidden // 2), dtype=torch.uint8) + experts = SimpleNamespace(backend=backend, moe_max_num_tokens=16) + block = SimpleNamespace( + shared_experts=object(), experts=experts, routed_output_is_global=False, hidden_dim=hidden + ) + x = torch.zeros((8, hidden), dtype=torch.bfloat16) + assert modeling_minimaxm3.MiniMaxM3MoE.fold_shared_ok(block, x, None) is expected + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("sm, hidden", [(103, 3072), (100, 3072), (107, 384), (107, 16384)]) +def test_ctx_boundary_norm_declines_off_rubin_and_off_geometry( + monkeypatch, sm: int, hidden: int +) -> None: + # The fused boundary norm + MXFP8 kernel is SM107-only and needs whole 256-element groups in at most 1024 + # threads; anything else keeps the stock AllReduce + RMSNorm (None) before touching the layer. + monkeypatch.setattr(modeling_minimaxm3, "_CTX_NORM_MXFP8", True) + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: sm) + monkeypatch.setattr(modeling_minimaxm3, "ctx_eager_only", lambda: True) + layer = SimpleNamespace(allreduce=Mock(side_effect=AssertionError("fused boundary norm ran"))) + hidden_states = torch.zeros( + (modeling_minimaxm3._CTX_NORM_MXFP8_MIN_ROWS, hidden), dtype=torch.bfloat16 + ) + norm = SimpleNamespace(weight=torch.ones(hidden, dtype=torch.bfloat16), variance_epsilon=1e-6) + assert ( + modeling_minimaxm3.MiniMaxM3DecoderLayer._reduce_norm_mxfp8( + layer, hidden_states, hidden_states, norm + ) + is None + ) + + +@pytest.mark.skipif(not _has_cuda(), reason="the embedding gather is a Triton kernel") +def test_embedding_gather_matches_f_embedding_for_any_id_layout() -> None: + # The fused gather equals F.embedding with out-of-vocabulary rows zeroed, for contiguous, 2-D and strided ids. + torch.manual_seed(0) + vocab, hidden = 64, 1536 + weight = torch.randn(vocab, hidden, dtype=torch.bfloat16, device="cuda") + base = torch.tensor([1, 5, -1, 7, vocab, 3, 63, 0], dtype=torch.int32, device="cuda") + + def reference(ids: torch.Tensor) -> torch.Tensor: + valid = (ids >= 0) & (ids < vocab) + out = torch.nn.functional.embedding(torch.where(valid, ids, 0).long(), weight) + return out.masked_fill(~valid.unsqueeze(-1), 0) + + for ids in (base, base.view(2, 4), base[::2], base.view(2, 4)[:, 1::2]): + out = modeling_minimaxm3.minimax_m3_embedding_gather(ids, weight) + assert out.shape == (*ids.shape, hidden) + assert torch.equal(out, reference(ids)) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "use_dp, comm, folds", + [(False, None, True), (True, None, False), (False, object(), False)], + ids=["local_tokens", "attention_dp", "moe_communication"], +) +def test_cutedsl_shared_fold_only_without_token_dispatch(monkeypatch, use_dp, comm, folds) -> None: + # With attention DP or MoE communication the finalize rows can be other ranks' tokens, so the shared output of + # this rank's tokens must not be folded into them. + monkeypatch.setattr(modeling_minimaxm3, "_FOLD_SHARED_INTO_FINALIZE", True) + monkeypatch.setattr(modeling_minimaxm3, "_fold_shared_backend", lambda experts: True) + monkeypatch.setattr(modeling_minimaxm3, "ctx_eager_only", lambda: True) + moe = SimpleNamespace( + experts=SimpleNamespace(comm=comm), + aux_stream=object(), + routed_output_is_global=False, + use_dp=use_dp, + ) + assert modeling_minimaxm3.MiniMaxM3MoE.cutedsl_fold_ok(moe) is folds + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("tuning", [False, True]) +def test_ctx_qkv_fused_skips_autotune_pass(monkeypatch, tuning: bool) -> None: + # The fused QKV producer stays out of the AutoTuner warmup pass, so the stock MXFP8 QKV GEMM profiles its shape + # for the steps the producer does not take. + from tensorrt_llm._torch.autotuner import AutoTuner + from tensorrt_llm._torch.models import modeling_minimaxm3 as m3 + + monkeypatch.setattr(AutoTuner.get(), "is_tuning_mode", tuning) + monkeypatch.setattr(m3, "_CTX_QKV_FUSED_YIELD_LOGGED", False) + assert m3._autotuner_tuning() is tuning + # The yield is logged once per process, and only when it happens. + assert m3._CTX_QKV_FUSED_YIELD_LOGGED is tuning diff --git a/tests/unittest/_torch/modules/test_mxfp8_linear.py b/tests/unittest/_torch/modules/test_mxfp8_linear.py index 4efee07ab4da..bcd6c286f25c 100644 --- a/tests/unittest/_torch/modules/test_mxfp8_linear.py +++ b/tests/unittest/_torch/modules/test_mxfp8_linear.py @@ -30,6 +30,7 @@ MXFP8GemmRunner, MXFP8QuantizeRunner, _get_mxfp8_large_m_tuning_buckets, + _get_mxfp8_small_m_buckets, _map_to_mxfp8_large_m_bucket, ) from tensorrt_llm._torch.modules.linear import ( @@ -44,6 +45,7 @@ get_quant_method, ) from tensorrt_llm._torch.modules.mxfp8_utils import dequant_mxfp8_weight, quant_bf16_to_mxfp8 +from tensorrt_llm._utils import get_sm_version from tensorrt_llm.mapping import Mapping from tensorrt_llm.models.modeling_utils import QuantConfig from tensorrt_llm.quantization.mode import QuantAlgo @@ -176,6 +178,7 @@ def _mock_mxfp8_ops( ops=SimpleNamespace(trtllm=fake_trtllm_ops), ones=torch.ones, float32=torch.float32, + compiler=SimpleNamespace(is_compiling=lambda: False), ) monkeypatch.setattr(linear_module, "torch", fake_torch) return ( @@ -407,7 +410,9 @@ def test_mxfp8_auto_fallback_does_not_rearm_native_autotuning(monkeypatch): (32769, 32769), ], ) -def test_mxfp8_large_m_bucket_mapping(num_tokens, expected): +def test_mxfp8_large_m_bucket_mapping(monkeypatch, num_tokens, expected): + # The SM100 / SM103 large-M bands; SM107 adds small-M buckets (covered below). + monkeypatch.setattr(custom_ops_module, "_get_mxfp8_small_m_buckets", lambda: ()) assert _map_to_mxfp8_large_m_bucket(num_tokens) == expected @@ -420,10 +425,23 @@ def test_mxfp8_large_m_bucket_mapping(num_tokens, expected): (29765, (8192, 16384, 32768)), ], ) -def test_mxfp8_large_m_tuning_buckets(max_num_tokens, expected): +def test_mxfp8_large_m_tuning_buckets(monkeypatch, max_num_tokens, expected): + monkeypatch.setattr(custom_ops_module, "_get_mxfp8_small_m_buckets", lambda: ()) assert _get_mxfp8_large_m_tuning_buckets(max_num_tokens) == expected +@pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() != 107, + reason="the native runner has small-M buckets on SM107 only", +) +def test_mxfp8_small_m_buckets_map_first_on_sm107(): + small = _get_mxfp8_small_m_buckets() + assert small and small == tuple(sorted(small)) and small[-1] < 8192 + assert _map_to_mxfp8_large_m_bucket(1) == small[0] + assert _map_to_mxfp8_large_m_bucket(small[-1]) == small[-1] + assert _get_mxfp8_large_m_tuning_buckets(6599) == small + (8192,) + + def test_mxfp8_large_m_cache_profile_maps_act_and_constrains_scale(): AutoTuner._find_nearest_profile.cache_clear() input_shapes = ( diff --git a/tests/unittest/_torch/modules/test_prequantized_mxfp8_streams.py b/tests/unittest/_torch/modules/test_prequantized_mxfp8_streams.py new file mode 100644 index 000000000000..ef02f6c30db9 --- /dev/null +++ b/tests/unittest/_torch/modules/test_prequantized_mxfp8_streams.py @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The one-entry pre-quantized MXFP8 slot (modules/linear.py) across CUDA streams. + +The pair is produced on one stream (the main stream's fused norm) and can be taken on another (the MoE shared +expert's aux stream). The take records the consuming stream on the pair, so once the slot's references are gone the +caching allocator does not hand the pair's memory to a new tensor on the producing stream while the consumer still +reads it. +""" + +import pytest +import torch + +from tensorrt_llm._torch.modules import linear + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") + +N = 1 << 22 + + +def _take_on(stream: torch.cuda.Stream, source: torch.Tensor): + with torch.cuda.stream(stream): + return linear.take_prequantized_mxfp8(source) + + +def test_a_take_on_another_stream_keeps_the_pair_alive_until_the_consumer_reads_it() -> None: + main = torch.cuda.current_stream() + aux = torch.cuda.Stream() + source = torch.empty((N,), dtype=torch.bfloat16, device="cuda") + q = torch.full((N,), 7, dtype=torch.uint8, device="cuda") + sf = torch.full((N // 32,), 9, dtype=torch.uint8, device="cuda") + linear.set_prequantized_mxfp8(source, q, sf, tag="test_streams") + del q, sf # only the slot holds the pair now + aux.wait_stream(main) + pair = _take_on(aux, source) + assert pair is not None + with torch.cuda.stream(aux): + # The consumer is still busy when the producing stream allocates again. + torch.cuda._sleep(200_000_000) + got_q = pair[0].clone() + got_sf = pair[1].clone() + del pair + # The producing stream allocates and writes same-sized tensors while the consumer sleeps. + overwrite = [torch.full((N,), 0x55, dtype=torch.uint8, device="cuda") for _ in range(2)] + overwrite += [torch.full((N // 32,), 0x55, dtype=torch.uint8, device="cuda") for _ in range(2)] + torch.cuda.synchronize() + del overwrite + assert bool((got_q == 7).all()), ( + "the consumer read MXFP8 values the producing stream had reused" + ) + assert bool((got_sf == 9).all()), "the consumer read scales the producing stream had reused" + + +def test_a_take_on_the_producing_stream_records_nothing(monkeypatch) -> None: + recorded = [] + monkeypatch.setattr(torch.Tensor, "record_stream", lambda self, s: recorded.append(s)) + source = torch.empty((1024,), dtype=torch.bfloat16, device="cuda") + q = torch.zeros((1024,), dtype=torch.uint8, device="cuda") + sf = torch.zeros((32,), dtype=torch.uint8, device="cuda") + linear.set_prequantized_mxfp8(source, q, sf, tag="test_streams") + assert linear.take_prequantized_mxfp8(source) is not None + assert recorded == [] + linear.set_prequantized_mxfp8(source, q, sf, tag="test_streams") + aux = torch.cuda.Stream() + assert _take_on(aux, source) is not None + assert recorded == [aux, aux] diff --git a/tests/unittest/_torch/moe/test_cutedsl_rubin_deterministic.py b/tests/unittest/_torch/moe/test_cutedsl_rubin_deterministic.py new file mode 100644 index 000000000000..901d612a606c --- /dev/null +++ b/tests/unittest/_torch/moe/test_cutedsl_rubin_deterministic.py @@ -0,0 +1,197 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Rule 1b gate a for the deterministic CuteDSL NVFP4 MoE on SM107 (FC2 per permuted row + fixed-order +moe_unpermute; SwiGLU-OAI in the FC1 act epilogue), at the MiniMax-M3 EP2 rank shape (64 local experts, hidden 6144, +intermediate 3072, top-4, SwiGLU-OAI alpha 1.702 / beta 1 / limit 7, NVFP4): +- run-to-run determinism: 3 calls bitwise, at two token counts; +- batch independence (fixed permutation / finalize order): a token block's output is bitwise the same whether it runs + alone or inside a larger batch with other tokens; +- band: max abs / max rel error vs the quantize util's reference module (dequantized math) within 1.25x of the stock + TRTLLM-gen backend's error on the same weights and inputs. +The kill switch (TLLM_CUTEDSL_MOE_DETERMINISTIC=0) restores the fused scatter-add FC2.""" + +import pytest +import torch +from _torch.moe.moe_test_utils import MoeBackendType +from _torch.moe.quantize_utils import get_test_quant_params +from _torch.moe.test_moe_backend import create_test_backend, run_backend_moe + +import tensorrt_llm._torch.moe.fused_moe.cutedsl.grouped_gemm.nvfp4 as cute_moe +from tensorrt_llm._torch.autotuner import AutoTuner +from tensorrt_llm._torch.moe.fused_moe import RenormalizeMoeRoutingMethod +from tensorrt_llm._torch.utils import ActivationType +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantAlgo + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability() != (10, 7), + reason="the deterministic CuteDSL FC2 path is SM107 only", +) + +H, INTER, E, TOP_K = 6144, 3072, 64, 4 + + +def _build(backend_type, x): + dtype = torch.bfloat16 + qcls, qcfg, qkw = get_test_quant_params(QuantAlgo.NVFP4, x, backend_type) + qu = qcls( + num_experts=E, dtype=dtype, intermediate_size=INTER, hidden_size=H, quant_config=qcfg, bias=False, + swiglu_gptoss_style=True, swiglu_alpha=1.702, swiglu_beta=1.0, swiglu_limit=7.0, + activation_type=ActivationType.Swiglu, + ) # fmt: skip + sw = qu._swiglu_tensors + routing = RenormalizeMoeRoutingMethod(top_k=TOP_K) + backend = create_test_backend( + backend_type=backend_type, routing_method=routing, num_experts=E, hidden_size=H, intermediate_size=INTER, + dtype=dtype, quant_config=qcfg, mapping=Mapping(), swiglu_alpha=sw["swiglu_alpha"], + swiglu_beta=sw["swiglu_beta"], swiglu_limit=sw["swiglu_limit"], + ) # fmt: skip + return qu, qkw, routing, backend + + +def _run(backend, backend_type, routing, x, logits): + with torch.inference_mode(): + sel, scl = routing.apply(logits) + xq, xsf = backend.quantize_input(x, post_quant_comm=False) + return run_backend_moe( + backend, backend_type, xq, xsf, sel, scl, torch.bfloat16, logits + ).clone() + + +def _err(y, ref): + d = (y.float() - ref.float()).abs() + return float(d.max()), float( + (d / ref.float().abs().amax(dim=1, keepdim=True).clamp_min(1e-30)).max() + ) + + +def test_deterministic_cutedsl_gate_a() -> None: + assert cute_moe._RUBIN_DETERMINISTIC_FC2, "the kill switch is off in this environment" + with torch.device("cuda"): + torch.manual_seed(0) + AutoTuner.get().setup_distributed_state(Mapping()) + big = 8192 + x = torch.randn((big, H), dtype=torch.bfloat16) + logits = torch.randn((big, E), dtype=torch.bfloat16) + qu, qkw, routing, cute = _build(MoeBackendType.CUTEDSL, x) + ref_cls = qkw.pop("ref_cls", None) + weights = qu.create_weights(**qkw) + cute.load_weights([weights]) + cute.post_load_weights() + cute.cuda() + # run-to-run determinism at two token counts + for t in (2048, big): + outs = [ + _run(cute, MoeBackendType.CUTEDSL, routing, x[:t], logits[:t]) for _ in range(3) + ] + for o in outs[1:]: + assert torch.equal(outs[0].view(torch.int16), o.view(torch.int16)), ( + f"not deterministic at {t} tokens" + ) + # batch independence: rows [0, 1024) alone vs inside the full batch + alone = _run(cute, MoeBackendType.CUTEDSL, routing, x[:1024], logits[:1024]) + full = _run(cute, MoeBackendType.CUTEDSL, routing, x, logits) + assert torch.equal(alone.view(torch.int16), full[:1024].view(torch.int16)), ( + "output depends on the batch" + ) + # band vs the reference module, next to stock TRTLLM-gen on the same weights + ref_mod = ( + qu.create_ref_module(routing, ref_cls=ref_cls) + if ref_cls + else qu.create_ref_module(routing) + ) + ref_mod.load_weights([weights]) + ref_mod.cuda() + with torch.inference_mode(): + ref = ref_mod.forward(x, logits) + _, _, _, stock = _build(MoeBackendType.TRTLLM, x) + stock.load_weights([weights]) + stock.post_load_weights() + stock.cuda() + e_cute = _err(full, ref) + e_stock = _err(_run(stock, MoeBackendType.TRTLLM, routing, x, logits), ref) + print( + f"\nGATEA cutedsl det: err vs ref abs {e_cute[0]:.3e} rel {e_cute[1]:.3e} | stock abs {e_stock[0]:.3e} " + f"rel {e_stock[1]:.3e} | ratio abs {e_cute[0] / e_stock[0]:.2f} rel {e_cute[1] / e_stock[1]:.2f}", + flush=True, + ) + assert e_cute[0] <= 1.25 * e_stock[0] and e_cute[1] <= 1.25 * e_stock[1] + + +@pytest.mark.parametrize("tokens", [8192, 16384]) +def test_shared_fold_bitwise(tokens) -> None: + """The shared-expert output offered to the deterministic finalize (TLLM_M3_MOE_FOLD_SHARED) is bitwise + ``shared.add_(routed)``.""" + with torch.device("cuda"): + torch.manual_seed(1) + AutoTuner.get().setup_distributed_state(Mapping()) + x = torch.randn((tokens, H), dtype=torch.bfloat16) + logits = torch.randn((tokens, E), dtype=torch.bfloat16) + shared = (torch.randn((tokens, H)) * 0.5).to(torch.bfloat16) + qu, qkw, routing, cute = _build(MoeBackendType.CUTEDSL, x) + qkw.pop("ref_cls", None) + cute.load_weights([qu.create_weights(**qkw)]) + cute.post_load_weights() + cute.cuda() + + def plain(): + return shared.clone().add_(_run(cute, MoeBackendType.CUTEDSL, routing, x, logits)) + + def folded(): + holder = cute_moe.offer_finalize_residual(shared.clone()) + try: + out = _run(cute, MoeBackendType.CUTEDSL, routing, x, logits) + finally: + cute_moe.clear_finalize_residual() + assert holder.consumed, "the deterministic finalize did not take the residual" + return out + + ref, got = plain(), folded() + assert torch.equal(ref.view(torch.int16), got.view(torch.int16)), ( + "fold is not bitwise the separate add" + ) + + +@pytest.mark.parametrize("tokens", [8192, 16384]) +def test_shared_fold_bitwise_cuda_graph(tokens) -> None: + """The folded deterministic finalize captured in a CUDA graph and replayed is bitwise the eager + ``shared.add_(routed)`` (the fold's arithmetic does not depend on the launch mode).""" + with torch.device("cuda"): + torch.manual_seed(1) + AutoTuner.get().setup_distributed_state(Mapping()) + x = torch.randn((tokens, H), dtype=torch.bfloat16) + logits = torch.randn((tokens, E), dtype=torch.bfloat16) + shared = (torch.randn((tokens, H)) * 0.5).to(torch.bfloat16) + qu, qkw, routing, cute = _build(MoeBackendType.CUTEDSL, x) + qkw.pop("ref_cls", None) + cute.load_weights([qu.create_weights(**qkw)]) + cute.post_load_weights() + cute.cuda() + ref = shared.clone().add_(_run(cute, MoeBackendType.CUTEDSL, routing, x, logits)) + residual = shared.clone() + + def folded(): + holder = cute_moe.offer_finalize_residual(residual) + try: + return _run(cute, MoeBackendType.CUTEDSL, routing, x, logits), holder + finally: + cute_moe.clear_finalize_residual() + + side = torch.cuda.Stream() + side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side): + for _ in range(2): # warm-up outside capture (autotuning, allocations) + residual.copy_(shared) + folded() + torch.cuda.current_stream().wait_stream(side) + graph = torch.cuda.CUDAGraph() + residual.copy_(shared) + with torch.cuda.graph(graph): + out, holder = folded() + assert holder.consumed, "the captured deterministic finalize did not take the residual" + residual.copy_(shared) + graph.replay() + torch.cuda.synchronize() + assert torch.equal(ref.view(torch.int16), out.view(torch.int16)), ( + "captured fold is not bitwise the separate add" + ) diff --git a/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py b/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py new file mode 100644 index 000000000000..763032a5852b --- /dev/null +++ b/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax M3's SwigluBias (SwiGLU-OAI) MoE must resolve THROUGH backend resolution to CuteDslFusedMoE on SM107 +NVFP4 with the deterministic FC2 (CTX-7), and must be declined everywhere else: expert biases, the +non-deterministic FC2, other SMs. Gates the dispatch, not the op.""" + +import pytest +import torch +from transformers.configuration_utils import PretrainedConfig + +import tensorrt_llm._torch.moe.fused_moe.cutedsl.grouped_gemm.nvfp4 as cute_moe +from tensorrt_llm._torch.model_config import ModelConfig +from tensorrt_llm._torch.moe.fused_moe import RenormalizeMoeRoutingMethod +from tensorrt_llm._torch.moe.fused_moe.activation import SwigluBiasActivation +from tensorrt_llm._torch.moe.fused_moe.create_moe import create_moe +from tensorrt_llm._torch.moe.fused_moe.impl_contract import MoEDeployment, MoERejectReason +from tensorrt_llm._torch.moe.fused_moe.impl_environment import MoEDep, MoEEnvironment +from tensorrt_llm._torch.moe.fused_moe.moe_resolution import ( + build_moe_problem, + impl_class_for, + infer_swiglu_gptoss_style, + resolve_moe_impl, +) +from tensorrt_llm._utils import get_sm_version +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantAlgo, QuantConfig + +# M3's constants (modeling_minimaxm3: alpha 1.702, beta 1, limit 7). +_M3_ACT = SwigluBiasActivation(gate_sigmoid_scale=1.702, linear_offset=1.0, clamp=7.0) +_SHAPE = dict(num_experts=8, hidden_size=512, intermediate_size=256) + + +def _model_config(): + pretrained = PretrainedConfig() + pretrained.torch_dtype = torch.bfloat16 + return ModelConfig( + pretrained_config=pretrained, + mapping=Mapping(world_size=1, rank=0, tp_size=1), + moe_backend="CUTEDSL", + quant_config=QuantConfig(quant_algo=QuantAlgo.NVFP4, group_size=16), + ) + + +def _deployment(sm): + return MoEDeployment( + ep_size=1, + tp_size=1, + use_dp=False, + num_slots=_SHAPE["num_experts"], + env=MoEEnvironment(sm=sm, available_deps=(MoEDep.CUTEDSL_RUBIN.value,)), + parallel_size=1, + ) + + +def _resolve(sm, bias=False): + return resolve_moe_impl( + _model_config(), + deployment=_deployment(sm), + dtype=torch.bfloat16, + swiglu_gptoss_style=infer_swiglu_gptoss_style(bias=bias, activation_type=_M3_ACT.kind), + bias=bias, + activation=_M3_ACT, + allow_degradation=True, + **_SHAPE, + ) + + +@pytest.mark.cpu_only +def test_m3_swiglu_bias_resolves_to_cutedsl_on_sm107(monkeypatch) -> None: + monkeypatch.setattr(cute_moe, "_RUBIN_DETERMINISTIC_FC2", True) + report = _resolve(107) + assert not report.degraded, report + assert impl_class_for(report) is cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("case", ["nondeterministic_fc2", "expert_bias", "sm100"]) +def test_swiglu_bias_declined_outside_the_deterministic_rubin_path(monkeypatch, case) -> None: + monkeypatch.setattr(cute_moe, "_RUBIN_DETERMINISTIC_FC2", case != "nondeterministic_fc2") + sm, bias = (100, False) if case == "sm100" else (107, case == "expert_bias") + problem = build_moe_problem( + _model_config(), + dtype=torch.bfloat16, + swiglu_gptoss_style=infer_swiglu_gptoss_style(bias=bias, activation_type=_M3_ACT.kind), + bias=bias, + activation=_M3_ACT, + **_SHAPE, + ) + verdict = cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl.can_implement(problem, _deployment(sm)) + assert not verdict.eligible + assert verdict.reject_reason is MoERejectReason.ACTIVATION_UNSUPPORTED + + +@pytest.mark.skipif( + not torch.cuda.is_available() or get_sm_version() != 107, reason="SM107 (Rubin) only" +) +def test_m3_create_moe_builds_cutedsl_on_this_gpu() -> None: + """The real environment probe, the real create_moe path M3 takes, no degradation allowed.""" + if not cute_moe._RUBIN_DETERMINISTIC_FC2: + pytest.skip("TLLM_CUTEDSL_MOE_DETERMINISTIC=0") + with torch.device("cuda"): + moe = create_moe( + routing_method=RenormalizeMoeRoutingMethod(top_k=2), + dtype=torch.bfloat16, + model_config=_model_config(), + activation=_M3_ACT, + allow_backend_degradation=False, + layer_idx=0, + **_SHAPE, + ) + assert isinstance(moe.backend, cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl), type(moe.backend) diff --git a/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py b/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py new file mode 100644 index 000000000000..e11809712fad --- /dev/null +++ b/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py @@ -0,0 +1,136 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate a for the M3 CTX shared-add fold (TLLM_M3_MOE_FOLD_SHARED): through the real dispatch (create_moe with the +TRTLLM backend, MiniMaxM3MoeRoutingMethod with a correction bias and routed scaling 2.0, SwigluBiasActivation), +fold_shared_into_finalize(experts(..., do_finalize=False), shared) must equal experts(...) then shared.add_ bit for +bit, with the experts input as bf16 (CTX's NVFP4 slot killed) and as the slot's unswizzled Fp4QuantizedTensor (slot +engaged), at CTX chunk sizes; and it must be run-to-run deterministic. With routing outside the kernel the triple's +expert_weights is never written, so the fold must be refused there.""" + +from types import SimpleNamespace + +import pytest +import torch +from _torch.moe.moe_test_utils import MoeBackendType +from _torch.moe.quantize_utils import get_test_quant_params +from transformers.configuration_utils import PretrainedConfig + +import tensorrt_llm._torch.models.modeling_minimaxm3 as modeling_minimaxm3 +import tensorrt_llm._torch.moe.fused_moe.moe_scheduler as moe_scheduler +import tensorrt_llm._torch.moe.fused_moe.trtllm_gen.base as trtllm_gen_base +from tensorrt_llm._torch.autotuner import AutoTuner +from tensorrt_llm._torch.model_config import ModelConfig +from tensorrt_llm._torch.models.modeling_minimaxm3 import MiniMaxM3MoE, fold_shared_into_finalize +from tensorrt_llm._torch.moe.fused_moe.activation import SwigluBiasActivation +from tensorrt_llm._torch.moe.fused_moe.create_moe import create_moe +from tensorrt_llm._torch.moe.fused_moe.routing import MiniMaxM3MoeRoutingMethod +from tensorrt_llm._torch.utils import ActivationType, Fp4QuantizedTensor +from tensorrt_llm._utils import get_sm_version +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantAlgo + +# TP2 / EP2 CTX rank shape is 64 local experts; one GPU here: 64 experts, top-4, the M3 widths. +H, INTER, E, TOP_K = 6144, 3072, 64, 4 +ACT = SwigluBiasActivation(gate_sigmoid_scale=1.702, linear_offset=1.0, clamp=7.0) + +pytestmark = pytest.mark.skipif( + get_sm_version() not in (100, 103, 107), reason="TRTLLM-gen NVFP4 MoE" +) + + +def _build(tokens): + AutoTuner.get().setup_distributed_state(Mapping()) + g = torch.Generator(device="cuda").manual_seed(0) + x = torch.randn((tokens, H), device="cuda", generator=g).to(torch.bfloat16) + bias = (0.05 * torch.randn(E, device="cuda", generator=g)).float() + logits = ( + x.float() @ (torch.randn((E, H), device="cuda", generator=g) / H**0.5).t() + ).contiguous() + shared = (0.5 * torch.randn((tokens, H), device="cuda", generator=g)).to(torch.bfloat16) + routing = MiniMaxM3MoeRoutingMethod(top_k=TOP_K, num_experts=E, callable_e_score_correction_bias=lambda: bias, + routed_scaling_factor=2.0) # fmt: skip + torch.manual_seed(0) + qcls, qcfg, qkw = get_test_quant_params(QuantAlgo.NVFP4, x, MoeBackendType.TRTLLM) + qu = qcls(num_experts=E, dtype=torch.bfloat16, intermediate_size=INTER, hidden_size=H, quant_config=qcfg, + bias=False, swiglu_gptoss_style=True, swiglu_alpha=1.702, swiglu_beta=1.0, swiglu_limit=7.0, + activation_type=ActivationType.Swiglu) # fmt: skip + qkw.pop("ref_cls", None) + weights = qu.create_weights(**qkw) + pc = PretrainedConfig() + pc.torch_dtype = torch.bfloat16 + mc = ModelConfig(pretrained_config=pc, mapping=Mapping(world_size=1, rank=0, tp_size=1), moe_backend="TRTLLM", + quant_config=qcfg, moe_max_num_tokens=32768) # fmt: skip + moe = create_moe(routing_method=routing, num_experts=E, hidden_size=H, intermediate_size=INTER, + dtype=torch.bfloat16, model_config=mc, activation=ACT, allow_backend_degradation=False, + layer_idx=3) # fmt: skip + moe.load_weights([weights]) + moe.post_load_weights() + moe.cuda() + return moe, x, logits, shared + + +@pytest.mark.parametrize("slot", ["killed", "engaged"]) +@pytest.mark.parametrize("tokens", [4096, 16384]) +def test_fold_shared_bitwise(tokens, slot) -> None: + with torch.device("cuda"), torch.inference_mode(): + moe, x, logits, shared = _build(tokens) + backend = moe.backend + assert type(backend).__name__ == "TrtllmTrtllmGenNvfp4Impl", type(backend) + assert backend.supports_unfinalized_output() and moe.comm is None + if slot == "engaged": # CTX's fused pre-MoE norm hand-off (TRTLLM_CTX_NORM_FP4=1) + fp4, sf = torch.ops.trtllm.fp4_quantize(x, backend.fc31_input_scale, 16, False, False) + inp = Fp4QuantizedTensor(fp4, sf, is_sf_swizzled=False, unquantized_hidden_states=x) + kw = {"output_dtype": torch.bfloat16} + else: + inp, kw = x, {} + stock = shared.clone().add_(moe(inp, logits, **kw)) + outs = [] + for _ in range(3): + unfinalized = moe(inp, logits, do_finalize=False, **kw) + assert isinstance(unfinalized, (list, tuple)) and len(unfinalized) == 3 + outs.append(fold_shared_into_finalize(unfinalized, shared, TOP_K).clone()) + for o in outs: + assert torch.equal(o.view(torch.int16), stock.view(torch.int16)), ( + "fold != finalize + add_" + ) + print(f"\nFOLDGATE T={tokens} slot={slot}: bitwise vs finalize + add_ x3 PASS", flush=True) + + +def _fold_ok(moe, x) -> bool: + block = SimpleNamespace( + shared_experts=object(), experts=moe, routed_output_is_global=False, hidden_dim=H + ) + return MiniMaxM3MoE.fold_shared_ok(block, x, None) + + +def test_fold_shared_refused_with_separated_routing(monkeypatch) -> None: + tokens = 512 + monkeypatch.setattr(modeling_minimaxm3, "_FOLD_SHARED_INTO_FINALIZE", True) + # The fold engages on SM107 only; pin it so the routing checks below are exercised on every SM10x. + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: 107) + with torch.device("cuda"), torch.inference_mode(): + moe, x, logits, shared = _build(tokens) + assert _fold_ok(moe, x), "fold must stay enabled when the kernel routes from the logits" + for sm in (100, 103): + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda sm=sm: sm) + assert not _fold_ok(moe, x), f"fold must stay off on SM{sm}" + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: 107) + + monkeypatch.setattr(trtllm_gen_base, "FORCE_SEPARATED_ROUTING", True) + monkeypatch.setattr(moe_scheduler, "FORCE_SEPARATED_ROUTING", True) + assert moe.backend._routes_outside_the_kernel() + stock = shared.clone().add_(moe(x, logits)) + # The runner finalizes with the precomputed top-k weights and returns an expert_weights tensor it never + # writes: poison the allocator's free blocks so the unwritten tensor cannot alias a copy of those weights. + poison = [ + torch.full((tokens, TOP_K), float("nan"), dtype=torch.bfloat16) for _ in range(64) + ] + del poison + unfinalized = moe(x, logits, do_finalize=False) + folded = fold_shared_into_finalize(unfinalized, shared, TOP_K) + assert not torch.equal(folded.view(torch.int16), stock.view(torch.int16)), ( + "expected the unwritten expert_weights to corrupt the fold" + ) + assert not _fold_ok(moe, x), ( + "fold must be refused when top-k is precomputed outside the kernel" + ) diff --git a/tests/unittest/_torch/moe/test_m3_router_tc_fp4_moe.py b/tests/unittest/_torch/moe/test_m3_router_tc_fp4_moe.py new file mode 100644 index 000000000000..0148a2b89e7f --- /dev/null +++ b/tests/unittest/_torch/moe/test_m3_router_tc_fp4_moe.py @@ -0,0 +1,93 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""SM107 generation steps of 9..16 rows: the TF32 tensor-core router's NVFP4 activation as the routed experts' input +(TRTLLM_M3_ROUTER_TC_FP4_MOE), through the real dispatch (create_moe with the TRTLLM backend, MiniMaxM3MoeRoutingMethod, +SwigluBiasActivation, 128 experts at the M3 hidden size). + +router_tc's payload must equal fp4_quantize(x, fc31_input_scale, 16, False, False) bit for bit, and the experts fed that +payload as an unswizzled Fp4QuantizedTensor must equal the experts fed bf16 x bit for bit, so handing the payload over +removes the experts' own quantize without changing the MoE output.""" + +import pytest +import torch +from _torch.moe.moe_test_utils import MoeBackendType +from _torch.moe.quantize_utils import get_test_quant_params +from transformers.configuration_utils import PretrainedConfig + +from tensorrt_llm._torch.autotuner import AutoTuner +from tensorrt_llm._torch.model_config import ModelConfig +from tensorrt_llm._torch.models import modeling_minimaxm3 as mm +from tensorrt_llm._torch.models.modeling_minimaxm3 import MiniMaxM3Gate +from tensorrt_llm._torch.moe.fused_moe.activation import SwigluBiasActivation +from tensorrt_llm._torch.moe.fused_moe.create_moe import create_moe +from tensorrt_llm._torch.moe.fused_moe.routing import MiniMaxM3MoeRoutingMethod +from tensorrt_llm._torch.utils import ActivationType, Fp4QuantizedTensor +from tensorrt_llm._utils import get_sm_version +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantAlgo + +H, INTER, E, TOP_K = 6144, 1536, 128, 4 +ACT = SwigluBiasActivation(gate_sigmoid_scale=1.702, linear_offset=1.0, clamp=7.0) + +pytestmark = pytest.mark.skipif(get_sm_version() != 107, reason="SM107 (Rubin) only") + + +def _build(tokens): + AutoTuner.get().setup_distributed_state(Mapping()) + g = torch.Generator(device="cuda").manual_seed(0) + x = torch.randn((tokens, H), device="cuda", generator=g).to(torch.bfloat16) + bias = (0.05 * torch.randn(E, device="cuda", generator=g)).float() + routing = MiniMaxM3MoeRoutingMethod(top_k=TOP_K, num_experts=E, callable_e_score_correction_bias=lambda: bias, + routed_scaling_factor=2.0) # fmt: skip + torch.manual_seed(0) + qcls, qcfg, qkw = get_test_quant_params(QuantAlgo.NVFP4, x, MoeBackendType.TRTLLM) + qu = qcls(num_experts=E, dtype=torch.bfloat16, intermediate_size=INTER, hidden_size=H, quant_config=qcfg, + bias=False, swiglu_gptoss_style=True, swiglu_alpha=1.702, swiglu_beta=1.0, swiglu_limit=7.0, + activation_type=ActivationType.Swiglu) # fmt: skip + qkw.pop("ref_cls", None) + weights = qu.create_weights(**qkw) + pc = PretrainedConfig() + pc.torch_dtype = torch.bfloat16 + mc = ModelConfig(pretrained_config=pc, mapping=Mapping(world_size=1, rank=0, tp_size=1), moe_backend="TRTLLM", + quant_config=qcfg, moe_max_num_tokens=8192) # fmt: skip + moe = create_moe(routing_method=routing, num_experts=E, hidden_size=H, intermediate_size=INTER, + dtype=torch.bfloat16, model_config=mc, activation=ACT, allow_backend_degradation=False, + layer_idx=3) # fmt: skip + moe.load_weights([weights]) + moe.post_load_weights() + moe.cuda() + gate = MiniMaxM3Gate(H, E, TOP_K, 1.0).cuda() + gate.weight.data.copy_((torch.randn(E, H, device="cuda", generator=g) / H**0.5).float()) + return moe, gate, x + + +@pytest.mark.parametrize("tokens", [9, 12, 16]) +def test_router_tc_payload_feeds_experts_bitwise(tokens, monkeypatch) -> None: + if not torch.ops.trtllm.minimax_m3_router_tc_cluster16(H): + pytest.skip("this device cannot co-schedule 16-CTA clusters (router_tc not used)") + monkeypatch.setattr( + mm, "_ROUTER_TC_GEN", True + ) # default OFF until its gates pass: the gate below must take router_tc + with torch.device("cuda"), torch.inference_mode(): + moe, gate, x = _build(tokens) + backend = moe.backend + assert type(backend).__name__ == "TrtllmTrtllmGenNvfp4Impl", type(backend) + scale = backend.fc31_input_scale + logits, q, sf = gate.router_tc_with_fp4(x, scale) + assert torch.equal(logits, gate(x, generation_only=True)), ( + "payload launch changed the logits" + ) + ref_q, ref_sf = torch.ops.trtllm.fp4_quantize(x, scale, 16, False, False) + assert torch.equal(q.view(torch.uint8).flatten(), ref_q.view(torch.uint8).flatten()), ( + "packed e2m1 differs" + ) + assert torch.equal(sf.view(torch.uint8).flatten(), ref_sf.view(torch.uint8).flatten()), ( + "block scales differ" + ) + stock = moe(x, logits) + handed = moe( + Fp4QuantizedTensor(q, sf, is_sf_swizzled=False, unquantized_hidden_states=x), + logits, + output_dtype=torch.bfloat16, + ) + assert torch.equal(stock.view(torch.int16), handed.view(torch.int16)), "MoE output differs" diff --git a/tests/unittest/_torch/moe/test_router_gemm_tf32.py b/tests/unittest/_torch/moe/test_router_gemm_tf32.py new file mode 100644 index 000000000000..7e7d6337cb89 --- /dev/null +++ b/tests/unittest/_torch/moe/test_router_gemm_tf32.py @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gate a for the batch-invariant TF32 router GEMM at the M3 gate shape ([M, 6144] x [6144, 128]): rows bitwise +identical for every M (the breakable-prefill buckets included), run to run; error vs fp64 no worse than the stock +router (fp32 F.linear with TF32 allowed); top-4 (sigmoid + bias) close to stock. The split-K kernel (default) and the +single-pass kernel (kill TRTLLM_CTX_ROUTER_TF32_SPLITK=0) each meet all of it.""" + +import pytest +import torch +import torch.nn.functional as F + +from tensorrt_llm._torch.moe.fused_moe import router_gemm_tf32 as rgt +from tensorrt_llm._torch.moe.fused_moe.router_gemm_tf32 import ( + prepare_router_weight_tf32, + router_gemm_tf32, +) + +H, E, TOP_K = 6144, 128, 4 + + +@pytest.fixture(scope="module") +def data(): + g = torch.Generator(device="cuda").manual_seed(11) + x = torch.randn(16384, H, device="cuda", generator=g).to(torch.bfloat16) + w = (torch.randn(E, H, device="cuda", generator=g) / H**0.5).float().contiguous() + bias = (0.05 * torch.randn(E, device="cuda", generator=g)).float() + return x, w, prepare_router_weight_tf32(w), bias + + +def test_prepare_is_cvt_rna(data) -> None: + _, w, wr, _ = data + # TF32 keeps 10 mantissa bits: the low 13 are zero and |wr - w| <= half a TF32 ulp + assert int((wr.view(torch.int32) & 0x1FFF).abs().max()) == 0 + ulp = torch.ldexp(torch.ones_like(w), torch.frexp(w)[1] - 11) + assert bool(((wr - w).abs() <= ulp / 2).all()) + + +def test_m_invariant_and_deterministic(data) -> None: + x, _, wr, _ = data + full = router_gemm_tf32(x, wr) + capped = router_gemm_tf32(x[: rgt.SPLITK_MAX_M].contiguous(), wr) + for _ in range(3): + assert torch.equal(router_gemm_tf32(x, wr).view(torch.int32), full.view(torch.int32)) + for m in ( + 0, + 1, + 2, + 13, + 32, + 48, + 64, + 127, + 128, + 129, + 256, + 512, + 1024, + 1160, + 2048, + 4096, + 7304, + 8192, + 12288, + 14336, + 16383, + ): + o = router_gemm_tf32(x[:m].contiguous(), wr) + assert o.shape == (m, E) + ref = ( + capped if m <= rgt.SPLITK_MAX_M else full + ) # M-invariant within each side of the split-K cap + assert torch.equal(o.view(torch.int32), ref[:m].view(torch.int32)), f"rows differ at M={m}" + + +def test_error_and_top4_vs_stock(data) -> None: + x, w, wr, bias = data + ref64 = x.double() @ w.double().t() + prev = torch.backends.cuda.matmul.allow_tf32 + try: + torch.backends.cuda.matmul.allow_tf32 = ( + True # stock: NGC TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1 + ) + stock = F.linear(x.float(), w) + finally: + torch.backends.cuda.matmul.allow_tf32 = prev + mine = router_gemm_tf32(x, wr) + err_stock = float((stock.double() - ref64).abs().max()) + err_mine = float((mine.double() - ref64).abs().max()) + assert err_mine <= 1.05 * err_stock, (err_mine, err_stock) + + def top4(lg): + return torch.topk(torch.sigmoid(lg) + bias, TOP_K, dim=1).indices.sort(dim=1).values + + flips = int((top4(mine) != top4(stock)).any(1).sum()) + assert flips <= x.shape[0] // 1000, flips # near-ties only + + +def test_cuda_graph(data) -> None: + x, _, wr, _ = data + for m in (1, 512, 1024): # CTX piecewise graph pieces + xs = x[:m].clone() + eager = router_gemm_tf32(xs, wr) + g = torch.cuda.CUDAGraph() + with torch.cuda.graph(g): + out = router_gemm_tf32(xs, wr) + xs.copy_(x[m : 2 * m]) + g.replay() + torch.cuda.synchronize() + assert torch.equal( + out.view(torch.int32), router_gemm_tf32(x[m : 2 * m].contiguous(), wr).view(torch.int32) + ) + assert not torch.equal(out, eager) + + +@pytest.mark.threadleak(enabled=False) # torch.compile starts a tqdm monitor thread +def test_torch_compile(data) -> None: + x, _, wr, _ = data + compiled = torch.compile( + lambda a, b: torch.ops.trtllm.router_gemm_tf32(a, b), fullgraph=True, dynamic=True + ) + for m in (1, 7, 1024): + assert torch.equal( + compiled(x[:m], wr).view(torch.int32), router_gemm_tf32(x[:m], wr).view(torch.int32) + ) + + +@pytest.fixture(params=[True, False], ids=["splitk", "single_pass"]) +def kernel_mode(request, monkeypatch): + monkeypatch.setattr(rgt, "SPLITK", request.param) + return request.param + + +def test_both_kernels_m_invariant_and_error(data, kernel_mode) -> None: + x, w, wr, _ = data + x = x[: rgt.SPLITK_MAX_M].contiguous() # the split kernel's side of the cap + full = router_gemm_tf32(x, wr) + for m in (1, 32, 129, 512, 2048, 4096, rgt.SPLITK_MAX_M - 1): + o = router_gemm_tf32(x[:m].contiguous(), wr) + assert torch.equal(o.view(torch.int32), full[:m].view(torch.int32)), (kernel_mode, m) + ref64 = x.double() @ w.double().t() + prev = torch.backends.cuda.matmul.allow_tf32 + try: + torch.backends.cuda.matmul.allow_tf32 = True + stock = F.linear(x.float(), w) + finally: + torch.backends.cuda.matmul.allow_tf32 = prev + assert float((full.double() - ref64).abs().max()) <= 1.05 * float( + (stock.double() - ref64).abs().max() + ) + + +def test_kill_switch_is_the_single_pass_kernel(data, monkeypatch) -> None: + x, _, wr, _ = data + monkeypatch.setattr(rgt, "SPLITK", False) + single = router_gemm_tf32(x[:2048].contiguous(), wr) + monkeypatch.setattr(rgt, "SPLITK", True) + split = router_gemm_tf32(x[:2048].contiguous(), wr) + assert not torch.equal( + split.view(torch.int32), single.view(torch.int32) + ) # split-K engaged by default + assert float((split - single).abs().max()) < 1e-3 + + +def test_split_k_cap_keeps_the_single_pass_kernel_above(data, monkeypatch) -> None: + x, _, wr, _ = data + m = rgt.SPLITK_MAX_M + 1 + monkeypatch.setattr(rgt, "SPLITK", False) + single = router_gemm_tf32(x[:m].contiguous(), wr) + monkeypatch.setattr(rgt, "SPLITK", True) + above = router_gemm_tf32(x[:m].contiguous(), wr) + assert torch.equal( + above.view(torch.int32), single.view(torch.int32) + ) # bitwise to the kill above the cap + + +#: Rows of the prefill router calls the oracle covers: one-row and small chunks, the breakable-prefill buckets, and the +#: split-K cap. +ORACLE_ROWS = (1, 7, 32, 129, 512, 2048, 4096, 8192) + + +@pytest.mark.parametrize("m", ORACLE_ROWS) +def test_split_k_matches_the_single_pass_kernel_within_the_stated_bound( + data, monkeypatch, m +) -> None: + """The split-K kernel against the single-pass kernel (the kill) at the router shape [m, 6144] x [6144, 128]. + + STATED TOLERANCE. Both kernels multiply the same TF32 operands exactly into fp32 and differ only in the order + of the fp32 additions (K split into SPLIT_K slices whose partials are summed in slice order, vs one serial chain). + For any summation order, an fp32 sum of K products is within gamma_K * sum_k |x_k w_k| of the exact sum, with + gamma_K = K u / (1 - K u) and u = 2**-24; so the two kernels differ by at most + |split - single| <= 2 * gamma_K * sum_k |x_k| |w_k| (per logit, K = 6144), + which this test asserts element-wise. It also asserts the routing outcome: the top-4 experts (sigmoid + bias) + differ on at most m // 1000 rows (near-ties only), the stock router comparison's own allowance.""" + x, _, wr, bias = data + x = x[:m].contiguous() + monkeypatch.setattr(rgt, "SPLITK", False) + single = router_gemm_tf32(x, wr) + monkeypatch.setattr(rgt, "SPLITK", True) + split = router_gemm_tf32(x, wr) + k = x.shape[1] + u = 2.0**-24 + gamma = k * u / (1.0 - k * u) + bound = 2.0 * gamma * (x.double().abs() @ wr.double().abs().t()) + diff = (split.double() - single.double()).abs() + print( + f"ROUTERTF32 split vs single M={m}: max |d| {float(diff.max()):.3e}, " + f"max d / bound {float((diff / bound).max()):.3e}" + ) + assert bool((diff <= bound).all()), ( + f"M={m}: {int((diff > bound).sum())} logits outside the stated bound" + ) + + def top4(lg): + return torch.topk(torch.sigmoid(lg) + bias, TOP_K, dim=1).indices.sort(dim=1).values + + flips = int((top4(split) != top4(single)).any(1).sum()) + assert flips <= m // 1000, (m, flips) diff --git a/tests/unittest/_torch/moe/test_unpermute_residual.py b/tests/unittest/_torch/moe/test_unpermute_residual.py new file mode 100644 index 000000000000..9eaa2d166c30 --- /dev/null +++ b/tests/unittest/_torch/moe/test_unpermute_residual.py @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""unpermute_residual is bitwise moe_unpermute_inplace (+ the ATen bf16 add of the residual), on adversarial data where +the top-k summation order and the fma contraction matter: mixed magnitudes (1e-3 .. 1e3), cancellation (paired +x / -x +rows), fp32 scales with full mantissas, -1 (non-local) slots, and the M3 CTX rank shape.""" + +import pytest +import torch + +import tensorrt_llm._torch.custom_ops # noqa: F401 (registers torch.ops.trtllm) +import tensorrt_llm._torch.moe.fused_moe.unpermute_residual as ur + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA only") + + +def _case(t, hidden, top_k, seed): + g = torch.Generator(device="cuda").manual_seed(seed) + m = t * top_k + mag = 10.0 ** torch.randint(-3, 4, (m, 1), device="cuda", generator=g).float() + rows = (torch.randn(m, hidden, device="cuda", generator=g) * mag).to(torch.bfloat16) + rows[1::2] = -rows[0::2] * 1.0009765625 # near-cancelling neighbours + perm = torch.randperm(m, device="cuda", generator=g).int() + e2p = perm.clone() + e2p[torch.rand(m, device="cuda", generator=g) < 0.4] = -1 # non-local experts + scales = torch.rand(t, top_k, device="cuda", generator=g) * 1.7 + 1e-3 + res = (torch.randn(t, hidden, device="cuda", generator=g) * 50.0).to(torch.bfloat16) + return rows, e2p.view(t, top_k), scales, res + + +@pytest.mark.parametrize("t,hidden", [(97, 6144), (2048, 6144)]) +def test_bitwise_vs_moe_unpermute_plus_add(t, hidden) -> None: + top_k = 4 + rows, e2p, scales, res = _case(t, hidden, top_k, 7 + t) + ref = torch.empty(t, hidden, dtype=torch.bfloat16, device="cuda") + torch.ops.trtllm.moe_unpermute_inplace( + permuted_input=rows, output=ref, expanded_idx_to_permuted_idx=e2p, topk_scales=scales + ) + ref_add = res.clone().add_(ref) + match = {} + for contract in (True, False): + o = torch.empty_like(ref) + ur.unpermute_residual(rows, o, e2p, scales, None, contract) + o2 = torch.empty_like(ref) + ur.unpermute_residual(rows, o2, e2p, scales, res, contract) + match[contract] = (torch.equal(o.view(torch.int16), ref.view(torch.int16)), + torch.equal(o2.view(torch.int16), ref_add.view(torch.int16))) # fmt: skip + print(f"\nUNPERM t={t}: contract {match[True]} separate {match[False]}", flush=True) + assert all(match[True]), "the fma form must reproduce moe_unpermute (+ add) bit for bit" + + +@pytest.mark.parametrize("t", [16384, 32768]) +def test_every_launch_config_bitwise(t, monkeypatch) -> None: + """Every (BLOCK, num_warps) launch config of unpermute_residual (with residual) is bitwise moe_unpermute_inplace + + add_ at the CTX shape (hidden 6144, top-4, 50 % local rows).""" + hidden, top_k = 6144, 4 + rows, e2p, scales, res = _case(t, hidden, top_k, 3) + ref = torch.empty(t, hidden, dtype=torch.bfloat16, device="cuda") + torch.ops.trtllm.moe_unpermute_inplace( + permuted_input=rows, output=ref, expanded_idx_to_permuted_idx=e2p, topk_scales=scales + ) + want = res.clone().add_(ref) + out = torch.empty_like(ref) + for block in (512, 1024, 2048): + for warps in (2, 4, 8): + monkeypatch.setattr(ur, "_CFG", (block, warps)) + ur.unpermute_residual(rows, out, e2p, scales, res) + assert torch.equal(out.view(torch.int16), want.view(torch.int16)), (block, warps) diff --git a/tests/unittest/_torch/peft/test_moe_lora_model_path.py b/tests/unittest/_torch/peft/test_moe_lora_model_path.py index a9af087646cb..adcda4905a2a 100644 --- a/tests/unittest/_torch/peft/test_moe_lora_model_path.py +++ b/tests/unittest/_torch/peft/test_moe_lora_model_path.py @@ -103,6 +103,10 @@ def test_model_moe_forward_passes_lora_params_to_routed_experts( ) if moe_cls is MiniMaxM2MoE: fake_self.hidden_dim = hidden_dim + if moe_cls is MiniMaxM3MoE: + fake_self._prequantized_fp4 = None + # LoRA disables the shared-expert fold (the real check needs a GPU for the SM version). + fake_self.fold_shared_ok = lambda hidden_states, lora_params: False moe_cls.forward( fake_self, @@ -388,6 +392,10 @@ def run_both(routed_fn, shared_fn, *_args, **_kwargs): event_dict=MagicMock(), aux_stream=object(), allreduce=None, + _prequantized_fp4=None, + # LoRA disables both shared-expert folds (the real checks need a GPU). + fold_shared_ok=lambda hidden_states, lora_params: False, + cutedsl_fold_ok=lambda: False, ) with patch.object(minimaxm3_module, "maybe_execute_in_parallel", side_effect=run_both): m3_output = MiniMaxM3MoE.forward( diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py index 1cc4847fe19b..1b596ef343ae 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py @@ -5202,6 +5202,162 @@ def test_replay_only_batch_clears_deferred_generation_overlap_state( manager.try_allocate_generation.assert_called_with(decoding) +# =========================================================================== +# Context append reserve: shortest-first order behind the first request +# =========================================================================== + + +class TestAppendReserveShortestFirst: + """The first context request keeps its place and its max_num_tokens - R chunk; the requests behind it share the + reserve shortest-uncached-first (TLLM_CTX_APPEND_RESERVE_SJF=0 keeps arrival order).""" + + @pytest.fixture(autouse=True) + def _reserve_env(self, monkeypatch): + for name in ( + "TLLM_CTX_APPEND_RESERVE", + "TLLM_CTX_APPEND_RESERVE_ADAPTIVE", + "TLLM_CTX_APPEND_RESERVE_SJF", + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("TLLM_CTX_APPEND_RESERVE", "2048") + + def _schedule(self, mgr, reqs): + sched = make_scheduler(mgr, max_num_tokens=8192, ctx_chunk_config=(None, 64)) + return sched.schedule_request(reqs, set()) + + def test_reserve_is_opt_in(self, monkeypatch): + """Without TLLM_CTX_APPEND_RESERVE the scheduler keeps the full max_num_tokens chunk and arrival order.""" + monkeypatch.delenv("TLLM_CTX_APPEND_RESERVE") + sched = make_scheduler( + make_kv_cache_manager(tokens_per_block=64), + max_num_tokens=8192, + ctx_chunk_config=(None, 64), + ) + assert sched._ctx_append_reserve == 0 + assert not sched._ctx_append_reserve_adaptive and not sched._ctx_append_reserve_sjf + head = make_ctx_request(0, context_remaining_length=20000) + short = make_ctx_request(1, context_remaining_length=1000) + out = sched.schedule_request([head, short], set()) + assert ids(out.context_requests) == [0] + assert head.context_chunk_size == 8192 + + def test_short_request_takes_the_reserve_ahead_of_a_second_long_one(self): + head = make_ctx_request(0, context_remaining_length=20000) + long_second = make_ctx_request(1, context_remaining_length=6000) + short = make_ctx_request(2, context_remaining_length=1000) + out = self._schedule(make_kv_cache_manager(tokens_per_block=64), [head, long_second, short]) + assert sorted(ids(out.context_requests)) == [0, 1, 2] + assert head.context_chunk_size == 8192 - 2048 + assert short.context_chunk_size == 1000 + assert long_second.context_chunk_size == 1024 + + def test_kill_switch_keeps_arrival_order(self, monkeypatch): + monkeypatch.setenv("TLLM_CTX_APPEND_RESERVE_SJF", "0") + head = make_ctx_request(0, context_remaining_length=20000) + long_second = make_ctx_request(1, context_remaining_length=6000) + short = make_ctx_request(2, context_remaining_length=1000) + out = self._schedule(make_kv_cache_manager(tokens_per_block=64), [head, long_second, short]) + assert sorted(ids(out.context_requests)) == [0, 1] + assert long_second.context_chunk_size == 2048 + + def test_order_uses_the_uncached_length_from_the_reuse_probe(self): + mgr = make_kv_cache_manager(tokens_per_block=64) + mgr.probe_context_reuse.side_effect = lambda req: 5900 if req.py_request_id == 3 else None + head = make_ctx_request(0, context_remaining_length=20000) + short = make_ctx_request(2, context_remaining_length=1000) + mostly_cached = make_ctx_request(3, context_remaining_length=6000) + out = self._schedule(mgr, [head, short, mostly_cached]) + assert 3 in ids(out.context_requests) + assert 2 not in ids(out.context_requests) + + def test_head_keeps_its_place(self): + head = make_ctx_request(0, context_remaining_length=20000) + short = make_ctx_request(1, context_remaining_length=500) + shorter = make_ctx_request(2, context_remaining_length=100) + self._schedule(make_kv_cache_manager(tokens_per_block=64), [head, short, shorter]) + assert head.context_chunk_size == 8192 - 2048 + + def test_started_continuation_keeps_its_place_ahead_of_new_requests(self): + """A started prefill holds pages; reordering it behind new short requests could preempt it.""" + sched = make_scheduler( + make_kv_cache_manager(tokens_per_block=64), + max_num_tokens=8192, + ctx_chunk_config=(None, 64), + ) + head = make_ctx_request(0, context_remaining_length=20000) + started = make_ctx_request(1, context_remaining_length=12000, is_first_context_chunk=False) + new_long = make_ctx_request(2, context_remaining_length=6000) + new_short = make_ctx_request(3, context_remaining_length=500) + pending = [head, new_long, started, new_short] + sched._order_reserve_shortest_first(pending) + assert ids(pending) == [0, 1, 3, 2] + + def test_joint_draft_pool_orders_by_the_common_claim_depth(self): + """With a paired draft pool, the reuse that will be claimed is min(draft, target).""" + mgr = make_kv_cache_manager(tokens_per_block=64, enable_joint_kv_cache_reuse=True) + draft_mgr = make_kv_cache_manager(tokens_per_block=64) + mgr.probe_context_reuse.side_effect = lambda req: 5900 + draft_mgr.probe_context_reuse.side_effect = ( + lambda req: 1000 if req.py_request_id == 1 else 5900 + ) + sched = make_scheduler( + mgr, max_num_tokens=8192, ctx_chunk_config=(None, 64), draft_kv_cache_manager=draft_mgr + ) + draft_short = make_ctx_request(1, context_remaining_length=6000) + both_deep = make_ctx_request(2, context_remaining_length=6000) + assert sched._uncached_context_tokens(draft_short) == 5000 + assert sched._uncached_context_tokens(both_deep) == 100 + pending = [make_ctx_request(0, context_remaining_length=20000), draft_short, both_deep] + sched._order_reserve_shortest_first(pending) + assert ids(pending) == [0, 2, 1] + + def test_uncached_count_is_memoized_between_reprobes(self, monkeypatch): + monkeypatch.setenv("TLLM_CTX_APPEND_RESERVE_SJF_REPROBE", "3") + mgr = make_kv_cache_manager(tokens_per_block=64) + sched = make_scheduler(mgr, max_num_tokens=8192, ctx_chunk_config=(None, 64)) + reqs = [make_ctx_request(i, context_remaining_length=1000 * (i + 1)) for i in range(3)] + for _ in range(3): + sched._order_reserve_shortest_first(list(reqs)) + assert mgr.probe_context_reuse.call_count == 2 # requests 1 and 2, probed once in 3 passes + sched._order_reserve_shortest_first(list(reqs)) + assert mgr.probe_context_reuse.call_count == 4 # re-probed on the 4th pass + + def test_memo_drops_requests_that_left(self): + mgr = make_kv_cache_manager(tokens_per_block=64) + sched = make_scheduler(mgr, max_num_tokens=8192, ctx_chunk_config=(None, 64)) + reqs = [make_ctx_request(i, context_remaining_length=1000 * (i + 1)) for i in range(4)] + sched._order_reserve_shortest_first(list(reqs)) + sched._order_reserve_shortest_first([reqs[0], reqs[1], reqs[2]]) + assert set(sched._uncached_context_memo) == {1, 2} + + def test_a_request_deferred_behind_a_contributor_is_reprobed_next_pass(self): + """Its reuse jumps once the contributor commits the shared block, so its memo must not keep it 'long'.""" + reuse = {} + mgr = make_kv_cache_manager( + tokens_per_block=64, + enable_block_reuse=True, + block_reuse_policy=BlockReusePolicy.ALL_REUSABLE, + first_new_block_fn=lambda req: {0: b"blockA", 1: b"blockA", 2: b"blockB"}.get( + req.request_id + ), + ) + mgr.probe_context_reuse.side_effect = lambda req: reuse.get(req.py_request_id) + sched = make_scheduler(mgr, max_num_tokens=10000) + req0, req1, req2 = ( + make_ctx_request(0, 5000), + make_ctx_request(1, 3000), + make_ctx_request(2, 2000), + ) + out = sched.schedule_request([req0, req1, req2], set()) + assert 1 not in ids(out.context_requests) # deferred behind request 0's block + assert 1 not in sched._uncached_context_memo and 2 in sched._uncached_context_memo + reuse[1] = 2900 # request 0 committed the shared prefix + req3 = make_ctx_request(3, 1500) + pending = [req0, req3, req1] + sched._order_reserve_shortest_first(pending) + assert ids(pending) == [0, 1, 3] + + @pytest.mark.parametrize("prompt_len", [0, 8]) def test_rewind_context_after_cache_drop_handles_empty_rank_local_prompt( prompt_len: int, diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_connector_v2_prefix_real_manager.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_connector_v2_prefix_real_manager.py index 59746a8a969f..5f5900cd4bd7 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_connector_v2_prefix_real_manager.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_connector_v2_prefix_real_manager.py @@ -890,3 +890,118 @@ def test_real_kv_pressure_rejects_reserved_prefix_without_transmission() -> None if blocker is not None: blocker.close() manager.shutdown() + + +# --------------------------------------------------------------------------- +# probe_context_reuse is a pure lookup: the scheduler's shortest-first append reserve calls it on every pending +# request each pass, so it must not refresh recency, onboard, or claim / pin pages. +# --------------------------------------------------------------------------- + + +def _public_state(obj): + return { + name: repr(getattr(obj, name)) + for name in dir(obj) + if not name.startswith("_") and not callable(getattr(obj, name)) + } + + +def _cache_state(manager): + return ( + [_public_state(s) for s in manager.impl.get_storage_statistics()], + _public_state(manager.impl.get_committed_stats()), + sorted(manager.kv_cache_map), + ) + + +def _commit_prefix(manager, request_id, tokens): + request = LlmRequest( + request_id=request_id, + max_new_tokens=4, + input_tokens=list(tokens), + sampling_config=SamplingConfig(1), + is_streaming=False, + ) + schedule(manager, request) + manager.kv_cache_map[request_id].commit(list(tokens)) + manager.free_resources(request) + + +def _probe_request(request_id, tokens): + return LlmRequest( + request_id=request_id, + max_new_tokens=4, + input_tokens=list(tokens), + sampling_config=SamplingConfig(1), + is_streaming=False, + ) + + +def test_probe_context_reuse_leaves_the_cache_state_unchanged(): + torch.cuda.init() + manager = make_manager(None) + try: + prefix = list(range(PROMPT_LEN)) + _commit_prefix(manager, 1, prefix) + reader = _probe_request(2, prefix + [7] * TOKENS_PER_BLOCK) + before = _cache_state(manager) + depths = {manager.probe_context_reuse(reader) for _ in range(100)} + assert len(depths) == 1 and depths.pop() > 0 + assert _cache_state(manager) == before + assert 2 not in manager.kv_cache_map + finally: + manager.shutdown() + + +def test_probe_context_reuse_does_not_refresh_eviction_recency(): + """Commit P1, then P2; probe P1 many times; grow the pool until one prefix is evicted. A probe that touched + recency would make P2 the older one and evict it first; a pure lookup leaves P1 first.""" + torch.cuda.init() + # No host tier: by default the V2 manager provisions one the size of the device quota, an evicted prefix + # migrates there and stays probe-able, and the device eviction order this test reads is never observable. + # 15-block fillers exhaust the free blocks within the manager's live-sequence limit, so the pool runs out of free + # blocks (and must evict a committed prefix) before admission is refused for that limit. + manager = make_manager( + None, + max_seq_len=512, + kv_cache_config=KvCacheConfig(max_tokens=2048, enable_block_reuse=True, host_cache_size=0), + ) + try: + p1 = list(range(PROMPT_LEN)) + p2 = list(range(1000, 1000 + PROMPT_LEN)) + _commit_prefix(manager, 1, p1) + _commit_prefix(manager, 2, p2) + r1, r2 = _probe_request(3, p1 + [7] * 4), _probe_request(4, p2 + [7] * 4) + full1, full2 = manager.probe_context_reuse(r1), manager.probe_context_reuse(r2) + assert full1 > 0 and full2 > 0 + for _ in range(50): + manager.probe_context_reuse(r1) + # Large fillers take the free blocks; once one no longer fits (admission is all or nothing), one-block + # fillers each need exactly one more block, which only evicting a committed prefix block can provide. + filler_len = 15 * TOKENS_PER_BLOCK + fillers = [] + evicted = None + for k in range(64): + # Distinct tokens: a filler sharing a prefix would legitimately claim (and refresh) its blocks. + filler = _probe_request( + 100 + k, list(range(5000 + 1000 * k, 5000 + 1000 * k + filler_len)) + ) + if not manager.prepare_context(filler) or not manager.resize_context( + filler, filler_len + ): + if filler.py_request_id in manager.kv_cache_map: + manager.free_resources(filler) + if filler_len == TOKENS_PER_BLOCK: + break + filler_len = TOKENS_PER_BLOCK + continue + fillers.append(filler) + d2, d1 = manager.probe_context_reuse(r2), manager.probe_context_reuse(r1) + if d1 < full1 or d2 < full2: + evicted = "P1" if d1 < full1 else "P2" + break + assert evicted == "P1", f"expected the older prefix P1 to be evicted first, got {evicted}" + for filler in fillers: + manager.free_resources(filler) + finally: + manager.shutdown() From 8b00e904c15a257f0d6c0addb8d137af8276d6e8 Mon Sep 17 00:00:00 2001 From: peihengh <259410613+peihu-nv@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:45:54 -0700 Subject: [PATCH 02/27] [None][fix] MiniMax-M3 prefill: zero the V tail past kv_len before fmha_sm100 fmha_sm100 masks only the scores, so P @ V still multiplies the V rows past kv_len on a partial last page by zero. An FP8 NaN byte left there by an earlier request on a recycled page turns the whole prefill tile NaN. FA4 already zeroes that tail; do the same before the fmha_sm100 prefill (dense layers on SM100/SM103, SM107 without FA4). Finite results are unchanged. Kill switch: TRTLLM_MSA_PREFILL_V_TAIL_ZERO=0. Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com> --- .../attention/backends/fmha/msa_prefill.py | 20 +++ .../msa/test_minimax_m3_prefill_v_tail.py | 124 ++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_prefill_v_tail.py diff --git a/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py b/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py index e101d930fd1d..e686f54d1b2e 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/msa_prefill.py @@ -54,6 +54,10 @@ # turns the tile's output NaN. Zeroing those rows first leaves every finite result bitwise unchanged. Kill switch: # TRTLLM_MSA_DENSE_FA4_V_TAIL_ZERO=0. _DENSE_FA4_V_TAIL_ZERO = os.environ.get("TRTLLM_MSA_DENSE_FA4_V_TAIL_ZERO", "1") != "0" +# The same zeroing before the FP8 / BF16 fmha_sm100 prefill (dense layers on SM100 / SM103, and SM107 without FA4): +# it also masks only the scores, so a NaN byte past kv_len on a recycled partial last page turns its P @ V NaN. +# Kill switch: TRTLLM_MSA_PREFILL_V_TAIL_ZERO=0. +_FMHA_SM100_V_TAIL_ZERO = os.environ.get("TRTLLM_MSA_PREFILL_V_TAIL_ZERO", "1") != "0" # What the patched flash_fwd_sm100 holds for the FP8 rescale threshold. _DENSE_FA4_PATCH_MARKER = "0.0 if const_expr(self.q_dtype.width == 8) else" # SM107: the FP8-KV prefill's E4M3 query is cast from the strided query rows of the fused QKV output by one Triton pass @@ -807,6 +811,22 @@ def rows_of(lens: Optional[torch.Tensor]) -> Optional[torch.Tensor]: ): return + kv_rows = rows_of(metadata.msa_kv_lens_cpu) + if _FMHA_SM100_V_TAIL_ZERO and kv_rows is not None: + if _v_tail_zero_safe(metadata.kv_cache_manager): + page_table = metadata.msa_block_table[row_first : row_first + num_rows] + _zero_partial_page_v_tail(v_paged, page_table, kv_rows) + logger.info_once( + "MiniMax-M3 prefill: fmha_sm100 V tail past kv_len zeroed on partial pages", + key="minimax_m3_prefill_fmha_sm100_v_tail", + ) + else: + logger.warning_once( + "MiniMax-M3 prefill: this KV cache can share a partially reused page without copying it, so the " + "fmha_sm100 V tail past kv_len is not zeroed; a NaN left there by an earlier request reaches P @ V", + key="minimax_m3_prefill_fmha_sm100_v_tail_unsafe", + ) + run_msa_sparse_gqa( q_view, k_paged, diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_prefill_v_tail.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_prefill_v_tail.py new file mode 100644 index 000000000000..830b376ea950 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_prefill_v_tail.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-M3 fmha_sm100 prefill over a partial last page whose V tail past kv_len holds FP8 NaN bytes. + +A recycled page keeps what an earlier request wrote past this request's kv_len. fmha_sm100 masks only the scores, +so P @ V multiplies those V rows by zero, and an E4M3 NaN byte (0x7F) turns the tile NaN. run_msa_prefill_gqa +zeroes the V tail first (TRTLLM_MSA_PREFILL_V_TAIL_ZERO), so the output equals the one over a zeroed tail. +""" + +import math +from unittest.mock import create_autospec + +import pytest +import torch + +from tensorrt_llm._torch.attention.backends.fmha import msa_prefill +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import ( + MiniMaxM3KVCacheManagerV2, + MiniMaxM3MsaSparseAttention, +) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.kernels.msa_utils import ( + msa_package_available, +) +from tensorrt_llm._torch.attention.backends.sparse.minimax_m3.msa_backend import ( + MiniMaxM3MsaSparseAttentionMetadata, +) + +HEAD_DIM, PAGE = 128, 128 +FP8_NAN_BYTE = 0x7F + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() + or torch.cuda.get_device_capability()[0] != 10 + or not msa_package_available(), + reason="requires SM10x and fmha_sm100", +) + + +def _case(rows: list, num_kv_heads: int, tail_byte: int): + """A batch whose rows (qo_len, kv_len) own pages of an FP8 pool filled with tail_byte past each kv_len.""" + g = torch.Generator(device="cuda").manual_seed(912) + pages_per_row = [math.ceil(kv / PAGE) for _, kv in rows] + slots = sum(pages_per_row) + 3 + pool = torch.full( + (slots, 2, num_kv_heads, PAGE, HEAD_DIM), tail_byte, dtype=torch.uint8, device="cuda" + ).view(torch.float8_e4m3fn) + table = torch.zeros(len(rows), max(pages_per_row), dtype=torch.int32, device="cuda") + flat, start = [], 0 + for i, ((_, kv), n) in enumerate(zip(rows, pages_per_row)): + pages = torch.arange(start, start + n, dtype=torch.int32, device="cuda") + table[i, :n] = pages + flat.append(pages) + start += n + kv_tokens = torch.randn(2, num_kv_heads, kv, HEAD_DIM, device="cuda", generator=g) * 0.5 + padded = torch.zeros(2, num_kv_heads, n * PAGE, HEAD_DIM, device="cuda") + padded[:, :, :kv] = kv_tokens + live = padded.view(2, num_kv_heads, n, PAGE, HEAD_DIM).permute(2, 0, 1, 3, 4) + # Only the first kv_len tokens are written; the rest of the last page keeps tail_byte. + for p in range(n): + count = min(PAGE, kv - p * PAGE) + pool[pages[p], :, :, :count] = live[p, :, :, :count].to(torch.float8_e4m3fn) + qo_lens = torch.tensor([qo for qo, _ in rows], dtype=torch.int32) + kv_lens = torch.tensor([kv for _, kv in rows], dtype=torch.int32) + kv_cache_manager = create_autospec(MiniMaxM3KVCacheManagerV2, instance=True) + kv_cache_manager.get_buffers.return_value = pool + kv_cache_manager.is_nvfp4_layer.return_value = False + metadata = create_autospec(MiniMaxM3MsaSparseAttentionMetadata, instance=True) + metadata.kv_cache_manager = kv_cache_manager + metadata.msa_qo_lens_cpu = qo_lens + metadata.msa_kv_lens_cpu = kv_lens + metadata.msa_qo_offset_cpu = kv_lens - qo_lens + metadata.msa_block_table = table + metadata.msa_kv_indices = torch.cat(flat) + return pool, metadata + + +def _run(q, metadata, num_heads): + attn = create_autospec(MiniMaxM3MsaSparseAttention, instance=True) + attn.head_dim, attn.num_heads, attn.layer_idx, attn.q_scaling = HEAD_DIM, num_heads, 0, 1.0 + out = torch.zeros_like(q) + msa_prefill.run_msa_prefill_gqa( + attn, + q, + metadata, + out, + kv_block_indexes=None, + plan=None, + row_first=0, + num_rows=int(metadata.msa_qo_lens_cpu.shape[0]), + ) + torch.cuda.synchronize() + return out + + +# Rows ending mid-page: short prompts, a short chunk over a long prefix, and a two-request batch. +ROWS = [[(5, 5)], [(38, 38)], [(129, 129)], [(170, 170)], [(5, 900)], [(38, 38), (86, 86)]] + + +@pytest.mark.parametrize("rows", ROWS, ids=lambda rows: "_".join(f"{q}x{kv}" for q, kv in rows)) +@pytest.mark.parametrize("num_heads,num_kv_heads", [(32, 2), (16, 1)], ids=["32x2", "16x1"]) +def test_fmha_sm100_prefill_ignores_nan_past_kv_len( + monkeypatch: pytest.MonkeyPatch, rows: list, num_heads: int, num_kv_heads: int +) -> None: + monkeypatch.setattr(msa_prefill, "dense_prefill_fa4_enabled", lambda *_: False) + num_tokens = sum(qo for qo, _ in rows) + g = torch.Generator(device="cuda").manual_seed(7) + q = (torch.randn(num_tokens, num_heads * HEAD_DIM, device="cuda", generator=g) * 0.5).to( + torch.bfloat16 + ) + + pool, metadata = _case(rows, num_kv_heads, FP8_NAN_BYTE) + out = _run(q, metadata, num_heads) + _, zero_tail_metadata = _case(rows, num_kv_heads, 0) + expected = _run(q, zero_tail_metadata, num_heads) + + assert torch.isfinite(out).all() + assert torch.equal(out, expected) + # The V tail of each partial last page is zeroed; K keeps its stale bytes (the scores mask them). + for i, (_, kv) in enumerate(rows): + if kv % PAGE: + page = int(metadata.msa_block_table[i, kv // PAGE]) + tail = pool.view(torch.uint8)[page, :, :, kv % PAGE :] + assert (tail[1] == 0).all() + assert (tail[0] == FP8_NAN_BYTE).all() From 6431c53dda089e5db1ce62d135dbb0a58da6de03 Mon Sep 17 00:00:00 2001 From: peihengh <259410613+peihu-nv@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:41:33 -0800 Subject: [PATCH 03/27] [None][fix] Preserve MiniMax-M3 CTX contracts after rebase Reject unsupported OAI locality execution and pre-scaled FP4 handoffs, preserve activation offsets and refit cache allocations, release stale CLC weight arguments, and validate native input devices. Keep scheduler starvation caps and release the optional reserve for indivisible chunks. Add focused routing, FA4 geometry, refit, and rejection regressions plus explicit Rubin CI registrations. Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com> --- .../minimaxM3SelectPrefillTileOp.cpp | 3 + .../minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp | 4 + .../minimax_m3_nvfp4__sm_107__tp2/modeling.py | 8 +- .../backends/sparse/minimax_m3/msa_backend.py | 12 ++- .../backends/sparse/minimax_m3/msa_indexer.py | 5 +- .../_torch/custom_ops/cute_dsl_custom_ops.py | 53 +++++++---- .../custom_ops/trtllm_gen_custom_ops.py | 6 +- .../kernels/rubin/m3_qkv_fusion/plain_gemm.py | 4 + .../_torch/models/modeling_minimaxm3.py | 19 +++- tensorrt_llm/_torch/modules/linear.py | 4 +- .../_torch/modules/m3_ctx_clc_gemm.py | 11 ++- .../fused_moe/cutedsl/grouped_gemm/nvfp4.py | 65 ++++++++----- .../pyexecutor/scheduler/scheduler_v2.py | 31 ++++--- .../integration/test_lists/test-db/l0_cpu.yml | 4 + .../test_lists/test-db/l0_gr100.yml | 15 +++ .../msa/test_minimax_m3_dense_prefill_fa4.py | 24 +++++ .../sparse/msa/test_minimax_m3_tile_select.py | 15 +++ .../kernels/serial/test_m3_ctx_clc_gemm.py | 40 ++++++-- .../kernels/serial/test_m3_ctx_fused_quant.py | 26 ++++++ .../_torch/misc/test_fp4_moe_tactic_table.py | 22 +++++ .../test_modeling_v2_m3_capture_boundary.py | 16 ++++ .../unittest/_torch/models/test_minimax_m3.py | 58 ++++++++++++ .../moe/test_cutedsl_swiglu_oai_resolution.py | 23 ++++- .../moe/test_m3_fold_shared_finalize.py | 12 --- .../_torch/moe/test_router_gemm_tf32.py | 93 ++++++++++++++++++- .../kv_cache/test_kv_cache_v2_scheduler.py | 40 ++++++++ 26 files changed, 519 insertions(+), 94 deletions(-) diff --git a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp index 57277019ac09..e32458d9db79 100644 --- a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp +++ b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp @@ -41,6 +41,7 @@ void minimaxM3SelectPrefillTile(torch::Tensor const& scores, torch::Tensor const TORCH_CHECK(nValidBlocks.is_cuda() && nValidBlocks.scalar_type() == torch::kInt32 && nValidBlocks.is_contiguous() && nValidBlocks.numel() >= scores.size(2), "minimax_m3_select_prefill_tile: n_valid_blocks must be contiguous int32 CUDA with at least total_q elements"); + TORCH_CHECK(nValidBlocks.device() == scores.device(), "n_valid_blocks must use the scores device"); int64_t const numKvHeads = scores.size(0); int64_t const numBlocks = scores.size(1); int64_t const totalQ = scores.size(2); @@ -51,6 +52,8 @@ void minimaxM3SelectPrefillTile(torch::Tensor const& scores, torch::Tensor const && out.size(1) == numKvHeads && out.size(2) == 16 && out.stride(2) == 1, "minimax_m3_select_prefill_tile: out must be int32 [total_q, num_kv_heads, 16] with unit last-dim stride"); + TORCH_CHECK(out.device() == scores.device(), "out must use the scores device"); + c10::cuda::CUDAGuard const deviceGuard{scores.device()}; auto const stream = at::cuda::getCurrentCUDAStream(scores.get_device()); cudaError_t const err = tensorrt_llm::kernels::invokeMinimaxM3SelectPrefillTile(scores.data_ptr(), diff --git a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp index d534ab7e977f..6f88e973a352 100644 --- a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp +++ b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp @@ -45,9 +45,12 @@ std::tuple= 2); TORCH_CHECK( residual.is_contiguous() && residual.scalar_type() == at::kBFloat16 && residual.sizes() == inter.sizes()); + TORCH_CHECK(residual.device() == inter.device(), "residual must use the inter device"); int64_t const hidden = inter.size(-1); + TORCH_CHECK(hidden > 0, "hidden must be positive"); int64_t const rows = inter.numel() / hidden; TORCH_CHECK(weight.is_contiguous() && weight.scalar_type() == at::kBFloat16 && weight.numel() == hidden); + TORCH_CHECK(weight.device() == inter.device(), "weight must use the inter device"); TORCH_CHECK(hidden % 256 == 0 && hidden / 8 <= 1024, "hidden must be a multiple of 256 and at most 8192"); at::cuda::CUDAGuard const guard(inter.device()); auto const opts = inter.options(); @@ -58,6 +61,7 @@ std::tupledevice() == inter.device(), "fp4_global_scale must use the inter device"); TORCH_CHECK( fp4GlobalScale->is_cuda() && fp4GlobalScale->scalar_type() == at::kFloat && fp4GlobalScale->numel() == 1); } diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py index df3034830b78..c389e0a19e19 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py @@ -2671,8 +2671,14 @@ def post_load_weights(self) -> None: self._built_for = identity def cache_derived_state(self) -> None: - """The staged loaders' entry to the same build (``post_load_weights``).""" + """Build the target and refresh captured router weights after in-place refit.""" self.post_load_weights() + from tensorrt_llm._torch.moe.fused_moe.router_gemm_tf32 import prepare_router_weight_tf32 + + # post_load_weights intentionally skips rebuilding unchanged storages; + # their contents can still change on refit. Captures retain these buffers. + for i, cached in self.router_w_tf32.items(): + cached.copy_(prepare_router_weight_tf32(self.w[f"l{i}_router"].float())) def _derive_moe(self, i: int) -> _MoeScalars: """The routed experts' kernel scalars from the checkpoint's per-tensor scales (trtllm-gen NVFP4 layout). diff --git a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py index 9cc31b6d5ce4..82764fd97b88 100644 --- a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py +++ b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_backend.py @@ -1281,9 +1281,14 @@ def plan_for( if segments is not None: seg_qo, seg_kv, seg_off = segments self._msa_prefill_proxy_plan = fmha_sm100.fmha_sm100_plan( - seg_qo, seg_kv, qo_offset=seg_off, page_size=page_size, + seg_qo, + seg_kv, + qo_offset=seg_off, + page_size=page_size, num_kv_splits=proxy_kv_splits(int(seg_qo.shape[0]), _cache_device(self)), - causal=True, num_qo_heads=num_index_heads, num_kv_heads=1, + causal=True, + num_qo_heads=num_index_heads, + num_kv_heads=1, output_maxscore=True, ) self._msa_prefill_proxy_kv_indices = self.msa_proxy_kv_indices @@ -1303,7 +1308,8 @@ def plan_for( proxy_rows, num_kv_splits=( proxy_kv_splits(proxy_rows[1] - proxy_rows[0], _cache_device(self)) - if proxy_rows is not None and self.msa_proxy_kv_indices is not None else 1 + if proxy_rows is not None and self.msa_proxy_kv_indices is not None + else 1 ), num_qo_heads=num_index_heads, num_kv_heads=1, diff --git a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py index 9f7fe6d98826..8def6fc7e046 100644 --- a/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py +++ b/tensorrt_llm/_torch/attention/backends/sparse/minimax_m3/msa_indexer.py @@ -14,15 +14,14 @@ from __future__ import annotations import functools -from types import ModuleType import os +from types import ModuleType from typing import TYPE_CHECKING, Optional import torch from tensorrt_llm._torch.attention.backends.fmha.utils import get_multi_processor_count_for_device -from tensorrt_llm._utils import async_tensor_h2d -from tensorrt_llm._utils import get_sm_version +from tensorrt_llm._utils import async_tensor_h2d, get_sm_version from tensorrt_llm.logger import logger from .kernels.msa_utils import ( diff --git a/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py b/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py index 0643c71c8897..582ea79c16e6 100644 --- a/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py @@ -95,6 +95,17 @@ def _canonicalize_situ_beta(situ_beta: float) -> Optional[float]: return None if situ_beta <= 0 else float(situ_beta) +def _canonicalize_rubin_activation_beta(activation_type: ActivationType, + value: float) -> Optional[float]: + """OAI constants are scalars, including non-positive linear offsets. + + Only SiTU soft-caps use non-positive values as the absent sentinel. + """ + if activation_type == ActivationType.SwigluBias: + return float(value) + return _canonicalize_situ_beta(value) + + _KIMI_K3_MXFP8_TUNING_BUCKETS = (1, 2, 4, 8, *range(16, 193, 16)) # Both dense MXFP8 wrappers pass a scalar one to the CuTe kernel. Keep one @@ -16610,8 +16621,10 @@ def _run_nvfp4_gather_grouped_gemm_act_fusion_rubin( tile_size, scaling_vector_size, activation_type=activation_type, - situ_beta=_canonicalize_situ_beta(situ_beta), - situ_linear_beta=_canonicalize_situ_beta(situ_linear_beta), + situ_beta=_canonicalize_rubin_activation_beta( + activation_type, situ_beta), + situ_linear_beta=_canonicalize_rubin_activation_beta( + activation_type, situ_linear_beta), swiglu_limit_scalar=_canonicalize_swiglu_limit_scalar( swiglu_limit_scalar), sf_dtype=sf_dtype, @@ -16922,8 +16935,10 @@ def cute_dsl_nvfp4_gather_grouped_gemm_act_fusion_locality_domain_inplace_rubin( tile_size, scaling_vector_size, activation_type=ActivationType(activation_type), - situ_beta=_canonicalize_situ_beta(situ_beta), - situ_linear_beta=_canonicalize_situ_beta(situ_linear_beta), + situ_beta=_canonicalize_rubin_activation_beta( + activation_type, situ_beta), + situ_linear_beta=_canonicalize_rubin_activation_beta( + activation_type, situ_linear_beta), swiglu_limit_scalar=_canonicalize_swiglu_limit_scalar( swiglu_limit_scalar), )) @@ -17634,17 +17649,16 @@ class Sm107BlockScaledContiguousGroupedGemmFinalizeFusionRunner( kernel_cache = dict() tuning_config_cache = dict() - def __init__( - self, - num_experts: int, - top_k: int, - num_local_experts: int, - local_expert_offset: int, - tile_size: int, - output_dtype: torch.dtype, - scaling_vector_size: int = 16, - sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN, - store_permuted: bool = False): + def __init__(self, + num_experts: int, + top_k: int, + num_local_experts: int, + local_expert_offset: int, + tile_size: int, + output_dtype: torch.dtype, + scaling_vector_size: int = 16, + sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN, + store_permuted: bool = False): super().__init__() # store_permuted: FC2 stores bf16(alpha * acc) at each permuted row of c [m, n] instead of the # fused scatter-add finalize (deterministic route; the finalize runs separately in fixed order). @@ -17791,8 +17805,10 @@ def get_tuning_config(self) -> TuningConfig: functools.partial( fp4_scale_infer_shape, sf_vec_size=self.scaling_vector_size)), - ConstraintSpec(5, 0, helper.infer_shape_max_num_permuted_tokens - if self.store_permuted else helper.infer_shape_num_tokens), + ConstraintSpec( + 5, 0, helper.infer_shape_max_num_permuted_tokens + if self.store_permuted else + helper.infer_shape_num_tokens), ConstraintSpec(6, 0, helper.infer_shape_max_num_tiles), ConstraintSpec(7, 0, @@ -17932,7 +17948,8 @@ def forward(self, inputs: List[torch.Tensor], cache_key = (self.scaling_vector_size, self.sf_dtype, self.tile_size, self.top_k, mma_tiler, mma_inst_shape, cluster_shape_mn, raster_along_m, - locality_domain_half_gemm, max_active_clusters, self.store_permuted) + locality_domain_half_gemm, max_active_clusters, + self.store_permuted) if cache_key not in self.__class__.kernel_cache: gemm = self.__class__.kernel_class( sf_vec_size=self.scaling_vector_size, diff --git a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py index 19e70f4b3c3b..d2fe8d922ae7 100644 --- a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py @@ -696,6 +696,9 @@ def lookup_tactic( the tuned choice, or None (not tuned yet). A caller that routes the tokens itself builds its tables for this tile and passes the tactic as ``prerouted_tactic``.""" + pinned = _pinned_fp4_moe_tactic(self, inputs[2].shape[0]) + if pinned is not None: + return list(pinned) shapes = tuple( t.size() if isinstance(t, torch.Tensor) else torch.Size((0, )) for t in inputs) @@ -887,7 +890,8 @@ def fp4_block_scale_moe_runner( tuning_config_with_hook, input_tensors_for_tuner, ) - pinned_tactic = _pinned_fp4_moe_tactic(kernel_runner, hidden_states.shape[0]) + pinned_tactic = _pinned_fp4_moe_tactic(kernel_runner, + hidden_states.shape[0]) if pinned_tactic is not None: best_tactic = pinned_tactic result = kernel_runner( diff --git a/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py index b6c7445524d2..84dc9ac64efb 100644 --- a/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py +++ b/tensorrt_llm/_torch/kernels/rubin/m3_qkv_fusion/plain_gemm.py @@ -162,6 +162,10 @@ def check(self, act, act_sf, weight, weight_sf, alpha) -> str: return "operands are not on one CUDA device" return "" + def clear_weight_cache(self) -> None: + """Drop DLPack arguments and their source tensors before a refit.""" + self._weight_args.clear() + def _weight_dl(self, weight, weight_sf, alpha) -> Tuple: key = ( weight.data_ptr(), diff --git a/tensorrt_llm/_torch/models/modeling_minimaxm3.py b/tensorrt_llm/_torch/models/modeling_minimaxm3.py index dc42198d128c..c30045339edf 100644 --- a/tensorrt_llm/_torch/models/modeling_minimaxm3.py +++ b/tensorrt_llm/_torch/models/modeling_minimaxm3.py @@ -118,7 +118,11 @@ def _fold_shared_backend(experts: nn.Module) -> bool: from ..moe.fused_moe.cutedsl.grouped_gemm import nvfp4 as _cute_moe backend = getattr(experts, "backend", experts) - return _cute_moe._RUBIN_DETERMINISTIC_FC2 and isinstance(backend, _cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl) + return ( + get_sm_version() == 107 + and _cute_moe._RUBIN_DETERMINISTIC_FC2 + and isinstance(backend, _cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl) + ) def _moe_routed_output_is_global(experts: nn.Module) -> bool: @@ -1075,11 +1079,15 @@ def __init__( def cache_tf32_weight(self) -> None: """Build the TF32-rounded weight copy for the fixed-tile router (after every weight load).""" - self._weight_tf32 = None if _CTX_ROUTER_TF32_FIXED and self._sm107_fp32_cast: from ..moe.fused_moe.router_gemm_tf32 import prepare_router_weight_tf32 - self._weight_tf32 = prepare_router_weight_tf32(self.weight.float()) + refreshed = prepare_router_weight_tf32(self.weight.float()) + if self._weight_tf32 is None: + self._weight_tf32 = refreshed + else: + # Captures retain this allocation across refit. + self._weight_tf32.copy_(refreshed) if self._router_tc_gen: # Decide the TF32 tensor-core router at load time (cluster query + its log), never inside a CUDA-graph # capture of a 9..16-row bucket; a device without 16-CTA clusters keeps the stock router. @@ -1349,7 +1357,7 @@ def fp4_input_scale(self, num_rows: int) -> Optional[torch.Tensor]: pre-scale, no hidden padding) or CuteDSL backend: there quantize_input is exactly fp4_quantize(x, fc31_input_scale, 16, False, False) and passes an unswizzled Fp4QuantizedTensor through unchanged. """ - from ..moe.fused_moe import CuteDslFusedMoE + from ..moe.fused_moe.cutedsl.grouped_gemm.nvfp4 import TrtllmCutedslGroupedGemmNvfp4Impl from ..moe.fused_moe.trtllm_gen.trtllm_nvfp4 import TrtllmTrtllmGenNvfp4Impl experts = self.experts @@ -1361,6 +1369,7 @@ def fp4_input_scale(self, num_rows: int) -> Optional[torch.Tensor]: or getattr(experts, "enable_dwdp", False) or num_rows > getattr(experts, "moe_max_num_tokens", 0) or getattr(backend, "lora_params", None) is not None + or getattr(backend, "fc31_act_scale", None) is not None ): return None if type(backend) is TrtllmTrtllmGenNvfp4Impl: @@ -1372,7 +1381,7 @@ def fp4_input_scale(self, num_rows: int) -> Optional[torch.Tensor]: or w.shape[-1] * 2 != self.hidden_dim ): return None - elif not (isinstance(backend, CuteDslFusedMoE) and getattr(backend, "has_nvfp4", False)): + elif not isinstance(backend, TrtllmCutedslGroupedGemmNvfp4Impl): return None if getattr(backend, "scaling_vector_size", None) != 16: return None diff --git a/tensorrt_llm/_torch/modules/linear.py b/tensorrt_llm/_torch/modules/linear.py index 6fc6ec391b71..98326f63dbe6 100644 --- a/tensorrt_llm/_torch/modules/linear.py +++ b/tensorrt_llm/_torch/modules/linear.py @@ -52,7 +52,8 @@ unswizzle_sf) from .low_m_gemm import (_should_apply_low_m_gemm, apply_low_m_gemm, low_m_gemm_dispatcher) -from .m3_ctx_clc_gemm import ctx_clc_gemm_enabled, try_ctx_clc_mxfp8_gemm +from .m3_ctx_clc_gemm import (clear_ctx_clc_weight_cache, ctx_clc_gemm_enabled, + try_ctx_clc_mxfp8_gemm) class WeightMode(str, enum.Enum): @@ -4938,6 +4939,7 @@ def post_load_weights(self) -> None: self.transform_weights() def pre_reload_weights(self): + clear_ctx_clc_weight_cache() self._output_slice_cache = None assert hasattr( self.quant_method, "pre_reload_weights" diff --git a/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py b/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py index 8c59c5fc7a4b..55e75e64645f 100644 --- a/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py +++ b/tensorrt_llm/_torch/modules/m3_ctx_clc_gemm.py @@ -46,6 +46,7 @@ # (the warmup) therefore builds every variant. Kill switch: TRTLLM_CTX_CLC_GEMM_PRECOMPILE=0 compiles each on first use. _PRECOMPILE = os.environ.get("TRTLLM_CTX_CLC_GEMM_PRECOMPILE", "1") != "0" _precompiled = [False] +_loaded_gemms: dict[tuple[int, int], object] = {} def ctx_clc_gemm_enabled() -> bool: @@ -69,7 +70,15 @@ def ctx_clc_heads_per_tile(m: int, n: int, k: int) -> Optional[int]: def _get_gemm(n: int, heads_per_tile: int): from ..kernels.rubin.m3_qkv_fusion.plain_gemm import get_gemm - return get_gemm(n, heads_per_tile) + gemm = get_gemm(n, heads_per_tile) + _loaded_gemms[(n, heads_per_tile)] = gemm + return gemm + + +def clear_ctx_clc_weight_cache() -> None: + """Release weight generations before Linear replaces its refit parameters.""" + for gemm in _loaded_gemms.values(): + gemm.clear_weight_cache() def _precompile_all() -> None: diff --git a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py index 317346299252..c7ad23ba4103 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py +++ b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py @@ -68,8 +68,7 @@ # (rule 1b) Rubin CuteDSL NVFP4 MoE: FC2 as a plain grouped GEMM per permuted row + a fixed-order unpermute instead # of the fused scatter-add finalize (bf16 atomics, run-to-run order dependent). Kill: TLLM_CUTEDSL_MOE_DETERMINISTIC=0. -_RUBIN_DETERMINISTIC_FC2 = os.environ.get("TLLM_CUTEDSL_MOE_DETERMINISTIC", - "1") == "1" +_RUBIN_DETERMINISTIC_FC2 = os.environ.get("TLLM_CUTEDSL_MOE_DETERMINISTIC", "1") == "1" _DETERMINISTIC_FC2_LOGGED = False @@ -82,14 +81,15 @@ def __init__(self, residual: torch.Tensor, event=None): self.residual = residual self.event = event self.consumed = False - self.calls = 0 # det-finalize calls seen since the offer: only the FIRST may consume (pairing guard) + self.calls = ( + 0 # det-finalize calls seen since the offer: only the FIRST may consume (pairing guard) + ) _FINALIZE_RESIDUAL: list[FinalizeResidual] = [] -def offer_finalize_residual(residual: torch.Tensor, - event=None) -> FinalizeResidual: +def offer_finalize_residual(residual: torch.Tensor, event=None) -> FinalizeResidual: """Offer ``residual`` to the next deterministic Rubin FC2 finalize on this thread (cleared by the caller).""" _FINALIZE_RESIDUAL.clear() holder = FinalizeResidual(residual, event) @@ -134,7 +134,14 @@ class TrtllmCutedslGroupedGemmNvfp4Impl(CuteDslFusedMoEBase): # and the epilogue has no "clamp absent" branch, so an absent clamp is # +inf, not None. activation_support = MoEActivationSupport( - kinds=frozenset({ActivationType.Swiglu, ActivationType.Relu2, ActivationType.SiTu, ActivationType.SwigluBias}), + kinds=frozenset( + { + ActivationType.Swiglu, + ActivationType.Relu2, + ActivationType.SiTu, + ActivationType.SwigluBias, + } + ), alpha_beta=ActivationParamShape.UNIFORM_SCALAR, limit=ActivationParamShape.UNIFORM_SCALAR, limit_when_absent=float("inf"), @@ -146,10 +153,16 @@ def can_implement(cls, p: MoEProblem, d: MoEDeployment) -> MoEEligibility: # which asserts 128-row tiles; without this gate an unaligned shard # dies mid weight load with a bare swizzle error. return check_grouped_gemm_leaf( - cls, p, d, nvfp4_fc1_row_alignment_rejection(p, d), + cls, + p, + d, + nvfp4_fc1_row_alignment_rejection(p, d), allow_swiglu_oai=( - p.activation == ActivationType.SwigluBias.name and not p.bias - and d.env.sm == 107 and _RUBIN_DETERMINISTIC_FC2 + p.activation == ActivationType.SwigluBias.name + and not p.bias + and d.env.sm == 107 + and not d.locality_domain_requested + and _RUBIN_DETERMINISTIC_FC2 ), ) @@ -508,7 +521,9 @@ def run_moe_nvfp4_impl( has_aux_streams = self._has_moe_output_memset_aux_stream() # The deterministic Rubin FC2 overwrites every output row (moe_unpermute_inplace): no zeroed output needed. - deterministic_fc2 = use_rubin and _RUBIN_DETERMINISTIC_FC2 and not use_count_native_expert_metadata + deterministic_fc2 = ( + use_rubin and _RUBIN_DETERMINISTIC_FC2 and not use_count_native_expert_metadata + ) if use_rubin and not _RUBIN_DETERMINISTIC_FC2: logger.warning_once( "CuteDSL NVFP4 MoE on SM107 with TLLM_CUTEDSL_MOE_DETERMINISTIC=0: the FC2 finalize uses bf16 " @@ -615,10 +630,9 @@ def run_moe_nvfp4_impl( # (rule 1b) Deterministic FC2 on Rubin: the grouped GEMM stores bf16(alpha * acc) per permuted row # (no scatter-add atomics), then moe_unpermute_inplace sums each token's top-k rows in fixed index # order with the token scales. Same run-to-run output; kill: TLLM_CUTEDSL_MOE_DETERMINISTIC=0. - fc2_rows = torch.empty(x.shape[0], - weight_view.w2_weight.shape[1], - dtype=output_dtype, - device=x.device) + fc2_rows = torch.empty( + x.shape[0], weight_view.w2_weight.shape[1], dtype=output_dtype, device=x.device + ) torch.ops.trtllm.cute_dsl_nvfp4_grouped_gemm_store_rubin( input=x.view(torch.float4_e2m1fn_x2), weight=weight_view.w2_weight.view(torch.float4_e2m1fn_x2), @@ -641,21 +655,28 @@ def run_moe_nvfp4_impl( holder = _FINALIZE_RESIDUAL[0] if _FINALIZE_RESIDUAL else None if holder is not None: holder.calls += 1 - if (holder is not None and not holder.consumed and holder.calls == 1 - and holder.residual.shape == moe_output.shape - and holder.residual.dtype == moe_output.dtype - and moe_output.dtype == torch.bfloat16): + if ( + holder is not None + and not holder.consumed + and holder.calls == 1 + and holder.residual.shape == moe_output.shape + and holder.residual.dtype == moe_output.dtype + and moe_output.dtype == torch.bfloat16 + ): # The shared + routed add folded into the finalize (bitwise; kill TLLM_M3_MOE_FOLD_SHARED=0). from ...unpermute_residual import unpermute_residual + if holder.event is not None: torch.cuda.current_stream().wait_event(holder.event) - if not (torch.compiler.is_compiling() - or torch.cuda.is_current_stream_capturing()): + if not (torch.compiler.is_compiling() or torch.cuda.is_current_stream_capturing()): holder.residual.record_stream(torch.cuda.current_stream()) unpermute_residual( - fc2_rows, moe_output, + fc2_rows, + moe_output, expanded_idx_to_permuted_idx.view(moe_output.shape[0], -1), - token_final_scales, holder.residual.contiguous()) + token_final_scales, + holder.residual.contiguous(), + ) holder.consumed = True _FINALIZE_RESIDUAL.clear() else: diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py index 0516079f4fdc..964c29dde755 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py @@ -905,6 +905,7 @@ def preempt_for_pages(req: LlmRequest) -> bool: f"Deferring context request {req.py_request_id}: its first new " "block is already contributed by a request that runs this iteration" ) + self._uncached_context_memo.pop(req.py_request_id, None) deferred_behind_contributor = True continue peft_pages = budget.peft_pages_needed(req) @@ -1564,11 +1565,15 @@ def _try_schedule_context_chunked( """ reserve = self._ctx_append_reserve if self._ctx_append_reserve_active else 0 if not reserve or budget.num_tokens != 0 or budget.max_num_tokens is None: - return self._try_schedule_context_chunked_impl(req, budget, preempt_for_pages) + return self._try_schedule_context_chunked_impl( + req, budget, preempt_for_pages, token_cap + ) full = budget.max_num_tokens budget.max_num_tokens = full - reserve try: - result = self._try_schedule_context_chunked_impl(req, budget, preempt_for_pages) + result = self._try_schedule_context_chunked_impl( + req, budget, preempt_for_pages, token_cap, full_token_budget=full + ) finally: budget.max_num_tokens = full if self._ctx_append_reserve_logged < 3 and result[0] is ScheduleAction.SCHEDULED: @@ -1584,6 +1589,8 @@ def _try_schedule_context_chunked_impl( req: LlmRequest, budget: BudgetTracker, preempt_for_pages: Callable[[LlmRequest], bool], + token_cap: Optional[int] = None, + full_token_budget: Optional[int] = None, ) -> tuple[ScheduleAction, int, bool]: """FCFS interleaved chunking for a single context request. @@ -1680,19 +1687,11 @@ def _try_schedule_context_chunked_impl( # a longer chunk would grow the capacity again before the history catches up. pregrown = self._pregrown_context_tokens(req) if pregrown > 0: - if chunk_size < pregrown: - return ScheduleAction.SKIP, 0, False - chunk_size = pregrown - - if chunk_size <= 0: - # Out of token budget rather than out of pages, so releasing pages - # would not help; the next iteration gets a fresh budget. Not - # suspended either, to avoid pathological suspend/resume cycles. - return ScheduleAction.SKIP, 0, False + chunk_size = pregrown if chunk_size >= pregrown else 0 # A pre-grown chunk was MM-aligned from this same position when it was # first sized, and either snap direction would break the exact replay. - if pregrown == 0: + if pregrown == 0 and chunk_size > 0: chunk_size = self._align_chunk_to_mm_block( req, chunk_size, remaining_budget, context_remaining ) @@ -1701,6 +1700,14 @@ def _try_schedule_context_chunked_impl( # than schedule a chunk that would corrupt attention. Next iteration # gets a fresh budget; under steady-state load this resolves quickly. if chunk_size <= 0: + if full_token_budget is not None: + # The reserve is optional. Release it once when MM alignment or + # exact pre-grown replay cannot advance; token_cap still applies. + # No resize/allocation has happened, so prepare_context is safe to repeat. + budget.max_num_tokens = full_token_budget + return self._try_schedule_context_chunked_impl( + req, budget, preempt_for_pages, token_cap + ) return ScheduleAction.SKIP, 0, False budget_chunk_size = chunk_size # Decoder queries are a subset of these physical Encoder rows, including diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index b81776109860..b825baf128d1 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -110,6 +110,7 @@ l0_cpu: - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_draft_attention_bcg_route.py - unittest/_torch/attention/test_fallback_fmha_extra_page_sizes.py - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_ctx_stack_route.py + - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py::test_ctx_router_cache_refreshes_in_place_after_refit - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_dense_backend_library_order - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_fp8_indexer_rejects_different_qk_norm_epsilons - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_moe_reduces_only_local_terms @@ -141,6 +142,9 @@ l0_cpu: - unittest/_torch/models/test_minimax_m3_vl.py - unittest/_torch/models/test_minimax_m3_vl_spec_reuse.py - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_split_router_weight_reconstructs_fp32 + - unittest/_torch/models/test_minimax_m3.py::test_ctx_fp4_input_scale_rejects_cutedsl_awq_prescale + - unittest/_torch/models/test_minimax_m3.py::test_minimax_m3_gate_tf32_refit_preserves_allocation + - unittest/_torch/models/test_minimax_m3.py::test_cutedsl_shared_fold_backend_is_rubin_only # l0_h100 and l0_b200 select unittest/_torch/misc with -m "not cpu_only", so this entry is # what runs it. - unittest/_torch/misc/test_xgrammar_structural_tag.py diff --git a/tests/integration/test_lists/test-db/l0_gr100.yml b/tests/integration/test_lists/test-db/l0_gr100.yml index 6c85a96523c3..57fded42d03a 100644 --- a/tests/integration/test_lists/test-db/l0_gr100.yml +++ b/tests/integration/test_lists/test-db/l0_gr100.yml @@ -13,6 +13,21 @@ l0_gr100: stage: post_merge backend: pytorch tests: + # MiniMax-M3 context kernels and router validation; all run on one Rubin GPU. + - unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py + - unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py + - unittest/_torch/kernels/serial/test_m3_qkv_fusion.py + - unittest/_torch/attention/fmha/test_msa_combine_mxfp8.py + - unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py + - unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py + - unittest/_torch/attention/sparse/msa/test_msa_prefill_nvfp4_out_in_place.py + - unittest/_torch/attention/sparse/msa/test_minimax_m3_proxy_nofill.py + - unittest/_torch/attention/test_drafter_kv_tail_zero.py + - unittest/_torch/modules/test_prequantized_mxfp8_streams.py + - unittest/_torch/moe/test_cutedsl_rubin_deterministic.py + - unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py + - unittest/_torch/moe/test_router_gemm_tf32.py + - unittest/_torch/moe/test_unpermute_residual.py - unittest/_torch/modeling_v2/models/minimax_m3/test_shared_kernel_contracts.py # MiniMax-M3 Rubin target unit tests. - unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/activation diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py index 962b4808701d..343517300e80 100644 --- a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4.py @@ -8,6 +8,7 @@ """ import math +import sys from unittest.mock import create_autospec import pytest @@ -174,3 +175,26 @@ def test_dense_prefill_fa4_kill_switch(monkeypatch: pytest.MonkeyPatch) -> None: assert msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, PAGE) assert not msa_prefill.dense_prefill_fa4_enabled(False, HEAD_DIM, PAGE) assert not msa_prefill.dense_prefill_fa4_enabled(True, HEAD_DIM, 64) + + +@pytest.mark.parametrize("heads,kv_heads", [(32, 2), (16, 1), (8, 1)]) +def test_dense_prefill_fa4_short_tail_band_per_tp_geometry( + monkeypatch: pytest.MonkeyPatch, heads: int, kv_heads: int +) -> None: + """Keep a short row's error visible instead of hiding it in a larger batch.""" + monkeypatch.setattr(sys.modules[__name__], "NUM_HEADS", heads) + monkeypatch.setattr(sys.modules[__name__], "NUM_KV_HEADS", kv_heads) + rows = [(5, 900)] + q, pool, metadata, flat = _case(912, rows, False) + reference = _reference(q, pool, rows, flat) + fa4 = _run(q, metadata, 0, 1) + monkeypatch.setattr(msa_prefill, "dense_prefill_fa4_enabled", lambda *_: False) + stock = _run(q, metadata, 0, 1) + fa4_error, stock_error = _max_err(fa4, reference), _max_err(stock, reference) + assert torch.isfinite(fa4).all() + assert fa4_error <= stock_error * 1.05 + 2.0**-9 * float(reference.abs().max()), ( + heads, + kv_heads, + fa4_error, + stock_error, + ) diff --git a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py index 1a2dc6bb1032..88206db9a46e 100644 --- a/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py +++ b/tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py @@ -204,3 +204,18 @@ def test_tile_select_gate(monkeypatch, sm_version, enabled, total_q, num_blocks) monkeypatch.setattr(msa_indexer, "_SM107_TILE_SELECT", enabled) scores = torch.zeros(4, num_blocks, total_q) assert msa_indexer._tile_select(scores, torch.ones(total_q, dtype=torch.int32), 0, 1) is None + + +@sm107 +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="requires two GPUs") +@pytest.mark.parametrize("operand", ["n_valid_blocks", "out"]) +def test_tile_select_rejects_mismatched_device(operand: str) -> None: + scores = torch.zeros((1, 32, 4), device="cuda:0") + n_valid = torch.full((4,), 32, dtype=torch.int32, device="cuda:0") + out = torch.empty((4, 1, 16), dtype=torch.int32, device="cuda:0") + if operand == "n_valid_blocks": + n_valid = n_valid.to("cuda:1") + else: + out = out.to("cuda:1") + with pytest.raises(RuntimeError, match=f"{operand} must use the scores device"): + torch.ops.trtllm.minimax_m3_select_prefill_tile(scores, n_valid, out, 0, 1) diff --git a/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py b/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py index de6346cee5f1..0288b125ceac 100644 --- a/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py +++ b/tests/unittest/_torch/kernels/serial/test_m3_ctx_clc_gemm.py @@ -22,10 +22,12 @@ """ import argparse +import gc import importlib import os import sys import time +import weakref import pytest import torch @@ -68,11 +70,8 @@ def _pkg(): def _dispatch_module(): - """The in-model dispatcher (registers trtllm::m3_ctx_clc_mxfp8_gemm), or None if this tensorrt_llm lacks it.""" - try: - return importlib.import_module("tensorrt_llm._torch.modules.m3_ctx_clc_gemm") - except ImportError: - return None + """Import the in-model dispatcher; broken in-tree imports must fail the test.""" + return importlib.import_module("tensorrt_llm._torch.modules.m3_ctx_clc_gemm") def hpt_for(name, m): @@ -234,9 +233,6 @@ def gate(name, m, log=print, hpt=None): def dispatch(log=print, name="o_proj"): """MXFP8 Linear through the real loader: engagement, slot, threshold and kill switch.""" mod = _dispatch_module() - if mod is None: - log("DISPATCH SKIP: tensorrt_llm._torch.modules.m3_ctx_clc_gemm not importable") - return True from tensorrt_llm._torch.modules import linear as linear_module from tensorrt_llm._torch.modules.linear import Linear, MXFP8LinearMethod from tensorrt_llm.logger import logger as trt_logger @@ -454,3 +450,31 @@ def test_m3_ctx_clc_gemm_dispatch(): for mm in [int(v) for v in a.timing.split(",") if v]: timing(nm, mm, log=plog) print(f"GATE ALL {'PASS' if all_ok else 'FAIL'}", flush=True) + + +def test_clc_weight_arguments_released_before_linear_refit() -> None: + # Import after _pkg establishes CUTE_DSL_ARCH, as in the other dispatch tests. + _, pg = _pkg() + mod = _dispatch_module() + from tensorrt_llm._torch.modules.linear import Linear, MXFP8LinearMethod + + gemm = mod._get_gemm(3072, 2) + weight = torch.zeros((3072, 128), dtype=torch.float8_e4m3fn, device="cuda") + scales = torch.zeros(pg.swizzled_sf_numel(3072, 128), dtype=torch.uint8, device="cuda") + alpha = torch.ones(1, device="cuda") + gemm._weight_dl(weight, scales, alpha) + refs = [weakref.ref(t) for t in (weight, scales, alpha)] + del weight, scales, alpha + gc.collect() + assert all(ref() is not None for ref in refs) + + # A real Linear executes the refit hook; empty metadata avoids allocating unrelated weights. + linear = Linear.__new__(Linear) + torch.nn.Module.__init__(linear) + linear.quant_method = MXFP8LinearMethod.__new__(MXFP8LinearMethod) + linear.rebuild_tensor_metadata = {} + linear._locality_domain_weight_shards = None + linear.pre_reload_weights() + gc.collect() + assert not gemm._weight_args + assert all(ref() is None for ref in refs) diff --git a/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py b/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py index 33de534fedfd..7cde495d8363 100644 --- a/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py +++ b/tests/unittest/_torch/kernels/serial/test_m3_ctx_fused_quant.py @@ -78,3 +78,29 @@ def test_swiglu_mxfp8_is_bitwise_the_quantized_swiglu( ) assert torch.equal(_bits(q), _bits(ref_q)), "MXFP8 values" assert torch.equal(sf.view(-1), ref_sf.view(torch.uint8).view(-1)), "MXFP8 swizzled scales" + + +@pytest.mark.parametrize("operand", ["residual", "weight", "fp4_global_scale"]) +@pytest.mark.parametrize("other_device", ["cpu", "cuda:1"]) +def test_ctx_residual_rmsnorm_rejects_mismatched_device(operand: str, other_device: str) -> None: + if other_device == "cuda:1" and torch.cuda.device_count() < 2: + pytest.skip("requires two GPUs") + inter = torch.zeros((1, 256), dtype=torch.bfloat16, device="cuda:0") + args = { + "residual": torch.zeros_like(inter), + "weight": torch.ones(256, dtype=torch.bfloat16, device=inter.device), + "fp4_global_scale": torch.ones(1, device=inter.device), + } + args[operand] = args[operand].to(other_device) + with pytest.raises(RuntimeError, match=f"{operand} must use the inter device"): + torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8( + inter, args["residual"], args["weight"], EPS, True, args["fp4_global_scale"] + ) + + +def test_ctx_residual_rmsnorm_rejects_zero_hidden() -> None: + inter = torch.empty((1, 0), dtype=torch.bfloat16, device="cuda") + with pytest.raises(RuntimeError, match="hidden must be positive"): + torch.ops.trtllm.minimax_m3_ctx_residual_rmsnorm_mxfp8( + inter, torch.empty_like(inter), inter.reshape(-1), EPS, True + ) diff --git a/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py b/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py index 0794f563b940..eb78ec3aa04c 100644 --- a/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py +++ b/tests/unittest/_torch/misc/test_fp4_moe_tactic_table.py @@ -16,8 +16,10 @@ import json from types import SimpleNamespace +from unittest.mock import Mock import pytest +import torch from tensorrt_llm._torch.custom_ops import trtllm_gen_custom_ops as ops @@ -62,3 +64,23 @@ def test_table_path_is_resolved_at_import(table, monkeypatch): # The environment is not re-read per call (CUDA-graph capture must see the same tactic as eager steps). monkeypatch.delenv(ops.FP4_MOE_TACTIC_TABLE_ENV, raising=False) assert ops._pinned_fp4_moe_tactic(_runner(), 1761) == [128, 23] + + +def test_prerouted_lookup_uses_pinned_tile_before_building_tables(table, monkeypatch): + # Fields are initialized by the production constructor, not class attributes. + runner = ops.FP4BlockScaleMoERunner.__new__(ops.FP4BlockScaleMoERunner) + runner.top_k = 4 + runner.intermediate_size = 3072 + runner.local_num_experts = 64 + runner.act_type = 0 + runner.tuning_config = _runner().tuning_config + cache = Mock(spec_set=["search_cache"]) + cache.search_cache.return_value = (True, None, [256, 99], None) + tuner = Mock(spec_set=["profiling_cache"]) + tuner.profiling_cache = cache + monkeypatch.setattr(ops.AutoTuner, "get", lambda: tuner) + inputs = [None, None, torch.empty((1761, 1), device="meta")] + assert runner.lookup_tactic(inputs) == [128, 23] + cache.search_cache.assert_not_called() + monkeypatch.setattr(ops, "_FP4_MOE_TACTIC_TABLE_PATH", None) + assert runner.lookup_tactic(inputs) == [256, 99] diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py index 03510d0338f7..65da37411008 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py @@ -16,6 +16,7 @@ from tensorrt_llm._torch._experimental.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp2 import ( # noqa: E501 modeling, ) +from tensorrt_llm._torch.moe.fused_moe.router_gemm_tf32 import prepare_router_weight_tf32 LAYERS = 4 @@ -170,3 +171,18 @@ def no_boundary(*a, **k): assert out == (("normed", 2), ("updated", 2)) assert seen and seen[0][0] == 2 and seen[0][3] == "in_norm3" assert captured == [(2, ("updated", 2), None)] + + +@pytest.mark.cpu_only +def test_ctx_router_cache_refreshes_in_place_after_refit(monkeypatch: pytest.MonkeyPatch) -> None: + core = modeling.MiniMaxM3Tp2ModelingV2.__new__(modeling.MiniMaxM3Tp2ModelingV2) + torch.nn.Module.__init__(core) + core.w = {"l0_router": torch.ones(8, 64)} + core.router_w_tf32 = {0: prepare_router_weight_tf32(core.w["l0_router"])} + captured = core.router_w_tf32[0] + # Existing storages take post_load_weights' idempotent return; no kernels need rebuilding. + monkeypatch.setattr(core, "post_load_weights", lambda: None) + core.w["l0_router"].fill_(2.0) + core.cache_derived_state() + assert core.router_w_tf32[0] is captured + torch.testing.assert_close(captured, torch.full((8, 64), 2.0), rtol=0, atol=0) diff --git a/tests/unittest/_torch/models/test_minimax_m3.py b/tests/unittest/_torch/models/test_minimax_m3.py index bacf92caeffd..048064dab1c2 100644 --- a/tests/unittest/_torch/models/test_minimax_m3.py +++ b/tests/unittest/_torch/models/test_minimax_m3.py @@ -38,6 +38,7 @@ from utils.llm_data import llm_models_root import tensorrt_llm._torch.models.modeling_minimaxm3 as modeling_minimaxm3 +import tensorrt_llm._torch.moe.fused_moe.cutedsl.grouped_gemm.nvfp4 as cutedsl_nvfp4 from tensorrt_llm._torch.attention.backends.fmha.msa_prefill import _aligned_nvfp4_dequant_scales from tensorrt_llm._torch.attention.backends.interface import AttentionMetadata from tensorrt_llm._torch.attention.backends.sparse.minimax_m3 import ( @@ -88,6 +89,9 @@ from tensorrt_llm._torch.models.modeling_utils import _load_weights_impl_v2 from tensorrt_llm._torch.modules.linear import MXFP8LinearMethod, _load_kv_cache_scales from tensorrt_llm._torch.modules.rms_norm import RMSNorm +from tensorrt_llm._torch.moe.fused_moe.cutedsl.grouped_gemm.nvfp4 import ( + TrtllmCutedslGroupedGemmNvfp4Impl, +) from tensorrt_llm._torch.moe.fused_moe.interface import MoESchedulerKind from tensorrt_llm._torch.moe.fused_moe.routing import ( MiniMaxM2MoeRoutingMethod, @@ -3280,3 +3284,57 @@ def test_ctx_qkv_fused_skips_autotune_pass(monkeypatch, tuning: bool) -> None: assert m3._autotuner_tuning() is tuning # The yield is logged once per process, and only when it happens. assert m3._CTX_QKV_FUSED_YIELD_LOGGED is tuning + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("has_prescale", [False, True]) +def test_ctx_fp4_input_scale_rejects_cutedsl_awq_prescale(has_prescale: bool) -> None: + backend = TrtllmCutedslGroupedGemmNvfp4Impl.__new__(TrtllmCutedslGroupedGemmNvfp4Impl) + nn.Module.__init__(backend) + backend.scaling_vector_size = 16 + backend.fc31_input_scale = torch.ones(1, dtype=torch.float32) + backend.fc31_act_scale = torch.ones(64) if has_prescale else None + experts = nn.Module() + experts.backend = backend + experts.moe_max_num_tokens = 32 + block = modeling_minimaxm3.MiniMaxM3MoE.__new__(modeling_minimaxm3.MiniMaxM3MoE) + nn.Module.__init__(block) + block.experts = experts + block.routed_output_is_global = False + block.hidden_dim = 64 + + scale = block.fp4_input_scale(16) + if has_prescale: + assert scale is None + else: + assert scale is backend.fc31_input_scale + + +@pytest.mark.cpu_only +def test_minimax_m3_gate_tf32_refit_preserves_allocation(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: 107) + monkeypatch.setattr(modeling_minimaxm3, "_CTX_ROUTER_TF32_FIXED", True) + monkeypatch.setattr(modeling_minimaxm3, "_ROUTER_TC_GEN", False) + # CPU check uses the real bitwise TF32 conversion; captured replay is tested on Rubin. + gate = modeling_minimaxm3.MiniMaxM3Gate(64, 8, 2, 1.0) + gate.load_weights([{"weight": torch.ones(8, 64)}]) + gate.cache_tf32_weight() + captured_weight = gate._weight_tf32 + ptr = captured_weight.data_ptr() + gate.load_weights([{"weight": torch.full((8, 64), 2.0)}]) + gate.cache_tf32_weight() + assert gate._weight_tf32 is captured_weight + assert gate._weight_tf32.data_ptr() == ptr + torch.testing.assert_close(captured_weight, torch.full((8, 64), 2.0), rtol=0, atol=0) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("sm", [100, 103, 107, 110]) +def test_cutedsl_shared_fold_backend_is_rubin_only( + monkeypatch: pytest.MonkeyPatch, sm: int +) -> None: + monkeypatch.setattr(modeling_minimaxm3, "get_sm_version", lambda: sm) + monkeypatch.setattr(cutedsl_nvfp4, "_RUBIN_DETERMINISTIC_FC2", True) + backend = TrtllmCutedslGroupedGemmNvfp4Impl.__new__(TrtllmCutedslGroupedGemmNvfp4Impl) + nn.Module.__init__(backend) + assert modeling_minimaxm3._fold_shared_backend(backend) is (sm == 107) diff --git a/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py b/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py index 763032a5852b..2e308bc44d2c 100644 --- a/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py +++ b/tests/unittest/_torch/moe/test_cutedsl_swiglu_oai_resolution.py @@ -4,11 +4,14 @@ NVFP4 with the deterministic FC2 (CTX-7), and must be declined everywhere else: expert biases, the non-deterministic FC2, other SMs. Gates the dispatch, not the op.""" +from dataclasses import replace + import pytest import torch from transformers.configuration_utils import PretrainedConfig import tensorrt_llm._torch.moe.fused_moe.cutedsl.grouped_gemm.nvfp4 as cute_moe +from tensorrt_llm._torch.custom_ops.cute_dsl_custom_ops import _canonicalize_rubin_activation_beta from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.moe.fused_moe import RenormalizeMoeRoutingMethod from tensorrt_llm._torch.moe.fused_moe.activation import SwigluBiasActivation @@ -21,6 +24,7 @@ infer_swiglu_gptoss_style, resolve_moe_impl, ) +from tensorrt_llm._torch.utils import ActivationType from tensorrt_llm._utils import get_sm_version from tensorrt_llm.mapping import Mapping from tensorrt_llm.models.modeling_utils import QuantAlgo, QuantConfig @@ -74,7 +78,9 @@ def test_m3_swiglu_bias_resolves_to_cutedsl_on_sm107(monkeypatch) -> None: @pytest.mark.cpu_only -@pytest.mark.parametrize("case", ["nondeterministic_fc2", "expert_bias", "sm100"]) +@pytest.mark.parametrize( + "case", ["nondeterministic_fc2", "expert_bias", "sm100", "locality_domain"] +) def test_swiglu_bias_declined_outside_the_deterministic_rubin_path(monkeypatch, case) -> None: monkeypatch.setattr(cute_moe, "_RUBIN_DETERMINISTIC_FC2", case != "nondeterministic_fc2") sm, bias = (100, False) if case == "sm100" else (107, case == "expert_bias") @@ -86,7 +92,8 @@ def test_swiglu_bias_declined_outside_the_deterministic_rubin_path(monkeypatch, activation=_M3_ACT, **_SHAPE, ) - verdict = cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl.can_implement(problem, _deployment(sm)) + deployment = replace(_deployment(sm), locality_domain_requested=case == "locality_domain") + verdict = cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl.can_implement(problem, deployment) assert not verdict.eligible assert verdict.reject_reason is MoERejectReason.ACTIVATION_UNSUPPORTED @@ -109,3 +116,15 @@ def test_m3_create_moe_builds_cutedsl_on_this_gpu() -> None: **_SHAPE, ) assert isinstance(moe.backend, cute_moe.TrtllmCutedslGroupedGemmNvfp4Impl), type(moe.backend) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("linear_offset", [0.0, -1.0, -2.5, 1.0]) +def test_rubin_oai_linear_offset_survives_parameter_conversion(linear_offset: float) -> None: + assert ( + _canonicalize_rubin_activation_beta(ActivationType.SwigluBias, linear_offset) + == linear_offset + ) + assert _canonicalize_rubin_activation_beta(ActivationType.SiTu, linear_offset) == ( + linear_offset if linear_offset > 0 else None + ) diff --git a/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py b/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py index e11809712fad..a2a653f55add 100644 --- a/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py +++ b/tests/unittest/_torch/moe/test_m3_fold_shared_finalize.py @@ -119,18 +119,6 @@ def test_fold_shared_refused_with_separated_routing(monkeypatch) -> None: monkeypatch.setattr(trtllm_gen_base, "FORCE_SEPARATED_ROUTING", True) monkeypatch.setattr(moe_scheduler, "FORCE_SEPARATED_ROUTING", True) assert moe.backend._routes_outside_the_kernel() - stock = shared.clone().add_(moe(x, logits)) - # The runner finalizes with the precomputed top-k weights and returns an expert_weights tensor it never - # writes: poison the allocator's free blocks so the unwritten tensor cannot alias a copy of those weights. - poison = [ - torch.full((tokens, TOP_K), float("nan"), dtype=torch.bfloat16) for _ in range(64) - ] - del poison - unfinalized = moe(x, logits, do_finalize=False) - folded = fold_shared_into_finalize(unfinalized, shared, TOP_K) - assert not torch.equal(folded.view(torch.int16), stock.view(torch.int16)), ( - "expected the unwritten expert_weights to corrupt the fold" - ) assert not _fold_ok(moe, x), ( "fold must be refused when top-k is precomputed outside the kernel" ) diff --git a/tests/unittest/_torch/moe/test_router_gemm_tf32.py b/tests/unittest/_torch/moe/test_router_gemm_tf32.py index 7e7d6337cb89..205e778fd1d3 100644 --- a/tests/unittest/_torch/moe/test_router_gemm_tf32.py +++ b/tests/unittest/_torch/moe/test_router_gemm_tf32.py @@ -2,13 +2,15 @@ # SPDX-License-Identifier: Apache-2.0 """Gate a for the batch-invariant TF32 router GEMM at the M3 gate shape ([M, 6144] x [6144, 128]): rows bitwise identical for every M (the breakable-prefill buckets included), run to run; error vs fp64 no worse than the stock -router (fp32 F.linear with TF32 allowed); top-4 (sigmoid + bias) close to stock. The split-K kernel (default) and the +TF32 F.linear comparison; the actual loaded stock gate and complete routing have a separate test. +The split-K kernel (default) and the single-pass kernel (kill TRTLLM_CTX_ROUTER_TF32_SPLITK=0) each meet all of it.""" import pytest import torch import torch.nn.functional as F +from tensorrt_llm._torch.models import modeling_minimaxm3 from tensorrt_llm._torch.moe.fused_moe import router_gemm_tf32 as rgt from tensorrt_llm._torch.moe.fused_moe.router_gemm_tf32 import ( prepare_router_weight_tf32, @@ -72,14 +74,13 @@ def test_m_invariant_and_deterministic(data) -> None: assert torch.equal(o.view(torch.int32), ref[:m].view(torch.int32)), f"rows differ at M={m}" -def test_error_and_top4_vs_stock(data) -> None: +def test_error_and_top4_vs_tf32_linear(data) -> None: x, w, wr, bias = data ref64 = x.double() @ w.double().t() prev = torch.backends.cuda.matmul.allow_tf32 try: - torch.backends.cuda.matmul.allow_tf32 = ( - True # stock: NGC TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1 - ) + # Same-precision comparison; the loaded stock gate is tested separately. + torch.backends.cuda.matmul.allow_tf32 = True stock = F.linear(x.float(), w) finally: torch.backends.cuda.matmul.allow_tf32 = prev @@ -215,3 +216,85 @@ def top4(lg): flips = int((top4(split) != top4(single)).any(1).sum()) assert flips <= m // 1000, (m, flips) + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability() != (10, 7), + reason="SM107 router replay validation", +) +def test_gate_tf32_cuda_graph_replay_after_refit(monkeypatch) -> None: + monkeypatch.setattr(modeling_minimaxm3, "_CTX_ROUTER_TF32_FIXED", True) + monkeypatch.setattr(modeling_minimaxm3, "_ROUTER_TC_GEN", False) + gate = modeling_minimaxm3.MiniMaxM3Gate(H, E, TOP_K, 1.0).cuda() + weight = torch.randn(E, H, device="cuda") / H**0.5 + gate.load_weights([{"weight": weight}]) + gate.cache_tf32_weight() + ptr = gate._weight_tf32.data_ptr() + x = torch.randn(128, H, device="cuda").bfloat16() + for _ in range(3): + gate(x) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured = gate(x) + before = captured.clone() + gate.load_weights([{"weight": -weight}]) + gate.cache_tf32_weight() + assert gate._weight_tf32.data_ptr() == ptr + graph.replay() + torch.testing.assert_close(captured, gate(x), rtol=0, atol=0) + assert not torch.equal(captured, before) + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability() != (10, 7), + reason="SM107 gate validation against the loaded stock router", +) +@pytest.mark.parametrize("rows", [48, 2048, 8192, 8193]) +def test_gate_tf32_vs_loaded_split_weight_and_complete_routing( + monkeypatch, data, rows: int +) -> None: + """Compare the production gate and full routing against the actual loaded stock path. + + Keep the existing top-k flip budget (at most one per thousand rows), require + every flip to lie within the measured score-perturbation tie band, and bound + normalized logit and matching-expert routing-weight errors by 5e-4. + This is a kernel/gate budget; model-level accuracy qualification is separate. + """ + x, weight, _, bias = data + x = x[:rows].contiguous() + gate = modeling_minimaxm3.MiniMaxM3Gate(H, E, TOP_K, 1.0).cuda() + gate.load_weights([{"weight": weight, "e_score_correction_bias": bias}]) + assert gate.split_weight is not None + assert gate._weight_tf32 is None + stock = gate(x) + stock_ids, stock_weights = gate.routing_method.apply(stock) + + monkeypatch.setattr(modeling_minimaxm3, "_CTX_ROUTER_TF32_FIXED", True) + gate.cache_tf32_weight() + optimized = gate(x) + optimized_ids, optimized_weights = gate.routing_method.apply(optimized) + reference = x.double() @ weight.double().t() + reference_scale = reference.abs().max().clamp_min(1e-30) + normalized_logit_error = float((optimized.double() - reference).abs().max() / reference_scale) + stock_logit_error = float((stock.double() - reference).abs().max() / reference_scale) + assert normalized_logit_error <= 5e-4, (normalized_logit_error, stock_logit_error) + + stock_order = stock_ids.argsort(dim=1) + optimized_order = optimized_ids.argsort(dim=1) + matched = (stock_ids.gather(1, stock_order) == optimized_ids.gather(1, optimized_order)).all(1) + flips = int((~matched).sum()) + assert flips <= rows // 1000, flips + scores = torch.sigmoid(stock) + bias + score_delta = (torch.sigmoid(optimized) - torch.sigmoid(stock)).abs().amax(dim=1) + ranked = scores.topk(TOP_K + 1, dim=1).values + clear_margin = ranked[:, TOP_K - 1] - ranked[:, TOP_K] > 2 * score_delta + assert not bool(((~matched) & clear_margin).any()), "routing changed away from a near-tie" + stock_aligned = stock_weights.gather(1, stock_order)[matched] + optimized_aligned = optimized_weights.gather(1, optimized_order)[matched] + weight_error = float((optimized_aligned - stock_aligned).abs().max()) + assert weight_error <= 5e-4, weight_error + print( + f"loaded-stock comparison: rows={rows}, stock_logit_error={stock_logit_error:.8g}, " + f"tf32_logit_error={normalized_logit_error:.8g}, complete_routing_flips={flips}, " + f"routing_weight_error={weight_error:.8g}" + ) diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py index 1b596ef343ae..6b8b743494d6 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py @@ -5241,6 +5241,26 @@ def test_reserve_is_opt_in(self, monkeypatch): assert ids(out.context_requests) == [0] assert head.context_chunk_size == 8192 + def test_reserve_released_for_indivisible_multimodal_block(self): + requests = [ + TestMultimodalAwareChunkingV2()._make_mm_req(i, 10000, [(0, 7000)]) for i in range(2) + ] + out = self._schedule(make_kv_cache_manager(tokens_per_block=64), requests) + assert ids(out.context_requests) == [0] + assert requests[0].context_chunk_size == 8192 + + def test_reserve_released_for_exact_pregrown_replay(self): + manager = make_kv_cache_manager(tokens_per_block=64) + manager.enable_swa_scratch_reuse = True + requests = [make_ctx_request(i, context_remaining_length=10000) for i in range(2)] + for request in requests: + manager.kv_cache_map[request.py_request_id].capacity = ( + 7168 + manager.num_extra_kv_tokens + ) + out = self._schedule(manager, requests) + assert ids(out.context_requests) == [0] + assert requests[0].context_chunk_size == 7168 + def test_short_request_takes_the_reserve_ahead_of_a_second_long_one(self): head = make_ctx_request(0, context_remaining_length=20000) long_second = make_ctx_request(1, context_remaining_length=6000) @@ -5917,3 +5937,23 @@ def test_generation_requests_still_scheduled(self): base, gated = self._both(64, reqs) assert ids(base.out.generation_requests) == ids(gated.out.generation_requests) == [2, 4] assert gated.admitted == [0] and gated.allocated == [0, 1] + + +@pytest.mark.parametrize("reserve", [0, 2048]) +def test_append_reserve_preserves_starved_context_token_cap( + monkeypatch: pytest.MonkeyPatch, reserve: int +) -> None: + monkeypatch.setenv("TLLM_CTX_APPEND_RESERVE", str(reserve)) + scheduler = make_scheduler( + make_kv_cache_manager(tokens_per_block=64), + max_num_tokens=8192, + ctx_chunk_config=(None, 64), + ) + request = make_ctx_request(0, context_remaining_length=20000) + budget = BudgetTracker(8192, 8) + action, tokens, chunked = scheduler._try_schedule_context( + request, budget, lambda req: False, token_cap=512 + ) + assert action is ScheduleAction.SCHEDULED + assert tokens == 512 and chunked + assert budget.max_num_tokens == 8192 From f26bc90d4c2a186aed62d4139db0cfd1d1248144 Mon Sep 17 00:00:00 2001 From: peihengh <259410613+peihu-nv@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:53:49 -0800 Subject: [PATCH 04/27] [None][fix] Validate CTX output layouts and chunk budgets Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com> --- 3rdparty/patches/msa_strided_paged_kv.patch | 18 ++++--- .../minimaxM3SelectPrefillTileOp.cpp | 1 + .../minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp | 14 ++--- .../pyexecutor/scheduler/scheduler_v2.py | 8 ++- .../sparse/msa/test_fmha_sm107_gates.py | 51 +++++++++++++++++++ .../sparse/msa/test_minimax_m3_tile_select.py | 12 +++++ .../attention/test_drafter_kv_tail_zero.py | 5 ++ .../kernels/serial/test_m3_ctx_fused_quant.py | 19 ++++++- .../_torch/moe/test_router_gemm_tf32.py | 2 + .../kv_cache/test_kv_cache_v2_scheduler.py | 11 ++++ 10 files changed, 126 insertions(+), 15 deletions(-) diff --git a/3rdparty/patches/msa_strided_paged_kv.patch b/3rdparty/patches/msa_strided_paged_kv.patch index 732680ff6b1b..64a4e5fa6707 100644 --- a/3rdparty/patches/msa_strided_paged_kv.patch +++ b/3rdparty/patches/msa_strided_paged_kv.patch @@ -5609,7 +5609,7 @@ index b9e6bbb..fa18fab 100644 ): """K2: merge sparse forward split partials into the final output. -@@ -1245,7 +1335,28 @@ def combine( +@@ -1245,7 +1335,34 @@ def combine( provided, the final O accumulator is multiplied once before store. use_pdl: When True, wait on PDL dependencies from the producer K1 kernel. When False, launch without PDL waits. @@ -5629,6 +5629,12 @@ index b9e6bbb..fa18fab 100644 + raise ValueError("the MXFP8 combine epilogue supports the varlen use_pdl path only") + if o_out.dtype != torch.bfloat16 or o_partial_fake.shape[-1] != 128: + raise ValueError("the MXFP8 combine epilogue needs a bf16 output and head_dim 128") ++ if o_fp8.device != o_out.device or sf_out.device != o_out.device: ++ raise ValueError("MXFP8 destinations must use the o_out device") ++ if sf_out.ndim != 1 or not sf_out.is_contiguous(): ++ raise ValueError("sf_out must be a contiguous one-dimensional buffer") ++ if o_fp8.dtype not in (torch.uint8, torch.float8_e4m3fn): ++ raise ValueError("o_fp8 must be uint8 or float8_e4m3fn") + o_fp8 = o_fp8.view(torch.uint8) + if o_fp8.shape != (o_out.shape[0], o_out.shape[1] * o_out.shape[2]) or not o_fp8.is_contiguous(): + raise ValueError(f"o_fp8 must be contiguous [total_q, head_q * dim], got {tuple(o_fp8.shape)}") @@ -5638,7 +5644,7 @@ index b9e6bbb..fa18fab 100644 D = o_partial_fake.shape[-1] num_splits = o_partial_fake.shape[0] return_temperature_lse = ( -@@ -1352,6 +1463,8 @@ def combine( +@@ -1352,6 +1469,8 @@ def combine( has_output_scale, use_pdl, min_blocks_per_mp, @@ -5647,7 +5653,7 @@ index b9e6bbb..fa18fab 100644 ) if key not in _combine_compile_cache: from src.common.aot_cache import try_load_aot, save_aot -@@ -1371,6 +1484,7 @@ def combine( +@@ -1371,6 +1490,7 @@ def combine( topk=num_splits, use_pdl=use_pdl, min_blocks_per_mp=min_blocks_per_mp, @@ -5655,7 +5661,7 @@ index b9e6bbb..fa18fab 100644 # stages=2 halves per-block SMEM (168 KB -> 103 KB) -> 2 blocks/SM, # theoretical occupancy 12.5% -> 25%. NCU DRAM throughput 76.35% # -> 88.64%. Runtime latency within noise (kernel already at HBM -@@ -1452,6 +1566,16 @@ def combine( +@@ -1452,6 +1572,16 @@ def combine( if has_output_scale else None ) @@ -5672,7 +5678,7 @@ index b9e6bbb..fa18fab 100644 stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) _combine_compile_cache[key] = cute.compile( -@@ -1474,6 +1598,8 @@ def combine( +@@ -1474,6 +1604,8 @@ def combine( mSplitCounts, mOutputScale, Int32(qheadperkv), @@ -5681,7 +5687,7 @@ index b9e6bbb..fa18fab 100644 stream, options="--enable-tvm-ffi", ) -@@ -1495,4 +1621,6 @@ def combine( +@@ -1495,4 +1627,6 @@ def combine( split_counts, output_scale, qheadperkv, diff --git a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp index e32458d9db79..d025c5fe1a2a 100644 --- a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp +++ b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3SelectPrefillTileOp.cpp @@ -52,6 +52,7 @@ void minimaxM3SelectPrefillTile(torch::Tensor const& scores, torch::Tensor const && out.size(1) == numKvHeads && out.size(2) == 16 && out.stride(2) == 1, "minimax_m3_select_prefill_tile: out must be int32 [total_q, num_kv_heads, 16] with unit last-dim stride"); + TORCH_CHECK(out.is_non_overlapping_and_dense(), "out must have a non-overlapping dense layout"); TORCH_CHECK(out.device() == scores.device(), "out must use the scores device"); c10::cuda::CUDAGuard const deviceGuard{scores.device()}; diff --git a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp index 6f88e973a352..d3609f17ac3a 100644 --- a/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp +++ b/cpp/tensorrt_llm/thop/minimaxM3/minimaxM3Sm107Tp2CtxNormMxfp8Op.cpp @@ -52,12 +52,6 @@ std::tuple