You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by bo...@apache.org on 2026/05/29 04:45:10 UTC
(tvm) 15/22: refactor(op-dispatch): ewise broadcast at layout level + copy vec-alignment fix (#645)
This is an automated email from the ASF dual-hosted git repository.
spectrometerHBH pushed a commit to branch tir-bench
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit 3432c72a504fd77bc519066e5545ebb56328d733
Author: Bohan Hou <bo...@andrew.cmu.edu>
AuthorDate: Wed May 27 14:07:19 2026 -0700
refactor(op-dispatch): ewise broadcast at layout level + copy vec-alignment fix (#645)
* refactor(op-dispatch): split CUDA elementwise into reg + smem dispatches
Mirror the cuda/copy/ split (PR #640) along storage scope: every op
registers two variants instead of three.
reg.py — operands all in ``local`` (registers); partition induced
by anchor layout (Case A: non-trivial layout via
``buf.local(*shape)``; Case B: all-trivial = each thread
runs the full loop on its private buffer).
smem.py — operands all in ``shared*``; partition synthesized from
``sctx.intra`` with end-of-emit ``cta_sync`` /
``warpgroup_sync`` / ``warp_sync``.
OpSpec gains a first-class ``vec_impls: list[VecImpl]``. Each VecImpl
declares ``(vec_len, applies, emit)`` for one packed PTX/CUDA
intrinsic; the schedule picks the widest one matching both the layout
contig tail and the op-provided menu (mirrors copy's
``copy_{8,16,32,64,128}b`` selection). When no VecImpl matches, the
schedule falls back to ``Tx.vectorized(vec_chunk)`` with scalar
compute — memory access stays vectorized, math goes scalar.
The packed-emit collapses the previous 4 (operand-shape) × 2
(view-mode) ``@Tx.prim_func`` explosion (~240 + 140 + 300 lines in
``schema.py``) because shape branching now happens in plain Python
inside the VecImpl's ``emit`` callable, not as TVMScript IR.
Borrowed primitives from copy (PR #640):
_common.py ← _TID_AXIS_FOR_SCOPE, _thread_cnt, _carve_tail,
_sort_by_stride_desc, _extract_tile,
_vec_len_candidates, _verify_s_tail_contig
reg.py ← _all_threads_active, _axis_decl, _compute_perm_r,
_make_thread_placeholders, _substitute_axes,
_ptr_off, align_layouts_raw
Schedule selection now uses Tx.lane_id / Tx.thread_id_in_wg /
threadIdx.x via ``_axis_decl`` (the placeholder + substitute pattern
enabled by PR #640's ``PrepareLaunchParams`` /
``ResolveAllScopeBinds`` split) instead of the legacy ``tx % cnt``
local-tid expressions.
Layout signature check (``sigs_equal`` from ``cuda/layout_utils.py``)
is preserved as a predicate-time guard in reg.py — catches operands
with same thread axes but different extents.
File layout:
cuda/elementwise/
├── __init__.py re-export register
├── register.py loops ALL_OPS × {reg, smem}
├── _common.py multi-operand layout helpers
├── reg.py induced + trivial paths
├── smem.py synthesized
├── ops/{unary,binary,cast,fma}.py per-family parse + compute_scalar
└── vec_emit/{binary_f32x2,cast_vec2,fma_f32x2}.py
one VecImpl per packed intrinsic
Deleted: schedule_thread.py, schedule_collective_reg.py,
schedule_collective_smem.py, schema.py.
Testing: added codegen-dispatch checks (no GPU runtime required) to
the existing per-op test files. Force explicit target arch
(``sm_80`` / ``sm_100a``) so the codegen path runs even when host
CUDA detection fails:
test_binary.py + test_binary_add_f32_sm100_packed_f32x2_dispatch
+ test_binary_add_f16_scalar_fallback_dispatch
test_unary.py + test_unary_exp_f16_shared_scalar_fallback_dispatch
+ test_cast_vec2_packed_dispatch
test_fma.py + test_fma_f32_sm100_packed_f32x2_dispatch
* refactor(op-dispatch): handle ewise broadcast at layout level via shared preprocess
Introduce a shared preprocess in `cuda/elementwise/_common.py` that slices
each operand by its region and then lifts to the anchor's tensor shape via
stride-0 replica iters. NumPy-style right-aligned broadcast rules:
``len(op_shape) <= len(anchor_shape)`` and per-dim
``op_shape[d] == anchor_shape[d+pad] OR op_shape[d] == 1``. Anchor is always
``plan.dst`` (NumPy's strict ``out=`` semantics; verified empirically).
Reg path consumes the preprocessed layouts directly: emit functions use
``f * vec_len + k`` as a logical 1D coord into per-operand ``decl_buffer``
views — each buffer's lifted layout maps logical -> physical at access.
Removes the prior ``_apply_offset`` helper that computed physical offsets
and double-applied the layout transform.
Smem path predicate uses ``shape_broadcast_compat`` instead of strict
extent equality. Per-element index derivation moves from the now-removed
parser-side ``_binary_broadcast_index_fn`` to a generic
``_broadcast_indices`` in dispatch; ``fetch_src_value`` and a new
``_src_lane_indices`` helper consult it when shapes differ.
Trim 13 dead helpers (build_atoms_multi, atoms_contig_tail_extent_multi,
per_op_offset_template, align_layouts_synthesized, etc.) — the new pipeline
doesn't need them. _common.py drops from ~755 to ~390 lines.
Tests:
- Rewrite test_cast_warpgroup_src_layout_to_flat_uses_vec2_intrinsic to
use wg-view on dst (dispatch requires layout-symmetric operands; no
more flat-vs-wg asymmetry).
- Broaden test_cast_validate_extent_mismatch_rejected's regex to include
"thread part mismatch" (the new align-time check message).
- Bump test_binary_op_vectorized broadcast parametrize to ``(32, 5, 4)``
/ ``(32, 1, 4)`` (>= warp size for sub-cta sctx).
* fix(op-dispatch): exclude thread-axis strides from copy/reg vec alignment + unroll outer loop
Two correctness/perf fixes to ``cuda/copy/reg.py:_choose_vec_len`` and the
per-thread emit loop, both surfaced by ``wg_local_layout``-based R-side
operands flowing into a swizzled SMEM destination.
(1) Alignment check. ``shared_terms`` used to include
``[int(it.stride) for it in r_p.shard if it.axis.is_thread()]`` and the
s-side analog. Thread-axis strides are partition-coord (virtual), not
storage-physical: they don't enter the per-thread ld/st pointer (R-side
base is ``r_local.data`` starting at 0; S-side thread coord is
redistributed through ``apply_to_shape`` into mem-iter strides). For
``wg_local_layout`` (R thread iter has stride 1), the old check rejected
every vec >= 2 via ``1 % n != 0`` and degraded to ``copy_16b``. Strip
both sides; check only ``s_p.offset`` + ``r_p.offset`` + post-vec-split
outer atom strides — all genuinely physical.
(2) Outer loop. ``for f in range(total_outer)`` parses as a runtime serial
loop, not a Python-unrolled sequence, so emit_iter_offset's bit-select
over signed_strides never constant-folded. Switch to ``Tx.unroll`` so
the loop is fully expanded and each iter's bit pattern reduces to
literal constants at lowering.
Combined effect for the fp16 wg->swizzled-smem case in fp16_bf16_gemm's
writeback: ``for f in 0..64: copy_16b`` (64 scalar 2B stores per thread
with per-iter swizzle.apply()) -> 8 unrolled ``copy_128b`` with the
swizzle's signed-strides precomputed once.
Add regression test in ``test_reg.py`` that asserts: copy_128b in
generated CUDA, copy_16b absent, copy_128b call sites >= 9 (unroll catch),
and the fast-path ``& 1) * v_<n>[`` bit-select pattern appears >= 3 times.
* perf(op-dispatch): use range, not Tx.unroll, for emit outer loops
``Tx.unroll(outer_total)`` in both ``cuda/copy/reg.py:_emit_reg`` and
``cuda/elementwise/reg.py:_emit_induced_{packed,scalar}`` expands every
per-iter scratch buffer declaration into N copies. On kernels with many
emit sites (flash_attention4 writeback) this floods the function with
``alignas(64) int`` arrays — 1944 vs 72 in the pre-PR baseline. The
arrays pressure the register allocator, spill, and net-out as a
~10% slowdown on the s8192_h32kv16 config.
Switching to ``for f in range(N)`` keeps the loop body as a single
serial-loop TIR node; the per-iter scratch lives in one set of
declarations that the C compiler reuses across iterations. ptxas
auto-unrolls static-bound loops downstream without the scratch cost.
Measured impact on flash_attention4 s8192_h32kv16: tir 848us -> 761us
(within 0.3% of the recorded baseline of 763.47us). The wider-vec
``copy_128b`` from the ``_choose_vec_len`` fix is preserved (FA4 dump
still has 17 copy_128b calls vs 0 before that fix).
Relaxes the unroll-count assertion in the regression test added in the
prior commit; keeps the vec-width + swizzle-fast-path bit-select pattern
assertions, which are the actual signal we care about.
---
.../tirx/operator/tile_primitive/cuda/copy/reg.py | 47 +-
.../tile_primitive/cuda/elementwise/__init__.py | 24 +-
.../tile_primitive/cuda/elementwise/_common.py | 445 +++++---
.../cuda/elementwise/ops/__init__.py | 121 ++
.../tile_primitive/cuda/elementwise/ops/binary.py | 127 +++
.../tile_primitive/cuda/elementwise/ops/cast.py | 45 +
.../tile_primitive/cuda/elementwise/ops/fma.py | 50 +
.../tile_primitive/cuda/elementwise/ops/unary.py | 117 ++
.../tile_primitive/cuda/elementwise/reg.py | 362 ++++++
.../tile_primitive/cuda/elementwise/register.py | 55 +-
.../cuda/elementwise/schedule_collective_reg.py | 410 -------
.../cuda/elementwise/schedule_collective_smem.py | 132 ---
.../cuda/elementwise/schedule_thread.py | 121 --
.../tile_primitive/cuda/elementwise/schema.py | 1165 --------------------
.../tile_primitive/cuda/elementwise/smem.py | 264 +++++
.../cuda/elementwise/vec_emit/__init__.py | 40 +
.../cuda/elementwise/vec_emit/binary_f32x2.py | 96 ++
.../cuda/elementwise/vec_emit/cast_vec2.py | 89 ++
.../cuda/elementwise/vec_emit/fma_f32x2.py | 78 ++
.../operator/tile_primitive/cuda/copy/test_reg.py | 84 ++
.../tile_primitive/cuda/elementwise/test_binary.py | 83 +-
.../tile_primitive/cuda/elementwise/test_fma.py | 48 +
.../tile_primitive/cuda/elementwise/test_unary.py | 104 +-
23 files changed, 2029 insertions(+), 2078 deletions(-)
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/copy/reg.py b/python/tvm/tirx/operator/tile_primitive/cuda/copy/reg.py
index 0ca2c5dc34..a75d7eb53b 100644
--- a/python/tvm/tirx/operator/tile_primitive/cuda/copy/reg.py
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/copy/reg.py
@@ -354,29 +354,23 @@ def _choose_vec_len(elem_bits: int, atoms, r_p, s_p) -> int:
multiple of vec_len, so the resulting vec ld/st pointer is
naturally aligned to vec_bits/8 bytes.
- Per-thread S addr = s_p.offset + sum(thread_coord * s_p.shard.stride
- for thread axes) + sum(post-split atom_s_stride * round_count); R addr
- is the analogous sum on the R side. For natural alignment to
- vec_bits/8 bytes, each of those element-count strides / region bases
- must be a multiple of vec_len.
-
- Important: only the **post-vec-split** atom strides matter for
- alignment. The contig-tail atoms (whose extents the vec ld/st consumes)
- have stride 1 by definition; they live entirely inside the vec and
- contribute nothing to the per-round address delta. Checking them
- against vec_len would always fail (1 % n != 0 for n > 1).
+ Only **mem-axis** strides contribute to physical address. Thread-axis
+ iter strides live in partition-coord space (which thread owns which
+ logical position), not in the buffer's storage space — they're
+ redistributed through ``apply_to_shape`` into the mem iters and don't
+ appear directly in the per-thread address. So neither r-side nor
+ s-side thread-axis strides belong in the alignment check.
+
+ The contig-tail atoms (whose extents the vec ld/st consumes) have
+ stride 1 by definition; they live entirely inside the vec and
+ contribute nothing to the per-round address delta. Only the
+ **post-vec-split** outer atom strides matter for the per-round delta.
"""
t = _atoms_contiguous_tail_extent(atoms)
- # Region-base + thread-axis shard strides are the same for every
- # candidate. Memory-axis shard strides drive within-thread iteration
- # (already captured by atoms) and don't contribute to the per-thread
- # base / per-round delta, so they must NOT be alignment-checked —
- # otherwise a memory iter with stride 1 (the contig tail consumed by
- # the vec ld/st) would falsely reject every n > 1.
- shared_terms = [int(it.stride) for it in s_p.shard if it.axis.is_thread()]
- shared_terms += [int(it.stride) for it in r_p.shard if it.axis.is_thread()]
- shared_terms += list(s_p.offset.values())
- shared_terms += list(r_p.offset.values())
+ # Region-base offsets are real address contributions. Thread-iter
+ # strides on either side are partition-virtual, not storage-physical,
+ # so they don't enter the per-thread address — exclude them.
+ shared_terms = list(s_p.offset.values()) + list(r_p.offset.values())
for n in _vec_len_candidates(elem_bits):
if n == 1:
return n
@@ -562,11 +556,12 @@ def _emit_reg(op_call: TilePrimitiveCall, sctx: DispatchContext) -> PrimFunc:
s_off = _substitute_axes(s_off_template, placeholders, sctx)
_setup_swizzle(s_off)
r_local = r_buf.local(*per_thread_r_shape)
- # Use Python range so f is a compile-time Python int — emit_iter_offset
- # in the swizzle-fast path then constant-folds the bit-selection at
- # parse time (no runtime shift/and per iter). For non-swizzle and
- # fallback paths the body is identical to the previous Tx.unroll form
- # after the unroll pass anyway, since total_outer is always a Python int.
+ # Keep as a serial TIR loop and let ptxas unroll downstream. An
+ # explicit ``Tx.unroll`` materializes the per-iter scratch
+ # (ds/dr/s_ptr/r_ptr, swizzle ``v_<n>[]`` signed-strides) as N
+ # copies of each buffer declaration; on kernels with many R↔S copy
+ # sites and large ``total_outer`` (FA4 writeback) this floods the
+ # function with ``alignas(64) int`` arrays and pressures registers.
for f in range(total_outer):
ds, dr = _outer_const_offsets(outer, f)
s_ptr = _ptr_off(s_buf.ptr_to(s_zero_indices), _s_iter_off(f, ds, s_off))
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/__init__.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/__init__.py
index bf2945f0f2..872cad0867 100644
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/__init__.py
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/__init__.py
@@ -15,18 +15,24 @@
# specific language governing permissions and limitations
# under the License.
-"""Unified elementwise dispatch for CUDA.
+"""CUDA elementwise dispatch.
-Three schedules cover all elementwise ops (unary / binary / cast / fma):
+Split by storage scope to mirror ``cuda/copy/``:
- per_thread: scope == thread; one thread runs vectorized serial loop
- tile_local: scope > thread; local buffer with layout describing
- thread->element mapping; threads cooperatively cover the
- tile via per-thread views (buf.local(*shape))
- shared_distributed: scope > thread; shared buffer; fused-tid distribution
- with scope-level barrier at the end
+ reg.py — operands all in ``local`` (registers) → induced partition
+ smem.py — operands all in ``shared*`` → synthesized partition
-Phase 1 covers unary ops. Binary / cast / fma to follow.
+Each op in ``ops.ALL_OPS`` is registered under both variants. Per-op packed
+PTX/CUDA intrinsics live in ``vec_emit/`` (``binary_f32x2`` / ``cast_vec2``
+/ ``fma_f32x2``) and are attached to the relevant ``OpSpec.vec_impls``.
"""
from .register import *
+
+# Suppress submodule-attribute leakage. Without an explicit ``__all__`` here,
+# ``from tvm.tirx.operator.tile_primitive.cuda.elementwise import *`` (run by
+# tile_primitive/__init__.py) re-exports the implicit submodule attributes
+# (``ops``, ``reg``, ``smem``, ``vec_emit``) — and ``ops`` in particular
+# shadows the top-level ``tile_primitive/ops.py`` (BinaryReduce / UnaryReduce
+# / ...) when downstream code does ``from tile_primitive import ops``.
+__all__: list[str] = []
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/_common.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/_common.py
index 6c5187916f..57494ac9e8 100644
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/_common.py
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/_common.py
@@ -15,31 +15,39 @@
# specific language governing permissions and limitations
# under the License.
-"""Op-agnostic helpers shared by the three elementwise schedules."""
+"""Shared layout / vec-selection / emit helpers for ``reg.py`` and ``smem.py``.
+
+Borrows directly from ``cuda/copy/reg.py`` (induced partition) and
+``cuda/copy/_common.py`` (synthesized partition), extended to N operands.
+
+The dispatch split mirrors copy:
+ reg.py — all operands in ``local`` → partition induced by anchor's layout
+ smem.py — all operands in ``shared*`` → partition synthesized from ``sctx.intra``
+"""
from __future__ import annotations
import functools
import operator
-from typing import Literal
from tvm.arith.analyzer import Analyzer
from tvm.runtime import DataType
from tvm.script import tirx as Tx
-from tvm.tirx import BufferRegion, TilePrimitiveCall
-from tvm.tirx.layout import TileLayout
-from tvm.tirx.operator.tile_primitive import DispatchContext
+from tvm.tirx import BufferRegion
+from tvm.tirx.layout import Axis, Iter, TileLayout
+
+from ..common import get_indices, get_st_extent
-from ..common import get_indices, get_st_extent, get_vec_len, match_scope
-from ..layout_utils import get_local_region, get_sublayout_from_region, layout_signature, sig_equal
-from .schema import Plan, SrcSpec
+# Re-use copy's primitives (PR-640) — same algorithm, same scope_id machinery.
+from ..copy._common import _TID_AXIS_FOR_SCOPE, _extract_tile, _thread_cnt
+from ..copy.reg import _all_threads_active, _axis_decl, _compute_perm_r
# -----------------------------------------------------------------------------
# Plan helpers
# -----------------------------------------------------------------------------
-def buffer_regions(plan: Plan) -> list[BufferRegion]:
- """All BufferRegion args (dst + buffer-region srcs), in order."""
+def buffer_regions(plan) -> list[BufferRegion]:
+ """All BufferRegion args (dst + buffer-region srcs), in plan order."""
out: list[BufferRegion] = [plan.dst]
for s in plan.srcs:
if s.buf_region is not None:
@@ -47,15 +55,14 @@ def buffer_regions(plan: Plan) -> list[BufferRegion]:
return out
-def compute_dtype_of(plan: Plan) -> str:
- """Pick the dtype used for ops.compute (max bit-width of dst and bufferred srcs)."""
+def compute_dtype_of(plan) -> str:
+ """Widest dtype in bits across dst + buffer/scalar srcs (dst breaks ties)."""
candidates = [plan.dst.buffer.dtype]
for s in plan.srcs:
if s.buf_region is not None:
candidates.append(s.buf_region.buffer.dtype)
elif s.scalar is not None:
candidates.append(s.scalar.dtype)
- # Pick widest in bits; tiebreak: dst dtype first
widest = candidates[0]
widest_bits = DataType(widest).bits
for d in candidates[1:]:
@@ -70,184 +77,310 @@ def n_elements(buf_region: BufferRegion) -> int:
return functools.reduce(operator.mul, ext, 1)
-def is_full_region(buf_region: BufferRegion | None) -> bool:
- """Region covers the whole buffer (start=0, extent=shape)."""
- if buf_region is None:
- return True
- st, ext = get_st_extent(buf_region)
- a = Analyzer()
- return all(a.can_prove_equal(e, s) for e, s in zip(ext, buf_region.buffer.shape)) and all(
- a.can_prove_equal(s, 0) for s in st
- )
-
-
# -----------------------------------------------------------------------------
-# Storage scope predicate (works for any arity)
+# Anchor selection (reg.py)
# -----------------------------------------------------------------------------
-def match_all_scope(
- op_call: TilePrimitiveCall,
- sctx: DispatchContext,
- expected_scope: list[Literal["global", "shared*", "local"]],
-) -> tuple[bool, str | None]:
- """Predicate: dst + every BufferRegion src is in one of expected_scope."""
- from .schema import ALL_OPS # avoid cycle
-
- spec = ALL_OPS.get(op_call.op.name.removeprefix("tirx."))
- if spec is None:
- return False, f"unknown op {op_call.op.name}"
- plan, msg = spec.parse(op_call)
- if msg is not None or plan is None:
- return False, msg
-
- scopes = [plan.dst.buffer.scope()]
- for s in plan.srcs:
- if s.buf_region is not None:
- scopes.append(s.buf_region.buffer.scope())
- ok = any(all(match_scope(sc, want) for sc in scopes) for want in expected_scope)
- if ok:
- return True, None
- return False, f"storage scope mismatch: {scopes}; expected {expected_scope}"
+def pick_anchor(plan) -> BufferRegion:
+ """Anchor is always ``plan.dst`` — every operand must have a layout
+ (enforced by predicate); dst's layout drives iteration. No choice to make.
+ """
+ return plan.dst
# -----------------------------------------------------------------------------
-# Layout/sig checks (used by tile_local and shared validators)
+# Broadcast support (NumPy-style right-aligned, anchor = result shape)
# -----------------------------------------------------------------------------
-def slice_and_sig(buf_region: BufferRegion):
- st, ext = get_st_extent(buf_region)
- sliced = get_sublayout_from_region(buf_region.buffer.layout, buf_region.buffer.shape, st, ext)
- canonical = sliced.canonicalize() if hasattr(sliced, "canonicalize") else sliced
- return st, ext, sliced, layout_signature(canonical)
-
-
-def basic_layout_checks(
- cur: BufferRegion,
- ref: BufferRegion,
- analyzer: Analyzer,
- *,
- disallow_swizzle: bool,
-) -> bool:
- cur_buf, ref_buf = cur.buffer, ref.buffer
- cur_region = [r.extent for r in cur.region]
- ref_region = [r.extent for r in ref.region]
- return (
- len(cur_region) == len(ref_region)
- and all(analyzer.can_prove_equal(r, rr) for r, rr in zip(cur_region, ref_region))
- and (cur_buf.layout is not None and ref_buf.layout is not None)
- and isinstance(cur_buf.layout, TileLayout)
- and isinstance(ref_buf.layout, TileLayout)
- and getattr(cur_buf.layout, "shard", None)
- and getattr(ref_buf.layout, "shard", None)
- and not (disallow_swizzle and (cur_buf.layout.is_swizzle() or ref_buf.layout.is_swizzle()))
- )
-
-
-def sigs_equal(analyzer: Analyzer, *sigs) -> bool:
- """All non-None sigs equal."""
- ref = None
- for s in sigs:
- if s is None:
- continue
- if ref is None:
- ref = s
- continue
- if not sig_equal(analyzer, s, ref):
- return False
- return True
+def _tensor_shape_of(region) -> tuple[int, ...]:
+ """Per-dim region extent (post-slice tensor shape, NOT layout shape).
+
+ Accepts either ``[(start, end), ...]`` pairs (as built locally from a
+ ``BufferRegion``) or the ``BufferRegion.region`` sequence of ``Range``
+ objects directly. ``Range.extent`` is already simplified by the
+ front-end, so we avoid computing ``end - start`` on raw PrimExpr (which
+ yields an un-simplified ``Sub`` and breaks ``int(...)``).
+ """
+ out = []
+ a = Analyzer()
+ for r in region:
+ if hasattr(r, "extent"):
+ ext = r.extent
+ else:
+ start, end = r
+ ext = a.simplify(end - start)
+ out.append(int(ext))
+ return tuple(out)
+
+
+def shape_broadcast_compat(op_shape, anchor_shape) -> tuple[bool, str | None]:
+ """NumPy-style: right-align op against anchor; per-dim extent must equal
+ anchor's or be 1. anchor is the result shape; op broadcasts TO anchor.
+ """
+ pad = len(anchor_shape) - len(op_shape)
+ if pad < 0:
+ return False, f"op rank {len(op_shape)} > anchor rank {len(anchor_shape)}"
+ for d in range(len(op_shape)):
+ e_op = int(op_shape[d])
+ e_a = int(anchor_shape[pad + d])
+ if e_op != e_a and e_op != 1:
+ return False, f"dim {d}: op extent {e_op} vs anchor {e_a} (need equal or 1)"
+ return True, None
+
+
+def _broadcast_lift(op_layout, op_tensor_shape, anchor_tensor_shape):
+ """Lift ``op_layout`` to ``anchor_tensor_shape`` by inserting stride-0
+ iters for padded leading dims and replacing extent-1 buckets with a
+ single stride-0 iter of anchor's extent. Offset and replica list are
+ preserved untouched.
+
+ The lift preserves the physical-address function: new iters have
+ stride 0 so they contribute ``coord * 0 = 0`` to the address
+ regardless of which virtual index is supplied, and dropped extent-1
+ iters contributed ``0 * stride = 0`` already.
+ """
+ pad = len(anchor_tensor_shape) - len(op_tensor_shape)
+ assert pad >= 0, "shape_broadcast_compat should have rejected this"
+
+ try:
+ grouped, seps = op_layout.group(list(op_tensor_shape))
+ except Exception as e: # pylint: disable=broad-except
+ raise ValueError(
+ f"op layout {op_layout} not groupable by tensor shape {op_tensor_shape}: {e}"
+ ) from e
+
+ new_shard: list = []
+ # (1) Padded leading dims — one stride-0 iter each.
+ for d in range(pad):
+ new_shard.append(Iter(int(anchor_tensor_shape[d]), 0, Axis.get("m")))
+ # (2) Aligned dims.
+ for d_op in range(len(op_tensor_shape)):
+ e_op = int(op_tensor_shape[d_op])
+ e_a = int(anchor_tensor_shape[pad + d_op])
+ bucket = list(grouped.shard[seps[d_op] : seps[d_op + 1]])
+ if e_op == e_a:
+ new_shard.extend(bucket)
+ elif e_op == 1:
+ new_shard.append(Iter(e_a, 0, Axis.get("m")))
+ else:
+ raise ValueError(
+ f"dim {d_op}: op extent {e_op} vs anchor {e_a}"
+ " (shape_broadcast_compat should have rejected)"
+ )
+
+ return TileLayout.from_iters(new_shard, grouped.replica, grouped.offset)
# -----------------------------------------------------------------------------
-# vec_len inference (arity-agnostic)
+# Shared preprocess: slice each operand by its region, broadcast-lift to
+# anchor's tensor shape. Output: every operand has a layout whose logical
+# shape equals ``anchor_tensor_shape``. Reg / smem diverge from here.
# -----------------------------------------------------------------------------
-def infer_vec_len(
- op: TilePrimitiveCall, plan: Plan, thread_cnt: int, *, fallback_to_scalar: bool
-) -> int | None:
- """Infer vectorization length common to dst + all buffer-region srcs."""
- explicit = op.config.get("vec_len", None)
- if explicit is not None:
- return explicit
-
- ele_size = DataType(plan.dst.buffer.dtype).bits
- for s in plan.srcs:
- if s.buf_region is not None:
- ele_size = max(ele_size, DataType(s.buf_region.buffer.dtype).bits)
- candidates = [128 // ele_size, 64 // ele_size, 32 // ele_size, 1]
-
- vec = None
- for src in plan.srcs:
- if src.buf_region is None:
- continue
- v = get_vec_len(src.buf_region, plan.dst, candidates, thread_cnt)
- if v is None:
- return 1 if fallback_to_scalar else None
- candidates = [vl for vl in candidates if vl <= v]
- vec = v
- if vec is None:
- # No buffer srcs (scalar-only): use dst against itself
- vec = get_vec_len(plan.dst, plan.dst, candidates, thread_cnt)
- if vec is None and fallback_to_scalar:
- return 1
- return vec
+def preprocess_operand(op_br, anchor_tshape):
+ """Slice ``op_br``'s buffer layout by region (region offset absorbed into
+ layout.offset), then broadcast-lift to ``anchor_tshape`` if shapes differ.
+
+ Raises ``ValueError`` if the lift is not broadcast-compatible (caller
+ should have verified via ``shape_broadcast_compat`` in the predicate).
+ """
+ op_layout = op_br.buffer.layout
+ op_shape = op_br.buffer.shape
+ op_region = [(r.min, r.min + r.extent) for r in op_br.region]
+ sliced = op_layout.slice(list(op_shape), op_region).canonicalize()
+ sliced = _extract_tile(sliced, op_region)
+ op_tshape = _tensor_shape_of(op_br.region)
+ if op_tshape != tuple(anchor_tshape):
+ sliced = _broadcast_lift(sliced, op_tshape, anchor_tshape)
+ return sliced
+
+
+def preprocess_operands(plan):
+ """Shared entry for reg.py and smem.py: returns
+ ``(anchor_tensor_shape, {op_br: sliced_lifted_layout})``.
+
+ Every output layout has logical shape == ``anchor_tensor_shape``.
+ Broadcast iters carry stride 0 with the default mem axis. Reg's induced
+ partition (`align_operands_to_anchor`) and smem's synthesized partition
+ both build on this output.
+ """
+ anchor_tshape = _tensor_shape_of(plan.dst.region)
+ out: dict = {}
+ for br in buffer_regions(plan):
+ out[br] = preprocess_operand(br, anchor_tshape)
+ return anchor_tshape, out
# -----------------------------------------------------------------------------
-# Scope sync / tid expressions
+# Multi-operand layout alignment for reg.py (induced)
# -----------------------------------------------------------------------------
-def emit_scope_sync(scope_kind: str):
- @Tx.inline
- def sync():
- if scope_kind == "cta":
- Tx.cuda.cta_sync()
- elif scope_kind == "warpgroup":
- Tx.cuda.warpgroup_sync(8) # TODO: derive from launch config
- elif scope_kind == "warp":
- Tx.cuda.warp_sync()
- # thread: no sync needed
-
- return sync
+def _align_layouts_no_post_canon(r_layout, r_shape, r_region, s_layout, s_shape, s_region):
+ """Variant of copy ``reg.py:align_layouts_raw`` that omits the final
+ ``canonicalize()`` on ``r_p``.
+
+ Copy's version returns ``r_p = r.permute_dims(perm).canonicalize()`` —
+ that post-permute canonicalize can fuse adjacent iters (e.g. wgmma
+ layout's 5 iters collapse to 2), but ``s_seps`` is built from
+ ``perm`` of length ``len(r.shard) pre-canon``. The two lengths then
+ disagree and ``s_p.shard[s_seps[k]:s_seps[k+1]]`` indexes into the
+ wrong sub-range.
+
+ Dropping the final canonicalize keeps ``r_p.shard`` and ``s_seps`` in
+ 1-to-1 correspondence. Copy's tests don't hit this because R is
+ typically 1D and doesn't fuse further after permute.
+ """
+ r = r_layout.slice(list(r_shape), r_region).canonicalize()
+ s = s_layout.slice(list(s_shape), s_region).canonicalize()
+ s = _extract_tile(s, s_region)
+ # Broadcast lift: when op's post-slice tensor shape != anchor's, expand
+ # s via stride-0 iters so group() below can partition along anchor's
+ # iter structure. Legality must be enforced upstream by the predicate.
+ r_tshape = _tensor_shape_of(r_region)
+ s_tshape = _tensor_shape_of(s_region)
+ if s_tshape != r_tshape:
+ s = _broadcast_lift(s, s_tshape, r_tshape)
+ perm = _compute_perm_r(r)
+ r_shape_for_group = [int(it.extent) for it in r.shard]
+ s_grp, seps = s.group(r_shape_for_group)
+ s_p = s_grp.permute_by_groups(list(seps), perm)
+ r_p = r.permute_dims(perm) # NO post-canonicalize
+ sizes = [seps[i + 1] - seps[i] for i in range(len(seps) - 1)]
+ s_seps = [0]
+ for p in perm:
+ s_seps.append(s_seps[-1] + sizes[p])
+ return r_p, s_p, s_seps
+
+
+def align_operands_to_anchor(anchor_br, layout_others_br):
+ """Align every layout-bearing non-anchor operand to ``anchor_br``.
+
+ Returns ``(anchor_p, per_op_aligned)`` where ``per_op_aligned[op_br] =
+ (op_p, op_seps)``. Trivial-layout operands are NOT included here —
+ caller indexes them directly via their region. Scalar srcs likewise
+ live outside this map.
+
+ Caller must enter ``with sctx.target:`` so ``canonicalize()`` runs the
+ scope-aware fusers (e.g. laneid+wid_in_wg → tid_in_wg).
+
+ Uses ``_align_layouts_no_post_canon`` (not copy's ``align_layouts_raw``
+ directly) so ``anchor_p.shard`` length matches ``op_seps`` groupings.
+ """
+ anchor_layout = anchor_br.buffer.layout
+ anchor_shape = anchor_br.buffer.shape
+ anchor_region = [(r.min, r.min + r.extent) for r in anchor_br.region]
+
+ per_op_aligned: dict = {}
+ anchor_p = None
+ if not layout_others_br:
+ # Just slice + permute anchor alone (no post-canon — keep iters
+ # 1-to-1 with how they'd appear with srcs).
+ r = anchor_layout.slice(list(anchor_shape), anchor_region).canonicalize()
+ perm = _compute_perm_r(r)
+ anchor_p = r.permute_dims(perm)
+ return anchor_p, per_op_aligned
+
+ for op_br in layout_others_br:
+ op_layout = op_br.buffer.layout
+ op_shape = op_br.buffer.shape
+ op_region = [(r.min, r.min + r.extent) for r in op_br.region]
+ r_p, op_p, op_seps = _align_layouts_no_post_canon(
+ anchor_layout,
+ anchor_shape,
+ anchor_region,
+ op_layout,
+ op_shape,
+ op_region,
+ )
+ if anchor_p is None:
+ anchor_p = r_p
+ per_op_aligned[op_br] = (op_p, op_seps)
+ return anchor_p, per_op_aligned
-def tid_in_scope_expr(sctx: DispatchContext, thread_cnt: int):
- """Per-scope tid expression for fused-tid distribution."""
- tx_var = sctx.launch_params["threadIdx.x"].var
- if sctx.scope_kind == "cta":
- return tx_var
- if sctx.scope_kind in ("warp", "warpgroup"):
- return tx_var % thread_cnt
- if sctx.scope_kind == "thread":
- return 0
- return None
+# -----------------------------------------------------------------------------
+# vec_chunk selection
+# -----------------------------------------------------------------------------
+def pick_vec_chunk(spec, op_call, sctx, plan, max_layout_vec_len: int):
+ """Pick widest ``(vec_chunk, vec_impl)`` such that:
+ - ``vec_impl.vec_len`` divides ``max_layout_vec_len`` AND ``vec_impl.applies(...)``
+ - Or no vec_impl matches → scalar fallback ``(max_layout_vec_len, None)``
+
+ ``spec.vec_impls`` is assumed pre-sorted widest-first.
+ """
+ if max_layout_vec_len <= 0:
+ return 1, None
+ for impl in getattr(spec, "vec_impls", []):
+ if impl.vec_len > max_layout_vec_len:
+ continue
+ if max_layout_vec_len % impl.vec_len != 0:
+ continue
+ ok, _ = impl.applies(op_call, sctx, plan)
+ if ok:
+ return impl.vec_len, impl
+ return max_layout_vec_len, None
# -----------------------------------------------------------------------------
-# Per-element source fetch — uniform for buffer/scalar/broadcast srcs.
+# Emit-time helpers
# -----------------------------------------------------------------------------
-def fetch_src_value(src: SrcSpec, fused, dst_indices, dst_start, dst_extent):
- """Build the per-element value expression for one src."""
+def _broadcast_indices(dst_indices, dst_start, dst_extent, op_start, op_ext):
+ """NumPy-style right-aligned broadcast: derive op's per-dim indices from
+ dst's. For matching extents copies dst's coord (rebased); for op_ext[d]
+ == 1 returns the constant start (the only valid index for that dim).
+ """
+ pad = len(dst_extent) - len(op_ext)
+ return [
+ (dst_indices[i + pad] - dst_start[i + pad]) + op_start[i]
+ if int(op_ext[i]) != 1
+ else op_start[i]
+ for i in range(len(op_ext))
+ ]
+
+
+def fetch_src_value(src, fused, dst_indices, dst_start, dst_extent):
+ """Per-element load Expr for one src. Handles buffer / scalar / broadcast srcs."""
if src.is_scalar:
return src.scalar
region = src.buf_region
src_st, src_ext = get_st_extent(region)
if src.index_fn is not None:
idx = src.index_fn(dst_indices, dst_start, dst_extent, src_st, src_ext)
+ elif tuple(int(e) for e in src_ext) != tuple(int(e) for e in dst_extent):
+ # Broadcast — derive src indices from dst's via right-aligned compat.
+ idx = _broadcast_indices(dst_indices, dst_start, dst_extent, src_st, src_ext)
else:
idx = get_indices(fused, src_st, src_ext)
return region.buffer[tuple(idx)]
+def emit_scope_sync(scope_kind: str):
+ """Returns an ``@Tx.inline`` sync helper matched to the exec scope."""
+
+ @Tx.inline
+ def sync():
+ if scope_kind == "cta":
+ Tx.cuda.cta_sync()
+ elif scope_kind == "warpgroup":
+ Tx.cuda.warpgroup_sync(8)
+ elif scope_kind == "warp":
+ Tx.cuda.warp_sync()
+
+ return sync
+
+
__all__ = [
- "Plan",
- "SrcSpec",
- "basic_layout_checks",
+ "_TID_AXIS_FOR_SCOPE",
+ "_all_threads_active",
+ "_axis_decl",
+ "_broadcast_indices",
+ "_tensor_shape_of",
+ "_thread_cnt",
+ "align_operands_to_anchor",
"buffer_regions",
"compute_dtype_of",
"emit_scope_sync",
"fetch_src_value",
- "get_local_region",
- "infer_vec_len",
- "is_full_region",
- "match_all_scope",
"n_elements",
- "sigs_equal",
- "slice_and_sig",
- "tid_in_scope_expr",
+ "pick_anchor",
+ "pick_vec_chunk",
+ "preprocess_operand",
+ "preprocess_operands",
+ "shape_broadcast_compat",
]
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/__init__.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/__init__.py
new file mode 100644
index 0000000000..a552d7ddf3
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/__init__.py
@@ -0,0 +1,121 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Per-op data model + ALL_OPS registry.
+
+``OpSpec`` describes one elementwise op. ``VecImpl`` describes one packed-PTX
+or CUDA-intrinsic emit available for that op (e.g. ``add_f32x2``); a list of
+these (widest-first) lets ``reg.py``/``smem.py`` pick the widest matching
+both the layout and the op's available intrinsics, like copy picks
+``copy_{128,64,32,16,8}b`` based on bit-width and tail contiguity.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any
+
+from tvm.ir.expr import PrimExpr
+from tvm.tirx import BufferRegion, TilePrimitiveCall
+
+
+@dataclass
+class SrcSpec:
+ """One operand of an elementwise op.
+
+ Either a ``BufferRegion`` (per-element load) or a scalar ``PrimExpr``.
+ ``index_fn``, if given, derives per-element indices for broadcasting srcs:
+ ``index_fn(dst_indices, dst_start, dst_extent, src_start, src_extent) -> list[Expr]``
+ Default is the standard ``get_indices`` over the src's own region.
+ """
+
+ buf_region: BufferRegion | None = None
+ scalar: PrimExpr | None = None
+ index_fn: Callable | None = None
+
+ @property
+ def is_scalar(self) -> bool:
+ return self.scalar is not None
+
+ @property
+ def buffer(self):
+ return self.buf_region.buffer if self.buf_region is not None else None
+
+
+@dataclass
+class Plan:
+ """Parsed elementwise op ready for a schedule to consume."""
+
+ dst: BufferRegion
+ srcs: list[SrcSpec]
+ extras: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class VecImpl:
+ """One packed-vector implementation registered for an op.
+
+ Mirrors the ``copy_{Nb}`` menu in copy: each entry says "I can process
+ ``vec_len`` consecutive elements per call". The schedule picks the widest
+ one whose ``vec_len`` divides the layout's contig tail AND whose
+ ``applies()`` returns ``True``.
+ """
+
+ vec_len: int # elements per packed call
+ applies: Callable[[TilePrimitiveCall, Any, Plan], tuple[bool, str | None]]
+ # emit(dst_ptr, src_ptrs, extras) -> Stmt
+ # dst_ptr: typed ptr to ``vec_len`` consecutive dst elements
+ # src_ptrs[i]: typed ptr to ``vec_len`` consecutive src[i] elements,
+ # OR a scalar Expr if src[i].is_scalar.
+ # Runs in Python at @Tx.prim_func build time — branching on src kind is a
+ # normal Python ``if``, not a TVMScript shape limitation. This is what
+ # collapses the old 4x2 shape-explosion in schema.py's factories.
+ emit: Callable
+
+
+@dataclass
+class OpSpec:
+ """Metadata for an elementwise op."""
+
+ name: str
+ # parse(op_call) -> (Plan, msg|None); msg explains why parse failed.
+ parse: Callable[[TilePrimitiveCall], tuple[Plan | None, str | None]]
+ # Scalar compute used by the fallback emit path (wrapped in Tx.vectorized).
+ # compute_scalar(src_vals_at_one_idx, extras, dst_dtype) -> Expr
+ compute_scalar: Callable[[list, dict, str], Any]
+ # Optional dtype check on plan.extras (e.g. unary bias/scale dtype agreement).
+ check_extras: Callable | None = None
+ # Widest-first vec impls. Schedule picks first matching layout+applies.
+ vec_impls: list[VecImpl] = field(default_factory=list)
+
+
+def _build_all_ops() -> dict[str, OpSpec]:
+ """Aggregate per-family op specs. Deferred imports avoid cycles
+ (vec_emit/* imports VecImpl from this module)."""
+ from .binary import BINARY_OPS
+ from .cast import CAST_OPS
+ from .fma import FMA_OPS
+ from .unary import UNARY_OPS
+
+ return {**UNARY_OPS, **BINARY_OPS, **CAST_OPS, **FMA_OPS}
+
+
+ALL_OPS: dict[str, OpSpec] = _build_all_ops()
+
+
+__all__ = ["ALL_OPS", "OpSpec", "Plan", "SrcSpec", "VecImpl"]
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/binary.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/binary.py
new file mode 100644
index 0000000000..38a2a9a894
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/binary.py
@@ -0,0 +1,127 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Binary elementwise ops: add / sub / mul / fdiv.
+
+Includes constant-lhs commute logic. Broadcasting (extent=1 dims) is
+handled at the layout level in dispatch's ``_broadcast_lift``, not here —
+parser just records each src as-is.
+
+``add``/``sub``/``mul`` attach a ``VecImpl`` for sm_100+ packed f32x2;
+``fdiv`` has no packed PTX (uses scalar fallback only).
+"""
+
+from __future__ import annotations
+
+import functools
+import operator
+from typing import Any
+
+from tvm.tirx import BufferRegion, TilePrimitiveCall
+
+from ..vec_emit.binary_f32x2 import BINARY_F32X2_IMPLS
+from . import OpSpec, Plan, SrcSpec
+
+_COMMUTATIVE = frozenset({"add", "mul"})
+
+
+def _parse_binary_for(op_name: str):
+ """Build a ``parse(op_call) -> (Plan, msg)`` for a specific binary op."""
+
+ def parse(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
+ _dst: BufferRegion = op.args[0]
+ _src1 = op.args[1]
+ _src2 = op.args[2]
+
+ s1_scalar = not isinstance(_src1, BufferRegion)
+ s2_scalar = not isinstance(_src2, BufferRegion)
+ if s1_scalar and s2_scalar:
+ return None, "both inputs are constants"
+
+ # Move constant to rhs (commute if allowed; else reject).
+ if s1_scalar:
+ if op_name not in _COMMUTATIVE:
+ return None, f"non-commutative op {op_name} cannot have constant lhs"
+ _src1, _src2 = _src2, _src1
+ s2_scalar = True
+
+ # If rhs is a smaller buffer (broadcast), swap if commutative so the
+ # bigger one is in src1 — keeps src1 == dst convention.
+ if not s2_scalar:
+ s1_n = functools.reduce(operator.mul, [r.extent for r in _src1.region], 1)
+ s2_n = functools.reduce(operator.mul, [r.extent for r in _src2.region], 1)
+ if s1_n < s2_n:
+ if op_name not in _COMMUTATIVE:
+ return None, f"non-commutative op {op_name} cannot swap to broadcast"
+ _src1, _src2 = _src2, _src1
+
+ srcs: list[SrcSpec] = [SrcSpec(buf_region=_src1)]
+ if s2_scalar:
+ srcs.append(SrcSpec(scalar=_src2))
+ else:
+ srcs.append(SrcSpec(buf_region=_src2))
+
+ extras: dict[str, Any] = {}
+ rm = op.config.get("rounding_mode", None)
+ if rm is not None:
+ extras["rounding_mode"] = rm
+ return Plan(dst=_dst, srcs=srcs, extras=extras), None
+
+ return parse
+
+
+def _compute_add(src_vals, extras, dt):
+ return src_vals[0] + src_vals[1]
+
+
+def _compute_sub(src_vals, extras, dt):
+ return src_vals[0] - src_vals[1]
+
+
+def _compute_mul(src_vals, extras, dt):
+ return src_vals[0] * src_vals[1]
+
+
+def _compute_fdiv(src_vals, extras, dt):
+ return src_vals[0] / src_vals[1]
+
+
+BINARY_OPS: dict[str, OpSpec] = {
+ "add": OpSpec(
+ "add",
+ _parse_binary_for("add"),
+ _compute_add,
+ vec_impls=[BINARY_F32X2_IMPLS["add"]],
+ ),
+ "sub": OpSpec(
+ "sub",
+ _parse_binary_for("sub"),
+ _compute_sub,
+ vec_impls=[BINARY_F32X2_IMPLS["sub"]],
+ ),
+ "mul": OpSpec(
+ "mul",
+ _parse_binary_for("mul"),
+ _compute_mul,
+ vec_impls=[BINARY_F32X2_IMPLS["mul"]],
+ ),
+ "fdiv": OpSpec(
+ "fdiv",
+ _parse_binary_for("fdiv"),
+ _compute_fdiv,
+ ),
+}
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/cast.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/cast.py
new file mode 100644
index 0000000000..7ffb0b72ad
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/cast.py
@@ -0,0 +1,45 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Cast op: ``Tx.cast(dst, src)``. Outer ``Tx.cast(..., dst.dtype)`` in the
+schedule handles the scalar conversion; the vec-impl packs pairs via
+CUDA intrinsics like ``__float22half2_rn``."""
+
+from __future__ import annotations
+
+from tvm.tirx import BufferRegion, TilePrimitiveCall
+
+from ..vec_emit.cast_vec2 import CAST_VEC2_IMPL
+from . import OpSpec, Plan, SrcSpec
+
+
+def _parse_cast(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
+ _dst: BufferRegion = op.args[0]
+ _src = op.args[1]
+ if not isinstance(_src, BufferRegion):
+ return None, "cast src must be a buffer region"
+ return Plan(dst=_dst, srcs=[SrcSpec(buf_region=_src)], extras={}), None
+
+
+def _compute_cast(src_vals, extras, dt):
+ # Schedule wraps with Tx.cast(..., dst.dtype) — just pass through.
+ return src_vals[0]
+
+
+CAST_OPS: dict[str, OpSpec] = {
+ "cast": OpSpec("cast", _parse_cast, _compute_cast, vec_impls=[CAST_VEC2_IMPL]),
+}
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/fma.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/fma.py
new file mode 100644
index 0000000000..5b057f9cdd
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/fma.py
@@ -0,0 +1,50 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""FMA op: ``Tx.fma(dst, a, b, c)`` → ``dst = a*b + c``.
+
+Attaches ``fma_f32x2`` VecImpl for sm_100+ f32; falls back to scalar
+``a*b + c`` otherwise.
+"""
+
+from __future__ import annotations
+
+from tvm.tirx import BufferRegion, TilePrimitiveCall
+
+from ..vec_emit.fma_f32x2 import FMA_F32X2_IMPL
+from . import OpSpec, Plan, SrcSpec
+
+
+def _parse_fma(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
+ _dst: BufferRegion = op.args[0]
+ args = op.args[1:4]
+ srcs: list[SrcSpec] = []
+ for a in args:
+ if isinstance(a, BufferRegion):
+ srcs.append(SrcSpec(buf_region=a))
+ else:
+ srcs.append(SrcSpec(scalar=a))
+ return Plan(dst=_dst, srcs=srcs, extras={}), None
+
+
+def _compute_fma(src_vals, extras, dt):
+ return src_vals[0] * src_vals[1] + src_vals[2]
+
+
+FMA_OPS: dict[str, OpSpec] = {
+ "fma": OpSpec("fma", _parse_fma, _compute_fma, vec_impls=[FMA_F32X2_IMPL]),
+}
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/unary.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/unary.py
new file mode 100644
index 0000000000..b81f1a0780
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/ops/unary.py
@@ -0,0 +1,117 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Unary elementwise ops: zero / fill / reciprocal / sqrt / exp / exp2 / silu.
+
+All carry the same ``Tx.<unary>(dst, src[, bias, scale])`` shape (bias / scale
+optional; ``silu`` ignores bias/scale to preserve legacy behavior).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from tvm.ir.expr import PrimExpr
+from tvm.script import tirx as Tx
+from tvm.tirx import BufferRegion, TilePrimitiveCall
+from tvm.tirx.expr import FloatImm
+
+from . import OpSpec, Plan, SrcSpec
+
+
+def _parse_unary(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
+ """Tx.<unary>(dst, src[, bias, scale]) → Plan."""
+ _dst: BufferRegion = op.args[0]
+ _src = op.args[1]
+ _bias = op.args[2] if len(op.args) > 2 else None
+ _scale = op.args[3] if len(op.args) > 2 else None
+
+ srcs: list[SrcSpec] = []
+ if isinstance(_src, BufferRegion):
+ srcs.append(SrcSpec(buf_region=_src))
+ elif isinstance(_src, PrimExpr):
+ srcs.append(SrcSpec(scalar=_src))
+ else:
+ return None, f"unsupported src type {type(_src).__name__}"
+
+ extras: dict[str, Any] = {
+ "scale": _scale,
+ "bias_const": _bias if isinstance(_bias, FloatImm) else None,
+ }
+ if isinstance(_bias, BufferRegion):
+ srcs.append(SrcSpec(buf_region=_bias))
+ extras["has_bias_buf"] = True
+ else:
+ extras["has_bias_buf"] = False
+ return Plan(dst=_dst, srcs=srcs, extras=extras), None
+
+
+def _check_unary_extras(extras: dict, compute_dtype: str) -> tuple[bool, str | None]:
+ scale = extras.get("scale")
+ if scale is not None and scale.dtype != compute_dtype:
+ return False, f"scale dtype {scale.dtype} != compute dtype {compute_dtype}"
+ bias_const = extras.get("bias_const")
+ if bias_const is not None and bias_const.dtype != compute_dtype:
+ return False, f"bias_const dtype {bias_const.dtype} != compute dtype {compute_dtype}"
+ return True, None
+
+
+def _with_bias_scale(raw_op):
+ """Wrap ``raw_op`` (e.g. ``Tx.exp``) into a compute that applies bias/scale first."""
+
+ def compute(src_vals, extras, dt):
+ x = src_vals[0]
+ scale = extras.get("scale")
+ if scale is not None:
+ x = x * scale
+ if extras.get("has_bias_buf"):
+ x = x + src_vals[1]
+ elif extras.get("bias_const") is not None:
+ x = x + extras["bias_const"]
+ return raw_op(x)
+
+ return compute
+
+
+def _compute_zero(src_vals, extras, dt):
+ return 0.0
+
+
+def _compute_fill(src_vals, extras, dt):
+ return src_vals[0]
+
+
+def _compute_reciprocal(src_vals, extras, dt):
+ x = src_vals[0]
+ return Tx.FloatImm(x.dtype, 1.0) / x
+
+
+def _compute_silu(src_vals, extras, dt):
+ # Legacy: silu doesn't apply bias/scale.
+ x = src_vals[0]
+ return x / (Tx.FloatImm(x.dtype, 1.0) + Tx.exp(Tx.FloatImm(x.dtype, 0.0) - x))
+
+
+UNARY_OPS: dict[str, OpSpec] = {
+ "zero": OpSpec("zero", _parse_unary, _compute_zero, _check_unary_extras),
+ "fill": OpSpec("fill", _parse_unary, _compute_fill, _check_unary_extras),
+ "reciprocal": OpSpec("reciprocal", _parse_unary, _compute_reciprocal, _check_unary_extras),
+ "sqrt": OpSpec("sqrt", _parse_unary, _with_bias_scale(Tx.sqrt), _check_unary_extras),
+ "exp": OpSpec("exp", _parse_unary, _with_bias_scale(Tx.exp), _check_unary_extras),
+ "exp2": OpSpec("exp2", _parse_unary, _with_bias_scale(Tx.exp2), _check_unary_extras),
+ "silu": OpSpec("silu", _parse_unary, _compute_silu, _check_unary_extras),
+}
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/reg.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/reg.py
new file mode 100644
index 0000000000..edeeb2582f
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/reg.py
@@ -0,0 +1,362 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Elementwise dispatch when all operands live in ``local`` (registers).
+
+Mirrors ``cuda/copy/reg.py``: the partition is *induced* by the layout that
+carries thread-axis info (the "anchor" operand). The region slice is absorbed
+into the sliced layout up front via ``align_operands_to_anchor`` — emit
+operates on a flat 1D per-thread view and indexes it with a scalar offset, so
+codegen never sees multi-dim ``get_indices`` inside ``Tx.vectorized``.
+
+Two paths inside emit:
+ * induced (anchor exists) — atom-based, exactly mirrors copy reg.py
+ * trivial (no anchor) — flat full region, every thread runs the full
+ loop on its private storage
+"""
+
+from __future__ import annotations
+
+import functools
+import operator
+
+from tvm.arith import Analyzer
+from tvm.script import tirx as Tx
+from tvm.tirx import PrimFunc, TilePrimitiveCall
+from tvm.tirx.layout import TileLayout
+from tvm.tirx.operator.tile_primitive import DispatchContext
+from tvm.tirx.operator.tile_primitive.dispatcher import fail
+
+from ..common import get_st_extent
+from ..copy._common import _carve_tail, _verify_s_tail_contig
+from ..layout_utils import get_sublayout_from_region, layout_signature
+from ._common import (
+ _all_threads_active,
+ _tensor_shape_of,
+ align_operands_to_anchor,
+ buffer_regions,
+ compute_dtype_of,
+ pick_anchor,
+ shape_broadcast_compat,
+)
+
+
+# -----------------------------------------------------------------------------
+# Predicate
+# -----------------------------------------------------------------------------
+def _validate_anchor_layout(anchor_br) -> tuple[bool, str | None]:
+ layout = anchor_br.buffer.layout
+ if layout.is_swizzle():
+ return False, "anchor layout is swizzle"
+ if not isinstance(layout, TileLayout):
+ return False, f"anchor layout is {type(layout).__name__}, not TileLayout"
+ return True, None
+
+
+def _check_layout_operands_agree(plan) -> tuple[bool, str | None]:
+ """Replica sigs must match across non-trivial-layout operands.
+
+ ``align_operands_to_anchor`` normalizes thread + local parts via
+ permute/group, but the replica part isn't touched by alignment — if
+ operands disagree there, alignment can't fix it and emit will be wrong.
+ Thread / local mismatches that alignment can't resolve will raise
+ cleanly at align time, so we don't pre-check them.
+ """
+ # All operands have a layout (predicate already enforced this); just
+ # iterate them all.
+ layout_brs = list(buffer_regions(plan))
+ if len(layout_brs) < 2:
+ return True, None
+ analyzer = Analyzer()
+ replica_sigs = []
+ for br in layout_brs:
+ st, ext = get_st_extent(br)
+ sliced = get_sublayout_from_region(br.buffer.layout, br.buffer.shape, st, ext)
+ canon = sliced.canonicalize() if hasattr(sliced, "canonicalize") else sliced
+ sig = layout_signature(canon)
+ if sig is None:
+ return False, "layout has no signature (not a TileLayout?)"
+ # layout_signature returns (thread_sig, local_sig, replica_sig)
+ replica_sigs.append(sig[2])
+ for s in replica_sigs[1:]:
+ # Compare replica entries (axis_key, extent, stride) element-wise.
+ if len(s) != len(replica_sigs[0]):
+ return False, "replica sig mismatch (different number of replica iters)"
+ for (k_a, e_a, st_a), (k_b, e_b, st_b) in zip(replica_sigs[0], s):
+ if k_a != k_b:
+ return False, "replica sig mismatch (axis key)"
+ if not analyzer.can_prove_equal(e_a, e_b):
+ return False, "replica sig mismatch (extent)"
+ if not analyzer.can_prove_equal(st_a, st_b):
+ return False, "replica sig mismatch (stride)"
+ return True, None
+
+
+def is_reg_ewise(spec):
+ """Predicate factory: dispatch accepted iff all operands in ``local`` scope."""
+
+ def check(op_call: TilePrimitiveCall, sctx: DispatchContext) -> tuple[bool, str | None]:
+ if not sctx.is_cuda:
+ return False, "non-cuda target"
+ if sctx.scope_kind not in ("thread", "warp", "warpgroup", "cta"):
+ return False, f"unsupported scope {sctx.scope_kind}"
+ ok, reason = _all_threads_active(sctx)
+ if not ok:
+ return False, reason
+ plan, msg = spec.parse(op_call)
+ if msg is not None or plan is None:
+ return False, msg
+ for br in buffer_regions(plan):
+ if br.buffer.scope() != "local":
+ return False, f"operand scope {br.buffer.scope()} != local"
+ if br.buffer.layout is None:
+ return False, f"operand {br} has no layout"
+ if spec.check_extras is not None:
+ ok2, reason2 = spec.check_extras(plan.extras, compute_dtype_of(plan))
+ if not ok2:
+ return False, reason2
+ anchor = pick_anchor(plan)
+ ok3, reason3 = _validate_anchor_layout(anchor)
+ if not ok3:
+ return False, reason3
+ # Shape compat (NumPy-style broadcast): anchor's tensor shape is the
+ # result shape; every operand must broadcast TO anchor.
+ anchor_tshape = _tensor_shape_of(anchor.region)
+ for br in buffer_regions(plan):
+ if br is anchor:
+ continue
+ op_tshape = _tensor_shape_of(br.region)
+ ok_b, reason_b = shape_broadcast_compat(op_tshape, anchor_tshape)
+ if not ok_b:
+ return False, f"shape incompat: {reason_b}"
+ ok4, reason4 = _check_layout_operands_agree(plan)
+ if not ok4:
+ return False, reason4
+ return True, None
+
+ return check
+
+
+# -----------------------------------------------------------------------------
+# Shared helpers
+# -----------------------------------------------------------------------------
+def _prod(it) -> int:
+ return functools.reduce(operator.mul, it, 1)
+
+
+# -----------------------------------------------------------------------------
+# Main entry
+# -----------------------------------------------------------------------------
+def emit_reg(op_call: TilePrimitiveCall, spec, sctx: DispatchContext) -> PrimFunc:
+ plan, msg = spec.parse(op_call)
+ if msg is not None or plan is None:
+ fail(msg or "parse failed")
+ return _emit_induced(plan, spec, sctx, op_call, pick_anchor(plan))
+
+
+# -----------------------------------------------------------------------------
+# Induced path — anchor with non-trivial layout drives partition
+# -----------------------------------------------------------------------------
+def _strip_thread(layout):
+ """Return a new TileLayout with thread iters removed from shard."""
+ mem_iters = [it for it in layout.shard if not it.axis.is_thread()]
+ return TileLayout.from_iters(mem_iters, list(layout.replica), dict(layout.offset))
+
+
+def _pick_vec_and_carve(spec, op_call, sctx, plan, per_op_mem_layouts):
+ """Pick ``(vec_len, vec_impl, carved_layouts)``.
+
+ Enumerate ``spec.vec_impls`` widest-first. For each candidate ``vec_len``:
+ 1. Try ``_carve_tail`` on each operand's mem-only layout (may split a
+ boundary iter so the tail product equals ``vec_len``).
+ 2. Verify the carved tail is physically contiguous (stride-1 chain whose
+ product equals ``vec_len``).
+ 3. Call ``impl.applies(op_call, sctx, plan)``.
+ First candidate that passes all three on EVERY operand wins. Otherwise
+ fall back to scalar: ``vec_len=1``, ``vec_impl=None``, original (uncarved)
+ layouts.
+ """
+ impls = sorted(getattr(spec, "vec_impls", []), key=lambda i: -i.vec_len)
+ for impl in impls:
+ cand = impl.vec_len
+ carved_try = {}
+ all_ok = True
+ for op_br, layout in per_op_mem_layouts.items():
+ new_iters = _carve_tail(list(layout.shard), cand)
+ if new_iters is None:
+ all_ok = False
+ break
+ new_layout = TileLayout.from_iters(
+ new_iters, list(layout.replica), dict(layout.offset)
+ )
+ if not _verify_s_tail_contig(new_layout, cand):
+ all_ok = False
+ break
+ carved_try[op_br] = new_layout
+ if not all_ok:
+ continue
+ ok, _ = impl.applies(op_call, sctx, plan)
+ if not ok:
+ continue
+ return cand, impl, carved_try
+ # Scalar fallback — use uncarved mem layouts as-is.
+ return 1, None, dict(per_op_mem_layouts)
+
+
+def _emit_induced(plan, spec, sctx, op_call, anchor_br) -> PrimFunc:
+ # Every buffer-region operand has a layout (enforced by predicate);
+ # trivial / identity layouts are fine — the algorithm is robust to
+ # layouts with no thread axes (strip is no-op, placeholders empty).
+ layout_others = [br for br in buffer_regions(plan) if br is not anchor_br]
+
+ # Step 1: slice + permute (region offset absorbed into op_p.offset; per-iter
+ # strides reflect post-slice physical addressing). No (st, ext) leaks out.
+ with sctx.target:
+ anchor_p, per_op_aligned = align_operands_to_anchor(anchor_br, layout_others)
+
+ # Step 2: post-align thread-equality check. ``align`` is supposed to
+ # normalize the thread part; we verify it did. (Replica was pre-checked
+ # in the predicate.)
+ def _thread_iters(layout):
+ c = layout.canonicalize()
+ return [(it.axis, int(it.extent), int(it.stride)) for it in c.shard if it.axis.is_thread()]
+
+ anchor_thread = _thread_iters(anchor_p)
+ for op_br, (op_p, _) in per_op_aligned.items():
+ if _thread_iters(op_p) != anchor_thread:
+ fail("thread part mismatch between anchor and operand after alignment")
+
+ # Step 3: drop thread iters; from here on operands have mem-only layouts.
+ per_op_mem = {anchor_br: _strip_thread(anchor_p)}
+ for op_br, (op_p, _) in per_op_aligned.items():
+ per_op_mem[op_br] = _strip_thread(op_p)
+
+ # Step 4: enumerate spec.vec_impls widest-first; try carve tail for each
+ # operand. First candidate that all operands can carve + impl.applies wins.
+ # Otherwise scalar fallback (vec=1, no inner loop).
+ vec_len, vec_impl, per_op_carved = _pick_vec_and_carve(
+ spec, op_call, sctx, plan, per_op_mem
+ )
+
+ # Step 5: totals + emit. per_thread_total = ∏ extents of (carved) mem
+ # layout. All operands have the same per_thread_total (alignment invariant).
+ per_thread_total = _prod(int(it.extent) for it in per_op_carved[anchor_br].shard)
+ outer_total = per_thread_total // vec_len if vec_len > 0 else per_thread_total
+
+ if vec_impl is not None:
+ result = _emit_induced_packed(
+ plan, vec_impl, vec_len, outer_total, per_thread_total,
+ per_op_carved, anchor_br,
+ )
+ else:
+ result = _emit_induced_scalar(
+ plan, spec, outer_total, per_thread_total, per_op_carved, anchor_br,
+ )
+
+ return result
+
+
+def _make_views_meta(per_op_carved, per_thread_total):
+ """Build the per-operand 1D buffer view dict.
+
+ Each view aliases the operand's physical storage as a 1D shape of
+ ``per_thread_total`` elements, with layout = the operand's carved mem-only
+ TileLayout. Scalar indexing into the view goes through this layout's
+ iter strides at codegen time.
+ """
+ return {
+ op_br: Tx.decl_buffer(
+ (per_thread_total,),
+ op_br.buffer.dtype,
+ op_br.buffer.data,
+ scope="local",
+ layout=per_op_carved[op_br],
+ )
+ for op_br in per_op_carved
+ }
+
+
+# -----------------------------------------------------------------------------
+# Emit — packed (one PTX/CUDA call per outer chunk; no Tx.vectorized inside)
+# -----------------------------------------------------------------------------
+def _emit_induced_packed(plan, vec_impl, vec_len, outer_total, per_thread_total,
+ per_op_carved, anchor_br) -> PrimFunc:
+ extras = plan.extras
+ srcs = plan.srcs
+ dst_br = plan.dst
+
+ @Tx.prim_func(check_well_formed=False)
+ def impl():
+ views = Tx.meta_var(_make_views_meta(per_op_carved, per_thread_total))
+ # Serial loop (not Tx.unroll): Tx.unroll materializes each per-iter
+ # ``dst_lane_indices`` / ``src_args`` buffer as a fresh int[1]
+ # declaration, multiplying by outer_total. ptxas unrolls the
+ # static-bound loop without that scratch explosion.
+ for f in range(outer_total):
+ # Pass logical 1D coord; each buffer's own layout maps it to
+ # physical at access time (handles wgmma, broadcast, etc.).
+ dst_lane_indices = [[f * vec_len + k] for k in range(vec_len)]
+ src_args = Tx.meta_var(
+ [
+ src.scalar
+ if src.is_scalar
+ else (
+ views[src.buf_region],
+ [[f * vec_len + k] for k in range(vec_len)],
+ )
+ for src in srcs
+ ]
+ )
+ Tx.evaluate(vec_impl.emit(views[dst_br], dst_lane_indices, src_args, extras))
+
+ return impl
+
+
+# -----------------------------------------------------------------------------
+# Emit — scalar fallback (vec_len = 1; one element per outer iter; no
+# Tx.vectorized inside, so no codegen vec-packing of multi-dim indices).
+# -----------------------------------------------------------------------------
+def _emit_induced_scalar(plan, spec, outer_total, per_thread_total,
+ per_op_carved, anchor_br) -> PrimFunc:
+ extras = plan.extras
+ srcs = plan.srcs
+ dst_br = plan.dst
+ dst_dtype = dst_br.buffer.dtype
+ compute = spec.compute_scalar
+
+ @Tx.prim_func(check_well_formed=False)
+ def impl():
+ views = Tx.meta_var(_make_views_meta(per_op_carved, per_thread_total))
+ # Serial loop (not Tx.unroll) — see _emit_induced_packed for why.
+ for f in range(outer_total):
+ # Logical 1D coord = f (vec_len = 1 in scalar path); each
+ # buffer's layout maps to physical at access time.
+ src_vals = Tx.meta_var(
+ [
+ src.scalar
+ if src.is_scalar
+ else views[src.buf_region][f]
+ for src in srcs
+ ]
+ )
+ views[dst_br][f] = Tx.cast(
+ compute(src_vals, extras, dst_dtype), dst_dtype
+ )
+
+ return impl
+
+
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/register.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/register.py
index 91e85916b6..56e041851a 100644
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/register.py
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/register.py
@@ -15,70 +15,47 @@
# specific language governing permissions and limitations
# under the License.
-"""Register every elementwise op x 3 schedules.
+"""Register each op in ``ALL_OPS`` for both dispatch variants (``reg``, ``smem``).
-Loops over ``ALL_OPS`` once; no per-arity buckets, no per-op code.
+Mirrors copy PR-640's two-variant model: scope-pair drives the dispatch
+selection, the underlying algorithm (induced vs synthesized) follows.
"""
from tvm.tirx import PrimFunc, TilePrimitiveCall
from tvm.tirx.operator.tile_primitive import DispatchContext, predicate, register_dispatch
-from ._common import match_all_scope
-from .schedule_collective_reg import emit_tile_local, validate_tile_local
-from .schedule_collective_smem import emit_shared, validate_shared
-from .schedule_thread import emit_per_thread, validate_per_thread
-from .schema import ALL_OPS, OpSpec
+from .ops import ALL_OPS
+from .reg import emit_reg, is_reg_ewise
+from .smem import emit_smem, is_smem_ewise
-def _register_per_thread(spec: OpSpec) -> None:
+def _register_reg(spec) -> None:
@register_dispatch(
spec.name,
"cuda",
- variant="per_thread",
+ variant="reg",
priority=10,
- when=[
- predicate("storage_scope", match_all_scope, expected_scope=["local"]),
- predicate("per_thread_valid", validate_per_thread(spec)),
- ],
+ when=[predicate(f"{spec.name}_reg", is_reg_ewise(spec))],
)
def _dispatch(op: TilePrimitiveCall, sctx: DispatchContext, _spec=spec) -> PrimFunc:
- return emit_per_thread(op, _spec, sctx)
+ return emit_reg(op, _spec, sctx)
-def _register_tile_local(spec: OpSpec) -> None:
+def _register_smem(spec) -> None:
@register_dispatch(
spec.name,
"cuda",
- variant="tile_local",
+ variant="smem",
priority=10,
- when=[
- predicate("storage_scope", match_all_scope, expected_scope=["local"]),
- predicate("tile_local_valid", validate_tile_local(spec)),
- ],
+ when=[predicate(f"{spec.name}_smem", is_smem_ewise(spec))],
)
def _dispatch(op: TilePrimitiveCall, sctx: DispatchContext, _spec=spec) -> PrimFunc:
- return emit_tile_local(op, _spec, sctx)
-
-
-def _register_shared(spec: OpSpec) -> None:
- @register_dispatch(
- spec.name,
- "cuda",
- variant="shared_distributed",
- priority=10,
- when=[
- predicate("storage_scope", match_all_scope, expected_scope=["shared*"]),
- predicate("shared_valid", validate_shared(spec)),
- ],
- )
- def _dispatch(op: TilePrimitiveCall, sctx: DispatchContext, _spec=spec) -> PrimFunc:
- return emit_shared(op, _spec, sctx)
+ return emit_smem(op, _spec, sctx)
for _spec in ALL_OPS.values():
- _register_per_thread(_spec)
- _register_tile_local(_spec)
- _register_shared(_spec)
+ _register_reg(_spec)
+ _register_smem(_spec)
__all__: list[str] = []
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_collective_reg.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_collective_reg.py
deleted file mode 100644
index 42719cd953..0000000000
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_collective_reg.py
+++ /dev/null
@@ -1,410 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-"""Schedule B: tile-local collective (scope > thread + local buffer + layout).
-
-Generic over arity — iterates ``plan.srcs``. Two sub-paths:
-
- full : every buffer-region covers its full buffer; flatten via
- ``decl_buffer((local_total,), ...)`` and iterate the linear index.
- sliced : at least one region is partial; ``buf.local(*shape)`` per buffer
- + multi-dim get_indices per element.
-"""
-
-from __future__ import annotations
-
-import functools
-import operator
-
-from tvm.arith.analyzer import Analyzer
-from tvm.runtime import DataType
-from tvm.script import tirx as Tx
-from tvm.tirx import PrimFunc, TilePrimitiveCall
-from tvm.tirx.operator.tile_primitive import DispatchContext, fail
-
-from ..common import get_indices, get_st_extent, get_thread_cnt
-from ..layout_utils import get_local_region
-from ._common import (
- basic_layout_checks,
- buffer_regions,
- compute_dtype_of,
- infer_vec_len,
- is_full_region,
- sigs_equal,
- slice_and_sig,
-)
-from .schema import OpSpec
-
-
-def validate_tile_local(spec: OpSpec):
- """Predicate factory: scope in {warp,warpgroup,cta}; all bufs local + layout; sig match."""
-
- def _check(op: TilePrimitiveCall, sctx: DispatchContext) -> tuple[bool, str | None]:
- if sctx.scope_kind not in ["warp", "warpgroup", "cta"]:
- return False, f"tile_local requires warp/warpgroup/cta, got {sctx.scope_kind}"
- plan, msg = spec.parse(op)
- if msg is not None or plan is None:
- return False, msg
-
- if plan.dst.buffer.scope() != "local":
- return False, f"dst scope must be local, got {plan.dst.buffer.scope()}"
- for s in plan.srcs:
- if s.buf_region is None:
- continue
- buf = s.buf_region.buffer
- if buf.scope() != "local":
- return False, "src buffer must be in local scope"
-
- # tile_local handles three sub-shapes depending on layouts:
- # (a) all dst + buffer-srcs carry NON-trivial layouts -> shape/sig must match
- # (b) some buf has trivial (flat thread-private) layout while others have
- # non-trivial collective layouts -> thread-asymmetric view, e.g.
- # GEMM epilogue cast `dst_flat[no*8:no*8+8] = cast(src_wg[128, 8])`.
- # We accept both; the emit function picks the right view per buf.
- def _is_nontrivial(buf):
- return buf.layout is not None and not buf.layout.is_trivial()
-
- any_nontrivial = _is_nontrivial(plan.dst.buffer) or any(
- s.buf_region is not None and _is_nontrivial(s.buf_region.buffer) for s in plan.srcs
- )
- if not any_nontrivial:
- return False, "tile_local requires at least one buf with non-trivial layout"
-
- if spec.check_extras is not None:
- ok, why = spec.check_extras(plan.extras, compute_dtype_of(plan))
- if not ok:
- return False, why
-
- a = Analyzer()
- # Only enforce shape/sig equality across the buffers with NON-trivial layouts.
- # Trivially-laid-out (flat thread-private) buffers are validated separately.
- if _is_nontrivial(plan.dst.buffer):
- for s in plan.srcs:
- if (
- s.buf_region is None
- or s.index_fn is not None
- or not _is_nontrivial(s.buf_region.buffer)
- ):
- continue
- if not basic_layout_checks(s.buf_region, plan.dst, a, disallow_swizzle=True):
- return False, "shape/layout mismatch between src and dst"
-
- # Region-level layout constraints — only on bufs with non-trivial layouts.
- for br in buffer_regions(plan):
- if not _is_nontrivial(br.buffer):
- continue
- st, ext = get_st_extent(br)
- layout = br.buffer.layout
- for it in layout.shard:
- if it.axis.is_thread() and a.can_prove_equal(it.stride, 0):
- return False, "thread axis with zero stride unsupported"
- replica = getattr(layout, "replica", None) or []
- if any(it.axis.is_thread() for it in replica):
- return False, "thread axis in replica unsupported"
- if get_local_region(layout, br.buffer.shape, st, ext) is None:
- return False, "invalid region for tile_local"
-
- # Layout signatures must agree across all bufs with non-trivial layouts.
- sigs = []
- if _is_nontrivial(plan.dst.buffer):
- sigs.append(slice_and_sig(plan.dst)[3])
- for s in plan.srcs:
- if (
- s.buf_region is not None
- and _is_nontrivial(s.buf_region.buffer)
- and s.index_fn is None
- ):
- sigs.append(slice_and_sig(s.buf_region)[3])
- if not sigs_equal(a, *sigs):
- return False, "layout signature mismatch"
-
- # Launch-thread consistency: pick any buf with non-trivial layout as anchor.
- anchor_br = (
- plan.dst
- if _is_nontrivial(plan.dst.buffer)
- else next(
- s.buf_region
- for s in plan.srcs
- if s.buf_region is not None and _is_nontrivial(s.buf_region.buffer)
- )
- )
- _, _, anchor_sliced, _ = slice_and_sig(anchor_br)
- thr_extents = [it.extent for it in anchor_sliced.shard if it.axis.is_thread()]
- expected = functools.reduce(operator.mul, thr_extents, 1)
- actual = get_thread_cnt(sctx)
- if thr_extents and not a.can_prove_equal(expected, actual):
- return False, f"thread count mismatch: expected {expected} got {actual}"
- return True, None
-
- return _check
-
-
-def emit_tile_local(op_call: TilePrimitiveCall, spec: OpSpec, sctx: DispatchContext) -> PrimFunc:
- plan, msg = spec.parse(op_call)
- if msg is not None or plan is None:
- fail(msg or "parse failed")
-
- # Try vector intrinsic emit first (e.g. packed_f32x2 for sm100 f32 op).
- if spec.vec_emit_factory is not None:
- impl = spec.vec_emit_factory(op_call, plan, sctx, vec_len=2)
- if impl is not None:
- return impl
-
- # If any buffer lacks layout, we can't use the fast "full" flat path
- # uniformly — fall through to sliced which handles per-buf views.
- has_flat_buf = (plan.dst.buffer.layout is None or plan.dst.buffer.layout.is_trivial()) or any(
- s.buf_region is not None
- and (s.buf_region.buffer.layout is None or s.buf_region.buffer.layout.is_trivial())
- for s in plan.srcs
- )
- full = (
- not has_flat_buf
- and is_full_region(plan.dst)
- and all(s.buf_region is None or is_full_region(s.buf_region) for s in plan.srcs)
- )
- if full:
- return _emit_full(op_call, spec, plan)
- return _emit_sliced(op_call, spec, sctx, plan)
-
-
-# -----------------------------------------------------------------------------
-# Full-region: flatten each local buffer to (local_total,) and iterate linear idx.
-# -----------------------------------------------------------------------------
-def _emit_full(op_call: TilePrimitiveCall, spec, plan) -> PrimFunc:
- dst = plan.dst.buffer
- dst_st, dst_ext = get_st_extent(plan.dst)
- dst_info = get_local_region(dst.layout, list(dst.shape), dst_st, dst_ext)
- if not dst_info:
- fail("dst layout not supported for tile_local (full)")
- _, _, dst_local_ext = dst_info
- local_total = functools.reduce(operator.mul, dst_local_ext, 1)
-
- # vec_len: use op_call.config or infer from local_total alignment.
- vec_len = op_call.config.get("vec_len", None)
- if vec_len is None:
- a = Analyzer()
- ele = DataType(dst.dtype).bits
- for s in plan.srcs:
- if s.buf_region is not None:
- ele = max(ele, DataType(s.buf_region.buffer.dtype).bits)
- for v in [128 // ele, 64 // ele, 32 // ele, 1]:
- if v > 0 and a.can_prove_equal(local_total % v, 0):
- vec_len = v
- break
- assert vec_len is not None
-
- compute = spec.compute
- extras = plan.extras
- srcs = plan.srcs
-
- # Pre-extract the underlying buffers for buffer-region srcs (None for scalars).
- src_buffers = [s.buf_region.buffer if not s.is_scalar else None for s in srcs]
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- base_dst = Tx.decl_buffer((local_total,), dst.dtype, dst.data, scope=dst.scope())
- # Hoist one flat decl per buffer src.
- bases = Tx.meta_var(
- [
- None
- if b is None
- else Tx.decl_buffer((local_total,), b.dtype, b.data, scope=b.scope())
- for b in src_buffers
- ]
- )
- for s in Tx.serial(0, local_total // vec_len):
- for vec in Tx.vectorized(vec_len):
- idx = Tx.meta_var(s * vec_len + vec)
- src_vals = Tx.meta_var(
- [
- src.scalar if src.is_scalar else bases[i][idx]
- for i, src in enumerate(srcs)
- ]
- )
- base_dst[idx] = Tx.cast(compute(src_vals, extras, dst.dtype), dst.dtype)
-
- return impl
-
-
-# -----------------------------------------------------------------------------
-# Sliced-region: buf.local(*shape) per buffer + multi-dim index decomp.
-# -----------------------------------------------------------------------------
-def _emit_sliced(op_call: TilePrimitiveCall, spec, sctx: DispatchContext, plan) -> PrimFunc:
- thread_cnt = get_thread_cnt(sctx)
- assert thread_cnt is not None
-
- dst = plan.dst.buffer
- dst_st, dst_ext = get_st_extent(plan.dst)
-
- # Pick an anchor buf (the one with layout) to determine per-thread element count.
- if dst.layout is not None and not dst.layout.is_trivial():
- anchor_info = get_local_region(dst.layout, list(dst.shape), dst_st, dst_ext)
- if not anchor_info:
- fail("dst layout not supported for tile_local (sliced)")
- else:
- anchor_info = None
- for src in plan.srcs:
- if src.buf_region is not None and src.buf_region.buffer.layout is not None:
- b = src.buf_region.buffer
- st, ext = get_st_extent(src.buf_region)
- anchor_info = get_local_region(b.layout, b.shape, st, ext)
- if anchor_info is not None:
- break
- if anchor_info is None:
- fail("no anchor with valid layout for tile_local (sliced)")
- _, _, anchor_local_ext = anchor_info
- local_total = functools.reduce(operator.mul, anchor_local_ext, 1)
-
- vec_len = infer_vec_len(op_call, plan, thread_cnt=thread_cnt, fallback_to_scalar=True)
- if vec_len is None:
- fail("could not infer vec_len for tile_local (sliced)")
-
- # Per-buf access info: ("layout", local_info) for layout-bearing bufs,
- # or ("flat", (None, region_st, region_ext)) for bufs without layout.
- dst_has_layout = dst.layout is not None and not dst.layout.is_trivial()
- if dst_has_layout:
- dst_local_shape, dst_local_st, dst_local_ext = (
- anchor_info
- if anchor_info[0] is not None
- else get_local_region(dst.layout, list(dst.shape), dst_st, dst_ext)
- )
- else:
- dst_local_shape = None
- dst_local_st = dst_st
- dst_local_ext = dst_ext
-
- per_src_info: list = []
- for src in plan.srcs:
- if src.buf_region is None:
- per_src_info.append(None)
- continue
- b = src.buf_region.buffer
- st, ext = get_st_extent(src.buf_region)
- if b.layout is not None and not b.layout.is_trivial():
- info = get_local_region(b.layout, b.shape, st, ext)
- if not info:
- fail("src layout not supported for tile_local (sliced)")
- per_src_info.append(("layout", info))
- else:
- per_src_info.append(("flat", (None, st, ext)))
-
- compute = spec.compute
- extras = plan.extras
- srcs = plan.srcs
- src_buffers = [s.buf_region.buffer if not s.is_scalar else None for s in srcs]
-
- if dst_has_layout:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- src_views = Tx.meta_var(
- [
- None
- if per_src_info[i] is None or per_src_info[i][0] == "flat"
- else src_buffers[i].local(*per_src_info[i][1][0])
- for i in range(len(srcs))
- ]
- )
- for s in Tx.serial(0, local_total // vec_len):
- for vec in Tx.vectorized(vec_len):
- fused = Tx.meta_var(s * vec_len + vec)
- idx_dst = Tx.meta_var(get_indices(fused, dst_local_st, dst_local_ext))
- src_vals = Tx.meta_var(
- [
- src.scalar
- if src.is_scalar
- else (
- src_views[i][
- tuple(
- get_indices(
- fused,
- per_src_info[i][1][1],
- per_src_info[i][1][2],
- )
- )
- ]
- if per_src_info[i][0] == "layout"
- else src_buffers[i][
- tuple(
- get_indices(
- fused,
- per_src_info[i][1][1],
- per_src_info[i][1][2],
- )
- )
- ]
- )
- for i, src in enumerate(srcs)
- ]
- )
- dst_view[tuple(idx_dst)] = Tx.cast(
- compute(src_vals, extras, dst.dtype), dst.dtype
- )
-
- else:
- # dst is trivially laid out (flat thread-private) — index it directly.
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- src_views = Tx.meta_var(
- [
- None
- if per_src_info[i] is None or per_src_info[i][0] == "flat"
- else src_buffers[i].local(*per_src_info[i][1][0])
- for i in range(len(srcs))
- ]
- )
- for s in Tx.serial(0, local_total // vec_len):
- for vec in Tx.vectorized(vec_len):
- fused = Tx.meta_var(s * vec_len + vec)
- idx_dst = Tx.meta_var(get_indices(fused, dst_local_st, dst_local_ext))
- src_vals = Tx.meta_var(
- [
- src.scalar
- if src.is_scalar
- else (
- src_views[i][
- tuple(
- get_indices(
- fused,
- per_src_info[i][1][1],
- per_src_info[i][1][2],
- )
- )
- ]
- if per_src_info[i][0] == "layout"
- else src_buffers[i][
- tuple(
- get_indices(
- fused,
- per_src_info[i][1][1],
- per_src_info[i][1][2],
- )
- )
- ]
- )
- for i, src in enumerate(srcs)
- ]
- )
- dst[tuple(idx_dst)] = Tx.cast(
- compute(src_vals, extras, dst.dtype), dst.dtype
- )
-
- return impl
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_collective_smem.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_collective_smem.py
deleted file mode 100644
index ba2a80b687..0000000000
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_collective_smem.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-"""Schedule C: shared-buffer fused-tid distribution (scope > thread).
-
-Generic over arity — iterates ``plan.srcs`` and delegates math to
-``spec.compute``.
-"""
-
-from __future__ import annotations
-
-from tvm.arith.analyzer import Analyzer
-from tvm.script import tirx as Tx
-from tvm.tirx import PrimFunc, TilePrimitiveCall
-from tvm.tirx.operator.tile_primitive import DispatchContext, fail
-
-from ..common import get_indices, get_st_extent, get_thread_cnt
-from ._common import (
- basic_layout_checks,
- compute_dtype_of,
- emit_scope_sync,
- fetch_src_value,
- infer_vec_len,
- n_elements,
- sigs_equal,
- slice_and_sig,
- tid_in_scope_expr,
-)
-from .schema import OpSpec
-
-
-def validate_shared(spec: OpSpec):
- """Predicate factory: scope in {thread,warp,warpgroup,cta}; all bufs in shared*."""
-
- def _check(op: TilePrimitiveCall, sctx: DispatchContext) -> tuple[bool, str | None]:
- if sctx.scope_kind not in ["thread", "warp", "warpgroup", "cta"]:
- return False, f"unsupported scope {sctx.scope_kind}"
- plan, msg = spec.parse(op)
- if msg is not None or plan is None:
- return False, msg
-
- if not plan.dst.buffer.scope().startswith("shared"):
- return False, f"dst must be shared*, got {plan.dst.buffer.scope()}"
- if plan.dst.buffer.layout is None:
- return False, "dst must have layout"
- for s in plan.srcs:
- if s.buf_region is None:
- continue
- buf = s.buf_region.buffer
- if not buf.scope().startswith("shared"):
- return False, "src buffer must be shared*"
- if buf.layout is None:
- return False, "src buffer must have layout"
-
- if spec.check_extras is not None:
- ok, why = spec.check_extras(plan.extras, compute_dtype_of(plan))
- if not ok:
- return False, why
-
- a = Analyzer()
- for s in plan.srcs:
- if s.buf_region is None or s.index_fn is not None:
- # Skip shape check for broadcasting srcs (have custom index_fn).
- continue
- if not basic_layout_checks(s.buf_region, plan.dst, a, disallow_swizzle=False):
- return False, "shape/layout mismatch between src and dst"
-
- sigs = [slice_and_sig(plan.dst)[3]]
- for s in plan.srcs:
- if s.buf_region is not None and s.index_fn is None:
- sigs.append(slice_and_sig(s.buf_region)[3])
- if not sigs_equal(a, *sigs):
- return False, "layout signature mismatch"
- return True, None
-
- return _check
-
-
-def emit_shared(op_call: TilePrimitiveCall, spec: OpSpec, sctx: DispatchContext) -> PrimFunc:
- plan, msg = spec.parse(op_call)
- if msg is not None or plan is None:
- fail(msg or "parse failed")
-
- dst = plan.dst.buffer
- dst_st, dst_ext = get_st_extent(plan.dst)
- total = n_elements(plan.dst)
- thread_cnt = get_thread_cnt(sctx)
- if thread_cnt is None:
- fail(f"unsupported scope {sctx.scope_kind} for shared emit")
- assert "threadIdx.y" not in sctx.launch_params and "threadIdx.z" not in sctx.launch_params
-
- vec_len = infer_vec_len(op_call, plan, thread_cnt=thread_cnt, fallback_to_scalar=True)
- if vec_len is None:
- fail("could not infer vec_len for shared emit")
-
- compute = spec.compute
- srcs = plan.srcs
- extras = plan.extras
- sync = emit_scope_sync(sctx.scope_kind)
-
- def _tid():
- return tid_in_scope_expr(sctx, thread_cnt)
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- tid = _tid()
- for s in Tx.serial(0, Tx.ceildiv(total, vec_len * thread_cnt)):
- for vec in Tx.vectorized(vec_len):
- fused = Tx.meta_var(s * vec_len * thread_cnt + tid * vec_len + vec)
- if fused < total:
- dst_idx = Tx.meta_var(get_indices(fused, dst_st, dst_ext))
- src_vals = Tx.meta_var(
- [fetch_src_value(src, fused, dst_idx, dst_st, dst_ext) for src in srcs]
- )
- dst[tuple(dst_idx)] = Tx.cast(compute(src_vals, extras, dst.dtype), dst.dtype)
- sync()
-
- return impl
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_thread.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_thread.py
deleted file mode 100644
index e090b59a69..0000000000
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schedule_thread.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-"""Schedule A: per-thread vectorized serial loop (scope == thread).
-
-Generic over arity — iterates ``plan.srcs`` without knowing about
-unary/binary/cast/fma. The op-specific math is delegated to ``spec.compute``.
-"""
-
-from __future__ import annotations
-
-from tvm.script import tirx as Tx
-from tvm.tirx import PrimFunc, TilePrimitiveCall
-from tvm.tirx.operator.tile_primitive import DispatchContext, fail
-
-from ..common import get_indices, get_st_extent
-from ._common import (
- compute_dtype_of,
- fetch_src_value,
- infer_vec_len,
- n_elements,
-)
-from .schema import OpSpec
-
-
-def validate_per_thread(spec: OpSpec):
- """Predicate factory for ``per_thread``:
-
- Accepts:
- (a) scope == thread + all buf-region srcs in local scope
- (b) scope > thread (warp/warpgroup/cta) + all buf-region srcs in local
- scope AND all have trivial layouts (i.e. flat thread-private regs,
- no collective tile semantics — each thread independently runs the
- loop on its own private copy). Used by e.g. tests where binary is
- called at cta scope on flat local bufs.
- """
-
- def _check(op: TilePrimitiveCall, sctx: DispatchContext) -> tuple[bool, str | None]:
- plan, msg = spec.parse(op)
- if msg is not None or plan is None:
- return False, msg
- if plan.dst.buffer.scope() != "local":
- return False, f"dst scope must be local, got {plan.dst.buffer.scope()}"
- for s in plan.srcs:
- if s.buf_region is not None and s.buf_region.buffer.scope() != "local":
- return False, "all buffer-region srcs must be in local scope"
-
- if not sctx.is_thread:
- # Path (b): allowed only if all bufs are trivial (no non-trivial layout).
- if sctx.scope_kind not in ("warp", "warpgroup", "cta"):
- return False, f"per_thread unsupported scope {sctx.scope_kind}"
- dst_lay = plan.dst.buffer.layout
- if dst_lay is not None and not dst_lay.is_trivial():
- return False, "non-trivial dst layout — use tile_local instead"
- for s in plan.srcs:
- if s.buf_region is None:
- continue
- lay = s.buf_region.buffer.layout
- if lay is not None and not lay.is_trivial():
- return False, "non-trivial src layout — use tile_local instead"
-
- if spec.check_extras is not None:
- ok, why = spec.check_extras(plan.extras, compute_dtype_of(plan))
- if not ok:
- return False, why
- return True, None
-
- return _check
-
-
-def emit_per_thread(op_call: TilePrimitiveCall, spec: OpSpec, sctx: DispatchContext) -> PrimFunc:
- plan, msg = spec.parse(op_call)
- if msg is not None or plan is None:
- fail(msg or "parse failed")
- dst = plan.dst.buffer
- dst_st, dst_ext = get_st_extent(plan.dst)
- total = n_elements(plan.dst)
- vec_len = infer_vec_len(op_call, plan, thread_cnt=1, fallback_to_scalar=False)
- if vec_len is None:
- fail("could not infer vec_len for per_thread")
-
- # Try vector intrinsic emit first (e.g. add.<rm>.ftz.f32x2 for sm100 f32).
- # Carries PTX-level attrs (rounding_mode etc.) that scalar `a+b` cannot.
- if spec.vec_emit_factory is not None:
- impl = spec.vec_emit_factory(op_call, plan, sctx, vec_len)
- if impl is not None:
- return impl
-
- compute = spec.compute
- srcs = plan.srcs
- extras = plan.extras
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- for s in Tx.serial(0, total // vec_len):
- for vec in Tx.vectorized(vec_len):
- fused = Tx.meta_var(s * vec_len + vec)
- dst_idx = Tx.meta_var(get_indices(fused, dst_st, dst_ext))
- # Build src expressions in Python (Tx.meta_var binds the
- # list at meta-time so it isn't parsed as an IR alloc).
- src_vals = Tx.meta_var(
- [fetch_src_value(src, fused, dst_idx, dst_st, dst_ext) for src in srcs]
- )
- dst[tuple(dst_idx)] = Tx.cast(compute(src_vals, extras, dst.dtype), dst.dtype)
-
- return impl
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schema.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schema.py
deleted file mode 100644
index eed8666510..0000000000
--- a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/schema.py
+++ /dev/null
@@ -1,1165 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-"""Op-agnostic elementwise schema.
-
-All elementwise ops (unary / binary / cast / fma) live in one ``ALL_OPS``
-table. Each entry is an ``OpSpec`` with a ``parse(op_call) -> Plan`` and a
-``compute(src_vals, extras, dst_dtype) -> raw_value``. Schedules iterate
-``Plan.srcs`` without knowing the arity.
-"""
-
-from __future__ import annotations
-
-from collections.abc import Callable
-from dataclasses import dataclass, field
-from typing import Any
-
-from tvm.ir.expr import PrimExpr
-from tvm.script import tirx as Tx
-from tvm.tirx import BufferRegion, TilePrimitiveCall
-from tvm.tirx.expr import FloatImm
-
-
-@dataclass
-class SrcSpec:
- """One operand of an elementwise op.
-
- Either a buffer-region (per-element load) or a scalar PrimExpr.
- ``index_fn``, if given, computes per-element indices for broadcasting
- cases (e.g. binary src2 with extent=1 dims):
- index_fn(dst_indices, dst_start, dst_extent, src_start, src_extent) -> list[Expr]
- Default is the standard ``get_indices`` over the src's own region.
- """
-
- buf_region: BufferRegion | None = None
- scalar: PrimExpr | None = None
- index_fn: Callable | None = None
-
- @property
- def is_scalar(self) -> bool:
- return self.scalar is not None
-
- @property
- def buffer(self):
- return self.buf_region.buffer if self.buf_region is not None else None
-
-
-@dataclass
-class Plan:
- """Parsed elementwise op ready for a schedule to consume."""
-
- dst: BufferRegion
- srcs: list[SrcSpec]
- extras: dict[str, Any] = field(default_factory=dict)
-
-
-@dataclass
-class OpSpec:
- """Metadata for an elementwise op.
-
- Schedules consult ``vec_emit_factory`` first: given (op_call, plan, sctx, vec_len)
- it may return a fully-built PrimFunc using a PTX/CUDA intrinsic (e.g.
- ``add.<rm>.ftz.f32x2``). If it returns None, the schedule falls back to a
- scalar ``Tx.vectorized`` loop driven by ``compute``.
- """
-
- name: str # TIRx op short name, e.g. "exp" / "add" / "fma" / "cast"
- parse: Callable[[TilePrimitiveCall], tuple[Plan | None, str | None]]
- compute: Callable[[list, dict, str], Any]
- # extras dtype checker, optional: (extras, compute_dtype) -> (ok, msg)
- check_extras: Callable | None = None
- # Optional vector-intrinsic emit factory: (op_call, plan, sctx, vec_len)
- # -> PrimFunc | None. Called by each schedule before scalar emit. The
- # factory is responsible for ALL applicability checks (dtype, vec_len,
- # sm version, broadcasting, scope) and must return None if the intrinsic
- # cannot be used — the schedule will then emit the scalar fallback.
- vec_emit_factory: Callable | None = None
-
-
-# -----------------------------------------------------------------------------
-# Parse helpers — one per op family. They produce Plan/None+msg without touching
-# scope/layout (those checks live in the schedule validators).
-# -----------------------------------------------------------------------------
-def _parse_unary(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
- """Parse Tx.<unary>(dst, src[, bias, scale]).
-
- src can be a BufferRegion or a PrimExpr (scalar fill).
- bias can be a BufferRegion (per-element) or FloatImm (constant) or None.
- scale is FloatImm or None (defaults to 1.0).
-
- Produces:
- Plan(dst, srcs=[SrcSpec(main src), optional SrcSpec(bias_buf)],
- extras={scale: ..., bias_const: ... or None})
- """
- _dst: BufferRegion = op.args[0]
- _src = op.args[1]
- _bias = op.args[2] if len(op.args) > 2 else None
- _scale = op.args[3] if len(op.args) > 2 else None
-
- srcs: list[SrcSpec] = []
- if isinstance(_src, BufferRegion):
- srcs.append(SrcSpec(buf_region=_src))
- elif isinstance(_src, PrimExpr):
- srcs.append(SrcSpec(scalar=_src))
- else:
- return None, f"unsupported src type {type(_src).__name__}"
-
- extras: dict[str, Any] = {
- "scale": _scale,
- "bias_const": _bias if isinstance(_bias, FloatImm) else None,
- }
- if isinstance(_bias, BufferRegion):
- srcs.append(SrcSpec(buf_region=_bias))
- extras["has_bias_buf"] = True
- else:
- extras["has_bias_buf"] = False
- return Plan(dst=_dst, srcs=srcs, extras=extras), None
-
-
-def _check_unary_extras(extras: dict, compute_dtype: str) -> tuple[bool, str | None]:
- scale = extras.get("scale")
- if scale is not None and scale.dtype != compute_dtype:
- return False, f"scale dtype {scale.dtype} != compute dtype {compute_dtype}"
- bias_const = extras.get("bias_const")
- if bias_const is not None and bias_const.dtype != compute_dtype:
- return False, f"bias_const dtype {bias_const.dtype} != compute dtype {compute_dtype}"
- return True, None
-
-
-def _unary_with_bias_scale(raw_op):
- """Wrap a unary raw op (e.g. Tx.exp) into a compute that applies bias/scale.
-
- raw_op: lambda v: <expr> (applied AFTER scale+bias if any)
- Returns: lambda src_vals, extras, dt: <expr>
- """
-
- def compute(src_vals, extras, dt):
- x = src_vals[0]
- scale = extras.get("scale")
- if scale is not None:
- x = x * scale
- if extras.get("has_bias_buf"):
- x = x + src_vals[1]
- elif extras.get("bias_const") is not None:
- x = x + extras["bias_const"]
- return raw_op(x)
-
- return compute
-
-
-# Compute callbacks for unary ops.
-def _compute_zero(src_vals, extras, dt):
- return 0.0
-
-
-def _compute_fill(src_vals, extras, dt):
- return src_vals[0]
-
-
-def _compute_reciprocal(src_vals, extras, dt):
- x = src_vals[0]
- return Tx.FloatImm(x.dtype, 1.0) / x
-
-
-def _compute_silu(src_vals, extras, dt):
- # NOTE: silu doesn't apply bias/scale in the legacy table — preserve that.
- x = src_vals[0]
- return x / (Tx.FloatImm(x.dtype, 1.0) + Tx.exp(Tx.FloatImm(x.dtype, 0.0) - x))
-
-
-# -----------------------------------------------------------------------------
-# Binary: Tx.<op>(dst, src1, src2) with optional broadcasting + constant rhs.
-# -----------------------------------------------------------------------------
-def _binary_broadcast_index_fn(dst_indices, dst_start, dst_extent, src_start, src_extent):
- """Compute src2 indices when src2 has extent=1 broadcasting dims."""
- len_diff = len(dst_extent) - len(src_extent)
- return [
- (
- (dst_indices[i + len_diff] - dst_start[i + len_diff]) + src_start[i]
- if src_extent[i] != 1
- else src_start[i]
- )
- for i in range(len(src_extent))
- ]
-
-
-def _binary_is_commutative(op_name: str) -> bool:
- return op_name in ("add", "mul")
-
-
-def _parse_binary_for(op_name: str):
- """Build a parse(op_call) -> (Plan, msg) for a specific binary op name."""
-
- def parse(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
- _dst: BufferRegion = op.args[0]
- _src1 = op.args[1]
- _src2 = op.args[2]
-
- # Reject both-constant (degenerate).
- s1_scalar = not isinstance(_src1, BufferRegion)
- s2_scalar = not isinstance(_src2, BufferRegion)
- if s1_scalar and s2_scalar:
- return None, "both inputs are constants"
-
- # Move constant to rhs (commute if allowed; else reject).
- if s1_scalar:
- if not _binary_is_commutative(op_name):
- return None, f"non-commutative op {op_name} cannot have constant lhs"
- _src1, _src2 = _src2, _src1
- s1_scalar, s2_scalar = False, True
-
- # If rhs is a smaller buffer (broadcast), and op is commutative, optionally swap.
- if not s2_scalar:
- import functools
- import operator
-
- s1_n = functools.reduce(operator.mul, [r.extent for r in _src1.region], 1)
- s2_n = functools.reduce(operator.mul, [r.extent for r in _src2.region], 1)
- if s1_n < s2_n:
- if not _binary_is_commutative(op_name):
- return None, f"non-commutative op {op_name} cannot swap to broadcast"
- _src1, _src2 = _src2, _src1
-
- srcs: list[SrcSpec] = [SrcSpec(buf_region=_src1)]
- if s2_scalar:
- srcs.append(SrcSpec(scalar=_src2))
- else:
- # If src2 is broadcasting (any extent=1 dims smaller than src1's), attach
- # a broadcast index_fn that derives src2 indices from dst's.
- s1_ext = [r.extent for r in _src1.region]
- s2_ext = [r.extent for r in _src2.region]
- needs_broadcast = (len(s2_ext) != len(s1_ext)) or (
- any(e != 1 for e in s2_ext)
- and (
- any(
- int(s2_ext[i]) == 1 and int(s1_ext[-len(s2_ext) + i]) != 1
- for i in range(len(s2_ext))
- )
- )
- )
- srcs.append(
- SrcSpec(
- buf_region=_src2,
- index_fn=_binary_broadcast_index_fn if needs_broadcast else None,
- )
- )
- extras: dict[str, Any] = {}
- rm = op.config.get("rounding_mode", None)
- if rm is not None:
- extras["rounding_mode"] = rm
- return Plan(dst=_dst, srcs=srcs, extras=extras), None
-
- return parse
-
-
-# Compute callbacks for binary ops.
-def _compute_add(src_vals, extras, dt):
- return src_vals[0] + src_vals[1]
-
-
-def _compute_sub(src_vals, extras, dt):
- return src_vals[0] - src_vals[1]
-
-
-def _compute_mul(src_vals, extras, dt):
- return src_vals[0] * src_vals[1]
-
-
-def _compute_fdiv(src_vals, extras, dt):
- return src_vals[0] / src_vals[1]
-
-
-# -----------------------------------------------------------------------------
-# Packed f32x2 vector intrinsic emit (sm_100+, f32, vec_len=2) for add/sub/mul.
-# This carries rounding_mode (PTX attr) that scalar `a+b` cannot express.
-#
-# The underlying PTX ops are ``Tx.ptx.{add,sub,mul}_f32x2(d, a, b, ...)`` which
-# take packed-as-u64 register operands. We provide local adapters that accept
-# (4 scalar inputs + d_addr + rounding_mode) so the call sites here read more
-# directly; the adapters pack the scalars via ``Tx.cuda.make_float2``.
-# -----------------------------------------------------------------------------
-
-
-def _f32x2_adapter(op_name):
- """Return a callable with the old (a1, a2, b1, b2, d, rounding_mode=) shape
- that internally invokes the new DPS ``Tx.ptx.{op}_f32x2`` API."""
- op_func = getattr(Tx.ptx, f"{op_name}_f32x2")
-
- def _emit(a1, a2, b1, b2, d, rounding_mode):
- return op_func(
- d,
- Tx.cuda.make_float2(a1, a2),
- Tx.cuda.make_float2(b1, b2),
- rounding=rounding_mode,
- ftz=True,
- )
-
- return _emit
-
-
-_PACKED_F32X2_PTX = {
- "add": _f32x2_adapter("add"),
- "sub": _f32x2_adapter("sub"),
- "mul": _f32x2_adapter("mul"),
-}
-
-
-def _fma_f32x2_adapter(a1, a2, b1, b2, c1, c2, d, rounding_mode):
- """Adapter: (6 scalar inputs + d_addr + rounding_mode) → new DPS API."""
- return Tx.ptx.fma_f32x2(
- d,
- Tx.cuda.make_float2(a1, a2),
- Tx.cuda.make_float2(b1, b2),
- Tx.cuda.make_float2(c1, c2),
- rounding=rounding_mode,
- ftz=True,
- )
-
-
-def _make_binary_packed_f32x2_factory(op_name: str):
- """Build a vec_emit_factory for binary add/sub/mul on f32 vec_len=2."""
-
- op_func_f32x2 = _PACKED_F32X2_PTX[op_name]
-
- def factory(op_call, plan, sctx, vec_len):
- # Importing here to avoid module-level cycles with cuda.common.
- from ..common import get_st_extent, sm_version_ok
- from ..layout_utils import get_local_region
-
- # ---- applicability -----------------------------------------------
- # NOTE: this emit always processes 2 elements per chunk via the PTX
- # packed-f32x2 intrinsic, regardless of the schedule's vec_len choice
- # (codegen does not auto-fuse vec_len=4 + 4 scalar adds into packed).
- if plan.dst.buffer.dtype != "float32":
- return None
- if not sm_version_ok(op_call, sctx, min_version=100)[0]:
- return None
- # Two emit modes:
- # thread-scope : flat per-thread buffers; index buf[fused] directly
- # wg/warp scope: collective tile with layout; need buf.local(*shape)
- # to get the per-thread reg slice, then index that.
- if sctx.is_thread:
- use_view = False
- elif sctx.scope_kind in ("warp", "warpgroup", "cta"):
- use_view = True
- # All buffer srcs + dst must have non-trivial layout for view.
- if plan.dst.buffer.layout is None or plan.dst.buffer.layout.is_trivial():
- return None
- for s in plan.srcs:
- if not s.is_scalar and (
- s.buf_region.buffer.layout is None or s.buf_region.buffer.layout.is_trivial()
- ):
- return None
- else:
- return None
- # All buffer srcs must be f32; const srcs must be f32 too.
- for s in plan.srcs:
- if s.is_scalar:
- if s.scalar.dtype != "float32":
- return None
- else:
- if s.buf_region.buffer.dtype != "float32":
- return None
- if s.index_fn is not None:
- # Broadcasting not supported by this packed intrinsic.
- return None
- if len(plan.srcs) != 2:
- return None
-
- dst = plan.dst.buffer
- dst_st_raw, dst_ext_raw = get_st_extent(plan.dst)
- s1, s2 = plan.srcs[0], plan.srcs[1]
- rm = plan.extras.get("rounding_mode", "rz")
- s1_buf = None if s1.is_scalar else s1.buf_region.buffer
- s2_buf = None if s2.is_scalar else s2.buf_region.buffer
- s1_scalar_val = s1.scalar if s1.is_scalar else None
- s2_scalar_val = s2.scalar if s2.is_scalar else None
- if s1.is_scalar and s2.is_scalar:
- return None # degenerate, parse already rejects this
-
- import functools
- import operator
-
- from ..common import get_indices
-
- if not use_view:
- # ---- thread-scope: index raw buffer directly -------------------
- total = functools.reduce(operator.mul, dst_ext_raw, 1)
- try:
- if int(total) % 2 != 0:
- return None
- except (TypeError, ValueError):
- return None
- n_chunks = int(total) // 2
- dst_st, dst_ext = dst_st_raw, dst_ext_raw
- s1_st, s1_ext = (None, None) if s1.is_scalar else get_st_extent(s1.buf_region)
- s2_st, s2_ext = (None, None) if s2.is_scalar else get_st_extent(s2.buf_region)
-
- if not s1.is_scalar and s2.is_scalar:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- s1_idx_a = Tx.meta_var(get_indices(2 * s, s1_st, s1_ext))
- s1_idx_b = Tx.meta_var(get_indices(2 * s + 1, s1_st, s1_ext))
- op_func_f32x2(
- s1_buf[tuple(s1_idx_a)],
- s1_buf[tuple(s1_idx_b)],
- s2_scalar_val,
- s2_scalar_val,
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- if s1.is_scalar and not s2.is_scalar:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- s2_idx_a = Tx.meta_var(get_indices(2 * s, s2_st, s2_ext))
- s2_idx_b = Tx.meta_var(get_indices(2 * s + 1, s2_st, s2_ext))
- op_func_f32x2(
- s1_scalar_val,
- s1_scalar_val,
- s2_buf[tuple(s2_idx_a)],
- s2_buf[tuple(s2_idx_b)],
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- s1_idx_a = Tx.meta_var(get_indices(2 * s, s1_st, s1_ext))
- s1_idx_b = Tx.meta_var(get_indices(2 * s + 1, s1_st, s1_ext))
- s2_idx_a = Tx.meta_var(get_indices(2 * s, s2_st, s2_ext))
- s2_idx_b = Tx.meta_var(get_indices(2 * s + 1, s2_st, s2_ext))
- op_func_f32x2(
- s1_buf[tuple(s1_idx_a)],
- s1_buf[tuple(s1_idx_b)],
- s2_buf[tuple(s2_idx_a)],
- s2_buf[tuple(s2_idx_b)],
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- # ---- wg/warp/cta-scope: collective tile -> per-thread reg view ------
- # Use get_local_region to get the per-thread (shape, st, ext).
- dst_info = get_local_region(dst.layout, list(dst.shape), dst_st_raw, dst_ext_raw)
- if dst_info is None:
- return None
- dst_local_shape, dst_local_st, dst_local_ext = dst_info
- local_total = functools.reduce(operator.mul, dst_local_ext, 1)
- try:
- if int(local_total) % 2 != 0:
- return None
- except (TypeError, ValueError):
- return None
- n_chunks = int(local_total) // 2
-
- def _src_local_info(src):
- if src.is_scalar:
- return None
- b = src.buf_region.buffer
- st, ext = get_st_extent(src.buf_region)
- info = get_local_region(b.layout, b.shape, st, ext)
- return info
-
- s1_info = _src_local_info(s1)
- s2_info = _src_local_info(s2)
- if (not s1.is_scalar and s1_info is None) or (not s2.is_scalar and s2_info is None):
- return None
- s1_local_shape = s1_info[0] if s1_info else None
- s1_local_st = s1_info[1] if s1_info else None
- s1_local_ext = s1_info[2] if s1_info else None
- s2_local_shape = s2_info[0] if s2_info else None
- s2_local_st = s2_info[1] if s2_info else None
- s2_local_ext = s2_info[2] if s2_info else None
-
- if not s1.is_scalar and s2.is_scalar:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- s1_view = s1_buf.local(*s1_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_local_st, dst_local_ext))
- s1_idx_a = Tx.meta_var(get_indices(2 * s, s1_local_st, s1_local_ext))
- s1_idx_b = Tx.meta_var(get_indices(2 * s + 1, s1_local_st, s1_local_ext))
- op_func_f32x2(
- s1_view[tuple(s1_idx_a)],
- s1_view[tuple(s1_idx_b)],
- s2_scalar_val,
- s2_scalar_val,
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- if s1.is_scalar and not s2.is_scalar:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- s2_view = s2_buf.local(*s2_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_local_st, dst_local_ext))
- s2_idx_a = Tx.meta_var(get_indices(2 * s, s2_local_st, s2_local_ext))
- s2_idx_b = Tx.meta_var(get_indices(2 * s + 1, s2_local_st, s2_local_ext))
- op_func_f32x2(
- s1_scalar_val,
- s1_scalar_val,
- s2_view[tuple(s2_idx_a)],
- s2_view[tuple(s2_idx_b)],
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- s1_view = s1_buf.local(*s1_local_shape)
- s2_view = s2_buf.local(*s2_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_local_st, dst_local_ext))
- s1_idx_a = Tx.meta_var(get_indices(2 * s, s1_local_st, s1_local_ext))
- s1_idx_b = Tx.meta_var(get_indices(2 * s + 1, s1_local_st, s1_local_ext))
- s2_idx_a = Tx.meta_var(get_indices(2 * s, s2_local_st, s2_local_ext))
- s2_idx_b = Tx.meta_var(get_indices(2 * s + 1, s2_local_st, s2_local_ext))
- op_func_f32x2(
- s1_view[tuple(s1_idx_a)],
- s1_view[tuple(s1_idx_b)],
- s2_view[tuple(s2_idx_a)],
- s2_view[tuple(s2_idx_b)],
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- return factory
-
-
-# -----------------------------------------------------------------------------
-# Cast: Tx.cast(dst, src) -- arity 1, no bias/scale, dst dtype != src dtype.
-# -----------------------------------------------------------------------------
-def _parse_cast(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
- _dst: BufferRegion = op.args[0]
- _src = op.args[1]
- if not isinstance(_src, BufferRegion):
- return None, "cast src must be a buffer region"
- return Plan(dst=_dst, srcs=[SrcSpec(buf_region=_src)], extras={}), None
-
-
-def _compute_cast(src_vals, extras, dt):
- # Outer Tx.cast(..., dst.dtype) in the schedule already does the cast.
- return src_vals[0]
-
-
-# Cast vec2 packed CUDA intrinsics. Each value is the CUDA builtin name that
-# converts one packed-2 source to one packed-2 dest in a single instruction.
-_VEC2_CAST_INTRINSICS = {
- ("float32", "float16"): "__float22half2_rn",
- ("float16", "float32"): "__half22float2",
- ("bfloat16", "float32"): "__bfloat1622float2",
- ("float32", "bfloat16"): "__float22bfloat162_rn",
-}
-_DTYPE_X2_NAME = {"float32": "float2", "float16": "half2", "bfloat16": "nv_bfloat162"}
-
-
-def _is_contiguous_region(analyzer, st, ext, shape):
- """[st:st+ext] is a contiguous block in row-major ``shape``."""
- found_break = False
- for i in reversed(range(len(st))):
- is_full = analyzer.can_prove_equal(st[i], 0) and analyzer.can_prove_equal(ext[i], shape[i])
- if found_break:
- if not analyzer.can_prove_equal(ext[i], 1):
- return False
- else:
- if not is_full:
- found_break = True
- return True
-
-
-def _linear_offset(st, shape):
- """Row-major linear offset of position ``st`` in buffer of given ``shape``."""
- offset = 0
- stride = 1
- for i in reversed(range(len(st))):
- offset = offset + st[i] * stride
- stride = stride * shape[i]
- return offset
-
-
-def _make_cast_vec2_factory():
- """Cast vec_emit using CUDA packed-pair intrinsics (e.g. __float22half2_rn)."""
-
- def factory(op_call, plan, sctx, vec_len):
- from tvm.arith import Analyzer
-
- from ..common import get_indices, get_st_extent
- from ..layout_utils import get_local_region
-
- if len(plan.srcs) != 1 or plan.srcs[0].is_scalar:
- return None
- src = plan.srcs[0]
- if src.index_fn is not None:
- return None
- src_dtype = src.buf_region.buffer.dtype
- dst_dtype = plan.dst.buffer.dtype
- intrinsic = _VEC2_CAST_INTRINSICS.get((src_dtype, dst_dtype))
- if intrinsic is None:
- return None
-
- import functools
- import operator
-
- dst = plan.dst.buffer
- dst_st, dst_ext = get_st_extent(plan.dst)
- src_buf = src.buf_region.buffer
- src_st, src_ext = get_st_extent(src.buf_region)
-
- src_dtypex2 = _DTYPE_X2_NAME[src_dtype]
- dst_dtypex2 = _DTYPE_X2_NAME[dst_dtype]
- func_name = f"tvm_builtin_cast_{src_dtype}x2_{dst_dtype}x2"
- source_code = (
- f"\n__forceinline__ __device__ void {func_name}(void* dst, void* src) {{\n"
- f" (({dst_dtypex2}*)dst)[0] = {intrinsic}((({src_dtypex2}*)src)[0]);\n"
- "}\n"
- )
-
- if sctx.is_thread:
- total = functools.reduce(operator.mul, dst_ext, 1)
- try:
- if int(total) % 2 != 0:
- return None
- except (TypeError, ValueError):
- return None
- n_chunks = int(total) // 2
-
- @Tx.prim_func(check_well_formed=False)
- def impl_thread():
- # (no Tx.thread wrap; outer scope is already thread)
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- src_idx = Tx.meta_var(get_indices(2 * s, src_st, src_ext))
- Tx.cuda.func_call(
- func_name,
- Tx.address_of(dst[tuple(dst_idx)]),
- Tx.address_of(src_buf[tuple(src_idx)]),
- source_code=source_code,
- )
-
- return impl_thread
-
- if sctx.scope_kind not in ("warp", "warpgroup", "cta", "cluster"):
- return None
-
- # Per-thread vec2 cast at collective scope. Mirrors HEAD's
- # cast/local_view fast path: open Tx.thread, view each buffer as a
- # flat per-thread 1D array, issue cuda intrinsic per pair.
- src_has_layout = src_buf.layout is not None and not src_buf.layout.is_trivial()
- dst_has_layout = dst.layout is not None and not dst.layout.is_trivial()
- if not (src_has_layout or dst_has_layout):
- return None
-
- if src_has_layout:
- src_info = get_local_region(src_buf.layout, list(src_buf.shape), src_st, src_ext)
- if not src_info:
- return None
- src_local_shape, src_local_st, src_local_ext = src_info
- else:
- src_local_shape = list(src_buf.shape)
- src_local_st = list(src_st)
- src_local_ext = list(src_ext)
-
- if dst_has_layout:
- dst_info = get_local_region(dst.layout, list(dst.shape), dst_st, dst_ext)
- if not dst_info:
- return None
- dst_local_shape, dst_local_st, dst_local_ext = dst_info
- else:
- dst_local_shape = list(dst.shape)
- dst_local_st = list(dst_st)
- dst_local_ext = list(dst_ext)
-
- src_local_total = functools.reduce(operator.mul, src_local_ext, 1)
- dst_local_total = functools.reduce(operator.mul, dst_local_ext, 1)
- try:
- src_total_i = int(src_local_total)
- dst_total_i = int(dst_local_total)
- except (TypeError, ValueError):
- return None
- if src_total_i != dst_total_i or dst_total_i % 2 != 0:
- return None
- n2 = dst_total_i // 2
-
- analyzer = Analyzer()
- if not _is_contiguous_region(analyzer, src_local_st, src_local_ext, src_local_shape):
- return None
- if not _is_contiguous_region(analyzer, dst_local_st, dst_local_ext, dst_local_shape):
- return None
- src_off = _linear_offset(src_local_st, src_local_shape)
- dst_off = _linear_offset(dst_local_st, dst_local_shape)
- try:
- if int(src_off) % 2 != 0 or int(dst_off) % 2 != 0:
- return None
- except (TypeError, ValueError):
- if not (
- analyzer.can_prove_equal(src_off % 2, 0)
- and analyzer.can_prove_equal(dst_off % 2, 0)
- ):
- return None
-
- src_full_size = functools.reduce(operator.mul, src_local_shape, 1)
- dst_full_size = functools.reduce(operator.mul, dst_local_shape, 1)
-
- @Tx.prim_func(check_well_formed=False)
- def impl_collective():
- with Tx.thread():
- base_src = Tx.decl_buffer(
- (src_full_size,), src_buf.dtype, src_buf.data, scope=src_buf.scope()
- )
- base_dst = Tx.decl_buffer((dst_full_size,), dst.dtype, dst.data, scope=dst.scope())
- for s in Tx.serial(0, n2):
- src_idx = Tx.meta_var(src_off + s * 2)
- dst_idx = Tx.meta_var(dst_off + s * 2)
- Tx.cuda.func_call(
- func_name,
- Tx.address_of(base_dst[dst_idx]),
- Tx.address_of(base_src[src_idx]),
- source_code=source_code,
- )
-
- return impl_collective
-
- return factory
-
-
-# -----------------------------------------------------------------------------
-# FMA: Tx.fma(dst, a, b, c) -- compute = a*b + c.
-# -----------------------------------------------------------------------------
-def _parse_fma(op: TilePrimitiveCall) -> tuple[Plan | None, str | None]:
- _dst: BufferRegion = op.args[0]
- args = op.args[1:4]
- srcs: list[SrcSpec] = []
- for a in args:
- if isinstance(a, BufferRegion):
- srcs.append(SrcSpec(buf_region=a))
- else:
- srcs.append(SrcSpec(scalar=a))
- return Plan(dst=_dst, srcs=srcs, extras={}), None
-
-
-def _compute_fma(src_vals, extras, dt):
- return src_vals[0] * src_vals[1] + src_vals[2]
-
-
-def _make_fma_packed_f32x2_factory():
- """FMA vec_emit for sm_100+ f32: Tx.ptx.fma_packed_f32x2."""
-
- def factory(op_call, plan, sctx, vec_len):
- from ..common import get_indices, get_st_extent, sm_version_ok
- from ..layout_utils import get_local_region
-
- if plan.dst.buffer.dtype != "float32":
- return None
- if not sm_version_ok(op_call, sctx, min_version=100)[0]:
- return None
- # Two emit modes:
- if sctx.is_thread:
- use_view = False
- elif sctx.scope_kind in ("warp", "warpgroup", "cta"):
- use_view = True
- if plan.dst.buffer.layout is None or plan.dst.buffer.layout.is_trivial():
- return None
- for s in plan.srcs:
- if not s.is_scalar and (
- s.buf_region.buffer.layout is None or s.buf_region.buffer.layout.is_trivial()
- ):
- return None
- else:
- return None
- if len(plan.srcs) != 3:
- return None
- a, b, c = plan.srcs
- if a.is_scalar or a.buf_region.buffer.dtype != "float32":
- return None
- for s in (b, c):
- if s.is_scalar:
- if s.scalar.dtype != "float32":
- return None
- else:
- if s.buf_region.buffer.dtype != "float32":
- return None
- if s.index_fn is not None:
- return None
- if a.index_fn is not None:
- return None
-
- import functools
- import operator
-
- dst = plan.dst.buffer
- dst_st_raw, dst_ext_raw = get_st_extent(plan.dst)
- rm = plan.extras.get("rounding_mode", "rz")
- a_buf = a.buf_region.buffer
- a_st_raw, a_ext_raw = get_st_extent(a.buf_region)
-
- b_is_buf = not b.is_scalar
- c_is_buf = not c.is_scalar
- b_buf = b.buf_region.buffer if b_is_buf else None
- c_buf = c.buf_region.buffer if c_is_buf else None
- b_st_raw, b_ext_raw = get_st_extent(b.buf_region) if b_is_buf else (None, None)
- c_st_raw, c_ext_raw = get_st_extent(c.buf_region) if c_is_buf else (None, None)
- b_scalar = b.scalar if not b_is_buf else None
- c_scalar = c.scalar if not c_is_buf else None
-
- if not use_view:
- # thread-scope: use raw region st/ext, index buffer directly
- dst_st, dst_ext = dst_st_raw, dst_ext_raw
- a_st, a_ext = a_st_raw, a_ext_raw
- b_st, b_ext = b_st_raw, b_ext_raw
- c_st, c_ext = c_st_raw, c_ext_raw
- total = functools.reduce(operator.mul, dst_ext, 1)
- try:
- if int(total) % 2 != 0:
- return None
- except (TypeError, ValueError):
- return None
- n_chunks = int(total) // 2
- else:
- # wg/warp/cta-scope: build per-thread local views + use local st/ext.
- dst_info = get_local_region(dst.layout, list(dst.shape), dst_st_raw, dst_ext_raw)
- a_info = get_local_region(a_buf.layout, a_buf.shape, a_st_raw, a_ext_raw)
- if dst_info is None or a_info is None:
- return None
- b_info = (
- get_local_region(b_buf.layout, b_buf.shape, b_st_raw, b_ext_raw)
- if b_is_buf
- else None
- )
- c_info = (
- get_local_region(c_buf.layout, c_buf.shape, c_st_raw, c_ext_raw)
- if c_is_buf
- else None
- )
- if (b_is_buf and b_info is None) or (c_is_buf and c_info is None):
- return None
- dst_local_shape, dst_st, dst_ext = dst_info
- a_local_shape, a_st, a_ext = a_info
- b_local_shape, b_st, b_ext = b_info if b_info else (None, None, None)
- c_local_shape, c_st, c_ext = c_info if c_info else (None, None, None)
- local_total = functools.reduce(operator.mul, dst_ext, 1)
- try:
- if int(local_total) % 2 != 0:
- return None
- except (TypeError, ValueError):
- return None
- n_chunks = int(local_total) // 2
-
- # Four shape combos depending on whether b and c are buffers or scalars,
- # x two scope modes (thread = direct buf indexing, wg = .local(*shape) view).
- # TVMScript can't handle Python closure calls inside the IR body so each
- # combo gets its own @Tx.prim_func.
- if b_is_buf and c_is_buf:
- if not use_view:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- b_idx_a = Tx.meta_var(get_indices(2 * s, b_st, b_ext))
- b_idx_b = Tx.meta_var(get_indices(2 * s + 1, b_st, b_ext))
- c_idx_a = Tx.meta_var(get_indices(2 * s, c_st, c_ext))
- c_idx_b = Tx.meta_var(get_indices(2 * s + 1, c_st, c_ext))
- _fma_f32x2_adapter(
- a_buf[tuple(a_idx_a)],
- a_buf[tuple(a_idx_b)],
- b_buf[tuple(b_idx_a)],
- b_buf[tuple(b_idx_b)],
- c_buf[tuple(c_idx_a)],
- c_buf[tuple(c_idx_b)],
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- a_view = a_buf.local(*a_local_shape)
- b_view = b_buf.local(*b_local_shape)
- c_view = c_buf.local(*c_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- b_idx_a = Tx.meta_var(get_indices(2 * s, b_st, b_ext))
- b_idx_b = Tx.meta_var(get_indices(2 * s + 1, b_st, b_ext))
- c_idx_a = Tx.meta_var(get_indices(2 * s, c_st, c_ext))
- c_idx_b = Tx.meta_var(get_indices(2 * s + 1, c_st, c_ext))
- _fma_f32x2_adapter(
- a_view[tuple(a_idx_a)],
- a_view[tuple(a_idx_b)],
- b_view[tuple(b_idx_a)],
- b_view[tuple(b_idx_b)],
- c_view[tuple(c_idx_a)],
- c_view[tuple(c_idx_b)],
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- if b_is_buf and not c_is_buf:
- if not use_view:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- b_idx_a = Tx.meta_var(get_indices(2 * s, b_st, b_ext))
- b_idx_b = Tx.meta_var(get_indices(2 * s + 1, b_st, b_ext))
- _fma_f32x2_adapter(
- a_buf[tuple(a_idx_a)],
- a_buf[tuple(a_idx_b)],
- b_buf[tuple(b_idx_a)],
- b_buf[tuple(b_idx_b)],
- c_scalar,
- c_scalar,
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- a_view = a_buf.local(*a_local_shape)
- b_view = b_buf.local(*b_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- b_idx_a = Tx.meta_var(get_indices(2 * s, b_st, b_ext))
- b_idx_b = Tx.meta_var(get_indices(2 * s + 1, b_st, b_ext))
- _fma_f32x2_adapter(
- a_view[tuple(a_idx_a)],
- a_view[tuple(a_idx_b)],
- b_view[tuple(b_idx_a)],
- b_view[tuple(b_idx_b)],
- c_scalar,
- c_scalar,
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- if not b_is_buf and c_is_buf:
- if not use_view:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- c_idx_a = Tx.meta_var(get_indices(2 * s, c_st, c_ext))
- c_idx_b = Tx.meta_var(get_indices(2 * s + 1, c_st, c_ext))
- _fma_f32x2_adapter(
- a_buf[tuple(a_idx_a)],
- a_buf[tuple(a_idx_b)],
- b_scalar,
- b_scalar,
- c_buf[tuple(c_idx_a)],
- c_buf[tuple(c_idx_b)],
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- a_view = a_buf.local(*a_local_shape)
- c_view = c_buf.local(*c_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- c_idx_a = Tx.meta_var(get_indices(2 * s, c_st, c_ext))
- c_idx_b = Tx.meta_var(get_indices(2 * s + 1, c_st, c_ext))
- _fma_f32x2_adapter(
- a_view[tuple(a_idx_a)],
- a_view[tuple(a_idx_b)],
- b_scalar,
- b_scalar,
- c_view[tuple(c_idx_a)],
- c_view[tuple(c_idx_b)],
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- # Both b and c scalar
- if not use_view:
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- for s in Tx.serial(0, n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- _fma_f32x2_adapter(
- a_buf[tuple(a_idx_a)],
- a_buf[tuple(a_idx_b)],
- b_scalar,
- b_scalar,
- c_scalar,
- c_scalar,
- Tx.address_of(dst[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- @Tx.prim_func(check_well_formed=False)
- def impl():
- with Tx.thread():
- dst_view = dst.local(*dst_local_shape)
- a_view = a_buf.local(*a_local_shape)
- for s in Tx.unroll(n_chunks):
- dst_idx = Tx.meta_var(get_indices(2 * s, dst_st, dst_ext))
- a_idx_a = Tx.meta_var(get_indices(2 * s, a_st, a_ext))
- a_idx_b = Tx.meta_var(get_indices(2 * s + 1, a_st, a_ext))
- _fma_f32x2_adapter(
- a_view[tuple(a_idx_a)],
- a_view[tuple(a_idx_b)],
- b_scalar,
- b_scalar,
- c_scalar,
- c_scalar,
- Tx.address_of(dst_view[tuple(dst_idx)]),
- rounding_mode=rm,
- )
-
- return impl
-
- return factory
-
-
-# -----------------------------------------------------------------------------
-# Registry: one table, no per-arity buckets.
-# -----------------------------------------------------------------------------
-ALL_OPS: dict[str, OpSpec] = {
- "zero": OpSpec(
- name="zero", parse=_parse_unary, compute=_compute_zero, check_extras=_check_unary_extras
- ),
- "fill": OpSpec(
- name="fill", parse=_parse_unary, compute=_compute_fill, check_extras=_check_unary_extras
- ),
- "reciprocal": OpSpec(
- name="reciprocal",
- parse=_parse_unary,
- compute=_compute_reciprocal,
- check_extras=_check_unary_extras,
- ),
- "sqrt": OpSpec(
- name="sqrt",
- parse=_parse_unary,
- compute=_unary_with_bias_scale(Tx.sqrt),
- check_extras=_check_unary_extras,
- ),
- "exp": OpSpec(
- name="exp",
- parse=_parse_unary,
- compute=_unary_with_bias_scale(Tx.exp),
- check_extras=_check_unary_extras,
- ),
- "exp2": OpSpec(
- name="exp2",
- parse=_parse_unary,
- compute=_unary_with_bias_scale(Tx.exp2),
- check_extras=_check_unary_extras,
- ),
- "silu": OpSpec(
- name="silu",
- parse=_parse_unary,
- compute=_compute_silu,
- check_extras=_check_unary_extras,
- ),
- "add": OpSpec(
- name="add",
- parse=_parse_binary_for("add"),
- compute=_compute_add,
- vec_emit_factory=_make_binary_packed_f32x2_factory("add"),
- ),
- "sub": OpSpec(
- name="sub",
- parse=_parse_binary_for("sub"),
- compute=_compute_sub,
- vec_emit_factory=_make_binary_packed_f32x2_factory("sub"),
- ),
- "mul": OpSpec(
- name="mul",
- parse=_parse_binary_for("mul"),
- compute=_compute_mul,
- vec_emit_factory=_make_binary_packed_f32x2_factory("mul"),
- ),
- "fdiv": OpSpec(name="fdiv", parse=_parse_binary_for("fdiv"), compute=_compute_fdiv),
- "cast": OpSpec(
- name="cast",
- parse=_parse_cast,
- compute=_compute_cast,
- vec_emit_factory=_make_cast_vec2_factory(),
- ),
- "fma": OpSpec(
- name="fma",
- parse=_parse_fma,
- compute=_compute_fma,
- vec_emit_factory=_make_fma_packed_f32x2_factory(),
- ),
-}
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/smem.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/smem.py
new file mode 100644
index 0000000000..2b3fa1acfe
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/smem.py
@@ -0,0 +1,264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Elementwise dispatch when all operands live in ``shared*``.
+
+Mirrors ``cuda/copy/gmem_smem.py``: no operand carries a per-thread partition,
+so partition is *synthesized* from ``sctx.intra`` (``thread_cnt = ∏ intra``).
+Each thread takes ``ceildiv(total, vec_chunk * thread_cnt)`` strided chunks.
+
+The shared buffers are indexed multi-dim via ``get_indices(fused, dst_st,
+dst_ext)`` and the buffer's own layout resolves to physical addresses at
+codegen time. Packed-vec emit requires the innermost dim to have stride 1
+(non-swizzle slice) so lanes are physically contiguous; checked in
+``_max_layout_vec``.
+"""
+
+from __future__ import annotations
+
+from tvm.runtime import DataType
+from tvm.script import tirx as Tx
+from tvm.tirx import PrimFunc, TilePrimitiveCall
+from tvm.tirx.operator.tile_primitive import DispatchContext
+from tvm.tirx.operator.tile_primitive.dispatcher import fail
+
+from ..common import get_indices, get_st_extent, get_thread_cnt
+from ._common import (
+ _TID_AXIS_FOR_SCOPE,
+ _all_threads_active,
+ _axis_decl,
+ _broadcast_indices,
+ _tensor_shape_of,
+ buffer_regions,
+ compute_dtype_of,
+ emit_scope_sync,
+ fetch_src_value,
+ n_elements,
+ pick_vec_chunk,
+ shape_broadcast_compat,
+)
+
+
+# -----------------------------------------------------------------------------
+# Predicate
+# -----------------------------------------------------------------------------
+def is_smem_ewise(spec):
+ """Predicate factory: dispatch accepted iff all operands in ``shared*``."""
+
+ def check(op_call: TilePrimitiveCall, sctx: DispatchContext) -> tuple[bool, str | None]:
+ if not sctx.is_cuda:
+ return False, "non-cuda target"
+ if sctx.scope_kind not in ("thread", "warp", "warpgroup", "cta"):
+ return False, f"unsupported scope {sctx.scope_kind}"
+ ok, reason = _all_threads_active(sctx)
+ if not ok:
+ return False, reason
+ plan, msg = spec.parse(op_call)
+ if msg is not None or plan is None:
+ return False, msg
+ for br in buffer_regions(plan):
+ if not br.buffer.scope().startswith("shared"):
+ return False, f"operand scope {br.buffer.scope()} != shared*"
+ if br.buffer.layout is None:
+ return False, "shared operand has no layout"
+ if spec.check_extras is not None:
+ ok2, reason2 = spec.check_extras(plan.extras, compute_dtype_of(plan))
+ if not ok2:
+ return False, reason2
+ # NumPy-style right-aligned broadcast: anchor = plan.dst; every src
+ # must be shape-compatible with anchor (extent matches or is 1).
+ anchor_tshape = _tensor_shape_of(plan.dst.region)
+ for s in plan.srcs:
+ if s.buf_region is None:
+ continue
+ src_tshape = _tensor_shape_of(s.buf_region.region)
+ ok_b, reason_b = shape_broadcast_compat(src_tshape, anchor_tshape)
+ if not ok_b:
+ return False, f"shape incompat: {reason_b}"
+ return True, None
+
+ return check
+
+
+# -----------------------------------------------------------------------------
+# vec_chunk selection
+# -----------------------------------------------------------------------------
+def _max_layout_vec(plan, total: int, thread_cnt: int) -> int:
+ """Widest vec_chunk dividing all operands' innermost extents AND
+ ``total / thread_cnt``, within dtype-bit candidates ``{128,64,32,16,8}``."""
+ max_bits = DataType(plan.dst.buffer.dtype).bits
+ for s in plan.srcs:
+ if s.buf_region is not None:
+ max_bits = max(max_bits, DataType(s.buf_region.buffer.dtype).bits)
+ per_thread = total // thread_cnt if thread_cnt > 0 else total
+ if total % thread_cnt != 0:
+ return 1
+
+ inners = [int(plan.dst.region[-1].extent)]
+ for s in plan.srcs:
+ if s.buf_region is None or s.index_fn is not None:
+ continue
+ inners.append(int(s.buf_region.region[-1].extent))
+
+ for cand_bits in (128, 64, 32, 16, 8):
+ n = cand_bits // max_bits
+ if n <= 0:
+ continue
+ if per_thread % n != 0:
+ continue
+ if all(i % n == 0 for i in inners):
+ return n
+ return 1
+
+
+# -----------------------------------------------------------------------------
+# Main entry
+# -----------------------------------------------------------------------------
+def emit_smem(op_call: TilePrimitiveCall, spec, sctx: DispatchContext) -> PrimFunc:
+ plan, msg = spec.parse(op_call)
+ if msg is not None or plan is None:
+ fail(msg or "parse failed")
+
+ # Use cuda/common.py:get_thread_cnt rather than copy/_common.py:_thread_cnt
+ # — the latter computes ``∏ sctx.intra`` which silently returns 0 for
+ # sub-warp counts at cta scope (warpid extent rounds down to 0). The
+ # former reads launch_params["threadIdx.x"].dom.extent and is correct
+ # for all scopes.
+ thread_cnt = get_thread_cnt(sctx)
+ if thread_cnt is None:
+ fail(f"unsupported scope {sctx.scope_kind} for smem emit")
+ thread_cnt = int(thread_cnt)
+ if thread_cnt <= 0:
+ fail(f"non-positive thread_cnt {thread_cnt}")
+ assert "threadIdx.y" not in sctx.launch_params and "threadIdx.z" not in sctx.launch_params, (
+ "smem emit currently assumes 1D threadIdx"
+ )
+
+ total = n_elements(plan.dst)
+ vec_max = _max_layout_vec(plan, total, thread_cnt)
+ vec_chunk, vec_impl = pick_vec_chunk(spec, op_call, sctx, plan, vec_max)
+
+ if vec_impl is not None:
+ return _emit_packed(plan, vec_impl, vec_chunk, total, thread_cnt, sctx)
+ return _emit_scalar(plan, spec, vec_chunk, total, thread_cnt, sctx)
+
+
+def _tid_expr(sctx: DispatchContext):
+ """Per-scope tid expr. ``thread`` scope returns 0; collective scopes use
+ ``_axis_decl`` (Tx.lane_id / Tx.thread_id_in_wg / threadIdx.x)."""
+ if sctx.scope_kind == "thread":
+ return 0
+ axis_name = _TID_AXIS_FOR_SCOPE[sctx.scope_kind]
+ return _axis_decl(axis_name, sctx)
+
+
+# -----------------------------------------------------------------------------
+# Per-lane src index helper (handles broadcast via right-aligned compat)
+# -----------------------------------------------------------------------------
+def _src_lane_indices(src_br, dst_lane_indices, dst_st, dst_ext, vec_chunk, fused0):
+ """Return the per-lane multi-dim index list for ``src_br``.
+
+ If src's region shape matches dst's, fall through to ``get_indices``
+ (same as the legacy non-broadcast path). Otherwise derive each lane's
+ src index from the corresponding dst lane index via right-aligned
+ broadcast compat.
+ """
+ src_st, src_ext = get_st_extent(src_br)
+ if tuple(int(e) for e in src_ext) == tuple(int(e) for e in dst_ext):
+ return [get_indices(fused0 + k, src_st, src_ext) for k in range(vec_chunk)]
+ return [
+ _broadcast_indices(dst_lane_indices[k], dst_st, dst_ext, src_st, src_ext)
+ for k in range(vec_chunk)
+ ]
+
+
+# -----------------------------------------------------------------------------
+# Emit — packed
+# -----------------------------------------------------------------------------
+def _emit_packed(plan, vec_impl, vec_chunk, total, thread_cnt, sctx) -> PrimFunc:
+ extras = plan.extras
+ srcs = plan.srcs
+ dst_buf = plan.dst.buffer
+ dst_st, dst_ext = get_st_extent(plan.dst)
+ sync = emit_scope_sync(sctx.scope_kind)
+ n_outer = (total + vec_chunk * thread_cnt - 1) // (vec_chunk * thread_cnt)
+
+ @Tx.prim_func(check_well_formed=False)
+ def impl():
+ tid = _tid_expr(sctx)
+ for s in Tx.serial(0, n_outer):
+ # First lane's fused index for this thread, this chunk.
+ fused0 = Tx.meta_var(s * vec_chunk * thread_cnt + tid * vec_chunk)
+ # Predicate the call (skip the trailing partial chunk).
+ if fused0 + vec_chunk <= total:
+ dst_lane_indices = Tx.meta_var(
+ [get_indices(fused0 + k, dst_st, dst_ext) for k in range(vec_chunk)]
+ )
+ src_args = Tx.meta_var(
+ [
+ srcs[i].scalar
+ if srcs[i].is_scalar
+ else (
+ srcs[i].buf_region.buffer,
+ _src_lane_indices(
+ srcs[i].buf_region,
+ dst_lane_indices,
+ dst_st,
+ dst_ext,
+ vec_chunk,
+ fused0,
+ ),
+ )
+ for i in range(len(srcs))
+ ]
+ )
+ Tx.evaluate(vec_impl.emit(dst_buf, dst_lane_indices, src_args, extras))
+ sync()
+
+ return impl
+
+
+# -----------------------------------------------------------------------------
+# Emit — scalar fallback
+# -----------------------------------------------------------------------------
+def _emit_scalar(plan, spec, vec_chunk, total, thread_cnt, sctx) -> PrimFunc:
+ extras = plan.extras
+ srcs = plan.srcs
+ dst_buf = plan.dst.buffer
+ dst_st, dst_ext = get_st_extent(plan.dst)
+ dst_dtype = dst_buf.dtype
+ compute = spec.compute_scalar
+ sync = emit_scope_sync(sctx.scope_kind)
+ n_outer = (total + vec_chunk * thread_cnt - 1) // (vec_chunk * thread_cnt)
+
+ @Tx.prim_func(check_well_formed=False)
+ def impl():
+ tid = _tid_expr(sctx)
+ for s in Tx.serial(0, n_outer):
+ for vec in Tx.vectorized(vec_chunk):
+ fused = Tx.meta_var(s * vec_chunk * thread_cnt + tid * vec_chunk + vec)
+ if fused < total:
+ dst_idx = Tx.meta_var(get_indices(fused, dst_st, dst_ext))
+ src_vals = Tx.meta_var(
+ [fetch_src_value(src, fused, dst_idx, dst_st, dst_ext) for src in srcs]
+ )
+ dst_buf[tuple(dst_idx)] = Tx.cast(
+ compute(src_vals, extras, dst_dtype), dst_dtype
+ )
+ sync()
+
+ return impl
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/__init__.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/__init__.py
new file mode 100644
index 0000000000..6c1dd6bdc0
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/__init__.py
@@ -0,0 +1,40 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Packed-vector emit functions for elementwise ops.
+
+Each module here exposes one or more ``VecImpl`` instances that an ``OpSpec``
+(in ``ops/``) attaches to its ``vec_impls`` list. ``reg.py``/``smem.py`` then
+pick the widest matching one at dispatch time, mirroring how copy picks
+``copy_{Nb}`` from a menu.
+
+VecImpl emit contract:
+ emit(dst_buf, dst_lane_indices, src_args, extras) -> PrimExpr
+
+ * dst_buf: Buffer
+ * dst_lane_indices: list[list[Expr]] of length ``vec_len``; each entry is the
+ multi-dim indices for one lane (precomputed by schedule).
+ * src_args[i]: one of
+ - PrimExpr (scalar src — broadcast across all lanes)
+ - tuple (Buffer, list[list[Expr]] of length ``vec_len``) — buffer src
+ with per-lane indices
+ * extras: dict (rounding_mode, etc.)
+
+ Returns the PTX/CUDA call result; the schedule wraps in ``Tx.evaluate`` at
+ the call site. All Python-side shape branching (scalar vs buffer src) happens
+ in this emit function -- collapses the old 4x2 schema.py factory explosion.
+"""
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/binary_f32x2.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/binary_f32x2.py
new file mode 100644
index 0000000000..d7bf422acd
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/binary_f32x2.py
@@ -0,0 +1,96 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Packed f32x2 VecImpls for binary add/sub/mul on sm_100+.
+
+PTX op family: ``{add,sub,mul}.<rm>.ftz.f32x2``. Each call processes 2 f32s
+per operand. The old ``_make_binary_packed_f32x2_factory`` (240+ lines, 8
+``@Tx.prim_func`` shape combos per op) collapses to one ``emit`` per op
+because operand-shape branching is now Python-level (outside any
+``@Tx.prim_func``).
+"""
+
+from __future__ import annotations
+
+from tvm.ir.expr import PrimExpr
+from tvm.script import tirx as Tx
+
+from ..ops import VecImpl
+
+
+def _lane(arg, k):
+ """Read lane ``k`` of one operand argument.
+
+ arg is either a scalar Expr (broadcast) or ``(Buffer, lane_indices)``.
+ """
+ if isinstance(arg, tuple):
+ buf, lane_indices = arg
+ return buf[tuple(lane_indices[k])]
+ return arg
+
+
+def _f32x2_applies(op_name):
+ """Predicate: f32 dst+srcs, sm_100+, no broadcasting srcs, two srcs."""
+
+ def applies(op_call, sctx, plan):
+ from ...common import sm_version_ok
+
+ if plan.dst.buffer.dtype != "float32":
+ return False, "dst dtype not f32"
+ if not sm_version_ok(op_call, sctx, min_version=100)[0]:
+ return False, "sm version < 100"
+ if len(plan.srcs) != 2:
+ return False, "binary requires 2 srcs"
+ for s in plan.srcs:
+ if s.is_scalar:
+ if s.scalar.dtype != "float32":
+ return False, "scalar src dtype not f32"
+ else:
+ if s.buf_region.buffer.dtype != "float32":
+ return False, "buffer src dtype not f32"
+ if s.index_fn is not None:
+ return False, "broadcasting src not supported by f32x2 packed"
+ return True, None
+
+ return applies
+
+
+def _emit_binary_f32x2_for(op_name):
+ op_func = getattr(Tx.ptx, f"{op_name}_f32x2")
+
+ def emit(dst_buf, dst_lane_indices, src_args, extras) -> PrimExpr:
+ a_arg, b_arg = src_args
+ rm = extras.get("rounding_mode", "rz")
+ return op_func(
+ Tx.address_of(dst_buf[tuple(dst_lane_indices[0])]),
+ Tx.cuda.make_float2(_lane(a_arg, 0), _lane(a_arg, 1)),
+ Tx.cuda.make_float2(_lane(b_arg, 0), _lane(b_arg, 1)),
+ rounding=rm,
+ ftz=True,
+ )
+
+ return emit
+
+
+BINARY_F32X2_IMPLS: dict[str, VecImpl] = {
+ name: VecImpl(
+ vec_len=2,
+ applies=_f32x2_applies(name),
+ emit=_emit_binary_f32x2_for(name),
+ )
+ for name in ("add", "sub", "mul")
+}
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/cast_vec2.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/cast_vec2.py
new file mode 100644
index 0000000000..5bd7c5a34f
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/cast_vec2.py
@@ -0,0 +1,89 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Packed vec_len=2 cast via CUDA pair intrinsics.
+
+Each supported (src_dtype, dst_dtype) pair has a CUDA builtin that converts a
+packed-2 source to a packed-2 destination in one instruction
+(e.g. ``__float22half2_rn``). The intrinsic takes pointers to the first
+element of each packed pair on either side.
+"""
+
+from __future__ import annotations
+
+from tvm.ir.expr import PrimExpr
+from tvm.script import tirx as Tx
+
+from ..ops import VecImpl
+
+_VEC2_CAST_INTRINSICS = {
+ ("float32", "float16"): "__float22half2_rn",
+ ("float16", "float32"): "__half22float2",
+ ("bfloat16", "float32"): "__bfloat1622float2",
+ ("float32", "bfloat16"): "__float22bfloat162_rn",
+}
+_DTYPE_X2_NAME = {"float32": "float2", "float16": "half2", "bfloat16": "nv_bfloat162"}
+
+
+def _intrinsic_name(src_dtype, dst_dtype):
+ return f"tvm_builtin_cast_{src_dtype}x2_{dst_dtype}x2"
+
+
+def _intrinsic_source(src_dtype, dst_dtype):
+ intrinsic = _VEC2_CAST_INTRINSICS[(src_dtype, dst_dtype)]
+ return (
+ f"\n__forceinline__ __device__ void {_intrinsic_name(src_dtype, dst_dtype)}"
+ f"(void* dst, void* src) {{\n"
+ f" (({_DTYPE_X2_NAME[dst_dtype]}*)dst)[0] = "
+ f"{intrinsic}((({_DTYPE_X2_NAME[src_dtype]}*)src)[0]);\n"
+ "}\n"
+ )
+
+
+def _cast_vec2_applies(op_call, sctx, plan):
+ if len(plan.srcs) != 1 or plan.srcs[0].is_scalar:
+ return False, "cast requires 1 buffer src"
+ src = plan.srcs[0]
+ if src.index_fn is not None:
+ return False, "broadcasting src not supported by cast vec2"
+ src_dtype = src.buf_region.buffer.dtype
+ dst_dtype = plan.dst.buffer.dtype
+ if (src_dtype, dst_dtype) not in _VEC2_CAST_INTRINSICS:
+ return False, f"no vec2 intrinsic for {src_dtype}->{dst_dtype}"
+ return True, None
+
+
+def _emit_cast_vec2(dst_buf, dst_lane_indices, src_args, extras) -> PrimExpr:
+ src_arg = src_args[0]
+ # cast_vec2 requires buffer src (guarded by applies()).
+ assert isinstance(src_arg, tuple), "cast vec2 src must be a buffer"
+ src_buf, src_lane_indices = src_arg
+ func_name = _intrinsic_name(src_buf.dtype, dst_buf.dtype)
+ source_code = _intrinsic_source(src_buf.dtype, dst_buf.dtype)
+ return Tx.cuda.func_call(
+ func_name,
+ Tx.address_of(dst_buf[tuple(dst_lane_indices[0])]),
+ Tx.address_of(src_buf[tuple(src_lane_indices[0])]),
+ source_code=source_code,
+ )
+
+
+CAST_VEC2_IMPL = VecImpl(
+ vec_len=2,
+ applies=_cast_vec2_applies,
+ emit=_emit_cast_vec2,
+)
diff --git a/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/fma_f32x2.py b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/fma_f32x2.py
new file mode 100644
index 0000000000..3435b9799f
--- /dev/null
+++ b/python/tvm/tirx/operator/tile_primitive/cuda/elementwise/vec_emit/fma_f32x2.py
@@ -0,0 +1,78 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Packed f32x2 VecImpl for FMA on sm_100+.
+
+PTX: ``fma.<rm>.ftz.f32x2 d, a, b, c`` — 2 f32 FMAs per call. Same Python-side
+shape collapse as binary_f32x2.
+"""
+
+from __future__ import annotations
+
+from tvm.ir.expr import PrimExpr
+from tvm.script import tirx as Tx
+
+from ..ops import VecImpl
+from .binary_f32x2 import _lane
+
+
+def _fma_f32x2_applies(op_call, sctx, plan):
+ from ...common import sm_version_ok
+
+ if plan.dst.buffer.dtype != "float32":
+ return False, "dst dtype not f32"
+ if not sm_version_ok(op_call, sctx, min_version=100)[0]:
+ return False, "sm version < 100"
+ if len(plan.srcs) != 3:
+ return False, "fma requires 3 srcs"
+ a, b, c = plan.srcs
+ if a.is_scalar:
+ return False, "fma 'a' must be a buffer (no scalar-a packed FMA)"
+ if a.buf_region.buffer.dtype != "float32":
+ return False, "src a dtype not f32"
+ if a.index_fn is not None:
+ return False, "broadcasting src a not supported"
+ for s in (b, c):
+ if s.is_scalar:
+ if s.scalar.dtype != "float32":
+ return False, "scalar b/c dtype not f32"
+ else:
+ if s.buf_region.buffer.dtype != "float32":
+ return False, "buffer b/c dtype not f32"
+ if s.index_fn is not None:
+ return False, "broadcasting src b/c not supported"
+ return True, None
+
+
+def _emit_fma_f32x2(dst_buf, dst_lane_indices, src_args, extras) -> PrimExpr:
+ a_arg, b_arg, c_arg = src_args
+ rm = extras.get("rounding_mode", "rz")
+ return Tx.ptx.fma_f32x2(
+ Tx.address_of(dst_buf[tuple(dst_lane_indices[0])]),
+ Tx.cuda.make_float2(_lane(a_arg, 0), _lane(a_arg, 1)),
+ Tx.cuda.make_float2(_lane(b_arg, 0), _lane(b_arg, 1)),
+ Tx.cuda.make_float2(_lane(c_arg, 0), _lane(c_arg, 1)),
+ rounding=rm,
+ ftz=True,
+ )
+
+
+FMA_F32X2_IMPL = VecImpl(
+ vec_len=2,
+ applies=_fma_f32x2_applies,
+ emit=_emit_fma_f32x2,
+)
diff --git a/tests/python/tirx/operator/tile_primitive/cuda/copy/test_reg.py b/tests/python/tirx/operator/tile_primitive/cuda/copy/test_reg.py
index 8551ace0c1..b61c93c877 100644
--- a/tests/python/tirx/operator/tile_primitive/cuda/copy/test_reg.py
+++ b/tests/python/tirx/operator/tile_primitive/cuda/copy/test_reg.py
@@ -336,5 +336,89 @@ def test_copy_g2l_l2g_vec_load(task, dtype):
np.testing.assert_allclose(B_ref, B.numpy())
+def test_reg_copy_wg_local_to_swizzled_shared_uses_swizzle_fastpath():
+ """Regression: R→S copy where R has a ``wg_local_layout`` (thread iter
+ ``1 @ tid_in_wg``) must pick the widest vec ``copy_128b`` AND use the
+ swizzle fast path (precomputed ``signed_strides`` + per-iter
+ bit-select), not the per-iter ``swizzle.apply()`` fallback.
+
+ Two distinct bugs this test guards against:
+
+ (1) ``_choose_vec_len`` used to include R-side thread-iter strides in
+ its alignment check. ``wg_local_layout``'s thread iter has stride 1;
+ a vec=8 (16-byte) alignment check on ``1 % 8 != 0`` would reject
+ every wider variant and fall to scalar ``copy_16b``. Thread-axis
+ strides are partition-coord (virtual), not storage-physical, so they
+ must be excluded.
+
+ (2) Even at the widest vec, if the outer loop is a runtime serial
+ (Python ``range`` doesn't actually unroll in TVMScript) the swizzle
+ fast path's per-iter constant-fold can't kick in and the
+ ``tvm_builtin_pointer_offset`` swizzle XOR ends up recomputed every
+ iteration. Loop must be ``Tx.unroll``.
+ """
+ from tvm.tirx.layout import SwizzleLayout, wg_local_layout
+
+ N_THREADS, EPI_N = 128, 64
+ g_shape = (N_THREADS, EPI_N)
+ g_layout = TileLayout(S[g_shape])
+ # 128b swizzle on the SMEM side (per_element=3 ⇒ 8 fp16 atom width).
+ smem_layout = SwizzleLayout(per_element=3, swizzle_len=3, atom_len=3)
+
+ @Tx.prim_func
+ def kernel(A_ptr: Tx.handle, B_ptr: Tx.handle) -> None:
+ A = Tx.match_buffer(A_ptr, g_shape, "float16", layout=g_layout)
+ B = Tx.match_buffer(B_ptr, g_shape, "float16", layout=g_layout)
+
+ Tx.device_entry()
+ Tx.cta_id([1])
+ Tx.thread_id([N_THREADS])
+ tid = Tx.thread_id_in_wg([N_THREADS])
+
+ with Tx.thread():
+ reg = Tx.alloc_buffer(
+ g_shape, "float16", scope="local", layout=wg_local_layout(EPI_N)
+ )
+ smem = Tx.alloc_buffer(g_shape, "float16", scope="shared", layout=smem_layout)
+
+ # Populate the per-thread slice via .local() (decomposes the wg
+ # thread-axis layout into a per-thread 1D view).
+ reg_local = reg.local(EPI_N)
+ for i in Tx.serial(EPI_N):
+ reg_local[i] = A[tid, i]
+ with Tx.warpgroup():
+ Tx.copy(smem, reg)
+ Tx.cuda.cta_sync()
+ for i in Tx.serial(EPI_N):
+ B[tid, i] = smem[tid, i]
+
+ target = tvm.target.Target("cuda")
+ with target:
+ mod = tvm.IRModule({"main": kernel})
+ ex = tvm.compile(mod, target=target, tir_pipeline="tirx")
+ src = ex.mod.imports[0].inspect_source()
+
+ # (1) Widest variant: 8 fp16 elements per call.
+ assert "tvm_builtin_copy_128b" in src, (
+ "expected copy_128b in generated CUDA, alignment check fell back to a narrower variant"
+ )
+ assert "tvm_builtin_copy_16b" not in src, (
+ "scalar copy_16b appeared — vec=8 was wrongly rejected"
+ )
+ # (2) Swizzle fast path fingerprint:
+ # * emit_init allocates a size-N int buffer of "signed strides".
+ # * emit_iter_offset uses bit-select * signed-stride: ``(bit) * v[i]``
+ # where ``bit = (f >> M) & 1``.
+ # The fallback (per-iter ``swizzle.apply(s_off + ds_per_iter)``) has no
+ # such bit-select * signed-stride pattern.
+ import re
+
+ bitsel_pattern = re.findall(r"& 1\) \* v_\d+\[", src)
+ assert bitsel_pattern, (
+ "fast-path bit-select pattern '& 1) * v_<n>[' not found; "
+ "looks like emit_iter_offset's fast path didn't fire."
+ )
+
+
if __name__ == "__main__":
tvm.testing.main()
diff --git a/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_binary.py b/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_binary.py
index 7f8254efe4..8780768f03 100644
--- a/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_binary.py
+++ b/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_binary.py
@@ -396,10 +396,10 @@ def test_binary_op_local_subcta_trivial(exec_scope, rhs_kind, op_type):
),
######### broadcast test #########
(
- (16, 5, 4), # a_shape
- (16, 1, 4), # b_shape
- (16, 5, 4), # res_shape
- 16, # thread_cnt
+ (32, 5, 4), # a_shape
+ (32, 1, 4), # b_shape
+ (32, 5, 4), # res_shape
+ 32, # thread_cnt (≥ warp size so sctx.intra at cta scope models cleanly)
tvm.cuda(0), # dev
),
],
@@ -769,5 +769,80 @@ def test_fma_warpgroup_wg_local_emits_packed_f32x2():
), f"expected packed f32x2 fma PTX, source preview:\n{src[:2000]}"
+# -----------------------------------------------------------------------------
+# Dispatch codegen checks (no GPU runtime — explicit target arch).
+# These complement the existing `*_warpgroup_wg_local_layout` / `*_auto_dispatch`
+# variants by forcing the arch in the Target dict, so the codegen path runs
+# even on hosts where ``Target("cuda")`` cannot detect the GPU.
+# -----------------------------------------------------------------------------
+def test_binary_add_f32_sm100_packed_f32x2_dispatch():
+ """add f32 + all-local → reg.py + add_f32x2 packed (no Tx.vectorized)."""
+ shape = (64, 32)
+ lay = TileLayout(S[shape])
+
+ @Tx.prim_func
+ def k(A_ptr: Tx.handle, B_ptr: Tx.handle) -> None:
+ A = Tx.match_buffer(A_ptr, shape, "float32", layout=lay)
+ B = Tx.match_buffer(B_ptr, shape, "float32", layout=lay)
+ Tx.device_entry()
+ _bx = Tx.cta_id([1])
+ tx = Tx.thread_id([64])
+ with Tx.thread():
+ ra = Tx.alloc_buffer(
+ shape[1:], "float32", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ rb = Tx.alloc_buffer(
+ shape[1:], "float32", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ Tx.copy(ra, A[tx])
+ Tx.copy(rb, B[tx])
+ Tx.add(ra, ra, rb)
+ Tx.copy(A[tx], ra)
+
+ target = tvm.target.Target({"kind": "cuda", "arch": "sm_100a"})
+ with target:
+ mod = tvm.IRModule({"main": k})
+ mod = tvm.compile(mod, target=target, tir_pipeline="tirx")
+ src = mod.mod.imports[0].inspect_source()
+ assert re.search(r"add\.[a-z]+\.ftz\.f32x2", src) or re.search(
+ r"tvm_builtin_ptx_add_packed_", src
+ ), f"expected packed add_f32x2; got:\n{src[:2000]}"
+
+
+def test_binary_add_f16_scalar_fallback_dispatch():
+ """add f16 has no packed VecImpl → reg.py scalar fallback (Tx.vectorized)."""
+ shape = (64, 32)
+ lay = TileLayout(S[shape])
+
+ @Tx.prim_func
+ def k(A_ptr: Tx.handle, B_ptr: Tx.handle) -> None:
+ A = Tx.match_buffer(A_ptr, shape, "float16", layout=lay)
+ B = Tx.match_buffer(B_ptr, shape, "float16", layout=lay)
+ Tx.device_entry()
+ _bx = Tx.cta_id([1])
+ tx = Tx.thread_id([64])
+ with Tx.thread():
+ ra = Tx.alloc_buffer(
+ shape[1:], "float16", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ rb = Tx.alloc_buffer(
+ shape[1:], "float16", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ Tx.copy(ra, A[tx])
+ Tx.copy(rb, B[tx])
+ Tx.add(ra, ra, rb)
+ Tx.copy(A[tx], ra)
+
+ target = tvm.target.Target({"kind": "cuda", "arch": "sm_80"})
+ with target:
+ mod = tvm.IRModule({"main": k})
+ mod = tvm.compile(mod, target=target, tir_pipeline="tirx")
+ src = mod.mod.imports[0].inspect_source()
+ assert "half" in src or "__half" in src, f"expected scalar half add; got:\n{src[:2000]}"
+ assert not re.search(r"add\.[a-z]+\.ftz\.f(32|16)x2", src), (
+ f"unexpected packed f32x2/f16x2 add in scalar-fallback path; got:\n{src[:2000]}"
+ )
+
+
if __name__ == "__main__":
tvm.testing.main()
diff --git a/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_fma.py b/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_fma.py
index e384c633d7..dd6a8a1fdd 100644
--- a/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_fma.py
+++ b/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_fma.py
@@ -328,5 +328,53 @@ def test_fma_warpgroup_wg_local_layout():
tvm.testing.assert_allclose(expected, B_dev.numpy(), atol=1e-5)
+# -----------------------------------------------------------------------------
+# Dispatch codegen check (no GPU runtime — explicit target arch).
+# Complements ``test_fma_warpgroup_wg_local_emits_packed_f32x2`` (which uses
+# the host-detected ``Target("cuda")`` and skips when arch < sm_100).
+# -----------------------------------------------------------------------------
+def test_fma_f32_sm100_packed_f32x2_dispatch():
+ """fma f32 + all-local → reg.py + fma_f32x2 packed (no Tx.vectorized)."""
+ shape = (64, 32)
+ lay = TileLayout(S[shape])
+
+ @Tx.prim_func
+ def k(A_ptr: Tx.handle, B_ptr: Tx.handle, C_ptr: Tx.handle, D_ptr: Tx.handle) -> None:
+ A = Tx.match_buffer(A_ptr, shape, "float32", layout=lay)
+ B = Tx.match_buffer(B_ptr, shape, "float32", layout=lay)
+ C = Tx.match_buffer(C_ptr, shape, "float32", layout=lay)
+ D = Tx.match_buffer(D_ptr, shape, "float32", layout=lay)
+ Tx.device_entry()
+ _bx = Tx.cta_id([1])
+ tx = Tx.thread_id([64])
+ with Tx.thread():
+ ra = Tx.alloc_buffer(
+ shape[1:], "float32", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ rb = Tx.alloc_buffer(
+ shape[1:], "float32", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ rc = Tx.alloc_buffer(
+ shape[1:], "float32", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ rd = Tx.alloc_buffer(
+ shape[1:], "float32", scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ Tx.copy(ra, A[tx])
+ Tx.copy(rb, B[tx])
+ Tx.copy(rc, C[tx])
+ Tx.fma(rd, ra, rb, rc)
+ Tx.copy(D[tx], rd)
+
+ target = tvm.target.Target({"kind": "cuda", "arch": "sm_100a"})
+ with target:
+ mod = tvm.IRModule({"main": k})
+ mod = tvm.compile(mod, target=target, tir_pipeline="tirx")
+ src = mod.mod.imports[0].inspect_source()
+ assert re.search(r"fma\.[a-z]+\.ftz\.f32x2", src) or re.search(
+ r"tvm_builtin_ptx_fma_packed_", src
+ ), f"expected packed fma_f32x2; got:\n{src[:2000]}"
+
+
if __name__ == "__main__":
tvm.testing.main()
diff --git a/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_unary.py b/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_unary.py
index 1082478a77..bd2f6463ef 100644
--- a/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_unary.py
+++ b/tests/python/tirx/operator/tile_primitive/cuda/elementwise/test_unary.py
@@ -14,6 +14,8 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+import re
+
import numpy as np
import pytest
@@ -920,17 +922,14 @@ def test_cast_warpgroup_local_view(A_dtype, B_dtype):
def test_cast_warpgroup_src_layout_to_flat_uses_vec2_intrinsic(A_dtype, B_dtype):
"""Regression: GEMM-epilogue cast pattern must emit the packed vec2 cuda intrinsic.
- Pattern: src has ``wg_local_layout`` (per-thread 1xK row), dst is a flat 1D
- local buffer sliced into K-element chunks. This is the cast call in
- fp16_bf16_gemm.py:204. Before the fix, ``_make_cast_vec2_factory`` bailed
- out at warpgroup scope and ``_emit_sliced`` fell back to a scalar
- ``Tx.cast`` inside ``Tx.vectorized`` — a ~13% perf regression on M=N=K=8192.
+ Pattern: both sides have ``wg_local_layout`` (per-thread 1xK row). dst is
+ allocated per-chunk to keep both operands wg-distributed — the dispatch
+ requires layout-symmetric operands (no flat-vs-wg asymmetry).
"""
from tvm.tirx.layout import wg_local_layout
N_THREADS, LOCAL_LEN, N_CHUNKS = 128, 8, 4
- DST_LEN = LOCAL_LEN * N_CHUNKS # flat 1D dst buffer length
- g_shape = (N_THREADS, DST_LEN)
+ g_shape = (N_THREADS, LOCAL_LEN * N_CHUNKS)
g_layout = TileLayout(S[g_shape])
dev = tvm.cuda(0)
@@ -952,13 +951,9 @@ def test_cast_warpgroup_src_layout_to_flat_uses_vec2_intrinsic(A_dtype, B_dtype)
tid = Tx.thread_id_in_wg([N_THREADS])
with Tx.thread():
- # Flat per-thread dst buffer (no layout) — like Dreg_16b in the GEMM.
- Dreg_dst = Tx.alloc_local((DST_LEN,), B_dtype)
for no in Tx.unroll(N_CHUNKS):
- # Flat per-thread src, populate by direct indexing, then view
- # with wg_local_layout for the cast (same .view() trick used
- # by test_cast_warpgroup_local_view above).
reg_src = Tx.alloc_buffer((LOCAL_LEN,), A_dtype, scope="local")
+ Dreg_chunk = Tx.alloc_buffer((LOCAL_LEN,), B_dtype, scope="local")
with Tx.thread():
for i in Tx.serial(LOCAL_LEN):
reg_src[i] = A[tid, no * LOCAL_LEN + i]
@@ -966,9 +961,13 @@ def test_cast_warpgroup_src_layout_to_flat_uses_vec2_intrinsic(A_dtype, B_dtype)
reg_src_view = reg_src.view(
N_THREADS, LOCAL_LEN, layout=wg_local_layout(LOCAL_LEN)
)
- Tx.cast(Dreg_dst[no * LOCAL_LEN : no * LOCAL_LEN + LOCAL_LEN], reg_src_view)
- for i in Tx.serial(DST_LEN):
- B[tid, i] = Dreg_dst[i]
+ Dreg_chunk_view = Dreg_chunk.view(
+ N_THREADS, LOCAL_LEN, layout=wg_local_layout(LOCAL_LEN)
+ )
+ Tx.cast(Dreg_chunk_view, reg_src_view)
+ with Tx.thread():
+ for i in Tx.serial(LOCAL_LEN):
+ B[tid, no * LOCAL_LEN + i] = Dreg_chunk[i]
# fmt: on
target = tvm.target.Target("cuda")
@@ -1264,9 +1263,82 @@ def test_cast_validate_extent_mismatch_rejected():
target = tvm.target.Target("cuda")
with target:
mod = tvm.IRModule({"main": kernel})
- with pytest.raises(Exception, match="tile_local_valid|layout signature mismatch"):
+ with pytest.raises(
+ Exception, match="tile_local_valid|layout signature mismatch|thread part mismatch"
+ ):
tvm.compile(mod, target=target, tir_pipeline="tirx")
+# -----------------------------------------------------------------------------
+# Dispatch codegen checks (no GPU runtime — explicit target arch).
+# -----------------------------------------------------------------------------
+def test_unary_exp_f16_shared_scalar_fallback_dispatch():
+ """exp f16 + shared cta → smem.py + scalar (Tx.vectorized) — no exp packed."""
+ shape = (64, 32)
+ lay = TileLayout(S[shape])
+
+ @Tx.prim_func
+ def k(A_ptr: Tx.handle, B_ptr: Tx.handle) -> None:
+ A = Tx.match_buffer(A_ptr, shape, "float16", layout=lay)
+ B = Tx.match_buffer(B_ptr, shape, "float16", layout=lay)
+ Tx.device_entry()
+ _bx = Tx.cta_id([1])
+ _tx = Tx.thread_id([64])
+ with Tx.thread():
+ sa = Tx.alloc_buffer(shape, "float16", scope="shared", layout=lay)
+ sb = Tx.alloc_buffer(shape, "float16", scope="shared", layout=lay)
+ Tx.copy(sa, A)
+ with Tx.cta():
+ Tx.exp(sb, sa)
+ Tx.copy(B, sb)
+
+ target = tvm.target.Target({"kind": "cuda", "arch": "sm_80"})
+ with target:
+ mod = tvm.IRModule({"main": k})
+ mod = tvm.compile(mod, target=target, tir_pipeline="tirx")
+ src = mod.mod.imports[0].inspect_source()
+ assert re.search(r"hexp|exp\(|expf", src), f"expected scalar exp; got:\n{src[:2000]}"
+
+
+@pytest.mark.parametrize(
+ "src_dtype,dst_dtype,intrinsic",
+ [
+ ("float32", "float16", "__float22half2_rn"),
+ ("float16", "float32", "__half22float2"),
+ ],
+)
+def test_cast_vec2_packed_dispatch(src_dtype, dst_dtype, intrinsic):
+ """cast (f32↔f16) + all-local → reg.py + packed pair intrinsic."""
+ shape = (64, 32)
+ lay = TileLayout(S[shape])
+
+ @Tx.prim_func
+ def k(A_ptr: Tx.handle, B_ptr: Tx.handle) -> None:
+ A = Tx.match_buffer(A_ptr, shape, src_dtype, layout=lay)
+ B = Tx.match_buffer(B_ptr, shape, dst_dtype, layout=lay)
+ Tx.device_entry()
+ _bx = Tx.cta_id([1])
+ tx = Tx.thread_id([64])
+ with Tx.thread():
+ ra = Tx.alloc_buffer(
+ shape[1:], src_dtype, scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ rb = Tx.alloc_buffer(
+ shape[1:], dst_dtype, scope="local", layout=TileLayout(S[shape[1:]])
+ )
+ Tx.copy(ra, A[tx])
+ Tx.cast(rb, ra)
+ Tx.copy(B[tx], rb)
+
+ target = tvm.target.Target({"kind": "cuda", "arch": "sm_80"})
+ with target:
+ mod = tvm.IRModule({"main": k})
+ mod = tvm.compile(mod, target=target, tir_pipeline="tirx")
+ src = mod.mod.imports[0].inspect_source()
+ assert re.search(
+ rf"{re.escape(intrinsic)}|tvm_builtin_cast_{src_dtype}x2_{dst_dtype}x2", src
+ ), f"expected packed vec2 cast {intrinsic}; got:\n{src[:2000]}"
+
+
if __name__ == "__main__":
tvm.testing.main()