From 011eb24bf46e913661b2690ce6dd84cef27c88e5 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Fri, 18 Sep 2026 04:43:37 +0000 Subject: [PATCH 01/13] [None][feat] Support FP8 KV cache for non-MLA PrimsTS attention Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/backends/fmha/prims_ts.py | 101 ++++++++--- .../unittest/_torch/attention/backend_case.py | 9 +- .../test_prims_ts_attention_backend.py | 171 ++++++++++++++++++ .../_torch/attention/test_prims_ts_fmha.py | 88 +++++++-- 4 files changed, 324 insertions(+), 45 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 20b71a2a7c46..4c223e50aed4 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -105,6 +105,8 @@ def get_paged_kv_storage_unsupported_reason( def get_paged_kv_policy_unsupported_reason( attn: "TrtllmAttention", metadata: "TrtllmAttentionMetadata", + *, + allow_fp8_kv_cache: bool = False, ) -> Optional[str]: """Return why the request's decoding policy is outside the fixed page-table envelope.""" if metadata.beam_width != 1: @@ -123,13 +125,15 @@ def get_paged_kv_policy_unsupported_reason( quant_mode = QuantMode(attn.quant_mode) except (TypeError, ValueError): return "invalid KV-cache quantization mode." - is_fp8_mla = ( - attn.is_mla_enable + is_supported_fp8 = ( + (attn.is_mla_enable or allow_fp8_kv_cache) and quant_mode.has_fp8_kv_cache() and not quant_mode.has_int8_kv_cache() and not quant_mode.has_fp4_kv_cache() ) - if quant_mode.has_kv_cache_quant() and not is_fp8_mla: + if quant_mode.has_kv_cache_quant() and not is_supported_fp8: + if allow_fp8_kv_cache: + return "only FP8 E4M3 KV-cache quantization is supported." return "quantized KV cache is supported only for FP8 MLA decode." return None @@ -153,7 +157,12 @@ def get_attention_feature_unsupported_reason( class PrimsTSFmha(PhasedFmha): - """Blackwell task-scheduled paged context and decode FMHA library.""" + """Blackwell task-scheduled paged context and decode FMHA library. + + Standard FP8 KV cache uses fused preprocessing to quantize Q with the + shared Q/K/V scale. Kernels consume FP8 Q/K/V and write the model's FP16 + or BF16 output directly, using preprocessing-produced device scales. + """ supports_per_tensor_fp8 = True supports_vc_attention = True @@ -335,11 +344,12 @@ def _is_supported_with_reason( return False, "the attention mask is not causal or dense." if mask_type not in (AttentionMaskType.causal, AttentionMaskType.padding): return False, f"attention mask type {mask_type} is not supported." - policy_reason = get_paged_kv_policy_unsupported_reason(attn, meta) + policy_reason = get_paged_kv_policy_unsupported_reason(attn, meta, allow_fp8_kv_cache=True) if policy_reason is not None: return False, policy_reason is_mla = attn.is_mla_enable - is_fp8_mla = is_mla and QuantMode(attn.quant_mode).has_fp8_kv_cache() + is_fp8_kv = QuantMode(attn.quant_mode).has_fp8_kv_cache() + is_fp8_mla = is_mla and is_fp8_kv input_type = fwd.attention_input_type if input_type not in ( @@ -379,9 +389,9 @@ def _is_supported_with_reason( if q.dtype not in self.SUPPORTED_DTYPES: return False, f"query dtype {q.dtype} is unsupported." cache_dtype = binding_to_torch_dtype(meta.kv_cache_manager.dtype) - if is_fp8_mla and cache_dtype != torch.float8_e4m3fn: - return False, "FP8 MLA decode requires an FP8 E4M3 KV cache." - if not is_fp8_mla and cache_dtype != q.dtype: + if is_fp8_kv and cache_dtype != torch.float8_e4m3fn: + return False, "FP8 attention requires an FP8 E4M3 KV cache." + if not is_fp8_kv and cache_dtype != q.dtype: return False, f"query and KV-cache dtypes must match, got {q.dtype} and {cache_dtype}." if output.dtype != q.dtype: return False, f"output dtype must match query dtype, got {output.dtype} and {q.dtype}." @@ -412,6 +422,22 @@ def _is_supported_with_reason( if error is not None: return False, error else: + if is_fp8_kv: + for name, scale in ( + ("kv_scale_orig_quant", fwd.kv_scale_orig_quant), + ("kv_scale_quant_orig", fwd.kv_scale_quant_orig), + ): + if ( + scale is None + or scale.dtype != torch.float32 + or scale.device != q.device + or not scale.is_contiguous() + or scale.numel() != 1 + ): + return ( + False, + f"FP8 attention requires scalar float32 {name} on the query device.", + ) expected_width = (attn.num_heads + 2 * attn.num_kv_heads) * attn.head_dim if q.shape[1] != expected_width: return False, f"fused QKV width must be {expected_width}, got {q.shape[1]}." @@ -768,6 +794,7 @@ def _get_or_plan_decode_wrapper( mask_type=mask_type, window_left=window_left, workspace_buffer=workspace_buffer, + use_device_scales=QuantMode(self.attn.quant_mode).has_fp8_kv_cache(), ) self._decode_wrappers[batch_size] = wrapper return wrapper @@ -983,7 +1010,7 @@ def prepare_workspace( self.attn.head_dim, self.attn.rope_dim, True, - False, + QuantMode(self.attn.quant_mode).has_fp8_kv_cache(), skip_fmha_workspace=True, ) required_preprocess_bytes = max( @@ -1030,16 +1057,14 @@ def prepare_workspace( # sizing key aligned with the non-windowed plan selected at runtime. window_left = -1 + kernel_dtype = ( + torch.float8_e4m3fn if QuantMode(self.attn.quant_mode).has_fp8_kv_cache() else q.dtype + ) if self.attn.is_mla_enable: from tensorrt_llm._torch.attention.backends.prims_ts import ( get_prims_ts_batch_mla_decode_workspace_size, ) - kernel_dtype = ( - torch.float8_e4m3fn - if QuantMode(self.attn.quant_mode).has_fp8_kv_cache() - else q.dtype - ) required_bytes = get_prims_ts_batch_mla_decode_workspace_size( batch_size, self.attn.num_heads, @@ -1067,8 +1092,8 @@ def prepare_workspace( int(metadata.tokens_per_block), max_seq_len, seq_len_q=seq_len_q, - q_dtype=q.dtype, - kv_dtype=q.dtype, + q_dtype=kernel_dtype, + kv_dtype=kernel_dtype, out_dtype=forward_args.output.dtype, mask_type=mask_type, window_left=window_left, @@ -1155,8 +1180,8 @@ def run_context(self, params: FmhaParams) -> None: kv_pool, block_tables, _kv_scale_pool, - _bmm1_scale, - _bmm2_scale, + bmm1_scale, + bmm2_scale, fmha_workspace, cu_q_seqlens, _cu_kv_seqlens, @@ -1199,7 +1224,7 @@ def run_context(self, params: FmhaParams) -> None: self._get_bmm1_scale(attn), 1.0, attention_chunk_size, - False, + QuantMode(attn.quant_mode).has_fp8_kv_cache(), True, False, self._multi_processor_count, @@ -1231,6 +1256,9 @@ def run_context(self, params: FmhaParams) -> None: params.sequence_lengths, params.batch_size, ) + use_fp8 = QuantMode(attn.quant_mode).has_fp8_kv_cache() + if use_fp8: + q_processed = self._view_fp8_query(q_processed, params.num_tokens) mask_type = self._get_prims_mask_type(fwd) wrapper = self._get_or_plan_context_wrapper( q_processed, @@ -1252,6 +1280,8 @@ def run_context(self, params: FmhaParams) -> None: cu_q_seqlens, block_tables=fixed_block_tables, seq_lens_kv=seq_lens_kv, + scale_softmax_log2=bmm1_scale.reshape(-1)[1:2] if use_fp8 else None, + output_scale=bmm2_scale.reshape(-1)[:1] if use_fp8 else None, out=params.output, validate=False, ) @@ -1289,7 +1319,7 @@ def run_context(self, params: FmhaParams) -> None: rope_params.max_positions, attn.position_embedding_type, self._get_bmm1_scale(attn), - False, + QuantMode(attn.quant_mode).has_fp8_kv_cache(), True, False, attention_chunk_size, @@ -1343,7 +1373,7 @@ def _run_generation_preprocess(self, params: FmhaParams) -> tuple[Any, ...]: attn.position_embedding_type, self._get_bmm1_scale(attn), 1.0, - False, + QuantMode(attn.quant_mode).has_fp8_kv_cache(), attn.predicted_tokens_per_seq, attention_chunk_size, self._multi_processor_count, @@ -1371,8 +1401,8 @@ def run_generation(self, params: FmhaParams) -> None: kv_pool, block_tables, _kv_scale_pool, - _bmm1_scale, - _bmm2_scale, + bmm1_scale, + bmm2_scale, fmha_workspace, _cu_seqlens, _max_q_len, @@ -1399,6 +1429,9 @@ def run_generation(self, params: FmhaParams) -> None: fixed_block_tables = self._get_fixed_block_tables(block_tables, batch_size) max_seq_len = int(block_tables.shape[-1]) * params.tokens_per_block seq_lens = self._get_sequence_lengths(params.sequence_lengths, batch_size) + use_fp8 = QuantMode(attn.quant_mode).has_fp8_kv_cache() + if use_fp8: + q_processed = self._view_fp8_query(q_processed, params.num_tokens) query = q_processed.view( batch_size, params.input_seq_length, @@ -1443,12 +1476,28 @@ def run_generation(self, params: FmhaParams) -> None: (k_cache, v_cache), seq_lens, block_tables=fixed_block_tables, - softmax_scale=self._get_bmm1_scale(attn), - output_scale=1.0, + bmm1_scale=self._get_bmm1_scale(attn), + bmm2_scale=1.0, + bmm1_scale_device=bmm1_scale.reshape(-1)[:1] if use_fp8 else None, + bmm2_scale_device=bmm2_scale.reshape(-1)[:1] if use_fp8 else None, out=output, validate=False, ) + def _view_fp8_query(self, q_processed: torch.Tensor, num_tokens: int) -> torch.Tensor: + """View the packed FP8 prefix written by fused QKV preprocessing. + + Generation reserves a model-dtype Q buffer, but writes one byte per + element when FP8 is enabled. Its unused trailing bytes are not queries. + """ + numel = num_tokens * self.attn.num_heads * self.attn.head_dim + return ( + q_processed.view(torch.uint8) + .reshape(-1)[:numel] + .view(torch.float8_e4m3fn) + .view(num_tokens, self.attn.num_heads, self.attn.head_dim) + ) + def _get_decode_workspace( self, root_workspace: torch.Tensor, diff --git a/tests/unittest/_torch/attention/backend_case.py b/tests/unittest/_torch/attention/backend_case.py index 4c1b1cdfa02e..beaad315ee56 100644 --- a/tests/unittest/_torch/attention/backend_case.py +++ b/tests/unittest/_torch/attention/backend_case.py @@ -1651,6 +1651,13 @@ def run_backend( def create_metadata(AttentionCls, case, mgr, *, num_contexts: int = 0): seq_lens_kv = torch.tensor(case.seq_lens_kv, dtype=torch.int) if case.is_cross else None + # Context preprocessing needs this chunk's Q length; the cached + # prefix is already included separately in kv_lens by prepare(). + prompt_lens = ( + case.seq_lens + if case.is_cross + else case.seq_lens[:num_contexts] + case.token_nums[num_contexts:] + ) return AttentionCls.Metadata( num_contexts=num_contexts, kv_cache_params=KVCacheParams( @@ -1662,7 +1669,7 @@ def create_metadata(AttentionCls, case, mgr, *, num_contexts: int = 0): max_num_tokens=case.max_num_tokens, kv_cache_manager=mgr, request_ids=request_ids, - prompt_lens=case.seq_lens if case.is_cross else case.token_nums, + prompt_lens=prompt_lens, kv_layout=kv_layout, ) diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 9242485ebec9..6578154eac18 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -98,17 +98,28 @@ }, id="mixed", ), + pytest.param( + {"seq_lens": [41, 17], "num_cached_tokens": [63, 32], "num_contexts": 2}, + id="cached-context", + ), + pytest.param( + {"seq_lens": [1, 1], "num_cached_tokens": [8191, 4096], "num_contexts": 0}, + id="long-generation", + ), ], ) +@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["bf16-kv", "fp8-kv"]) def test_prims_ts_qwen2_gqa( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, phase_args: dict, + kv_dtype: str | None, ) -> None: monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") case = BackendCase( **_QWEN2_7B, **phase_args, + kv_dtype=kv_dtype, use_kv_cache_manager_v2=use_kv_cache_manager_v2, ) @@ -200,8 +211,10 @@ def run_with_zeroed_v_tail_check( assert zeroed_tails == [(0, 1), (1, 5)] +@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["fp16-kv", "fp8-kv"]) def test_prims_ts_fp16_dense_context_with_alternate_shape( monkeypatch: pytest.MonkeyPatch, + kv_dtype: str | None, ) -> None: monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") case = BackendCase( @@ -212,6 +225,7 @@ def test_prims_ts_fp16_dense_context_with_alternate_shape( num_cached_tokens=[0, 0], num_contexts=2, dtype="float16", + kv_dtype=kv_dtype, causal=False, kv_layout="HND", page_size=64, @@ -1685,3 +1699,160 @@ def counted_prims_context(self, *args, **kwargs): assert calls["fallback"] > 0 assert calls["prims_context"] == 0 + + +@pytest.mark.parametrize("head_dim", [64, 128, 256]) +@pytest.mark.parametrize( + ("mode", "page_size", "head_ratio"), + [ + ("disabled", 16, 1), + ("gmem_reduction", 32, 7), + ("gmem_reduction_with_separate_kernel", 64, 8), + ("cluster_smem_reduction", 128, 16), + ], +) +def test_prims_ts_fp8_decode_bf16_device_scales( + monkeypatch: pytest.MonkeyPatch, head_dim: int, mode: str, page_size: int, head_ratio: int +) -> None: + """Qualify BF16 stores/reducers and live device scales across graph replay.""" + from dataclasses import replace + + import cutlass + + from tensorrt_llm._torch.attention.backends.prims_ts import decode + from tensorrt_llm._torch.attention.backends.prims_ts.kernels.fmha_decode.fmha_decode_config import ( + make_decode_config, + ) + + torch.manual_seed(123) + batch_size, kv_heads = 2, 2 + qo_heads = kv_heads * head_ratio + max_kv_len = 2048 + pages_per_seq = max_kv_len // page_size + num_pages = batch_size * pages_per_seq + q = torch.randn(batch_size, qo_heads, head_dim, device="cuda").to(torch.float8_e4m3fn) + k = torch.randn(num_pages, kv_heads, page_size, head_dim, device="cuda").to(torch.float8_e4m3fn) + v = torch.randn_like(k, dtype=torch.float32).to(torch.float8_e4m3fn) + # Permuted pages and padded table rows catch assumptions about pool layout. + table = torch.full((batch_size, pages_per_seq + 3), -1, dtype=torch.int32, device="cuda") + table[:, :pages_per_seq] = torch.randperm(num_pages, device="cuda").reshape(batch_size, -1) + lengths_host = [max_kv_len - 13, max_kv_len // 2 + 7] + lengths = torch.tensor(lengths_host, dtype=torch.int32, device="cuda") + bmm1 = torch.tensor([0.25 / math.sqrt(head_dim)], device="cuda") + bmm2 = torch.tensor([1.75], device="cuda") + output = torch.empty_like(q, dtype=torch.bfloat16) + splits = 1 if mode == "disabled" else 4 + cfg = make_decode_config( + headdim=head_dim, + args={"tile_size_q": 16, "groups_tokens_heads_q": True, "use_keeps_mma_ab": False}, + seq_len_q=1, + seq_len_kv=max_kv_len, + batch_size=batch_size, + num_heads_q=qo_heads, + num_heads_kv=kv_heads, + qkv_dtype=cutlass.Float8E4M3FN, + o_dtype=cutlass.BFloat16, + qkv_layout="pagedKv", + num_tokens_per_page=page_size, + split_kv_mode=mode, + splits_kv=splits, + max_splits_kv=splits, + mask_type="causal", + auto_tuner=False, + ) + + def plan(output_dtype: torch.dtype, use_device_scales: bool): + spec = decode._decode_launch_spec_from_config( + replace( + cfg, + out_dtype=cutlass.BFloat16 if output_dtype == torch.bfloat16 else cutlass.Float16, + ), + batch_size=batch_size, + num_qo_heads=qo_heads, + num_kv_heads=kv_heads, + head_dim=head_dim, + seq_len_q=1, + max_active_clusters=torch.cuda.get_device_properties(0).multi_processor_count, + ) + monkeypatch.setattr(decode, "_resolve_decode_launch_spec", lambda *args: spec) + wrapper = decode.BatchDecodePagedTSWrapper() + wrapper.plan( + q.device, + batch_size, + qo_heads, + kv_heads, + head_dim, + page_size, + max_kv_len, + q_data_type=q.dtype, + o_data_type=output_dtype, + mask_type="causal", + use_device_scales=use_device_scales, + ) + return wrapper + + wrapper = plan(torch.bfloat16, True) + fp16_wrapper = plan(torch.float16, False) + + def run() -> torch.Tensor: + if mode == "gmem_reduction": + wrapper._plan_state.workspace.split_kv_counter.zero_() + return wrapper.run( + q, + (k, v), + lengths, + table, + out=output, + bmm1_scale_device=bmm1, + bmm2_scale_device=bmm2, + validate=False, + ) + + def reference() -> torch.Tensor: + results = [] + for batch_idx, length in enumerate(lengths_host): + ids = table[batch_idx, :pages_per_seq].long() + keys = k.float()[ids].permute(1, 0, 2, 3).reshape(kv_heads, -1, head_dim)[:, :length] + values = v.float()[ids].permute(1, 0, 2, 3).reshape(kv_heads, -1, head_dim)[:, :length] + keys = keys.repeat_interleave(head_ratio, dim=0) + values = values.repeat_interleave(head_ratio, dim=0) + scores = torch.einsum("hd,htd->ht", q[batch_idx].float(), keys) * bmm1 + results.append(torch.einsum("ht,htd->hd", scores.softmax(-1), values) * bmm2) + return torch.stack(results) + + def check_output() -> None: + # The FP8 kernel rounds the intermediate P operand to E4M3. Compare + # math with that quantization tolerance, and the existing FP16 output + # path tightly to isolate BF16 stores and device-scale handling. + torch.testing.assert_close(output.float(), reference(), atol=0.01, rtol=0.05) + if mode == "gmem_reduction": + fp16_wrapper._plan_state.workspace.split_kv_counter.zero_() + fp16_output = fp16_wrapper.run( + q, + (k, v), + lengths, + table, + bmm1_scale=bmm1.item(), + bmm2_scale=bmm2.item(), + validate=False, + ) + torch.testing.assert_close(output.float(), fp16_output.float(), atol=0.0005, rtol=0.008) + + run() + torch.cuda.synchronize() + check_output() + + def no_host_read(*args, **kwargs): + raise AssertionError("decode must not read scales back to the host") + + with monkeypatch.context() as guard: + guard.setattr(torch.Tensor, "item", no_host_read) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + run() + # Both attention scores and final output must consume updated scales. + bmm1.mul_(2) + bmm2.mul_(0.5) + graph.replay() + torch.cuda.synchronize() + check_output() diff --git a/tests/unittest/_torch/attention/test_prims_ts_fmha.py b/tests/unittest/_torch/attention/test_prims_ts_fmha.py index 0343355ae562..6d49b9c1f4a2 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_fmha.py +++ b/tests/unittest/_torch/attention/test_prims_ts_fmha.py @@ -196,6 +196,9 @@ def _support_result( relative_attention_bias=torch.empty(1) if has_relative_attention_bias else None, is_fused_qkv=is_fused_qkv, ) + if quant_mode.has_fp8_kv_cache(): + forward_args.kv_scale_orig_quant = _TensorSpec((1,), torch.float32) + forward_args.kv_scale_quant_orig = _TensorSpec((1,), torch.float32) if is_mla and quant_mode.has_fp8_kv_cache(): forward_args.quant_q_buffer = _TensorSpec(q.shape, torch.uint8) forward_args.mla_bmm1_scale = _TensorSpec((2,), torch.float32) @@ -321,6 +324,20 @@ def test_supported_matrix(case: dict) -> None: assert supported, reason +@pytest.mark.parametrize("phase", list(AttentionInputType)) +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("use_v2", [False, True]) +def test_fp8_standard_supported(phase, dtype, use_v2) -> None: + supported, reason = _support_result( + attention_input_type=phase, + dtype=dtype, + kv_dtype=DataType.FP8, + quant_mode=QuantMode.FP8_KV_CACHE, + use_kv_cache_v2=use_v2, + ) + assert supported, reason + + @pytest.mark.parametrize("num_heads", [6, 12, 64, 96, 128]) @pytest.mark.parametrize("use_kv_cache_v2", [False, True]) @pytest.mark.parametrize("tokens_per_block", [16, 32, 64, 128]) @@ -345,10 +362,12 @@ def test_fp8_mla_supported( @pytest.mark.parametrize( ("overrides", "expected_reason"), [ - ({"is_mla": False, "head_dim": 128}, "only for FP8 MLA"), - ({"quant_mode": QuantMode.INT8_KV_CACHE}, "only for FP8 MLA"), - ({"quant_mode": QuantMode.NVFP4_KV_CACHE}, "only for FP8 MLA"), - ({"quant_mode": QuantMode.FP8_KV_CACHE | QuantMode.INT8_KV_CACHE}, "only for FP8 MLA"), + ({"quant_mode": QuantMode.INT8_KV_CACHE}, "only FP8 E4M3 KV-cache quantization"), + ({"quant_mode": QuantMode.NVFP4_KV_CACHE}, "only FP8 E4M3 KV-cache quantization"), + ( + {"quant_mode": QuantMode.FP8_KV_CACHE | QuantMode.INT8_KV_CACHE}, + "only FP8 E4M3 KV-cache quantization", + ), ({"kv_dtype": DataType.BF16}, "FP8 E4M3 KV cache"), ({"quant_mode": QuantMode(0)}, "query and KV-cache dtypes"), ({"dtype": torch.float16}, "BF16 query input and output"), @@ -915,15 +934,21 @@ def test_sequence_lengths_are_live_source_view() -> None: torch.testing.assert_close(actual, torch.tensor([33, 65], dtype=torch.int32)) +@pytest.mark.parametrize("fp8", [False, True], ids=["bf16", "fp8"]) def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( monkeypatch: pytest.MonkeyPatch, + fp8: bool, ) -> None: monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) attn = _Attention() + attn.quant_mode = QuantMode.FP8_KV_CACHE if fp8 else QuantMode(0) + kernel_dtype = torch.float8_e4m3fn if fp8 else torch.bfloat16 + bmm1 = torch.tensor([0.125, 0.125 * math.log2(math.e)]) + bmm2 = torch.tensor([0.75]) fmha = PrimsTSFmha(attn) fmha._multi_processor_count = 120 q_processed = torch.empty((3, attn.num_heads, attn.head_dim), dtype=torch.bfloat16) - kv_pool = torch.empty((12, attn.num_kv_heads, 32, attn.head_dim), dtype=torch.bfloat16) + kv_pool = torch.empty((12, attn.num_kv_heads, 32, attn.head_dim), dtype=kernel_dtype) block_tables = torch.tensor( [ [[0, 1, 2, 3], [6, 7, 8, 9]], @@ -940,8 +965,8 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( kv_pool, block_tables, None, - 1.0, - 1.0, + bmm1, + bmm2, fmha_workspace, cu_q_seqlens, cu_kv_seqlens, @@ -1037,9 +1062,9 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( "num_qo_heads": attn.num_heads, "num_kv_heads": attn.num_kv_heads, "head_dim": attn.head_dim, - "q_dtype": torch.bfloat16, - "k_dtype": torch.bfloat16, - "v_dtype": torch.bfloat16, + "q_dtype": kernel_dtype, + "k_dtype": kernel_dtype, + "v_dtype": kernel_dtype, "out_dtype": torch.bfloat16, "page_size": 32, "mask_type": "causal", @@ -1051,7 +1076,13 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( wrapper.run.assert_called_once() run_args = wrapper.run.call_args.args run_kwargs = wrapper.run.call_args.kwargs - assert run_args[0] is q_processed + assert run_args[0].data_ptr() == q_processed.data_ptr() + assert run_args[0].dtype == kernel_dtype + assert context_preprocess.call_args.args[35] is fp8 + assert context_postprocess.call_args.args[32] is fp8 + if fp8: + assert run_kwargs["scale_softmax_log2"].data_ptr() == bmm1[1:].data_ptr() + assert run_kwargs["output_scale"].data_ptr() == bmm2.data_ptr() k_cache, v_cache = run_args[1], run_args[2] assert k_cache.shape == v_cache.shape == (6, attn.num_kv_heads, 32, attn.head_dim) assert v_cache.storage_offset() - k_cache.storage_offset() == 6 * math.prod(kv_pool.shape[1:]) @@ -1119,8 +1150,10 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( pytest.param(True, False, True, False, id="cluster-smem-reduction"), ), ) +@pytest.mark.parametrize("fp8", [False, True], ids=["bf16", "fp8"]) def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( monkeypatch: pytest.MonkeyPatch, + fp8: bool, use_split_kv: bool, use_separate_reduction_kernel: bool, use_cluster_smem_reduction: bool, @@ -1128,13 +1161,17 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( ) -> None: monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) attn = _Attention() + attn.quant_mode = QuantMode.FP8_KV_CACHE if fp8 else QuantMode(0) + kernel_dtype = torch.float8_e4m3fn if fp8 else torch.bfloat16 + bmm1 = torch.tensor([0.125, 0.125 * math.log2(math.e)]) + bmm2 = torch.tensor([0.75]) fmha = PrimsTSFmha(attn) fmha._multi_processor_count = 120 fmha._decode_workspace_offset_bytes = 0 fmha._decode_workspace_required_bytes = 64 fmha_workspace = torch.empty(0, dtype=torch.uint8) q_processed = torch.empty((2, attn.num_heads, attn.head_dim), dtype=torch.bfloat16) - kv_pool = torch.empty((12, attn.num_kv_heads, 32, attn.head_dim), dtype=torch.bfloat16) + kv_pool = torch.empty((12, attn.num_kv_heads, 32, attn.head_dim), dtype=kernel_dtype) block_tables = torch.tensor( [ [[0, 1, 2, 3], [6, 7, 8, 9]], @@ -1150,8 +1187,8 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( kv_pool, block_tables, None, - 1.0, - 1.0, + bmm1, + bmm2, fmha_workspace, None, 1, @@ -1252,9 +1289,10 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( assert {key: value for key, value in plan_kwargs.items() if key != "workspace_buffer"} == { "max_q_len": 1, "packed_query": False, - "q_dtype": torch.bfloat16, - "kv_dtype": torch.bfloat16, - "out_dtype": torch.bfloat16, + "use_device_scales": fp8, + "q_data_type": kernel_dtype, + "kv_data_type": kernel_dtype, + "o_data_type": torch.bfloat16, "mask_type": "causal", "window_left": 15, } @@ -1264,6 +1302,11 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( run_kwargs = wrapper.run.call_args.kwargs assert run_args[0].shape == (2, attn.num_heads, attn.head_dim) assert run_args[0].data_ptr() == q_processed.data_ptr() + assert run_args[0].dtype == kernel_dtype + assert generation_preprocess.call_args.args[35] is fp8 + if fp8: + assert run_kwargs["bmm1_scale_device"].data_ptr() == bmm1.data_ptr() + assert run_kwargs["bmm2_scale_device"].data_ptr() == bmm2.data_ptr() k_cache, v_cache = run_args[1] assert k_cache.shape == v_cache.shape == (6, attn.num_kv_heads, 32, attn.head_dim) assert v_cache.storage_offset() - k_cache.storage_offset() == 6 * math.prod(kv_pool.shape[1:]) @@ -2075,8 +2118,10 @@ def test_mla_caller_workspace_grows_across_plan_profiles( assert workspace.numel() == 64 +@pytest.mark.parametrize("fp8", [False, True]) def test_decode_prepare_workspace_reserves_tail_after_compact_preprocessing( monkeypatch: pytest.MonkeyPatch, + fp8: bool, ) -> None: monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) monkeypatch.setattr( @@ -2084,12 +2129,14 @@ def test_decode_prepare_workspace_reserves_tail_after_compact_preprocessing( "get_trtllm_gen_generation_workspace_layout", lambda *args, **kwargs: {"total_size": 64}, ) + workspace_size = Mock(return_value=48) monkeypatch.setattr( prims_ts_package, "get_prims_ts_batch_decode_workspace_size", - lambda *args, **kwargs: 48, + workspace_size, ) attn = _Attention() + attn.quant_mode = QuantMode.FP8_KV_CACHE if fp8 else QuantMode(0) fmha = PrimsTSFmha(attn) fmha._multi_processor_count = 1 metadata = SimpleNamespace( @@ -2123,6 +2170,11 @@ def test_decode_prepare_workspace_reserves_tail_after_compact_preprocessing( assert decode_workspace.data_ptr() == workspace.data_ptr() + 64 assert decode_workspace.numel() == 48 + expected_dtype = torch.float8_e4m3fn if fp8 else torch.bfloat16 + assert workspace_size.call_args.kwargs["q_dtype"] == expected_dtype + assert workspace_size.call_args.kwargs["kv_dtype"] == expected_dtype + assert workspace_size.call_args.kwargs["out_dtype"] == torch.bfloat16 + def test_decode_workspace_tail_is_stable_across_mixed_context_layouts( monkeypatch: pytest.MonkeyPatch, From 2ce050aec6d07f25a9cda479a120d70dc1ab7850 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Tue, 13 Oct 2026 09:17:03 +0000 Subject: [PATCH 02/13] [None][fix] Adapt FP8 decode integration to refreshed PrimTS APIs Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../_torch/attention/test_prims_ts_attention_backend.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 6578154eac18..6c0eaab9160e 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -1774,7 +1774,7 @@ def plan(output_dtype: torch.dtype, use_device_scales: bool): seq_len_q=1, max_active_clusters=torch.cuda.get_device_properties(0).multi_processor_count, ) - monkeypatch.setattr(decode, "_resolve_decode_launch_spec", lambda *args: spec) + monkeypatch.setattr(decode, "_resolve_decode_launch_spec", lambda *args, **kwargs: spec) wrapper = decode.BatchDecodePagedTSWrapper() wrapper.plan( q.device, From ae3b72809f34f7ded2b587d812b2a8dfaf5c3dfa Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:07:39 +0000 Subject: [PATCH 03/13] [None][fix] Separate persistent FP8 decode scale specializations Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/test_prims_ts_attention_backend.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 6c0eaab9160e..347c7deccd47 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -1793,6 +1793,7 @@ def plan(output_dtype: torch.dtype, use_device_scales: bool): wrapper = plan(torch.bfloat16, True) fp16_wrapper = plan(torch.float16, False) + bf16_host_wrapper = plan(torch.bfloat16, False) def run() -> torch.Tensor: if mode == "gmem_reduction": @@ -1838,6 +1839,21 @@ def check_output() -> None: ) torch.testing.assert_close(output.float(), fp16_output.float(), atol=0.0005, rtol=0.008) + if mode == "gmem_reduction": + bf16_host_wrapper._plan_state.workspace.split_kv_counter.zero_() + bf16_host_output = bf16_host_wrapper.run( + q, + (k, v), + lengths, + table, + bmm1_scale=bmm1.item(), + bmm2_scale=bmm2.item(), + validate=False, + ) + torch.testing.assert_close( + output.float(), bf16_host_output.float(), atol=0.0005, rtol=0.008 + ) + run() torch.cuda.synchronize() check_output() From 77aaec7a849633b4cec6f2f003aabdbf8117f6ca Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:05:06 +0000 Subject: [PATCH 04/13] [None][fix] Enable non-MLA PrimsTS attention on Rubin Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/backends/fmha/prims_ts.py | 23 +++++++++++----- .../test_prims_ts_attention_backend.py | 18 ++++++++++--- .../_torch/attention/test_prims_ts_fmha.py | 27 ++++++++++++------- 3 files changed, 48 insertions(+), 20 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 4c223e50aed4..2c0b3f8f3d7d 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""TRT-LLM FMHA adapter for the vendored PrimTS Blackwell kernels.""" +"""TRT-LLM FMHA adapter for the vendored PrimTS kernels.""" from __future__ import annotations @@ -58,6 +58,7 @@ _MIN_CUTLASS_DSL_VERSION = Version("4.7.0") +_MIN_RUBIN_CUTLASS_DSL_VERSION = Version("4.8.0") _MIN_CUTLASS_COMPILER_VERSION = "13.3" _WORKSPACE_ALIGNMENT = 32 @@ -157,7 +158,7 @@ def get_attention_feature_unsupported_reason( class PrimsTSFmha(PhasedFmha): - """Blackwell task-scheduled paged context and decode FMHA library. + """Task-scheduled paged context and decode FMHA library. Standard FP8 KV cache uses fused preprocessing to quantize Q with the shared Q/K/V scale. Kernels consume FP8 Q/K/V and write the model's FP16 @@ -167,7 +168,7 @@ class PrimsTSFmha(PhasedFmha): supports_per_tensor_fp8 = True supports_vc_attention = True - SUPPORTED_SMS = frozenset({100, 103}) + SUPPORTED_SMS = frozenset({100, 103, 107}) SUPPORTED_PAGE_SIZES = {16, 32, 64, 128} SUPPORTED_CONTEXT_HEAD_DIMS = {128, 256} SUPPORTED_DECODE_HEAD_DIMS = {64, 128, 256} @@ -203,17 +204,25 @@ def __init__(self, attn: "TrtllmAttention") -> None: def _is_available(cls, attn: "TrtllmAttention") -> bool: sm = get_sm_version() if sm not in cls.SUPPORTED_SMS: - logger.debug(f"PrimTS FMHA is unavailable: requires SM100 or SM103, got SM{sm}.") + logger.debug( + f"PrimTS FMHA is unavailable: requires SM100, SM103, or SM107, got SM{sm}." + ) + return False + if sm == 107 and attn.is_mla_enable: + logger.debug("PrimTS MLA FMHA is unavailable on SM107.") return False + min_dsl_version = _MIN_RUBIN_CUTLASS_DSL_VERSION if sm == 107 else _MIN_CUTLASS_DSL_VERSION try: installed_version = Version(version("nvidia-cutlass-dsl")) except (PackageNotFoundError, InvalidVersion): - logger.debug("PrimTS FMHA is unavailable: nvidia-cutlass-dsl>=4.7 is required.") + logger.debug( + f"PrimTS FMHA is unavailable: nvidia-cutlass-dsl>={min_dsl_version} is required." + ) return False - if installed_version < _MIN_CUTLASS_DSL_VERSION: + if installed_version < min_dsl_version: logger.debug( "PrimTS FMHA is unavailable: " - f"nvidia-cutlass-dsl>={_MIN_CUTLASS_DSL_VERSION} is required, " + f"nvidia-cutlass-dsl>={min_dsl_version} is required, " f"got {installed_version}." ) return False diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 347c7deccd47..5a0bb3cfa759 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -33,8 +33,14 @@ from utils.util import getSMVersion pytestmark = pytest.mark.skipif( + getSMVersion() not in (100, 103, 107), + reason="PrimsTS attention kernels require SM100, SM103, or SM107", +) + + +_REQUIRES_BLACKWELL_MLA = pytest.mark.skipif( getSMVersion() not in (100, 103), - reason="PrimsTS attention kernels require SM100 or SM103", + reason="MLA PrimsTS integration requires SM100 or SM103", ) @@ -108,16 +114,18 @@ ), ], ) -@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["bf16-kv", "fp8-kv"]) +@pytest.mark.parametrize("dtype", ["bfloat16", "float16"], ids=["bf16", "fp16"]) +@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) def test_prims_ts_qwen2_gqa( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, phase_args: dict, kv_dtype: str | None, + dtype: str, ) -> None: monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") case = BackendCase( - **_QWEN2_7B, + **{**_QWEN2_7B, "dtype": dtype}, **phase_args, kv_dtype=kv_dtype, use_kv_cache_manager_v2=use_kv_cache_manager_v2, @@ -377,6 +385,7 @@ def record_decode_workspace( @pytest.mark.parametrize("use_kv_cache_manager_v2", [False, True], ids=["v1", "v2"]) +@_REQUIRES_BLACKWELL_MLA def test_prims_ts_deepseek_v3_lite_mla_generation( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, @@ -395,6 +404,7 @@ def test_prims_ts_deepseek_v3_lite_mla_generation( @pytest.mark.parametrize("num_heads", [6, 12, 96]) @pytest.mark.parametrize("use_kv_cache_manager_v2", [False, True], ids=["v1", "v2"]) +@_REQUIRES_BLACKWELL_MLA def test_prims_ts_fp8_mla_preprocessing( monkeypatch: pytest.MonkeyPatch, num_heads: int, use_kv_cache_manager_v2: bool ) -> None: @@ -461,6 +471,7 @@ def run_and_capture(fmha: PrimsTSFmha, params: FmhaParams) -> None: @pytest.mark.parametrize("num_heads", [6, 12, 96]) @pytest.mark.parametrize("batch_size", [2, 65]) @pytest.mark.parametrize("max_seq_len", [64, 128], ids=["short-kv", "regular-kv"]) +@_REQUIRES_BLACKWELL_MLA def test_prims_ts_fp8_mla_scales_and_graph_replay( monkeypatch: pytest.MonkeyPatch, num_heads: int, batch_size: int, max_seq_len: int ) -> None: @@ -938,6 +949,7 @@ def test_prims_ts_decode_live_wrapper_cuda_graph_replay() -> None: @pytest.mark.parametrize("max_seq_len", [64, 1024], ids=["short-kv", "regular-kv"]) +@_REQUIRES_BLACKWELL_MLA def test_prims_ts_mla_live_wrapper_cuda_graph_replay(max_seq_len: int) -> None: from tensorrt_llm._torch.attention.backends.prims_ts import ( BatchMLADecodePagedTSWrapper, diff --git a/tests/unittest/_torch/attention/test_prims_ts_fmha.py b/tests/unittest/_torch/attention/test_prims_ts_fmha.py index 6d49b9c1f4a2..c82fb31ab627 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_fmha.py +++ b/tests/unittest/_torch/attention/test_prims_ts_fmha.py @@ -722,15 +722,19 @@ def test_unsupported_matrix_falls_through(case: dict, expected_reason: str) -> N @pytest.mark.parametrize( - ("sm", "cutlass_version", "compiler_version", "expected"), + ("sm", "cutlass_version", "compiler_version", "is_mla", "expected"), [ - (100, "4.7.0", "13.3", True), - (103, "4.7.0", "13.3", True), - (100, "4.7.0", "13.4", True), - (100, "4.7.0", "13.2", False), - (107, "4.7.0", "13.3", False), - (120, "4.7.0", "13.3", False), - (100, "4.6.2", "13.3", False), + (100, "4.7.0", "13.3", False, True), + (103, "4.7.0", "13.3", False, True), + (100, "4.7.0", "13.4", False, True), + (100, "4.7.0", "13.2", False, False), + (107, "4.7.0", "13.3", False, False), + (107, "4.8.0", "13.3", False, True), + (107, "4.8.0", "13.2", False, False), + (107, "4.8.0", "13.3", True, False), + (100, "4.7.0", "13.3", True, True), + (120, "4.7.0", "13.3", False, False), + (100, "4.6.2", "13.3", False, False), ], ) def test_static_availability_gate( @@ -738,6 +742,7 @@ def test_static_availability_gate( sm: int, cutlass_version: str, compiler_version: str, + is_mla: bool, expected: bool, ) -> None: target_version = Mock( @@ -756,8 +761,10 @@ def import_cutlass_module(module_name: str) -> object: monkeypatch.setattr(prims_ts_module, "import_module", import_cutlass_module) monkeypatch.setattr(PrimsTSFmha, "_missing_fused_nanobind_ops", staticmethod(lambda: [])) - assert PrimsTSFmha.is_available(_Attention()) is expected - if sm in (100, 103) and Version(cutlass_version) >= Version("4.7.0"): + assert PrimsTSFmha.is_available(_Attention(is_mla=is_mla)) is expected + if (sm in (100, 103) and Version(cutlass_version) >= Version("4.7.0")) or ( + sm == 107 and not is_mla and Version(cutlass_version) >= Version("4.8.0") + ): target_version.assert_called_once_with(min_version="13.3") else: target_version.assert_not_called() From c8cafb62efdcfe7929ef837c967eb6e597a6ddeb Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:58:30 +0000 Subject: [PATCH 05/13] [None][fix] Simplify PrimsTS FP8 scale arguments Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/backends/fmha/prims_ts.py | 25 +----------- .../test_prims_ts_attention_backend.py | 24 ++++++++++-- .../_torch/attention/test_prims_ts_fmha.py | 39 ++++++++----------- 3 files changed, 39 insertions(+), 49 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 2c0b3f8f3d7d..02375d0b1dc3 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -19,11 +19,9 @@ import math from importlib import import_module -from importlib.metadata import PackageNotFoundError, version from typing import TYPE_CHECKING, Any, Optional import torch -from packaging.version import InvalidVersion, Version from tensorrt_llm._torch.attention.backends.interface import ( AttentionForwardArgs, @@ -57,8 +55,6 @@ ) -_MIN_CUTLASS_DSL_VERSION = Version("4.7.0") -_MIN_RUBIN_CUTLASS_DSL_VERSION = Version("4.8.0") _MIN_CUTLASS_COMPILER_VERSION = "13.3" _WORKSPACE_ALIGNMENT = 32 @@ -211,21 +207,6 @@ def _is_available(cls, attn: "TrtllmAttention") -> bool: if sm == 107 and attn.is_mla_enable: logger.debug("PrimTS MLA FMHA is unavailable on SM107.") return False - min_dsl_version = _MIN_RUBIN_CUTLASS_DSL_VERSION if sm == 107 else _MIN_CUTLASS_DSL_VERSION - try: - installed_version = Version(version("nvidia-cutlass-dsl")) - except (PackageNotFoundError, InvalidVersion): - logger.debug( - f"PrimTS FMHA is unavailable: nvidia-cutlass-dsl>={min_dsl_version} is required." - ) - return False - if installed_version < min_dsl_version: - logger.debug( - "PrimTS FMHA is unavailable: " - f"nvidia-cutlass-dsl>={min_dsl_version} is required, " - f"got {installed_version}." - ) - return False try: cutlass = import_module("cutlass") compiler_version_supported = cutlass.target_version( @@ -1485,10 +1466,8 @@ def run_generation(self, params: FmhaParams) -> None: (k_cache, v_cache), seq_lens, block_tables=fixed_block_tables, - bmm1_scale=self._get_bmm1_scale(attn), - bmm2_scale=1.0, - bmm1_scale_device=bmm1_scale.reshape(-1)[:1] if use_fp8 else None, - bmm2_scale_device=bmm2_scale.reshape(-1)[:1] if use_fp8 else None, + bmm1_scale=bmm1_scale.reshape(-1)[:1] if use_fp8 else self._get_bmm1_scale(attn), + bmm2_scale=bmm2_scale.reshape(-1)[:1] if use_fp8 else 1.0, out=output, validate=False, ) diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 5a0bb3cfa759..456be7677b56 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -1816,8 +1816,8 @@ def run() -> torch.Tensor: lengths, table, out=output, - bmm1_scale_device=bmm1, - bmm2_scale_device=bmm2, + bmm1_scale=bmm1, + bmm2_scale=bmm2, validate=False, ) @@ -1866,7 +1866,18 @@ def check_output() -> None: output.float(), bf16_host_output.float(), atol=0.0005, rtol=0.008 ) - run() + if mode == "gmem_reduction": + wrapper._plan_state.workspace.split_kv_counter.zero_() + wrapper.run( + q, + (k, v), + lengths, + table, + out=output, + bmm1_scale=bmm1, + bmm2_scale=bmm2, + validate=True, + ) torch.cuda.synchronize() check_output() @@ -1875,6 +1886,13 @@ def no_host_read(*args, **kwargs): with monkeypatch.context() as guard: guard.setattr(torch.Tensor, "item", no_host_read) + guard.setattr(torch.Tensor, "__float__", no_host_read) + sync_debug_mode = torch.cuda.get_sync_debug_mode() + try: + torch.cuda.set_sync_debug_mode("error") + run() + finally: + torch.cuda.set_sync_debug_mode(sync_debug_mode) graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): run() diff --git a/tests/unittest/_torch/attention/test_prims_ts_fmha.py b/tests/unittest/_torch/attention/test_prims_ts_fmha.py index c82fb31ab627..2bbee024fcf4 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_fmha.py +++ b/tests/unittest/_torch/attention/test_prims_ts_fmha.py @@ -722,25 +722,22 @@ def test_unsupported_matrix_falls_through(case: dict, expected_reason: str) -> N @pytest.mark.parametrize( - ("sm", "cutlass_version", "compiler_version", "is_mla", "expected"), + ("sm", "compiler_version", "is_mla", "expected"), [ - (100, "4.7.0", "13.3", False, True), - (103, "4.7.0", "13.3", False, True), - (100, "4.7.0", "13.4", False, True), - (100, "4.7.0", "13.2", False, False), - (107, "4.7.0", "13.3", False, False), - (107, "4.8.0", "13.3", False, True), - (107, "4.8.0", "13.2", False, False), - (107, "4.8.0", "13.3", True, False), - (100, "4.7.0", "13.3", True, True), - (120, "4.7.0", "13.3", False, False), - (100, "4.6.2", "13.3", False, False), + (100, "13.3", False, True), + (103, "13.3", False, True), + (100, "13.4", False, True), + (100, "13.2", False, False), + (107, "13.3", False, True), + (107, "13.2", False, False), + (107, "13.3", True, False), + (100, "13.3", True, True), + (120, "13.3", False, False), ], ) def test_static_availability_gate( monkeypatch: pytest.MonkeyPatch, sm: int, - cutlass_version: str, compiler_version: str, is_mla: bool, expected: bool, @@ -757,14 +754,11 @@ def import_cutlass_module(module_name: str) -> object: return object() monkeypatch.setattr(prims_ts_module, "get_sm_version", lambda: sm) - monkeypatch.setattr(prims_ts_module, "version", lambda _: cutlass_version) monkeypatch.setattr(prims_ts_module, "import_module", import_cutlass_module) monkeypatch.setattr(PrimsTSFmha, "_missing_fused_nanobind_ops", staticmethod(lambda: [])) assert PrimsTSFmha.is_available(_Attention(is_mla=is_mla)) is expected - if (sm in (100, 103) and Version(cutlass_version) >= Version("4.7.0")) or ( - sm == 107 and not is_mla and Version(cutlass_version) >= Version("4.8.0") - ): + if sm in (100, 103) or (sm == 107 and not is_mla): target_version.assert_called_once_with(min_version="13.3") else: target_version.assert_not_called() @@ -775,7 +769,6 @@ def test_static_availability_gate_fails_closed_when_compiler_query_fails( ) -> None: cutlass = SimpleNamespace(target_version=Mock(side_effect=RuntimeError("query failed"))) monkeypatch.setattr(prims_ts_module, "get_sm_version", lambda: 100) - monkeypatch.setattr(prims_ts_module, "version", lambda _: "4.7.0") monkeypatch.setattr( prims_ts_module, "import_module", @@ -796,7 +789,6 @@ def test_unsupported_cutlass_compiler_excludes_prims_ts_from_fmha_selection( cutlass = SimpleNamespace(target_version=target_version) monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts,fallback") monkeypatch.setattr(prims_ts_module, "get_sm_version", lambda: 100) - monkeypatch.setattr(prims_ts_module, "version", lambda _: "4.7.0") monkeypatch.setattr( prims_ts_module, "import_module", @@ -1312,8 +1304,11 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( assert run_args[0].dtype == kernel_dtype assert generation_preprocess.call_args.args[35] is fp8 if fp8: - assert run_kwargs["bmm1_scale_device"].data_ptr() == bmm1.data_ptr() - assert run_kwargs["bmm2_scale_device"].data_ptr() == bmm2.data_ptr() + assert run_kwargs["bmm1_scale"].data_ptr() == bmm1.data_ptr() + assert run_kwargs["bmm2_scale"].data_ptr() == bmm2.data_ptr() + else: + assert run_kwargs["bmm1_scale"] == pytest.approx(1.0 / math.sqrt(attn.head_dim)) + assert run_kwargs["bmm2_scale"] == 1.0 k_cache, v_cache = run_args[1] assert k_cache.shape == v_cache.shape == (6, attn.num_kv_heads, 32, attn.head_dim) assert v_cache.storage_offset() - k_cache.storage_offset() == 6 * math.prod(kv_pool.shape[1:]) @@ -1326,8 +1321,6 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( fixed_block_tables, torch.tensor([[0, 1, 2, 3], [2, 3, 4, 5]], dtype=torch.int32), ) - assert run_kwargs["softmax_scale"] == pytest.approx(1.0 / math.sqrt(attn.head_dim)) - assert run_kwargs["output_scale"] == 1.0 assert run_kwargs["out"].shape == (2, attn.num_heads, attn.head_dim) assert run_kwargs["out"].data_ptr() == output.data_ptr() assert run_kwargs["validate"] is False From 1fefcd72c62f18cb0b1d0112c99de9fa97a05749 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:08:39 +0000 Subject: [PATCH 06/13] [None][fix] Consolidate PrimsTS decode compile identity and reducer arguments Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../sparse/test_prims_ts_block_sparse.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py b/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py index 8c0613f98399..a77192316f14 100644 --- a/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py +++ b/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py @@ -40,6 +40,7 @@ from tensorrt_llm._torch.attention.kernels.sage_quant import SageQuantized from tensorrt_llm._torch.pyexecutor.resource_manager import KVCacheManager from tensorrt_llm.functional import PositionEmbeddingType +from tensorrt_llm.quantization.mode import QuantMode _REQUIRES_PRIMTS_GPU = pytest.mark.skipif( getSMVersion() not in (100, 103), @@ -295,6 +296,20 @@ def test_block_sparse_support_is_phase_specific_and_paged_proxy_is_rejected( assert reason == "paged block-sparse attention only supports BSR exact routes" +@pytest.mark.cpu_only +def test_paged_block_sparse_rejects_fp8_kv_cache() -> None: + attention, fmha, q, metadata, args = _paged_case() + attention.quant_mode = QuantMode.FP8_KV_CACHE + metadata.kv_cache_manager.dtype = torch.float8_e4m3fn + + supported, reason = fmha._is_supported_with_reason( + q, None, None, metadata, args, phase=FmhaPhase.GENERATION + ) + + assert not supported + assert "quantized KV cache" in reason + + @pytest.mark.cpu_only def test_contiguous_proxy_routes_reject_causal_mask_before_planning(monkeypatch) -> None: _attention, fmha, q, k, v, metadata, args = _contiguous_case() From c12407570fc980243239bca21c554daa30478ae0 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:44:57 +0000 Subject: [PATCH 07/13] [None][fix] Preserve MLA architecture routing after rebase Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- tensorrt_llm/_torch/attention/backends/fmha/cute_dsl_mla.py | 2 +- tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py | 5 +++-- tests/unittest/_torch/attention/test_cute_dsl_mla.py | 1 + 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/cute_dsl_mla.py b/tensorrt_llm/_torch/attention/backends/fmha/cute_dsl_mla.py index a3cd0364cbee..71974051eb24 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/cute_dsl_mla.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/cute_dsl_mla.py @@ -286,7 +286,7 @@ def _page_size_exclusive_to_cute_dsl(meta: "TrtllmAttentionMetadata") -> bool: if tokens_per_block in getattr(kv_cache_manager, "trtllm_gen_extra_tokens_per_block", ()): return False return not ( - get_sm_version() in PrimsTSFmha.SUPPORTED_SMS + get_sm_version() in PrimsTSFmha.SUPPORTED_MLA_SMS and tokens_per_block in PrimsTSFmha.SUPPORTED_PAGE_SIZES and getattr(kv_cache_manager, "dtype", None) in (DataType.FP8, DataType.BF16) ) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 02375d0b1dc3..13080046ef1c 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -165,6 +165,7 @@ class PrimsTSFmha(PhasedFmha): supports_vc_attention = True SUPPORTED_SMS = frozenset({100, 103, 107}) + SUPPORTED_MLA_SMS = frozenset({100, 103}) SUPPORTED_PAGE_SIZES = {16, 32, 64, 128} SUPPORTED_CONTEXT_HEAD_DIMS = {128, 256} SUPPORTED_DECODE_HEAD_DIMS = {64, 128, 256} @@ -204,8 +205,8 @@ def _is_available(cls, attn: "TrtllmAttention") -> bool: f"PrimTS FMHA is unavailable: requires SM100, SM103, or SM107, got SM{sm}." ) return False - if sm == 107 and attn.is_mla_enable: - logger.debug("PrimTS MLA FMHA is unavailable on SM107.") + if attn.is_mla_enable and sm not in cls.SUPPORTED_MLA_SMS: + logger.debug(f"PrimTS MLA FMHA is unavailable on SM{sm}.") return False try: cutlass = import_module("cutlass") diff --git a/tests/unittest/_torch/attention/test_cute_dsl_mla.py b/tests/unittest/_torch/attention/test_cute_dsl_mla.py index 63a9dc77ad06..14e7cb621a10 100644 --- a/tests/unittest/_torch/attention/test_cute_dsl_mla.py +++ b/tests/unittest/_torch/attention/test_cute_dsl_mla.py @@ -391,6 +391,7 @@ def test_mixed_batch_gate_admits_only_page_sizes_exclusive_to_cute_dsl( (100, 128, DataType.FP8, (), False), (103, 128, DataType.BF16, (), False), (107, 128, DataType.FP8, (), True), + (107, 128, DataType.BF16, (), True), # An NVFP4 manager's FP8 fallback layers on the FP4 MLA pages. (100, 128, DataType.NVFP4, (), True), (103, 128, DataType.NVFP4, (), True), From 622ccf42457fcb3d61f9b50bff55013010e8cc00 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Sat, 7 Nov 2026 07:46:47 +0000 Subject: [PATCH 08/13] [None][fix] Bind FP8 attention scales through the upstream PrimTS APIs Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/backends/fmha/prims_ts.py | 27 +++++++++++++------ .../test_prims_ts_attention_backend.py | 23 ++++++++-------- .../_torch/attention/test_prims_ts_fmha.py | 23 ++++++++-------- 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 13080046ef1c..2f419285ad0e 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -705,8 +705,9 @@ def _get_or_plan_context_wrapper( page_size: int, mask_type: str, window_left: int, - softmax_scale: float, + softmax_scale: float | torch.Tensor, output_dtype: torch.dtype, + output_scale: float | torch.Tensor = 1.0, ) -> "BatchPrefillPagedTSWrapper": wrapper = self._context_wrappers.get(batch_size) if wrapper is not None: @@ -734,7 +735,7 @@ def _get_or_plan_context_wrapper( mask_type=mask_type, window_left=window_left, softmax_scale=softmax_scale, - output_scale=1.0, + output_scale=output_scale, # Preprocessing establishes this invariant for every context # request admitted by this adapter. paged_v_tail_is_zero=True, @@ -758,6 +759,8 @@ def _get_or_plan_decode_wrapper( output_dtype: torch.dtype, mask_type: str, window_left: int, + softmax_scale: float | torch.Tensor | None = None, + output_scale: float | torch.Tensor = 1.0, ) -> "BatchDecodePagedTSWrapper": if batch_size <= 0: raise RuntimeError("PrimTS decode requires a positive batch size.") @@ -785,7 +788,8 @@ def _get_or_plan_decode_wrapper( mask_type=mask_type, window_left=window_left, workspace_buffer=workspace_buffer, - use_device_scales=QuantMode(self.attn.quant_mode).has_fp8_kv_cache(), + softmax_scale=softmax_scale, + output_scale=output_scale, ) self._decode_wrappers[batch_size] = wrapper return wrapper @@ -1250,6 +1254,8 @@ def run_context(self, params: FmhaParams) -> None: use_fp8 = QuantMode(attn.quant_mode).has_fp8_kv_cache() if use_fp8: q_processed = self._view_fp8_query(q_processed, params.num_tokens) + softmax_scale = bmm1_scale.reshape(-1)[:1] if use_fp8 else self._get_bmm1_scale(attn) + output_scale = bmm2_scale.reshape(-1)[:1] if use_fp8 else 1.0 mask_type = self._get_prims_mask_type(fwd) wrapper = self._get_or_plan_context_wrapper( q_processed, @@ -1261,7 +1267,8 @@ def run_context(self, params: FmhaParams) -> None: page_size=params.tokens_per_block, mask_type=mask_type, window_left=window_left, - softmax_scale=self._get_bmm1_scale(attn), + softmax_scale=softmax_scale, + output_scale=output_scale, output_dtype=params.output.dtype, ) wrapper.run( @@ -1271,8 +1278,8 @@ def run_context(self, params: FmhaParams) -> None: cu_q_seqlens, block_tables=fixed_block_tables, seq_lens_kv=seq_lens_kv, - scale_softmax_log2=bmm1_scale.reshape(-1)[1:2] if use_fp8 else None, - output_scale=bmm2_scale.reshape(-1)[:1] if use_fp8 else None, + softmax_scale=softmax_scale, + output_scale=output_scale, out=params.output, validate=False, ) @@ -1435,6 +1442,8 @@ def run_generation(self, params: FmhaParams) -> None: output = output[:, 0] mask_type = self._get_prims_mask_type(fwd) decode_workspace = self._get_decode_workspace(params.workspace) + softmax_scale = bmm1_scale.reshape(-1)[:1] if use_fp8 else self._get_bmm1_scale(attn) + output_scale = bmm2_scale.reshape(-1)[:1] if use_fp8 else 1.0 wrapper = self._get_or_plan_decode_wrapper( decode_workspace, batch_size=batch_size, @@ -1449,6 +1458,8 @@ def run_generation(self, params: FmhaParams) -> None: output_dtype=output.dtype, mask_type=mask_type, window_left=window_left, + softmax_scale=softmax_scale, + output_scale=output_scale, ) plan_state = wrapper._plan_state if plan_state is None: @@ -1467,8 +1478,8 @@ def run_generation(self, params: FmhaParams) -> None: (k_cache, v_cache), seq_lens, block_tables=fixed_block_tables, - bmm1_scale=bmm1_scale.reshape(-1)[:1] if use_fp8 else self._get_bmm1_scale(attn), - bmm2_scale=bmm2_scale.reshape(-1)[:1] if use_fp8 else 1.0, + softmax_scale=softmax_scale, + output_scale=output_scale, out=output, validate=False, ) diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 456be7677b56..0735b43ecb72 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -1796,10 +1796,11 @@ def plan(output_dtype: torch.dtype, use_device_scales: bool): head_dim, page_size, max_kv_len, - q_data_type=q.dtype, - o_data_type=output_dtype, + q_dtype=q.dtype, + out_dtype=output_dtype, mask_type="causal", - use_device_scales=use_device_scales, + softmax_scale=bmm1 if use_device_scales else bmm1.item(), + output_scale=bmm2 if use_device_scales else bmm2.item(), ) return wrapper @@ -1816,8 +1817,8 @@ def run() -> torch.Tensor: lengths, table, out=output, - bmm1_scale=bmm1, - bmm2_scale=bmm2, + softmax_scale=bmm1, + output_scale=bmm2, validate=False, ) @@ -1845,8 +1846,8 @@ def check_output() -> None: (k, v), lengths, table, - bmm1_scale=bmm1.item(), - bmm2_scale=bmm2.item(), + softmax_scale=bmm1.item(), + output_scale=bmm2.item(), validate=False, ) torch.testing.assert_close(output.float(), fp16_output.float(), atol=0.0005, rtol=0.008) @@ -1858,8 +1859,8 @@ def check_output() -> None: (k, v), lengths, table, - bmm1_scale=bmm1.item(), - bmm2_scale=bmm2.item(), + softmax_scale=bmm1.item(), + output_scale=bmm2.item(), validate=False, ) torch.testing.assert_close( @@ -1874,8 +1875,8 @@ def check_output() -> None: lengths, table, out=output, - bmm1_scale=bmm1, - bmm2_scale=bmm2, + softmax_scale=bmm1, + output_scale=bmm2, validate=True, ) torch.cuda.synchronize() diff --git a/tests/unittest/_torch/attention/test_prims_ts_fmha.py b/tests/unittest/_torch/attention/test_prims_ts_fmha.py index 2bbee024fcf4..aea3506e5a24 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_fmha.py +++ b/tests/unittest/_torch/attention/test_prims_ts_fmha.py @@ -1068,8 +1068,8 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( "page_size": 32, "mask_type": "causal", "window_left": -1, - "softmax_scale": pytest.approx(1.0 / math.sqrt(attn.head_dim)), - "output_scale": 1.0, + "softmax_scale": bmm1[:1] if fp8 else pytest.approx(1.0 / math.sqrt(attn.head_dim)), + "output_scale": bmm2[:1] if fp8 else 1.0, "paged_v_tail_is_zero": True, } wrapper.run.assert_called_once() @@ -1080,7 +1080,7 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( assert context_preprocess.call_args.args[35] is fp8 assert context_postprocess.call_args.args[32] is fp8 if fp8: - assert run_kwargs["scale_softmax_log2"].data_ptr() == bmm1[1:].data_ptr() + assert run_kwargs["softmax_scale"].data_ptr() == bmm1.data_ptr() assert run_kwargs["output_scale"].data_ptr() == bmm2.data_ptr() k_cache, v_cache = run_args[1], run_args[2] assert k_cache.shape == v_cache.shape == (6, attn.num_kv_heads, 32, attn.head_dim) @@ -1288,10 +1288,11 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( assert {key: value for key, value in plan_kwargs.items() if key != "workspace_buffer"} == { "max_q_len": 1, "packed_query": False, - "use_device_scales": fp8, - "q_data_type": kernel_dtype, - "kv_data_type": kernel_dtype, - "o_data_type": torch.bfloat16, + "softmax_scale": bmm1[:1] if fp8 else fmha._get_bmm1_scale(attn), + "output_scale": bmm2[:1] if fp8 else 1.0, + "q_dtype": kernel_dtype, + "kv_dtype": kernel_dtype, + "out_dtype": torch.bfloat16, "mask_type": "causal", "window_left": 15, } @@ -1304,11 +1305,11 @@ def test_generation_wrapper_plans_once_and_reads_live_fixed_metadata( assert run_args[0].dtype == kernel_dtype assert generation_preprocess.call_args.args[35] is fp8 if fp8: - assert run_kwargs["bmm1_scale"].data_ptr() == bmm1.data_ptr() - assert run_kwargs["bmm2_scale"].data_ptr() == bmm2.data_ptr() + assert run_kwargs["softmax_scale"].data_ptr() == bmm1.data_ptr() + assert run_kwargs["output_scale"].data_ptr() == bmm2.data_ptr() else: - assert run_kwargs["bmm1_scale"] == pytest.approx(1.0 / math.sqrt(attn.head_dim)) - assert run_kwargs["bmm2_scale"] == 1.0 + assert run_kwargs["softmax_scale"] == pytest.approx(1.0 / math.sqrt(attn.head_dim)) + assert run_kwargs["output_scale"] == 1.0 k_cache, v_cache = run_args[1] assert k_cache.shape == v_cache.shape == (6, attn.num_kv_heads, 32, attn.head_dim) assert v_cache.storage_offset() - k_cache.storage_offset() == 6 * math.prod(kv_pool.shape[1:]) From b146f59ae7fc82b8f57a4acc2390673dafa5182f Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Sun, 8 Nov 2026 06:59:54 +0000 Subject: [PATCH 09/13] [None][fix] Address PrimTS FP8 tail safety and review coverage Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/backends/fmha/prims_ts.py | 6 ++-- .../backends/fmha/prims_ts_block_sparse.py | 1 + .../accuracy/references/cnn_dailymail.yaml | 2 ++ .../defs/accuracy/test_llm_api_pytorch.py | 7 +++- .../test_lists/test-db/l0_b200.yml | 3 +- .../sparse/test_prims_ts_block_sparse.py | 22 +++++++++++++ .../test_prims_ts_attention_backend.py | 32 +++++++++++++++---- .../_torch/attention/test_prims_ts_fmha.py | 2 +- 8 files changed, 62 insertions(+), 13 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 2f419285ad0e..283aa6fee8dd 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -736,9 +736,9 @@ def _get_or_plan_context_wrapper( window_left=window_left, softmax_scale=softmax_scale, output_scale=output_scale, - # Preprocessing establishes this invariant for every context - # request admitted by this adapter. - paged_v_tail_is_zero=True, + # Preprocessing clears native V tails. Quantized caches rely on + # the consumer to clear invalid rows after loading each V tile. + paged_v_tail_is_zero=v_cache.dtype in self.SUPPORTED_DTYPES, ) self._context_wrappers[batch_size] = wrapper return wrapper diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py index b31b95cd22ef..435e56976d30 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py @@ -230,6 +230,7 @@ class PrimsTSBlockSparseFmha(PrimsTSFmha): here, on a dense plan. """ + SUPPORTED_SMS = frozenset({100, 103}) PLAN_CACHE_KEY = "prims_ts_block_sparse" supports_block_sparse_inputs = True diff --git a/tests/integration/defs/accuracy/references/cnn_dailymail.yaml b/tests/integration/defs/accuracy/references/cnn_dailymail.yaml index 0c70741c3bf3..31ecbcd637e9 100644 --- a/tests/integration/defs/accuracy/references/cnn_dailymail.yaml +++ b/tests/integration/defs/accuracy/references/cnn_dailymail.yaml @@ -94,6 +94,8 @@ deepseek-ai/DeepSeek-R1: spec_dec_algo: MTP accuracy: 28.706 Qwen3/Qwen3-8B: + - kv_cache_quant_algo: FP8 + accuracy: 30 - quant_algo: FP8_BLOCK_SCALES accuracy: 30 - accuracy: 30 diff --git a/tests/integration/defs/accuracy/test_llm_api_pytorch.py b/tests/integration/defs/accuracy/test_llm_api_pytorch.py index 27f6a135b772..93f8946cf461 100644 --- a/tests/integration/defs/accuracy/test_llm_api_pytorch.py +++ b/tests/integration/defs/accuracy/test_llm_api_pytorch.py @@ -3089,7 +3089,9 @@ def test_bf16(self, tp_size, pp_size, ep_size, attention_dp, cuda_graph, task.evaluate(llm) @skip_pre_blackwell - def test_prims_ts_bfloat16(self, mocker): + @pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"], + ids=["bf16-kv", "fp8-kv"]) + def test_prims_ts_bfloat16(self, mocker, kv_cache_dtype): if get_sm_version() not in (100, 103): pytest.skip("PrimTS requires SM100 or SM103") @@ -3099,6 +3101,7 @@ def test_prims_ts_bfloat16(self, mocker): "TLLM_WORKER_USE_SINGLE_PROCESS": "1", } kv_cache_config = KvCacheConfig( + dtype=kv_cache_dtype, free_gpu_memory_fraction=0.75, tokens_per_block=32, use_kv_cache_manager_v2=True, @@ -3109,6 +3112,8 @@ def test_prims_ts_bfloat16(self, mocker): kv_cache_config=kv_cache_config, disable_overlap_scheduler=True, cuda_graph_config=None) as llm: + if kv_cache_dtype == "fp8": + assert llm.args.quant_config.kv_cache_quant_algo == QuantAlgo.FP8 calls.update({name: 0 for name in calls}) task = CnnDailymail(self.MODEL_NAME) task.evaluate(llm) diff --git a/tests/integration/test_lists/test-db/l0_b200.yml b/tests/integration/test_lists/test-db/l0_b200.yml index d21856bf3e62..3f1b92749990 100644 --- a/tests/integration/test_lists/test-db/l0_b200.yml +++ b/tests/integration/test_lists/test-db/l0_b200.yml @@ -88,7 +88,8 @@ l0_b200: - accuracy/test_llm_api_pytorch.py::TestGPTOSS::test_w4_1gpu_suspend_resume - accuracy/test_llm_api_pytorch.py::TestGPTOSS::test_dummy_load_format - accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_fp8_block_scales[latency] # Cover nvbugs 5461712 and 5505402 - - accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_prims_ts_bfloat16 + - accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_prims_ts_bfloat16[bf16-kv] + - accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_prims_ts_bfloat16[fp8-kv] - accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_dspark[TRTLLM] # SM100+ only; l0_h100 runs [VANILLA] - accuracy/test_llm_api_pytorch.py::TestQwen3_30B_A3B::test_nvfp4[latency_moe_trtllm-torch_compile=True] - accuracy/test_llm_api_pytorch.py::TestQwen3_30B_A3B::test_w4a8_mxfp4[fp8-latency-TRTLLM] diff --git a/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py b/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py index a77192316f14..c7e8b59ce148 100644 --- a/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py +++ b/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py @@ -240,6 +240,28 @@ def _paged_case(): return attention, fmha, q, metadata, args +@pytest.mark.cpu_only +@pytest.mark.parametrize("sm, expected", [(100, True), (103, True), (107, False)]) +def test_default_block_sparse_selection_keeps_blackwell_scope(monkeypatch, sm, expected) -> None: + from tensorrt_llm._torch.attention.backends.fmha import prims_ts as prims_ts_fmha + from tensorrt_llm._torch.attention.backends.fmha.registry import get_enabled_fmha_lib_classes + + monkeypatch.delenv("TLLM_FMHA_LIBS", raising=False) + monkeypatch.setattr(prims_ts_fmha, "get_sm_version", lambda: sm) + monkeypatch.setattr( + prims_ts_fmha, "import_module", lambda _: SimpleNamespace(target_version=lambda **_: True) + ) + monkeypatch.setattr( + prims_ts_fmha.PrimsTSFmha, "_missing_fused_nanobind_ops", staticmethod(lambda: []) + ) + cls = block_sparse_fmha.PrimsTSBlockSparseFmha + + attention = SimpleNamespace(skip_correction_threshold=0.0, is_mla_enable=False) + assert cls in get_enabled_fmha_lib_classes() + assert cls.is_available(attention) is expected + assert prims_ts_fmha.PrimsTSFmha.is_available(attention) + + @pytest.mark.cpu_only def test_block_sparse_route_mode_is_derived_from_payload() -> None: bsr = _bsr_inputs() diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 0735b43ecb72..7f1a232137a2 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -135,9 +135,13 @@ def test_prims_ts_qwen2_gqa( @pytest.mark.parametrize("use_kv_cache_manager_v2", [False, True], ids=["v1", "v2"]) +@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) +@pytest.mark.parametrize("num_cached_tokens", [[0, 0], [32, 64]], ids=["context", "cached-context"]) def test_prims_ts_context_receives_zeroed_v_tail( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, + kv_dtype: str | None, + num_cached_tokens: list[int], ) -> None: import backend_case @@ -145,7 +149,13 @@ def test_prims_ts_context_receives_zeroed_v_tail( original_build_kv_cache_manager = backend_case._build_kv_cache_manager original_run = BatchPrefillPagedTSWrapper.run - zeroed_tails: list[tuple[int, int]] = [] + checked_tails: list[tuple[int, int]] = [] + plan_flags: list[bool] = [] + original_plan = BatchPrefillPagedTSWrapper.plan + + def record_plan(self: BatchPrefillPagedTSWrapper, *args, **kwargs) -> None: + plan_flags.append(kwargs["paged_v_tail_is_zero"]) + original_plan(self, *args, **kwargs) def build_kv_cache_manager_with_nan_v( case: BackendCase, @@ -167,8 +177,8 @@ def run_with_zeroed_v_tail_check( seq_lens_kv: torch.Tensor, **kwargs: object, ) -> torch.Tensor: - # The TRT-LLM producer promises zeroed V tails to PrimTS. Check the - # invariant at the handoff, before the PrimTS consumer launches. + # Native tails are zeroed by preprocessing. Poison FP8 tails at the + # handoff so fresh zero-filled cache allocations cannot mask the bug. page_size = v_cache.shape[2] seq_lens = seq_lens_kv.cpu().tolist() page_indices = block_tables.cpu() @@ -179,8 +189,12 @@ def run_with_zeroed_v_tail_check( continue physical_page = int(page_indices[batch_idx, logical_last_page].item()) tail = v_cache[physical_page, :, tail_start:, :] - assert torch.count_nonzero(tail).item() == 0 - zeroed_tails.append((batch_idx, tail_start)) + if kv_dtype == "fp8": + tail.fill_(float("nan")) + assert torch.isnan(tail.float()).all() + else: + assert torch.count_nonzero(tail).item() == 0 + checked_tails.append((batch_idx, tail_start)) return original_run( self, @@ -204,11 +218,13 @@ def run_with_zeroed_v_tail_check( "run", run_with_zeroed_v_tail_check, ) + monkeypatch.setattr(BatchPrefillPagedTSWrapper, "plan", record_plan) monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") case = BackendCase( **_QWEN2_7B, seq_lens=[65, 37], - num_cached_tokens=[0, 0], + num_cached_tokens=num_cached_tokens, + kv_dtype=kv_dtype, num_contexts=2, use_kv_cache_manager_v2=use_kv_cache_manager_v2, ) @@ -216,7 +232,9 @@ def run_with_zeroed_v_tail_check( results = run_case(case) assert "TRTLLM" in results - assert zeroed_tails == [(0, 1), (1, 5)] + assert torch.isfinite(results["TRTLLM"]).all() + assert checked_tails == [(0, 1), (1, 5)] + assert plan_flags == [kv_dtype != "fp8"] @pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["fp16-kv", "fp8-kv"]) diff --git a/tests/unittest/_torch/attention/test_prims_ts_fmha.py b/tests/unittest/_torch/attention/test_prims_ts_fmha.py index aea3506e5a24..e8612a8c60dd 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_fmha.py +++ b/tests/unittest/_torch/attention/test_prims_ts_fmha.py @@ -1070,7 +1070,7 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( "window_left": -1, "softmax_scale": bmm1[:1] if fp8 else pytest.approx(1.0 / math.sqrt(attn.head_dim)), "output_scale": bmm2[:1] if fp8 else 1.0, - "paged_v_tail_is_zero": True, + "paged_v_tail_is_zero": not fp8, } wrapper.run.assert_called_once() run_args = wrapper.run.call_args.args From 724734c43547851a114aefe680948da7d86547e5 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:40:33 +0000 Subject: [PATCH 10/13] [None][fix] Repair PrimTS accuracy selectors and model-test imports Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- tests/integration/defs/accuracy/test_llm_api_pytorch.py | 4 ++-- tests/integration/test_lists/qa/llm_function_core.txt | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/integration/defs/accuracy/test_llm_api_pytorch.py b/tests/integration/defs/accuracy/test_llm_api_pytorch.py index 93f8946cf461..240aecd0bbae 100644 --- a/tests/integration/defs/accuracy/test_llm_api_pytorch.py +++ b/tests/integration/defs/accuracy/test_llm_api_pytorch.py @@ -3092,8 +3092,8 @@ def test_bf16(self, tp_size, pp_size, ep_size, attention_dp, cuda_graph, @pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"], ids=["bf16-kv", "fp8-kv"]) def test_prims_ts_bfloat16(self, mocker, kv_cache_dtype): - if get_sm_version() not in (100, 103): - pytest.skip("PrimTS requires SM100 or SM103") + if get_sm_version() not in (100, 103, 107): + pytest.skip("PrimTS requires SM100, SM103, or SM107") calls = _count_prims_ts_phase_calls(mocker) env = { diff --git a/tests/integration/test_lists/qa/llm_function_core.txt b/tests/integration/test_lists/qa/llm_function_core.txt index 94cac6743efd..0908cabb6060 100644 --- a/tests/integration/test_lists/qa/llm_function_core.txt +++ b/tests/integration/test_lists/qa/llm_function_core.txt @@ -612,7 +612,8 @@ accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_eagle3[eagle3_one_model=Tru accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_eagle3[eagle3_one_model=True-enable_chunked_prefill=True-enable_max_concurrency=False-enable_draft_len_schedule=False] accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_fp8_block_scales[latency] accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_fp8_block_scales_early_first_token_response -accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_prims_ts_bfloat16 +accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_prims_ts_bfloat16[bf16-kv] +accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_prims_ts_bfloat16[fp8-kv] accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_w4a8_mxfp4[fp8-latency] accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_w4a8_mxfp4[mxfp8-latency] accuracy/test_llm_api_pytorch.py::TestQwen3_8_27B::test_dflash2[VANILLA] From a9bdfe43035cba2e46d25d8069685fdac4dfb88b Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:41:33 +0000 Subject: [PATCH 11/13] [None][fix] Share PrimTS architecture support after Rubin qualification Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../attention/backends/fmha/prims_ts_block_sparse.py | 1 - .../attention/sparse/test_prims_ts_block_sparse.py | 10 +++++----- .../sparse_attention/vsa/test_vsa_parity.py | 12 ++++++------ 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py index 435e56976d30..b31b95cd22ef 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py @@ -230,7 +230,6 @@ class PrimsTSBlockSparseFmha(PrimsTSFmha): here, on a dense plan. """ - SUPPORTED_SMS = frozenset({100, 103}) PLAN_CACHE_KEY = "prims_ts_block_sparse" supports_block_sparse_inputs = True diff --git a/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py b/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py index c7e8b59ce148..768e5ec21aa3 100644 --- a/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py +++ b/tests/unittest/_torch/attention/sparse/test_prims_ts_block_sparse.py @@ -43,8 +43,8 @@ from tensorrt_llm.quantization.mode import QuantMode _REQUIRES_PRIMTS_GPU = pytest.mark.skipif( - getSMVersion() not in (100, 103), - reason="PrimTS block-sparse attention requires SM100 or SM103", + getSMVersion() not in (100, 103, 107), + reason="PrimTS block-sparse attention requires SM100, SM103, or SM107", ) @@ -241,8 +241,8 @@ def _paged_case(): @pytest.mark.cpu_only -@pytest.mark.parametrize("sm, expected", [(100, True), (103, True), (107, False)]) -def test_default_block_sparse_selection_keeps_blackwell_scope(monkeypatch, sm, expected) -> None: +@pytest.mark.parametrize("sm", [100, 103, 107]) +def test_default_block_sparse_selection_shares_dense_architectures(monkeypatch, sm) -> None: from tensorrt_llm._torch.attention.backends.fmha import prims_ts as prims_ts_fmha from tensorrt_llm._torch.attention.backends.fmha.registry import get_enabled_fmha_lib_classes @@ -258,7 +258,7 @@ def test_default_block_sparse_selection_keeps_blackwell_scope(monkeypatch, sm, e attention = SimpleNamespace(skip_correction_threshold=0.0, is_mla_enable=False) assert cls in get_enabled_fmha_lib_classes() - assert cls.is_available(attention) is expected + assert cls.is_available(attention) assert prims_ts_fmha.PrimsTSFmha.is_available(attention) diff --git a/tests/unittest/_torch/visual_gen/sparse_attention/vsa/test_vsa_parity.py b/tests/unittest/_torch/visual_gen/sparse_attention/vsa/test_vsa_parity.py index 90e2af853903..53b774ef21ca 100644 --- a/tests/unittest/_torch/visual_gen/sparse_attention/vsa/test_vsa_parity.py +++ b/tests/unittest/_torch/visual_gen/sparse_attention/vsa/test_vsa_parity.py @@ -24,7 +24,7 @@ import pytest import torch import torch.nn.functional as F -from utils.util import isSM100Family +from utils.util import getSMVersion from tensorrt_llm._torch.attention.backends.fmha.prims_ts_block_sparse import PrimsTSBlockSparseFmha from tensorrt_llm._torch.visual_gen.attention.attention import Attention, QKVMode, apply_rotary_emb @@ -40,9 +40,9 @@ from tensorrt_llm.visual_gen.args import AttentionConfig, VideoSparseAttentionConfig _REQUIRES_CUDA = pytest.mark.skipif(not torch.cuda.is_available(), reason="VSA needs CUDA") -_REQUIRES_SM100 = pytest.mark.skipif( - not isSM100Family(), - reason="CuTe DSL and PrimTS block-sparse parity requires SM100 or SM103", +_REQUIRES_PRIMTS_GPU = pytest.mark.skipif( + getSMVersion() not in (100, 103, 107), + reason="CuTe DSL and PrimTS block-sparse parity requires SM100, SM103, or SM107", ) _BACKENDS = pytest.mark.parametrize("backend", ["CUTEDSL", "TRTLLM"]) @@ -158,7 +158,7 @@ def test_vsa_backends_match_dense_at_sparsity_zero(backend: str) -> None: torch.testing.assert_close(out_vsa, out_dense, rtol=1e-2, atol=1e-2) -@_REQUIRES_SM100 +@_REQUIRES_PRIMTS_GPU def test_vsa_backends_match_each_other_on_ragged_input(monkeypatch: pytest.MonkeyPatch) -> None: """CuTeDSL and TRTLLM implement the same sparse VSA fine-stage semantics. @@ -210,7 +210,7 @@ def counted_primts(*args, **kwargs): torch.testing.assert_close(outputs["CUTEDSL"], outputs["TRTLLM"], rtol=1e-2, atol=1e-2) -@_REQUIRES_SM100 +@_REQUIRES_PRIMTS_GPU def test_vsa_trtllm_cuda_graph_replays_live_routes() -> None: """Captured VSA recomputes routes when graph-stable input storage changes.""" From 17b8fe0c94ff15af24473bbe00ecc1b1f8d7f922 Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:43:12 +0000 Subject: [PATCH 12/13] [None][fix] Zero FP8 KV tails in fused preprocessing Use cache-width packed stores for FP8 V tails in both preprocessing variants and restore the producer-zeroed-tail contract. Disable absent vision regions with the proper sentinel so computed RoPE preserves text positions in context and decode. Cover native and FP8 cache contents and attention output without changing existing accuracy tolerances. Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../unfusedAttentionKernels_2_template.h | 21 +++- .../thop/trtllmGenQKVProcessOp.cpp | 12 +- .../attention/backends/fmha/prims_ts.py | 6 +- .../test_prims_ts_attention_backend.py | 103 ++++++++++++++++-- .../_torch/attention/test_prims_ts_fmha.py | 2 +- 5 files changed, 120 insertions(+), 24 deletions(-) diff --git a/cpp/tensorrt_llm/kernels/unfusedAttentionKernels/unfusedAttentionKernels_2_template.h b/cpp/tensorrt_llm/kernels/unfusedAttentionKernels/unfusedAttentionKernels_2_template.h index fdbc23fd91b0..95482dc65e1d 100644 --- a/cpp/tensorrt_llm/kernels/unfusedAttentionKernels/unfusedAttentionKernels_2_template.h +++ b/cpp/tensorrt_llm/kernels/unfusedAttentionKernels/unfusedAttentionKernels_2_template.h @@ -195,7 +195,12 @@ inline __device__ void zeroPagedVCacheTail(QKVPreprocessingParams && std::is_same_v) +#ifdef ENABLE_FP8 + constexpr bool kFp8Cache = std::is_same_v; +#else + constexpr bool kFp8Cache = false; +#endif + if constexpr (!GEN_PHASE && std::is_same_v && (std::is_same_v || kFp8Cache)) { if (params.generation_phase || !isUniqueTokenWriter || cacheSeqLen <= 0 || tokenIdxInKvCache != cacheSeqLen - 1) { @@ -210,12 +215,20 @@ inline __device__ void zeroPagedVCacheTail(QKVPreprocessingParams(params.kv_cache_buffer.getVBlockPtr(batchIdx, cacheSeqLen - 1)); - auto* vBlockVec = reinterpret_cast(vBlock); - TVec const zero{}; for (int tokenInBlock = validTokensInLastBlock; tokenInBlock < tokensPerBlock; ++tokenInBlock) { int const vIdx = kvHeadIdx * tokensPerBlock * vecsPerHead + tokenInBlock * vecsPerHead + channelIdx; - vBlockVec[vIdx] = zero; + if constexpr (std::is_same_v) + { + reinterpret_cast(vBlock)[vIdx] = TVec{}; + } + else + { + // Match the packed FP8 stores used for the valid V tokens. + using CacheVec = typename mmha::packed_type::value>::type; + static_assert(sizeof(CacheVec) == sizeof(TVec) / sizeof(T)); + reinterpret_cast(vBlock)[vIdx] = CacheVec{}; + } } } } diff --git a/cpp/tensorrt_llm/thop/trtllmGenQKVProcessOp.cpp b/cpp/tensorrt_llm/thop/trtllmGenQKVProcessOp.cpp index f1cf2d2b9e60..3bc2a0dea6a4 100644 --- a/cpp/tensorrt_llm/thop/trtllmGenQKVProcessOp.cpp +++ b/cpp/tensorrt_llm/thop/trtllmGenQKVProcessOp.cpp @@ -407,8 +407,8 @@ trtllmGenContextPreprocess(torch::Tensor qkv_input, torch::Tensor workspace, tor qkvParams.generation_phase = false; qkvParams.q_only_input = qOnlyInput; qkvParams.multi_processor_count = static_cast(multi_processor_count); - qkvParams.rotary_vision_start = 0; - qkvParams.rotary_vision_length = 0; + qkvParams.rotary_vision_start = -1; + qkvParams.rotary_vision_length = -1; switch (qkvDtype) { @@ -559,8 +559,8 @@ void trtllmGenContextPostprocess(torch::Tensor qkv_input, torch::Tensor workspac qkvParams.quantized_fp8_output = fp8_context_fmha; qkvParams.generation_phase = false; qkvParams.multi_processor_count = static_cast(multi_processor_count); - qkvParams.rotary_vision_start = 0; - qkvParams.rotary_vision_length = 0; + qkvParams.rotary_vision_start = -1; + qkvParams.rotary_vision_length = -1; switch (qkvDtype) { @@ -745,8 +745,8 @@ trtllmGenGenerationPreprocess(torch::Tensor qkv_input, torch::Tensor workspace, qkvParams.generation_phase = true; qkvParams.q_only_input = qOnlyInput; qkvParams.multi_processor_count = static_cast(multi_processor_count); - qkvParams.rotary_vision_start = 0; - qkvParams.rotary_vision_length = 0; + qkvParams.rotary_vision_start = -1; + qkvParams.rotary_vision_length = -1; switch (qkvDtype) { diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 283aa6fee8dd..a8ed5fca7bbe 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -736,9 +736,9 @@ def _get_or_plan_context_wrapper( window_left=window_left, softmax_scale=softmax_scale, output_scale=output_scale, - # Preprocessing clears native V tails. Quantized caches rely on - # the consumer to clear invalid rows after loading each V tile. - paged_v_tail_is_zero=v_cache.dtype in self.SUPPORTED_DTYPES, + # Context preprocessing clears unused native and FP8 V rows in + # the final physical page before attention consumes the cache. + paged_v_tail_is_zero=True, ) self._context_wrappers[batch_size] = wrapper return wrapper diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 7f1a232137a2..671f571e4cf2 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -137,17 +137,60 @@ def test_prims_ts_qwen2_gqa( @pytest.mark.parametrize("use_kv_cache_manager_v2", [False, True], ids=["v1", "v2"]) @pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) @pytest.mark.parametrize("num_cached_tokens", [[0, 0], [32, 64]], ids=["context", "cached-context"]) +@pytest.mark.parametrize("dtype", ["bfloat16", "float16"], ids=["bf16", "fp16"]) +@pytest.mark.parametrize("preprocessing", ["cached-rope", "computed-rope"]) +@pytest.mark.parametrize("head_dim", [128, 256]) def test_prims_ts_context_receives_zeroed_v_tail( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, kv_dtype: str | None, num_cached_tokens: list[int], + dtype: str, + preprocessing: str, + head_dim: int, ) -> None: import backend_case + from tensorrt_llm._torch.attention.backends.fmha.prims_ts import PrimsTSFmha from tensorrt_llm._torch.attention.backends.prims_ts.context import BatchPrefillPagedTSWrapper + original_run_context = PrimsTSFmha.run_context + + def run_context_with_selected_preprocessing(self, params): + # An absent cosine/sine table selects the preprocessing kernel that + # computes RoPE coefficients, with the same RoPE semantics. + with monkeypatch.context() as context_patch: + if preprocessing == "computed-rope": + context_patch.setattr(self.attn, "rotary_cos_sin", None) + return original_run_context(self, params) + original_build_kv_cache_manager = backend_case._build_kv_cache_manager + original_fill_kv_cache = backend_case.fill_kv_cache_logical + original_generate_inputs = backend_case.generate_inputs + trt_managers: set[int] = set() + inputs_for_check: dict = {} + + def generate_inputs(*args, **kwargs): + inputs = original_generate_inputs(*args, **kwargs) + # Bound RoPE operands so FP8 rounding at a bin boundary stays within + # the cache oracle's tolerance. Valid V values remain unmodified. + for tensor in (inputs["q"], inputs["new_k"], *inputs["cached_k"]): + tensor.clamp_(-1, 1) + inputs_for_check.update(inputs) + return inputs + + def fill_cache_and_poison_tail(manager, layer_idx, request_ids, *args, **kwargs): + original_fill_kv_cache(manager, layer_idx, request_ids, *args, **kwargs) + if id(manager) not in trt_managers: + return + pool = manager.get_buffers(layer_idx, kv_layout="HND") + page_size = pool.shape[3] + block_indices = manager.get_batch_cache_indices(list(request_ids), layer_idx) + for batch_idx, seq_len in enumerate(case.token_nums): + tail_start = (seq_len - 1) % page_size + 1 + physical_page = int(block_indices[batch_idx][(seq_len - 1) // page_size]) + pool[physical_page, 1, :, tail_start:, :].fill_(float("nan")) + original_run = BatchPrefillPagedTSWrapper.run checked_tails: list[tuple[int, int]] = [] plan_flags: list[bool] = [] @@ -164,7 +207,7 @@ def build_kv_cache_manager_with_nan_v( ) -> object: manager = original_build_kv_cache_manager(case, backend, kv_dtype) if backend == "TRTLLM": - manager.get_buffers(0, kv_layout="HND")[:, 1].fill_(float("nan")) + trt_managers.add(id(manager)) return manager def run_with_zeroed_v_tail_check( @@ -177,8 +220,8 @@ def run_with_zeroed_v_tail_check( seq_lens_kv: torch.Tensor, **kwargs: object, ) -> torch.Tensor: - # Native tails are zeroed by preprocessing. Poison FP8 tails at the - # handoff so fresh zero-filled cache allocations cannot mask the bug. + # Check the producer's zero-tail contract before the consumer runs, + # including preservation of every valid V element in the last page. page_size = v_cache.shape[2] seq_lens = seq_lens_kv.cpu().tolist() page_indices = block_tables.cpu() @@ -189,11 +232,18 @@ def run_with_zeroed_v_tail_check( continue physical_page = int(page_indices[batch_idx, logical_last_page].item()) tail = v_cache[physical_page, :, tail_start:, :] - if kv_dtype == "fp8": - tail.fill_(float("nan")) - assert torch.isnan(tail.float()).all() - else: - assert torch.count_nonzero(tail).item() == 0 + assert torch.count_nonzero(tail.float()).item() == 0 + new_v_start = sum(case.seq_lens[:batch_idx]) + new_v = inputs_for_check["new_v"][new_v_start : new_v_start + case.seq_lens[batch_idx]] + logical_v = torch.cat( + ( + inputs_for_check["cached_v"][batch_idx], + new_v.view(-1, case.num_kv_heads, case.head_dim), + ) + ) + expected = logical_v[logical_last_page * page_size :].to(v_cache.dtype) + actual = v_cache[physical_page, :, :tail_start, :].transpose(0, 1) + torch.testing.assert_close(actual.float(), expected.float(), rtol=0, atol=0) checked_tails.append((batch_idx, tail_start)) return original_run( @@ -208,6 +258,9 @@ def run_with_zeroed_v_tail_check( ) monkeypatch.setattr(backend_case, "BACKENDS_UNDER_TEST", ("TRTLLM",)) + monkeypatch.setattr(PrimsTSFmha, "run_context", run_context_with_selected_preprocessing) + monkeypatch.setattr(backend_case, "generate_inputs", generate_inputs) + monkeypatch.setattr(backend_case, "fill_kv_cache_logical", fill_cache_and_poison_tail) monkeypatch.setattr( backend_case, "_build_kv_cache_manager", @@ -220,8 +273,10 @@ def run_with_zeroed_v_tail_check( ) monkeypatch.setattr(BatchPrefillPagedTSWrapper, "plan", record_plan) monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") + rope = dict(_QWEN2_7B["rope"]) + rope["dim"] = head_dim case = BackendCase( - **_QWEN2_7B, + **{**_QWEN2_7B, "head_dim": head_dim, "dtype": dtype, "rope": rope}, seq_lens=[65, 37], num_cached_tokens=num_cached_tokens, kv_dtype=kv_dtype, @@ -234,7 +289,35 @@ def run_with_zeroed_v_tail_check( assert "TRTLLM" in results assert torch.isfinite(results["TRTLLM"]).all() assert checked_tails == [(0, 1), (1, 5)] - assert plan_flags == [kv_dtype != "fp8"] + assert plan_flags == [True] + + +@pytest.mark.parametrize("dtype", ["bfloat16", "float16"], ids=["bf16", "fp16"]) +@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) +def test_prims_ts_decode_with_computed_rope( + monkeypatch: pytest.MonkeyPatch, dtype: str, kv_dtype: str | None +) -> None: + from tensorrt_llm._torch.attention.backends.fmha.prims_ts import PrimsTSFmha + + original_run_generation = PrimsTSFmha.run_generation + + def run_generation_without_rope_table(self, params): + with monkeypatch.context() as context_patch: + context_patch.setattr(self.attn, "rotary_cos_sin", None) + return original_run_generation(self, params) + + monkeypatch.setattr(PrimsTSFmha, "run_generation", run_generation_without_rope_table) + monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") + run_case( + BackendCase( + **{**_QWEN2_7B, "dtype": dtype}, + seq_lens=[1, 1], + num_cached_tokens=[65, 37], + num_contexts=0, + kv_dtype=kv_dtype, + use_kv_cache_manager_v2=True, + ) + ) @pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["fp16-kv", "fp8-kv"]) diff --git a/tests/unittest/_torch/attention/test_prims_ts_fmha.py b/tests/unittest/_torch/attention/test_prims_ts_fmha.py index e8612a8c60dd..aea3506e5a24 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_fmha.py +++ b/tests/unittest/_torch/attention/test_prims_ts_fmha.py @@ -1070,7 +1070,7 @@ def test_context_wrapper_plans_once_and_reads_live_fixed_metadata( "window_left": -1, "softmax_scale": bmm1[:1] if fp8 else pytest.approx(1.0 / math.sqrt(attn.head_dim)), "output_scale": bmm2[:1] if fp8 else 1.0, - "paged_v_tail_is_zero": not fp8, + "paged_v_tail_is_zero": True, } wrapper.run.assert_called_once() run_args = wrapper.run.call_args.args From fc41ebd0160965704028db985965110228e9a43b Mon Sep 17 00:00:00 2001 From: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Date: Tue, 10 Nov 2026 02:42:18 +0000 Subject: [PATCH 13/13] [None][test] Reduce PrimTS FP8 GPU regression matrix Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> --- .../test_prims_ts_attention_backend.py | 284 ++++++++++-------- 1 file changed, 154 insertions(+), 130 deletions(-) diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index 671f571e4cf2..a8c42634357e 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -19,6 +19,7 @@ from types import SimpleNamespace from unittest.mock import Mock +import backend_case import pytest import torch from backend_case import ( @@ -76,57 +77,49 @@ } -@pytest.mark.parametrize("use_kv_cache_manager_v2", [False, True], ids=["v1", "v2"]) @pytest.mark.parametrize( - "phase_args", + ( + "seq_lens", + "num_cached_tokens", + "num_contexts", + "dtype", + "kv_dtype", + "use_kv_cache_manager_v2", + ), [ + pytest.param([65, 37], [0, 0], 2, "bfloat16", None, False, id="native-context-v1"), + pytest.param([65, 37], [0, 0], 2, "bfloat16", None, True, id="native-context-v2"), + pytest.param([1, 1], [64, 96], 0, "bfloat16", None, False, id="native-generation-v1"), + pytest.param([1, 1], [64, 96], 0, "bfloat16", None, True, id="native-generation-v2"), + pytest.param([41, 1], [0, 63], 1, "bfloat16", None, False, id="native-mixed-v1"), + pytest.param([41, 1], [0, 63], 1, "bfloat16", None, True, id="native-mixed-v2"), + pytest.param([65, 37], [0, 0], 2, "bfloat16", "fp8", False, id="fp8-context-bf16-v1"), + pytest.param([65, 37], [0, 0], 2, "float16", "fp8", True, id="fp8-context-fp16-v2"), + pytest.param([1, 1], [64, 96], 0, "float16", "fp8", False, id="fp8-generation-fp16-v1"), pytest.param( - { - "seq_lens": [65, 37], - "num_cached_tokens": [0, 0], - "num_contexts": 2, - }, - id="context", - ), - pytest.param( - { - "seq_lens": [1, 1], - "num_cached_tokens": [64, 96], - "num_contexts": 0, - }, - id="generation", - ), - pytest.param( - { - "seq_lens": [41, 1], - "num_cached_tokens": [0, 63], - "num_contexts": 1, - }, - id="mixed", - ), - pytest.param( - {"seq_lens": [41, 17], "num_cached_tokens": [63, 32], "num_contexts": 2}, - id="cached-context", - ), - pytest.param( - {"seq_lens": [1, 1], "num_cached_tokens": [8191, 4096], "num_contexts": 0}, - id="long-generation", + [1, 1], [8191, 4096], 0, "bfloat16", "fp8", True, id="fp8-long-generation-bf16-v2" ), + pytest.param([41, 1], [0, 63], 1, "bfloat16", "fp8", False, id="fp8-mixed-bf16-v1"), + pytest.param([41, 1], [0, 63], 1, "float16", "fp8", True, id="fp8-mixed-fp16-v2"), ], ) -@pytest.mark.parametrize("dtype", ["bfloat16", "float16"], ids=["bf16", "fp16"]) -@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) def test_prims_ts_qwen2_gqa( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, - phase_args: dict, + seq_lens: list[int], + num_cached_tokens: list[int], + num_contexts: int, kv_dtype: str | None, dtype: str, ) -> None: monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") + if kv_dtype == "fp8": + monkeypatch.setattr(backend_case, "BACKENDS_UNDER_TEST", ("TRTLLM",)) case = BackendCase( **{**_QWEN2_7B, "dtype": dtype}, - **phase_args, + seq_lens=seq_lens, + num_cached_tokens=num_cached_tokens, + num_contexts=num_contexts, kv_dtype=kv_dtype, use_kv_cache_manager_v2=use_kv_cache_manager_v2, ) @@ -134,12 +127,92 @@ def test_prims_ts_qwen2_gqa( run_case(case) -@pytest.mark.parametrize("use_kv_cache_manager_v2", [False, True], ids=["v1", "v2"]) -@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) -@pytest.mark.parametrize("num_cached_tokens", [[0, 0], [32, 64]], ids=["context", "cached-context"]) -@pytest.mark.parametrize("dtype", ["bfloat16", "float16"], ids=["bf16", "fp16"]) -@pytest.mark.parametrize("preprocessing", ["cached-rope", "computed-rope"]) -@pytest.mark.parametrize("head_dim", [128, 256]) +@pytest.mark.parametrize( + ( + "dtype", + "preprocessing", + "head_dim", + "use_kv_cache_manager_v2", + "num_cached_tokens", + "kv_dtype", + ), + [ + pytest.param("bfloat16", "cached-rope", 128, False, [0, 0], None, id="native-v1"), + pytest.param("bfloat16", "cached-rope", 128, True, [0, 0], None, id="native-v2"), + pytest.param( + "bfloat16", + "cached-rope", + 128, + False, + [0, 0], + "fp8", + id="fp8-bf16-cached-rope-d128-v1-context", + ), + pytest.param( + "bfloat16", + "cached-rope", + 256, + True, + [32, 64], + "fp8", + id="fp8-bf16-cached-rope-d256-v2-prefix", + ), + pytest.param( + "bfloat16", + "computed-rope", + 128, + True, + [0, 0], + "fp8", + id="fp8-bf16-computed-rope-d128-v2-context", + ), + pytest.param( + "bfloat16", + "computed-rope", + 256, + False, + [32, 64], + "fp8", + id="fp8-bf16-computed-rope-d256-v1-prefix", + ), + pytest.param( + "float16", + "cached-rope", + 128, + True, + [32, 64], + "fp8", + id="fp8-fp16-cached-rope-d128-v2-prefix", + ), + pytest.param( + "float16", + "cached-rope", + 256, + False, + [0, 0], + "fp8", + id="fp8-fp16-cached-rope-d256-v1-context", + ), + pytest.param( + "float16", + "computed-rope", + 128, + False, + [32, 64], + "fp8", + id="fp8-fp16-computed-rope-d128-v1-prefix", + ), + pytest.param( + "float16", + "computed-rope", + 256, + True, + [0, 0], + "fp8", + id="fp8-fp16-computed-rope-d256-v2-context", + ), + ], +) def test_prims_ts_context_receives_zeroed_v_tail( monkeypatch: pytest.MonkeyPatch, use_kv_cache_manager_v2: bool, @@ -149,8 +222,6 @@ def test_prims_ts_context_receives_zeroed_v_tail( preprocessing: str, head_dim: int, ) -> None: - import backend_case - from tensorrt_llm._torch.attention.backends.fmha.prims_ts import PrimsTSFmha from tensorrt_llm._torch.attention.backends.prims_ts.context import BatchPrefillPagedTSWrapper @@ -292,8 +363,11 @@ def run_with_zeroed_v_tail_check( assert plan_flags == [True] -@pytest.mark.parametrize("dtype", ["bfloat16", "float16"], ids=["bf16", "fp16"]) -@pytest.mark.parametrize("kv_dtype", [None, "fp8"], ids=["native-kv", "fp8-kv"]) +@pytest.mark.parametrize( + ("dtype", "kv_dtype"), + [("bfloat16", None), ("float16", "fp8")], + ids=["native-bf16", "fp8-fp16"], +) def test_prims_ts_decode_with_computed_rope( monkeypatch: pytest.MonkeyPatch, dtype: str, kv_dtype: str | None ) -> None: @@ -308,6 +382,7 @@ def run_generation_without_rope_table(self, params): monkeypatch.setattr(PrimsTSFmha, "run_generation", run_generation_without_rope_table) monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") + monkeypatch.setattr(backend_case, "BACKENDS_UNDER_TEST", ("TRTLLM",)) run_case( BackendCase( **{**_QWEN2_7B, "dtype": dtype}, @@ -326,6 +401,8 @@ def test_prims_ts_fp16_dense_context_with_alternate_shape( kv_dtype: str | None, ) -> None: monkeypatch.setenv("TLLM_FMHA_LIBS", "prims_ts") + if kv_dtype == "fp8": + monkeypatch.setattr(backend_case, "BACKENDS_UNDER_TEST", ("TRTLLM",)) case = BackendCase( num_heads=8, num_kv_heads=2, @@ -1814,22 +1891,10 @@ def counted_prims_context(self, *args, **kwargs): assert calls["prims_context"] == 0 -@pytest.mark.parametrize("head_dim", [64, 128, 256]) -@pytest.mark.parametrize( - ("mode", "page_size", "head_ratio"), - [ - ("disabled", 16, 1), - ("gmem_reduction", 32, 7), - ("gmem_reduction_with_separate_kernel", 64, 8), - ("cluster_smem_reduction", 128, 16), - ], -) def test_prims_ts_fp8_decode_bf16_device_scales( - monkeypatch: pytest.MonkeyPatch, head_dim: int, mode: str, page_size: int, head_ratio: int + monkeypatch: pytest.MonkeyPatch, ) -> None: - """Qualify BF16 stores/reducers and live device scales across graph replay.""" - from dataclasses import replace - + """Check FP8 decode with live device scales across graph replay.""" import cutlass from tensorrt_llm._torch.attention.backends.prims_ts import decode @@ -1838,6 +1903,7 @@ def test_prims_ts_fp8_decode_bf16_device_scales( ) torch.manual_seed(123) + head_dim, page_size, head_ratio = 128, 64, 8 batch_size, kv_heads = 2, 2 qo_heads = kv_heads * head_ratio max_kv_len = 2048 @@ -1854,7 +1920,7 @@ def test_prims_ts_fp8_decode_bf16_device_scales( bmm1 = torch.tensor([0.25 / math.sqrt(head_dim)], device="cuda") bmm2 = torch.tensor([1.75], device="cuda") output = torch.empty_like(q, dtype=torch.bfloat16) - splits = 1 if mode == "disabled" else 4 + splits = 4 cfg = make_decode_config( headdim=head_dim, args={"tile_size_q": 16, "groups_tokens_heads_q": True, "use_keeps_mma_ab": False}, @@ -1867,51 +1933,40 @@ def test_prims_ts_fp8_decode_bf16_device_scales( o_dtype=cutlass.BFloat16, qkv_layout="pagedKv", num_tokens_per_page=page_size, - split_kv_mode=mode, + split_kv_mode="gmem_reduction_with_separate_kernel", splits_kv=splits, max_splits_kv=splits, mask_type="causal", auto_tuner=False, ) - def plan(output_dtype: torch.dtype, use_device_scales: bool): - spec = decode._decode_launch_spec_from_config( - replace( - cfg, - out_dtype=cutlass.BFloat16 if output_dtype == torch.bfloat16 else cutlass.Float16, - ), - batch_size=batch_size, - num_qo_heads=qo_heads, - num_kv_heads=kv_heads, - head_dim=head_dim, - seq_len_q=1, - max_active_clusters=torch.cuda.get_device_properties(0).multi_processor_count, - ) - monkeypatch.setattr(decode, "_resolve_decode_launch_spec", lambda *args, **kwargs: spec) - wrapper = decode.BatchDecodePagedTSWrapper() - wrapper.plan( - q.device, - batch_size, - qo_heads, - kv_heads, - head_dim, - page_size, - max_kv_len, - q_dtype=q.dtype, - out_dtype=output_dtype, - mask_type="causal", - softmax_scale=bmm1 if use_device_scales else bmm1.item(), - output_scale=bmm2 if use_device_scales else bmm2.item(), - ) - return wrapper - - wrapper = plan(torch.bfloat16, True) - fp16_wrapper = plan(torch.float16, False) - bf16_host_wrapper = plan(torch.bfloat16, False) + spec = decode._decode_launch_spec_from_config( + cfg, + batch_size=batch_size, + num_qo_heads=qo_heads, + num_kv_heads=kv_heads, + head_dim=head_dim, + seq_len_q=1, + max_active_clusters=torch.cuda.get_device_properties(0).multi_processor_count, + ) + monkeypatch.setattr(decode, "_resolve_decode_launch_spec", lambda *args, **kwargs: spec) + wrapper = decode.BatchDecodePagedTSWrapper() + wrapper.plan( + q.device, + batch_size, + qo_heads, + kv_heads, + head_dim, + page_size, + max_kv_len, + q_dtype=q.dtype, + out_dtype=output.dtype, + mask_type="causal", + softmax_scale=bmm1, + output_scale=bmm2, + ) def run() -> torch.Tensor: - if mode == "gmem_reduction": - wrapper._plan_state.workspace.split_kv_counter.zero_() return wrapper.run( q, (k, v), @@ -1936,40 +1991,9 @@ def reference() -> torch.Tensor: return torch.stack(results) def check_output() -> None: - # The FP8 kernel rounds the intermediate P operand to E4M3. Compare - # math with that quantization tolerance, and the existing FP16 output - # path tightly to isolate BF16 stores and device-scale handling. + # The FP8 kernel rounds the intermediate P operand to E4M3. torch.testing.assert_close(output.float(), reference(), atol=0.01, rtol=0.05) - if mode == "gmem_reduction": - fp16_wrapper._plan_state.workspace.split_kv_counter.zero_() - fp16_output = fp16_wrapper.run( - q, - (k, v), - lengths, - table, - softmax_scale=bmm1.item(), - output_scale=bmm2.item(), - validate=False, - ) - torch.testing.assert_close(output.float(), fp16_output.float(), atol=0.0005, rtol=0.008) - - if mode == "gmem_reduction": - bf16_host_wrapper._plan_state.workspace.split_kv_counter.zero_() - bf16_host_output = bf16_host_wrapper.run( - q, - (k, v), - lengths, - table, - softmax_scale=bmm1.item(), - output_scale=bmm2.item(), - validate=False, - ) - torch.testing.assert_close( - output.float(), bf16_host_output.float(), atol=0.0005, rtol=0.008 - ) - if mode == "gmem_reduction": - wrapper._plan_state.workspace.split_kv_counter.zero_() wrapper.run( q, (k, v),