Skip to content

Commit ce3a859

Browse files
committed
[None][fix] Repair MSA patch composition and CPU test registration
Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com>
1 parent 5085662 commit ce3a859

4 files changed

Lines changed: 239 additions & 22 deletions

File tree

‎3rdparty/fetch_content.json‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,7 @@
9696
"git_submodules": "",
9797
"source_subdir": "dont-add-this-project-with-add-subdirectory",
9898
"patch_file": [
99-
"patches/msa_strided_paged_kv.patch",
100-
"patches/msa_jit_device_arch.patch"
99+
"patches/msa_strided_paged_kv.patch"
101100
]
102101
},
103102
{

‎3rdparty/patches/msa_strided_paged_kv.patch‎

Lines changed: 225 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6625,7 +6625,6 @@ index 21c777e..fa48c96 100644
66256625
v_q.global_scale,
66266626
k2q_row_ptr,
66276627
diff --git a/python/fmha_sm100/jit.py b/python/fmha_sm100/jit.py
6628-
index fa63a02..2d2aa2b 100644
66296628
--- a/python/fmha_sm100/jit.py
66306629
+++ b/python/fmha_sm100/jit.py
66316630
@@ -1,4 +1,5 @@
@@ -6648,7 +6647,7 @@ index fa63a02..2d2aa2b 100644
66486647
import logging
66496648
import os
66506649
import shutil
6651-
@@ -22,11 +24,54 @@ import jinja2
6650+
@@ -22,11 +24,54 @@
66526651

66536652
logger = logging.getLogger(__name__)
66546653

@@ -6706,7 +6705,7 @@ index fa63a02..2d2aa2b 100644
67066705
# Different build configs get separate cache dirs to avoid conflicts
67076706
suffix = ""
67086707
if os.environ.get("GPU_TRACE") is not None:
6709-
@@ -35,12 +80,58 @@ def _compute_cache_base():
6708+
@@ -35,12 +80,58 @@
67106709
suffix += "_sm_timing"
67116710
if os.environ.get("FMHA_GMEM_CHECK") is not None:
67126711
suffix += "_gmem_check"
@@ -6719,6 +6718,9 @@ index fa63a02..2d2aa2b 100644
67196718
+ if suffix and not explicit:
67206719
base = base.parent / (base.name + suffix)
67216720
- return base
6721+
-
6722+
-
6723+
-CACHE_BASE = _compute_cache_base()
67226724
+
67236725
+ # Hash templates, bindings and headers together; jit.py also covers changes
67246726
+ # to dispatch and compiler flags. Use relative names so installs share keys.
@@ -6738,9 +6740,8 @@ index fa63a02..2d2aa2b 100644
67386740
+ "diagnostic modes require recompilation)", cache_base,
67396741
+ )
67406742
+ return cache_base
6741-
6742-
6743-
-CACHE_BASE = _compute_cache_base()
6743+
+
6744+
+
67446745
+class _LazyCacheBase:
67456746
+ """The cache root, computed on first use: its suffix depends on the device (see _proxy_modes)."""
67466747
+
@@ -6768,7 +6769,7 @@ index fa63a02..2d2aa2b 100644
67686769

67696770

67706771
def _acquire_file_lock(lock_path):
6771-
@@ -55,13 +146,6 @@ def _release_file_lock(fd):
6772+
@@ -55,13 +146,6 @@
67726773
os.close(fd)
67736774

67746775

@@ -6782,17 +6783,92 @@ index fa63a02..2d2aa2b 100644
67826783

67836784
_PACK_FACTORS = [1,2,4,6,8,16]
67846785
# _PACK_FACTORS = [1, 6]
6785-
@@ -187,7 +271,8 @@ def _get_cuda_home():
6786+
@@ -187,7 +271,83 @@
67866787
raise RuntimeError("Cannot find CUDA toolkit. Set CUDA_HOME.")
67876788

67886789

67896790
-_ALL_VARIANTS_SO = CACHE_BASE / "_all_variants" / "all_variants.so"
67906791
+def _all_variants_so() -> Path:
67916792
+ return CACHE_BASE / "_all_variants" / "all_variants.so"
6793+
+
6794+
+_JIT_TARGET_UNSET = object()
6795+
+_jit_target_value = _JIT_TARGET_UNSET
6796+
+
6797+
+
6798+
+def _resolve_jit_target():
6799+
+ """The SM100-family target to build for: the visible devices', else None.
6800+
+
6801+
+ A JIT build only has to run on this process's GPUs, so when they all share
6802+
+ one architecture it targets that alone (one device compile instead of
6803+
+ three). MINFER_FMHA_CUDA_ARCH (e.g. ``103a``) overrides it; with no CUDA
6804+
+ device, devices outside the family, or visible devices of different
6805+
+ architectures, it is None and the build keeps the portable three-target
6806+
+ image. A resolved target is exported to MINFER_FMHA_CUDA_ARCH, so child
6807+
+ processes build for, and look in, the same target. Resolved on the first
6808+
+ build, not at import, so importing initializes no CUDA context.
6809+
+ """
6810+
+ global _jit_target_value
6811+
+ if _jit_target_value is not _JIT_TARGET_UNSET:
6812+
+ return _jit_target_value
6813+
+ target = os.environ.get("MINFER_FMHA_CUDA_ARCH") or None
6814+
+ if target is None:
6815+
+ try:
6816+
+ import torch
6817+
+ if torch.cuda.is_available():
6818+
+ caps = {
6819+
+ torch.cuda.get_device_capability(i)
6820+
+ for i in range(torch.cuda.device_count())
6821+
+ }
6822+
+ if len(caps) == 1 and caps <= {(10, 0), (10, 3)}:
6823+
+ major, minor = caps.pop()
6824+
+ target = f"{major}{minor}a"
6825+
+ except (ImportError, RuntimeError): # keep the portable image
6826+
+ target = None
6827+
+ if target is not None:
6828+
+ os.environ["MINFER_FMHA_CUDA_ARCH"] = target
6829+
+ _jit_target_value = target
6830+
+ return target
6831+
+
6832+
+
6833+
+def _jit_base():
6834+
+ """Root of what JIT builds: per target, so images for one GPU are never
6835+
+ loaded on another; the portable image keeps the shared root."""
6836+
+ target = _resolve_jit_target()
6837+
+ return CACHE_BASE / f"sm_{target}" if target else CACHE_BASE
6838+
+
6839+
+
6840+
+def _built_dir(name, so_name):
6841+
+ """Where module ``name`` is loaded from and built: this target's directory,
6842+
+ unless only the shared CACHE_BASE holds a build of it, a portable image
6843+
+ from scripts/warmup_fmha_sm100.py or from a process that built without a
6844+
+ target (no usable CUDA device, or GPUs of different architectures)."""
6845+
+ target_dir = _jit_base() / name
6846+
+ shared_dir = CACHE_BASE / name
6847+
+ if not (target_dir / so_name).exists() and (shared_dir / so_name).exists():
6848+
+ return shared_dir
6849+
+ return target_dir
6850+
+
6851+
+
6852+
+def _select_gencode(nvcc_flags, cache_dir):
6853+
+ """nvcc_flags with its -gencode targets replaced, in place, by the one of
6854+
+ _resolve_jit_target(), for a build in that target's directory
6855+
+ (_jit_base()). Builds elsewhere, such as scripts/warmup_fmha_sm100.py
6856+
+ writing to the shared CACHE_BASE, keep every target, so any GPU can load
6857+
+ what they write."""
6858+
+ target = _resolve_jit_target()
6859+
+ first = next((i for i, flag in enumerate(nvcc_flags)
6860+
+ if flag.startswith("-gencode=")), None)
6861+
+ if (not target or first is None
6862+
+ or not Path(cache_dir).is_relative_to(_jit_base())):
6863+
+ return nvcc_flags
6864+
+ rest = [flag for flag in nvcc_flags if not flag.startswith("-gencode=")]
6865+
+ return (rest[:first] + [f"-gencode=arch=compute_{target},code=sm_{target}"]
6866+
+ + rest[first:])
6867+
+
67926868

67936869
def _get_nvcc_flags(cache_dir, fmha=True):
67946870
tvm_include = _get_tvm_ffi_include()
6795-
@@ -199,6 +284,9 @@ def _get_nvcc_flags(cache_dir, fmha=True):
6871+
@@ -199,6 +359,9 @@
67966872
"--expt-relaxed-constexpr", "--expt-extended-lambda",
67976873
"-gencode=arch=compute_100a,code=sm_100a",
67986874
"-gencode=arch=compute_103a,code=sm_103a",
@@ -6802,19 +6878,21 @@ index fa63a02..2d2aa2b 100644
68026878
"-static-global-template-stub=false",
68036879
"-DFLASHINFER_ENABLE_BF16",
68046880
"-DFLASHINFER_ENABLE_FP8_E4M3",
6805-
@@ -225,6 +313,11 @@ def _get_nvcc_flags(cache_dir, fmha=True):
6881+
@@ -225,7 +388,12 @@
68066882
nvcc_flags.append("-DSM_TIMING_ENABLED")
68076883
if os.environ.get("FMHA_GMEM_CHECK") is not None:
68086884
nvcc_flags.append("-DFMHA_GMEM_BOUNDS_CHECK")
6885+
- return " ".join(nvcc_flags)
68096886
+ proxy_chain, proxy_single_s = _proxy_modes()
68106887
+ if proxy_chain:
68116888
+ nvcc_flags.append("-DFMHA_ONLYSCORE_PER_TILE_CORRECTION")
68126889
+ if proxy_single_s:
68136890
+ nvcc_flags.append("-DFMHA_ONLYSCORE_SINGLE_S")
6814-
return " ".join(nvcc_flags)
6891+
+ return " ".join(_select_gencode(nvcc_flags, cache_dir))
68156892

68166893
class _VariantWrapper:
6817-
@@ -257,9 +350,10 @@ class FMHAVariantManager:
6894+
"""Wraps a TVM-FFI function to look like a module with .run()."""
6895+
@@ -257,9 +425,10 @@
68186896
def _ensure_all_module(self):
68196897
if not self._all_module_checked:
68206898
self._all_module_checked = True
@@ -6827,6 +6905,141 @@ index fa63a02..2d2aa2b 100644
68276905

68286906
def get_variant(self, dtype_code, qo_tile_size, single_wg,
68296907
sparse_mode, page_size, split_kv, pack_factor):
6908+
@@ -289,12 +458,12 @@
6909+
pass
6910+
6911+
# Try per-variant .so
6912+
- cache_dir = CACHE_BASE / variant_name
6913+
+ cache_dir = _built_dir(variant_name, f"{variant_name}.so")
6914+
so_path = cache_dir / f"{variant_name}.so"
6915+
lock_fd = _acquire_file_lock(cache_dir / ".compile.lock")
6916+
try:
6917+
if not so_path.exists():
6918+
- self._compile_only(variant_name, params)
6919+
+ self._compile_only(variant_name, params, cache_dir)
6920+
6921+
import tvm_ffi
6922+
module = tvm_ffi.load_module(str(so_path))
6923+
@@ -304,9 +473,14 @@
6924+
self._loaded[variant_name] = _VariantWrapper(fn)
6925+
return self._loaded[variant_name]
6926+
6927+
- def _compile_only(self, variant_name, params):
6928+
- """Compile a variant without loading. Safe to call from subprocesses."""
6929+
- cache_dir = CACHE_BASE / variant_name
6930+
+ def _compile_only(self, variant_name, params, cache_dir=None):
6931+
+ """Compile a variant without loading. Safe to call from subprocesses.
6932+
+
6933+
+ ``cache_dir`` is where to build, so a caller that already chose the
6934+
+ directory it will load from builds into that one; by default
6935+
+ _built_dir() chooses."""
6936+
+ if cache_dir is None:
6937+
+ cache_dir = _built_dir(variant_name, f"{variant_name}.so")
6938+
so_path = cache_dir / f"{variant_name}.so"
6939+
6940+
if so_path.exists():
6941+
@@ -363,7 +537,7 @@
6942+
6943+
def _run_ninja(self, cache_dir):
6944+
result = subprocess.run(
6945+
- ["ninja", "-j1"],
6946+
+ ["ninja", "-j2"],
6947+
cwd=str(cache_dir),
6948+
capture_output=True,
6949+
text=True,
6950+
@@ -395,9 +569,11 @@
6951+
_plan_lock = threading.Lock()
6952+
6953+
6954+
-def _do_compile_plan():
6955+
- """Generate and compile plan kernel. No TVM loading."""
6956+
- cache_dir = CACHE_BASE / "plan"
6957+
+def _do_compile_plan(cache_dir=None):
6958+
+ """Generate and compile plan kernel. No TVM loading. ``cache_dir``: where
6959+
+ to build; by default _built_dir() chooses."""
6960+
+ if cache_dir is None:
6961+
+ cache_dir = _built_dir("plan", "fmha_sm100_plan.so")
6962+
so_path = cache_dir / "fmha_sm100_plan.so"
6963+
6964+
if so_path.exists():
6965+
@@ -455,11 +631,14 @@
6966+
6967+
def _compile_plan_module():
6968+
"""Compile and load plan kernel."""
6969+
- lock_fd = _acquire_file_lock(CACHE_BASE / "plan.lock")
6970+
+ # Build and load in one directory, under the lock every process building
6971+
+ # there takes.
6972+
+ cache_dir = _built_dir("plan", "fmha_sm100_plan.so")
6973+
+ lock_fd = _acquire_file_lock(cache_dir.parent / "plan.lock")
6974+
try:
6975+
- _do_compile_plan()
6976+
+ _do_compile_plan(cache_dir)
6977+
import tvm_ffi
6978+
- so_path = CACHE_BASE / "plan" / "fmha_sm100_plan.so"
6979+
+ so_path = cache_dir / "fmha_sm100_plan.so"
6980+
return tvm_ffi.load_module(str(so_path))
6981+
finally:
6982+
_release_file_lock(lock_fd)
6983+
@@ -486,8 +665,9 @@
6984+
_sparse_topk_lock = threading.Lock()
6985+
6986+
6987+
-def _do_compile_sparse_topk():
6988+
- cache_dir = CACHE_BASE / "sparse_topk"
6989+
+def _do_compile_sparse_topk(cache_dir=None):
6990+
+ if cache_dir is None:
6991+
+ cache_dir = _built_dir("sparse_topk", "sparse_topk_select.so")
6992+
so_path = cache_dir / "sparse_topk_select.so"
6993+
6994+
if so_path.exists():
6995+
@@ -553,11 +733,14 @@
6996+
with _sparse_topk_lock:
6997+
if _sparse_topk_module is not None:
6998+
return _sparse_topk_module
6999+
- lock_fd = _acquire_file_lock(CACHE_BASE / "sparse_topk.lock")
7000+
+ # Build and load in one directory, under the lock every process
7001+
+ # building there takes.
7002+
+ cache_dir = _built_dir("sparse_topk", "sparse_topk_select.so")
7003+
+ lock_fd = _acquire_file_lock(cache_dir.parent / "sparse_topk.lock")
7004+
try:
7005+
- _do_compile_sparse_topk()
7006+
+ _do_compile_sparse_topk(cache_dir)
7007+
import tvm_ffi
7008+
- so_path = CACHE_BASE / "sparse_topk" / "sparse_topk_select.so"
7009+
+ so_path = cache_dir / "sparse_topk_select.so"
7010+
_sparse_topk_module = tvm_ffi.load_module(str(so_path))
7011+
finally:
7012+
_release_file_lock(lock_fd)
7013+
@@ -572,8 +755,9 @@
7014+
_reduction_lock = threading.Lock()
7015+
7016+
7017+
-def _do_compile_reduction():
7018+
- cache_dir = CACHE_BASE / "reduction"
7019+
+def _do_compile_reduction(cache_dir=None):
7020+
+ if cache_dir is None:
7021+
+ cache_dir = _built_dir("reduction", "fmha_sm100_reduction.so")
7022+
so_path = cache_dir / "fmha_sm100_reduction.so"
7023+
7024+
if so_path.exists():
7025+
@@ -638,11 +822,14 @@
7026+
with _reduction_lock:
7027+
if _reduction_module is not None:
7028+
return _reduction_module
7029+
- lock_fd = _acquire_file_lock(CACHE_BASE / "reduction.lock")
7030+
+ # Build and load in one directory, under the lock every process
7031+
+ # building there takes.
7032+
+ cache_dir = _built_dir("reduction", "fmha_sm100_reduction.so")
7033+
+ lock_fd = _acquire_file_lock(cache_dir.parent / "reduction.lock")
7034+
try:
7035+
- _do_compile_reduction()
7036+
+ _do_compile_reduction(cache_dir)
7037+
import tvm_ffi
7038+
- so_path = CACHE_BASE / "reduction" / "fmha_sm100_reduction.so"
7039+
+ so_path = cache_dir / "fmha_sm100_reduction.so"
7040+
_reduction_module = tvm_ffi.load_module(str(so_path))
7041+
finally:
7042+
_release_file_lock(lock_fd)
68307043
diff --git a/python/fmha_sm100/sparse.py b/python/fmha_sm100/sparse.py
68317044
index 7006fcd..9a09324 100644
68327045
--- a/python/fmha_sm100/sparse.py

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,6 @@ l0_cpu:
160160
- unittest/_torch/models/test_minimax_m3_drafter_rows.py
161161
- unittest/_torch/kernels/serial/test_m3_qkv_contract.py
162162
- unittest/_torch/models/test_minimax_m3.py::test_ctx_qkv_invalid_arguments_keep_stock_fallback
163-
- unittest/_torch/models/test_minimax_m3.py::test_cutedsl_shared_fold_backend_is_rubin_only
164163
- unittest/_torch/models/test_minimax_m3.py::test_ctx_qkv_fused_keeps_native_mxfp8_without_rubin_dsl
165164
- unittest/_torch/models/test_minimax_m3.py::test_ctx_qkv_fused_shares_initialization_cache
166165
- unittest/_torch/models/test_minimax_m3.py::test_ctx_qkv_fused_skips_autotune_pass

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

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515
msa_package_available,
1616
)
1717

18-
pytestmark = pytest.mark.skipif(
19-
not msa_package_available(), reason="fmha_sm100 (MSA submodule) required"
20-
)
18+
pytestmark = [
19+
pytest.mark.cpu_only,
20+
pytest.mark.skipif(not msa_package_available(), reason="fmha_sm100 (MSA submodule) required"),
21+
]
2122

2223
ARCH_ENV = "MINFER_FMHA_CUDA_ARCH"
2324

@@ -29,15 +30,20 @@ def jit(monkeypatch, tmp_path):
2930
import fmha_sm100.jit as jit
3031

3132
monkeypatch.setattr(jit, "_jit_target_value", jit._JIT_TARGET_UNSET)
33+
monkeypatch.setattr(jit, "_proxy_modes_cache", None)
3234
monkeypatch.setattr(jit, "CACHE_BASE", tmp_path)
3335
monkeypatch.setenv(ARCH_ENV, "")
3436
return jit
3537

3638

37-
def fake_gpus(monkeypatch, *capabilities):
39+
def fake_gpus(monkeypatch: pytest.MonkeyPatch, *capabilities: tuple[int, int]) -> None:
3840
monkeypatch.setattr(torch.cuda, "is_available", lambda: bool(capabilities))
3941
monkeypatch.setattr(torch.cuda, "device_count", lambda: len(capabilities))
40-
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda i: capabilities[i])
42+
monkeypatch.setattr(
43+
torch.cuda,
44+
"get_device_capability",
45+
lambda device=None: capabilities[0 if device is None else device],
46+
)
4147

4248

4349
def gencodes(jit, cache_dir):
@@ -63,8 +69,8 @@ def test_one_architecture_is_the_target_and_is_exported(jit, monkeypatch, capabi
6369

6470
@pytest.mark.parametrize(
6571
"capabilities",
66-
[[(10, 0), (10, 3)], [(9, 0)], [(12, 0)], []],
67-
ids=["sm100_and_sm103", "sm90", "sm120", "no_gpu"],
72+
[[(10, 0), (10, 3)], [(10, 7)], [(9, 0)], [(12, 0)], []],
73+
ids=["sm100_and_sm103", "sm107_family", "sm90", "sm120", "no_gpu"],
6874
)
6975
def test_other_devices_keep_the_portable_image(jit, monkeypatch, capabilities):
7076
fake_gpus(monkeypatch, *capabilities)

0 commit comments

Comments
 (0)