From fe23ab5320927bd5a4fe41c44493cd0c2a45b2fb Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Thu, 26 Nov 2026 00:37:38 -0800 Subject: [PATCH 1/2] [cutedsl] Pipeline gathered softmax pages and merge their split weights MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fuse a proved online-softmax transition and share FP32 weights across its split merge. Normalize signed K and V page indices independently. The new CuTe options cute_gathered_page_pipeline and cute_gathered_page_stages control the aligned BF16 panel ring (two through eight stages). Normal search offers two-, four- and eight-stage software-counter seeds. An installed cooperative toolkit adds a structural eight-stage carrier; a runtime compiler rejection declines that specific candidate without changing the persistent cache key. Preserve strict and fast arithmetic in both fused helpers. If fast math removes the numerator’s implicit zero mask, still require zero weights for inactive splits and the identical explicit mask on the partial load. The default public preset uses the strict path. Testing: nine CuTe CPU source checks passed, including actual strict and fast fused programs, a rejected mismatched mask and stable cache fingerprints after toolkit rejection; the combined grid/seed subset passed 19. Seventeen B200 GPU cases passed, including the complete eight-stage fast-math page, signed physical pages, partial final pages, and independent subnormal tests for exp2 and FP32 division. The final stream-explicit native helper passed again on B200 1. The ordinary cold Full search independently elected the eight-stage pipeline; the public result is in the following preset PR. 26,237 CuTe CPU and 16,148 GPU tests (B200 1/2), 4,904 Triton CPU and 3,394 GPU tests (B200 3), and 269 Pallas interpreter tests (44 skipped) passed on the integration preceding the direct-ConfigSpec probe and host-loader changes; that Triton run also includes an isolated host-test device model. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4763, branch: choijon5/helion-b200/mla/4 --- helion/_compiler/cute/README.md | 7 + .../_compiler/cute/_gathered_panel_runtime.py | 211 ++++++++ .../cute/_gathered_softmax_runtime.py | 379 ++++++++++++++ .../cute/analysis/gathered_softmax.py | 216 ++++++++ .../_compiler/cute/analysis/match_common.py | 17 + .../cute/analysis/split_weighted_merge.py | 352 +++++++++++++ helion/_compiler/cute/autotune/config_keys.py | 2 + .../_compiler/cute/autotune/fragment_knobs.py | 12 +- .../heuristics/cute_gathered_bf16_mma.py | 134 +++++ .../cute/autotune/mma_dag_surface.py | 2 + .../_compiler/cute/autotune/search_surface.py | 36 ++ helion/_compiler/cute/computed_fragment.py | 39 +- helion/_compiler/cute/fragment_context.py | 20 +- .../_compiler/cute/fragment_control_flow.py | 28 +- .../_compiler/cute/gathered_panel_layout.py | 34 ++ helion/_compiler/cute/gathered_softmax.py | 319 ++++++++++++ helion/_compiler/cute/split_weighted_merge.py | 91 ++++ helion/_testing/cute_gathered_bf16.py | 43 ++ helion/_testing/cute_weighted_merge.py | 64 +++ helion/autotuner/config_spec.py | 1 + test/shard_durations.json | 2 +- test/test_config_spec_keys_migration.py | 4 + test/test_cute_fragment_half_mma.py | 150 ++++++ test/test_cute_gathered_bf16_mma.py | 479 +++++++++++++++++- test/test_cute_register_subblocks.py | 17 + 25 files changed, 2646 insertions(+), 13 deletions(-) create mode 100644 helion/_compiler/cute/_gathered_panel_runtime.py create mode 100644 helion/_compiler/cute/_gathered_softmax_runtime.py create mode 100644 helion/_compiler/cute/analysis/gathered_softmax.py create mode 100644 helion/_compiler/cute/analysis/split_weighted_merge.py create mode 100644 helion/_compiler/cute/gathered_panel_layout.py create mode 100644 helion/_compiler/cute/gathered_softmax.py create mode 100644 helion/_compiler/cute/split_weighted_merge.py create mode 100644 helion/_testing/cute_weighted_merge.py diff --git a/helion/_compiler/cute/README.md b/helion/_compiler/cute/README.md index 9815c03a4..d37960838 100644 --- a/helion/_compiler/cute/README.md +++ b/helion/_compiler/cute/README.md @@ -543,3 +543,10 @@ Module docstrings carry a `Role:` line using one of these words: * **Known test gaps.** `test/test_cute_tcgen05_split_k_search.py::test_sampled_splits_render` is unseeded; the rank-1 recurrence kernels do not bind on CPU, so the CPU render dump never covers them. + +The gathered BF16 online reduction recognizes the base-2, FP32 softmax +recurrence with an explicit negative-infinity identity and a signed +per-row position limit. Equivalently spelled or differently rounded +recurrences (natural exponentials, reordered masking, other dot precision) +use normal lowering. The two-pass split combiner also proves both masks, +loop-carried values, and nonaliasing output before sharing weights. diff --git a/helion/_compiler/cute/_gathered_panel_runtime.py b/helion/_compiler/cute/_gathered_panel_runtime.py new file mode 100644 index 000000000..24fcff284 --- /dev/null +++ b/helion/_compiler/cute/_gathered_panel_runtime.py @@ -0,0 +1,211 @@ +"""Aligned BF16 page-panel transfers and warp fragment mappings for four warps.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing import cast + +import cutlass +import cutlass.cute as cute + +from . import gathered_panel_layout as panels +from ._flash_row_mma_runtime import mma_bf16 +from .device.ptx import cp_async_16 +from .device.ptx import cp_async_16_zfill +from .device.ptx import ldmatrix_x4 as _ldmatrix_x4 +from .device.ptx import ldmatrix_x4_trans as _ldmatrix_x4_trans + +if TYPE_CHECKING: + from collections.abc import Callable + +# The table-driven PTX wrappers return the declared four packed BF16 words. +ldmatrix_x4 = cast( + "Callable[[object], tuple[cutlass.Uint32, cutlass.Uint32, cutlass.Uint32, cutlass.Uint32]]", + _ldmatrix_x4, +) +ldmatrix_x4_trans = cast( + "Callable[[object], tuple[cutlass.Uint32, cutlass.Uint32, cutlass.Uint32, cutlass.Uint32]]", + _ldmatrix_x4_trans, +) + + +@cute.jit +def _address( + base: cute.Numeric, + row: cute.Numeric, + packet: cute.Numeric, + width: cutlass.Constexpr, +) -> cutlass.Int32: + # Rows contain a power-of-two number of naturally aligned 16-byte + # packets. XOR rotates their banks without changing the lane's bytes. + col = packet ^ (row % (width // 8)) + return base + (row * (width // 8) + col) * 16 + + +@cute.jit +def _issue_qk( + qbase: cute.Numeric, + kbase: cute.Numeric, + qpitch: cute.Numeric, + kpitch: cute.Numeric, + panel: cute.Numeric, + group: cutlass.Constexpr, + stage: cute.Numeric, + tid: cute.Numeric, + valid_k: cutlass.Boolean, +) -> None: + # Every Q/K panel has 64 depth columns: one packet per lane for + # 16 rows of Q, and four packets per lane for 64 rows of K. + row, col = tid // 8, tid % 8 + cp_async_16( + _address(stage, row, col, 64), + qbase + ((group * 16 + row) * qpitch + panel * 64 + col * 8) * 2, + ) + for chunk in cutlass.range_constexpr(4): + i = tid + 128 * chunk + row, col = i // 8, i % 8 + cp_async_16_zfill( + _address(stage + 2048, row, col, 64), + kbase + (row * kpitch + panel * 64 + col * 8) * 2, + cutlass.Int32(valid_k) * 16, + ) + + +@cute.jit +def query_key( + scores: cute.Tensor, + q: cute.Tensor, + k: cute.Tensor, + physical: cute.Numeric, + kpage: cute.Numeric, + qpitch: cute.Numeric, + kpitch: cute.Numeric, + group: cutlass.Constexpr, + slab: cute.Numeric, + tid: cute.Numeric, + valid_k: cutlass.Boolean, + depth: cutlass.Constexpr, + stages: cutlass.Constexpr, +) -> None: + # Each 10-KiB stage holds 16x64 Q and 64x64 K. An invalid physical + # page uses a valid base for the zero-byte copy; the V extent is independent. + qbase = cutlass.Int64(cast("cute.Pointer", q.iterator).toint()) + safe_k = cutlass.Int64(physical if valid_k else cutlass.Int64(0)) + kbase = cutlass.Int64(cast("cute.Pointer", k.iterator).toint()) + safe_k * kpage * 2 + lane = tid % 32 + quadrant = lane // 8 + warp = tid // 32 + for warm in cutlass.range_constexpr(stages - 1): + if cutlass.const_expr(warm < depth // 64): + _issue_qk( + qbase, + kbase, + qpitch, + kpitch, + warm, + group, + slab + warm * panels.STAGE_BYTES, + tid, + valid_k, + ) + cute.arch.cp_async_commit_group() + for panel in range(depth // 64): + future = panel + stages - 1 + if future < depth // 64: + _issue_qk( + qbase, + kbase, + qpitch, + kpitch, + future, + group, + slab + (future % stages) * panels.STAGE_BYTES, + tid, + valid_k, + ) + # Empty prologue/tail groups keep a fixed distance even if K has + # fewer 64-column panels than the number of prefetched groups. + cute.arch.cp_async_commit_group() + cute.arch.cp_async_wait_group(stages - 1) + cute.arch.sync_threads() + cur = slab + (panel % stages) * panels.STAGE_BYTES + for step in cutlass.range_constexpr(4): + a0, a1, a2, a3 = ldmatrix_x4( + _address( + cur, lane % 8 + (quadrant % 2) * 8, step * 2 + quadrant // 2, 64 + ) + ) + krow = lane % 8 + 8 * ((quadrant // 2) * 4 + warp) + b0, b1, b2, b3 = ldmatrix_x4( + _address(cur + 2048, krow, step * 2 + quadrant % 2, 64) + ) + c0, c1, c2, c3 = mma_bf16( + a0, a1, a2, a3, b0, b1, scores[0], scores[1], scores[2], scores[3] + ) + scores[0], scores[1], scores[2], scores[3] = c0, c1, c2, c3 + c0, c1, c2, c3 = mma_bf16( + a0, a1, a2, a3, b2, b3, scores[4], scores[5], scores[6], scores[7] + ) + scores[4], scores[5], scores[6], scores[7] = c0, c1, c2, c3 + cute.arch.sync_threads() + cute.arch.cp_async_wait_group(0) + + +@cute.jit +def issue_values( + slab: cute.Numeric, + vals: cute.Tensor, + physical: cute.Numeric, + page: cute.Numeric, + row_pitch: cute.Numeric, + dim0: cute.Numeric, + tid: cute.Numeric, + valid: cutlass.Boolean, + width: cute.Numeric, +) -> None: + # Recycle the two consumed QK stages for a 64x128 V panel. Its transfer + # can overlap the unmodified FP32 online softmax and denominator. + base = ( + cutlass.Int64(cast("cute.Pointer", vals.iterator).toint()) + + cutlass.Int64(physical if valid else cutlass.Int64(0)) * page * 2 + ) + for chunk in cutlass.range_constexpr(8): + index = tid + 128 * chunk + row, col = index // 16, index % 16 + vcol = cutlass.Int64(dim0) + col * 8 + live = valid & (vcol >= 0) & (vcol + 7 < width) + cp_async_16_zfill( + _address(slab, row, col, 128), + base + (row * row_pitch + vcol) * 2, + cutlass.Int32(live) * 16, + ) + cute.arch.cp_async_commit_group() + + +@cute.jit +def probability_value( + slab: cute.Numeric, + probs: cute.Tensor, + tid: cute.Numeric, + nc: cutlass.Constexpr, + pitch: cutlass.Constexpr, + c0: cutlass.Float32, + c1: cutlass.Float32, + c2: cutlass.Float32, + c3: cutlass.Float32, +) -> tuple[cutlass.Float32, cutlass.Float32, cutlass.Float32, cutlass.Float32]: + lane = tid % 32 + quadrant = lane // 8 + pbase = cutlass.Int32(cast("cute.Pointer", probs.iterator).toint()) + for pair in cutlass.range_constexpr(2): + row = pair * 32 + quadrant * 8 + lane % 8 + b0, b1, b2, b3 = ldmatrix_x4_trans(_address(slab, row, nc * 4 + tid // 32, 128)) + for half in cutlass.range_constexpr(2): + prow = lane % 8 + (quadrant % 2) * 8 + col = pair * 32 + 16 * half + (quadrant // 2) * 8 + a0, a1, a2, a3 = ldmatrix_x4(pbase + (prow * pitch + col) * 2) + if cutlass.const_expr(half == 0): + c0, c1, c2, c3 = mma_bf16(a0, a1, a2, a3, b0, b1, c0, c1, c2, c3) + else: + c0, c1, c2, c3 = mma_bf16(a0, a1, a2, a3, b2, b3, c0, c1, c2, c3) + return c0, c1, c2, c3 diff --git a/helion/_compiler/cute/_gathered_softmax_runtime.py b/helion/_compiler/cute/_gathered_softmax_runtime.py new file mode 100644 index 000000000..8e7e84b4e --- /dev/null +++ b/helion/_compiler/cute/_gathered_softmax_runtime.py @@ -0,0 +1,379 @@ +"""Warp-native BF16 page transitions and bounded FP32 split-weight reductions.""" + +from __future__ import annotations + +from typing import cast + +import cutlass +import cutlass.cute as cute + +from . import _gathered_panel_runtime as panel +from ._flash_row_mma_runtime import mma_bf16 +from ._flash_row_mma_runtime import pack_bf16x2 +from .reduce_helpers import _cute_nan_max +from .reduce_helpers import _warp_reduce_max +from .reduce_helpers import _warp_reduce_sum + + +@cute.jit +def _pair(ptr: cute.Pointer, index: cute.Numeric, step: cute.Numeric) -> cutlass.Uint32: + return pack_bf16x2( + cutlass.Float32((ptr + index).load()), + cutlass.Float32((ptr + index + step).load()), + ) + + +@cute.jit +def _qk_pair( + ptr: cute.Pointer, + index: cute.Numeric, + step: cute.Numeric, + packed: cutlass.Constexpr, +) -> cutlass.Uint32: + # MMA expects the increasing-K BF16 pair in low/high order. A naturally + # aligned unit-stride word has that representation already. + if cutlass.const_expr(packed): + return cutlass.Uint32(cute.recast_ptr(ptr + index, dtype=cutlass.Uint32).load()) + return _pair(ptr, index, step) + + +@cute.jit +def _key_pair( + ptr: cute.Pointer, + index: cute.Numeric, + step: cute.Numeric, + valid: cutlass.Boolean, + packed: cutlass.Constexpr, +) -> cutlass.Uint32: + pair = cutlass.Uint32(0) + if valid: + pair = _qk_pair(ptr, index, step, packed) + return pair + + +@cute.jit +def _zero_pair( + ptr: cute.Pointer, index: cute.Numeric, step: cute.Numeric, valid: cutlass.Boolean +) -> cutlass.Uint32: + pair = cutlass.Uint32(0) + if valid: + pair = _pair(ptr, index, step) + return pair + + +@cute.jit +def gathered_softmax_page( + q: cute.Tensor, + keys: cute.Tensor, + vals: cute.Tensor, + limit: cute.Tensor, + prev_m: cute.Tensor, + prev_l: cute.Tensor, + prev_a: cute.Tensor, + out_m: cute.Tensor, + out_l: cute.Tensor, + out_a: cute.Tensor, + probs: cute.Tensor, + scratch: cute.Tensor, + tid: cute.Numeric, + physical: cute.Numeric, + logical: cute.Numeric, + dim0: cute.Numeric, + scale: cute.Numeric, + nkeys: cute.Numeric, + nvals: cute.Numeric, + vwidth: cute.Numeric, + qr: cute.Numeric, + qk: cute.Numeric, + kp: cute.Numeric, + kr: cute.Numeric, + kk: cute.Numeric, + vp: cute.Numeric, + vr: cute.Numeric, + vd: cute.Numeric, + M: cutlass.Constexpr, + N: cutlass.Constexpr, + K: cutlass.Constexpr, + D: cutlass.Constexpr, + W: cutlass.Constexpr, + A_IN: cutlass.Constexpr, + A_OUT: cutlass.Constexpr, + P_ROW: cutlass.Constexpr, + PACKED_Q: cutlass.Constexpr = False, + PACKED_K: cutlass.Constexpr = False, + panel_storage: cute.Tensor | None = None, + panel_stages: cutlass.Constexpr = 2, + fast_math: cutlass.Constexpr = False, +) -> None: + warp = tid // 32 + lane = tid % 32 + g = lane // 4 + t = lane % 4 + # The unmasked K and V lookups each wrap once against their own bank. + raw = cutlass.Int64(physical) + k_index = raw + cutlass.Int64(nkeys) if raw < 0 else raw + v_index = raw + cutlass.Int64(nvals) if raw < 0 else raw + valid_k = (k_index >= 0) & (k_index < nkeys) + valid_v = (v_index >= 0) & (v_index < nvals) + # Pointer arithmetic is 64-bit, including for dynamically strided views. + q_row = cutlass.Int64(qr) + q_col = cutlass.Int64(qk) + k_page = k_index * cutlass.Int64(kp) + k_row = cutlass.Int64(kr) + k_col = cutlass.Int64(kk) + v_page = v_index * cutlass.Int64(vp) + v_row = cutlass.Int64(vr) + v_col = cutlass.Int64(vd) + slab = cutlass.Int32(0) + if cutlass.const_expr(panel_storage is not None): + assert panel_storage is not None + slab = ( + cutlass.Int32(cast("cute.Pointer", panel_storage.iterator).toint()) + 127 + ) & -128 + for group in cutlass.range_constexpr(M // 16): + h0 = group * 16 + g + h1 = h0 + 8 + a_lim = limit[h0] + b_lim = limit[h1] + scores = cute.make_rmem_tensor((N // (8 * W) * 4,), cutlass.Float32) + scores.fill(cutlass.Float32(0)) + if cutlass.const_expr(panel_storage is not None): + panel.query_key( + scores, + q, + keys, + k_index, + kp, + q_row, + k_row, + group, + slab, + tid, + valid_k, + K, + panel_stages, + ) + panel.issue_values( + slab, vals, v_index, vp, v_row, dim0, tid, valid_v, vwidth + ) + else: + for ks in range(K // 16): + k = ks * 16 + 2 * t + a0 = _qk_pair(q.iterator, h0 * q_row + k * q_col, q_col, PACKED_Q) + a1 = _qk_pair(q.iterator, h1 * q_row + k * q_col, q_col, PACKED_Q) + a2 = _qk_pair(q.iterator, h0 * q_row + (k + 8) * q_col, q_col, PACKED_Q) + a3 = _qk_pair(q.iterator, h1 * q_row + (k + 8) * q_col, q_col, PACKED_Q) + for nt in cutlass.range_constexpr(N // (8 * W)): + base = k_page + (8 * (nt * W + warp) + g) * k_row + b0 = _key_pair( + keys.iterator, base + k * k_col, k_col, valid_k, PACKED_K + ) + b1 = _key_pair( + keys.iterator, base + (k + 8) * k_col, k_col, valid_k, PACKED_K + ) + i = 4 * nt + s0, s1, s2, s3 = mma_bf16( + a0, + a1, + a2, + a3, + b0, + b1, + scores[i], + scores[i + 1], + scores[i + 2], + scores[i + 3], + ) + scores[i], scores[i + 1], scores[i + 2], scores[i + 3] = ( + s0, + s1, + s2, + s3, + ) + top = cutlass.Float32(float("-inf")) + bottom = cutlass.Float32(float("-inf")) + for nt in cutlass.range_constexpr(N // (8 * W)): + i = 4 * nt + p0 = cutlass.Int32(logical * N + 8 * (nt * W + warp) + 2 * t) + p1 = cutlass.Int32(p0 + 1) + scores[i] = ( + scores[i] * scale if p0 < a_lim else cutlass.Float32(float("-inf")) + ) + scores[i + 1] = ( + scores[i + 1] * scale if p1 < a_lim else cutlass.Float32(float("-inf")) + ) + scores[i + 2] = ( + scores[i + 2] * scale if p0 < b_lim else cutlass.Float32(float("-inf")) + ) + scores[i + 3] = ( + scores[i + 3] * scale if p1 < b_lim else cutlass.Float32(float("-inf")) + ) + top = _cute_nan_max(top, _cute_nan_max(scores[i], scores[i + 1])) + bottom = _cute_nan_max(bottom, _cute_nan_max(scores[i + 2], scores[i + 3])) + top = _warp_reduce_max(top, threads_in_group=4) + bottom = _warp_reduce_max(bottom, threads_in_group=4) + if t == 0: + scratch[warp * 16 + g] = top + scratch[warp * 16 + g + 8] = bottom + cute.arch.sync_threads() + if tid < 16: + h = 16 * group + tid + incoming_max = cutlass.Float32(prev_m[h]) + mm = incoming_max + for w in cutlass.range_constexpr(W): + mm = _cute_nan_max(mm, cutlass.Float32(scratch[16 * w + tid])) + safe = cutlass.Float32(0) if mm == cutlass.Float32(float("-inf")) else mm + out_m[h] = mm + scratch[16 * W + tid] = safe + scratch[16 * (W + 1) + tid] = cute.math.exp2( + incoming_max - safe, fastmath=fast_math + ) + cute.arch.sync_threads() + m0, m1 = scratch[16 * W + g], scratch[16 * W + g + 8] + sum0 = cutlass.Float32(0) + sum1 = cutlass.Float32(0) + for nt in cutlass.range_constexpr(N // (8 * W)): + i = 4 * nt + col = 8 * (nt * W + warp) + 2 * t + p0, p1 = ( + cute.math.exp2(scores[i] - m0, fastmath=fast_math), + cute.math.exp2(scores[i + 1] - m0, fastmath=fast_math), + ) + p2, p3 = ( + cute.math.exp2(scores[i + 2] - m1, fastmath=fast_math), + cute.math.exp2(scores[i + 3] - m1, fastmath=fast_math), + ) + sum0 = sum0 + (p0 + p1) + sum1 = sum1 + (p2 + p3) + # Preserve the graph's round-to-nearest conversion immediately + # before operand A of PV. The denominator consumed FP32 above. + probs[g * P_ROW + col], probs[g * P_ROW + col + 1] = ( + cutlass.BFloat16(p0), + cutlass.BFloat16(p1), + ) + probs[(g + 8) * P_ROW + col], probs[(g + 8) * P_ROW + col + 1] = ( + cutlass.BFloat16(p2), + cutlass.BFloat16(p3), + ) + sum0 = _warp_reduce_sum(sum0, threads_in_group=4) + sum1 = _warp_reduce_sum(sum1, threads_in_group=4) + if t == 0: + scratch[16 * warp + g] = sum0 + scratch[16 * warp + g + 8] = sum1 + cute.arch.sync_threads() + if tid < 16: + total = cutlass.Float32(0) + for w in cutlass.range_constexpr(W): + total = total + scratch[16 * w + tid] + h = group * 16 + tid + out_l[h] = ( + cutlass.Float32(prev_l[h]) + * cutlass.Float32(scratch[16 * (W + 1) + tid]) + + total + ) + if cutlass.const_expr(panel_storage is not None): + cute.arch.cp_async_wait_group(0) + cute.arch.sync_threads() + alpha0 = cutlass.Float32(scratch[16 * (W + 1) + g]) + alpha1 = cutlass.Float32(scratch[16 * (W + 1) + g + 8]) + for nc in cutlass.range_constexpr(D // (8 * W)): + base = 8 * (nc * W + warp) + col = base + 2 * t + c0, c1 = ( + prev_a[h0 * A_IN + col] * alpha0, + prev_a[h0 * A_IN + col + 1] * alpha0, + ) + c2, c3 = ( + prev_a[h1 * A_IN + col] * alpha1, + prev_a[h1 * A_IN + col + 1] * alpha1, + ) + if cutlass.const_expr(panel_storage is not None): + c0, c1, c2, c3 = panel.probability_value( + slab, probs, tid, nc, P_ROW, c0, c1, c2, c3 + ) + else: + vindex = cutlass.Int64(dim0) + base + g + valid_col = valid_v & (vindex >= 0) & (vindex < vwidth) + for ks in cutlass.range_constexpr(N // 16): + k = ks * 16 + 2 * t + a0 = _pair(probs.iterator, g * P_ROW + k, 1) + a1 = _pair(probs.iterator, (g + 8) * P_ROW + k, 1) + a2 = _pair(probs.iterator, g * P_ROW + k + 8, 1) + a3 = _pair(probs.iterator, (g + 8) * P_ROW + k + 8, 1) + basev = v_page + vindex * v_col + b0 = _zero_pair(vals.iterator, basev + k * v_row, v_row, valid_col) + b1 = _zero_pair( + vals.iterator, basev + (k + 8) * v_row, v_row, valid_col + ) + c0, c1, c2, c3 = mma_bf16(a0, a1, a2, a3, b0, b1, c0, c1, c2, c3) + out_a[h0 * A_OUT + col], out_a[h0 * A_OUT + col + 1] = c0, c1 + out_a[h1 * A_OUT + col], out_a[h1 * A_OUT + col + 1] = c2, c3 + # All users of P and the row scratch must finish before another + # iteration/row group can recycle either allocation. + cute.arch.sync_threads() + + +@cute.jit +def split_weighted_merge( + lse: cute.Tensor, + values: cute.Tensor, + output: cute.Tensor, + row: cute.Numeric, + col_base: cute.Numeric, + live_raw: cute.Numeric, + fast_math: cutlass.Constexpr = False, +) -> None: + nsplit = 64 # Two split slots per lane of the first warp. + x, y, z = cute.arch.thread_idx() + dx, dy, _dz = cute.arch.block_dim() + tid = cutlass.Int32(x + dx * (y + dy * z)) + buf = cutlass.utils.SmemAllocator().allocate(4 * (nsplit + 1), 16) + weights = cute.recast_ptr(buf, dtype=cutlass.Float32) + denominator = weights + nsplit + live = cutlass.Int32(live_raw) + if live < 0: + live = cutlass.Int32(0) + if live > nsplit: + live = cutlass.Int32(nsplit) + if tid < 32: + z0 = cutlass.Float32(float("-inf")) + z1 = cutlass.Float32(float("-inf")) + if tid < live: + z0 = lse[cutlass.Int64(tid), cutlass.Int64(row)] + if tid + 32 < live: + z1 = lse[cutlass.Int64(tid + 32), cutlass.Int64(row)] + top = _warp_reduce_max( + _cute_nan_max(cutlass.Float32(z0), cutlass.Float32(z1)), threads_in_group=32 + ) + if top == cutlass.Float32(float("-inf")): + top = cutlass.Float32(0) + a = cutlass.Float32(0) + b = cutlass.Float32(0) + if tid < live: + a = cute.math.exp2(z0 - top, fastmath=fast_math) + if tid + 32 < live: + b = cute.math.exp2(z1 - top, fastmath=fast_math) + (weights + tid).store(a) + (weights + tid + 32).store(b) + cute.arch.sync_threads() + if tid == 0: + den = cutlass.Float32(0) + for split in range(cutlass.Int32(0), live): + den = den + (weights + split).load() + denominator.store(den) + cute.arch.sync_threads() + acc = cutlass.Float32(0) + col = col_base + tid + for split in range(cutlass.Int32(0), live): + acc = ( + acc + + (weights + split).load() + * values[cutlass.Int64(split), cutlass.Int64(row), cutlass.Int64(col)] + ) + den = denominator.load() + if cutlass.const_expr(fast_math): + quotient = cute.math.div(acc, den, approx=True, ftz=True) + else: + quotient = acc / den + output[cutlass.Int64(row), cutlass.Int64(col)] = cutlass.BFloat16(quotient) + cute.arch.sync_threads() diff --git a/helion/_compiler/cute/analysis/gathered_softmax.py b/helion/_compiler/cute/analysis/gathered_softmax.py new file mode 100644 index 000000000..cf9912bde --- /dev/null +++ b/helion/_compiler/cute/analysis/gathered_softmax.py @@ -0,0 +1,216 @@ +"""Recognize a complete gathered QK, online softmax and PV page transition.""" + +from __future__ import annotations + +from dataclasses import dataclass +import operator +from typing import TYPE_CHECKING +from typing import cast + +import torch +from torch.fx import Node + +from ....language import _tracing_ops +from ....language import matmul_ops +from ....language import view_ops +from ..register_loads import host_load_is_readonly +from .gathered_bf16_mma import GatheredBf16Mma +from .gathered_bf16_mma import prove_gathered_bf16_mma +from .gathered_bf16_mma import unmasked_host_load +from .match_common import MatchFailure as _Mismatch +from .match_common import input_closure +from .match_common import is_call +from .match_common import match_args as _args +from .match_common import node_tensor +from .match_common import require_match as _require +from .match_common import scalar_value +from .match_common import strip_new_var + +if TYPE_CHECKING: + from collections.abc import Sequence + + from ...compile_environment import CompileEnvironment + from ...device_ir import GraphInfo + + +@dataclass(frozen=True) +class GatheredSoftmax: + qk: GatheredBf16Mma + value: Node + value_bid: int + logical: Node + scale: Node + limit: Node + previous_maximum: Node + previous_denominator: Node + previous_numerator: Node + + +def _row(node: object) -> object: + source, index = _args(node, view_ops.subscript, 2) + _require(index == [slice(None), None]) + return source + + +def _capture(node: object, dtype: torch.dtype, rank: int) -> Node: + source = strip_new_var(node) + t = node_tensor(source) + _require(isinstance(source, Node) and source.op == "placeholder") + _require(t is not None and t.dtype == dtype and t.ndim == rank) + return cast("Node", source) + + +def prove_gathered_softmax( + graph: torch.fx.Graph, graphs: Sequence[GraphInfo], env: CompileEnvironment +) -> GatheredSoftmax | None: + """Require exact dataflow through both MMAs and all three returned carries.""" + try: + aten = torch.ops.aten + output = graph.find_nodes(op="output")[0] + out = output.args[0] + _require(isinstance(out, (tuple, list)) and len(out) == 3) + maximum, denominator, numerator = cast("tuple[Node, Node, Node]", out) + maximum = cast("Node", strip_new_var(maximum)) + old_m, reduced_m = _args(maximum, aten.maximum.default, 2) + folded_m, axis = _args(reduced_m, aten.amax.default, 2) + scores, identity = _args(folded_m, _tracing_ops._mask_to, 2) + _require(axis == [-1] and identity == -float("inf")) + mask, scaled, invalid = _args(scores, aten.where.self, 3) + _require(scalar_value(invalid) == -float("inf")) + qk_phi, scale = _args(scaled, aten.mul.Tensor, 2) + _require( + is_call(scale, _tracing_ops._get_symnode) + and isinstance(cast("Node", scale).meta.get("val"), torch.SymFloat) + ) + seed, extraction = _args(qk_phi, _tracing_ops._phi, 2) + kfold, index = _args(extraction, operator.getitem, 2) + _require(isinstance(kfold, Node) and index == 0) + qk = prove_gathered_bf16_mma(cast("Node", kfold), graphs, env) + if qk is None or qk.seed is not seed: + return None + # Reductions below exclude no physical keys beyond the proved row mask. + pos2d, limits = _args(mask, aten.lt.Tensor, 2) + pos, index = _args(pos2d, view_ops.subscript, 2) + _require(index == [None, slice(None)]) + limit0 = _row(limits) + limit = strip_new_var(limit0) + ltensor = node_tensor(limit) + _require(isinstance(limit, Node) and limit.op == "placeholder") + _require( + ltensor is not None + and ltensor.shape == (qk.rows,) + and ltensor.dtype in (torch.int32, torch.int64) + ) + iota, offset = _args(pos, aten.add.Tensor, 2) + logical, page_len = _args(offset, operator.mul, 2) + table = unmasked_host_load(qk.page) + _require( + table is not None and table[1][-1] is logical and page_len == qk.columns + ) + _require(isinstance(iota, Node) and is_call(iota, torch.ops.prims.iota.default)) + arange = cast("Node", iota) + _require( + arange.args == (qk.columns,) + and arange.kwargs.get("start") == 0 + and arange.kwargs.get("step") == 1 + ) + _require( + arange.kwargs.get("dtype") == torch.int32 + and not arange.kwargs.get("requires_grad", False) + ) + lhs_cast, v, correction, precision = _args(numerator, matmul_ops.dot, 4) + _require(precision is None) + p32, cast_type = _args( + lhs_cast, torch.ops.prims.convert_element_type.default, 2 + ) + _require(cast_type == torch.bfloat16) + (diff,) = _args(p32, aten.exp2.default, 1) + scores2, broadcast_m = _args(diff, aten.sub.Tensor, 2) + _require(scores2 is scores) + safe_m = _row(broadcast_m) + eq, zero, same_max = _args(safe_m, aten.where.self, 3) + eq_max, eq_inf = _args(eq, aten.eq.Scalar, 2) + _require( + eq_max is maximum + and same_max is maximum + and eq_inf == -float("inf") + and scalar_value(zero) == 0 + ) + old_acc, broadcast_alpha = _args(correction, aten.mul.Tensor, 2) + alpha = _row(broadcast_alpha) + (adiff,) = _args(alpha, aten.exp2.default, 1) + _require(_args(adiff, aten.sub.Tensor, 2) == (old_m, safe_m)) + scaled_old, reduced_l = _args(denominator, aten.add.Tensor, 2) + old_l, lalpha = _args(scaled_old, aten.mul.Tensor, 2) + folded_p, axis = _args(reduced_l, aten.sum.dim_IntList, 2) + _require( + lalpha is alpha + and axis == [-1] + and _args(folded_p, _tracing_ops._mask_to, 2) == (p32, 0) + ) + # FX scalar promotion and the reduction dtype are part of the + # recurrence. In particular a widened or pre-rounded denominator + # is not the FP32 sum of the unrounded exponentials. + for value32 in ( + scaled, + scores, + maximum, + safe_m, + alpha, + p32, + denominator, + numerator, + ): + tensor32 = node_tensor(value32) + _require(tensor32 is not None and tensor32.dtype == torch.float32) + pos1d = node_tensor(pos) + _require(pos1d is not None and pos1d.dtype == torch.int32) + m = _capture(old_m, torch.float32, 1) + denom = _capture(old_l, torch.float32, 1) + a = _capture(old_acc, torch.float32, 2) + _require(len({m, denom, a, limit}) == 4) + vm = unmasked_host_load(v) + if vm is None: + return None + value, vidx = vm + _require(len(vidx) == 3 and vidx[0] is qk.page and vidx[1] == slice(None)) + vid = vidx[2] + _require(_args(vid, aten.sym_size.int, 2) == (a, 1)) + sym = cast("Node", vid).meta.get("val") + bid = env.resolve_block_id(sym) + _require( + isinstance(sym, torch.SymInt) + and bid is not None + and sym._sympy_() == env.block_sizes[bid].var._sympy_() + ) + vt = node_tensor(value) + _require( + vt is not None + and vt.dtype == torch.bfloat16 + and vt.ndim == 3 + and env.known_equal(vt.size(1), qk.columns) + ) + _require( + host_load_is_readonly(cast("Node", v), env, graphs) + and host_load_is_readonly(qk.page, env, graphs) + ) + for state in (m, denom, a): + st = node_tensor(state) + _require(st is not None and env.known_equal(st.size(0), qk.rows)) + # The omitted body is exactly the ancestors of its outputs. Never drop a + # store, assertion, barrier, atomic, or any other unused executable node. + live = input_closure(output) + _require(all(n.op == "placeholder" or n in live for n in graph.nodes)) + return GatheredSoftmax( + qk, + value, + cast("int", bid), + cast("Node", logical), + cast("Node", scale), + cast("Node", limit), + m, + denom, + a, + ) + except _Mismatch: + return None diff --git a/helion/_compiler/cute/analysis/match_common.py b/helion/_compiler/cute/analysis/match_common.py index 45c7674a2..e96c39970 100644 --- a/helion/_compiler/cute/analysis/match_common.py +++ b/helion/_compiler/cute/analysis/match_common.py @@ -24,6 +24,7 @@ from typing import TYPE_CHECKING from typing import NamedTuple +from typing import cast import sympy import torch @@ -47,6 +48,22 @@ def is_call(node: object, *targets: object) -> bool: ) +class MatchFailure(Exception): + """A required FX dataflow or memory fact is absent.""" + + +def require_match(test: object) -> None: + if not test: + raise MatchFailure + + +def match_args(node: object, target: object, arity: int) -> tuple[object, ...]: + require_match(is_call(node, target)) + call = cast("torch.fx.Node", node) + require_match(len(call.args) == arity and not call.kwargs) + return call.args + + def input_closure(output: torch.fx.Node) -> set[torch.fx.Node]: """All FX inputs required to produce one value, including the value itself.""" live = {output} diff --git a/helion/_compiler/cute/analysis/split_weighted_merge.py b/helion/_compiler/cute/analysis/split_weighted_merge.py new file mode 100644 index 000000000..38fdb6e63 --- /dev/null +++ b/helion/_compiler/cute/analysis/split_weighted_merge.py @@ -0,0 +1,352 @@ +"""Proof of a bounded two-pass, masked softmax-weighted split reduction.""" + +from __future__ import annotations + +from dataclasses import dataclass +import operator +from typing import TYPE_CHECKING +from typing import cast + +import torch +from torch.fx import Node + +from ....language import _tracing_ops as ops +from ....language import creation_ops +from ....language import memory_ops +from ....language import tile_ops +from ....language import view_ops +from ...device_ir import ForLoopGraphInfo +from ...device_ir import IfGraphInfo +from ..register_loads import host_storages_may_alias +from .match_common import MatchFailure as _Mismatch +from .match_common import input_closure +from .match_common import is_call +from .match_common import match_args as _args +from .match_common import node_tensor +from .match_common import require_match as _require +from .match_common import strip_new_var + +if TYPE_CHECKING: + from collections.abc import Sequence + + from ...compile_environment import CompileEnvironment + from ...device_ir import GraphInfo + + +@dataclass(frozen=True) +class SplitWeightedMerge: + live: Node + scores: Node + values: Node + output: Node + split_axis: int + + +def _outputs(g: torch.fx.Graph) -> list[Node]: + stmt = g.find_nodes(op="output")[0] + seq = stmt.args[0] + _require(isinstance(seq, (tuple, list))) + return list(cast("list[Node]", seq)) + + +def _covered(g: torch.fx.Graph, sinks: list[Node]) -> None: + # Do not erase a sibling effect, even when its result never reaches the + # visible carries (stores, inline assembly, nested barriers, etc.). + active = set().union(*(input_closure(s) for s in sinks)) + _require(all(n.op in ("output", "placeholder") or n in active for n in g.nodes)) + + +def _axis(x: object, env: CompileEnvironment) -> int: + _require( + isinstance(x, Node) + and is_call(x, ops._get_symnode, torch.ops.aten.sym_size.int) + ) + val = cast("Node", x).meta.get("val") + _require(isinstance(val, torch.SymInt)) + bid = env.resolve_block_id(cast("torch.SymInt", val)) + _require(type(bid) is int) + return cast("int", bid) + + +def _axes(x: object, env: CompileEnvironment) -> list[int]: + _require(isinstance(x, (list, tuple))) + return [_axis(a, env) for a in cast("list[object]", x)] + + +def _typed(x: object, dtype: torch.dtype, rank: int) -> torch.Tensor: + t = node_tensor(x) + _require(t is not None and t.dtype == dtype and t.ndim == rank) + return cast("torch.Tensor", t) + + +def _scalar(x: object, value: float) -> None: + _require(is_call(x, torch.ops.aten.scalar_tensor.default)) + n = cast("Node", x) + _require(n.args == (value,) and not set(n.kwargs) - {"dtype", "device", "layout"}) + _typed(n, torch.float32, 0) + + +def _view(x: object, index: Sequence[object]) -> object: + src, subscripts = _args(x, view_ops.subscript, 2) + _require(subscripts == index) + return src + + +def _loop( + call: Node, graphs: Sequence[GraphInfo], env: CompileEnvironment, carries: int +) -> tuple[int, list[Node], list[Node], list[Node]]: + gid, start, stop, captures = _args(call, ops._for_loop, 4) + _require(type(gid) is int and start == [0] and stop == [64]) + _require(0 <= cast("int", gid) < len(graphs)) + info = graphs[cast("int", gid)] + _require(isinstance(info, ForLoopGraphInfo)) + body = cast("ForLoopGraphInfo", info) + _require(len(body.block_ids) == 1 and not body.needs_barrier_before) + (axis,) = body.block_ids + params = body.graph.find_nodes(op="placeholder") + _require( + isinstance(captures, (tuple, list)) + and len(params) == len(cast("list[Node]", captures)) == 2 * carries + ) + conditionals = body.graph.find_nodes(op="call_function", target=ops._if) + _require(len(conditionals) == 1) + (cond,) = conditionals + pred, then_id, else_id, args, no_args = _args(cond, ops._if, 5) + _require(type(then_id) is int and type(else_id) is int and no_args == []) + _require( + isinstance(args, (tuple, list)) + and [strip_new_var(a) for a in cast("list[Node]", args)] == params + ) + limit, begin = _args(pred, torch.ops.aten.gt.Scalar, 2) + (axis_sym,) = _args(begin, tile_ops.tile_begin, 1) + _require(strip_new_var(limit) is params[0] and _axis(axis_sym, env) == axis) + _require(all(0 <= cast("int", gid) < len(graphs) for gid in (then_id, else_id))) + then = graphs[cast("int", then_id)] + other = graphs[cast("int", else_id)] + _require(isinstance(then, IfGraphInfo) and not _outputs(other.graph)) + _covered(other.graph, []) + branch = cast("IfGraphInfo", then) + _require(branch.else_branch == else_id and branch.predicate_is_tensor is False) + joined = _outputs(body.graph) + _require(len(joined) == carries and len(branch.branches_outputs or ()) == carries) + _covered(body.graph, joined) + for i, result in enumerate(joined): + prev, updated = _args(result, ops._phi, 2) + _require(_args(prev, operator.getitem, 2) == (cond, i + carries)) + _require(_args(updated, operator.getitem, 2) == (cond, i)) + names = branch.if_arg_names + _require( + names is not None + and len(names) == len(params) + and len(set(names)) == len(params) + ) + _require(branch.else_arg_names == []) + _require( + branch.branches_outputs + == [ + (i, cast("list[str]", names)[len(params) - carries + i]) + for i in range(carries) + ] + ) + inputs = branch.graph.find_nodes(op="placeholder") + _require(len(inputs) == len(params)) + outputs = _outputs(branch.graph)[:carries] + _require(len(outputs) == carries) + _covered(branch.graph, outputs) + return axis, list(cast("list[Node]", captures)), inputs, outputs + + +def prove_split_weighted_merge( + graph: torch.fx.Graph, + graphs: Sequence[GraphInfo], + env: CompileEnvironment, + row: int, + column: int, +) -> SplitWeightedMerge | None: + """Prove axis, carry, address, mask and alias identity through both loops. + + Only the scalar live bound is opaque, and it is compiled with the normal + graph lowering. Its input loads are scalar and CTA-uniform. Sixty-four + split slots are the only measured two-elements-per-warp-lane schedule. + """ + aten = torch.ops.aten + sl = slice(None) + negative_infinity = -float("inf") + try: + loops = graph.find_nodes(op="call_function", target=ops._for_loop) + stores = graph.find_nodes(op="call_function", target=memory_ops.store) + _require(len(loops) == 2 and len(stores) == 1) + lmax, lsum = loops + (store,) = stores + dst, idx, stored, mask = _args(store, memory_ops.store, 4) + _require( + mask is None + and _axes(idx, env) == [row, column] + and is_call(dst, ops._host_tensor) + ) + _require(graph.find_nodes(op="output")[0].args == (None,)) + _covered(graph, [store]) + sa, c0, p0, max_out = _loop(lmax, graphs, env, 1) + sb, c1, p1, sum_out = _loop(lsum, graphs, env, 2) + _require(sa == sb and len({sa, row, column}) == 3 and c0[0] is c1[0]) + live = c0[0] + _typed(live, torch.int32, 0) + # Live may be any expression composed of these scalar, uniform ops. + # Do not hoist per-tile/per-lane inputs or an unrelated effect. + srcs = [] + for n in input_closure(live): + if is_call(n, ops._host_tensor): + continue + _typed(n, torch.int32, 0) + if is_call(n, memory_ops.load): + host, coords, guard, fallback = _args(n, memory_ops.load, 4) + _require( + is_call(host, ops._host_tensor) + and guard is None + and fallback is None + ) + _require( + isinstance(coords, (tuple, list)) + and all(type(i) is int for i in cast("list[object]", coords)) + ) + srcs.append(cast("Node", host)) + else: + _require( + is_call( + n, + aten.add.Tensor, + aten.sub.Tensor, + aten.mul.Tensor, + aten.div.Tensor_mode, + ) + ) + + def full(x: object, dimensions: list[int], value: float) -> None: + shape, fill, dt, extra = _args(x, creation_ops.full, 4) + _require( + _axes(shape, env) == dimensions + and fill == value + and dt == torch.float32 + and extra is None + ) + + full(c0[1], [row], negative_infinity) + full(c1[2], [row], 0) + full(c1[3], [row, column], 0) + eq, zero, top = _args(c1[1], aten.where.self, 3) + _require(_args(eq, aten.eq.Scalar, 2) == (top, negative_infinity)) + _scalar(zero, 0) + + def joined(x: object, loop: Node, index: int, init: Node) -> None: + old, extracted = _args(x, ops._phi, 2) + _require( + old is init and _args(extracted, operator.getitem, 2) == (loop, index) + ) + + joined(top, lmax, 0, c0[1]) + val, dt = _args(stored, torch.ops.prims.convert_element_type.default, 2) + _require(dt == torch.bfloat16) + numerator, denom = _args(val, aten.div.Tensor, 2) + joined(numerator, lsum, 1, c1[3]) + joined(_view(denom, [sl, None]), lsum, 0, c1[2]) + + def masked_load( + x: object, dims: list[int], provided: object, arg: Node + ) -> Node: + host, index, masked, mode = _args(x, memory_ops.load, 4) + _require( + is_call(host, ops._host_tensor) + and mode is None + and _axes(index, env) == dims + ) + valid = _view(masked, [sl] + [None] * (len(dims) - 1)) + ids, limit = _args(valid, aten.lt.Tensor, 2) + (split,) = _args(ids, tile_ops.tile_index, 1) + _require(_axis(split, env) == sa and strip_new_var(limit) is arg) + if provided is not None: + _require(valid is provided) + return cast("Node", host) + + old, group = _args(max_out[0], aten.maximum.default, 2) + _require(strip_new_var(old) is p0[1]) + masked, axis = _args(group, aten.amax.default, 2) + chosen, identity = _args(masked, ops._mask_to, 2) + _require(axis == [0] and identity == negative_infinity) + cond, lse, neg_inf = _args(chosen, aten.where.self, 3) + _scalar(neg_inf, negative_infinity) + scores = masked_load(lse, [sa, row], _view(cond, [sl, None]), p0[0]) + + def summed(x: Node, previous: Node, *, product: bool = False) -> object: + prev, total = _args(x, aten.add.Tensor, 2) + _require(strip_new_var(prev) is previous) + mask_to, which = _args(total, aten.sum.dim_IntList, 2) + _require(which == [0]) + if is_call(mask_to, ops._mask_to): + expr, neutral = _args(mask_to, ops._mask_to, 2) + _require(neutral == 0) + return expr + # Fast math can drop the implicit zero mask around the numerator + # product. Below, prove the weight is zero for every inactive + # split and the value load has the identical live split mask. + # The emitter requires full rows/columns and a unit split tile. + _require( + product and env.settings.fast_math and is_call(mask_to, aten.mul.Tensor) + ) + return mask_to + + weight = summed(sum_out[0], p1[2]) + condition, e, zero2 = _args(weight, aten.where.self, 3) + _scalar(zero2, 0) + valid = _view(condition, [sl, None]) + (diff,) = _args(e, aten.exp2.default, 1) + lse2, best2 = _args(diff, aten.sub.Tensor, 2) + _require(strip_new_var(_view(best2, [None, sl])) is p1[1]) + same_scores = masked_load(lse2, [sa, row], valid, p1[0]) + _require( + scores.args == same_scores.args + and node_tensor(scores) is node_tensor(same_scores) + ) + w, partial = _args(summed(sum_out[1], p1[3], product=True), aten.mul.Tensor, 2) + _require(_view(w, [sl, sl, None]) is weight) + values = masked_load(partial, [sa, row, column], valid, p1[0]) + dst_tensor = _typed(dst, torch.bfloat16, 2) + lse_tensor = _typed(scores, torch.float32, 2) + val_tensor = _typed(values, torch.float32, 3) + rows, cols = dst_tensor.shape + _require( + type(rows) is int + and type(cols) is int + and rows > 0 + and cols > 0 + and cols % 128 == 0 + ) + row_extent, column_extent = ( + env.block_sizes[row].size, + env.block_sizes[column].size, + ) + if not isinstance(row_extent, (int, torch.SymInt)) or not isinstance( + column_extent, (int, torch.SymInt) + ): + return None + _require( + env.known_equal(row_extent, rows) and env.known_equal(column_extent, cols) + ) + _require( + tuple(lse_tensor.shape) == (64, rows) + and tuple(val_tensor.shape) == (64, rows, cols) + ) + _require( + env.traced_strides_hold(dst_tensor) + and all(type(s) is int for s in dst_tensor.stride()) + ) + # Disjoint rows/columns suffice; transposed outputs also qualify. + rs, cs = dst_tensor.stride() + _require(rs > 0 and cs > 0 and (rs >= cols * cs or cs >= rows * rs)) + for source in [scores, values, *srcs]: + src = node_tensor(source) + _require( + src is not None and not host_storages_may_alias(env, dst_tensor, src) + ) + return SplitWeightedMerge(live, scores, values, cast("Node", dst), sa) + except _Mismatch: + return None diff --git a/helion/_compiler/cute/autotune/config_keys.py b/helion/_compiler/cute/autotune/config_keys.py index f135b2dc0..626ae6139 100644 --- a/helion/_compiler/cute/autotune/config_keys.py +++ b/helion/_compiler/cute/autotune/config_keys.py @@ -129,6 +129,8 @@ def _cute_chunk_recurrence_config_is_safe( "cute_fragment_reduction", "cute_fp32_dot", "cute_fragment_half_mma", + "cute_gathered_page_pipeline", + "cute_gathered_page_stages", "cute_fragment_threads", "cute_fragment_register_loads", "cute_fragment_producer_cache", diff --git a/helion/_compiler/cute/autotune/fragment_knobs.py b/helion/_compiler/cute/autotune/fragment_knobs.py index d3a29fdd0..4e4b85b81 100644 --- a/helion/_compiler/cute/autotune/fragment_knobs.py +++ b/helion/_compiler/cute/autotune/fragment_knobs.py @@ -1659,6 +1659,7 @@ def _half_mma_roots(env: CompileEnvironment, ir: DeviceIR) -> RootFacts: from ..analysis.gathered_bf16_mma import gathered_phase_region from ..computed_fragment import computed_fragment_supported from .heuristics.cute_gathered_bf16_mma import gathered_phase_carrier + from .heuristics.cute_gathered_bf16_mma import streaming_phase_carriers roots = { region.root @@ -1672,7 +1673,7 @@ def _half_mma_roots(env: CompileEnvironment, ir: DeviceIR) -> RootFacts: carrier = gathered_phase_carrier(env, ir, region) if carrier is not None: roots.add(ir.root_ids[0]) - carriers = (carrier,) + carriers = (carrier, *streaming_phase_carriers(env, ir, carrier, region)) return RootFacts( frozenset(roots), ( @@ -1681,6 +1682,15 @@ def _half_mma_roots(env: CompileEnvironment, ir: DeviceIR) -> RootFacts: frozenset(tuple(c.num_threads) for c in carriers), ), ("cute_gathered_phase_carriers", tuple(c.config for c in carriers)), + ( + "cute_gathered_page_value_bid", + ir.grid_block_ids[0][1] + if any( + c.config.get("cute_gathered_page_pipeline") + for c in carriers + ) + else None, + ), ), ) return RootFacts(frozenset(roots)) diff --git a/helion/_compiler/cute/autotune/heuristics/cute_gathered_bf16_mma.py b/helion/_compiler/cute/autotune/heuristics/cute_gathered_bf16_mma.py index 9192934a1..44d2014c5 100644 --- a/helion/_compiler/cute/autotune/heuristics/cute_gathered_bf16_mma.py +++ b/helion/_compiler/cute/autotune/heuristics/cute_gathered_bf16_mma.py @@ -10,8 +10,12 @@ from .....runtime.config import Config from ....autotuner_heuristics.registry import AutotunerHeuristic from ....inductor_lowering import ReductionLowering +from ... import gathered_panel_layout as panels +from ... import target_facts from ...analysis.match_common import unit_fixed_block +from ...cooperative_grid_init import grid_init_carrier from ...gathered_launch import GATHERED_SEED_THREADS +from ..config_keys import GRID_INIT_KEY if TYPE_CHECKING: from collections.abc import Sequence @@ -142,6 +146,136 @@ def down(value: int, cap: int) -> int: ) +def streaming_phase_carriers( + env: CompileEnvironment, ir: DeviceIR, base: Config, region: Sequence[GraphInfo] +) -> list[Config]: + """When an entire page transition is warp-native, give the merge every lane. + + The producer cooperates across the whole CTA, so its logical page and + output axes need no physical thread coordinates. Assigning all CTA lanes + to consecutive merge columns avoids executing each split loop once per + unused producer x-lane. At two page widths, split-first order balances + independent CTAs and QK reuse; a one-page-width value-first panel keeps + consecutive PIDs on live splits. Retain the wide panel for long contexts. + """ + # The registry loads before the public Config export; FX analysis imports + # fragment memory code that depends on that export. + from ...analysis.gathered_softmax import prove_gathered_softmax + from ...gathered_softmax import can_pipeline_page + + if ir.host_function is None or len(ir.grid_block_ids) != 2: + return [] + with ir.host_function: + pages = [ + p + for g in region + if (p := prove_gathered_softmax(g.graph, ir.graphs, env)) is not None + ] + if len(pages) != 1: + return [] + page = pages[0] + _, value_axis = ir.grid_block_ids[0] + row_axis, column_axis = ir.grid_block_ids[1] + extent = env.block_sizes[value_axis].size + if ( + page.value_bid != value_axis + or type(extent) is not int + or extent < GATHERED_SEED_THREADS + or extent % GATHERED_SEED_THREADS + ): + return [] + spec = env.config_spec + lanes = [ + GATHERED_SEED_THREADS if item.block_id == column_axis else 1 + for item in spec.num_threads + ] + choices = [] + for width in dict.fromkeys( + min(extent, size) + for size in (2 * page.qk.columns, page.qk.columns, 4 * page.qk.columns) + ): + if width % 32 or extent % width: + continue + sizes = {value_axis: width, row_axis: 1, column_axis: GATHERED_SEED_THREADS} + # The first grid axis is split, the second is value. Only this + # narrow panel benefits from assigning neighboring physical workers + # consecutive value panels of the same live split. Keep every other + # root's ordinary order. + order: dict[str, object] = {} + if width == page.qk.columns: + orders = [] + for item in spec.loop_orders: + axes = list(range(len(item.block_ids))) + if item.block_ids == ir.grid_block_ids[0]: + axes.reverse() + orders.append(axes) + if orders: + order["loop_orders"] = orders + choices.append( + Config.from_dict( + base.config + | order + | { + "block_sizes": [ + sizes.get(item.block_id, existing) + for item, existing in zip( + spec.block_sizes, base.block_sizes, strict=True + ) + ], + "num_threads": lanes, + # Both independent barrier phases can occupy all workers, + # including a short merge after a much larger producer. + "pid_type": ( + "persistent_interleaved" + if "persistent_interleaved" in spec.allowed_pid_types + else base.pid_type + ), + } + ) + ) + # Preserve existing reproducible seeds and add opt-in pipeline + # carriers for compatible geometry, row strides and current pointers. + # Lowering independently requires all three cache-backed alignment proofs. + for config in choices.copy(): + width = next( + size + for item, size in zip(spec.block_sizes, config.block_sizes, strict=True) + if item.block_id == value_axis + ) + if can_pipeline_page( + env, page, width, GATHERED_SEED_THREADS, require_bound_pointer=False + ): + pipeline = config.config | {"cute_gathered_page_pipeline": True} + choices.extend( + ( + Config.from_dict(pipeline), + Config.from_dict(pipeline | {"cute_gathered_page_stages": 4}), + ) + ) + # A long contraction can start eight distinct cp.async groups + # immediately. Do not plant this high-storage carrier on a short + # contraction or a device where even its page buffers do not fit. + # Codegen subsequently budgets the complete phase and launcher. + maximum = panels.RING_STAGES[-1] + capacity = target_facts.per_cta_smem_capacity_bytes(env.device) + if ( + page.qk.depth >= maximum * panels.DEPTH_PANEL + and capacity + and panels.working_set_bytes( + page.qk.rows, page.qk.columns, width, maximum + ) + <= capacity + ): + deepest = pipeline | {"cute_gathered_page_stages": maximum} + choices.append(Config.from_dict(deepest)) + # A short merge should not pay a second device launch just + # to zero its grid counter. Keep the host-zeroed schedule as + # a comparison and offer only one additional long-K carrier. + if grid_init_carrier(spec, deepest): + choices.append(Config.from_dict(deepest | {GRID_INIT_KEY: True})) + return choices + + class CuteGatheredBf16MmaSeed(AutotunerHeuristic): name = "cute_gathered_bf16_mma" backend = "cute" diff --git a/helion/_compiler/cute/autotune/mma_dag_surface.py b/helion/_compiler/cute/autotune/mma_dag_surface.py index e5fdadb8b..11a2e36d9 100644 --- a/helion/_compiler/cute/autotune/mma_dag_surface.py +++ b/helion/_compiler/cute/autotune/mma_dag_surface.py @@ -468,6 +468,8 @@ def _normalize_cute_register_subblocks( for key in ( "cute_fp32_dot", "cute_fragment_half_mma", + "cute_gathered_page_pipeline", + "cute_gathered_page_stages", "cute_fragment_padded_rows", "cute_fragment_unrolled_loops", "cute_fragment_vector_io", diff --git a/helion/_compiler/cute/autotune/search_surface.py b/helion/_compiler/cute/autotune/search_surface.py index d68aa6a3f..711846b3f 100644 --- a/helion/_compiler/cute/autotune/search_surface.py +++ b/helion/_compiler/cute/autotune/search_surface.py @@ -92,6 +92,8 @@ from ..fragment_mma_dot import FRAGMENT_MMA_ROW_THREADS from ..gathered_launch import GATHERED_SEED_THREADS from ..gathered_launch import gathered_launch_compatible +from ..gathered_panel_layout import RING_STAGES +from ..gathered_panel_layout import VALUE_PANEL from ..packet_store_policy import store_policy_reaches_a_packet from ..pdl_release import CUTE_PDL_CAPTURE_RELEASE_CHOICES from ..pdl_release import CUTE_PDL_RELEASE_CHOICES @@ -398,6 +400,25 @@ class _FragmentOption(NamedTuple): "an fp32 hl.dot in a computed fragment under tf32 dot precision", ("simt", "tf32_mma"), ), + "cute_gathered_page_stages": _FragmentOption( + lambda spec, config: config.get("cute_gathered_page_pipeline") is True, + "a 16-byte-aligned asynchronous gathered page", + RING_STAGES, + ), + "cute_gathered_page_pipeline": _FragmentOption( + lambda spec, config: ( + config.get("cute_fragment_half_mma") is True + and (bid := spec.cute_gathered_page_value_bid) is not None + and isinstance(sizes := config.get("block_sizes"), (list, tuple)) + and spec.block_sizes.config_get(list(sizes), bid) == VALUE_PANEL + and gathered_launch_compatible( + config, + actual_threads=_fragment_threads(config), + required_threads=GATHERED_SEED_THREADS, + ) + ), + "a certified, 16-byte aligned gathered BF16 page and its four-warp panel geometry", + ), "cute_fragment_half_mma": _FragmentOption( lambda spec, config: spec.cute_fragment_half_mma_root_ids, "an FP16/BF16 hl.dot with FP32 accumulation in a computed fragment on SM80+", @@ -3284,6 +3305,12 @@ def normalize_knobs( ) ): config.pop("cute_fragment_half_mma", None) + _normalize_fragment_option( + config_spec, config, "cute_gathered_page_pipeline", fix_invalid=fix_invalid + ) + _normalize_fragment_option( + config_spec, config, "cute_gathered_page_stages", fix_invalid=fix_invalid + ) _normalize_cute_fragment_threads(config_spec, config, fix_invalid=fix_invalid) _normalize_fragment_option( config_spec, config, "cute_fragment_producer_cache", fix_invalid=fix_invalid @@ -4525,6 +4552,12 @@ def cute_flat_fields( if enabled } ) + if any( + c.get("cute_gathered_page_pipeline") + for c in config_spec.cute_gathered_phase_carriers + ): + fields["cute_gathered_page_pipeline"] = BooleanFragment() + fields["cute_gathered_page_stages"] = EnumFragment(choices=RING_STAGES) if config_spec.cute_fragment_warp_scan_search_enabled: fields["cute_fragment_warp_scan"] = BooleanFragment() if config_spec.cute_fragment_topk_network_search_enabled: @@ -5488,6 +5521,8 @@ def flatten_missing_field_default( return True, "off" if key == "cute_materialized_operand_schedule": return True, "off" + if key == "cute_gathered_page_stages": + return True, 2 if key in ("cute_fragment_private_scalar_loops", GRID_INIT_KEY): return True, False if key == "cute_fragment_producer_cache": @@ -5497,6 +5532,7 @@ def flatten_missing_field_default( if key in ( "cute_fragment_register_loads", "cute_fragment_half_mma", + "cute_gathered_page_pipeline", "cute_fragment_warp_scan", "cute_fragment_topk_network", "cute_fragment_cta_topk", diff --git a/helion/_compiler/cute/computed_fragment.py b/helion/_compiler/cute/computed_fragment.py index d59e02079..88047eb7a 100644 --- a/helion/_compiler/cute/computed_fragment.py +++ b/helion/_compiler/cute/computed_fragment.py @@ -68,7 +68,10 @@ from .full_reduction_owner import fragment_store_destinations from .full_reduction_owner import requires_full_reduction_owner from .gathered_bf16_dot import gathered_bf16_dot +from .gathered_launch import GATHERED_SEED_THREADS from .gathered_launch import gathered_launch_compatible +from .gathered_softmax import emit_gathered_softmax_preamble +from .gathered_softmax import gathered_softmax_page from .handler_ops import integer_to_float_expr from .handler_ops import scalar_value_dtype from .launch_shape import LINEAR_THREAD @@ -94,6 +97,7 @@ from .selection.ordered_selection import is_ordered_selection from .selection.ordered_selection import ordered_selection_args from .selection.ordered_selection import topk_outputs_keep_sort_lanes +from .split_weighted_merge import emit_split_weighted_merge from .static_indexing import shape_only_indices from .static_indexing import static_tensor_index @@ -652,9 +656,22 @@ def graph( values: dict[Node, object], *, output_indices: frozenset[int] | None = None, + private_loop_outputs: dict[int, tuple[Node, Fragment]] | None = None, ) -> object: from .producer_cache import producer_cache_candidates + if output_indices is None and self.df.config.get( + "cute_fragment_half_mma", False + ): + fused = gathered_softmax_page(self, graph, values, private_loop_outputs) + if fused is not None: + return fused + if private_loop_outputs is not None: + # Ordinary graph evaluation does not promise that all readers of + # an incoming carry finished before a returned fragment aliases it. + # Keep its established parallel-assignment/synchronization path. + private_loop_outputs.clear() + cache_nodes = ( producer_cache_candidates(graph, self.shape) if self.df.config.get("cute_fragment_producer_cache", False) @@ -2241,6 +2258,9 @@ def codegen_computed_fragment_root(cg: GenerateAST) -> bool: "a planned root cannot share a computed fragment schedule" ) return False + if state.lanes.gathered_phase_threads == GATHERED_SEED_THREADS: + if emit_split_weighted_merge(cg): + return True ir = cg.host_function.device_ir multiple_roots = len(ir.root_ids) != 1 selection_required = False @@ -2708,6 +2728,17 @@ def active_graphs(graphs: list[GraphInfo]) -> list[GraphInfo]: compiler.synchronize() if compiler.warp_producer_recorder is not None: compiler.warp_producer_recorder.lower(body) + if ( + gathered_region is not None + and compiler.df.config.get("cute_gathered_page_pipeline") + and not compiler.used_async_gathered_page + ): + # A different gathered-dot fold is not evidence that the configured + # complete page pipeline ran. Do not time scalar or direct folds + # under an explicit async configuration. + raise exc.InvalidConfig( + "the certified producer did not emit the configured asynchronous gathered page" + ) capacity = target_facts.per_cta_smem_capacity_bytes(compiler.env.device) if ( required_owner @@ -2755,8 +2786,10 @@ def active_graphs(graphs: list[GraphInfo]) -> list[GraphInfo]: "shared producer caches require a known shared memory capacity" ) if capacity and compiler.smem_bytes > capacity: - if required_owner: - # These roots have no other owner: the config is invalid. + if required_owner or compiler.used_async_gathered_page: + # A required owner has no fallback; an explicitly selected async + # program must also fit its actual allocation rather than silently + # timing a scalar fallback under the pipeline's config. raise exc.InvalidConfig( f"computed fragments need {compiler.smem_bytes} shared bytes, exceeding {capacity}" ) @@ -2809,6 +2842,8 @@ def active_graphs(graphs: list[GraphInfo]) -> list[GraphInfo]: ) elif gathered_region is not None: cg.device_function.cute_state.lanes.gathered_phase_threads = compiler.threads + if compiler.needs_gathered_softmax_runtime: + emit_gathered_softmax_preamble(cg) compiler.emit_mma_preamble() allocations = compiler.allocations() if compiler.shared_arena_plan is not None: diff --git a/helion/_compiler/cute/fragment_context.py b/helion/_compiler/cute/fragment_context.py index f5972d87c..dce67a685 100644 --- a/helion/_compiler/cute/fragment_context.py +++ b/helion/_compiler/cute/fragment_context.py @@ -115,6 +115,17 @@ def _loop_carry_slots(node: Node) -> dict[int, int]: return slots +@dataclass(frozen=True) +class DenseSharedIndex: + """The canonical zero-offset read of an allocator-owned shared tile.""" + + name: str + physical_shape: tuple[int, ...] + + def __call__(self, indices: tuple[str, ...]) -> str: + return f"{self.name}[{FragmentContext.flatten(indices, self.physical_shape)}]" + + @dataclass(frozen=True) class Fragment: shape: tuple[int, ...] @@ -476,12 +487,17 @@ def graph( values: dict[Node, object], *, output_indices: frozenset[int] | None = None, + private_loop_outputs: dict[int, tuple[Node, Fragment]] | None = None, ) -> object: """Walk a (nested) graph, binding every node's lowering into ``values``. The control-flow emitters call back into the walk for their bodies; ``FragmentCompiler`` provides it. A proved branch projection can retain only selected return slots; it still emits every node and effect. + A loop may offer its private input/output buffers to a complete + transition. Returning an offered buffer by identity means its final + value is already visible to the CTA; lowering that cannot guarantee + this clears the offer before returning ordinary graph results. """ raise NotImplementedError @@ -509,6 +525,8 @@ def __init__(self, cg: GenerateAST, graphs: list[GraphInfo] | None = None) -> No self.held: list[object] = [] self.threads = cast("int", self.df.config.get("cute_fragment_threads", 128)) self.used_gathered_bf16_fold = False + self.used_async_gathered_page = False + self.needs_gathered_softmax_runtime = False self.thread = "" self.block_volume: str | None = None self.padded_rows = bool(self.df.config.get("cute_fragment_padded_rows", False)) @@ -1190,7 +1208,7 @@ def allocate(self, value: Fragment) -> Fragment: return Fragment( value.shape, value.dtype, - lambda indices: f"{name}[{self.flatten(indices, physical)}]", + DenseSharedIndex(name, physical), True, (), name, diff --git a/helion/_compiler/cute/fragment_control_flow.py b/helion/_compiler/cute/fragment_control_flow.py index 74ce15020..d04fdea15 100644 --- a/helion/_compiler/cute/fragment_control_flow.py +++ b/helion/_compiler/cute/fragment_control_flow.py @@ -373,7 +373,19 @@ def proof_source(value: object, rendered: str) -> str: ], ), ): - results = self.graph(graph.graph, body_inputs) + # A newly copied loop carry is private to this invocation. A + # specialized graph may update it in place only if it proves the + # matching input/output dependence and coordinate ownership itself. + private_outputs = { + i: (placeholders[slot], carries[i]) + for i, slot in carry_slots.items() + if slot in copied_slots + } + results = self.graph( + graph.graph, + body_inputs, + private_loop_outputs=private_outputs, + ) assert isinstance(results, list) # Snapshot every value that reads a carry before writing any carry. # Disjoint recipes can write directly: none of their inputs changes @@ -381,15 +393,25 @@ def proof_source(value: object, rendered: str) -> str: snapshots = [] self.held.extend([results, snapshots]) destinations = self.referenced_buffers(carries) - for result in results: + in_place = { + i for i, (_, target) in private_outputs.items() if results[i] is target + } + for i, result in enumerate(results): value = cast("Fragment", result) + if i in in_place: + # The certified native transition has already written this + # result to its private target and synchronized the CTA. + snapshots.append(value) + continue snapshots.append( self.materialize(value, copy=True) if self.referenced_buffers([value]) & destinations and id(value) not in self.local_logical_sizes else value ) - for target, source in zip(carries, snapshots, strict=True): + for i, (target, source) in enumerate(zip(carries, snapshots, strict=True)): + if i in in_place: + continue if id(target) in self.local_logical_sizes: if source is not target: raise exc.InvalidConfig( diff --git a/helion/_compiler/cute/gathered_panel_layout.py b/helion/_compiler/cute/gathered_panel_layout.py new file mode 100644 index 000000000..43b50558d --- /dev/null +++ b/helion/_compiler/cute/gathered_panel_layout.py @@ -0,0 +1,34 @@ +"""Static geometry and shared-memory bounds of the swizzled BF16 page ring.""" + +from __future__ import annotations + +from .gathered_launch import GATHERED_SEED_THREADS + +RING_STAGES = tuple(range(2, 9)) +MMA_ROWS = 16 +PAGE_ROWS = 64 +DEPTH_PANEL = 64 +VALUE_PANEL = 128 +STAGE_BYTES = (MMA_ROWS + PAGE_ROWS) * DEPTH_PANEL * 2 + + +def slab_bytes(stages: int) -> int: + # A 16-byte aligned arena can need 112 extra bytes to reach a 128-byte + # swizzle origin. Even the smallest ring can also hold the later V panel. + return stages * STAGE_BYTES + 112 + + +def row_scratch_size(warps: int) -> int: + return (warps + 2) * MMA_ROWS + + +def working_set_bytes(rows: int, columns: int, width: int, stages: int) -> int: + # Both incoming and outgoing (row max, denominator and accumulator) may + # need storage. Private carries can use less, but are not assumed here. + carries = 2 * (2 * rows + rows * width) * 4 + return ( + slab_bytes(stages) + + carries + + MMA_ROWS * columns * 2 + + row_scratch_size(GATHERED_SEED_THREADS // 32) * 4 + ) diff --git a/helion/_compiler/cute/gathered_softmax.py b/helion/_compiler/cute/gathered_softmax.py new file mode 100644 index 000000000..97ff0aa05 --- /dev/null +++ b/helion/_compiler/cute/gathered_softmax.py @@ -0,0 +1,319 @@ +"""Lower a complete certified page transition while preserving its host loop.""" + +from __future__ import annotations + +import ast +from typing import TYPE_CHECKING +from typing import cast + +import torch +from torch._inductor.virtualized import V + +from ... import exc +from . import gathered_panel_layout as panels +from .analysis.gathered_softmax import GatheredSoftmax +from .analysis.gathered_softmax import prove_gathered_softmax +from .fragment_context import DenseSharedIndex +from .fragment_context import Fragment +from .gathered_launch import GATHERED_SEED_THREADS +from .memory_ops import _PERSISTENT_VEC_ALIGNMENT_SPECIALIZATION_KEY +from .memory_ops import tensor_proven_base_alignment + +if TYPE_CHECKING: + from torch.fx import Node + + from ..compile_environment import CompileEnvironment + from ..generate_ast import GenerateAST + from .computed_fragment import FragmentCompiler + + +_RUNTIME = "_helion_gathered_softmax" + + +def emit_gathered_softmax_preamble(cg: GenerateAST) -> None: + if not any( + isinstance(statement, ast.Import) + and any(alias.asname == _RUNTIME for alias in statement.names) + for statement in cg.module_statements + ): + cg.module_statements.extend( + ast.parse( + f"import helion._compiler.cute._gathered_softmax_runtime as {_RUNTIME}" + ).body + ) + + +def can_pack_bf16_k_pairs(env: CompileEnvironment, tensor: torch.Tensor) -> bool: + return _aligned_packets(env, tensor, 4) + + +def _seed_base_is_aligned( + env: CompileEnvironment, tensor: torch.Tensor, size: int +) -> bool: + # Discovery runs before the ordinary persistent-vector specialization + # snapshots its pointer residues. The bound code later checks that snapshot; + # the seed can already exclude a misaligned example without retaining it. + def aligned_input(env: CompileEnvironment, source: torch.Tensor, size: int) -> bool: + arg = env.tensor_input_source(source) + specialization = env.runtime_input_specializations.get( + _PERSISTENT_VEC_ALIGNMENT_SPECIALIZATION_KEY + ) + if ( + arg is None + or specialization is None + or arg not in specialization.sources + or not env.input_residues_hold_modulo(size) + ): + return False + live = env.live_example_input(arg) + return live is not None and live.data_ptr() % size == 0 + + return ( + tensor_proven_base_alignment(env, tensor, (size,), input_aligned=aligned_input) + == size + ) + + +def _aligned_packets( + env: CompileEnvironment, + tensor: torch.Tensor, + size: int, + *, + require_bound_pointer: bool = True, +) -> bool: + # Packet-sized row/page strides preserve base alignment for every + # possible index. A graph with dynamic placeholder strides must take + # scalar loads, even if the particular traced layout happens to qualify. + storage = tensor.untyped_storage() + origins = env.tensor_storage_provenance(tensor) + # A host branch can join aligned and misaligned views of the same shape. + # Its synthetic storage has no runtime pointer of its own. Trust only a + # direct guarded input storage or a positively tracked fresh allocation. + if origins is None or len(origins) != 1 or origins[0][0] != storage: + return False + if not origins[0][1] and not any( + source.untyped_storage() == storage for source in env.input_sources + ): + return False + return ( + tensor.dtype == torch.bfloat16 + and tensor.ndim >= 1 + and env.traced_strides_hold(tensor) + and type(tensor.stride(-1)) is int + and tensor.stride(-1) == 1 + and all( + type(stride) is int and stride % (size // 2) == 0 + for stride in tensor.stride()[:-1] + ) + and ( + tensor_proven_base_alignment(env, tensor, (size,)) == size + if require_bound_pointer + else _seed_base_is_aligned(env, tensor, size) + ) + ) + + +def can_pipeline_page( + env: CompileEnvironment, + proof: GatheredSoftmax, + width: int, + threads: int, + *, + require_bound_pointer: bool = True, +) -> bool: + capability = env.config_spec.target_device_capability + return ( + capability is not None + and capability[0] >= 8 + and threads == GATHERED_SEED_THREADS + and proof.qk.rows % panels.MMA_ROWS == 0 + and proof.qk.columns == panels.PAGE_ROWS + and proof.qk.depth > 0 + and proof.qk.depth % panels.DEPTH_PANEL == 0 + and width == panels.VALUE_PANEL + and all( + _aligned_packets( + env, + cast("torch.Tensor", node.meta["val"]), + 16, + require_bound_pointer=require_bound_pointer, + ) + for node in (proof.qk.lhs, proof.qk.rhs, proof.value) + ) + ) + + +def gathered_softmax_page( + compiler: FragmentCompiler, + graph: torch.fx.Graph, + values: dict[Node, object], + private_loop_outputs: dict[int, tuple[Node, Fragment]] | None = None, +) -> list[Fragment] | None: + capability = compiler.env.config_spec.target_device_capability + if ( + capability is None + or capability[0] < 8 + or compiler.threads % 32 + or not compiler.offsets + ): + return None + proof = prove_gathered_softmax(graph, compiler.graphs, compiler.env) + if proof is None or proof.value_bid not in compiler.offsets: + return None + old_acc = values[proof.previous_numerator] + if not isinstance(old_acc, Fragment) or len(old_acc.shape) != 2: + return None + m, d = old_acc.shape + n, k = proof.qk.columns, proof.qk.depth + w = compiler.threads // 32 + if m != proof.qk.rows or n % 16 or d % (8 * w) or n % (8 * w): + return None + # A rounded last value tile can carry out-of-domain columns to a later + # reduction. Only full value panels have a trivial projected output + # domain, regardless of how the parent consumes the three results. + value_width = cast("torch.Tensor", proof.value.meta["val"]).size(2) + source_extent = compiler.env.block_sizes[proof.value_bid].size + if ( + type(value_width) is not int + or type(source_extent) is not int + or value_width != source_extent + or value_width % d + or compiler.bounds.get(proof.value_bid) != str(source_extent) + ): + return None + # Only the table, scalar scale and logical page are evaluated by the ordinary + # fragment path; this retains both table address guards and signed indexing. + compiler.needs_gathered_softmax_runtime = True + compiler.used_gathered_bf16_fold = True + held: list[object] = [*values.values()] + compiler.held.append(held) + + def evaluate(node: Node) -> object: + if node not in values: + for source in node.all_input_nodes: + evaluate(source) + with node.meta["location"], V.set_current_node(node): + values[node] = compiler.node(node, values) + held.append(values[node]) + return values[node] + + def reserve(shape: tuple[int, ...], dtype: torch.dtype) -> Fragment: + buf = compiler.allocate(Fragment(shape, dtype, lambda _: "0")) + held.append(buf) + return buf + + def stage(node: Node) -> Fragment: + f = cast("Fragment", values[node]) + # Resident lazy views can have arbitrary coordinate transforms. Request + # a plain allocation unless its own row-major storage is identified. + source = compiler.materialize( + f, copy=not isinstance(f.element, DenseSharedIndex) + ) + held.append(source) + return source + + try: + phys = evaluate(proof.qk.page) + scale = evaluate(proof.scale) + logical = evaluate(proof.logical) + + q, keys, v = ( + compiler.host_tensor(x) for x in (proof.qk.lhs, proof.qk.rhs, proof.value) + ) + limit, old_m, old_l, old_a = ( + stage(x) + for x in ( + proof.limit, + proof.previous_maximum, + proof.previous_denominator, + proof.previous_numerator, + ) + ) + + def output( + index: int, param: Node, old: Fragment, shape: tuple[int, ...] + ) -> Fragment: + # The warp program loads the old row or accumulator coordinates + # into registers before the same owning lanes store their updates. + # A scratch copy created by stage() is not the private loop carry. + target = (private_loop_outputs or {}).get(index) + if target is not None and target[0] is param and target[1] is old: + return old + return reserve(shape, torch.float32) + + out_m = output(0, proof.previous_maximum, old_m, (m,)) + out_l = output(1, proof.previous_denominator, old_l, (m,)) + out_a = output(2, proof.previous_numerator, old_a, (m, d)) + probs = reserve((panels.MMA_ROWS, n), torch.bfloat16) + scratch = reserve((panels.row_scratch_size(w),), torch.float32) + pipeline = bool(compiler.df.config.get("cute_gathered_page_pipeline")) + if pipeline and not can_pipeline_page(compiler.env, proof, d, compiler.threads): + raise exc.InvalidConfig( + "asynchronous gathered panels require an aligned four-warp BF16 page" + ) + stages = compiler.df.config.get("cute_gathered_page_stages", 2) + assert type(stages) is int and stages in panels.RING_STAGES + # The QK stages share this slab with the later V panel. The fragment + # allocator aligns buffers to 16 bytes; include enough space to round + # up to the 128-byte bank swizzle origin inside the helper. + slab = reserve((panels.slab_bytes(stages),), torch.uint8) if pipeline else None + compiler.flush_pending_barrier() + dyn = [ + q.name, + keys.name, + v.name, + *( + str(x.storage) + for x in ( + limit, + old_m, + old_l, + old_a, + out_m, + out_l, + out_a, + probs, + scratch, + ) + ), + compiler.thread, + compiler.scalar(phys), + compiler.scalar(logical), + compiler.offsets[proof.value_bid], + compiler.scalar(scale), + compiler.sym(keys.value.size(0)), + compiler.sym(v.value.size(0)), + compiler.sym(v.value.size(2)), + ] + strides = [ + compiler.host_stride(host, i) + for host in (q, keys, v) + for i in range(host.value.ndim) + ] + assert ( + old_a.physical_row is not None + and out_a.physical_row is not None + and probs.physical_row is not None + ) + const = [ + m, + n, + k, + d, + w, + old_a.physical_row[0] // old_a.dtype.itemsize, + out_a.physical_row[0] // out_a.dtype.itemsize, + probs.physical_row[0] // probs.dtype.itemsize, + can_pack_bf16_k_pairs(compiler.env, q.value), + can_pack_bf16_k_pairs(compiler.env, keys.value), + ] + args = [*dyn, *strides, *map(str, const)] + if slab is not None: + compiler.used_async_gathered_page = True + args.extend([str(slab.storage), str(stages)]) + if compiler.env.settings.fast_math: + args.append("fast_math=True") + compiler.emit(f"{_RUNTIME}.gathered_softmax_page({', '.join(args)})") + return [out_m, out_l, out_a] + finally: + compiler.held.pop() diff --git a/helion/_compiler/cute/split_weighted_merge.py b/helion/_compiler/cute/split_weighted_merge.py new file mode 100644 index 000000000..e03a6b715 --- /dev/null +++ b/helion/_compiler/cute/split_weighted_merge.py @@ -0,0 +1,91 @@ +"""Emit a certified split reduction with one weight vector per CTA.""" + +from __future__ import annotations + +import ast +from typing import TYPE_CHECKING +from typing import cast + +import torch + +from ..ast_extension import statement_from_string +from ..compile_environment import CompileEnvironment +from ..inductor_lowering import codegen_call_with_graph +from ..tile_strategy import DeviceGridState +from .analysis.match_common import input_closure +from .analysis.split_weighted_merge import prove_split_weighted_merge +from .gathered_launch import gathered_launch_compatible +from .gathered_softmax import emit_gathered_softmax_preamble + +if TYPE_CHECKING: + from ..generate_ast import GenerateAST + + +def emit_split_weighted_merge(cg: GenerateAST) -> bool: + ir = cg.host_function.device_ir + root = cg.current_root_graph_info + grid = cg.current_grid_state + df = cg.device_function + if ( + root is None + or len(ir.root_ids) != 2 + or root.graph_id != ir.root_ids[-1] + or len(ir.grid_block_ids[-1]) != 2 + or not isinstance(grid, DeviceGridState) + or not df.config.get("cute_fragment_half_mma") + or not gathered_launch_compatible(df.config.config) + ): + return False + env = CompileEnvironment.current() + row, col = ir.grid_block_ids[-1] + spec = env.config_spec + sizes = spec.block_sizes + if ( + sizes.config_get(df.config.block_sizes, row) != 1 + or sizes.config_get(df.config.block_sizes, col) != 128 + ): + return False + if any( + lane != (128 if item.block_id == col else 1) + for item, lane in zip(spec.num_threads, df.config.num_threads, strict=True) + ): + return False + proof = prove_split_weighted_merge(root.graph, cg.codegen_graphs, env, row, col) + if proof is None: + return False + out_tensor = cast("torch.Tensor", proof.output.meta["val"]) + for axis, extent in zip((row, col), out_tensor.shape, strict=True): + dim = grid.block_id_to_info[axis] + if dim.begin_expr != 0 or dim.end_expr != extent: + return False + # Keeping the split width at one preserves the source's ordered FP32 + # denominator and numerator reductions, including the final division. + if sizes.config_get(df.config.block_sizes, proof.split_axis, 1) != 1: + return False + # Only the already certified scalar prefix is projected. Let the ordinary + # lowering interpret its original signed arithmetic, indexing and divisors. + prefix = torch.fx.Graph() + copies = {} + nodes = input_closure(proof.live) + for n in root.graph.nodes: + if n in nodes: + copies[n] = prefix.node_copy(n, copies.__getitem__) + prefix.output([copies[proof.live]]) + (live,) = codegen_call_with_graph(cg, prefix, []) + assert isinstance(live, ast.AST) + names = [ + df.tensor_arg( + cast("torch.Tensor", n.meta["val"]), prefer_name=cast("str", n.args[0]) + ).name + for n in (proof.scores, proof.values, proof.output) + ] + emit_gathered_softmax_preamble(cg) + math_option = ", fast_math=True" if env.settings.fast_math else "" + cg.add_statement( + statement_from_string( + f"_helion_gathered_softmax.split_weighted_merge({', '.join(names)}, " + f"{grid.strategy.grid_origin_var(row)}, {grid.strategy.grid_origin_var(col)}, {{live}}{math_option})", + live=live, + ) + ) + return True diff --git a/helion/_testing/cute_gathered_bf16.py b/helion/_testing/cute_gathered_bf16.py index e6e5b013b..f68ec009f 100644 --- a/helion/_testing/cute_gathered_bf16.py +++ b/helion/_testing/cute_gathered_bf16.py @@ -33,6 +33,49 @@ def routed_transposed_product( return out +@helion.kernel(backend="cute", static_shapes=True, autotune_effort="none") +def masked_page_stream( + q: torch.Tensor, + bank: torch.Tensor, + table: torch.Tensor, + state: torch.Tensor, + scale: float, +) -> torch.Tensor: + rows, depth = q.shape + keys = bank.size(1) + out = torch.empty_like(q, dtype=torch.float32) + block_k = hl.register_block_size(depth) + for tile_d in hl.tile(depth): + # These two slices can share one cooperative load. The mask must read + # the second row, including its shared-memory offset. + limit = state[1, :] + maximum = state[0, :].float() + norm = hl.zeros([rows], dtype=torch.float32) + output = hl.zeros([rows, tile_d], dtype=torch.float32) + for page in hl.tile(0, 8, block_size=1): + index = table[0, page.begin] + scores = hl.zeros([rows, keys], dtype=torch.float32) + for k in hl.tile(depth, block_size=block_k): + scores = hl.dot(q[:, k], bank[index, :, k].T, acc=scores) + pos = page.begin * keys + hl.arange(keys) + scores = torch.where( + pos[None, :] < limit[:, None], scores * scale, -float("inf") + ) + new_max = torch.maximum(maximum, torch.amax(scores, dim=-1)) + safe = torch.where(new_max == -float("inf"), 0.0, new_max) + alpha = torch.exp2(maximum - safe) + probability = torch.exp2(scores - safe[:, None]) + norm = norm * alpha + torch.sum(probability, dim=-1) + output = hl.dot( + probability.to(torch.bfloat16), + bank[index, :, tile_d], + acc=output * alpha[:, None], + ) + maximum = new_max + out[:, tile_d] = (output + maximum[:, None]) / norm[:, None] + return out + + def split_paged_attention( query: torch.Tensor, kv_cache: torch.Tensor, diff --git a/helion/_testing/cute_weighted_merge.py b/helion/_testing/cute_weighted_merge.py new file mode 100644 index 000000000..d10469f40 --- /dev/null +++ b/helion/_testing/cute_weighted_merge.py @@ -0,0 +1,64 @@ +"""Isolate the emitted split merge's FP32 rounding from its BF16 matmul producer.""" + +from __future__ import annotations + +import importlib + +import cutlass +from cutlass import cute +from cutlass.cute.runtime import from_dlpack +import torch + +from helion._compiler.cute._gathered_softmax_runtime import split_weighted_merge + +cuda = importlib.import_module("cuda.bindings.driver") + + +@cute.kernel +def _merge_one( + scores: cute.Tensor, + partials: cute.Tensor, + out: cute.Tensor, + live: cutlass.Int32, + fast_math: cutlass.Constexpr, +) -> None: + split_weighted_merge( + scores, + partials, + out, + cutlass.Int32(0), + cutlass.Int32(0), + live, + fast_math=fast_math, + ) + + +@cute.jit +def _launch_merge_one( + scores: cute.Tensor, + partials: cute.Tensor, + out: cute.Tensor, + live: cutlass.Int32, + fast_math: cutlass.Constexpr, + stream: cuda.CUstream, +) -> None: + _merge_one(scores, partials, out, live, fast_math).launch( + grid=(1, 1, 1), block=(128, 1, 1), smem=272, stream=stream + ) + + +def merge_one( + scores: torch.Tensor, + partials: torch.Tensor, + output: torch.Tensor, + live: int, + fast_math: bool, +) -> None: + _launch_merge_one( + from_dlpack(scores), + from_dlpack(partials), + from_dlpack(output), + cutlass.Int32(live), + fast_math, + cuda.CUstream(torch.cuda.current_stream().cuda_stream), + ) diff --git a/helion/autotuner/config_spec.py b/helion/autotuner/config_spec.py index b052a84d7..5fa5e9ab1 100644 --- a/helion/autotuner/config_spec.py +++ b/helion/autotuner/config_spec.py @@ -1665,6 +1665,7 @@ def __init__( self.cute_fragment_half_mma_search_enabled = False # Validated lane carrier of an ordinary-barrier gathered phase pair. self.cute_gathered_phase_carriers: tuple[dict[str, object], ...] = () + self.cute_gathered_page_value_bid: int | None = None self.cute_gathered_phase_search_lanes: frozenset[tuple[int, ...]] = frozenset() self.cute_fp32_dot_seed_worthy = False self.cute_fragment_thread_root_ids: frozenset[int] = frozenset() diff --git a/test/shard_durations.json b/test/shard_durations.json index 589441768..d67382417 100644 --- a/test/shard_durations.json +++ b/test/shard_durations.json @@ -153,7 +153,7 @@ "test/test_cute_fragment_assertion.py": 4.2, "test/test_cute_fragment_direct_store.py": 12.1, "test/test_cute_fragment_epilogue.py": 2.7, - "test/test_cute_fragment_half_mma.py": 3.1, + "test/test_cute_fragment_half_mma.py": 21.2, "test/test_cute_fragment_index_domains_gpu.py": 2.2, "test/test_cute_fragment_input_layout_gpu.py": 0.7, "test/test_cute_fragment_signed_coordinates.py": 4.4, diff --git a/test/test_config_spec_keys_migration.py b/test/test_config_spec_keys_migration.py index 1f16f02de..09d8ad4dc 100644 --- a/test/test_config_spec_keys_migration.py +++ b/test/test_config_spec_keys_migration.py @@ -96,6 +96,7 @@ cute_fragment_atomic_aggregation cute_fragment_atomic_consumer_fusion cute_fragment_batched_loads cute_fragment_bounded_gather cute_fragment_cta_topk cute_fragment_half_mma + cute_gathered_page_pipeline cute_gathered_page_stages cute_fragment_integer_atomic_epochs cute_fragment_local_atomic_registers cute_fragment_mma_rows cute_fragment_packet_loads cute_fragment_padded_rows cute_in_kernel_grid_init cute_fragment_private_scalar_loops cute_fragment_producer_cache @@ -275,6 +276,7 @@ cute_fragment_atomic_aggregation cute_fragment_atomic_consumer_fusion cute_fragment_batched_loads cute_fragment_bounded_gather cute_fragment_cta_topk cute_fragment_half_mma + cute_gathered_page_pipeline cute_gathered_page_stages cute_fragment_integer_atomic_epochs cute_fragment_local_atomic_registers cute_fragment_mma_rows cute_fragment_packet_loads cute_fragment_padded_rows cute_in_kernel_grid_init cute_fragment_private_scalar_loops cute_fragment_producer_cache @@ -406,6 +408,7 @@ cute_fmnmx_extrema cute_fp32_dot cute_fragment_atomic_aggregation cute_fragment_atomic_consumer_fusion cute_fragment_batched_loads cute_fragment_bounded_gather cute_fragment_cta_topk cute_fragment_half_mma + cute_gathered_page_pipeline cute_gathered_page_stages cute_fragment_integer_atomic_epochs cute_fragment_local_atomic_registers cute_fragment_mma_rows cute_fragment_packet_loads cute_fragment_padded_rows cute_in_kernel_grid_init cute_fragment_private_scalar_loops cute_fragment_producer_cache @@ -514,6 +517,7 @@ cute_fragment_atomic_aggregation cute_fragment_atomic_consumer_fusion cute_fragment_batched_loads cute_fragment_bounded_gather cute_fragment_cta_topk cute_fragment_half_mma + cute_gathered_page_pipeline cute_gathered_page_stages cute_fragment_integer_atomic_epochs cute_fragment_local_atomic_registers cute_fragment_mma_rows cute_fragment_packet_loads cute_fragment_padded_rows cute_in_kernel_grid_init cute_fragment_private_scalar_loops cute_fragment_producer_cache diff --git a/test/test_cute_fragment_half_mma.py b/test/test_cute_fragment_half_mma.py index 2130ad985..ca3f6be00 100644 --- a/test/test_cute_fragment_half_mma.py +++ b/test/test_cute_fragment_half_mma.py @@ -7,12 +7,18 @@ import helion from helion._testing import DEVICE +from helion._testing import matchesBackends from helion._testing.cute_gathered_bf16 import routed_transposed_product +from helion._testing.cute_gathered_bf16 import split_paged_attention from helion._testing.cute_half_mma import batched_dot from helion._testing.cute_half_mma import cast_dot from helion._testing.cute_half_mma import computed_dot from helion._testing.cute_half_mma import recurrent_dot +if matchesBackends(["cute"]): + pytest.importorskip("cutlass.cute") + from helion._testing.cute_weighted_merge import merge_one + pytestmark = pytest.mark.skipif( not torch.cuda.is_available(), reason="CUDA is required" ) @@ -106,3 +112,147 @@ def test_gathered_nt_signed_pages_and_repeated_routes() -> None: reference = torch.einsum("mk,bnk->bmn", x.float(), key) reference[(order < -bank.size(0)) | (order >= bank.size(0))] = 0 torch.testing.assert_close(got, reference, rtol=3e-4, atol=5e-5) + + +def test_fused_gathered_page_keeps_causal_row_limits_and_online_carry() -> None: + torch.manual_seed(46) + query = torch.randn((1, 2, 8, 128), device=DEVICE, dtype=torch.bfloat16) + bank = torch.randn((5, 1, 32, 128), device=DEVICE, dtype=torch.bfloat16) + # A distinct final page has one live key; its high score makes accidentally + # including/excluding that key in either query row easy to detect. + query[0, 0, 0] = query[0, 1, 0] + bank[4, 0, 0] = query[0, 1, 0] * 2 + pages = torch.tensor( + [([2, -5, 3, 1] * 16) + [-1]], device=DEVICE, dtype=torch.int32 + ) + length = 2049 # Two 32-key pages per live split. + seq = torch.tensor([length], device=DEVICE, dtype=torch.int32) + scale = 128**-0.5 + args = (query, bank, pages, seq, scale) + op = helion.kernel(backend="cute", static_shapes=False)(split_paged_attention) + bound = op.bind(args) + config = next( + candidate + for candidate in bound.config_spec.compiler_seed_configs + if candidate.config.get("cute_fragment_half_mma") + ) + assert ".gathered_softmax_page(" in bound.to_code(config) + actual = bound.compile_config(config)(*args) + # Independently flatten the permuted physical pages and normalize across + # every visible key. This oracle does not split the context into pages. + ordered = bank[pages[0].long(), 0].reshape(-1, 128)[:length].float() + scores = torch.einsum("qhd,ld->qhl", query[0].float(), ordered) * scale + limits = torch.tensor([length - 1, length], device=DEVICE) + visible = torch.arange(length, device=DEVICE)[None, :] < limits[:, None] + weights = scores.masked_fill(~visible[:, None, :], -torch.inf).softmax(-1) + expected = torch.einsum("qhl,ld->qhd", weights, ordered[:, :64]).bfloat16()[None] + assert (expected[0, 0, 0] - expected[0, 1, 0]).abs().max() > 1 + torch.testing.assert_close(actual, expected, rtol=0.01, atol=0.008) + + +@pytest.mark.parametrize("pipelined", (False, True), ids=("direct", "async")) +def test_streaming_split_merge_shares_both_halves_of_the_weight_vector( + pipelined: bool, +) -> None: + torch.manual_seed(62) + query = torch.randn((1, 1, 16, 192), device=DEVICE, dtype=torch.bfloat16) + page = 64 if pipelined else 32 + keys = torch.randn((64, 1, page, 192), device=DEVICE, dtype=torch.bfloat16) + pages = torch.randperm(64, device=DEVICE, dtype=torch.int32)[None, :] + seq = torch.tensor([page], device=DEVICE, dtype=torch.int32) + scale = 192**-0.5 + args = (query, keys, pages, seq, scale) + op = helion.kernel(backend="cute", static_shapes=False)(split_paged_attention) + bound = op.bind(args) + assert not any( + c.config.get("cute_gathered_page_stages") == 8 + for c in bound.config_spec.compiler_seed_configs + ) + candidate = next( + c + for c in bound.config_spec.compiler_seed_configs + if c.config.get("cute_fragment_half_mma") + and c.pid_type == "persistent_interleaved" + and ( + c.config.get("cute_gathered_page_stages") == 4 + if pipelined + else not c.config.get("cute_gathered_page_pipeline") + ) + ) + assert ".split_weighted_merge(" in bound.to_code(candidate) + compiled = bound.compile_config(candidate) + visible = keys[pages[0].long(), 0].reshape(-1, 192).float() + # Zero, one occupied half-warp, both halves and every one of the 64 slots + # run a single compilation and the same persistent kernel/allocations. + for length in (0, page + 3, 32 * page + 1, 64 * page): + seq.fill_(length) + actual = compiled(*args).float() + if length == 0: + # The public program finishes with 0/0 when there are no splits. + assert torch.isnan(actual).all() + continue + scores = query[0, 0].float() @ visible[:length].T * scale + reference = scores.softmax(-1) @ visible[:length, :128] + torch.testing.assert_close(actual[0, 0], reference, rtol=0.02, atol=0.003) + + +@pytest.mark.parametrize( + ("stages", "fast_math"), + [(2, False), (4, False), (8, False), (8, True)], + ids=("2", "4", "8", "8-fast-math"), +) +def test_async_panel_ring_refills_and_reuses_slots( + stages: int, fast_math: bool +) -> None: + # Nine QK panels require at least one slot refill at every selected + # depth. Two distinct pages also exercise a partial last page. + torch.manual_seed(91) + query = torch.randn((1, 1, 16, 576), device=DEVICE, dtype=torch.bfloat16) + keys = torch.randn((2, 1, 64, 576), device=DEVICE, dtype=torch.bfloat16) + pages = torch.tensor([[-1, -2]], device=DEVICE, dtype=torch.int32) + length = torch.tensor([99], device=DEVICE, dtype=torch.int32) + scale = 576**-0.5 + args = (query, keys, pages, length, scale) + bound = helion.kernel(backend="cute", static_shapes=False, fast_math=fast_math)( + split_paged_attention + ).bind(args) + cfg = next( + c + for c in bound.config_spec.compiler_seed_configs + if c.config.get("cute_gathered_page_pipeline") + and c.config.get("cute_gathered_page_stages", 2) == stages + ) + result = bound.compile_config(cfg)(*args)[0, 0].float() + ordered = keys[pages[0].long(), 0].reshape(-1, 576)[:99].float() + expected = (query[0, 0].float() @ ordered.T * scale).softmax(-1) @ ordered[:, :512] + torch.testing.assert_close(result, expected, rtol=0.02, atol=0.003) + + +def test_split_weighted_merge_respects_fast_math_for_subnormals() -> None: + scores = torch.zeros((64, 1), device=DEVICE, dtype=torch.float32) + partials = torch.zeros((64, 1, 128), device=DEVICE, dtype=torch.float32) + partials[0].fill_(2.0**-130) + out = torch.empty((1, 128), device=DEVICE, dtype=torch.bfloat16) + for fast in (False, True): + out.fill_(float("nan")) + merge_one(scores, partials, out, 1, fast) + # exp2(0) = 1. The single input has BF16 bits 0x0008. Approximate + # FP32 division flushes it; the default quotient preserves it. + torch.testing.assert_close( + out.view(torch.int16), + torch.full_like(out.view(torch.int16), 0 if fast else 8), + atol=0, + rtol=0, + ) + + # The quotient is now normal in strict math. The tiny weight times the + # large partial isolates exp2 flushing, independently of division FTZ. + scores[1].fill_(-130) + partials.zero_() + partials[1].fill_(2.0**126) + for fast in (False, True): + out.fill_(float("nan")) + merge_one(scores, partials, out, 2, fast) + torch.testing.assert_close( + out, torch.full_like(out, 0.0 if fast else 0.0625), rtol=0, atol=0 + ) diff --git a/test/test_cute_gathered_bf16_mma.py b/test/test_cute_gathered_bf16_mma.py index aba9f1287..3b032d782 100644 --- a/test/test_cute_gathered_bf16_mma.py +++ b/test/test_cute_gathered_bf16_mma.py @@ -3,20 +3,43 @@ from __future__ import annotations import ast +from contextlib import ExitStack import copy +from unittest.mock import Mock +from unittest.mock import patch import pytest import torch import helion +from helion._compiler._inductor.template_buffer import inductor_call_facts from helion._compiler.cute.analysis.gathered_bf16_mma import gathered_phase_region from helion._compiler.cute.analysis.gathered_bf16_mma import prove_gathered_bf16_mma +from helion._compiler.cute.analysis.gathered_softmax import prove_gathered_softmax +from helion._compiler.cute.analysis.split_weighted_merge import ( + prove_split_weighted_merge, +) +from helion._compiler.cute.autotune.heuristics.cute_gathered_bf16_mma import ( + CuteGatheredBf16MmaSeed, +) +from helion._compiler.cute.autotune.heuristics.cute_gathered_bf16_mma import ( + gathered_phase_carrier, +) +from helion._compiler.cute.gathered_softmax import _seed_base_is_aligned +from helion._compiler.cute.gathered_softmax import can_pack_bf16_k_pairs +from helion._compiler.cute.gathered_softmax import can_pipeline_page +from helion._compiler.cute.memory_ops import ( + _PERSISTENT_VEC_ALIGNMENT_SPECIALIZATION_KEY, +) from helion._testing.cute_codegen import cpu_bind from helion._testing.cute_codegen import cpu_render_target from helion._testing.cute_codegen import cpu_target from helion._testing.cute_codegen import default_cute_mma_support +from helion._testing.cute_gathered_bf16 import masked_page_stream from helion._testing.cute_gathered_bf16 import routed_transposed_product from helion._testing.cute_gathered_bf16 import split_paged_attention +from helion.language import _tracing_ops +from helion.language import memory_ops pytestmark = pytest.mark.cpu_only @@ -135,6 +158,9 @@ def test_unproved_reduction_falls_back( def test_ordered_producer_keeps_the_combines_launch_and_barrier() -> None: + # Keep this real CPU pointer outside the traced host's fake-tensor context. + misaligned = torch.empty(33, dtype=torch.bfloat16)[1:] + assert misaligned.data_ptr() % 16 != 0 with torch.device("meta"): inputs = ( torch.empty((1, 1, 16, 576), dtype=torch.bfloat16), @@ -152,12 +178,205 @@ def test_ordered_producer_keeps_the_combines_launch_and_barrier() -> None: kernel = helion.kernel(backend="cute", static_shapes=False)( split_paged_attention ) - bound = cpu_bind(kernel, inputs) + gate = "helion._compiler.cute.cooperative_grid_init.grid_toolkit_installed" + rejected = "helion._compiler.cute.cooperative_grid_init.grid_sync_rejected" + with patch(gate, return_value=True), patch(rejected, return_value=False): + bound = cpu_bind(kernel, inputs) + cache_key = bound.config_spec.cache_fingerprint_hash() + # A compiler can reject the cooperative instruction on first use. + # Keep the seed roster and its disk key; viability declines that + # specific config while the cached software-counter winner survives. + with patch(gate, return_value=True), patch(rejected, return_value=True): + after_rejection = cpu_bind( + helion.kernel(backend="cute", static_shapes=False)( + split_paged_attention + ), + inputs, + ) + assert after_rejection.config_spec.cache_fingerprint_hash() == cache_key + carriers = [ + c + for c in after_rejection.config_spec.compiler_seed_configs + if c.get("cute_in_kernel_grid_init") + and c.get("cute_gathered_page_pipeline") + ] + assert len(carriers) == 1 + spec_after = after_rejection.config_spec + assert not spec_after.backend.can_reuse_autotune_result( + spec_after, carriers[0] + ) + software = next( + c + for c in spec_after.compiler_seed_configs + if not c.get("cute_in_kernel_grid_init") + and c.get("cute_gathered_page_stages") == 8 + ) + assert spec_after.backend.can_reuse_autotune_result(spec_after, software) + # Discovery snapshots its candidates at bind time. A separate kernel + # ensures the toolkit-absent binding cannot reuse the first one. + with patch(gate, return_value=False): + unsupported = cpu_bind( + helion.kernel(backend="cute", static_shapes=False)( + split_paged_attention + ), + inputs, + ) + assert not any( + c.get("cute_gathered_page_stages") and c.get("cute_in_kernel_grid_init") + for c in unsupported.config_spec.compiler_seed_configs + ) assert bound.host_function is not None with bound.env, bound.host_function: ir = bound.host_function.device_ir + merge_graph = ir.graphs[ir.root_ids[-1]].graph + + def merge_proof(): + return prove_split_weighted_merge( + merge_graph, ir.graphs, bound.env, *ir.grid_block_ids[-1] + ) + + assert merge_proof() is not None + # Corrupt the update selected by the first loop's conditional. + # This must decline even if the score and value shapes still match. + max_loop = next( + iter( + merge_graph.find_nodes( + op="call_function", target=_tracing_ops._for_loop + ) + ) + ) + cond_loop = ir.graphs[max_loop.args[0]].graph + if_node = next( + iter(cond_loop.find_nodes(op="call_function", target=_tracing_ops._if)) + ) + first_branch = ir.graphs[if_node.args[1]] + first_max = next( + iter( + first_branch.graph.find_nodes( + op="call_function", target=torch.ops.aten.maximum.default + ) + ) + ) + with patch.object(first_max, "target", torch.ops.aten.minimum.default): + assert merge_proof() is None + with patch.object( + first_branch, "branches_outputs", [(0, first_branch.if_arg_names[0])] + ): + assert merge_proof() is None + merge_div = next( + iter( + merge_graph.find_nodes( + op="call_function", target=torch.ops.aten.div.Tensor + ) + ) + ) + with patch.object(merge_div, "target", torch.ops.aten.mul.Tensor): + assert merge_proof() is None + cond = next( + iter( + merge_graph.find_nodes( + op="call_function", target=torch.ops.aten.eq.Scalar + ) + ) + ) + original_args = cond.args + try: + cond.args = (cond.args[0], 0) + assert merge_proof() is None + finally: + cond.args = original_args producer = gathered_phase_region(ir, bound.env, ir.graphs) assert producer is not None + pages = [ + (g, p) + for g in ir.graphs + if (p := prove_gathered_softmax(g.graph, ir.graphs, bound.env)) + is not None + ] + assert len(pages) == 1 + page, proof = pages[0] + query, bank = (n.meta["val"] for n in (proof.qk.lhs, proof.qk.rhs)) + assert can_pipeline_page(bound.env, proof, 128, 128) + # Seed admission sees the current arguments before the binding + # snapshots its pointer facts. Do not advertise an unaligned seed. + with patch.object(bound.env, "live_example_input", return_value=misaligned): + assert not can_pipeline_page( + bound.env, proof, 128, 128, require_bound_pointer=False + ) + assert not can_pipeline_page(bound.env, proof, 64, 128) + assert not can_pipeline_page(bound.env, proof, 128, 64) + # A two-element BF16 offset still permits existing 32-bit pairs, + # but not a 16-byte async copy. Check every operand independently. + for operand in (proof.qk.lhs, proof.qk.rhs, proof.value): + saved = operand.meta["val"] + with patch.dict(operand.meta, {"val": saved[..., 2:]}): + assert can_pack_bf16_k_pairs(bound.env, operand.meta["val"]) + assert not can_pipeline_page(bound.env, proof, 128, 128) + assert can_pack_bf16_k_pairs(bound.env, query) + assert can_pack_bf16_k_pairs(bound.env, bank) + alternatives = (query[:, :-1], query[:, 1:]) + joined = torch.empty_like(alternatives[0]) + bound.env.register_tensor_storage_join(joined, alternatives) + assert not can_pack_bf16_k_pairs(bound.env, joined) + assert not can_pack_bf16_k_pairs(bound.env, query[:, 1:]) + assert not can_pack_bf16_k_pairs(bound.env, query[:, ::2]) + assert not can_pack_bf16_k_pairs( + bound.env, query.as_strided((16, 16), (33, 1)) + ) + with inductor_call_facts( + bound, + symbolic_input_layouts=True, + symbolic_strides=tuple(bound.env.input_sources.values()), + ): + assert not can_pipeline_page(bound.env, proof, 128, 128) + assert not can_pack_bf16_k_pairs(bound.env, query) + assert not can_pack_bf16_k_pairs(bound.env, bank) + nodes = list(page.graph.nodes) + with ExitStack() as omitted: + for n in nodes: + if n.target in ( + torch.ops.aten.amax.default, + torch.ops.aten.sum.dim_IntList, + ): + omitted.enter_context(patch.dict(n.meta, lowering=None)) + assert gathered_phase_carrier(bound.env, ir, producer) is None + + # Each mutation breaks a different semantic edge. Restoring it + # lets all six adversarial cases share one traced/compiled kernel. + converted = next( + n + for n in nodes + if n.target is torch.ops.prims.convert_element_type.default + ) + safe = next(n for n in nodes if n.target is torch.ops.aten.eq.Scalar) + choice = next(n for n in nodes if n.target is torch.ops.aten.lt.Tensor) + loaded = next(n for n in nodes if n.args and n.args[0] is proof.value) + cast_input, _ = converted.args + near = next( + n + for n in nodes + if n.target is torch.ops.aten.exp2.default and n is not cast_input + ) + ssum = next(n for n in nodes if n.target is torch.ops.aten.sum.dim_IntList) + for node, replacement in ( + (converted, (cast_input, torch.float16)), + (safe, (safe.args[0], 0)), + (choice, tuple(reversed(choice.args))), + ( + loaded, + (proof.value, [proof.logical, *loaded.args[1][1:]], None, None), + ), + (converted, (near, torch.bfloat16)), + (ssum, (ssum.args[0], [0])), + ): + original = node.args + try: + node.args = replacement + assert ( + prove_gathered_softmax(page.graph, ir.graphs, bound.env) is None + ) + finally: + node.args = original assert bound.config_spec.cute_fragment_half_mma_root_ids == {ir.root_ids[0]} assert ir.root_ids[1] not in {g.graph_id for g in producer} for attribute, value in ( @@ -175,14 +394,176 @@ def test_ordered_producer_keeps_the_combines_launch_and_barrier() -> None: ) witness = next(w for w in group.witnesses if w.value is True) config = witness.carrier.config | {group.key: witness.value} + # The search repairs incompatible variants without compiling them; + # the positive witness survives normalization unchanged. assert ( tuple(config["num_threads"]) in bound.config_spec.cute_gathered_phase_search_lanes ) + with bound.env, bound.host_function: + seeds = CuteGatheredBf16MmaSeed.get_seed_configs(bound.env, ir) + # The ordinary seven remain available without a cooperative toolkit. + # Exercise joint seed discovery without probing NVRTC on a CPU job. + original = [s for s in seeds if not s.get("cute_in_kernel_grid_init")] + extra = [s for s in seeds if s.get("cute_in_kernel_grid_init")] + assert len(extra) == 1 + assert extra[0].config == original[-1].config | { + "cute_in_kernel_grid_init": True + } + seeds = original + assert len(seeds) == 7 + registered = [ + s + for s in bound.config_spec.compiler_seed_configs + if s.config.get("cute_fragment_half_mma") + and not s.get("cute_in_kernel_grid_init") + ] + assert [s.config for s in registered] == [s.config for s in seeds] + assert ( + seeds[0].config + == CuteGatheredBf16MmaSeed.get_seed_config(bound.env, ir).config + ) + assert [s.block_sizes[2] for s in seeds[1:]] == [128, 64, 256, 128, 128, 128] + assert seeds[2].loop_orders[0] == [1, 0] + assert not seeds[1].config.get("loop_orders") + assert all( + tuple(s.num_threads) in bound.config_spec.cute_gathered_phase_search_lanes + for s in seeds + ) + pipeline = seeds[-1] + assert pipeline.config.get("cute_gathered_page_pipeline") is True + assert pipeline.config.get("cute_gathered_page_stages") == 8 + pipelined = bound.to_code(pipeline) + fast = cpu_bind( + helion.kernel(backend="cute", static_shapes=False, fast_math=True)( + split_paged_attention + ), + inputs, + ) + fast_source = fast.to_code(pipeline) + math_calls = { + node.func.attr + for node in ast.walk(ast.parse(fast_source)) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and any( + kw.arg == "fast_math" + and isinstance(kw.value, ast.Constant) + and kw.value.value is True + for kw in node.keywords + ) + } + assert {"gathered_softmax_page", "split_weighted_merge"} <= math_calls + assert fast.host_function is not None + with fast.env, fast.host_function: + fast_ir = fast.host_function.device_ir + root = fast_ir.graphs[fast_ir.root_ids[-1]].graph + axes = fast_ir.grid_block_ids[-1] + positive = prove_split_weighted_merge(root, fast_ir.graphs, fast.env, *axes) + assert positive is not None + # Losing the implicit zero mask is safe only for the matched + # weight/product: the partial must still have the same live mask. + load = next( + n + for g in fast_ir.graphs + for n in g.graph.nodes + if n.target is memory_ops.load and n.args[0] is positive.values + ) + old_load_args = load.args + try: + load.args = (old_load_args[0], old_load_args[1], None, old_load_args[3]) + assert ( + prove_split_weighted_merge(root, fast_ir.graphs, fast.env, *axes) + is None + ) + finally: + load.args = old_load_args + + def page_call(code: str) -> ast.Call: + return next( + n + for n in ast.walk(ast.parse(code)) + if isinstance(n, ast.Call) + and isinstance(n.func, ast.Attribute) + and n.func.attr == "gathered_softmax_page" + ) + + alternate = bound.to_code(seeds[1]) + assert len(page_call(pipelined).args) == len(page_call(alternate).args) + 2 + assert isinstance(page_call(pipelined).args[-2], ast.Name) + assert ast.literal_eval(page_call(pipelined).args[-1]) == 8 + # The producer owns the 128-wide V panel; it does not own the merge + # tile width. The same eligible producer must survive unrelated tuning. + different_merge = copy.deepcopy(pipeline.config) + different_merge["block_sizes"][-1] = 256 + bound.config_spec.normalize(different_merge) + other_call = page_call(bound.to_code(helion.Config.from_dict(different_merge))) + assert ast.literal_eval(other_call.args[-1]) == 8 + with ( + patch( + "helion._compiler.cute.computed_fragment.gathered_softmax_page", + return_value=None, + ), + pytest.raises( + helion.exc.InvalidConfig, + match="did not emit the configured asynchronous", + ), + ): + bound.to_code(pipeline) + # A packed producer does not implicitly require the async slab: at a + # tight budget its ordinary fused schedule still fits, but the + # explicitly selected 8-stage ring alone already exceeds this limit. + with patch( + "helion._compiler.cute.target_facts.per_cta_smem_capacity_bytes", + return_value=64 * 1024, + ): + with pytest.raises(helion.exc.InvalidConfig, match="shared bytes"): + bound.to_code(pipeline) + assert ".gathered_softmax_page(" in bound.to_code(seeds[1]) + invalid_pipeline = copy.deepcopy( + seeds[2].config | {"cute_gathered_page_pipeline": True} + ) + bound.config_spec.normalize(invalid_pipeline, _fix_invalid=True) + assert not invalid_pipeline.get("cute_gathered_page_pipeline") + assert "block=(128, 1, 1)" in alternate + assert ".gathered_softmax_page(" in alternate + assert ".split_weighted_merge(" in alternate + page_update = next( + n + for n in ast.walk(ast.parse(alternate)) + if isinstance(n, ast.Call) + and isinstance(n.func, ast.Attribute) + and n.func.attr == "gathered_softmax_page" + ) + assert [ast.unparse(a) for a in page_update.args[4:7]] == [ + ast.unparse(a) for a in page_update.args[7:10] + ] + # The fully synchronized update is the end of the enclosing page + # loop: no snapshot/copy-back or extra CTA barrier is necessary. + assert any( + isinstance(loop, ast.For) + and isinstance(loop.body[-1], ast.Expr) + and isinstance(loop.body[-1].value, ast.Call) + and isinstance(loop.body[-1].value.func, ast.Attribute) + and loop.body[-1].value.func.attr == "gathered_softmax_page" + for loop in ast.walk(ast.parse(alternate)) + ) + assert seeds[1].pid_type == "persistent_interleaved" + compatible = copy.deepcopy(config) + bound.config_spec.normalize(compatible, _fix_invalid=True) + assert compatible.get("cute_fragment_half_mma") + for changes in ( + {"num_threads": [1, 1, 4, 1, 4, 1, 64]}, + {"cross_loop_pipeline": "static"}, + ): + incompatible = copy.deepcopy(config) | changes + bound.config_spec.normalize(incompatible, _fix_invalid=True) + assert not incompatible.get("cute_fragment_half_mma") source = bound.to_code(helion.Config.from_dict(config)) assert source.count("_launcher(") == 1 assert source.count("_cute_grid_barrier(x_grid_sem.iterator)") == 1 assert "block=(64, 2, 1)" in source + assert ".split_weighted_merge(" not in source assert "q2d_stride_1" in source and "kv3_stride_2" in source # Every warp leaving a producer iteration (even on a false predicate) # rendezvous before the persistent CTA reuses its local storage. @@ -191,16 +572,104 @@ def test_ordered_producer_keeps_the_combines_launch_and_barrier() -> None: and node.body and ast.unparse(node.body[-1]) == "cute.arch.sync_threads()" and any( - isinstance(n, ast.Name) and n.id == "gathered_mma_page" + isinstance(n, ast.Attribute) and n.attr == "gathered_softmax_page" for n in ast.walk(node) ) for node in ast.walk(ast.parse(source)) ) - assert ( - "gathered_mma_page" in source and "_helion_fragment_mma.mma_bf16(" in source - ) + assert ".gathered_softmax_page(" in source + assert "gathered_mma_page" not in source conflict = config | {"num_threads": [1, 1, 4, 1, 4, 1, 64]} with pytest.raises( helion.exc.InvalidConfig, match="needs 128 physical threads" ): bound.to_code(helion.Config.from_dict(conflict)) + + +def test_fused_gathered_page_applies_the_limits_slab_offset() -> None: + args = ( + torch.empty((64, 64), dtype=torch.bfloat16), + torch.empty((8, 64, 64), dtype=torch.bfloat16), + torch.empty((1, 8), dtype=torch.int32), + torch.empty((2, 64), dtype=torch.int32), + 0.35, + ) + with cpu_target(): + bound = cpu_bind(masked_page_stream, args) + sizes = list(bound.config_spec.default_config().block_sizes) + assert bound.host_function is not None + with bound.env, bound.host_function: + graphs = bound.host_function.device_ir.graphs + page = next( + proof + for g in graphs + if (proof := prove_gathered_softmax(g.graph, graphs, bound.env)) + is not None + ) + for i, item in enumerate(bound.config_spec.block_sizes): + if item.block_id == page.value_bid: + sizes[i] = 64 + cfg = helion.Config( + block_sizes=sizes, + cute_fragment_slab_loads=True, + cute_fragment_half_mma=True, + ) + source = bound.to_code(cfg) + tree = ast.parse(source) + call = next( + n + for n in ast.walk(tree) + if isinstance(n, ast.Call) + and isinstance(n.func, ast.Attribute) + and n.func.attr == "gathered_softmax_page" + ) + limit = ast.unparse(call.args[3]) + # The helper's limit argument must be the tile filled from the + # second row of the slab, not the slab beginning at state[0, :]. + assert any( + isinstance(store, ast.Assign) + and isinstance(store.targets[0], ast.Subscript) + and ast.unparse(store.targets[0].value) == limit + and any( + isinstance(read, ast.Subscript) + and ast.unparse(read.value) != limit + and ast.unparse(read.slice).startswith("1 * 64 +") + for read in ast.walk(store.value) + ) + for store in ast.walk(tree) + ) + + +def test_seed_pointer_offset_uses_each_aliased_dtype_in_bytes() -> None: + # The FP32 owner begins 16 bytes into storage. The BF16 view of that + # address has offset 8, while its owner has offset 4. + owner = torch.empty(68, dtype=torch.float32)[4:] + assert owner.data_ptr() % 16 == 0 + alias = owner.view(torch.bfloat16) + env = Mock() + env.input_sources = (owner,) + registered = Mock() + registered.sources = (env.tensor_input_source.return_value,) + env.runtime_input_specializations = { + _PERSISTENT_VEC_ALIGNMENT_SPECIALIZATION_KEY: registered + } + env.input_residues_hold_modulo.return_value = True + env.live_example_input.return_value = owner + assert _seed_base_is_aligned(env, alias, 16) + assert not _seed_base_is_aligned(env, alias[4:], 16) + + # An unaligned input and an offset can cancel for this one example. + # The binding only proves individually aligned input and view offsets. + misaligned = torch.empty(32, dtype=torch.bfloat16)[1:] + env.input_sources = (misaligned,) + env.live_example_input.return_value = misaligned + assert misaligned[7:].data_ptr() % 16 == 0 + assert not _seed_base_is_aligned(env, misaligned[7:], 16) + + # An int64 input may be viewed as BF16, but the binding does not + # register an int64 input's pointer residue in its cache key. + integer_owner = torch.empty(32, dtype=torch.int64) + env.input_sources = (integer_owner,) + env.live_example_input.return_value = integer_owner + registered.sources = () + assert not _seed_base_is_aligned(env, integer_owner.view(torch.bfloat16), 16) diff --git a/test/test_cute_register_subblocks.py b/test/test_cute_register_subblocks.py index 7c4d8dd21..4e0a13d7a 100644 --- a/test/test_cute_register_subblocks.py +++ b/test/test_cute_register_subblocks.py @@ -20,6 +20,9 @@ import helion from helion._compiler.cute import cute_register_subblocks as family +from helion._compiler.cute.autotune.mma_dag_surface import ( + _normalize_cute_register_subblocks, +) from helion._testing import DEVICE from helion.exc import InvalidConfig import helion.language as hl @@ -980,6 +983,20 @@ def test_knob_normalization() -> None: ) assert on.config[WARPS] == 2 and on.config[PREFETCH] == 0 assert "cute_fp32_dot" not in on.config # inert fragment knobs are pinned + explicit = on.config | { + "cute_fragment_half_mma": True, + "cute_gathered_page_pipeline": True, + "cute_gathered_page_stages": 8, + } + _normalize_cute_register_subblocks(spec, explicit, fix_invalid=False) + assert ( + not { + "cute_fragment_half_mma", + "cute_gathered_page_pipeline", + "cute_gathered_page_stages", + } + & explicit.keys() + ) # the promoted default carries the family and its first seed assert spec.default_config().config.get(KEY) == "on" off = spec.normalized_config( From 8d969839c9a5af347289689c0d1f6ad58ac12f40 Mon Sep 17 00:00:00 2001 From: Jongsok Choi Date: Wed, 25 Nov 2026 23:33:26 -0800 Subject: [PATCH 2/2] [benchmarks] Publish and exercise the B200 CuTe Flash MLA preset in CI Add an opt-in DeepSeek-V3 MLA decode preset for one request, one query, 16 heads and a (1, 1024) int32 page table. It wraps the same DSL function as Triton, with a persistent eight-stage gathered-page pipeline. The shipped Triton kernel and configuration stay available. Check real/fake geometry, actual query/KV alignment and int32 index eligibility, including the KV pool's element count. Refuse unresolved negative views on the raw-storage path. Context lengths and signed page IDs remain runtime data, including on graph replay. Report CuTe as its own B200 nightly benchmark against both the shipped Triton preset and FlashInfer. Keep inputs, outputs and provider-owned workspace alive until timing finishes, and verify all three graphs against the FP32 reference before and after timing. The Triton row keeps its kernel and configuration and benefits from the corrected capture lifetimes. On GitHub's SM100 CuTe lane, missing NVRTC/cooperative groups support fails the preset's numerical test rather than silently skipping it. Testing: scripts/run_tests.py on B200 4 passed the two CuTe signed-replay and fullgraph/Inductor alignment tests, including the slow one. A fresh cache run of the PR-tier signed numerical on that device took 5.58 s in the test body. The scoped CuTe CPU lane passed six metadata, prerequisite, reference and dashboard tests; the Triton CPU lane passed three with two CuTe-only skips. Strict lint and Pyrefly passed. The actual nightly CLI at context 1024 reported CuTe 16.22 us, Triton 16.26 us and FlashInfer 18.18 us for complete CUDA graph replay (B200 4, PyTorch 2.15.0.dev20260814, CuTe DSL 4.8.1, FlashInfer 0.7.0.post1). CuTe/Triton are effectively tied in this sample. Separately, cold-L2 CUPTI device spans at the published setup were 9.760/9.856 us for CuTe versus 10.432/10.416 for Triton and 14.048/14.016 for FlashInfer in reversed capture orders; those numbers do not measure complete graph replay. Review notes: - Deferred: upstream CPP_FAKETENSOR=1 cannot bind with the Python cache hook. KNOWN_GAPS.md, cpp-fake-mode-tile-provenance. Simply omitting the hook loses three tile IDs; using a private Python mode passes six eager controls but outer strict C++ fakes still reach raw pointer queries in real captures and alias keys, so that constructor-only workaround does not safely support the process-wide mode. - Deferred: shipped raw-pointer dispatch can ignore lazy-negative operands on origin/main. KNOWN_GAPS.md, triton-raw-storage-lazy-negative-inputs. The new explicit CuTe preset always rejects these views. A general policy for aliased inputs, in-place writes and graph dispatch would change other kernels' public contract. The verified entry includes the original four tensors and scale and the caller-side resolve_neg workaround. An attempted selector-only guard still returned the wrong value in both warm compile and disabled modes. A local source-body normalization is a change to the shared authored function; the new CuTe entry is guarded without changing that function. autoreview passed: claude, codex stack-info: PR: https://github.com/pytorch/helion/pull/4764, branch: choijon5/helion-b200/mla/5 --- KNOWN_GAPS.md | 32 +++ pretuned_kernels/README.md | 11 +- .../_helion_aot_flash_mla_cute_cuda_sm100.py | 17 ++ .../megakernels/flash_mla/flash_mla.py | 171 +++++++++++-- .../megakernels/flash_mla/flash_mla_cute.py | 16 ++ pretuned_kernels/run.py | 1 + test/test_pretuned_kernels.py | 235 ++++++++++++++++++ 7 files changed, 460 insertions(+), 23 deletions(-) create mode 100644 pretuned_kernels/megakernels/flash_mla/_helion_aot_flash_mla_cute_cuda_sm100.py create mode 100644 pretuned_kernels/megakernels/flash_mla/flash_mla_cute.py diff --git a/KNOWN_GAPS.md b/KNOWN_GAPS.md index 28b5931a5..509ed138a 100644 --- a/KNOWN_GAPS.md +++ b/KNOWN_GAPS.md @@ -874,6 +874,38 @@ these labelled lines. `test/test_cute_fragment_loop_captures.py` checks computed-fragment index widths; it does not exercise the ordinary nested-store overflow. +## cpp-fake-mode-tile-provenance + +- Area: all Helion backends when PyTorch constructs C++ fake tensors + (`CPP_FAKETENSOR=1` on the November 2026 nightly). +- What is wrong: `create_fake_tensor_mode(ShapeEnv())` raises + `AttributeError: 'CppFakeTensorMode' object has no attribute + '_get_output_tensor_from_cache_entry'` before binding a kernel. + `CPP_FAKETENSOR=1 pytest test/test_fake_tensor.py::test_fake_tensor_mode_supports_cond` + reproduces it without CUDA. +- Since: reproduced on upstream main at `f1d2bf392`. +- Why deferred: the C++ implementation does not use Python's dispatch + cache or expose its output-rebuilding hook. Simply skipping that hook + allows the conditional test to run, but all three + `test_bmm_cast_keeps_distinct_tile_axes` cases then lose a symbolic tile + at the cast between two matrix multiplies: the second multiply's + `m_block_id` is `None` instead of the first multiply's block ID. A + private Python mode constructed under + `torch._dynamo.config.patch(use_cpp_fake_tensor=False)` passes those + eager tests (all six cases in the module), but still receives C++ fake + inputs from Dynamo. On main, `_overlap_aliases((x[:4], x[4:8]))` with + a 16-element strict C++ fake tensor calls `data_ptr()` and raises; the + Python-fake case returns the expected disjoint identity. The alias + partition and `CompileEnvironment.live_example_input` both use a + Python-subclass check to distinguish trace inputs from concrete storage. + A constructor switch alone cannot guarantee that callers using the C++ + mode will keep fake addresses out of native layout and alias proofs. + Supporting that mode across backends needs agreement on those proofs as + well as on symbolic tile provenance. +- Pinned by: `test/test_fake_tensor.py::test_fake_tensor_mode_supports_cond` + and `test_bmm_cast_keeps_distinct_tile_axes` exercise these constraints in + the normal Python mode. No C++ mode support is asserted. + ## triton-raw-storage-lazy-negative-inputs - Area: compiled Triton kernels that consume a tensor's raw storage without diff --git a/pretuned_kernels/README.md b/pretuned_kernels/README.md index 8617905cd..29188e8ee 100644 --- a/pretuned_kernels/README.md +++ b/pretuned_kernels/README.md @@ -80,7 +80,11 @@ pretuned_kernels/ ``` Each kernel ships with one heuristic file per supported compute capability. -At runtime Helion picks the file matching the current GPU. +At runtime Helion picks the file matching the current GPU for AOT kernels. +The fixed `flash_mla_cute` preset is declared on the public kernel in +`megakernels/flash_mla/flash_mla.py`; its SM100 heuristic exposes that same +config and input guard to the benchmark registry. Retune the public preset +there rather than replacing the discovery file. | Kernel | Shape sweep | Reference baseline | |---|---|---| @@ -115,7 +119,8 @@ At runtime Helion picks the file matching the current GPU. | `qwen3_decode_layer_bf16` | Qwen3-8B BF16 batch-1 decode, contexts 576 and 1088 (B2/B4 configs checked, not benchmarked) | compiled vLLM `Qwen3DecoderLayer` with default backends | | `llama32_1b_decode_layer_bf16` | Llama-3.2-1B BF16 batch-1 decode, contexts 576 and 1088 (B2/B4 configs checked, not benchmarked) | compiled vLLM `LlamaDecoderLayer` with default backends | | `qwen3_30b_a3b_moe` | Qwen3-30B-A3B BF16 MoE block (RMSNorm, router, top-8 experts, residual), batch 1 | vLLM's compiled RMSNorm + `Qwen3MoeSparseMoeBlock` with default backend selection (its residual add is fused into the next layer) | -| `flash_mla` | DeepSeek-V3 MLA decode, one request, 16 heads (TP8), context 1024 (checked up to 64K) | FlashInfer TRT-LLM-gen MLA decode, as vLLM's decode CUDA graph calls it (`max_seq_len` = `max_model_len`) | +| `flash_mla` | DeepSeek-V3 MLA decode, one request, 16 heads (TP8), context 1024 (checked up to 64K); shipped Triton preset | FlashInfer TRT-LLM-gen MLA decode, as vLLM's decode CUDA graph calls it (`max_seq_len` = `max_model_len`) | +| `flash_mla_cute` | Same decode on B200: one query token, a contiguous (1, 1024) int32 block table, 16-byte aligned query and KV pointers, int32 indexing (at most 2³¹ − 1 KV elements), and compiler support for CUDA cooperative groups. Materialize lazy negative views first. | Shipped Helion Triton preset and FlashInfer TRT-LLM-gen, measured with the same graph timer | | `deepseek_v3_moe_nvfp4_tp` | DeepSeek-V3 NVFP4 MoE batch-1 decode at TP4, fused all-reduce + residual + RMSNorm | vLLM's router kernel + FlashInfer MoE (PDL) + FlashInfer fused all-reduce/RMSNorm | | `gpt_oss_decode_layer` | GPT-OSS-120B MXFP4 batch-1 decode layer, positions 1000 and 4000, sliding-window and full attention | FP32 PyTorch reference (check); timed alone (it replaces SGLang's per-layer launches) | | `gpt_oss_verify_layer` | GPT-OSS-120B EAGLE3 verify layer, 4 tokens, positions 400 and 4000, sliding-window and full attention | FP32 PyTorch reference (check); timed alone | @@ -128,6 +133,8 @@ At runtime Helion picks the file matching the current GPU. | `inkling2_small` | Inkling-2-Small TP4 / EP4 verify, 8 rows, local / block / global attention layers and NVFP4 / MXFP8 MoE | the stock vLLM Inkling 2 path, end to end in vLLM | | `gemma4_a4b_moe` | Gemma 4 26B-A4B BF16 batch-1 MoE | vLLM Gemma 4 router + fused MoE with default backend selection | +The nightly B200 sweep reports both MLA rows. To run just the CuTe comparison, use `python pretuned_kernels/run.py --kernels flash_mla_cute --hardware b200`. The CuTe B200 pull-request tests separately replay the preset against the FP32 reference with changed lengths and signed page IDs; on GitHub Actions these tests fail if the SM100 NVRTC/cooperative-groups prerequisite is unavailable. They do not require FlashInfer. + Most kernels additionally benchmark against `torch.compile` of the listed PyTorch baseline (a speedup-comparison baseline only -- correctness is checked against the eager reference). The grouped-GEMM entries instead use the named diff --git a/pretuned_kernels/megakernels/flash_mla/_helion_aot_flash_mla_cute_cuda_sm100.py b/pretuned_kernels/megakernels/flash_mla/_helion_aot_flash_mla_cute_cuda_sm100.py new file mode 100644 index 000000000..37c294b5e --- /dev/null +++ b/pretuned_kernels/megakernels/flash_mla/_helion_aot_flash_mla_cute_cuda_sm100.py @@ -0,0 +1,17 @@ +"""Expose the existing guarded B200 MLA preset to pretuned benchmark discovery.""" + +from __future__ import annotations + +from copy import deepcopy + +from pretuned_kernels.megakernels.flash_mla import flash_mla as mla +from pretuned_kernels.megakernels.flash_mla.flash_mla import ( + _cute_key as key_flash_mla_cute, +) + + +def autotune_flash_mla_cute(*args) -> dict[str, object]: + """Use the same input contract and sole fixed config as the public CuTe entry.""" + key_flash_mla_cute(*args) + (config,) = mla.flash_mla_cute.configs + return deepcopy(config.config) diff --git a/pretuned_kernels/megakernels/flash_mla/flash_mla.py b/pretuned_kernels/megakernels/flash_mla/flash_mla.py index 766494908..9062f36bb 100644 --- a/pretuned_kernels/megakernels/flash_mla/flash_mla.py +++ b/pretuned_kernels/megakernels/flash_mla/flash_mla.py @@ -17,20 +17,24 @@ compiled kernel (dynamic shapes, no host-side bucketing); * log-sum-exp combine of the live splits into the BF16 output. -Each call is an isolated launch (no programmatic dependent launch). Tuned for -short decode contexts; long contexts pay the column slices' repeated QK^T. The -benchmark compares against the production B200 MLA decode of vLLM and SGLang -(FlashInfer trtllm-gen), called as vLLM's decode CUDA graph calls it (see -MAX_MODEL_LEN). +The default Triton preset targets short decode contexts. Its column slices +repeat QK^T at long contexts. The optional ``flash_mla_cute`` entry targets +one query on SM100 with 16-byte aligned query and KV pointers and matching +NVRTC and CUDA cooperative-groups headers for SM100. Each preset +runs in one launch, without programmatic dependent launch. The benchmark +compares with FlashInfer TRT-LLM-gen as vLLM calls it in its decode graph +(see MAX_MODEL_LEN). """ from __future__ import annotations +import argparse import math from pathlib import Path from typing import TYPE_CHECKING import torch +from torch._subclasses.fake_tensor import is_fake import helion import helion.language as hl @@ -170,6 +174,99 @@ def flash_mla( return output.view(1, query_len, num_heads, value_dim) +def _cute_grid_available() -> bool: + # Load this CuTe-only prerequisite when the opt-in preset is requested. + from helion._compiler.cute.cooperative_grid_ptx import GridCompilerUnavailable + from helion._compiler.cute.cooperative_grid_ptx import grid_sync_asm + + try: + return grid_sync_asm((10, 0)) is not None + except GridCompilerUnavailable: + return False + + +def _cute_key( + query: torch.Tensor, + kv_cache: torch.Tensor, + block_tables: torch.Tensor, + seq_lens: torch.Tensor, + scale: float, +) -> int: + """The one-query B200 preset keeps sequence lengths and page IDs on device.""" + if ( + query.device.type != "cuda" + or torch.cuda.get_device_capability(query.device) != (10, 0) + or query.shape != (1, 1, NUM_HEADS, QK_DIM) + or query.dtype != torch.bfloat16 + or kv_cache.ndim != 4 + or kv_cache.shape[1:] != (1, CACHE_BLOCK_SIZE, QK_DIM) + or kv_cache.dtype != torch.bfloat16 + or block_tables.shape != (1, BLOCK_TABLE_CAPACITY) + or block_tables.dtype != torch.int32 + or seq_lens.shape != (1,) + or seq_lens.dtype != torch.int32 + or scale != MLA_SCALE + or any( + t.device != query.device or not t.is_contiguous() + for t in (query, kv_cache, block_tables, seq_lens) + ) + ): + raise ValueError( + "flash_mla_cute requires SM100 and the single-query BF16 decode layout" + ) + # The compiled kernel reads the physical storage of all four operands. + # A lazy negative view shares that storage but has different logical values. + # The gathered-page config matches an int32 page-lane range. Auto + # indexing widens that range when any input exceeds the int32 limit. + if kv_cache.numel() > torch.iinfo( + torch.int32 + ).max or flash_mla_cute.settings.index_dtype not in (None, torch.int32): + raise ValueError( + "flash_mla_cute requires int32 indexing and a KV pool with at most " + "2**31 - 1 elements; use flash_mla for wider indexing" + ) + if any(t.is_neg() for t in (query, kv_cache, block_tables, seq_lens)): + raise ValueError("flash_mla_cute requires resolved negative views") + # Fake operands have no storage addresses. Keep metadata binding separate + # from eager dispatch, where both actual inputs must be aligned. Inductor + # may realign its graph inputs before calling the generated launch. + has_fake_operand = False + for operand in (query, kv_cache): + if is_fake(operand): + has_fake_operand = True + elif operand.data_ptr() % 16: + raise ValueError( + "flash_mla_cute requires 16-byte aligned query and KV pointers" + ) + if not _cute_grid_available(): + raise RuntimeError( + "flash_mla_cute requires matching NVRTC and CUDA cooperative-groups headers " + "for SM100; use flash_mla for the Triton preset" + ) + return int(has_fake_operand) + + +# B200, one query / 16 heads: stage eight aligned Q/K panels, then combine +# the split weights in the same persistent launch. The default Triton entry +# above and the CuTe entry share the exact same Helion function. +flash_mla_cute = helion.kernel( + flash_mla.fn, + backend="cute", + static_shapes=False, + config=helion.Config( + block_sizes=[32, 1, 128, 1, 128], + num_threads=[1, 1, 1, 1, 128, 1, 1], + pid_type="persistent_interleaved", + cross_loop_pipeline="barrier", + cute_fragment_half_mma=True, + cute_gathered_page_pipeline=True, + cute_gathered_page_stages=8, + cute_in_kernel_grid_init=True, + ), + key=_cute_key, +) + + def _make_inputs(context: int, seed: int = 0) -> dict[str, torch.Tensor]: """One request at ``context`` tokens; its QUERY_TOKENS query tokens are its last positions.""" @@ -321,11 +418,15 @@ def correctness_check() -> None: @torch.inference_mode() -def main(verbose: bool = True) -> dict: - """Benchmark the megakernel against FlashInfer trtllm-gen over the decode contexts.""" +def main(verbose: bool = True, *, include_cute: bool = False) -> dict: + """Compare captured graphs; request CuTe to also time the shipped Triton preset.""" _require_sm100() if not has_flashinfer(): raise RuntimeError("FlashInfer is required for this comparison") + if include_cute and not _cute_grid_available(): + raise RuntimeError( + "The CuTe benchmark requires NVRTC and matching cooperative-groups headers" + ) import sys @@ -333,22 +434,42 @@ def main(verbose: bool = True) -> dict: from _bench import capture_cuda_graph from _bench import run_sweep + # CUDA graphs store raw addresses, not ownership of captured Python + # tensors. Keep the callable (including FlashInfer's private table, + # counter and workspace), its output and its reference through timing. + captures: list[ + tuple[Callable, torch.cuda.CUDAGraph, torch.Tensor, torch.Tensor] + ] = [] + + def capture(call: Callable[[], torch.Tensor], expected: torch.Tensor) -> Callable: + graph, output = capture_cuda_graph(call) + graph.replay() + torch.testing.assert_close(output.float(), expected, atol=0.02, rtol=0.05) + captures.append((call, graph, output, expected)) + return graph.replay + + def check_timed_graphs() -> None: + for _owner, graph, output, expected in captures: + graph.replay() + torch.testing.assert_close(output.float(), expected, atol=0.02, rtol=0.05) + captures.clear() + def make_calls(context: int) -> tuple: + # Drop the previous shape's storage only after its timed replays. + check_timed_graphs() tensors = _make_inputs(context, seed=context) args = _kernel_args(tensors) - flashinfer = _make_flashinfer_call(tensors) - torch.testing.assert_close( - flash_mla(*args).float(), reference(tensors).float(), atol=0.02, rtol=0.05 - ) - helion_graph, _ = capture_cuda_graph(lambda: flash_mla(*args)) - flashinfer_graph, _ = capture_cuda_graph(flashinfer) - return ( - helion_graph.replay, - [("flashinfer_trtllm_gen", flashinfer_graph.replay)], - f"{context:>8d}", - ) - - return run_sweep( + expected = reference(tensors).float() + triton = capture(lambda: flash_mla(*args), expected) + baseline = capture(_make_flashinfer_call(tensors), expected) + baselines = [("flashinfer_trtllm_gen", baseline)] + selected = triton + if include_cute: + selected = capture(lambda: flash_mla_cute(*args), expected) + baselines.insert(0, ("helion_triton", triton)) + return selected, baselines, f"{context:>8d}" + + result = run_sweep( CONTEXTS, make_calls, use_cudagraph=False, @@ -357,7 +478,15 @@ def make_calls(context: int) -> tuple: verbose=verbose, shape_header=f"{'context':>8s}", ) + check_timed_graphs() + return result if __name__ == "__main__": - main() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--cute", + action="store_true", + help="compare CuTe, shipped Triton and FlashInfer", + ) + main(include_cute=parser.parse_args().cute) diff --git a/pretuned_kernels/megakernels/flash_mla/flash_mla_cute.py b/pretuned_kernels/megakernels/flash_mla/flash_mla_cute.py new file mode 100644 index 000000000..5d3df3edf --- /dev/null +++ b/pretuned_kernels/megakernels/flash_mla/flash_mla_cute.py @@ -0,0 +1,16 @@ +"""Nightly B200 comparison of DeepSeek-V3 CuTe MLA, shipped Triton and FlashInfer.""" + +from __future__ import annotations + +from pretuned_kernels.megakernels.flash_mla import flash_mla as mla +from pretuned_kernels.megakernels.flash_mla.flash_mla import ( + use_cudagraph as use_cudagraph, +) + + +def main(verbose: bool = True) -> dict: + return mla.main(verbose=verbose, include_cute=True) + + +if __name__ == "__main__": + main() diff --git a/pretuned_kernels/run.py b/pretuned_kernels/run.py index ffb7bdf9d..1b805d0d9 100755 --- a/pretuned_kernels/run.py +++ b/pretuned_kernels/run.py @@ -74,6 +74,7 @@ "gemma4_a4b_moe", "gpt_oss_moe", "flash_mla", + "flash_mla_cute", "deepseek_v3_moe_nvfp4", # External grouped references compile substantial CuTe/DeepGEMM code. "grouped_gemm", diff --git a/test/test_pretuned_kernels.py b/test/test_pretuned_kernels.py index 77bd66bc7..ab31db0a4 100644 --- a/test/test_pretuned_kernels.py +++ b/test/test_pretuned_kernels.py @@ -6,11 +6,13 @@ from __future__ import annotations +from contextlib import nullcontext from dataclasses import dataclass import importlib.util import inspect import math import os +import runpy import subprocess import sys from typing import TYPE_CHECKING @@ -19,7 +21,11 @@ import pytest import torch +from torch._dynamo import config as dynamo_config from torch._environment import is_fbcode +from torch._functorch import config as functorch_config +from torch._inductor import config as inductor_config +from torch._subclasses.fake_tensor import FakeTensorMode import torch.distributed as dist import torch.nn.functional as F from torch.testing._internal.distributed.fake_pg import FakeStore @@ -27,6 +33,8 @@ import helion from helion._compat import GLUON_REQUIREMENT from helion._compat import supports_gluon +from helion._compat import supports_torch_compile_template_lowering +from helion._compiler.cute import cooperative_grid_ptx from helion._hardware import HardwareInfo from helion._hardware import get_hardware_info from helion._testing import DEVICE @@ -214,6 +222,43 @@ def test_qwen3_decode_layer_has_explicit_runtime_metadata_contract() -> None: assert max(module.CONTEXT_LENGTHS) <= module.CONTEXT +@pytest.mark.cpu_only +def test_runner_registers_b200_flash_mla_cute() -> None: + from pretuned_kernels.megakernels.flash_mla import flash_mla as mla + + runner = _import_pretuned_runner() + name = "flash_mla_cute" + assert {"flash_mla", name} <= set(runner.KERNELS) + assert runner._supported_hardware(name) == {"b200"} + assert "skipped" in runner.run_kernel(name, "h100") + metrics = { + "helion_wins": 1, + "total": 1, + "geomean": 1.25, + "best_speedup": 1.25, + "baselines": { + name: {"wins": 1, "total": 1, "geomean": speedup, "best_speedup": speedup} + for name, speedup in ( + ("helion_triton", 1.25), + ("flashinfer_trtllm_gen", 1.5), + ) + }, + } + with patch.object(mla, "main", return_value=metrics) as compare: + assert runner.run_kernel(name, "b200") == { + "kernel": name, + "pretuned_hardware": ["b200"], + "cudagraph": True, + **metrics, + } + compare.assert_called_once_with(verbose=True, include_cute=True) + compare.reset_mock() + runpy.run_module( + "pretuned_kernels.megakernels.flash_mla.flash_mla_cute", run_name="__main__" + ) + compare.assert_called_once_with(verbose=True, include_cute=True) + + def test_runner_supported_hardware_parses_cuda_and_rocm_heuristics( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -428,6 +473,87 @@ def args( key(*changed) +@pytest.mark.cpu_only +@onlyBackends(["cute"]) +@pytest.mark.parametrize("cpp", [False, True]) +def test_flash_mla_key_infers_metadata_without_a_fake_pointer(cpp: bool) -> None: + # Exercise the preset key itself; the separate compiler-wide C++ fake + # issue is documented in KNOWN_GAPS.md (cpp-fake-mode-tile-provenance). + module = _import_pretuned_kernel_module("flash_mla") + supports_cpp = hasattr(dynamo_config, "use_cpp_fake_tensor") + if cpp and not supports_cpp: + pytest.skip("this PyTorch does not offer C++ fake tensors") + with ( + dynamo_config.patch(use_cpp_fake_tensor=cpp) if supports_cpp else nullcontext(), + functorch_config.patch(fake_tensor_allow_unsafe_data_ptr_access=False), + FakeTensorMode(), + patch.object(torch.cuda, "get_device_capability", return_value=(10, 0)), + patch.object( + cooperative_grid_ptx, "grid_sync_asm", return_value="ret;" + ) as leaf, + ): + cuda = torch.device("cuda", 0) + q = torch.empty((1, 1, 16, 576), dtype=torch.bfloat16, device=cuda) + kv = torch.empty((16, 1, 64, 576), dtype=q.dtype, device=cuda) + table = torch.empty((1, 1024), dtype=torch.int32, device=cuda) + seq = torch.empty((1,), dtype=table.dtype, device=cuda) + fake_args = (q, kv, table, seq, module.MLA_SCALE) + assert module._cute_key(*fake_args) == 1 + preset = _import_pretuned_heuristic("flash_mla_cute") + assert preset.key_flash_mla_cute(*fake_args) == 1 + config = preset.autotune_flash_mla_cute(*fake_args) + assert config == dict(module.flash_mla_cute.configs[0]) + # Fake tensors exercise the actual automatic index transition without + # allocating a multi-gigabyte KV pool on device. + limit = torch.iinfo(torch.int32).max // (64 * 576) + for pages in (limit, limit + 1): + pool = kv.new_empty((pages, 1, 64, 576)) + if pages == limit: + assert module._cute_key(q, pool, table, seq, module.MLA_SCALE) == 1 + else: + with pytest.raises(ValueError, match="int32 indexing"): + module._cute_key(q, pool, table, seq, module.MLA_SCALE) + with ( + patch.object(module.flash_mla_cute.settings, "index_dtype", torch.int64), + pytest.raises(ValueError, match="int32 indexing"), + ): + module._cute_key(*fake_args) + with pytest.raises(ValueError, match="single-query"): + module._cute_key(q[..., :512], kv, table, seq, module.MLA_SCALE) + inputs = (q, kv, table, seq) + for i, arg in enumerate(inputs): + args = [*inputs] + args[i] = torch._neg_view(arg) + with pytest.raises(ValueError, match="resolved negative views"): + module._cute_key(*args, module.MLA_SCALE) + leaf.return_value = None + with pytest.raises(RuntimeError, match="cooperative-groups"): + module._cute_key(q, kv, table, seq, module.MLA_SCALE) + + +@pytest.mark.cpu_only +@onlyBackends(["cute"]) +def test_flash_mla_checks_the_grid_operation_on_first_use() -> None: + module = _import_pretuned_kernel_module("flash_mla") + toolkit = cooperative_grid_ptx._Toolkit(cooperative_grid_ptx, (), frozenset({100})) + with ( + patch.object(cooperative_grid_ptx, "_toolkit", return_value=toolkit), + patch.object( + cooperative_grid_ptx, "_compile_grid_sync", return_value=None + ) as compile_leaf, + ): + assert cooperative_grid_ptx.grid_toolkit_installed((10, 0)) + assert not module._cute_grid_available() + assert not module._cute_grid_available() + compile_leaf.assert_called_once_with(toolkit, 100) + with patch.object( + cooperative_grid_ptx, + "grid_sync_asm", + side_effect=cooperative_grid_ptx.GridCompilerUnavailable("NVRTC unavailable"), + ): + assert not module._cute_grid_available() + + @skipIfRefEager("tile dependencies are built only in compiled mode") @skipIfNotTriton("the TP4 megakernels are pinned to backend='triton'") def test_deepseek_v3_tp_megakernels_compile() -> None: @@ -1314,6 +1440,115 @@ def test_gpt_oss_moe(self): self.skipTest("gpt_oss_moe correctness requires vLLM with FlashInfer.") module.correctness_check() + @onlyBackends(["cute"]) + def test_flash_mla_cute_pretuned(self) -> None: + if not is_cuda() or torch.cuda.get_device_capability() != (10, 0): + self.skipTest("requires an SM100 device") + module = _import_pretuned_kernel_module("flash_mla") + kernel = module.flash_mla_cute + self.assertIs(kernel.fn, module.flash_mla.fn) + if not module._cute_grid_available(): + requirement = cooperative_grid_ptx.grid_sync_requirement((10, 0)) + if os.environ.get("GITHUB_ACTIONS") == "true": + self.fail(f"SM100 CuTe CI must run the MLA preset: {requirement}") + self.skipTest(requirement) + # 513 pages require repeated softmax updates within a split. Within + # each page, the nine 64-column QK panels wrap the eight-stage ring. + data = module._make_inputs(32769, seed=41) + args = module._kernel_args(data) + # The same graph and pointers must observe new page IDs and the new + # live length. The CuTe preset must never cache them in the config key. + kernel(*args) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + output = kernel(*args) + graph.replay() + torch.testing.assert_close( + output.float(), module.reference(data).float(), atol=0.02, rtol=0.05 + ) + table = data["block_tables"] + table.copy_(table.roll(1, 1)) + table[0, 0] = -1 + table[0, 1] = -data["kv_cache"].shape[0] + # Both signed page IDs are live at 65 tokens; only the first is live + # at 31. These replays use the same graph and storage addresses. + for length in (65, 31): + data["seq_lens"].fill_(length) + graph.replay() + torch.testing.assert_close( + output.float(), module.reference(data).float(), atol=0.02, rtol=0.05 + ) + with self.assertRaisesRegex(ValueError, "single-query"): + kernel.bind((args[0].expand(1, 2, -1, -1), *args[1:])) + query = data["query"] + offset_query = query.new_empty(query.numel() + 1)[1:].view_as(query) + with self.assertRaisesRegex(ValueError, "16-byte aligned"): + kernel.bind((offset_query, *args[1:])) + # The lazy and materialized negatives have equal logical values but + # different storage values. A warm eager bind may only use the latter. + for i in (0, 1): + lazy = list(args) + lazy[i] = torch._neg_view(args[i]) + with self.assertRaisesRegex(ValueError, "resolved negative views"): + kernel(*lazy) + + @pytest.mark.slow + @onlyBackends(["cute"]) + def test_flash_mla_cute_compiled_alignment(self) -> None: + if ( + not is_cuda() + or torch.cuda.get_device_capability() != (10, 0) + or not supports_torch_compile_template_lowering() + ): + self.skipTest("requires SM100 and torch.compile template lowering") + module = _import_pretuned_kernel_module("flash_mla") + if not module._cute_grid_available(): + self.skipTest("requires matching NVRTC and cooperative-groups headers") + data = module._make_inputs(65, seed=41) + args = module._kernel_args(data) + expected = module.reference(data).float() + eager = torch.compile(module.flash_mla_cute, backend="eager", fullgraph=True) + # Exercise the copying policy even if this installation normally asks + # Inductor to assert alignment instead. Older versions always copy. + options = ( + {"alignment_asserts_inputs": False} + if hasattr(inductor_config, "alignment_asserts_inputs") + else {} + ) + compiled = torch.compile(module.flash_mla_cute, fullgraph=True, options=options) + for run in (eager, compiled): + torch.testing.assert_close( + run(*args).float(), expected, atol=0.02, rtol=0.05 + ) + + for name in ("query", "kv_cache"): + src = data[name] + lazy_args = module._kernel_args({**data, name: torch._neg_view(src)}) + for run in (eager, compiled): + with self.assertRaisesRegex( + (ValueError, RuntimeError), "resolved negative views" + ): + run(*lazy_args) + shifted = src.new_empty(src.numel() + 1)[1:].view_as(src) + shifted.copy_(-src) + changed = {**data, name: shifted} + actual_args = module._kernel_args(changed) + other = module.reference(changed).float() + self.assertFalse(torch.equal(expected, other)) + # An unallocated operand does not exempt the other (real) pointer. + counterpart = 1 if name == "query" else 0 + mixed = list(actual_args) + mixed[counterpart] = FakeTensorMode().from_tensor(args[counterpart]) + with self.assertRaisesRegex(ValueError, "16-byte aligned"): + module._cute_key(*mixed) + # Eager dispatch checks the caller's pointer. The default + # Inductor graph realigns its input before the generated launch. + with self.assertRaisesRegex(ValueError, "16-byte aligned"): + eager(*actual_args) + torch.testing.assert_close( + compiled(*actual_args).float(), other, atol=0.02, rtol=0.05 + ) + @pytest.mark.timeout(600) @skipIfCute(_PINNED_TO_TRITON) def test_flash_mla(self):