Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions KNOWN_GAPS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 17 additions & 9 deletions helion/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
20 changes: 18 additions & 2 deletions helion/_compiler/cute/_ast_pass_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
35 changes: 30 additions & 5 deletions helion/_compiler/cute/autotune/search_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -6032,4 +6056,5 @@ def config_generation_extension(
return CuteConfigGenerationExtension(generation)


_BUILTIN_CURRENT_CAPABILITY = CuteSearchSurface.default_target_device_capability
CUTE_SEARCH_SURFACE = CuteSearchSurface()
3 changes: 2 additions & 1 deletion helion/_compiler/cute/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 14 additions & 4 deletions helion/_compiler/cute/passes/launch_attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
8 changes: 5 additions & 3 deletions helion/_compiler/cute/target_facts.py
Original file line number Diff line number Diff line change
@@ -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),
Expand Down
14 changes: 9 additions & 5 deletions helion/_testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`` /
Expand Down Expand Up @@ -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",
),
Expand Down
1 change: 1 addition & 0 deletions helion/_testing/cute_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading