Skip to content

Commit dc2f5c4

Browse files
committed
[None][fix] Isolate finalize offers and MSA targets and preserve carrier shapes
Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com>
1 parent ce3a859 commit dc2f5c4

8 files changed

Lines changed: 307 additions & 36 deletions

File tree

‎3rdparty/patches/msa_strided_paged_kv.patch‎

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2789,27 +2789,26 @@ index 4719a48..65e51be 100644
27892789

27902790

27912791
diff --git a/python/fmha_sm100/cute/src/common/aot_cache.py b/python/fmha_sm100/cute/src/common/aot_cache.py
2792-
index 99fd0b4..8037d13 100644
27932792
--- a/python/fmha_sm100/cute/src/common/aot_cache.py
27942793
+++ b/python/fmha_sm100/cute/src/common/aot_cache.py
2795-
@@ -6,6 +6,12 @@
2794+
@@ -5,6 +5,12 @@
2795+
27962796
Saves compiled TVM FFI kernels as .o files on first compile,
27972797
loads them on subsequent runs to skip JIT compilation.
2798-
2798+
+
27992799
+Cached objects are keyed by the caller's kernel key *and* a build fingerprint
28002800
+covering the target GPU architecture and the kernel sources. Without the
28012801
+fingerprint a .o built for one architecture (or from an older revision of the
28022802
+kernel) is silently reused on another, which both miscompiles across
28032803
+SM100/SM103 and makes local kernel edits appear to have no effect.
2804-
+
2804+
28052805
Environment variables:
28062806
MM_SPARSE_ATTN_AOT_CACHE: Override cache directory
2807-
(default: ~/.cache/minfer/mm_sparse_attn)
2808-
@@ -25,10 +31,87 @@ _AOT_CACHE_DIR = os.environ.get(
2807+
@@ -25,10 +31,87 @@
28092808
_AOT_DISABLE = os.environ.get("MM_SPARSE_ATTN_AOT_DISABLE", "0") == "1"
28102809

28112810
_loaded_modules: dict[str, object] = {}
2812-
+_build_fingerprint_cache: str | None = None
2811+
+_build_fingerprint_cache: dict[str, str] = {}
28132812
+
28142813
+# .../cute/src/common/aot_cache.py -> .../cute
28152814
+_PACKAGE_ROOT = os.path.dirname(
@@ -2848,29 +2847,29 @@ index 99fd0b4..8037d13 100644
28482847
+ return "smunknown"
28492848
+
28502849
+
2851-
+_r2_store_cache: bool | None = None
2850+
+_r2_store_cache: dict[tuple[int, int], bool] = {}
28522851
+
28532852
+
28542853
+def r2_store_enabled() -> bool:
28552854
+ """Whether the NVFP4-KV sparse prefill uses the R2 store warpgroup.
28562855
+
2857-
+ SM107 only (resolved once from the device capability); TRTLLM_MSA_DISABLE_R2STORE=1 restores the stock
2856+
+ SM107 only (resolved once per target architecture); TRTLLM_MSA_DISABLE_R2STORE=1 restores the stock
28582857
+ in-softmax epilogue there too.
28592858
+ """
2860-
+ global _r2_store_cache
2861-
+ if _r2_store_cache is None:
2862-
+ import torch
2859+
+ import torch
28632860
+
2864-
+ _r2_store_cache = (
2865-
+ torch.cuda.get_device_capability() == (10, 7)
2861+
+ target = torch.cuda.get_device_capability()
2862+
+ if target not in _r2_store_cache:
2863+
+ _r2_store_cache[target] = (
2864+
+ target == (10, 7)
28662865
+ and os.environ.get("TRTLLM_MSA_DISABLE_R2STORE", "0") != "1"
28672866
+ )
2868-
+ return _r2_store_cache
2867+
+ return _r2_store_cache[target]
28692868
+
28702869
+
28712870
+def _build_fingerprint() -> str:
2872-
+ global _build_fingerprint_cache
2873-
+ if _build_fingerprint_cache is None:
2871+
+ target = _target_arch()
2872+
+ if target not in _build_fingerprint_cache:
28742873
+ try:
28752874
+ import cutlass
28762875
+
@@ -2880,10 +2879,10 @@ index 99fd0b4..8037d13 100644
28802879
+ # Construction-time codegen knobs must be part of the key: the source hash
28812880
+ # alone would hand one mode's cached .o to the other.
28822881
+ r2store = "r2store" + ("0" if r2_store_enabled() else "1")
2883-
+ _build_fingerprint_cache = "-".join(
2884-
+ (_target_arch(), str(cutlass_version), _source_fingerprint(), r2store)
2882+
+ _build_fingerprint_cache[target] = "-".join(
2883+
+ (target, str(cutlass_version), _source_fingerprint(), r2store)
28852884
+ )
2886-
+ return _build_fingerprint_cache
2885+
+ return _build_fingerprint_cache[target]
28872886

28882887

28892888
def _key_to_path(key: tuple) -> str:

‎tensorrt_llm/_torch/modules/linear.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3801,6 +3801,8 @@ def apply(self, module: Linear, input: torch.Tensor | MxFp8QuantizedTensor,
38013801
# Tune only in the warmup-only pass (flashinfer_mxfp8_autotune).
38023802
if quantized_input is not None:
38033803
input = quantized_input.unquantized()
3804+
if input.dim() > 2:
3805+
input = input.reshape(-1, input.shape[-1])
38043806
output = mxfp8_quantize_gemm_autotuned(
38053807
input,
38063808
module.weight,
@@ -3814,6 +3816,8 @@ def apply(self, module: Linear, input: torch.Tensor | MxFp8QuantizedTensor,
38143816
act_e4m3, act_sf = (
38153817
quantized_input.quantized() if quantized_input is not None
38163818
else torch.ops.trtllm.mxfp8_quantize(input, True))
3819+
if act_e4m3.dim() > 2:
3820+
act_e4m3 = act_e4m3.reshape(-1, act_e4m3.shape[-1])
38173821
use_flashinfer = self.backend == "flashinfer" or (
38183822
self.backend == "auto" and not is_torch_compiling() and
38193823
(_FLASHINFER_MXFP8_AUTOTUNE_ACTIVE.get() or

‎tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""``TrtllmCutedslGroupedGemmNvfp4Impl``: ``trtllm.cutedsl.grouped_gemm.nvfp4``."""
1616

1717
import os
18+
from contextvars import ContextVar
1819

1920
import torch
2021

@@ -74,7 +75,8 @@ class FinalizeResidual:
7475
finalize to add while it un-permutes: bitwise ``residual.add_(routed_output)``. ``event`` (recorded on the stream
7576
that produced it) is waited on right before the finalize; ``consumed`` tells the caller to skip its own add."""
7677

77-
def __init__(self, residual: torch.Tensor, event=None):
78+
def __init__(self, residual: torch.Tensor, event: torch.cuda.Event | None = None) -> None:
79+
self.previous: FinalizeResidual | None = None
7880
self.residual = residual
7981
self.event = event
8082
self.consumed = False
@@ -83,19 +85,25 @@ def __init__(self, residual: torch.Tensor, event=None):
8385
)
8486

8587

86-
_FINALIZE_RESIDUAL: list[FinalizeResidual] = []
88+
_FINALIZE_RESIDUAL: ContextVar[FinalizeResidual | None] = ContextVar(
89+
"moe_finalize_residual", default=None
90+
)
8791

8892

89-
def offer_finalize_residual(residual: torch.Tensor, event=None) -> FinalizeResidual:
90-
"""Offer ``residual`` to the next deterministic Rubin FC2 finalize on this thread (cleared by the caller)."""
91-
_FINALIZE_RESIDUAL.clear()
93+
def offer_finalize_residual(
94+
residual: torch.Tensor, event: torch.cuda.Event | None = None
95+
) -> FinalizeResidual:
96+
"""Offer ``residual`` to the next deterministic Rubin FC2 finalize in this execution context."""
9297
holder = FinalizeResidual(residual, event)
93-
_FINALIZE_RESIDUAL.append(holder)
98+
holder.previous = _FINALIZE_RESIDUAL.get()
99+
_FINALIZE_RESIDUAL.set(holder)
94100
return holder
95101

96102

97103
def clear_finalize_residual() -> None:
98-
_FINALIZE_RESIDUAL.clear()
104+
"""Restore the offer that preceded the current execution context's innermost offer."""
105+
holder = _FINALIZE_RESIDUAL.get()
106+
_FINALIZE_RESIDUAL.set(holder.previous if holder is not None else None)
99107

100108

101109
@register_moe_impl
@@ -643,7 +651,7 @@ def run_moe_nvfp4_impl(
643651
tile_size=tile_size,
644652
output_dtype=output_dtype,
645653
)
646-
holder = _FINALIZE_RESIDUAL[0] if _FINALIZE_RESIDUAL else None
654+
holder = _FINALIZE_RESIDUAL.get()
647655
if holder is not None:
648656
holder.calls += 1
649657
if (
@@ -669,7 +677,6 @@ def run_moe_nvfp4_impl(
669677
holder.residual.contiguous(),
670678
)
671679
holder.consumed = True
672-
_FINALIZE_RESIDUAL.clear()
673680
else:
674681
torch.ops.trtllm.moe_unpermute_inplace(
675682
permuted_input=fc2_rows,

‎tests/integration/test_lists/test-db/l0_gr100.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ l0_gr100:
2424
- unittest/_torch/attention/sparse/msa/test_minimax_m3_dense_prefill_fa4_patched.py
2525
- unittest/_torch/attention/sparse/msa/test_minimax_m3_tile_select.py
2626
- unittest/_torch/attention/sparse/msa/test_msa_prefill_nvfp4_out_in_place.py
27+
- unittest/_torch/attention/sparse/msa/test_minimax_m3_sparse_attn_decode.py::test_msa_nvfp4_r2_store_matches_reference
2728
- unittest/_torch/attention/sparse/msa/test_msa_k2q_ws_stream.py::test_k2q_workspace_matches_stock_contents
2829
- unittest/_torch/attention/sparse/msa/test_msa_q_e4m3.py
2930
- unittest/_torch/attention/sparse/msa/test_minimax_m3_proxy_nofill.py

‎tests/unittest/_torch/attention/sparse/msa/test_minimax_m3_sparse_attn_decode.py‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@
1010
truncated at the query token's own causal extent.
1111
"""
1212

13+
import inspect
1314
import logging
1415
import os
1516
from pathlib import Path
1617
from types import SimpleNamespace
18+
from unittest.mock import Mock
1719

1820
import pytest
1921
import torch
@@ -46,7 +48,7 @@
4648
pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
4749

4850
skip_not_sm100 = pytest.mark.skipif(
49-
get_sm_version() not in (100, 103),
51+
not torch.cuda.is_available() or get_sm_version() not in (100, 103),
5052
reason="MiniMax-M3 NVFP4 and fmha_sm100 require SM100/SM103.",
5153
)
5254

@@ -307,6 +309,95 @@ def _make_nvfp4_inputs(seq_lens, *, num_kv_heads=1, group=8, decode_query_len=1,
307309
)
308310

309311

312+
@pytest.mark.skipif(
313+
not torch.cuda.is_available() or get_sm_version() != 107,
314+
reason="R2 sparse-prefill store requires SM107",
315+
)
316+
def test_msa_nvfp4_r2_store_matches_reference(monkeypatch: pytest.MonkeyPatch) -> None:
317+
require_msa_module()
318+
# Optional CuTe-DSL dependency: import only after the GPU/platform gate.
319+
from fmha_sm100 import sparse as msa_sparse
320+
from src.common import aot_cache
321+
322+
interface = inspect.getmodule(msa_sparse.sparse_atten_nvfp4_kv_func)
323+
assert interface is not None
324+
q_len, kv_len, group = 257, 513, 8
325+
case = _make_nvfp4_inputs([kv_len], group=group, decode_query_len=q_len, seed=101)
326+
cu_q = torch.tensor([0, q_len], device="cuda", dtype=torch.int32)
327+
cu_k = torch.tensor([0, kv_len], device="cuda", dtype=torch.int32)
328+
row_ptr, q_indices, schedule = msa_sparse.build_k2q_csr(
329+
case.topk_idx,
330+
cu_q,
331+
cu_k,
332+
PAGE_SIZE,
333+
total_k=kv_len,
334+
max_seqlen_k=kv_len,
335+
max_seqlen_q=q_len,
336+
total_rows=(kv_len + PAGE_SIZE - 1) // PAGE_SIZE,
337+
qhead_per_kv=group,
338+
return_schedule=True,
339+
)
340+
# Fewer blocks than top-k: the helper selects the entire causal prefix.
341+
# Use independently dequantized K/V, including a partial last page.
342+
pages = case.block_table[0].long()
343+
keys = case.k_ref[pages, 0].reshape(-1, HEAD_DIM)[:kv_len]
344+
values = case.v_ref[pages, 0].reshape(-1, HEAD_DIM)[:kv_len]
345+
logits = torch.einsum("qhd,kd->qhk", case.q.float(), keys) * HEAD_DIM**-0.5
346+
causal_end = kv_len - q_len + torch.arange(q_len, device="cuda")
347+
invalid = torch.arange(kv_len, device="cuda")[None, :] > causal_end[:, None]
348+
logits.masked_fill_(invalid[:, None, :], -float("inf"))
349+
reference = torch.einsum("qhk,kd->qhd", logits.softmax(dim=-1), values)
350+
reference_lse = logits.logsumexp(dim=-1)
351+
352+
results = []
353+
for enabled in (False, True):
354+
with monkeypatch.context() as patch:
355+
patch.setenv("TRTLLM_MSA_DISABLE_R2STORE", "0" if enabled else "1")
356+
patch.setattr(aot_cache, "_r2_store_cache", {})
357+
patch.setattr(aot_cache, "_build_fingerprint_cache", {})
358+
patch.setattr(aot_cache, "_AOT_DISABLE", True)
359+
patch.setattr(interface, "_compile_cache", {})
360+
# Observe real compilation; a cached binary must not hide either path.
361+
compile_spy = Mock(spec_set=interface.cute.compile, wraps=interface.cute.compile)
362+
patch.setattr(interface.cute, "compile", compile_spy)
363+
out, lse = msa_sparse.sparse_atten_nvfp4_kv_func(
364+
case.q,
365+
case.k_paged,
366+
case.v_paged,
367+
case.scales["k_block_scale"],
368+
case.scales["v_block_scale"],
369+
case.scales["k_global_scale"],
370+
case.scales["v_global_scale"],
371+
row_ptr,
372+
q_indices,
373+
MSA_REQUIRED_TOPK,
374+
cu_seqlens_q=cu_q,
375+
cu_seqlens_k=cu_k,
376+
max_seqlen_q=q_len,
377+
max_seqlen_k=kv_len,
378+
blk_kv=PAGE_SIZE,
379+
causal=True,
380+
softmax_scale=HEAD_DIM**-0.5,
381+
partial_dtype=torch.bfloat16,
382+
return_softmax_lse=True,
383+
page_table=case.block_table,
384+
seqused_k=case.seq_lens,
385+
schedule=schedule,
386+
)
387+
kernels = [
388+
call.args[0]
389+
for call in compile_spy.call_args_list
390+
if call.args
391+
and isinstance(call.args[0], interface.SparseAttentionForwardNvfp4KvSm100)
392+
]
393+
assert kernels and all(kernel.r2_store is enabled for kernel in kernels)
394+
torch.testing.assert_close(out.float(), reference, rtol=3e-2, atol=3e-2)
395+
torch.testing.assert_close(lse, reference_lse, rtol=1e-2, atol=1e-2)
396+
results.append((out.clone(), lse.clone()))
397+
assert torch.equal(results[0][0].view(torch.int16), results[1][0].view(torch.int16))
398+
assert torch.equal(results[0][1].view(torch.int32), results[1][1].view(torch.int32))
399+
400+
310401
def _run_nvfp4(case, **kwargs):
311402
# An E4M3 q is widened in-register, so the output stays at compute dtype.
312403
out_dtype = torch.bfloat16 if case.q.dtype == torch.float8_e4m3fn else case.q.dtype

‎tests/unittest/_torch/attention/sparse/msa/test_msa_jit_target.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
import os
99
import re
10+
from pathlib import Path
11+
from types import ModuleType
1012

1113
import pytest
1214
import torch
@@ -110,3 +112,31 @@ def test_a_shared_build_is_loaded_until_the_target_has_its_own(jit, monkeypatch)
110112
target_dir.mkdir(parents=True)
111113
(target_dir / so_name).touch()
112114
assert jit._built_dir("plan", so_name) == target_dir
115+
116+
117+
@pytest.mark.parametrize(
118+
"targets", [((10, 0), (10, 7)), ((10, 7), (10, 0))], ids=["sm100_first", "sm107_first"]
119+
)
120+
@pytest.mark.parametrize("disable_r2", [False, True])
121+
def test_aot_cache_and_codegen_follow_each_target(
122+
jit: ModuleType,
123+
monkeypatch: pytest.MonkeyPatch,
124+
tmp_path: Path,
125+
targets: tuple[tuple[int, int], tuple[int, int]],
126+
disable_r2: bool,
127+
) -> None:
128+
# The optional MSA package and its import path are prepared by the jit fixture.
129+
from src.common import aot_cache
130+
131+
monkeypatch.setattr(aot_cache, "_build_fingerprint_cache", {})
132+
monkeypatch.setattr(aot_cache, "_r2_store_cache", {})
133+
monkeypatch.setattr(aot_cache, "_AOT_CACHE_DIR", str(tmp_path))
134+
monkeypatch.setenv("TRTLLM_MSA_DISABLE_R2STORE", "1" if disable_r2 else "0")
135+
paths = []
136+
for target in (*targets, targets[0]):
137+
fake_gpus(monkeypatch, target)
138+
assert aot_cache.r2_store_enabled() is (target == (10, 7) and not disable_r2)
139+
assert aot_cache._build_fingerprint().startswith(f"sm{target[0]}{target[1]}-")
140+
paths.append(aot_cache._key_to_path(("target_isolation", 128)))
141+
assert paths[0] != paths[1]
142+
assert paths[0] == paths[2]

0 commit comments

Comments
 (0)