From c1896ed351adb5f3093652ce77db16177547b757 Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Thu, 26 Nov 2026 05:37:33 -0800 Subject: [PATCH 1/5] [autotuner] Match direct CuTe configuration facts to the requested device A direct config for a B200 could validate against the current H100 even while it recorded the B200's 148 SMs. Direct configuration under a simulated CuTe target could also observe the host capability or only one SM while a bound kernel correctly used the simulated facts. Read the canonical capability from its module at query time. The explicit-device hook delegates to the existing no-argument backend hook by default; CuTe probes the requested device unless the existing hook was overridden. Bound-kernel facts, including an explicit None, take priority. A nonexistent visible CUDA ordinal gives an unknown capability. Detect it on Torch's specific invalid-device assertion, then confirm it is out of range: successful queries keep their cache fast path, and unrelated driver or initialization errors still propagate. Model both direct and bound SM counts in the target context. Hide the indexed capability reader itself in the unavailable-CUDA fixture, so it neither fills the process's real cache with None nor exposes a warm entry; an outer modeled public probe remains authoritative. A CUDA process using PyTorch's NVML-based check can regain visibility before CUDA initializes. Return None for the unavailable probe without caching it: the next request can read the device, and a successful cached explicit lookup needs no further availability or property checks. The flash and config tests that used the former private search-surface probe now patch the canonical name; the redundant resource-test patch is gone. Testing: Scoped scripts/run_tests.py CPU configuration, helper and flash lanes passed 548 (20 skipped) CuTe and 143 (7 skipped) stable CI Triton. Strict lint and Pyrefly passed. The cold zero-to-one test previously returned None twice; now no absent entry is cached, the restored ordinal gives SM100, and no CUDA availability or property call is made on the next hit. Current-H100/requested-B200 gives SM90/120 and SM100/148; explicit None gives None/148. Class, subclass and plugin overrides, outer facts and the one-visible-device invalid-ordinal controls are exercised. The 25,987 full standalone CuTe CPU passes (567 skips) were on an earlier revision; the current counts above refer to the scoped tests. Integrated validation before changing the unavailable-cache miss to be retried: full CuTe lanes passed 26,211 CPU and 16,138 GPU tests on B200 3/5; full Triton lanes passed 4,900 CPU and 3,395 GPU tests on B200 6; Pallas interpreter passed 269 with 44 skipped. These runs include the requested-device, unavailable-ordinal, legacy-hook and fixture fixes. The final cache correction also passed the real zero-to-one transition on B200 4 with PyTorch's NVML-based availability check. No CUDA context was initialized while hidden; exposing the device then gave SM100/148 rather than a cached unknown. The separate real one-visible-device control returned unknown for a missing ordinal and left the visible target correct before and after a cold or warm simulated scope. Review notes: - Deferred: tensor-descriptor admission still uses the current device, including for a bound spec which already supplies the requested capability on upstream main. KNOWN_GAPS.md, tensor-descriptor-choices-use-the-current-gpu. Fixing only the search menu would leave lowering and epilogue decisions inconsistent across heterogeneous targets. Both configuration directions were reproduced; the single-B200 presets do not exercise that hardware mismatch. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4750, branch: choijon5/helion-b200/shared/2 --- KNOWN_GAPS.md | 38 ++++ helion/_compat.py | 26 ++- .../_compiler/cute/autotune/search_surface.py | 29 ++- helion/_compiler/cute/target_facts.py | 8 +- helion/_testing/__init__.py | 14 +- helion/_testing/cute_codegen.py | 1 + helion/autotuner/config_spec.py | 2 + helion/autotuner/search_surface.py | 8 + test/test_config_api.py | 4 +- test/test_cute_flash_flex_walk.py | 2 +- test/test_cute_flash_kv_smem_config.py | 4 - test/test_cute_flash_length_invariance.py | 6 +- test/test_testing_helpers.py | 211 ++++++++++++++++++ 13 files changed, 324 insertions(+), 29 deletions(-) diff --git a/KNOWN_GAPS.md b/KNOWN_GAPS.md index 990cfb4094..216844005f 100644 --- a/KNOWN_GAPS.md +++ b/KNOWN_GAPS.md @@ -238,6 +238,44 @@ these labelled lines. test_chains_of_integer_extrema_of_negated_values_equal_eager` compares the covered chains with eager; a fix for a form above adds it there. +## tensor-descriptor-choices-use-the-current-gpu + +- Area: `ConfigSpec` load, store, atomic and prefetch indexing choices + for an explicitly targeted GPU, and the descriptor-dependent epilogue + choices. CuTe and Triton share this detection. +- What is wrong: With Triton's tensor-descriptor API installed, put an + SM80 A100 at the current ordinal and request an SM100 B200 at another + ordinal. In a fresh process, this reports an SM100 target but no + `tensor_descriptor` choice: + + ```python + spec = ConfigSpec(backend=CuteBackend(), device=torch.device("cuda:1"), + target_device_capability=(10, 0)) + print(spec.target_device_capability, spec.valid_indexing_types()) + ``` + + With simulated device properties, the result was `(10, 0)` and + `("pointer", "block_ptr")`. Reverse the two devices in another fresh + process and request `(8, 0)`: the SM80 spec incorrectly offers + `("pointer", "tensor_descriptor")`. Atomic and prefetch choices + follow the same wrong-device decision. The calculation caches one + answer based on `torch.cuda.current_device()`. Bound kernels already + pass the target's capability explicitly; direct CuTe specs can now + resolve it from their requested device, but share the same indexing + calculation. These are reproduced configuration results, not measured + kernel failures on mixed hardware. +- Since: Reproduced on upstream main at `f1d2bf392` with the explicit + capability used by a bound kernel, and on the direct-spec path after + requested-device capability resolution. +- Why deferred: A target-aware answer must agree across the search + space, descriptor lowering and epilogue validation, while preserving + Triton's installed API checks, ROCm/XPU behavior and saved configs. + Changing only the indexing menu can advertise a descriptor that a + later stage still rejects. End-to-end validation of both directions + requires devices on opposite sides of the SM90 boundary; the release + was qualified on homogeneous B200s. +- Pinned by: No test pins the incorrect indexing choices. + ## index-tensor-out-of-bounds - Area: compiled kernels, Triton and CuTe backends: a load or a store in a diff --git a/helion/_compat.py b/helion/_compat.py index 2d0be3c8c3..d1f9521527 100644 --- a/helion/_compat.py +++ b/helion/_compat.py @@ -447,20 +447,28 @@ def target_device_capability( if device is not None and device.type != "cuda": return None if device is not None and device.index is not None: - return _target_device_capability(device.index) - if not torch.cuda.is_available(): + index = device.index + else: + if not torch.cuda.is_available(): + return None + # Resolve the current device per call so set_device is not frozen. + index = torch.cuda.current_device() + try: + return _target_device_capability(index) + except _CudaUnavailable: return None - # device=None means the current device; resolve it per call so a later - # set_device is not frozen under one cache key. - return _target_device_capability(torch.cuda.current_device()) + + +class _CudaUnavailable(Exception): + """A transient cache miss before CUDA initialization.""" @functools.cache -def _target_device_capability(index: int) -> tuple[int, int] | None: - # Memoize per index (capability is fixed per device). Tests patch the - # public wrapper above, mirroring is_hip / _is_hip. +def _target_device_capability(index: int) -> tuple[int, int]: + # An NVML availability check can change before CUDA initializes; only + # successful device properties belong in the per-ordinal cache. if not torch.cuda.is_available(): - return None + raise _CudaUnavailable return torch.cuda.get_device_capability(index) diff --git a/helion/_compiler/cute/autotune/search_surface.py b/helion/_compiler/cute/autotune/search_surface.py index 5068513c4a..679786ba54 100644 --- a/helion/_compiler/cute/autotune/search_surface.py +++ b/helion/_compiler/cute/autotune/search_surface.py @@ -19,7 +19,7 @@ import torch -from ...._compat import target_device_capability as get_target_device_capability +from .... import _compat from ...._utils import next_power_of_2 from ...._utils import prev_power_of_2 from ...._utils import widest_halvable @@ -5851,7 +5851,31 @@ def eviction_policy_search_choices( def default_target_device_capability(self) -> tuple[int, int] | None: # Direct CuTe specs use the current CUDA device so validation still # enforces the arch gates. - return get_target_device_capability() + return _compat.target_device_capability() + + def default_target_device_capability_for( + self, device: torch.device + ) -> tuple[int, int] | None: + # A specialization may supply its own target instead of a hardware + # query. Its existing no-argument override remains authoritative. + legacy = self.default_target_device_capability + if getattr(legacy, "__func__", None) is not _BUILTIN_CURRENT_CAPABILITY: + return legacy() + try: + return _compat.target_device_capability(device) + except AssertionError as error: + # Torch's get_device_properties rejects a missing visible ordinal + # with this assertion. A real driver/initialization error must + # still reach the caller. Successful (cached) queries do no extra + # device discovery, and the failed query cannot populate the cache. + if ( + device.type == "cuda" + and device.index is not None + and error.args == ("Invalid device id",) + and device.index >= torch.cuda.device_count() + ): + return None + raise def fields( self, config_spec: ConfigSpec, *, flash_pipeline_family: str | None = None @@ -6032,4 +6056,5 @@ def config_generation_extension( return CuteConfigGenerationExtension(generation) +_BUILTIN_CURRENT_CAPABILITY = CuteSearchSurface.default_target_device_capability CUTE_SEARCH_SURFACE = CuteSearchSurface() diff --git a/helion/_compiler/cute/target_facts.py b/helion/_compiler/cute/target_facts.py index 2c7641cb5d..227068dd24 100644 --- a/helion/_compiler/cute/target_facts.py +++ b/helion/_compiler/cute/target_facts.py @@ -1,9 +1,11 @@ """Target facts: the device model behind the CuTe planners' budget probes (analysis). The facts about the compile target are answered by probes: -``helion._compat.target_device_capability`` (also bound by name in -``helion.runtime.kernel`` and ``helion._compiler.compile_environment``; -``patch_target_facts`` patches all three), ``helion.runtime.get_num_sm``, +``helion._compat.target_device_capability`` (read through its module by the +CuTe search surface, and also bound by name in ``helion.runtime.kernel`` and +``helion._compiler.compile_environment``; ``patch_target_facts`` patches all +three), ``helion.runtime.get_num_sm`` and +the direct configuration probe ``helion.autotuner.config_spec.device_num_sm``, ``cute.tcgen05.search_plan._cuda_num_sms_or_zero`` (the wave-quantization gate's raw SM count), the per-CTA SMEM probes of this module (:func:`per_cta_smem_capacity_bytes` and the two budgets derived from it), diff --git a/helion/_testing/__init__.py b/helion/_testing/__init__.py index fc2cf81eef..41af0eb100 100644 --- a/helion/_testing/__init__.py +++ b/helion/_testing/__init__.py @@ -678,10 +678,11 @@ def patch_target_facts( dotted path fixtures patched by hand before this helper existed, so the values a fixture pins are unchanged: - * ``capability`` -> ``helion._compat.target_device_capability`` and its - by-name bindings ``helion.runtime.kernel.target_device_capability`` and - ``helion._compiler.compile_environment.target_device_capability`` - * ``num_sm`` -> ``helion.runtime.get_num_sm`` + * ``capability`` -> ``helion._compat.target_device_capability``, which the + CuTe search surface reads through its module, and the two bindings + imported by the kernel runtime and compile environment + * ``num_sm`` -> ``helion.runtime.get_num_sm`` and the direct constructor + probe ``helion.autotuner.config_spec.device_num_sm`` * ``matmul_num_sm`` -> ``helion._compiler.cute.tcgen05.search_plan._cuda_num_sms_or_zero`` * ``smem_capacity_bytes`` / ``smem_budget_bytes`` -> ``helion._compiler.cute.target_facts.per_cta_smem_capacity_bytes`` / @@ -736,7 +737,10 @@ def pick(value: object, modelled: object) -> object: "helion.runtime.kernel.target_device_capability", "helion._compiler.compile_environment.target_device_capability", ), - "num_sm": ("helion.runtime.get_num_sm",), + "num_sm": ( + "helion.autotuner.config_spec.device_num_sm", + "helion.runtime.get_num_sm", + ), "matmul_num_sm": ( "helion._compiler.cute.tcgen05.search_plan._cuda_num_sms_or_zero", ), diff --git a/helion/_testing/cute_codegen.py b/helion/_testing/cute_codegen.py index 6f125019fe..4a656038cf 100644 --- a/helion/_testing/cute_codegen.py +++ b/helion/_testing/cute_codegen.py @@ -244,6 +244,7 @@ def mock_cuda_unavailable() -> Generator[None, None, None]: side_effect=require_cute_codegen, ), patch("torch.cuda.is_available", return_value=False), + patch("helion._compat._target_device_capability", return_value=None), patch("helion._compat._supports_maxnreg", return_value=False), patch("helion._compat._supports_tensor_descriptor", return_value=False), patch("helion._compat._is_hip", return_value=False), diff --git a/helion/autotuner/config_spec.py b/helion/autotuner/config_spec.py index 0caf0235f1..c79d3ec167 100644 --- a/helion/autotuner/config_spec.py +++ b/helion/autotuner/config_spec.py @@ -1224,6 +1224,8 @@ def __init__( if target_device_capability is _TARGET_DEVICE_CAPABILITY_UNSET: self.target_device_capability: tuple[int, int] | None = ( self.search_surface.default_target_device_capability() + if device is None + else self.search_surface.default_target_device_capability_for(device) ) else: self.target_device_capability = cast( diff --git a/helion/autotuner/search_surface.py b/helion/autotuner/search_surface.py index 557ddc0287..b9b3011e2f 100644 --- a/helion/autotuner/search_surface.py +++ b/helion/autotuner/search_surface.py @@ -47,6 +47,8 @@ from collections.abc import Mapping from collections.abc import Sequence + import torch + from ..runtime.config import Config from .block_id_sequence import BlockIdSequence from .config_fragment import ConfigSpecFragment @@ -95,6 +97,12 @@ def default_target_device_capability(self) -> tuple[int, int] | None: """The capability a spec built without one validates against.""" return None + def default_target_device_capability_for( + self, device: torch.device + ) -> tuple[int, int] | None: + """Resolve an explicit device, preserving existing no-argument hooks.""" + return self.default_target_device_capability() + def fields( self, config_spec: ConfigSpec, *, flash_pipeline_family: str | None = None ) -> dict[str, BlockIdSequence[Any] | ConfigSpecFragment] | None: diff --git a/test/test_config_api.py b/test/test_config_api.py index cf87ad8282..d60e22de32 100644 --- a/test/test_config_api.py +++ b/test/test_config_api.py @@ -3675,10 +3675,10 @@ def test_direct_cute_config_spec_enforces_clc_arch_gate(self) -> None: patch("helion._compat._supports_tensor_descriptor", return_value=True), # Patch the helion seam: torch.cuda.get_device_capability is # memoized behind _target_device_capability (is_hip / _is_hip - # pattern), so config_spec's get_target_device_capability() must + # pattern), so the CuTe search surface's capability must # be patched at the wrapper, not the cached torch query. patch( - "helion._compiler.cute.autotune.search_surface.get_target_device_capability", + "helion._compat.target_device_capability", return_value=(9, 0), ), ): diff --git a/test/test_cute_flash_flex_walk.py b/test/test_cute_flash_flex_walk.py index 105e471477..63d757d6ac 100644 --- a/test/test_cute_flash_flex_walk.py +++ b/test/test_cute_flash_flex_walk.py @@ -828,7 +828,7 @@ def test_flex_coverage_design_covers_the_cooperative_widths() -> None: with ( patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": ""}, clear=True), patch( - "helion._compiler.cute.autotune.search_surface.get_target_device_capability", + "helion._compat.target_device_capability", return_value=(10, 0), ), ): diff --git a/test/test_cute_flash_kv_smem_config.py b/test/test_cute_flash_kv_smem_config.py index 65af511fc7..42332b3c61 100644 --- a/test/test_cute_flash_kv_smem_config.py +++ b/test/test_cute_flash_kv_smem_config.py @@ -46,10 +46,6 @@ def _cpu_only() -> Iterator[None]: with ( cpu_render_target(capability=(10, 3)), patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": ""}, clear=True), - patch( - "helion._compiler.cute.autotune.search_surface.get_target_device_capability", - return_value=(10, 3), - ), ): yield diff --git a/test/test_cute_flash_length_invariance.py b/test/test_cute_flash_length_invariance.py index dca1ffeaa9..59de1632c7 100644 --- a/test/test_cute_flash_length_invariance.py +++ b/test/test_cute_flash_length_invariance.py @@ -1854,7 +1854,7 @@ def test_ws_legacy_kv_stage_is_canonicalized_before_fixed_config_validation( ) -> None: with ( patch( - "helion._compiler.cute.autotune.search_surface.get_target_device_capability", + "helion._compat.target_device_capability", return_value=(10, 0), ), patch( @@ -2215,7 +2215,7 @@ def test_ws_structural_generation_is_bounded_and_complete( ) -> None: with ( patch( - "helion._compiler.cute.autotune.search_surface.get_target_device_capability", + "helion._compat.target_device_capability", return_value=(10, 0), ), patch( @@ -3638,7 +3638,7 @@ def test_unsafe_cga2_local_stage_local_softmax_canonicalizes(num_kv: int) -> Non with ( patch( - "helion._compiler.cute.autotune.search_surface.get_target_device_capability", + "helion._compat.target_device_capability", return_value=(10, 0), ), patch( diff --git a/test/test_testing_helpers.py b/test/test_testing_helpers.py index 78cdd9a67f..b9fdc2739e 100644 --- a/test/test_testing_helpers.py +++ b/test/test_testing_helpers.py @@ -3,6 +3,7 @@ from __future__ import annotations import dataclasses +import functools import itertools import json from pathlib import Path @@ -10,6 +11,7 @@ import shutil import sys import textwrap +from types import SimpleNamespace from unittest.mock import patch import pytest @@ -18,6 +20,8 @@ import helion from helion import _compat from helion import _hardware +from helion._compiler.cute.autotune.search_surface import CuteSearchSurface +from helion._compiler.cute.backend import CuteBackend from helion._compiler.cute.target_facts import B200 from helion._testing import cpu_render_target from helion._testing import import_path @@ -27,18 +31,225 @@ from helion._testing import sharding from helion._testing.cute_codegen import CpuRefMode from helion._testing.cute_codegen import cpu_bind +from helion._testing.cute_codegen import mock_cuda_unavailable from helion._testing.cute_codegen import tcgen05_target from helion._testing.sharding import MIN_WEIGHT from helion._testing.sharding import assign_shards from helion._testing.sharding import load_durations from helion._testing.sharding import shard_loads +from helion.autotuner import config_spec from helion.autotuner.base_search import BaseSearch +from helion.autotuner.config_spec import ConfigSpec from helion.autotuner.local_cache import LocalAutotuneCache +from helion.autotuner.search_surface import BackendSearchSurface import helion.language as hl pytestmark = pytest.mark.cpu_only +@onlyBackends(["cute"]) +def test_direct_cute_config_uses_the_scoped_target() -> None: + probe = _compat.target_device_capability + sm_probe = config_spec.device_num_sm + with ( + patch.object(_compat, "target_device_capability", return_value=(9, 0)), + patch.object(config_spec, "device_num_sm", return_value=120), + ): + with cpu_render_target(capability=(10, 3), num_sm=148): + outer = ConfigSpec(backend=CuteBackend()) + assert (outer.target_device_capability, outer.num_sm) == ((10, 3), 148) + with patch_target_facts(capability=None, num_sm=17): + inner = ConfigSpec(backend=CuteBackend()) + assert (inner.target_device_capability, inner.num_sm) == (None, 17) + restored = ConfigSpec(backend=CuteBackend()) + assert (restored.target_device_capability, restored.num_sm) == ( + (10, 3), + 148, + ) + external = ConfigSpec(backend=CuteBackend()) + assert (external.target_device_capability, external.num_sm) == ((9, 0), 120) + assert _compat.target_device_capability is probe + assert config_spec.device_num_sm is sm_probe + + +@onlyBackends(["cute"]) +def test_direct_config_uses_its_device_for_an_implicit_capability() -> None: + b200 = torch.device("cuda:1") + with ( + patch.object( + _compat, + "target_device_capability", + side_effect=lambda device=None: (10, 0) if device == b200 else (9, 0), + ) as probe, + patch.object( + config_spec, + "device_num_sm", + side_effect=lambda device: 148 if device == b200 else 120, + ), + ): + backend = CuteBackend() + current = ConfigSpec(backend=backend) + requested = ConfigSpec(backend=backend, device=b200) + assert (current.target_device_capability, current.num_sm) == ((9, 0), 120) + assert (requested.target_device_capability, requested.num_sm) == ((10, 0), 148) + probe.reset_mock() + unknown = ConfigSpec( + backend=backend, device=b200, target_device_capability=None + ) + explicit = ConfigSpec( + backend=backend, device=b200, target_device_capability=(8, 0) + ) + assert (unknown.target_device_capability, unknown.num_sm) == (None, 148) + assert explicit.target_device_capability == (8, 0) + probe.assert_not_called() + + +@onlyBackends(["cute"]) +def test_unavailable_cuda_skips_cold_and_warm_indexed_capability_caches() -> None: + # A fresh instance of the actual indexed cache leaves other tests' state + # alone and makes the cold-to-warm transition deterministic. + cached = functools.cache(_compat._target_device_capability.__wrapped__) + device = torch.device("cuda:0") + backend = CuteBackend() + with ( + patch.object(_compat, "_target_device_capability", cached), + patch.object(torch.cuda, "is_available", return_value=True), + patch.object( + torch.cuda, "get_device_capability", return_value=(10, 0) + ) as hardware, + ): + for start_size in (0, 1): + before = cached.cache_info() + assert before.currsize == start_size + with mock_cuda_unavailable(): + direct = ConfigSpec(backend=backend, device=device, num_sm=148) + assert direct.target_device_capability is None + assert cached.cache_info() == before + assert _compat.target_device_capability(device) == (10, 0) + hardware.assert_called_once_with(0) + + # Explicit test models are above the raw cache, so an outer model + # remains effective inside the CUDA-denied renderer. + with patch_target_facts(capability=(9, 0)), mock_cuda_unavailable(): + assert ConfigSpec( + backend=backend, device=device + ).target_device_capability == (9, 0) + + +def test_indexed_capability_retries_after_cuda_becomes_visible() -> None: + cached = functools.cache(_compat._target_device_capability.__wrapped__) + device = torch.device("cuda:0") + with ( + patch.object(_compat, "_target_device_capability", cached), + patch.object(torch.cuda, "is_available", return_value=False) as visible, + patch.object(torch.cuda, "get_device_capability", return_value=(10, 0)) as read, + ): + assert _compat.target_device_capability(device) is None + assert cached.cache_info().currsize == 0 + read.assert_not_called() + + visible.return_value = True + assert _compat.target_device_capability(device) == (10, 0) + visible.reset_mock() + assert _compat.target_device_capability(device) == (10, 0) + visible.assert_not_called() + read.assert_called_once_with(0) + assert cached.cache_info().hits == 1 + + +@onlyBackends(["cute"]) +def test_direct_config_handles_only_an_unavailable_cuda_ordinal() -> None: + # Exercise Torch's actual get_device_capability -> get_device_properties + # validation with one visible ordinal; only device discovery is simulated. + cached = functools.cache(_compat._target_device_capability.__wrapped__) + backend = CuteBackend() + device = torch.device("cuda:1") + with ( + mock_cuda_unavailable(), + patch.object(torch.cuda, "current_device", return_value=0), + patch.object(_compat, "_target_device_capability", cached), + patch.object(torch.cuda, "is_available", return_value=True), + patch.object(config_spec, "get_num_xcd", return_value=1), + patch.object(torch.cuda, "_lazy_init"), + patch.object(torch.cuda, "device_count", return_value=1) as count, + patch.object( + torch.cuda, + "_get_device_properties", + create=True, + return_value=SimpleNamespace(major=10, minor=0), + ) as properties, + ): + + def capability() -> tuple[int, int] | None: + return ConfigSpec( + backend=backend, device=device, num_sm=1 + ).target_device_capability + + assert capability() is None + assert cached.cache_info().currsize == 0 + properties.assert_not_called() + with patch_target_facts(capability=(9, 0)): + assert capability() == (9, 0) + assert ConfigSpec( + backend=backend, device=device, num_sm=1, target_device_capability=(8, 0) + ).target_device_capability == (8, 0) + + count.return_value = 2 + assert capability() == (10, 0) + before = count.call_count + assert capability() == (10, 0) + assert count.call_count == before + properties.assert_called_once_with(1) + + for available, error in ( + (1, AssertionError("unrelated assertion")), + (2, AssertionError("Invalid device id")), + (1, RuntimeError("driver failed")), + ): + count.return_value = available + with ( + patch.object( + _compat, + "target_device_capability", + side_effect=error, + ), + pytest.raises(type(error), match=str(error)), + ): + capability() + + +@onlyBackends(["cute"]) +def test_direct_config_keeps_legacy_capability_hook() -> None: + class PluginSurface(BackendSearchSurface): + def default_target_device_capability(self) -> tuple[int, int]: + return (7, 0) + + class SpecializedSurface(CuteSearchSurface): + def default_target_device_capability(self) -> tuple[int, int]: + return (8, 0) + + backend = CuteBackend() + with patch_target_facts(capability=(10, 0), num_sm=148): + for surface, expected in ( + (PluginSurface(), (7, 0)), + (SpecializedSurface(), (8, 0)), + ): + with patch.object(backend, "config_spec_extension", return_value=surface): + assert ConfigSpec(backend=backend).target_device_capability == expected + assert ( + ConfigSpec( + backend=backend, device=torch.device("cuda:1") + ).target_device_capability + == expected + ) + with patch.object( + CuteSearchSurface, "default_target_device_capability", lambda self: (8, 9) + ): + assert ConfigSpec( + backend=backend, device=torch.device("cuda:1") + ).target_device_capability == (8, 9) + + @onlyBackends(["triton", "cute"]) def test_cpu_render_target_constructs_cache_without_host_cuda_runtime(monkeypatch): @helion.kernel() From 4d9086baa7ae0e5470629f909953be9bba6bae7c Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Thu, 26 Nov 2026 00:36:45 -0800 Subject: [PATCH 2/5] [scripts] Tell Claude to place the review verdict before its confirmation A resumed review twice returned its unique completion marker followed by LGTM. The reviewer had been told that both the verdict and the transport marker must be the last line. Spell out which belongs to the review text and which finishes the entire message. Keep the result parser and its confirmation check unchanged; previously rejected reviews remain unconfirmed. Testing: scripts/run_tests.py --backend triton --lane cpu --slow test/test_autoreview.py passed all 157 cases, including a verdict after the marker that must remain unconfirmed. Strict lint and Pyrefly passed. No GPU needed. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4751, branch: choijon5/helion-b200/shared/3 --- scripts/autoreview.py | 9 ++++++--- test/test_autoreview.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/scripts/autoreview.py b/scripts/autoreview.py index 4c0ec0d742..08ee9dc7ef 100755 --- a/scripts/autoreview.py +++ b/scripts/autoreview.py @@ -1373,9 +1373,12 @@ def send( "format above): keep tool work in the foreground and wait for its " "results before completing this request. Do not end the turn with " "progress text or a promise to report later. When the requested " - "review, combination, or fix is complete, append the following " - "exact line after the substantive response (also after an ERROR " - "response). Never append it to an interim update.\n" + "review, combination, or fix is complete, finish its text first. " + "The last-line rules above apply to that text: on a passing " + "review, LGTM comes BEFORE the completion line. Then write the " + "exact line below as the final line of the entire message, also " + "after findings or an ERROR. Nothing follows it. Never append it " + "to an interim update.\n" f"{completion}" ) # Allow an explicitly long tool command within the send budget. Keep diff --git a/test/test_autoreview.py b/test/test_autoreview.py index 9296b16306..f09d880717 100644 --- a/test/test_autoreview.py +++ b/test/test_autoreview.py @@ -554,6 +554,7 @@ def forbidden_process(*args, **kwargs): for index, (cmd, kwargs) in enumerate(calls): prompt = cmd[cmd.index("-p") + 1] assert prompt.startswith(prompts[index] + "\n\n") + assert "LGTM comes BEFORE the completion line" in prompt assert cmd == [ "claude", *(["--dangerously-enable-internet-mode"] if meta else []), @@ -785,6 +786,19 @@ def test_followup_cannot_reuse_previous_completion(review, monkeypatch, tmp_path assert not (log_dir / "combined-review.txt").exists() +@pytest.mark.slow +def test_verdict_after_the_completion_line_is_unconfirmed(review, monkeypatch): + # A resumed reviewer once followed the two "last line" instructions in + # reverse order. A passing verdict cannot confirm an unfinished response. + monkeypatch.setenv( + "FAKE_CLAUDE_PAYLOAD", + json.dumps({"result": "\n\nLGTM", "session_id": "s1"}), + ) + code, out, err = review("claude") + assert code == 2 and not out.strip() + assert "did not confirm completion" in err and "autoreview passed:" not in err + + @pytest.mark.slow def test_incomplete_fix_warns_that_edits_may_be_present(review, monkeypatch, tmp_path): monkeypatch.setenv( From 7824295795f258314a6d138755095866600a6aa3 Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Thu, 26 Nov 2026 01:34:04 -0800 Subject: [PATCH 3/5] [testing] Exercise trace-window resizing with deterministic timestamps The kernel timer resizes a short profiling window using the first trace's observed call period. A second window can still end before warmup if calls arrive much faster. In the full Triton lane, both 15- and 113-call traces parsed, but neither settled; the timer correctly returned infinity. A test using CUDA sleeps and a wall-time threshold assumed it would always obtain a reading. Use the existing simulated device events to exercise the same timer, flush learning, trace parsing and resize logic. Check that the second window is larger and returns just the candidate's 7 us when calls settle, and that it reports an unreadable window when they do not. Neighboring tests still exercise real CUPTI traces and public do_bench. No timer behavior or production timeout changes. Testing: scripts/run_tests.py --backend triton,cute --lane cpu test/test_benchmarking_batched_replay.py (10 passed on each backend); strict scoped lint passed. No GPU required for this change. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4752, branch: choijon5/helion-b200/shared/4 --- test/test_benchmarking_batched_replay.py | 55 ++++++++++++++++-------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/test/test_benchmarking_batched_replay.py b/test/test_benchmarking_batched_replay.py index cffe66981b..102016bb5f 100644 --- a/test/test_benchmarking_batched_replay.py +++ b/test/test_benchmarking_batched_replay.py @@ -15,6 +15,7 @@ from helion._dist_utils import all_ranks_agree from helion._testing import DEVICE from helion._testing import skipIfRocm +from helion._testing.benchmark_timers import stand_in_trace from helion._testing.benchmark_timers import trace_test from helion.autotuner import benchmark_job from helion.autotuner import benchmarking @@ -603,29 +604,49 @@ def backward_call() -> None: assert traced_windows == [3] -@trace_test +@pytest.mark.cpu_only +@pytest.mark.parametrize( + ("first_flush_ns", "next_flush_ns", "expected_ms"), + [(8_000, 8_000, 0.007), (65_000, 12_000, math.inf)], + ids=["stable-period", "faster-second-window"], +) def test_kernel_timer_resizes_a_window_whose_estimate_ran_long( + monkeypatch, traced_windows, + caplog, + first_flush_ns: int, + next_flush_ns: int, + expected_ms: float, ) -> None: - """The windows are sized by an estimate; when the calls then run far - shorter (here: the estimate's calls sleep), the first session settles - too few calls past the traced warmup, and a second one sized by the - traced call period times them.""" - a = torch.randn(64, 64, device=DEVICE) - calls = [0] - - def call() -> None: - calls[0] += 1 - # the setup call and the estimate - if calls[0] <= 1 + benchmarking._KERNEL_TIMER_ESTIMATE_CALLS: - torch.cuda._sleep(5_000_000) - torch.mm(a, a) + """Resize from the first trace's period. Even the longer second window + can end before warmup if its calls arrive much faster.""" + trace = stand_in_trace(monkeypatch) + # The estimate times five calls at 1 ms total; both first traces are + # faster. No fixed retry size fits both cases: at 15 us/call it takes + # over 130 calls to settle, whereas at 19 us/call 110 calls suffice. + first_flush = trace.launch("flush", first_flush_ns) + next_flush = trace.launch("flush", next_flush_ns) + + def flush() -> None: + # Learning, estimation and the first window use first_flush; only + # the retry sees a window already recorded. + (next_flush if traced_windows else first_flush)() - reading = benchmarking.do_bench(call, warmup=20, rep=20, l2_flush_mode="kernel") - assert reading < 1.0 # milliseconds: no sleeping call is timed - # a second, longer session sized by the traced call period + with caplog.at_level(logging.WARNING, logger=benchmarking.__name__): + reading = benchmarking._do_bench_kernel_durations( + trace.launch("candidate", 7_000), + flush, + trace.device, + warmup=2, + rep=2, + quantiles=None, + return_mode="median", + fixed_repetitions=None, + ) assert len(traced_windows) == 2 assert traced_windows[1] > traced_windows[0] + assert reading == pytest.approx(expected_ms) + assert ("traced no settled call" in caplog.text) == math.isinf(expected_ms) @trace_test From 4730f353c3935cd401fc1fbfa7d65134d7deff0d Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Thu, 26 Nov 2026 01:38:03 -0800 Subject: [PATCH 4/5] [testing] Split grouped MN source renders across bounded CPU test items The grouped seed test renders 120 or 140 complete CuTe programs in a single pytest item for each input shape. Under concurrent CPU suites one item lost its worker at the 180-second timeout, then passed alone in 71s. Keep the existing three IDs for the seed-prefix, default, normalization and geometry checks. Render the same first representative of each worklist geometry and L2 swizzle in eight disjoint slices per shape. The module-scoped fixture shares bindings on each worker without keeping the target mocks active between tests; its yield keeps the original input tensors alive during rendering. No scheduling code, timeout or MN test tier changes. Keep the shared offset and negative K-loop kernels and their argument and config builders in helion._testing. Place the eight K-loop refusal cases and the full P2 source journal in a CPU-only module. Preserve the three original modules' GPU coverage and the P2 journal payload verbatim. P2 still skips an incomplete CuTe SDK. Testing: the CuTe CPU lane passed 141 cases, including all 400 renders and all nine relocated source checks with CUDA hidden. The Triton CPU seed module passed 26 with one skip. Compared with main, 79 of the original 88 GPU-lane test IDs remain; the other nine now run on CPU. All eight original journal entries were unchanged. An independent inventory matched the 400 normalized render arguments (140, 140, 120) and checked the input weakrefs after collection and at each render. On the complete SDK the nine moved tests passed again, and P2 correctly skipped a simulated installation without cutlass.cute. Strict lint and Pyrefly passed. No GPU was allocated. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4753, branch: choijon5/helion-b200/shared/5 --- helion/_testing/cute_grouped_gemm.py | 136 +++++++ test/test_compiler_seed_overflow.py | 2 +- test/test_cute_grouped_ab_k.py | 81 +--- test/test_cute_grouped_balanced_workers.py | 6 +- test/test_cute_grouped_d_shift.py | 44 +- test/test_cute_grouped_large_device_seeds.py | 28 +- test/test_cute_grouped_mn_224.py | 2 +- test/test_cute_grouped_mn_device_seeds.py | 131 ++++-- ..._cute_grouped_prefix_adaptive_n_codegen.py | 2 +- test/test_cute_grouped_prefix_m256_codegen.py | 2 +- ...ute_grouped_worklist_codegen.expected_cute | 384 ++++++++++++++++++ test/test_cute_grouped_worklist_codegen.py | 86 ++++ ...e_role_local_grouped_renders.expected_cute | 382 ----------------- test/test_cute_role_local_grouped_renders.py | 43 +- 14 files changed, 709 insertions(+), 620 deletions(-) create mode 100644 helion/_testing/cute_grouped_gemm.py create mode 100644 test/test_cute_grouped_worklist_codegen.expected_cute create mode 100644 test/test_cute_grouped_worklist_codegen.py diff --git a/helion/_testing/cute_grouped_gemm.py b/helion/_testing/cute_grouped_gemm.py new file mode 100644 index 0000000000..e4b2eb6176 --- /dev/null +++ b/helion/_testing/cute_grouped_gemm.py @@ -0,0 +1,136 @@ +"""Shared CuTe kernels for grouped GEMM seed and code generation tests.""" + +from __future__ import annotations + +import torch + +import helion +import helion.language as hl + + +@helion.kernel(backend="cute", static_shapes=True, autotune_effort="none") +def _grouped_offsets_k64( + a: torch.Tensor, weights: torch.Tensor, offsets: torch.Tensor +) -> torch.Tensor: + rows, reduction = a.shape + groups, columns, _ = weights.shape + block_m = hl.register_block_size(256) + block_n = hl.register_block_size(128) + block_k = hl.register_block_size(64) + out = torch.empty((rows, columns), device=a.device, dtype=a.dtype) + for group_tile, row_tile, column_tile in hl.tile( + [groups, rows, columns], block_size=[1, block_m, block_n] + ): + group = group_tile.index.sum() + start = offsets[group] + extent = offsets[group + 1] - offsets[group] + row_indices = start + row_tile.index + valid = row_tile.index < extent + acc = hl.zeros([row_tile, column_tile], dtype=torch.float32) + for inner in hl.tile(reduction, block_size=block_k): + left = hl.load(a, [row_indices, inner], extra_mask=valid[:, None]) + acc = torch.addmm(acc, left, weights[group, column_tile, inner].T) + hl.store(out, [row_indices, column_tile], acc, extra_mask=valid[:, None]) + return out + + +@helion.kernel(backend="cute", static_shapes=True, autotune_effort="none") +def _unsupported_k_loop( + a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor, variant: int +) -> torch.Tensor: + hl.specialize(variant) + m, k = a.shape + groups, n, _ = b.shape + block_m = hl.register_block_size(256) + block_n = hl.register_block_size(128) + block_k = hl.register_block_size(64) + out = torch.empty((m, n), dtype=torch.float32, device=a.device) + for group_tile, rows, columns in hl.tile( + [groups, m, n], block_size=[1, block_m, block_n] + ): + group = group_tile.index.sum() + start = offsets[group] + length = offsets[group + 1] - offsets[group] + row_index = start + rows.index + valid = rows.index < length + acc = hl.full( + [rows, columns], 1.0 if variant == 1 else 0.0, dtype=torch.float32 + ) + begin = 64 if variant == 2 else 0 + for inner in hl.tile(begin, k, block_size=block_k): + left = hl.load(a, [row_index, inner], extra_mask=valid[:, None]) + if variant == 3: + left = left * 1.0 + acc = torch.addmm( + acc, + left, + b[group, columns, inner].T, + alpha=2 if variant == 4 else 1, + ) + if variant == 5: + acc = acc * 1.0 + hl.store(out, [row_index, columns], acc, extra_mask=valid[:, None]) + return out + + +def grouped_ab_k_args( + *, + m: int = 640, + k: int = 256, + n: int = 256, + dtype: torch.dtype = torch.bfloat16, + offset_dtype: torch.dtype = torch.int32, +) -> tuple[torch.Tensor, ...]: + return ( + torch.empty((m, k), dtype=dtype), + torch.empty((4, n, k), dtype=dtype), + torch.tensor([0, 0, 1, 129, m], dtype=offset_dtype), + ) + + +def grouped_ab_k_config(cluster_m: int, *, stages: int = 2) -> helion.Config: + return helion.Config( + block_sizes=[256, 128, 64], + pid_type="persistent_interleaved", + tcgen05_cluster_m=cluster_m, + tcgen05_cluster_n=1, + tcgen05_ab_stages=stages, + tcgen05_acc_stages=2, + tcgen05_c_stages=2, + tcgen05_num_epi_warps=4, + tcgen05_grouped_mode="worklist_nm", + tcgen05_grouped_worklist_source_m_tile=128, + tcgen05_grouped_ab_tile_k=128, + ) + + +def grouped_d_shift_args(kind: str, dtype: torch.dtype) -> tuple[torch.Tensor, ...]: + metadata = ( + [0, 1, 128, 128, 128, 128, 126, 1] + if kind == "sizes" + else [0, 0, 1, 129, 257, 385, 513, 639, 640] + ) + return ( + torch.empty((640, 256), dtype=torch.bfloat16), + torch.empty((8, 512, 256), dtype=torch.bfloat16), + torch.tensor(metadata, dtype=dtype), + ) + + +def grouped_d_shift_config(orientation: str, *, cluster_n: int = 1) -> helion.Config: + return helion.Config( + block_sizes=[256, 128, 64], + pid_type="persistent_interleaved", + tcgen05_cluster_m=2, + tcgen05_cluster_n=cluster_n, + tcgen05_ab_stages=2, + tcgen05_acc_stages=2, + tcgen05_c_stages=2, + tcgen05_num_epi_warps=4, + tcgen05_grouped_mode="worklist_nm", + tcgen05_grouped_worklist_orientation=orientation, + tcgen05_grouped_worklist_mma_n=256, + tcgen05_grouped_worklist_source_m_tile=128, + tcgen05_grouped_full_allocation_a=True, + tcgen05_grouped_d_shift=True, + ) diff --git a/test/test_compiler_seed_overflow.py b/test/test_compiler_seed_overflow.py index df20d0bcef..38e996584b 100644 --- a/test/test_compiler_seed_overflow.py +++ b/test/test_compiler_seed_overflow.py @@ -11,11 +11,11 @@ from .test_compiler_coverage import DOMAINS from .test_compiler_coverage import make_search from .test_compiler_coverage import make_spec -from .test_cute_grouped_ab_k import _unsupported_k_loop from helion._testing import skipUnlessBackends from helion._testing.cute_codegen import cpu_bind from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable +from helion._testing.cute_grouped_gemm import _unsupported_k_loop from helion.autotuner.pattern_search import InitialPopulationStrategy from helion.autotuner.pattern_search import PatternSearch from helion.autotuner.surrogate_pattern_search import LFBOPatternSearch diff --git a/test/test_cute_grouped_ab_k.py b/test/test_cute_grouped_ab_k.py index d669ca3e15..58260d3cd4 100644 --- a/test/test_cute_grouped_ab_k.py +++ b/test/test_cute_grouped_ab_k.py @@ -24,6 +24,8 @@ from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable from helion._testing.cute_codegen import require_cute_codegen +from helion._testing.cute_grouped_gemm import grouped_ab_k_args as _args +from helion._testing.cute_grouped_gemm import grouped_ab_k_config as _config from helion.autotuner.effort_profile import get_effort_profile from helion.autotuner.surrogate_pattern_search import LFBOTreeSearch from helion.exc import BackendUnsupported @@ -63,76 +65,6 @@ def _observed_logical_k( return out, block_k -@helion.kernel(backend="cute", static_shapes=True, autotune_effort="none") -def _unsupported_k_loop( - a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor, variant: int -) -> torch.Tensor: - hl.specialize(variant) - m, k = a.shape - groups, n, _ = b.shape - block_m = hl.register_block_size(256) - block_n = hl.register_block_size(128) - block_k = hl.register_block_size(64) - out = torch.empty((m, n), dtype=torch.float32, device=a.device) - for group_tile, rows, columns in hl.tile( - [groups, m, n], block_size=[1, block_m, block_n] - ): - group = group_tile.index.sum() - start = offsets[group] - length = offsets[group + 1] - offsets[group] - row_index = start + rows.index - valid = rows.index < length - acc = hl.full( - [rows, columns], 1.0 if variant == 1 else 0.0, dtype=torch.float32 - ) - begin = 64 if variant == 2 else 0 - for inner in hl.tile(begin, k, block_size=block_k): - left = hl.load(a, [row_index, inner], extra_mask=valid[:, None]) - if variant == 3: - left = left * 1.0 - acc = torch.addmm( - acc, - left, - b[group, columns, inner].T, - alpha=2 if variant == 4 else 1, - ) - if variant == 5: - acc = acc * 1.0 - hl.store(out, [row_index, columns], acc, extra_mask=valid[:, None]) - return out - - -def _args( - *, - m: int = 640, - k: int = 256, - n: int = 256, - dtype: torch.dtype = torch.bfloat16, - offset_dtype: torch.dtype = torch.int32, -) -> tuple[torch.Tensor, ...]: - return ( - torch.empty((m, k), dtype=dtype), - torch.empty((4, n, k), dtype=dtype), - torch.tensor([0, 0, 1, 129, m], dtype=offset_dtype), - ) - - -def _config(cluster_m: int, *, stages: int = 2) -> helion.Config: - return helion.Config( - block_sizes=[256, 128, 64], - pid_type="persistent_interleaved", - tcgen05_cluster_m=cluster_m, - tcgen05_cluster_n=1, - tcgen05_ab_stages=stages, - tcgen05_acc_stages=2, - tcgen05_c_stages=2, - tcgen05_num_epi_warps=4, - tcgen05_grouped_mode="worklist_nm", - tcgen05_grouped_worklist_source_m_tile=128, - tcgen05_grouped_ab_tile_k=128, - ) - - def _plans(source: str) -> list[dict[str, object]]: return next( ast.literal_eval(node.value) @@ -237,15 +169,6 @@ def reference() -> torch.Tensor: torch.testing.assert_close(captured, reference(), rtol=1e-3, atol=1e-3) -@pytest.mark.parametrize("variant", [1, 2, 3, 5]) -def test_noncanonical_k_loops_cannot_request_physical128(variant: int) -> None: - with forbid_cuda_work(), _target(), mock_cuda_unavailable(): - bound = cpu_bind(_unsupported_k_loop, (*_args(), variant)) - assert not bound.config_spec._cute_tcgen05_config.grouped_ab_k_fusion_supported - with pytest.raises((InvalidConfig, BackendUnsupported)): - bound.to_code(_config(2)) - - @pytest.mark.parametrize("alpha,beta", [(2, 1), (1, 0), (True, 1)]) def test_nonunit_addmm_arguments_fail_the_closed_loop_proof( alpha: object, beta: object diff --git a/test/test_cute_grouped_balanced_workers.py b/test/test_cute_grouped_balanced_workers.py index 3d938b8e05..25794bb8ad 100644 --- a/test/test_cute_grouped_balanced_workers.py +++ b/test/test_cute_grouped_balanced_workers.py @@ -11,9 +11,6 @@ from test._cute_grouped_gemm_split_sizes import _device_offsets_kernel from test._cute_grouped_gemm_split_sizes import _device_split_sizes_kernel from test.cute_population_contracts import _target -from test.test_cute_grouped_ab_k import _unsupported_k_loop -from test.test_cute_grouped_d_shift import _args -from test.test_cute_grouped_d_shift import _config as _d_shift_config from test.test_cute_grouped_d_shift import _plans from test.test_cute_grouped_d_shift import _unsafe_output @@ -22,6 +19,9 @@ from helion._testing.cute_codegen import cpu_bind from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable +from helion._testing.cute_grouped_gemm import _unsupported_k_loop +from helion._testing.cute_grouped_gemm import grouped_d_shift_args as _args +from helion._testing.cute_grouped_gemm import grouped_d_shift_config as _d_shift_config from helion.exc import BackendUnsupported from helion.exc import InvalidConfig from helion.runtime.cute.launcher import _append_cute_wrapper_plan diff --git a/test/test_cute_grouped_d_shift.py b/test/test_cute_grouped_d_shift.py index d91be96854..f638053377 100644 --- a/test/test_cute_grouped_d_shift.py +++ b/test/test_cute_grouped_d_shift.py @@ -13,7 +13,6 @@ from test._cute_grouped_gemm_split_sizes import _device_split_sizes_kernel from test.cute_population_contracts import _target from test.test_cute_grouped_ab_k import _observed_logical_k -from test.test_cute_grouped_ab_k import _unsupported_k_loop import helion from helion._compiler.cute.grouped_d_shift import bounded_d_shift_index_domain @@ -23,6 +22,8 @@ from helion._testing.cute_codegen import mock_cuda_unavailable from helion._testing.cute_codegen import require_cute_codegen from helion._testing.cute_flash import seeds_per_codegen_branch +from helion._testing.cute_grouped_gemm import grouped_d_shift_args as _args +from helion._testing.cute_grouped_gemm import grouped_d_shift_config as _config from helion.exc import BackendUnsupported from helion.exc import InvalidConfig import helion.language as hl @@ -63,38 +64,6 @@ def _unsafe_output( return out -def _config(orientation: str, *, cluster_n: int = 1) -> helion.Config: - return helion.Config( - block_sizes=[256, 128, 64], - pid_type="persistent_interleaved", - tcgen05_cluster_m=2, - tcgen05_cluster_n=cluster_n, - tcgen05_ab_stages=2, - tcgen05_acc_stages=2, - tcgen05_c_stages=2, - tcgen05_num_epi_warps=4, - tcgen05_grouped_mode="worklist_nm", - tcgen05_grouped_worklist_orientation=orientation, - tcgen05_grouped_worklist_mma_n=256, - tcgen05_grouped_worklist_source_m_tile=128, - tcgen05_grouped_full_allocation_a=True, - tcgen05_grouped_d_shift=True, - ) - - -def _args(kind: str, dtype: torch.dtype): - metadata = ( - [0, 1, 128, 128, 128, 128, 126, 1] - if kind == "sizes" - else [0, 0, 1, 129, 257, 385, 513, 639, 640] - ) - return ( - torch.empty((640, 256), dtype=torch.bfloat16), - torch.empty((8, 512, 256), dtype=torch.bfloat16), - torch.tensor(metadata, dtype=dtype), - ) - - def _plans(source: str): return next( ast.literal_eval(node.value) @@ -279,15 +248,6 @@ def test_default_off_matches_the_original_source(orientation: str) -> None: assert "bounded_output_shift" not in generated -@pytest.mark.parametrize("variant", [1, 2, 3, 5]) -def test_noncanonical_reductions_cannot_request_bounded_d_shift(variant: int) -> None: - with forbid_cuda_work(), _target(), mock_cuda_unavailable(): - bound = cpu_bind(_unsupported_k_loop, (*_args("fp32", torch.int32), variant)) - assert not bound.config_spec._cute_tcgen05_config.grouped_d_shift_supported - with pytest.raises((InvalidConfig, BackendUnsupported)): - bound.to_code(_config("mn")) - - @pytest.mark.parametrize("variant", [0, 1]) def test_owned_contiguous_output_is_required(variant: int) -> None: args = ( diff --git a/test/test_cute_grouped_large_device_seeds.py b/test/test_cute_grouped_large_device_seeds.py index 36bc7725b3..7afff62131 100644 --- a/test/test_cute_grouped_large_device_seeds.py +++ b/test/test_cute_grouped_large_device_seeds.py @@ -14,7 +14,7 @@ from helion._testing.cute_codegen import cpu_bind from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable -import helion.language as hl +from helion._testing.cute_grouped_gemm import _grouped_offsets_k64 pytestmark = pytest.mark.cpu_only @@ -24,32 +24,6 @@ SHIFTED = "tcgen05_grouped_d_shift" -@helion.kernel(backend="cute", static_shapes=True, autotune_effort="none") -def _grouped_offsets_k64( - a: torch.Tensor, weights: torch.Tensor, offsets: torch.Tensor -) -> torch.Tensor: - rows, reduction = a.shape - groups, columns, _ = weights.shape - block_m = hl.register_block_size(256) - block_n = hl.register_block_size(128) - block_k = hl.register_block_size(64) - out = torch.empty((rows, columns), device=a.device, dtype=a.dtype) - for group_tile, row_tile, column_tile in hl.tile( - [groups, rows, columns], block_size=[1, block_m, block_n] - ): - group = group_tile.index.sum() - start = offsets[group] - extent = offsets[group + 1] - offsets[group] - row_indices = start + row_tile.index - valid = row_tile.index < extent - acc = hl.zeros([row_tile, column_tile], dtype=torch.float32) - for inner in hl.tile(reduction, block_size=block_k): - left = hl.load(a, [row_indices, inner], extra_mask=valid[:, None]) - acc = torch.addmm(acc, left, weights[group, column_tile, inner].T) - hl.store(out, [row_indices, column_tile], acc, extra_mask=valid[:, None]) - return out - - def _kernel(): # A fresh bind is needed when comparing seed-generation policies. return helion.kernel( diff --git a/test/test_cute_grouped_mn_224.py b/test/test_cute_grouped_mn_224.py index 3e68ff9cee..69609d99e9 100644 --- a/test/test_cute_grouped_mn_224.py +++ b/test/test_cute_grouped_mn_224.py @@ -10,7 +10,6 @@ from test.cute_population_contracts import _target from test.test_cute_grouped_d_shift import _assignment -from test.test_cute_grouped_d_shift import _config from test.test_cute_grouped_d_shift import _plans from test.test_cute_grouped_d_shift import _unsafe_output from test.test_cute_grouped_d_shift import _value @@ -29,6 +28,7 @@ from helion._testing.cute_codegen import cpu_bind from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable +from helion._testing.cute_grouped_gemm import grouped_d_shift_config as _config from helion.exc import BackendUnsupported from helion.exc import InvalidConfig import helion.language as hl diff --git a/test/test_cute_grouped_mn_device_seeds.py b/test/test_cute_grouped_mn_device_seeds.py index 7113370b2b..ff1447c939 100644 --- a/test/test_cute_grouped_mn_device_seeds.py +++ b/test/test_cute_grouped_mn_device_seeds.py @@ -1,26 +1,34 @@ from __future__ import annotations import ast +from contextlib import contextmanager import random +from typing import TYPE_CHECKING +from typing import NamedTuple from unittest.mock import patch import pytest import torch -from test.cute_population_contracts import _target -from test.cute_population_contracts import checked_initial_population -from test.test_cute_grouped_ab_k import _unsupported_k_loop -from test.test_cute_grouped_large_device_seeds import _grouped_offsets_k64 - import helion from helion._compiler.cute.autotune.heuristics import cute as heuristics from helion._compiler.cute.tcgen05_constants import tcgen05_grouped_worklist_smem_bytes from helion._testing.cute_codegen import cpu_bind from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable +from helion._testing.cute_grouped_gemm import _grouped_offsets_k64 +from helion._testing.cute_grouped_gemm import _unsupported_k_loop +from helion._testing.cute_population_contracts import _target +from helion._testing.cute_population_contracts import checked_initial_population from helion.autotuner.effort_profile import get_effort_profile from helion.autotuner.surrogate_pattern_search import LFBOTreeSearch +if TYPE_CHECKING: + from collections.abc import Iterator + + from helion.autotuner.config_spec import ConfigSpec + from helion.runtime.kernel import BoundKernel + pytestmark = pytest.mark.cpu_only @@ -41,13 +49,8 @@ def _args(m: int, groups: int, n: int, k: int): ) -@pytest.mark.parametrize( - "m,groups,n,k", [(2048, 16, 1536, 2048), (8192, 16, 1536, 2048), (512, 4, 512, 256)] -) -def test_mn_seeds_preserve_old_prefix_normalize_and_reach_native_source( - m: int, groups: int, n: int, k: int -) -> None: - args = _args(m, groups, n, k) +@contextmanager +def _mn_target() -> Iterator[None]: with ( forbid_cuda_work(), _target(), @@ -56,49 +59,70 @@ def test_mn_seeds_preserve_old_prefix_normalize_and_reach_native_source( heuristics, "_tcgen05_grouped_prefix_adaptive_n_seeds", return_value=[] ), ): + yield + + +class _MNSeedCase(NamedTuple): + columns: int + old: ConfigSpec + bound: BoundKernel + added: list[helion.Config] + representatives: tuple[helion.Config, ...] + + +@pytest.fixture( + scope="module", + params=[(2048, 16, 1536, 2048), (8192, 16, 1536, 2048), (512, 4, 512, 256)], + ids=lambda shape: "-".join(map(str, shape)), +) +def mn_seed_case(request: pytest.FixtureRequest) -> Iterator[_MNSeedCase]: + m, groups, n, k = request.param + args = _args(m, groups, n, k) + with _mn_target(): with patch.object( heuristics, "_tcgen05_grouped_mn_device_tile_seeds", return_value=[] ): - previous = cpu_bind(_kernel(), args) - old_seeds = list(previous.config_spec.compiler_seed_configs) - old_default = previous.config_spec.compiler_default_config + old = cpu_bind(_kernel(), args).config_spec bound = cpu_bind(_kernel(), args) - spec = bound.config_spec - seeds = spec.compiler_seed_configs - assert seeds[: len(old_seeds)] == old_seeds - assert spec.compiler_default_config == old_default + added = bound.config_spec.compiler_seed_configs[len(old.compiler_seed_configs) :] + representatives: dict[tuple[object, ...], helion.Config] = {} + for seed in added: + # Pipeline depths resize the same source. Keep the first seed for + # every worklist geometry and L2 swizzle. + representatives.setdefault( + ( + seed["tcgen05_grouped_worklist_source_m_tile"], + seed["tcgen05_grouped_worklist_mma_n"], + seed["tcgen05_cluster_n"], + seed.get("tcgen05_grouped_balanced_workers"), + seed.get("tcgen05_l2_swizzle_size"), + seed.get("tcgen05_grouped_l2_swizzle_alternate"), + seed.get("tcgen05_grouped_l2_swizzle_mn_ratio"), + ), + seed, + ) + # BoundKernel weakly retains runtime inputs: keep args alive while any + # batch may render from this binding, with no target mocks active. + yield _MNSeedCase(n, old, bound, added, tuple(representatives.values())) + + +def test_mn_seeds_preserve_old_prefix_normalize_and_reach_native_source( + mn_seed_case: _MNSeedCase, +) -> None: + old_seeds = mn_seed_case.old.compiler_seed_configs + added = mn_seed_case.added + with _mn_target(): + spec = mn_seed_case.bound.config_spec + assert spec.compiler_seed_configs[: len(old_seeds)] == old_seeds + assert spec.compiler_default_config == mn_seed_case.old.compiler_default_config assert spec.block_sizes[2].declared_max_size == 64 - added = seeds[len(old_seeds) :] assert added - representatives: dict[tuple[object, ...], helion.Config] = {} for seed in added: assert seed.get("tcgen05_grouped_worklist_orientation") == "mn" assert seed.block_sizes == [256, 128, 64] assert seed["tcgen05_grouped_full_allocation_a"] is True assert seed["tcgen05_grouped_d_shift"] is True - normalized = spec.normalized_config(seed) - assert normalized.block_sizes[2] == 64 - # Every seed is normalized; one seed per worklist geometry and - # L2 swizzle layout is rendered below (the pipeline depths only - # resize the same source). - representatives.setdefault( - ( - seed["tcgen05_grouped_worklist_source_m_tile"], - seed["tcgen05_grouped_worklist_mma_n"], - seed["tcgen05_cluster_n"], - seed.get("tcgen05_grouped_balanced_workers"), - seed.get("tcgen05_l2_swizzle_size"), - seed.get("tcgen05_grouped_l2_swizzle_alternate"), - seed.get("tcgen05_grouped_l2_swizzle_mn_ratio"), - ), - normalized, - ) - for normalized in representatives.values(): - source = bound.to_code(normalized) - ast.parse(source) - assert "'bounded_output_shift': True" in source - assert "'immutable_ab_tensormaps': True" in source - assert "TensorMapManager" not in source + assert spec.normalized_config(seed).block_sizes[2] == 64 mn = [ seed for seed in added @@ -114,7 +138,7 @@ def test_mn_seeds_preserve_old_prefix_normalize_and_reach_native_source( 224, 256, } - if n == 1536: + if mn_seed_case.columns == 1536: assert any( seed["tcgen05_grouped_worklist_source_m_tile"] == 128 and seed["tcgen05_grouped_worklist_mma_n"] == 192 @@ -132,6 +156,23 @@ def test_mn_seeds_preserve_old_prefix_normalize_and_reach_native_source( ) +# Cross the original three shapes with disjoint slices of their complete +# representative sets so one pytest item cannot spend minutes rendering them. +_RENDER_BATCHES = 8 + + +@pytest.mark.parametrize("batch", range(_RENDER_BATCHES)) +def test_mn_seed_native_sources(mn_seed_case: _MNSeedCase, batch: int) -> None: + bound = mn_seed_case.bound + with _mn_target(): + for seed in mn_seed_case.representatives[batch::_RENDER_BATCHES]: + source = bound.to_code(bound.config_spec.normalized_config(seed)) + ast.parse(source) + assert "'bounded_output_shift': True" in source + assert "'immutable_ab_tensormaps': True" in source + assert "TensorMapManager" not in source + + def test_resource_and_complete_cluster_bounds_apply_to_each_proposal() -> None: with forbid_cuda_work(), _target(), mock_cuda_unavailable(): bound = cpu_bind(_kernel(), _args(512, 4, 256, 256)) diff --git a/test/test_cute_grouped_prefix_adaptive_n_codegen.py b/test/test_cute_grouped_prefix_adaptive_n_codegen.py index 918de21792..d647627764 100644 --- a/test/test_cute_grouped_prefix_adaptive_n_codegen.py +++ b/test/test_cute_grouped_prefix_adaptive_n_codegen.py @@ -14,7 +14,6 @@ import torch from test.cute_population_contracts import _target -from test.test_cute_grouped_d_shift import _config as _ordinary_config from test.test_cute_grouped_large_device_seeds import _kernel from test.test_cute_grouped_paired_clc_layout import _sdk from test.test_cute_grouped_prefix_adaptive_config import _args @@ -29,6 +28,7 @@ from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable from helion._testing.cute_codegen import require_cute_codegen +from helion._testing.cute_grouped_gemm import grouped_d_shift_config as _ordinary_config from helion.exc import InvalidConfig import helion.language as hl from helion.runtime.cute.launcher import _create_cute_wrapper diff --git a/test/test_cute_grouped_prefix_m256_codegen.py b/test/test_cute_grouped_prefix_m256_codegen.py index dcc3978ac2..0e5793a092 100644 --- a/test/test_cute_grouped_prefix_m256_codegen.py +++ b/test/test_cute_grouped_prefix_m256_codegen.py @@ -15,7 +15,6 @@ import torch from test.cute_population_contracts import _target -from test.test_cute_grouped_d_shift import _config as _ordinary_config from test.test_cute_grouped_large_device_seeds import _kernel from test.test_cute_grouped_paired_clc_layout import _sdk from test.test_cute_grouped_prefix_adaptive_config import _args @@ -31,6 +30,7 @@ from helion._testing.cute_codegen import forbid_cuda_work from helion._testing.cute_codegen import mock_cuda_unavailable from helion._testing.cute_codegen import require_cute_codegen +from helion._testing.cute_grouped_gemm import grouped_d_shift_config as _ordinary_config from helion.runtime.cute.launcher import _append_cute_wrapper_plan if TYPE_CHECKING: diff --git a/test/test_cute_grouped_worklist_codegen.expected_cute b/test/test_cute_grouped_worklist_codegen.expected_cute new file mode 100644 index 0000000000..9332a68b38 --- /dev/null +++ b/test/test_cute_grouped_worklist_codegen.expected_cute @@ -0,0 +1,384 @@ +This file is automatically generated by assertExpectedJournal calls in test_cute_grouped_worklist_codegen.py. +Update expected outputs by running tests with the EXPECTTEST_ACCEPT=1 environment variable set. + +--- assertExpectedJournal(TestRoleLocalGroupedRenders.test_p2_panel_raster) +from __future__ import annotations + +import torch +import helion +import cutlass +import cutlass.cute as cute +from helion.runtime import default_cute_launcher as _default_cute_launcher +import helion._compiler.cute._tcgen05_prologue_runtime as _helion_tc_pro + +_BLOCK_SIZE_0 = 256 +_BLOCK_SIZE_2 = 64 + +@cute.kernel +def _helion__grouped_offsets_k64(offsets, a, weights, out, tcgen05_grouped_tile_sched_params, tma_atom_a, tma_tensor_a, tma_atom_b, tma_tensor_b, tcgen05_tma_store_atom, tcgen05_tma_store_tensor): + cute.arch.griddepcontrol_wait() + cute.arch.griddepcontrol_launch_dependents() + tcgen05_work_tile_smem_ptr = cute.arch.alloc_smem(cutlass.Int32, 9, alignment=16) + tcgen05_work_tile_smem_tensor = cute.make_tensor(tcgen05_work_tile_smem_ptr, cute.make_layout((9,), stride=(1,))) + tcgen05_work_tile_smem = tcgen05_work_tile_smem_tensor + num_blocks_0 = 16 + num_blocks_1 = (2048 + _BLOCK_SIZE_0 - 1) // _BLOCK_SIZE_0 + pass + pass + start = cutlass.Int32(0) + pass + pass + pass + pass + v_3 = cutlass.Int32(0) + v_4 = cutlass.Int32(0) + v_5 = cutlass.Boolean(0) + acc = cutlass.Float32(0.0) + tcgen05_grouped_problem_sizes_smem_ptr = cute.arch.alloc_smem(cutlass.Int32, 64, alignment=16) + tcgen05_grouped_problem_sizes = cute.make_tensor(tcgen05_grouped_problem_sizes_smem_ptr, cute.make_layout((16, 4), stride=(4, 1))) + tcgen05_grouped_starts_smem_ptr = cute.arch.alloc_smem(cutlass.Int32, 16, alignment=16) + tcgen05_grouped_starts = cute.make_tensor(tcgen05_grouped_starts_smem_ptr, cute.make_layout((16,), stride=(1,))) + tcgen05_grouped_metadata_thread_idx = cute.arch.thread_idx() + tcgen05_grouped_metadata_block_dim = cute.arch.block_dim() + for tcgen05_grouped_metadata_group in cutlass.range(tcgen05_grouped_metadata_thread_idx[0] + tcgen05_grouped_metadata_block_dim[0] * (tcgen05_grouped_metadata_thread_idx[1] + tcgen05_grouped_metadata_block_dim[1] * tcgen05_grouped_metadata_thread_idx[2]), 16, tcgen05_grouped_metadata_block_dim[0] * tcgen05_grouped_metadata_block_dim[1] * tcgen05_grouped_metadata_block_dim[2], unroll=1): + tcgen05_grouped_raw_start = cutlass.Int32((offsets.iterator + cutlass.Int64(tcgen05_grouped_metadata_group) * cutlass.Int64(offsets.layout.stride[0])).load()) + tcgen05_grouped_raw_end = cutlass.Int32((offsets.iterator + cutlass.Int64(tcgen05_grouped_metadata_group + 1) * cutlass.Int64(offsets.layout.stride[0])).load()) + tcgen05_grouped_raw_extent = max(tcgen05_grouped_raw_end - tcgen05_grouped_raw_start, cutlass.Int32(0)) + tcgen05_grouped_source_end = tcgen05_grouped_raw_start + min(tcgen05_grouped_raw_extent, cutlass.Int32(2048)) + tcgen05_grouped_visible_start = min(max(tcgen05_grouped_raw_start, cutlass.Int32(0)), cutlass.Int32(2048)) + tcgen05_grouped_visible_end = min(max(tcgen05_grouped_source_end, cutlass.Int32(0)), cutlass.Int32(2048)) + tcgen05_grouped_visible_extent = max(tcgen05_grouped_visible_end - tcgen05_grouped_visible_start, cutlass.Int32(0)) if tcgen05_grouped_raw_extent > cutlass.Int32(0) else cutlass.Int32(0) + tcgen05_grouped_starts[cutlass.Int32(tcgen05_grouped_metadata_group)] = cutlass.Int32(tcgen05_grouped_visible_start) + tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(0)] = cutlass.Int32(tcgen05_grouped_visible_extent) + tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(1)] = cutlass.Int32(1536) + tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(2)] = cutlass.Int32(2048) + tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(3)] = cutlass.Int32(1) + cute.arch.sync_threads() + tcgen05_warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + tcgen05_lane_idx = cute.arch.lane_idx() + mma_tidx = cutlass.Int32(cute.arch.thread_idx()[0]) + cutlass.Int32(cute.arch.thread_idx()[1]) * cutlass.Int32(32) + mma_copy_tidx = mma_tidx + mma_active = cutlass.Int32(cute.arch.thread_idx()[1]) < cutlass.Int32(2) + tcgen05_tma_warp = tcgen05_warp_idx == cutlass.Int32(5) + tcgen05_exec_active = tcgen05_warp_idx == cutlass.Int32(4) + tcgen05_epi_active = tcgen05_warp_idx < cutlass.Int32(4) + tcgen05_epi_tidx = tcgen05_lane_idx + tcgen05_warp_idx * cutlass.Int32(32) if tcgen05_epi_active else cutlass.Int32(0) + if not tcgen05_epi_active: + cute.arch.setmaxregister_decrease(120) + if tcgen05_epi_active: + cute.arch.setmaxregister_increase(256) + mma_slice_tidx = _helion_tc_pro.mod_nonneg(cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()), 2) + tiled_mma = cutlass.utils.blackwell_helpers.make_trivial_tiled_mma(cutlass.BFloat16, cutlass.BFloat16, cute.nvgpu.OperandMajorMode.K, cute.nvgpu.OperandMajorMode.K, cutlass.Float32, cute.nvgpu.tcgen05.CtaGroup.TWO, (128, 128), cute.nvgpu.tcgen05.OperandSource.SMEM) + thr_mma = tiled_mma.get_slice(mma_slice_tidx) + tcgen05_cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((2, 1, 1)), (tiled_mma.thr_id.shape,)) + sA_layout = cutlass.utils.blackwell_helpers.make_smem_layout_a(tiled_mma, (128, 128, 64), cutlass.BFloat16, 13) + sB_layout = cutlass.utils.blackwell_helpers.make_smem_layout_b(tiled_mma, (128, 128, 64), cutlass.BFloat16, 13, is_k_major=True) + tcgen05_c_layout = cutlass.utils.layout.LayoutEnum.ROW_MAJOR + tcgen05_epi_tile = cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape((64, 128), True, tcgen05_c_layout, cutlass.BFloat16) + tcgen05_tmem_load_atom = cutlass.utils.blackwell_helpers.get_tmem_load_op((64, 128, 64), tcgen05_c_layout, cutlass.Float32, cutlass.Float32, tcgen05_epi_tile, True) + tcgen05_epilogue_rest_mode = cute.make_layout(1, stride=0) + acc_frag_base = tiled_mma.make_fragment_C(cute.append(tiled_mma.partition_shape_C((128, 128)), 2)) + tcgen05_acc_tmem_cols = cutlass.utils.get_num_tmem_alloc_cols(acc_frag_base, arch='sm_100') + tcgen05_tmem_holding_buf = cute.arch.alloc_smem(cutlass.Int32, 1) + tcgen05_tmem_dealloc_mbar_ptr = cute.arch.alloc_smem(cutlass.Int64, 1) + tcgen05_tmem_alloc_barrier = cutlass.pipeline.NamedBarrier(barrier_id=1, num_threads=160) + tcgen05_tmem_allocator = cutlass.utils.TmemAllocator(tcgen05_tmem_holding_buf, barrier_for_retrieve=tcgen05_tmem_alloc_barrier, allocator_warp_id=0, is_two_cta=True, two_cta_tmem_dealloc_mbar_ptr=tcgen05_tmem_dealloc_mbar_ptr, initialize_mbarrier=False) + tcgen05_acc_pipeline_barriers = cute.arch.alloc_smem(cutlass.Int64, cutlass.Int32(4)) + tcgen05_acc_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread) + tcgen05_acc_pipeline_consumer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(8)) + tcgen05_acc_pipeline = _helion_tc_pro.make_umma_async_pipeline(num_stages=2, producer_group=tcgen05_acc_pipeline_producer_group, consumer_group=tcgen05_acc_pipeline_consumer_group, barrier_storage=tcgen05_acc_pipeline_barriers, cta_layout_vmnk=tcgen05_cluster_layout_vmnk) + tcgen05_acc_producer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Producer, 2) + tcgen05_acc_consumer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Consumer, 2) + tcgen05_sched_pipeline_mbars = cute.arch.alloc_smem(cutlass.Int64, cutlass.Int32(2)) + tcgen05_sched_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, 1) + tcgen05_sched_pipeline_consumer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(192)) + tcgen05_sched_pipeline = cutlass.pipeline.PipelineAsync.create(num_stages=1, producer_group=tcgen05_sched_pipeline_producer_group, consumer_group=tcgen05_sched_pipeline_consumer_group, barrier_storage=tcgen05_sched_pipeline_mbars, defer_sync=True) + tcgen05_sched_pipeline_producer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Producer, 1) + tcgen05_sched_pipeline_consumer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Consumer, 1) + if tcgen05_tma_warp: + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_a) + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_b) + smem_a = cute.arch.alloc_smem(cutlass.BFloat16, cute.cosize(sA_layout.outer), alignment=128) + sA = cute.make_tensor(cute.recast_ptr(smem_a, sA_layout.inner, dtype=cutlass.BFloat16), sA_layout.outer) + smem_b = cute.arch.alloc_smem(cutlass.BFloat16, cute.cosize(sB_layout.outer), alignment=128) + sB = cute.make_tensor(cute.recast_ptr(smem_b, sB_layout.inner, dtype=cutlass.BFloat16), sB_layout.outer) + tcgen05_tCrA = tiled_mma.make_fragment_A(sA) + tcgen05_tCrB = tiled_mma.make_fragment_B(sB) + sA_tma_layout = cute.slice_(sA_layout, (None, None, None, 0)) + sB_tma_layout = cute.slice_(sB_layout, (None, None, None, 0)) + tma_thr_mma = tiled_mma.get_slice(mma_slice_tidx) + tma_a_cta_layout = cute.make_layout(cute.slice_(tcgen05_cluster_layout_vmnk, (0, 0, None, 0)).shape) + tma_b_cta_layout = cute.make_layout(cute.slice_(tcgen05_cluster_layout_vmnk, (0, None, 0, 0)).shape) + tcgen05_cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) & cutlass.Int32(1) + tcgen05_block_in_cluster_coord_vmnk = tcgen05_cluster_layout_vmnk.get_flat_coord(tcgen05_cta_rank_in_cluster) + tma_a_cta_coord = tcgen05_block_in_cluster_coord_vmnk[2] + tma_b_cta_coord = tcgen05_block_in_cluster_coord_vmnk[1] + tcgen05_a_mcast_mask = cute.nvgpu.cpasync.create_tma_multicast_mask(tcgen05_cluster_layout_vmnk, tcgen05_block_in_cluster_coord_vmnk, mcast_mode=2) + tcgen05_b_mcast_mask = cute.nvgpu.cpasync.create_tma_multicast_mask(tcgen05_cluster_layout_vmnk, tcgen05_block_in_cluster_coord_vmnk, mcast_mode=1) + tcgen05_ab_pipeline_mbars = cute.arch.alloc_smem(cutlass.Int64, cutlass.Int32(26)) + tcgen05_ab_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, 1) + tcgen05_ab_pipeline_consumer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(1)) + tcgen05_ab_pipeline_tx_count = (cute.size_in_bytes(cutlass.BFloat16, sA_tma_layout) + cute.size_in_bytes(cutlass.BFloat16, sB_tma_layout)) * cute.size(tiled_mma.thr_id.shape) + tcgen05_ab_pipeline = _helion_tc_pro.make_tma_umma_pipeline(num_stages=13, producer_group=tcgen05_ab_pipeline_producer_group, consumer_group=tcgen05_ab_pipeline_consumer_group, tx_count=tcgen05_ab_pipeline_tx_count, barrier_storage=tcgen05_ab_pipeline_mbars, cta_layout_vmnk=tcgen05_cluster_layout_vmnk) + tcgen05_ab_producer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Producer, 13) + tcgen05_ab_consumer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Consumer, 13) + if not tcgen05_tma_warp: + if tcgen05_warp_idx == cutlass.Int32(0): + with cute.arch.elect_one(): + cute.arch.mbarrier_init(tcgen05_tmem_dealloc_mbar_ptr, 32) + _helion_tc_pro.init_pipeline_barriers(tcgen05_warp_idx, (0,), tcgen05_acc_pipeline) + if tcgen05_warp_idx == cutlass.Int32(0): + cute.nvgpu.cpasync.prefetch_descriptor(tcgen05_tma_store_atom) + _helion_tc_pro.init_pipeline_barriers_pair(tcgen05_warp_idx, 1, tcgen05_ab_pipeline) + cutlass.pipeline.pipeline_init_arrive(cluster_shape_mn=tcgen05_cluster_layout_vmnk, is_relaxed=True) + cutlass.pipeline.pipeline_init_wait(cluster_shape_mn=tcgen05_cluster_layout_vmnk) + if tcgen05_epi_active: + tcgen05_tmem_allocator.allocate(tcgen05_acc_tmem_cols) + tcgen05_tmem_allocator.relinquish_alloc_permit() + tcgen05_exec_acc_tmem_ptr = cute.make_ptr(cutlass.Float32, 0, cute.AddressSpace.tmem, assumed_align=16) + tcgen05_epi_acc_tmem_ptr = cute.make_ptr(cutlass.Float32, 0, cute.AddressSpace.tmem, assumed_align=16) + cute.arch.sync_threads() + if tcgen05_exec_active or tcgen05_epi_active: + tcgen05_tmem_allocator.wait_for_alloc() + if tcgen05_exec_active: + tcgen05_exec_acc_tmem_ptr = tcgen05_tmem_allocator.retrieve_ptr(cutlass.Float32) + if tcgen05_epi_active: + tcgen05_epi_acc_tmem_ptr = tcgen05_tmem_allocator.retrieve_ptr(cutlass.Float32) + tcgen05_exec_acc_frag_base = cute.make_tensor(tcgen05_exec_acc_tmem_ptr, acc_frag_base.layout) + tcgen05_epi_acc_frag_base = cute.make_tensor(tcgen05_epi_acc_tmem_ptr, acc_frag_base.layout) + tcgen05_epilog_sync_barrier = cutlass.pipeline.NamedBarrier(barrier_id=cutlass.Int32(2), num_threads=cutlass.Int32(128)) + tcgen05_c_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(128)) + tcgen05_c_pipeline = cutlass.pipeline.PipelineTmaStore.create(num_stages=2, producer_group=tcgen05_c_pipeline_producer_group) + tcgen05_kernel_desc = type('Tcgen05KernelDesc', (), {'cta_tile_shape_mnk': (64, 128, 64), 'c_layout': cutlass.utils.layout.LayoutEnum.ROW_MAJOR, 'c_dtype': cutlass.BFloat16, 'acc_dtype': cutlass.Float32, 'epilog_sync_bar_id': cutlass.Int32(2), 'epilogue_warp_id': (cutlass.Int32(0), cutlass.Int32(1), cutlass.Int32(2), cutlass.Int32(3)), 'num_c_stage': cutlass.Int32(2), 'use_2cta_instrs': True})() + tcgen05_store_epi_tile = cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape((64, 128), True, cutlass.utils.layout.LayoutEnum.ROW_MAJOR, cutlass.BFloat16) + tcgen05_sD_layout = cutlass.utils.blackwell_helpers.make_smem_layout_epi(cutlass.BFloat16, cutlass.utils.layout.LayoutEnum.ROW_MAJOR, tcgen05_store_epi_tile, 2) + tcgen05_sD_ptr = cute.arch.alloc_smem(cutlass.BFloat16, cute.cosize(tcgen05_sD_layout.outer), alignment=1024) + tcgen05_sD = cute.make_tensor(cute.recast_ptr(tcgen05_sD_ptr, tcgen05_sD_layout.inner, dtype=cutlass.BFloat16), tcgen05_sD_layout.outer) + tcgen05_tAcc = cutlass.utils.gemm.sm100.transform_partitioned_tensor_layout(tcgen05_epi_acc_frag_base) + if cute.arch.make_warp_uniform(cute.arch.warp_idx()) == cutlass.Int32(5): + cute.arch.griddepcontrol_wait() + cute.arch.griddepcontrol_launch_dependents() + tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + tcgen05_role_local_0_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) + while tcgen05_role_local_0_valid: + tcgen05_grouped_cta_tile_idx_m = tcgen05_work_tile_smem[cutlass.Int32(0)] + tcgen05_grouped_cta_tile_idx_n = tcgen05_work_tile_smem[cutlass.Int32(1)] + tcgen05_grouped_group_idx = tcgen05_work_tile_smem[cutlass.Int32(4)] + tcgen05_grouped_problem_m = tcgen05_work_tile_smem[cutlass.Int32(5)] + tcgen05_grouped_problem_n = tcgen05_work_tile_smem[cutlass.Int32(6)] + tcgen05_grouped_global_m_start = tcgen05_work_tile_smem[cutlass.Int32(8)] + tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) + tcgen05_sched_pipeline_consumer_state.advance() + cute.arch.sync_warp() + gA_tma = cute.local_tile(cute.domain_offset((tcgen05_grouped_global_m_start, cutlass.Int32(0)), tma_tensor_a), (128, 64), (tcgen05_grouped_cta_tile_idx_m, None)) + gB_tma = cute.local_tile(tma_tensor_b, (128, 64), (tcgen05_grouped_group_idx * cutlass.Int32(12) + tcgen05_grouped_cta_tile_idx_n, None)) + gA_tma_part = tma_thr_mma.partition_A(gA_tma) + gB_tma_part = tma_thr_mma.partition_B(gB_tma) + tma_sA, tma_gA = cute.nvgpu.cpasync.tma_partition(tma_atom_a, tma_a_cta_coord, tma_a_cta_layout, cute.group_modes(sA, 0, cute.rank(sA) - 1), cute.group_modes(gA_tma_part, 0, cute.rank(gA_tma_part) - 1)) + tma_sB, tma_gB = cute.nvgpu.cpasync.tma_partition(tma_atom_b, tma_b_cta_coord, tma_b_cta_layout, cute.group_modes(sB, 0, cute.rank(sB) - 1), cute.group_modes(gB_tma_part, 0, cute.rank(gB_tma_part) - 1)) + for tile_offset_2 in range(cutlass.Int32(0), cutlass.Int32(2048), cutlass.Int32(_BLOCK_SIZE_2)): + tcgen05_tma_k_tile = _helion_tc_pro.floordiv_nonneg(tile_offset_2, 64) + tcgen05_tma_full_tile = tcgen05_grouped_cta_tile_idx_m * cutlass.Int32(128) < tcgen05_grouped_problem_m and tcgen05_grouped_cta_tile_idx_n * cutlass.Int32(128) < tcgen05_grouped_problem_n and (tile_offset_2 < cutlass.Int32(2048)) + tcgen05_ab_producer_try_token = cutlass.Boolean(0) + if tcgen05_tma_full_tile: + tcgen05_ab_producer_try_token = tcgen05_ab_pipeline.producer_try_acquire(tcgen05_ab_producer_state) + tcgen05_ab_pipeline.producer_acquire(tcgen05_ab_producer_state, tcgen05_ab_producer_try_token) + tcgen05_tma_barrier = tcgen05_ab_pipeline.producer_get_barrier(tcgen05_ab_producer_state) + cute.copy(tma_atom_a, tma_gA[None, tcgen05_tma_k_tile], tma_sA[None, tcgen05_ab_producer_state.index], tma_bar_ptr=tcgen05_tma_barrier, mcast_mask=tcgen05_a_mcast_mask) + cute.copy(tma_atom_b, tma_gB[None, tcgen05_tma_k_tile], tma_sB[None, tcgen05_ab_producer_state.index], tma_bar_ptr=tcgen05_tma_barrier, mcast_mask=tcgen05_b_mcast_mask) + tcgen05_ab_pipeline.producer_commit(tcgen05_ab_producer_state) + tcgen05_ab_producer_state.advance() + tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + tcgen05_role_local_0_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) + tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) + tcgen05_sched_pipeline_consumer_state.advance() + cute.arch.sync_warp() + if cute.arch.make_warp_uniform(cute.arch.warp_idx()) == cutlass.Int32(4): + tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + tcgen05_role_local_1_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) + while tcgen05_role_local_1_valid: + tcgen05_grouped_cta_tile_idx_m = tcgen05_work_tile_smem[cutlass.Int32(0)] + tcgen05_grouped_cta_tile_idx_n = tcgen05_work_tile_smem[cutlass.Int32(1)] + tcgen05_grouped_problem_m = tcgen05_work_tile_smem[cutlass.Int32(5)] + tcgen05_grouped_problem_n = tcgen05_work_tile_smem[cutlass.Int32(6)] + tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) + tcgen05_sched_pipeline_consumer_state.advance() + cute.arch.sync_warp() + acc_frag = tcgen05_exec_acc_frag_base[None, None, None, tcgen05_acc_producer_state.index] + tcgen05_ab_consumer_try_token = cutlass.Boolean(1) + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tcgen05_ab_consumer_try_token = tcgen05_ab_pipeline.consumer_try_wait(tcgen05_ab_consumer_state) + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tcgen05_acc_pipeline.producer_acquire(tcgen05_acc_producer_state) + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tiled_mma.set(cute.nvgpu.tcgen05.Field.ACCUMULATE, False) + for tile_offset_2 in range(cutlass.Int32(0), cutlass.Int32(2048), cutlass.Int32(_BLOCK_SIZE_2)): + mma_stage = tcgen05_ab_consumer_state.index + sA_mma = sA[None, None, None, mma_stage] + sB_mma = sB[None, None, None, mma_stage] + tcgen05_tma_full_tile = tcgen05_grouped_cta_tile_idx_m * cutlass.Int32(128) < tcgen05_grouped_problem_m and tcgen05_grouped_cta_tile_idx_n * cutlass.Int32(128) < tcgen05_grouped_problem_n and (tile_offset_2 < cutlass.Int32(2048)) + tcgen05_tma_next_consumer_tile = tile_offset_2 + cutlass.Int32(64) < cutlass.Int32(2048) + if tcgen05_tma_full_tile: + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tcgen05_ab_pipeline.consumer_wait(tcgen05_ab_consumer_state, tcgen05_ab_consumer_try_token) + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + for _tcgen05_kblk_idx in range(cute.size(tcgen05_tCrA, mode=[2])): + cute.gemm(tiled_mma, acc_frag, [tcgen05_tCrA[None, None, cutlass.Int32(_tcgen05_kblk_idx), mma_stage]], [tcgen05_tCrB[None, None, cutlass.Int32(_tcgen05_kblk_idx), mma_stage]], acc_frag) + tiled_mma.set(cute.nvgpu.tcgen05.Field.ACCUMULATE, True) + if tcgen05_tma_full_tile: + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tcgen05_ab_pipeline.consumer_release(tcgen05_ab_consumer_state) + tcgen05_ab_consumer_state.advance() + tcgen05_ab_consumer_try_token = cutlass.Boolean(1) + if tcgen05_tma_next_consumer_tile and cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tcgen05_ab_consumer_try_token = tcgen05_ab_pipeline.consumer_try_wait(tcgen05_ab_consumer_state) + if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): + tcgen05_acc_pipeline.producer_commit(tcgen05_acc_producer_state) + tcgen05_acc_producer_state.advance() + tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + tcgen05_role_local_1_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) + tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) + tcgen05_sched_pipeline_consumer_state.advance() + cute.arch.sync_warp() + if cute.arch.make_warp_uniform(cute.arch.warp_idx()) < cutlass.Int32(4): + tcgen05_tma_store_role_tile = cutlass.Int32(0) + tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + tcgen05_role_local_2_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) + while tcgen05_role_local_2_valid: + tcgen05_grouped_cta_tile_idx_m = tcgen05_work_tile_smem[cutlass.Int32(0)] + tcgen05_grouped_cta_tile_idx_n = tcgen05_work_tile_smem[cutlass.Int32(1)] + tcgen05_grouped_problem_m = tcgen05_work_tile_smem[cutlass.Int32(5)] + tcgen05_grouped_global_m_start = tcgen05_work_tile_smem[cutlass.Int32(8)] + tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) + tcgen05_sched_pipeline_consumer_state.advance() + cute.arch.sync_warp() + if True: + if tcgen05_warp_idx == cutlass.Int32(0): + tcgen05_c_pipeline.producer_acquire() + tcgen05_bounded_output = cute.domain_offset((cutlass.Int32(2048) - tcgen05_grouped_problem_m, cutlass.Int32(0), tcgen05_grouped_global_m_start + tcgen05_grouped_problem_m), tcgen05_tma_store_tensor) + tcgen05_gC = cute.local_tile(tcgen05_bounded_output, (128, 128), (tcgen05_grouped_cta_tile_idx_m, tcgen05_grouped_cta_tile_idx_n, 0)) + tcgen05_tCgC_base = thr_mma.partition_C(tcgen05_gC) + tcgen05_tCgC = cutlass.utils.gemm.sm100.transform_partitioned_tensor_layout(tcgen05_tCgC_base) + tcgen05_tCgC_planned = cute.make_tensor(tcgen05_tCgC.iterator, cute.append(cute.append(cute.append(tcgen05_tCgC.layout, tcgen05_epilogue_rest_mode), tcgen05_epilogue_rest_mode), tcgen05_epilogue_rest_mode)) + tcgen05_tiled_copy_t2r, tcgen05_tTR_tAcc_base, tcgen05_tTR_rAcc = cutlass.utils.gemm.sm100.epilogue_tmem_copy_and_partition(tcgen05_kernel_desc, tcgen05_epi_tidx, tcgen05_tAcc, tcgen05_tCgC_planned, tcgen05_store_epi_tile, True) + tcgen05_tTR_rD = cute.make_rmem_tensor(tcgen05_tTR_rAcc.shape, cutlass.BFloat16) + tcgen05_tiled_copy_r2s, tcgen05_tRS_rD, tcgen05_tRS_sD = cutlass.utils.gemm.sm100.epilogue_smem_copy_and_partition(tcgen05_kernel_desc, tcgen05_tiled_copy_t2r, tcgen05_tTR_rD, tcgen05_epi_tidx, tcgen05_sD) + tcgen05_tRS_rAcc = tcgen05_tiled_copy_r2s.retile(tcgen05_tTR_rAcc) + tcgen05_tCgC_epi = cute.flat_divide(tcgen05_tCgC_planned, tcgen05_store_epi_tile) + tcgen05_bSG_sD, tcgen05_bSG_gD_partitioned = cute.nvgpu.cpasync.tma_partition(tcgen05_tma_store_atom, 0, cute.make_layout(1), cute.group_modes(tcgen05_sD, 0, 2), cute.group_modes(tcgen05_tCgC_epi, 0, 2)) + tcgen05_bSG_gD = tcgen05_bSG_gD_partitioned[None, None, None, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int32(0)] + tcgen05_bSG_gD = cute.group_modes(tcgen05_bSG_gD, 1, cute.rank(tcgen05_bSG_gD)) + tcgen05_tTR_tAcc_stage = tcgen05_tTR_tAcc_base[None, None, None, None, None, tcgen05_acc_consumer_state.index] + tcgen05_tTR_tAcc = cute.group_modes(tcgen05_tTR_tAcc_stage, 3, cute.rank(tcgen05_tTR_tAcc_stage)) + tcgen05_subtile_count = cutlass.const_expr(cute.size(tcgen05_tTR_tAcc.shape, mode=[3])) + for _tcgen05_subtile in cutlass.range(tcgen05_subtile_count, unroll_full=True): + if _tcgen05_subtile != 0 and tcgen05_warp_idx == cutlass.Int32(0): + tcgen05_c_pipeline.producer_acquire() + if _tcgen05_subtile == 0: + tcgen05_acc_pipeline.consumer_wait(tcgen05_acc_consumer_state) + tcgen05_tTR_tAcc_mn = tcgen05_tTR_tAcc[None, None, None, cutlass.Int32(_tcgen05_subtile)] + cute.copy(tcgen05_tiled_copy_t2r, tcgen05_tTR_tAcc_mn, tcgen05_tTR_rAcc) + tcgen05_acc_vec = tcgen05_tRS_rAcc.load().to(cutlass.BFloat16) + if _tcgen05_subtile == tcgen05_subtile_count - 1: + cute.arch.fence_view_async_tmem_load() + with cute.arch.elect_one(): + tcgen05_acc_pipeline.consumer_release(tcgen05_acc_consumer_state) + tcgen05_tRS_rD.store(tcgen05_acc_vec) + tcgen05_epilog_sync_barrier.arrive_and_wait() + tcgen05_c_buffer = (tcgen05_tma_store_role_tile * cutlass.Int32(tcgen05_subtile_count) + cutlass.Int32(_tcgen05_subtile)) % cutlass.Int32(2) + cute.copy(tcgen05_tiled_copy_r2s, tcgen05_tRS_rD, tcgen05_tRS_sD[None, None, None, tcgen05_c_buffer]) + cute.arch.fence_view_async_shared() + tcgen05_epilog_sync_barrier.arrive_and_wait() + if tcgen05_warp_idx == cutlass.Int32(0): + cute.copy(tcgen05_tma_store_atom, tcgen05_bSG_sD[None, tcgen05_c_buffer], tcgen05_bSG_gD[None, cutlass.Int32(_tcgen05_subtile)]) + tcgen05_c_pipeline.producer_commit() + if tcgen05_epi_active: + tcgen05_acc_consumer_state.advance() + tcgen05_tma_store_role_tile = tcgen05_tma_store_role_tile + cutlass.Int32(1) + tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + tcgen05_role_local_2_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) + tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) + tcgen05_sched_pipeline_consumer_state.advance() + cute.arch.sync_warp() + if cute.arch.make_warp_uniform(cute.arch.warp_idx()) == cutlass.Int32(6): + tcgen05_grouped_selected_sched = cutlass.utils.StaticPersistentGroupTileScheduler.create(tcgen05_grouped_tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim(), (128, 128, 64), cutlass.utils.create_initial_search_state(), 16, tcgen05_grouped_problem_sizes) + tcgen05_grouped_selected_work_tile = tcgen05_grouped_selected_sched.initial_work_tile_info() + while tcgen05_grouped_selected_work_tile.is_valid_tile: + if cute.arch.lane_idx() == cutlass.Int32(0): + tcgen05_sched_pipeline.producer_acquire(tcgen05_sched_pipeline_producer_state) + tcgen05_grouped_selected_group_search_result = tcgen05_grouped_selected_work_tile.group_search_result + tcgen05_grouped_selected_metadata_idx = tcgen05_grouped_selected_group_search_result.group_idx + tcgen05_grouped_selected_group_idx = tcgen05_grouped_selected_metadata_idx + tcgen05_grouped_selected_cta_tile_idx_m = tcgen05_grouped_selected_group_search_result.cta_tile_idx_m >> cutlass.Int32(1) + tcgen05_grouped_selected_cta_tile_idx_n = tcgen05_grouped_selected_group_search_result.cta_tile_idx_n + tcgen05_grouped_panel_local_index = tcgen05_grouped_selected_sched._current_work_linear_idx - tcgen05_grouped_selected_sched.search_state.tile_count_prev_group + tcgen05_grouped_panel_m_clusters = (tcgen05_grouped_selected_group_search_result.problem_shape_m + cutlass.Int32(128) - 1) // cutlass.Int32(128) + tcgen05_grouped_panel_n_clusters = (tcgen05_grouped_selected_group_search_result.problem_shape_n + cutlass.Int32(128) - 1) // cutlass.Int32(128) + tcgen05_grouped_panel_size = cutlass.min(cutlass.Int32(4), tcgen05_grouped_panel_n_clusters) + tcgen05_grouped_panel_span = tcgen05_grouped_panel_size * tcgen05_grouped_panel_m_clusters + tcgen05_grouped_panel_index = tcgen05_grouped_panel_local_index // tcgen05_grouped_panel_span + tcgen05_grouped_panel_linear = tcgen05_grouped_panel_local_index % tcgen05_grouped_panel_span + tcgen05_grouped_panel_width = cutlass.min(tcgen05_grouped_panel_size, tcgen05_grouped_panel_n_clusters - tcgen05_grouped_panel_index * tcgen05_grouped_panel_size) + tcgen05_grouped_selected_cta_tile_idx_m = tcgen05_grouped_panel_linear // tcgen05_grouped_panel_width + tcgen05_grouped_selected_cta_tile_idx_n = (tcgen05_grouped_panel_index * tcgen05_grouped_panel_size + tcgen05_grouped_panel_linear % tcgen05_grouped_panel_width) * cutlass.Int32(1) + tcgen05_grouped_selected_cta_tile_idx_n % cutlass.Int32(1) + if tcgen05_grouped_panel_index % cutlass.Int32(2) == cutlass.Int32(1): + tcgen05_grouped_selected_cta_tile_idx_m = tcgen05_grouped_panel_m_clusters - cutlass.Int32(1) - tcgen05_grouped_selected_cta_tile_idx_m + tcgen05_work_tile_smem[cutlass.Int32(0)] = tcgen05_grouped_selected_cta_tile_idx_m + tcgen05_work_tile_smem[cutlass.Int32(1)] = tcgen05_grouped_selected_cta_tile_idx_n + tcgen05_work_tile_smem[cutlass.Int32(2)] = cutlass.Int32(1) + tcgen05_work_tile_smem[cutlass.Int32(4)] = tcgen05_grouped_selected_group_idx + tcgen05_work_tile_smem[cutlass.Int32(5)] = tcgen05_grouped_selected_group_search_result.problem_shape_m + tcgen05_work_tile_smem[cutlass.Int32(6)] = tcgen05_grouped_selected_group_search_result.problem_shape_n + tcgen05_work_tile_smem[cutlass.Int32(8)] = (tcgen05_grouped_starts.iterator + tcgen05_grouped_selected_metadata_idx * cutlass.Int32(tcgen05_grouped_starts.layout.stride[0])).load() + tcgen05_sched_pipeline.producer_commit(tcgen05_sched_pipeline_producer_state) + tcgen05_sched_pipeline_producer_state.advance() + cute.arch.sync_warp() + tcgen05_grouped_selected_sched.advance_to_next_work() + tcgen05_grouped_selected_work_tile = tcgen05_grouped_selected_sched.get_current_work() + if cute.arch.lane_idx() == cutlass.Int32(0): + tcgen05_sched_pipeline.producer_acquire(tcgen05_sched_pipeline_producer_state) + tcgen05_work_tile_smem[cutlass.Int32(2)] = cutlass.Int32(0) + tcgen05_sched_pipeline.producer_commit(tcgen05_sched_pipeline_producer_state) + tcgen05_sched_pipeline_producer_state.advance() + cute.arch.sync_warp() + if tcgen05_tma_warp: + tcgen05_ab_pipeline.producer_tail(tcgen05_ab_producer_state) + if tcgen05_exec_active: + cute.arch.griddepcontrol_launch_dependents() + if tcgen05_exec_active: + tcgen05_tmem_alloc_barrier.arrive() + if tcgen05_exec_active: + tcgen05_acc_pipeline.producer_tail(tcgen05_acc_producer_state) + tcgen05_tmem_allocator = cutlass.utils.TmemAllocator(tcgen05_tmem_holding_buf, barrier_for_retrieve=tcgen05_tmem_alloc_barrier, allocator_warp_id=0, is_two_cta=True, two_cta_tmem_dealloc_mbar_ptr=tcgen05_tmem_dealloc_mbar_ptr, num_allocated_columns=tcgen05_acc_tmem_cols, initialize_mbarrier=False) + if tcgen05_epi_active: + tcgen05_tmem_alloc_barrier.arrive_and_wait() + if tcgen05_epi_active: + tcgen05_tmem_allocator.free(tcgen05_epi_acc_tmem_ptr) + if tcgen05_warp_idx == cutlass.Int32(0): + tcgen05_c_pipeline.producer_tail() +_helion__grouped_offsets_k64._helion_cute_use_pdl = True +_helion__grouped_offsets_k64._helion_cute_wrapper_plans = [{'kind': 'tcgen05_grouped_static_persistent', 'scheduler_mode': 'device_group_search', 'm_tail_preserve': False, 'n_tail_preserve': False, 'group_count': 16, 'bm': 128, 'bn': 128, 'bk': 64, 'source_m_tile': 128, 'cluster_m': 2, 'cluster_n': 1, 'l2_swizzle_size': 4, 'device_panel_swizzle': True, 'n_size': 1536, 'device_split_sizes': True, 'device_layout_kind': 'offsets', 'm_size': 2048, 'k_total_size': 2048, 'problem_sizes_arg': 'tcgen05_grouped_problem_sizes', 'starts_arg': 'tcgen05_grouped_starts', 'sched_params_arg': 'tcgen05_grouped_tile_sched_params', 'total_clusters_arg': 'tcgen05_grouped_total_clusters', 'worklist_metadata': True, 'dynamic_ab_tensormaps': True, 'immutable_ab_tensormaps': True, 'bounded_output_shift': True, 'dynamic_ab_tensormap_rank': 2, 'lhs_idx': 1, 'rhs_idx': 2, 'layout_idx': 0, 'layout_bind_idx': 2}, {'kind': 'tcgen05_ab_tma', 'bm': 128, 'bn': 128, 'bk': 64, 'cluster_m': 2, 'cluster_n': 1, 'ab_stage_count': 13, 'input_dtype': 'cutlass.BFloat16', 'acc_dtype': 'cutlass.Float32', 'm_size': 2048, 'n_size': 1536, 'k_total_size': 2048, 'kernel_args': ['tma_atom_a', 'tma_tensor_a', 'tma_atom_b', 'tma_tensor_b'], 'full_allocation_a': True, 'full_allocation_b': True, 'source_m_tile': 128, 'device_split_sizes': True, 'device_layout_kind': 'offsets', 'use_2cta_instrs': True, 'b_k_major': True, 'rhs_rank3_grouped_nt': True, 'dynamic_ab_tensormaps': True, 'dynamic_ab_tensormap_rank': 2, 'use_pdl': True, 'lhs_idx': 1, 'rhs_idx': 2}, {'kind': 'tcgen05_d_tma', 'bm': 128, 'bn': 128, 'c_stage_count': 2, 'output_dtype': 'cutlass.BFloat16', 'kernel_args': ['tcgen05_tma_store_atom', 'tcgen05_tma_store_tensor'], 'rank3_mnl_tensor': True, 'bounded_output_shift': True, 'epi_tile_raw_expr': 'cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape((64, 128), True, cutlass.utils.layout.LayoutEnum.ROW_MAJOR, cutlass.BFloat16)', 'd_idx': 3}] +_helion__grouped_offsets_k64._helion_cute_cluster_shape = (2, 1, 1) + +def _grouped_offsets_k64(a: torch.Tensor, weights: torch.Tensor, offsets: torch.Tensor, *, _launcher=_default_cute_launcher): + _helion__grouped_offsets_k64._helion_cute_disable_bake_tensor_shapes = True + rows, reduction = a.shape + groups, columns, _ = weights.shape + out = torch.empty((rows, columns), device=a.device, dtype=a.dtype) + _NUM_SM = helion.runtime.get_num_sm(a.device) + _BLOCK_SIZE_0 = 256 + _BLOCK_SIZE_1 = 128 + _launcher(_helion__grouped_offsets_k64, (2, 1, min((16 * 2 + 2 - 1) // 2 * ((2048 + _BLOCK_SIZE_0 - 1) // _BLOCK_SIZE_0) * ((1536 + _BLOCK_SIZE_1 - 1) // _BLOCK_SIZE_1), max(1, _NUM_SM // 2))), offsets, a, weights, out, block=(32, 8, 1)) + return out diff --git a/test/test_cute_grouped_worklist_codegen.py b/test/test_cute_grouped_worklist_codegen.py new file mode 100644 index 0000000000..dee4e57b0e --- /dev/null +++ b/test/test_cute_grouped_worklist_codegen.py @@ -0,0 +1,86 @@ +"""CPU-only grouped worklist code generation and legality checks.""" + +from __future__ import annotations + +import pytest +import torch + +import helion +from helion._testing import TestCase +from helion._testing import cpu_render_target +from helion._testing.cute_codegen import cpu_bind +from helion._testing.cute_codegen import forbid_cuda_work +from helion._testing.cute_codegen import mock_cuda_unavailable +from helion._testing.cute_codegen import tcgen05_mma_support +from helion._testing.cute_codegen import tcgen05_target +from helion._testing.cute_grouped_gemm import _grouped_offsets_k64 +from helion._testing.cute_grouped_gemm import _unsupported_k_loop +from helion._testing.cute_grouped_gemm import grouped_ab_k_args +from helion._testing.cute_grouped_gemm import grouped_ab_k_config +from helion._testing.cute_grouped_gemm import grouped_d_shift_args +from helion._testing.cute_grouped_gemm import grouped_d_shift_config +from helion.exc import BackendUnsupported +from helion.exc import InvalidConfig + +pytestmark = pytest.mark.cpu_only + + +@pytest.mark.parametrize("variant", [1, 2, 3, 5]) +def test_noncanonical_k_loops_cannot_request_physical128(variant: int) -> None: + with forbid_cuda_work(), tcgen05_target(), mock_cuda_unavailable(): + args = (*grouped_ab_k_args(), variant) + bound = cpu_bind(_unsupported_k_loop, args) + assert not bound.config_spec._cute_tcgen05_config.grouped_ab_k_fusion_supported + with pytest.raises((InvalidConfig, BackendUnsupported)): + bound.to_code(grouped_ab_k_config(2)) + + +@pytest.mark.parametrize("variant", [1, 2, 3, 5]) +def test_noncanonical_reductions_cannot_request_bounded_d_shift(variant: int) -> None: + with forbid_cuda_work(), tcgen05_target(), mock_cuda_unavailable(): + args = (*grouped_d_shift_args("fp32", torch.int32), variant) + bound = cpu_bind(_unsupported_k_loop, args) + assert not bound.config_spec._cute_tcgen05_config.grouped_d_shift_supported + with pytest.raises((InvalidConfig, BackendUnsupported)): + bound.to_code(grouped_d_shift_config("mn")) + + +class TestRoleLocalGroupedRenders(TestCase): + def test_p2_panel_raster(self) -> None: + pytest.importorskip("cutlass.cute") + # The MN orientation with an L2 swizzle: the scheduler warp walks M,N + # panels and publishes the panel-local index. + config = helion.Config( + block_sizes=[256, 128, 64], + l2_groupings=[1], + loop_orders=[[0, 1, 2]], + num_stages=7, + num_warps=8, + pid_type="persistent_interleaved", + tcgen05_cluster_m=2, + tcgen05_cluster_n=1, + tcgen05_ab_stages=13, + tcgen05_acc_stages=2, + tcgen05_c_stages=2, + tcgen05_num_epi_warps=4, + tcgen05_consumer_regs=256, + tcgen05_grouped_mode="worklist_nm", + tcgen05_grouped_worklist_orientation="mn", + tcgen05_grouped_worklist_source_m_tile=128, + tcgen05_grouped_worklist_mma_n=128, + tcgen05_grouped_d_shift=True, + tcgen05_grouped_full_allocation_a=True, + tcgen05_l2_swizzle_size=4, + ) + args = ( + torch.empty((2048, 2048), dtype=torch.bfloat16), + torch.empty((16, 1536, 2048), dtype=torch.bfloat16), + torch.arange(17, dtype=torch.int32) * 128, + ) + with cpu_render_target(mma_support=tcgen05_mma_support()): + bound = cpu_bind(_grouped_offsets_k64, args) + code = bound.to_code(config, output_origin_lines=False) + self.assertIn("tcgen05_grouped_panel_local_index", code) + self.assertIn("StaticPersistentGroupTileScheduler.create", code) + self.assertIn("tcgen05_role_local_0_valid", code) + self.assertExpectedJournal(code) diff --git a/test/test_cute_role_local_grouped_renders.expected_cute b/test/test_cute_role_local_grouped_renders.expected_cute index 076a7cffdd..42633fb18f 100644 --- a/test/test_cute_role_local_grouped_renders.expected_cute +++ b/test/test_cute_role_local_grouped_renders.expected_cute @@ -3480,385 +3480,3 @@ def _selected_kernel(a_packed: torch.Tensor, b_grouped: torch.Tensor, work_tile_ raise _global_source0.OverflowError('root grid count exceeds signed Int64') _launcher(_helion__selected_kernel, (2, 1, min((4 * 2 + 2 - 1) // 2 * ((256 + _BLOCK_SIZE_0 - 1) // _BLOCK_SIZE_0) * ((224 + _BLOCK_SIZE_1 - 1) // _BLOCK_SIZE_1), max(1, _NUM_SM // 2))), work_tile_metadata, a_packed, b_grouped, out, work_tile_metadata.size(0), block=(32, 8, 1)) return out - ---- assertExpectedJournal(TestRoleLocalGroupedRenders.test_p2_panel_raster) -from __future__ import annotations - -import torch -import helion -import cutlass -import cutlass.cute as cute -from helion.runtime import default_cute_launcher as _default_cute_launcher -import helion._compiler.cute._tcgen05_prologue_runtime as _helion_tc_pro - -_BLOCK_SIZE_0 = 256 -_BLOCK_SIZE_2 = 64 - -@cute.kernel -def _helion__grouped_offsets_k64(offsets, a, weights, out, tcgen05_grouped_tile_sched_params, tma_atom_a, tma_tensor_a, tma_atom_b, tma_tensor_b, tcgen05_tma_store_atom, tcgen05_tma_store_tensor): - cute.arch.griddepcontrol_wait() - cute.arch.griddepcontrol_launch_dependents() - tcgen05_work_tile_smem_ptr = cute.arch.alloc_smem(cutlass.Int32, 9, alignment=16) - tcgen05_work_tile_smem_tensor = cute.make_tensor(tcgen05_work_tile_smem_ptr, cute.make_layout((9,), stride=(1,))) - tcgen05_work_tile_smem = tcgen05_work_tile_smem_tensor - num_blocks_0 = 16 - num_blocks_1 = (2048 + _BLOCK_SIZE_0 - 1) // _BLOCK_SIZE_0 - pass - pass - start = cutlass.Int32(0) - pass - pass - pass - pass - v_3 = cutlass.Int32(0) - v_4 = cutlass.Int32(0) - v_5 = cutlass.Boolean(0) - acc = cutlass.Float32(0.0) - tcgen05_grouped_problem_sizes_smem_ptr = cute.arch.alloc_smem(cutlass.Int32, 64, alignment=16) - tcgen05_grouped_problem_sizes = cute.make_tensor(tcgen05_grouped_problem_sizes_smem_ptr, cute.make_layout((16, 4), stride=(4, 1))) - tcgen05_grouped_starts_smem_ptr = cute.arch.alloc_smem(cutlass.Int32, 16, alignment=16) - tcgen05_grouped_starts = cute.make_tensor(tcgen05_grouped_starts_smem_ptr, cute.make_layout((16,), stride=(1,))) - tcgen05_grouped_metadata_thread_idx = cute.arch.thread_idx() - tcgen05_grouped_metadata_block_dim = cute.arch.block_dim() - for tcgen05_grouped_metadata_group in cutlass.range(tcgen05_grouped_metadata_thread_idx[0] + tcgen05_grouped_metadata_block_dim[0] * (tcgen05_grouped_metadata_thread_idx[1] + tcgen05_grouped_metadata_block_dim[1] * tcgen05_grouped_metadata_thread_idx[2]), 16, tcgen05_grouped_metadata_block_dim[0] * tcgen05_grouped_metadata_block_dim[1] * tcgen05_grouped_metadata_block_dim[2], unroll=1): - tcgen05_grouped_raw_start = cutlass.Int32((offsets.iterator + cutlass.Int64(tcgen05_grouped_metadata_group) * cutlass.Int64(offsets.layout.stride[0])).load()) - tcgen05_grouped_raw_end = cutlass.Int32((offsets.iterator + cutlass.Int64(tcgen05_grouped_metadata_group + 1) * cutlass.Int64(offsets.layout.stride[0])).load()) - tcgen05_grouped_raw_extent = max(tcgen05_grouped_raw_end - tcgen05_grouped_raw_start, cutlass.Int32(0)) - tcgen05_grouped_source_end = tcgen05_grouped_raw_start + min(tcgen05_grouped_raw_extent, cutlass.Int32(2048)) - tcgen05_grouped_visible_start = min(max(tcgen05_grouped_raw_start, cutlass.Int32(0)), cutlass.Int32(2048)) - tcgen05_grouped_visible_end = min(max(tcgen05_grouped_source_end, cutlass.Int32(0)), cutlass.Int32(2048)) - tcgen05_grouped_visible_extent = max(tcgen05_grouped_visible_end - tcgen05_grouped_visible_start, cutlass.Int32(0)) if tcgen05_grouped_raw_extent > cutlass.Int32(0) else cutlass.Int32(0) - tcgen05_grouped_starts[cutlass.Int32(tcgen05_grouped_metadata_group)] = cutlass.Int32(tcgen05_grouped_visible_start) - tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(0)] = cutlass.Int32(tcgen05_grouped_visible_extent) - tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(1)] = cutlass.Int32(1536) - tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(2)] = cutlass.Int32(2048) - tcgen05_grouped_problem_sizes[cutlass.Int32(tcgen05_grouped_metadata_group), cutlass.Int32(3)] = cutlass.Int32(1) - cute.arch.sync_threads() - tcgen05_warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) - tcgen05_lane_idx = cute.arch.lane_idx() - mma_tidx = cutlass.Int32(cute.arch.thread_idx()[0]) + cutlass.Int32(cute.arch.thread_idx()[1]) * cutlass.Int32(32) - mma_copy_tidx = mma_tidx - mma_active = cutlass.Int32(cute.arch.thread_idx()[1]) < cutlass.Int32(2) - tcgen05_tma_warp = tcgen05_warp_idx == cutlass.Int32(5) - tcgen05_exec_active = tcgen05_warp_idx == cutlass.Int32(4) - tcgen05_epi_active = tcgen05_warp_idx < cutlass.Int32(4) - tcgen05_epi_tidx = tcgen05_lane_idx + tcgen05_warp_idx * cutlass.Int32(32) if tcgen05_epi_active else cutlass.Int32(0) - if not tcgen05_epi_active: - cute.arch.setmaxregister_decrease(120) - if tcgen05_epi_active: - cute.arch.setmaxregister_increase(256) - mma_slice_tidx = _helion_tc_pro.mod_nonneg(cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()), 2) - tiled_mma = cutlass.utils.blackwell_helpers.make_trivial_tiled_mma(cutlass.BFloat16, cutlass.BFloat16, cute.nvgpu.OperandMajorMode.K, cute.nvgpu.OperandMajorMode.K, cutlass.Float32, cute.nvgpu.tcgen05.CtaGroup.TWO, (128, 128), cute.nvgpu.tcgen05.OperandSource.SMEM) - thr_mma = tiled_mma.get_slice(mma_slice_tidx) - tcgen05_cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((2, 1, 1)), (tiled_mma.thr_id.shape,)) - sA_layout = cutlass.utils.blackwell_helpers.make_smem_layout_a(tiled_mma, (128, 128, 64), cutlass.BFloat16, 13) - sB_layout = cutlass.utils.blackwell_helpers.make_smem_layout_b(tiled_mma, (128, 128, 64), cutlass.BFloat16, 13, is_k_major=True) - tcgen05_c_layout = cutlass.utils.layout.LayoutEnum.ROW_MAJOR - tcgen05_epi_tile = cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape((64, 128), True, tcgen05_c_layout, cutlass.BFloat16) - tcgen05_tmem_load_atom = cutlass.utils.blackwell_helpers.get_tmem_load_op((64, 128, 64), tcgen05_c_layout, cutlass.Float32, cutlass.Float32, tcgen05_epi_tile, True) - tcgen05_epilogue_rest_mode = cute.make_layout(1, stride=0) - acc_frag_base = tiled_mma.make_fragment_C(cute.append(tiled_mma.partition_shape_C((128, 128)), 2)) - tcgen05_acc_tmem_cols = cutlass.utils.get_num_tmem_alloc_cols(acc_frag_base, arch='sm_100') - tcgen05_tmem_holding_buf = cute.arch.alloc_smem(cutlass.Int32, 1) - tcgen05_tmem_dealloc_mbar_ptr = cute.arch.alloc_smem(cutlass.Int64, 1) - tcgen05_tmem_alloc_barrier = cutlass.pipeline.NamedBarrier(barrier_id=1, num_threads=160) - tcgen05_tmem_allocator = cutlass.utils.TmemAllocator(tcgen05_tmem_holding_buf, barrier_for_retrieve=tcgen05_tmem_alloc_barrier, allocator_warp_id=0, is_two_cta=True, two_cta_tmem_dealloc_mbar_ptr=tcgen05_tmem_dealloc_mbar_ptr, initialize_mbarrier=False) - tcgen05_acc_pipeline_barriers = cute.arch.alloc_smem(cutlass.Int64, cutlass.Int32(4)) - tcgen05_acc_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread) - tcgen05_acc_pipeline_consumer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(8)) - tcgen05_acc_pipeline = _helion_tc_pro.make_umma_async_pipeline(num_stages=2, producer_group=tcgen05_acc_pipeline_producer_group, consumer_group=tcgen05_acc_pipeline_consumer_group, barrier_storage=tcgen05_acc_pipeline_barriers, cta_layout_vmnk=tcgen05_cluster_layout_vmnk) - tcgen05_acc_producer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Producer, 2) - tcgen05_acc_consumer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Consumer, 2) - tcgen05_sched_pipeline_mbars = cute.arch.alloc_smem(cutlass.Int64, cutlass.Int32(2)) - tcgen05_sched_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, 1) - tcgen05_sched_pipeline_consumer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(192)) - tcgen05_sched_pipeline = cutlass.pipeline.PipelineAsync.create(num_stages=1, producer_group=tcgen05_sched_pipeline_producer_group, consumer_group=tcgen05_sched_pipeline_consumer_group, barrier_storage=tcgen05_sched_pipeline_mbars, defer_sync=True) - tcgen05_sched_pipeline_producer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Producer, 1) - tcgen05_sched_pipeline_consumer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Consumer, 1) - if tcgen05_tma_warp: - cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_a) - cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_b) - smem_a = cute.arch.alloc_smem(cutlass.BFloat16, cute.cosize(sA_layout.outer), alignment=128) - sA = cute.make_tensor(cute.recast_ptr(smem_a, sA_layout.inner, dtype=cutlass.BFloat16), sA_layout.outer) - smem_b = cute.arch.alloc_smem(cutlass.BFloat16, cute.cosize(sB_layout.outer), alignment=128) - sB = cute.make_tensor(cute.recast_ptr(smem_b, sB_layout.inner, dtype=cutlass.BFloat16), sB_layout.outer) - tcgen05_tCrA = tiled_mma.make_fragment_A(sA) - tcgen05_tCrB = tiled_mma.make_fragment_B(sB) - sA_tma_layout = cute.slice_(sA_layout, (None, None, None, 0)) - sB_tma_layout = cute.slice_(sB_layout, (None, None, None, 0)) - tma_thr_mma = tiled_mma.get_slice(mma_slice_tidx) - tma_a_cta_layout = cute.make_layout(cute.slice_(tcgen05_cluster_layout_vmnk, (0, 0, None, 0)).shape) - tma_b_cta_layout = cute.make_layout(cute.slice_(tcgen05_cluster_layout_vmnk, (0, None, 0, 0)).shape) - tcgen05_cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) & cutlass.Int32(1) - tcgen05_block_in_cluster_coord_vmnk = tcgen05_cluster_layout_vmnk.get_flat_coord(tcgen05_cta_rank_in_cluster) - tma_a_cta_coord = tcgen05_block_in_cluster_coord_vmnk[2] - tma_b_cta_coord = tcgen05_block_in_cluster_coord_vmnk[1] - tcgen05_a_mcast_mask = cute.nvgpu.cpasync.create_tma_multicast_mask(tcgen05_cluster_layout_vmnk, tcgen05_block_in_cluster_coord_vmnk, mcast_mode=2) - tcgen05_b_mcast_mask = cute.nvgpu.cpasync.create_tma_multicast_mask(tcgen05_cluster_layout_vmnk, tcgen05_block_in_cluster_coord_vmnk, mcast_mode=1) - tcgen05_ab_pipeline_mbars = cute.arch.alloc_smem(cutlass.Int64, cutlass.Int32(26)) - tcgen05_ab_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, 1) - tcgen05_ab_pipeline_consumer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(1)) - tcgen05_ab_pipeline_tx_count = (cute.size_in_bytes(cutlass.BFloat16, sA_tma_layout) + cute.size_in_bytes(cutlass.BFloat16, sB_tma_layout)) * cute.size(tiled_mma.thr_id.shape) - tcgen05_ab_pipeline = _helion_tc_pro.make_tma_umma_pipeline(num_stages=13, producer_group=tcgen05_ab_pipeline_producer_group, consumer_group=tcgen05_ab_pipeline_consumer_group, tx_count=tcgen05_ab_pipeline_tx_count, barrier_storage=tcgen05_ab_pipeline_mbars, cta_layout_vmnk=tcgen05_cluster_layout_vmnk) - tcgen05_ab_producer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Producer, 13) - tcgen05_ab_consumer_state = cutlass.pipeline.make_pipeline_state(cutlass.pipeline.PipelineUserType.Consumer, 13) - if not tcgen05_tma_warp: - if tcgen05_warp_idx == cutlass.Int32(0): - with cute.arch.elect_one(): - cute.arch.mbarrier_init(tcgen05_tmem_dealloc_mbar_ptr, 32) - _helion_tc_pro.init_pipeline_barriers(tcgen05_warp_idx, (0,), tcgen05_acc_pipeline) - if tcgen05_warp_idx == cutlass.Int32(0): - cute.nvgpu.cpasync.prefetch_descriptor(tcgen05_tma_store_atom) - _helion_tc_pro.init_pipeline_barriers_pair(tcgen05_warp_idx, 1, tcgen05_ab_pipeline) - cutlass.pipeline.pipeline_init_arrive(cluster_shape_mn=tcgen05_cluster_layout_vmnk, is_relaxed=True) - cutlass.pipeline.pipeline_init_wait(cluster_shape_mn=tcgen05_cluster_layout_vmnk) - if tcgen05_epi_active: - tcgen05_tmem_allocator.allocate(tcgen05_acc_tmem_cols) - tcgen05_tmem_allocator.relinquish_alloc_permit() - tcgen05_exec_acc_tmem_ptr = cute.make_ptr(cutlass.Float32, 0, cute.AddressSpace.tmem, assumed_align=16) - tcgen05_epi_acc_tmem_ptr = cute.make_ptr(cutlass.Float32, 0, cute.AddressSpace.tmem, assumed_align=16) - cute.arch.sync_threads() - if tcgen05_exec_active or tcgen05_epi_active: - tcgen05_tmem_allocator.wait_for_alloc() - if tcgen05_exec_active: - tcgen05_exec_acc_tmem_ptr = tcgen05_tmem_allocator.retrieve_ptr(cutlass.Float32) - if tcgen05_epi_active: - tcgen05_epi_acc_tmem_ptr = tcgen05_tmem_allocator.retrieve_ptr(cutlass.Float32) - tcgen05_exec_acc_frag_base = cute.make_tensor(tcgen05_exec_acc_tmem_ptr, acc_frag_base.layout) - tcgen05_epi_acc_frag_base = cute.make_tensor(tcgen05_epi_acc_tmem_ptr, acc_frag_base.layout) - tcgen05_epilog_sync_barrier = cutlass.pipeline.NamedBarrier(barrier_id=cutlass.Int32(2), num_threads=cutlass.Int32(128)) - tcgen05_c_pipeline_producer_group = cutlass.pipeline.CooperativeGroup(cutlass.pipeline.Agent.Thread, cutlass.Int32(128)) - tcgen05_c_pipeline = cutlass.pipeline.PipelineTmaStore.create(num_stages=2, producer_group=tcgen05_c_pipeline_producer_group) - tcgen05_kernel_desc = type('Tcgen05KernelDesc', (), {'cta_tile_shape_mnk': (64, 128, 64), 'c_layout': cutlass.utils.layout.LayoutEnum.ROW_MAJOR, 'c_dtype': cutlass.BFloat16, 'acc_dtype': cutlass.Float32, 'epilog_sync_bar_id': cutlass.Int32(2), 'epilogue_warp_id': (cutlass.Int32(0), cutlass.Int32(1), cutlass.Int32(2), cutlass.Int32(3)), 'num_c_stage': cutlass.Int32(2), 'use_2cta_instrs': True})() - tcgen05_store_epi_tile = cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape((64, 128), True, cutlass.utils.layout.LayoutEnum.ROW_MAJOR, cutlass.BFloat16) - tcgen05_sD_layout = cutlass.utils.blackwell_helpers.make_smem_layout_epi(cutlass.BFloat16, cutlass.utils.layout.LayoutEnum.ROW_MAJOR, tcgen05_store_epi_tile, 2) - tcgen05_sD_ptr = cute.arch.alloc_smem(cutlass.BFloat16, cute.cosize(tcgen05_sD_layout.outer), alignment=1024) - tcgen05_sD = cute.make_tensor(cute.recast_ptr(tcgen05_sD_ptr, tcgen05_sD_layout.inner, dtype=cutlass.BFloat16), tcgen05_sD_layout.outer) - tcgen05_tAcc = cutlass.utils.gemm.sm100.transform_partitioned_tensor_layout(tcgen05_epi_acc_frag_base) - if cute.arch.make_warp_uniform(cute.arch.warp_idx()) == cutlass.Int32(5): - cute.arch.griddepcontrol_wait() - cute.arch.griddepcontrol_launch_dependents() - tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) - cute.arch.fence_view_async_shared() - cute.arch.sync_warp() - tcgen05_role_local_0_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) - while tcgen05_role_local_0_valid: - tcgen05_grouped_cta_tile_idx_m = tcgen05_work_tile_smem[cutlass.Int32(0)] - tcgen05_grouped_cta_tile_idx_n = tcgen05_work_tile_smem[cutlass.Int32(1)] - tcgen05_grouped_group_idx = tcgen05_work_tile_smem[cutlass.Int32(4)] - tcgen05_grouped_problem_m = tcgen05_work_tile_smem[cutlass.Int32(5)] - tcgen05_grouped_problem_n = tcgen05_work_tile_smem[cutlass.Int32(6)] - tcgen05_grouped_global_m_start = tcgen05_work_tile_smem[cutlass.Int32(8)] - tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) - tcgen05_sched_pipeline_consumer_state.advance() - cute.arch.sync_warp() - gA_tma = cute.local_tile(cute.domain_offset((tcgen05_grouped_global_m_start, cutlass.Int32(0)), tma_tensor_a), (128, 64), (tcgen05_grouped_cta_tile_idx_m, None)) - gB_tma = cute.local_tile(tma_tensor_b, (128, 64), (tcgen05_grouped_group_idx * cutlass.Int32(12) + tcgen05_grouped_cta_tile_idx_n, None)) - gA_tma_part = tma_thr_mma.partition_A(gA_tma) - gB_tma_part = tma_thr_mma.partition_B(gB_tma) - tma_sA, tma_gA = cute.nvgpu.cpasync.tma_partition(tma_atom_a, tma_a_cta_coord, tma_a_cta_layout, cute.group_modes(sA, 0, cute.rank(sA) - 1), cute.group_modes(gA_tma_part, 0, cute.rank(gA_tma_part) - 1)) - tma_sB, tma_gB = cute.nvgpu.cpasync.tma_partition(tma_atom_b, tma_b_cta_coord, tma_b_cta_layout, cute.group_modes(sB, 0, cute.rank(sB) - 1), cute.group_modes(gB_tma_part, 0, cute.rank(gB_tma_part) - 1)) - for tile_offset_2 in range(cutlass.Int32(0), cutlass.Int32(2048), cutlass.Int32(_BLOCK_SIZE_2)): - tcgen05_tma_k_tile = _helion_tc_pro.floordiv_nonneg(tile_offset_2, 64) - tcgen05_tma_full_tile = tcgen05_grouped_cta_tile_idx_m * cutlass.Int32(128) < tcgen05_grouped_problem_m and tcgen05_grouped_cta_tile_idx_n * cutlass.Int32(128) < tcgen05_grouped_problem_n and (tile_offset_2 < cutlass.Int32(2048)) - tcgen05_ab_producer_try_token = cutlass.Boolean(0) - if tcgen05_tma_full_tile: - tcgen05_ab_producer_try_token = tcgen05_ab_pipeline.producer_try_acquire(tcgen05_ab_producer_state) - tcgen05_ab_pipeline.producer_acquire(tcgen05_ab_producer_state, tcgen05_ab_producer_try_token) - tcgen05_tma_barrier = tcgen05_ab_pipeline.producer_get_barrier(tcgen05_ab_producer_state) - cute.copy(tma_atom_a, tma_gA[None, tcgen05_tma_k_tile], tma_sA[None, tcgen05_ab_producer_state.index], tma_bar_ptr=tcgen05_tma_barrier, mcast_mask=tcgen05_a_mcast_mask) - cute.copy(tma_atom_b, tma_gB[None, tcgen05_tma_k_tile], tma_sB[None, tcgen05_ab_producer_state.index], tma_bar_ptr=tcgen05_tma_barrier, mcast_mask=tcgen05_b_mcast_mask) - tcgen05_ab_pipeline.producer_commit(tcgen05_ab_producer_state) - tcgen05_ab_producer_state.advance() - tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) - cute.arch.fence_view_async_shared() - cute.arch.sync_warp() - tcgen05_role_local_0_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) - tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) - tcgen05_sched_pipeline_consumer_state.advance() - cute.arch.sync_warp() - if cute.arch.make_warp_uniform(cute.arch.warp_idx()) == cutlass.Int32(4): - tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) - cute.arch.fence_view_async_shared() - cute.arch.sync_warp() - tcgen05_role_local_1_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) - while tcgen05_role_local_1_valid: - tcgen05_grouped_cta_tile_idx_m = tcgen05_work_tile_smem[cutlass.Int32(0)] - tcgen05_grouped_cta_tile_idx_n = tcgen05_work_tile_smem[cutlass.Int32(1)] - tcgen05_grouped_problem_m = tcgen05_work_tile_smem[cutlass.Int32(5)] - tcgen05_grouped_problem_n = tcgen05_work_tile_smem[cutlass.Int32(6)] - tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) - tcgen05_sched_pipeline_consumer_state.advance() - cute.arch.sync_warp() - acc_frag = tcgen05_exec_acc_frag_base[None, None, None, tcgen05_acc_producer_state.index] - tcgen05_ab_consumer_try_token = cutlass.Boolean(1) - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tcgen05_ab_consumer_try_token = tcgen05_ab_pipeline.consumer_try_wait(tcgen05_ab_consumer_state) - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tcgen05_acc_pipeline.producer_acquire(tcgen05_acc_producer_state) - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tiled_mma.set(cute.nvgpu.tcgen05.Field.ACCUMULATE, False) - for tile_offset_2 in range(cutlass.Int32(0), cutlass.Int32(2048), cutlass.Int32(_BLOCK_SIZE_2)): - mma_stage = tcgen05_ab_consumer_state.index - sA_mma = sA[None, None, None, mma_stage] - sB_mma = sB[None, None, None, mma_stage] - tcgen05_tma_full_tile = tcgen05_grouped_cta_tile_idx_m * cutlass.Int32(128) < tcgen05_grouped_problem_m and tcgen05_grouped_cta_tile_idx_n * cutlass.Int32(128) < tcgen05_grouped_problem_n and (tile_offset_2 < cutlass.Int32(2048)) - tcgen05_tma_next_consumer_tile = tile_offset_2 + cutlass.Int32(64) < cutlass.Int32(2048) - if tcgen05_tma_full_tile: - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tcgen05_ab_pipeline.consumer_wait(tcgen05_ab_consumer_state, tcgen05_ab_consumer_try_token) - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - for _tcgen05_kblk_idx in range(cute.size(tcgen05_tCrA, mode=[2])): - cute.gemm(tiled_mma, acc_frag, [tcgen05_tCrA[None, None, cutlass.Int32(_tcgen05_kblk_idx), mma_stage]], [tcgen05_tCrB[None, None, cutlass.Int32(_tcgen05_kblk_idx), mma_stage]], acc_frag) - tiled_mma.set(cute.nvgpu.tcgen05.Field.ACCUMULATE, True) - if tcgen05_tma_full_tile: - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tcgen05_ab_pipeline.consumer_release(tcgen05_ab_consumer_state) - tcgen05_ab_consumer_state.advance() - tcgen05_ab_consumer_try_token = cutlass.Boolean(1) - if tcgen05_tma_next_consumer_tile and cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tcgen05_ab_consumer_try_token = tcgen05_ab_pipeline.consumer_try_wait(tcgen05_ab_consumer_state) - if cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == cutlass.Int32(0): - tcgen05_acc_pipeline.producer_commit(tcgen05_acc_producer_state) - tcgen05_acc_producer_state.advance() - tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) - cute.arch.fence_view_async_shared() - cute.arch.sync_warp() - tcgen05_role_local_1_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) - tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) - tcgen05_sched_pipeline_consumer_state.advance() - cute.arch.sync_warp() - if cute.arch.make_warp_uniform(cute.arch.warp_idx()) < cutlass.Int32(4): - tcgen05_tma_store_role_tile = cutlass.Int32(0) - tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) - cute.arch.fence_view_async_shared() - cute.arch.sync_warp() - tcgen05_role_local_2_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) - while tcgen05_role_local_2_valid: - tcgen05_grouped_cta_tile_idx_m = tcgen05_work_tile_smem[cutlass.Int32(0)] - tcgen05_grouped_cta_tile_idx_n = tcgen05_work_tile_smem[cutlass.Int32(1)] - tcgen05_grouped_problem_m = tcgen05_work_tile_smem[cutlass.Int32(5)] - tcgen05_grouped_global_m_start = tcgen05_work_tile_smem[cutlass.Int32(8)] - tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) - tcgen05_sched_pipeline_consumer_state.advance() - cute.arch.sync_warp() - if True: - if tcgen05_warp_idx == cutlass.Int32(0): - tcgen05_c_pipeline.producer_acquire() - tcgen05_bounded_output = cute.domain_offset((cutlass.Int32(2048) - tcgen05_grouped_problem_m, cutlass.Int32(0), tcgen05_grouped_global_m_start + tcgen05_grouped_problem_m), tcgen05_tma_store_tensor) - tcgen05_gC = cute.local_tile(tcgen05_bounded_output, (128, 128), (tcgen05_grouped_cta_tile_idx_m, tcgen05_grouped_cta_tile_idx_n, 0)) - tcgen05_tCgC_base = thr_mma.partition_C(tcgen05_gC) - tcgen05_tCgC = cutlass.utils.gemm.sm100.transform_partitioned_tensor_layout(tcgen05_tCgC_base) - tcgen05_tCgC_planned = cute.make_tensor(tcgen05_tCgC.iterator, cute.append(cute.append(cute.append(tcgen05_tCgC.layout, tcgen05_epilogue_rest_mode), tcgen05_epilogue_rest_mode), tcgen05_epilogue_rest_mode)) - tcgen05_tiled_copy_t2r, tcgen05_tTR_tAcc_base, tcgen05_tTR_rAcc = cutlass.utils.gemm.sm100.epilogue_tmem_copy_and_partition(tcgen05_kernel_desc, tcgen05_epi_tidx, tcgen05_tAcc, tcgen05_tCgC_planned, tcgen05_store_epi_tile, True) - tcgen05_tTR_rD = cute.make_rmem_tensor(tcgen05_tTR_rAcc.shape, cutlass.BFloat16) - tcgen05_tiled_copy_r2s, tcgen05_tRS_rD, tcgen05_tRS_sD = cutlass.utils.gemm.sm100.epilogue_smem_copy_and_partition(tcgen05_kernel_desc, tcgen05_tiled_copy_t2r, tcgen05_tTR_rD, tcgen05_epi_tidx, tcgen05_sD) - tcgen05_tRS_rAcc = tcgen05_tiled_copy_r2s.retile(tcgen05_tTR_rAcc) - tcgen05_tCgC_epi = cute.flat_divide(tcgen05_tCgC_planned, tcgen05_store_epi_tile) - tcgen05_bSG_sD, tcgen05_bSG_gD_partitioned = cute.nvgpu.cpasync.tma_partition(tcgen05_tma_store_atom, 0, cute.make_layout(1), cute.group_modes(tcgen05_sD, 0, 2), cute.group_modes(tcgen05_tCgC_epi, 0, 2)) - tcgen05_bSG_gD = tcgen05_bSG_gD_partitioned[None, None, None, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int32(0)] - tcgen05_bSG_gD = cute.group_modes(tcgen05_bSG_gD, 1, cute.rank(tcgen05_bSG_gD)) - tcgen05_tTR_tAcc_stage = tcgen05_tTR_tAcc_base[None, None, None, None, None, tcgen05_acc_consumer_state.index] - tcgen05_tTR_tAcc = cute.group_modes(tcgen05_tTR_tAcc_stage, 3, cute.rank(tcgen05_tTR_tAcc_stage)) - tcgen05_subtile_count = cutlass.const_expr(cute.size(tcgen05_tTR_tAcc.shape, mode=[3])) - for _tcgen05_subtile in cutlass.range(tcgen05_subtile_count, unroll_full=True): - if _tcgen05_subtile != 0 and tcgen05_warp_idx == cutlass.Int32(0): - tcgen05_c_pipeline.producer_acquire() - if _tcgen05_subtile == 0: - tcgen05_acc_pipeline.consumer_wait(tcgen05_acc_consumer_state) - tcgen05_tTR_tAcc_mn = tcgen05_tTR_tAcc[None, None, None, cutlass.Int32(_tcgen05_subtile)] - cute.copy(tcgen05_tiled_copy_t2r, tcgen05_tTR_tAcc_mn, tcgen05_tTR_rAcc) - tcgen05_acc_vec = tcgen05_tRS_rAcc.load().to(cutlass.BFloat16) - if _tcgen05_subtile == tcgen05_subtile_count - 1: - cute.arch.fence_view_async_tmem_load() - with cute.arch.elect_one(): - tcgen05_acc_pipeline.consumer_release(tcgen05_acc_consumer_state) - tcgen05_tRS_rD.store(tcgen05_acc_vec) - tcgen05_epilog_sync_barrier.arrive_and_wait() - tcgen05_c_buffer = (tcgen05_tma_store_role_tile * cutlass.Int32(tcgen05_subtile_count) + cutlass.Int32(_tcgen05_subtile)) % cutlass.Int32(2) - cute.copy(tcgen05_tiled_copy_r2s, tcgen05_tRS_rD, tcgen05_tRS_sD[None, None, None, tcgen05_c_buffer]) - cute.arch.fence_view_async_shared() - tcgen05_epilog_sync_barrier.arrive_and_wait() - if tcgen05_warp_idx == cutlass.Int32(0): - cute.copy(tcgen05_tma_store_atom, tcgen05_bSG_sD[None, tcgen05_c_buffer], tcgen05_bSG_gD[None, cutlass.Int32(_tcgen05_subtile)]) - tcgen05_c_pipeline.producer_commit() - if tcgen05_epi_active: - tcgen05_acc_consumer_state.advance() - tcgen05_tma_store_role_tile = tcgen05_tma_store_role_tile + cutlass.Int32(1) - tcgen05_sched_pipeline.consumer_wait(tcgen05_sched_pipeline_consumer_state) - cute.arch.fence_view_async_shared() - cute.arch.sync_warp() - tcgen05_role_local_2_valid = tcgen05_work_tile_smem[cutlass.Int32(2)] != cutlass.Int32(0) - tcgen05_sched_pipeline.consumer_release(tcgen05_sched_pipeline_consumer_state) - tcgen05_sched_pipeline_consumer_state.advance() - cute.arch.sync_warp() - if cute.arch.make_warp_uniform(cute.arch.warp_idx()) == cutlass.Int32(6): - tcgen05_grouped_selected_sched = cutlass.utils.StaticPersistentGroupTileScheduler.create(tcgen05_grouped_tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim(), (128, 128, 64), cutlass.utils.create_initial_search_state(), 16, tcgen05_grouped_problem_sizes) - tcgen05_grouped_selected_work_tile = tcgen05_grouped_selected_sched.initial_work_tile_info() - while tcgen05_grouped_selected_work_tile.is_valid_tile: - if cute.arch.lane_idx() == cutlass.Int32(0): - tcgen05_sched_pipeline.producer_acquire(tcgen05_sched_pipeline_producer_state) - tcgen05_grouped_selected_group_search_result = tcgen05_grouped_selected_work_tile.group_search_result - tcgen05_grouped_selected_metadata_idx = tcgen05_grouped_selected_group_search_result.group_idx - tcgen05_grouped_selected_group_idx = tcgen05_grouped_selected_metadata_idx - tcgen05_grouped_selected_cta_tile_idx_m = tcgen05_grouped_selected_group_search_result.cta_tile_idx_m >> cutlass.Int32(1) - tcgen05_grouped_selected_cta_tile_idx_n = tcgen05_grouped_selected_group_search_result.cta_tile_idx_n - tcgen05_grouped_panel_local_index = tcgen05_grouped_selected_sched._current_work_linear_idx - tcgen05_grouped_selected_sched.search_state.tile_count_prev_group - tcgen05_grouped_panel_m_clusters = (tcgen05_grouped_selected_group_search_result.problem_shape_m + cutlass.Int32(128) - 1) // cutlass.Int32(128) - tcgen05_grouped_panel_n_clusters = (tcgen05_grouped_selected_group_search_result.problem_shape_n + cutlass.Int32(128) - 1) // cutlass.Int32(128) - tcgen05_grouped_panel_size = cutlass.min(cutlass.Int32(4), tcgen05_grouped_panel_n_clusters) - tcgen05_grouped_panel_span = tcgen05_grouped_panel_size * tcgen05_grouped_panel_m_clusters - tcgen05_grouped_panel_index = tcgen05_grouped_panel_local_index // tcgen05_grouped_panel_span - tcgen05_grouped_panel_linear = tcgen05_grouped_panel_local_index % tcgen05_grouped_panel_span - tcgen05_grouped_panel_width = cutlass.min(tcgen05_grouped_panel_size, tcgen05_grouped_panel_n_clusters - tcgen05_grouped_panel_index * tcgen05_grouped_panel_size) - tcgen05_grouped_selected_cta_tile_idx_m = tcgen05_grouped_panel_linear // tcgen05_grouped_panel_width - tcgen05_grouped_selected_cta_tile_idx_n = (tcgen05_grouped_panel_index * tcgen05_grouped_panel_size + tcgen05_grouped_panel_linear % tcgen05_grouped_panel_width) * cutlass.Int32(1) + tcgen05_grouped_selected_cta_tile_idx_n % cutlass.Int32(1) - if tcgen05_grouped_panel_index % cutlass.Int32(2) == cutlass.Int32(1): - tcgen05_grouped_selected_cta_tile_idx_m = tcgen05_grouped_panel_m_clusters - cutlass.Int32(1) - tcgen05_grouped_selected_cta_tile_idx_m - tcgen05_work_tile_smem[cutlass.Int32(0)] = tcgen05_grouped_selected_cta_tile_idx_m - tcgen05_work_tile_smem[cutlass.Int32(1)] = tcgen05_grouped_selected_cta_tile_idx_n - tcgen05_work_tile_smem[cutlass.Int32(2)] = cutlass.Int32(1) - tcgen05_work_tile_smem[cutlass.Int32(4)] = tcgen05_grouped_selected_group_idx - tcgen05_work_tile_smem[cutlass.Int32(5)] = tcgen05_grouped_selected_group_search_result.problem_shape_m - tcgen05_work_tile_smem[cutlass.Int32(6)] = tcgen05_grouped_selected_group_search_result.problem_shape_n - tcgen05_work_tile_smem[cutlass.Int32(8)] = (tcgen05_grouped_starts.iterator + tcgen05_grouped_selected_metadata_idx * cutlass.Int32(tcgen05_grouped_starts.layout.stride[0])).load() - tcgen05_sched_pipeline.producer_commit(tcgen05_sched_pipeline_producer_state) - tcgen05_sched_pipeline_producer_state.advance() - cute.arch.sync_warp() - tcgen05_grouped_selected_sched.advance_to_next_work() - tcgen05_grouped_selected_work_tile = tcgen05_grouped_selected_sched.get_current_work() - if cute.arch.lane_idx() == cutlass.Int32(0): - tcgen05_sched_pipeline.producer_acquire(tcgen05_sched_pipeline_producer_state) - tcgen05_work_tile_smem[cutlass.Int32(2)] = cutlass.Int32(0) - tcgen05_sched_pipeline.producer_commit(tcgen05_sched_pipeline_producer_state) - tcgen05_sched_pipeline_producer_state.advance() - cute.arch.sync_warp() - if tcgen05_tma_warp: - tcgen05_ab_pipeline.producer_tail(tcgen05_ab_producer_state) - if tcgen05_exec_active: - cute.arch.griddepcontrol_launch_dependents() - if tcgen05_exec_active: - tcgen05_tmem_alloc_barrier.arrive() - if tcgen05_exec_active: - tcgen05_acc_pipeline.producer_tail(tcgen05_acc_producer_state) - tcgen05_tmem_allocator = cutlass.utils.TmemAllocator(tcgen05_tmem_holding_buf, barrier_for_retrieve=tcgen05_tmem_alloc_barrier, allocator_warp_id=0, is_two_cta=True, two_cta_tmem_dealloc_mbar_ptr=tcgen05_tmem_dealloc_mbar_ptr, num_allocated_columns=tcgen05_acc_tmem_cols, initialize_mbarrier=False) - if tcgen05_epi_active: - tcgen05_tmem_alloc_barrier.arrive_and_wait() - if tcgen05_epi_active: - tcgen05_tmem_allocator.free(tcgen05_epi_acc_tmem_ptr) - if tcgen05_warp_idx == cutlass.Int32(0): - tcgen05_c_pipeline.producer_tail() -_helion__grouped_offsets_k64._helion_cute_use_pdl = True -_helion__grouped_offsets_k64._helion_cute_wrapper_plans = [{'kind': 'tcgen05_grouped_static_persistent', 'scheduler_mode': 'device_group_search', 'm_tail_preserve': False, 'n_tail_preserve': False, 'group_count': 16, 'bm': 128, 'bn': 128, 'bk': 64, 'source_m_tile': 128, 'cluster_m': 2, 'cluster_n': 1, 'l2_swizzle_size': 4, 'device_panel_swizzle': True, 'n_size': 1536, 'device_split_sizes': True, 'device_layout_kind': 'offsets', 'm_size': 2048, 'k_total_size': 2048, 'problem_sizes_arg': 'tcgen05_grouped_problem_sizes', 'starts_arg': 'tcgen05_grouped_starts', 'sched_params_arg': 'tcgen05_grouped_tile_sched_params', 'total_clusters_arg': 'tcgen05_grouped_total_clusters', 'worklist_metadata': True, 'dynamic_ab_tensormaps': True, 'immutable_ab_tensormaps': True, 'bounded_output_shift': True, 'dynamic_ab_tensormap_rank': 2, 'lhs_idx': 1, 'rhs_idx': 2, 'layout_idx': 0, 'layout_bind_idx': 2}, {'kind': 'tcgen05_ab_tma', 'bm': 128, 'bn': 128, 'bk': 64, 'cluster_m': 2, 'cluster_n': 1, 'ab_stage_count': 13, 'input_dtype': 'cutlass.BFloat16', 'acc_dtype': 'cutlass.Float32', 'm_size': 2048, 'n_size': 1536, 'k_total_size': 2048, 'kernel_args': ['tma_atom_a', 'tma_tensor_a', 'tma_atom_b', 'tma_tensor_b'], 'full_allocation_a': True, 'full_allocation_b': True, 'source_m_tile': 128, 'device_split_sizes': True, 'device_layout_kind': 'offsets', 'use_2cta_instrs': True, 'b_k_major': True, 'rhs_rank3_grouped_nt': True, 'dynamic_ab_tensormaps': True, 'dynamic_ab_tensormap_rank': 2, 'use_pdl': True, 'lhs_idx': 1, 'rhs_idx': 2}, {'kind': 'tcgen05_d_tma', 'bm': 128, 'bn': 128, 'c_stage_count': 2, 'output_dtype': 'cutlass.BFloat16', 'kernel_args': ['tcgen05_tma_store_atom', 'tcgen05_tma_store_tensor'], 'rank3_mnl_tensor': True, 'bounded_output_shift': True, 'epi_tile_raw_expr': 'cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape((64, 128), True, cutlass.utils.layout.LayoutEnum.ROW_MAJOR, cutlass.BFloat16)', 'd_idx': 3}] -_helion__grouped_offsets_k64._helion_cute_cluster_shape = (2, 1, 1) - -def _grouped_offsets_k64(a: torch.Tensor, weights: torch.Tensor, offsets: torch.Tensor, *, _launcher=_default_cute_launcher): - _helion__grouped_offsets_k64._helion_cute_disable_bake_tensor_shapes = True - rows, reduction = a.shape - groups, columns, _ = weights.shape - out = torch.empty((rows, columns), device=a.device, dtype=a.dtype) - _NUM_SM = helion.runtime.get_num_sm(a.device) - _BLOCK_SIZE_0 = 256 - _BLOCK_SIZE_1 = 128 - _launcher(_helion__grouped_offsets_k64, (2, 1, min((16 * 2 + 2 - 1) // 2 * ((2048 + _BLOCK_SIZE_0 - 1) // _BLOCK_SIZE_0) * ((1536 + _BLOCK_SIZE_1 - 1) // _BLOCK_SIZE_1), max(1, _NUM_SM // 2))), offsets, a, weights, out, block=(32, 8, 1)) - return out diff --git a/test/test_cute_role_local_grouped_renders.py b/test/test_cute_role_local_grouped_renders.py index ba133af413..2bfa6e51f5 100644 --- a/test/test_cute_role_local_grouped_renders.py +++ b/test/test_cute_role_local_grouped_renders.py @@ -13,11 +13,12 @@ * F5 ``_build_grouped_worklist_nm_role_local_while``: the runtime tile table, the scheduler mailbox, runtime CLC record ids, and the dense ``local_full`` branch; P2 ``_build_grouped_worklist_nm_scheduler_warp_role_local_while``: - the M,N panel raster and the dense full-coverage loop. + the dense full-coverage loop. The M,N panel raster is journaled in + ``test_cute_grouped_worklist_codegen``. -The kernels and config builders belong to the tests that own those paths +The kernels and config builders belong to the modules that own those paths (``test_cute_rank3_rhs_b_tma``, ``test_cute_deepgemm_selected``, -``test_cute_grouped_large_device_seeds``, ``examples.grouped_gemm``); their +``examples.grouped_gemm``); their argument builders allocate on ``DEVICE``, so the CPU copies live here. """ @@ -28,7 +29,6 @@ from test.test_cute_deepgemm_selected import _selected_config from test.test_cute_deepgemm_selected import _selected_kernel -from test.test_cute_grouped_large_device_seeds import _grouped_offsets_k64 from test.test_cute_rank3_rhs_b_tma import _dynamic_bk64_config from test.test_cute_rank3_rhs_b_tma import _grouped_config from test.test_cute_rank3_rhs_b_tma import _rank3_rhs_grouped_nt @@ -246,40 +246,7 @@ def test_f5_runtime_clc(self) -> None: absent=(RUNTIME_DIRECT_GRID_STRIDE,), ) - # P2: the group-search scheduler warp's rasters. - def test_p2_panel_raster(self) -> None: - # The MN orientation with an L2 swizzle: the scheduler warp walks M,N - # panels and publishes the panel-local index. - config = helion.Config( - block_sizes=[256, 128, 64], - l2_groupings=[1], - loop_orders=[[0, 1, 2]], - num_stages=7, - num_warps=8, - pid_type="persistent_interleaved", - tcgen05_cluster_m=2, - tcgen05_cluster_n=1, - tcgen05_ab_stages=13, - tcgen05_acc_stages=2, - tcgen05_c_stages=2, - tcgen05_num_epi_warps=4, - tcgen05_consumer_regs=256, - tcgen05_grouped_mode="worklist_nm", - tcgen05_grouped_worklist_orientation="mn", - tcgen05_grouped_worklist_source_m_tile=128, - tcgen05_grouped_worklist_mma_n=128, - tcgen05_grouped_d_shift=True, - tcgen05_grouped_full_allocation_a=True, - tcgen05_l2_swizzle_size=4, - ) - args = ( - torch.empty((2048, 2048), dtype=torch.bfloat16), - torch.empty((16, 1536, 2048), dtype=torch.bfloat16), - torch.arange(17, dtype=torch.int32) * 128, - ) - code = _render(_grouped_offsets_k64, args, config) - self._pin(code, PANEL_LOCAL_INDEX, GROUP_TILE_SCHEDULER, MAILBOX_VALID) - + # P2: the group-search scheduler warp's dense full-coverage loop. def test_dense_full_coverage(self) -> None: # P2's dense full-coverage loop: the scheduler warp publishes every # tile of the index domain. From ccc305cf949f11c55b9bfaa1ce25f2ef7fb58a72 Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Wed, 25 Nov 2026 22:54:22 -0800 Subject: [PATCH 5/5] [cutedsl] Launch local grid joins cooperatively Select a cooperative launch when the final generated device body calls a local grid barrier, including a call nested in control flow. The launch descriptor and disk cache key distinguish those kernels. Other launches keep their existing behavior. Read local barrier calls from the generated body before outlining the two cluster fallback alternatives. The launch attributes still describe the actual device program when the entry body delegates to helpers. Testing: on this commit, scripts/run_tests.py --backend cute --gpus 0 --slow test/test_barrier.py test/test_cute_min_blocks_carveout.py passed 13 CPU and 29 B200 GPU cases (one GPU skip). No standalone performance claim is made for this launch change. After integrating upstream #4739, the actual fallback cluster, its standalone helper, and split-K GEMMs passed against PyTorch on B200 4. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4754, branch: choijon5/helion-b200/shared/6 --- helion/_compiler/cute/_ast_pass_utils.py | 20 +++++++++++-- .../_compiler/cute/autotune/search_surface.py | 6 ++-- helion/_compiler/cute/backend.py | 3 +- .../cute/passes/launch_attributes.py | 18 +++++++++--- helion/runtime/cute/compile_cache.py | 2 ++ helion/runtime/cute/launch_descriptor.py | 5 ++++ helion/runtime/cute/launcher.py | 6 ++++ test/test_barrier.py | 6 ++-- test/test_cute_min_blocks_carveout.py | 28 ++++++++++++++++++- 9 files changed, 80 insertions(+), 14 deletions(-) diff --git a/helion/_compiler/cute/_ast_pass_utils.py b/helion/_compiler/cute/_ast_pass_utils.py index 54240664cb..5eb546c9a5 100644 --- a/helion/_compiler/cute/_ast_pass_utils.py +++ b/helion/_compiler/cute/_ast_pass_utils.py @@ -33,8 +33,9 @@ node. * dataflow -- ``exposed_reads`` (forward, with explicit branch/loop/define policies) and ``live_in`` (backward, zero-trip loops). -* device body -- ``body_end_follows_all_tiles``: whether a statement appended - to a device body runs once per CTA, after all of its tiles. +* device body -- ``phase_barrier_call`` recognizes the emitted local grid join + ABI (``PHASE_BARRIER_ARITIES``); ``body_end_follows_all_tiles`` tells whether + an appended statement runs once per CTA, after all of its tiles. Do not import this module from device-helper modules that generated code imports (``reduce_helpers``, ``vec_utils``, ``*_runtime``): they are part of @@ -426,6 +427,21 @@ def constexpr_v_loop(node: ast.AST) -> tuple[ast.For, int] | None: # -------------------------------------------------------------------------- +PHASE_BARRIER_ARITIES = {"_cute_grid_barrier": 1} + + +def phase_barrier_call(stmt: ast.stmt) -> ast.Call | None: + """A direct call to the compiler-emitted local grid join.""" + if isinstance(stmt, ast.Expr) and isinstance(call := stmt.value, ast.Call): + if ( + isinstance(call.func, ast.Name) + and len(call.args) == PHASE_BARRIER_ARITIES.get(call.func.id) + and not call.keywords + ): + return call + return None + + def body_end_follows_all_tiles(body: Sequence[ast.AST], device_ir: DeviceIR) -> bool: """Whether every thread of every CTA reaches the end of the device ``body`` once, after all of the CTA's tiles: the body has no early diff --git a/helion/_compiler/cute/autotune/search_surface.py b/helion/_compiler/cute/autotune/search_surface.py index 679786ba54..14ec475f4a 100644 --- a/helion/_compiler/cute/autotune/search_surface.py +++ b/helion/_compiler/cute/autotune/search_surface.py @@ -4287,9 +4287,9 @@ def normalize_strategy( _normalize_cute_flash_bwd(config_spec, config) if config_spec.multi_phase and config.get("num_sm_multiplier", 1) != 1: - # The grid barrier between the phases waits for every CTA, and the - # CuTe launcher has no cooperative launch to reject a grid larger - # than the GPU holds at once: such a launch would hang. + # A grid barrier waits for every CTA. A cooperative launch can + # reject an oversized grid, but the search has no per-function + # proof that additional blocks can reside on each SM. if fix_invalid: config.pop("num_sm_multiplier", None) else: diff --git a/helion/_compiler/cute/backend.py b/helion/_compiler/cute/backend.py index 0585beb639..535e0dec81 100644 --- a/helion/_compiler/cute/backend.py +++ b/helion/_compiler/cute/backend.py @@ -2762,10 +2762,11 @@ def finalize_kernel_def( # The final body, the spread pad included: a kernel whose shared # memory cannot fit one block fails here, not in libNVVM. check_smem_budget(fn_def, ctx.constexpr_values, fn.pid) + # Inspect the kernel before outlining moves its joins into a helper. + statements = launch_attributes.module_statements(fn, fn_def) # One body per cluster shape sharing that shared memory # (``tcgen05_fallback_cluster``). outline_fallback_cluster_bodies(fn, fn_def, prefix) - statements = launch_attributes.module_statements(fn) launch_attributes.project_launch_block(fn) return statements diff --git a/helion/_compiler/cute/passes/launch_attributes.py b/helion/_compiler/cute/passes/launch_attributes.py index b4fc32def1..ec134a3da0 100644 --- a/helion/_compiler/cute/passes/launch_attributes.py +++ b/helion/_compiler/cute/passes/launch_attributes.py @@ -4,17 +4,19 @@ The statements set the attributes ``helion.runtime.cute.launcher`` reads off the kernel function before its first launch: the device-helper kinds whose imports are absent from the generated source, the thread-block cluster -shape, programmatic dependent launch (``cute_pdl``), the SASS checks and -ptxas's ``minnctapersm``. ``project_launch_block`` refreshes the host launch -call's ``block=`` once a late device lowering fixed the CTA shape. +shape, cooperative launch for spinning grid joins, programmatic dependent +launch (``cute_pdl``), SASS checks and ptxas's ``minnctapersm``. +``project_launch_block`` updates the host launch block after device lowering. """ from __future__ import annotations from typing import TYPE_CHECKING +from ...ast_extension import iter_statements from ...ast_extension import statement_from_string from ...source_location import SyntheticLocation +from .._ast_pass_utils import phase_barrier_call from ..pdl_ops import has_explicit_pdl from ..thread_block_projection import update_launch_block from .pdl import pdl_applies @@ -25,9 +27,17 @@ from ...device_function import DeviceFunction -def module_statements(fn: DeviceFunction) -> list[ast.stmt]: +def module_statements(fn: DeviceFunction, fn_def: ast.FunctionDef) -> list[ast.stmt]: """The statements that follow ``fn``'s kernel definition in the module.""" result: list[ast.stmt] = [] + # A peer join also spins on the local grid. Inspect statement + # scopes, including wrappers, without walking every arithmetic expression. + if any( + phase_barrier_call(stmt) is not None for stmt in iter_statements(fn_def.body) + ): + result.append( + statement_from_string(f"{fn.name}._helion_cute_cooperative = True") + ) if fn.cute_state.lanes.resident_reduction_layouts: # These imported device helpers are absent from generated source. # Persist their dependency with this kernel through source reload. diff --git a/helion/runtime/cute/compile_cache.py b/helion/runtime/cute/compile_cache.py index ea2f38826e..474e45f4c3 100644 --- a/helion/runtime/cute/compile_cache.py +++ b/helion/runtime/cute/compile_cache.py @@ -26,6 +26,7 @@ from typing import Any from typing import cast +from .launch_descriptor import cooperative from .launch_descriptor import preferred_smem_carveout from .launch_descriptor import use_pdl from .source_dependencies import referenced_helper_sources @@ -495,6 +496,7 @@ def disk_cache_key( cutlass_version, num_sm, use_pdl(cute_kernel), + *(("cooperative",) if cooperative(cute_kernel) else ()), *(() if resident_clusters is None else (resident_clusters,)), *checker, ) diff --git a/helion/runtime/cute/launch_descriptor.py b/helion/runtime/cute/launch_descriptor.py index 5fe007f304..2bac660a79 100644 --- a/helion/runtime/cute/launch_descriptor.py +++ b/helion/runtime/cute/launch_descriptor.py @@ -50,6 +50,11 @@ def cluster_shape_from_wrapper_plans( return (cluster_m, cluster_n, 1) +def cooperative(cute_kernel: object) -> bool: + """Whether all CTAs must be resident for a generated grid join.""" + return getattr(cast("Any", cute_kernel), "_helion_cute_cooperative", False) is True + + def use_pdl(cute_kernel: object) -> bool: """Whether the generated kernel asked for programmatic dependent launch. diff --git a/helion/runtime/cute/launcher.py b/helion/runtime/cute/launcher.py index 52ce20e22b..7dfba493f7 100644 --- a/helion/runtime/cute/launcher.py +++ b/helion/runtime/cute/launcher.py @@ -139,6 +139,7 @@ ) from .launch_descriptor import bake_tensor_shapes as _cute_bake_tensor_shapes_guard from .launch_descriptor import cluster_shape as _cute_cluster_shape +from .launch_descriptor import cooperative as _cute_cooperative from .launch_descriptor import cute_launch_descriptor from .launch_descriptor import min_blocks_per_mp as _cute_min_blocks_per_mp from .launch_descriptor import preferred_smem_carveout as _cute_preferred_smem_carveout @@ -439,6 +440,11 @@ def _create_cute_wrapper( "cute", "SM100 recurrence must own the complete device root" ) launch_suffix = f", block={block!r}" + # Every CTA must be able to reach a spinning grid barrier. Only the + # driver can admit the complete grid under concurrent stream workloads. + if _cute_cooperative(cute_kernel): + launch_suffix += ", cooperative=True" + cluster_shape = _cute_cluster_shape(cute_kernel, wrapper_plans) if cluster_shape is not None: launch_suffix += f", cluster={list(cluster_shape)!r}" diff --git a/test/test_barrier.py b/test/test_barrier.py index 019f19b193..aac8e5ebc2 100644 --- a/test/test_barrier.py +++ b/test/test_barrier.py @@ -298,9 +298,8 @@ def test_dep_across_barrier(self) -> None: @skipIfRefEager("config normalization is only enforced in compiled mode") def test_multi_phase_requires_one_cta_per_sm(self) -> None: - """The grid barrier waits for every CTA, and the CuTe launcher has no - cooperative launch to reject a grid the GPU cannot hold at once: an - oversubscribed persistent grid would hang instead of failing.""" + """The search caps the grid at one CTA per SM. CUDA also checks if the + final cooperative launch can keep all those CTAs resident together.""" @helion.kernel(autotune_effort="none") def implicit_dependency(x: torch.Tensor) -> torch.Tensor: @@ -366,6 +365,7 @@ def test_default_config_is_persistent(self) -> None: code, out = code_and_output(barrier_dep_single, (x,), block_sizes=[4, 4]) torch.testing.assert_close(out, x * 2 + 1) self.assertIn("_cute_grid_barrier", code) + self.assertIn("._helion_cute_cooperative = True", code) @skipIfRefEager("promoted-seed pid_type is only materialized in compiled mode") def test_reduction_seed_default_config_is_persistent(self) -> None: diff --git a/test/test_cute_min_blocks_carveout.py b/test/test_cute_min_blocks_carveout.py index 41b96f1098..6b463d59c3 100644 --- a/test/test_cute_min_blocks_carveout.py +++ b/test/test_cute_min_blocks_carveout.py @@ -1,8 +1,9 @@ -"""The shared-memory carveout preference the CuTe launcher passes +"""The CuTe launcher’s residency and shared-memory carveout preferences (``helion.runtime.cute.launch_descriptor.preferred_smem_carveout``).""" from __future__ import annotations +import ast import inspect import re from types import SimpleNamespace @@ -14,6 +15,7 @@ import torch from helion.runtime.cute import launcher +from helion.runtime.cute.compile_cache import disk_cache_key from helion.runtime.cute.launch_descriptor import DRIVER_DEFAULT_SMEM_CARVEOUT from helion.runtime.cute.launch_descriptor import min_blocks_per_mp from helion.runtime.cute.launch_descriptor import preferred_smem_carveout @@ -171,3 +173,27 @@ def test_the_fa4_topology_launches_one_cta_per_sm() -> None: ) assert min_blocks_per_mp(_kernel(), [{"topology": "ws_overlap"}]) is None assert min_blocks_per_mp(_kernel(min_blocks_per_mp=True)) is None + + +def test_cooperative_marker_changes_the_launch_and_its_cache_key() -> None: + keys = [] + for marked in (False, True): + kernel = SimpleNamespace(_helion_cute_source_hash="same source") + if marked: + kernel._helion_cute_cooperative = True + wrapper = launcher._create_cute_wrapper(kernel, (), (32, 1, 1)) + (launch,) = [ + node + for node in ast.walk(ast.parse(inspect.getsource(wrapper))) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "launch" + ] + flags = [ + ast.literal_eval(kw.value) + for kw in launch.keywords + if kw.arg == "cooperative" + ] + assert flags == ([True] if marked else []) + keys.append(disk_cache_key(kernel, (), (32, 1, 1), (), None, None)) + assert None not in keys and keys[0] != keys[1]