feat(inductor): add TE ComboKernel support

Co-authored-by: rmch<chenruimin2@huawei.com>



# message auto-generated for no-merge-commit merge:
!47085 merge te-combo-kernel into master

feat(inductor): add TE ComboKernel support

Created-by: rmch
Commit-by: rmch
Merged-by: ascend-robot
Description: ## 变更摘要

完成 TE 后端 ComboKernel 适配第 5-9 步,将满足约束的多个 Triton Experimental pointwise kernel 合并为一次 TEComboKernel 调用,减少 kernel launch 次数并保持不满足条件时的原有 fallback 行为。

### 主要改动

- 新增 `TEComboKernel` 和 `TEComboSubKernel` codegen,共享 `XBLOCK=256`,按成员 kernel 的 block 数和前缀和执行分组 dispatch。
- 增加 `te_combo_meta` 元数据和 launcher grid 处理,支持一次 launch 内按 combo slot 分发成员 kernel。
- 增加 TE 专用准入检查:当前阶段仅合并静态、连续、同 shape、同 dtype、pointwise-only 的 kernel;不满足条件时回退到普通 kernel。
- 修复 combo fallback 生命周期,保留独立 fallback kernel 仍需要的 buffer,待所有 combo source 生成和注册成功后再提交 `mark_run`、buffer removal 等状态更新。
- 为 combo 成员变量和共享 tile constexpr 名称增加 slot 后缀,避免多个成员之间发生命名冲突。
- 保持 ComboKernel 与现有 `foreach`/Triton Experimental 调度路径兼容,并补充配置开关。

## 测试

- ComboKernel 定向测试:`4 passed`
- TE Triton Experimental 完整测试目录:`39 passed`
- 变更 Python 文件 `py_compile` 通过
- `git diff --check` 通过
- Ascend 910B3 数值验证通过:1024、10001、0、1、255、256、257 元素场景;combo disabled 和混合 dtype fallback 场景均正确。

## 当前边界

- 当前 phase-one 仅覆盖静态 contiguous、同 shape、同 dtype 的 pointwise kernel。
- 动态 shape、不同 dtype/shape、非 pointwise 操作和不满足 ABI/资源约束的场景继续使用普通 kernel 或显式 fallback。

**关联 issue:**
Fixes https://gitcode.com/Ascend/pytorch/issues/5093

**RFC设计文档:**
https://gitcode.com/Ascend/pytorch/issues/5325


See merge request: Ascend/pytorch!47085
This commit is contained in:
rmch
2026-10-10 15:45:27 +08:00
committed by ascend-robot
parent 472321bf2e
commit 3e0639707b
9 changed files with 782 additions and 21 deletions
@@ -0,0 +1,227 @@
import os
import unittest
os.environ.setdefault("TORCHINDUCTOR_NPU_BACKEND", "triton_experimental")
import torch
from torch._inductor import config as inductor_config
from torch._inductor.utils import run_and_get_code
from torch.testing._internal.common_utils import TestCase, run_tests
import torch_npu # noqa: F401
import torch_npu._inductor # noqa: F401
from torch_npu._inductor.triton_experimental import config as te_config
def pointwise_pair(x, y):
return x.relu(), y.sigmoid()
class TestComboTileAllocation(TestCase):
def test_core_ranges_cover_each_tile_once(self):
for cores in (40, 48):
for tiles in (0, 1, 2, cores - 1, cores, cores + 1, 2 * cores + 1):
covered = []
q, r = divmod(tiles, cores)
for core in range(cores):
count = q + (core < r)
base = core * q + min(core, r)
covered.extend(range(base, base + count))
self.assertEqual(covered, list(range(tiles)))
def test_member_prefixes_with_empty_members(self):
counts = (0, 3, 0, 5)
offsets = [0]
for count in counts:
offsets.append(offsets[-1] + count)
assigned = []
for tile in range(offsets[-1]):
member = next(i for i, end in enumerate(offsets[1:]) if tile < end)
assigned.append((member, tile - offsets[member]))
self.assertEqual(assigned, [(1, i) for i in range(3)] + [(3, i) for i in range(5)])
@unittest.skipUnless(torch.npu.is_available(), "requires an NPU")
class TestTEComboKernel(TestCase):
def setUp(self):
super().setUp()
torch._dynamo.reset()
def tearDown(self):
torch._dynamo.reset()
super().tearDown()
def compile_function(self, fn, *args, enabled=True, dynamic=False):
with (
inductor_config.patch(combo_kernels=True),
te_config.patch(enable_te_combo_kernel=enabled),
):
compiled = torch.compile(
fn,
dynamic=dynamic,
options={"npu_backend": "triton_experimental"},
)
result, codes = run_and_get_code(compiled, *args)
return result, "\n".join(codes)
def compile_pair(self, x, y, enabled=True):
return self.compile_function(pointwise_pair, x, y, enabled=enabled)
def assert_combo_result(self, fn, *args, expected_combo):
# Keep an owned copy: the NPU allocator may reuse an eager output
# buffer while the compiled variant is being materialized.
eager = tuple(value.clone() for value in fn(*args))
separate, separate_code = self.compile_function(fn, *args, enabled=False)
# Materialize before the second compilation can recycle NPU buffers.
separate = tuple(value.clone() for value in separate)
actual, code = self.compile_function(fn, *args)
actual = tuple(value.clone() for value in actual)
torch.testing.assert_close(separate, eager)
torch.testing.assert_close(actual, eager)
self.assertNotIn("te_combo_meta", separate_code)
self.assertEqual("te_combo_meta" in code, expected_combo)
return code
def test_single_launch_and_suffixed_headers(self):
x = torch.randn(10001, device="npu")
y = torch.randn(10001, device="npu")
expected = pointwise_pair(x, y)
actual, code = self.compile_pair(x, y)
for got, want in zip(actual, expected):
torch.testing.assert_close(got, want)
self.assertEqual(code.count("@npu_triton_heuristics.foreach"), 1)
self.assertEqual(code.count(".run("), 1)
self.assertIn("te_combo_meta", code)
for slot in (0, 1):
for stem in (rf"x\d+_{slot}numel", rf"real_block_x\d+_{slot}", rf"x\d+_{slot}_blocks"):
self.assertRegex(code, rf"\b{stem}\s*:\s*tl\.constexpr\s*=")
self.assertNotIn("@triton_heuristics.foreach", code)
def test_disabled_and_mixed_dtype_fall_back(self):
x = torch.randn(1025, device="npu")
y = torch.randn(1025, device="npu")
for enabled, second in ((False, y), (True, y.half())):
with self.subTest(enabled=enabled, dtype=second.dtype):
actual, code = self.compile_pair(x, second, enabled=enabled)
for got, want in zip(actual, pointwise_pair(x, second)):
torch.testing.assert_close(got, want)
self.assertNotIn("te_combo_meta", code)
self.assertEqual(code.count(".run("), 2)
def test_pointwise_ops_and_dtypes(self):
def fn(x, y):
return x + 3, y * 2
for dtype in (torch.float16, torch.bfloat16, torch.float32, torch.int32):
with self.subTest(dtype=dtype):
if dtype == torch.int32:
x = torch.randint(-10, 10, (1025,), device="npu", dtype=dtype)
y = torch.randint(-10, 10, (1025,), device="npu", dtype=dtype)
else:
x = torch.randn(1025, device="npu", dtype=dtype)
y = torch.randn(1025, device="npu", dtype=dtype)
code = self.assert_combo_result(fn, x, y, expected_combo=True)
self.assertEqual(code.count(".run("), 1)
def test_tile_boundaries(self):
for size in (0, 1, 255, 256, 257, 10001):
with self.subTest(size=size):
x = torch.randn(size, device="npu")
y = torch.randn(size, device="npu")
code = self.assert_combo_result(
pointwise_pair, x, y, expected_combo=size > 0
)
self.assertEqual(code.count(".run("), 0 if size == 0 else 1)
x = torch.randn((), device="npu")
y = torch.randn((), device="npu")
code = self.assert_combo_result(pointwise_pair, x, y, expected_combo=True)
self.assertEqual(code.count(".run("), 1)
self.assertIn("'combo_tile_counts': [1, 1]", code)
def test_three_members_and_shared_readonly_input(self):
def fn(x, y, z):
return x.relu(), y.sigmoid(), z.tanh()
inputs = tuple(torch.randn(1025, device="npu") for _ in range(3))
code = self.assert_combo_result(fn, *inputs, expected_combo=True)
self.assertEqual(code.count(".run("), 1)
def shared(x):
return x.relu(), x.sigmoid()
# The scheduler fuses these two consumers into one ordinary pointwise
# node before ComboKernel admission, so there is no combo candidate.
code = self.assert_combo_result(shared, inputs[0], expected_combo=False)
self.assertEqual(code.count(".run("), 1)
def test_foreach_add_and_unary(self):
def binary(a, b, c, d):
return torch._foreach_add([a, b], [c, d])
def unary(a, b):
return torch._foreach_abs([a, b])
inputs = tuple(torch.randn(1025, device="npu") for _ in range(4))
# TE phase one admits pointwise scheduler nodes only. Foreach nodes
# remain correct through the regular fallback path until a dedicated
# foreach lowering is enabled.
for fn, fn_inputs in ((binary, inputs), (unary, inputs[:2])):
code = self.assert_combo_result(fn, *fn_inputs, expected_combo=False)
self.assertNotIn("npu_triton_heuristics.foreach", code)
def test_mixed_shapes_and_noncontiguous_fall_back(self):
x = torch.randn(1025, device="npu")
y = torch.randn(513, device="npu")
self.assert_combo_result(pointwise_pair, x, y, expected_combo=False)
a = torch.randn(16, 16, device="npu").t()
b = torch.randn(16, 16, device="npu").t()
self.assert_combo_result(pointwise_pair, a, b, expected_combo=False)
def test_int64_falls_back(self):
x = torch.randint(-10, 10, (1025,), device="npu", dtype=torch.int64)
y = torch.randint(-10, 10, (1025,), device="npu", dtype=torch.int64)
code = self.assert_combo_result(pointwise_pair, x, y, expected_combo=False)
self.assertEqual(code.count(".run("), 2)
def test_member_limit_falls_back(self):
def three_members(x, y, z):
return x.relu(), y.sigmoid(), z.tanh()
inputs = tuple(torch.randn(1025, device="npu") for _ in range(3))
with te_config.patch(te_combo_max_members=2):
code = self.assert_combo_result(
three_members, *inputs, expected_combo=False
)
self.assertEqual(code.count(".run("), 3)
def test_combo_switch_restores_standalone_codegen(self):
x = torch.randn(1025, device="npu")
y = torch.randn(1025, device="npu")
for enabled in (False, True, False):
with self.subTest(enabled=enabled):
torch._dynamo.reset()
actual, code = self.compile_pair(x, y, enabled=enabled)
torch.testing.assert_close(actual, pointwise_pair(x, y))
self.assertEqual("te_combo_meta" in code, enabled)
self.assertEqual(code.count(".run("), 1 if enabled else 2)
def test_reduction_and_dynamic_shapes_fall_back(self):
def reduction(x, y):
return x.sum(dim=1), y.relu()
x = torch.randn(32, 16, device="npu")
y = torch.randn(32, 16, device="npu")
self.assert_combo_result(reduction, x, y, expected_combo=False)
a = torch.randn(1025, device="npu")
b = torch.randn(1025, device="npu")
eager = tuple(value.clone() for value in pointwise_pair(a, b))
actual, code = self.compile_function(pointwise_pair, a, b, dynamic=True)
torch.testing.assert_close(actual, eager)
self.assertNotIn("te_combo_meta", code)
if __name__ == "__main__":
run_tests()
@@ -70,6 +70,24 @@ class TestLauncherCodegen(unittest.TestCase):
self.assertEqual(calls, [(expected, 1, 1, 17)])
self.assertNotIn("_grid_cache", launcher.__globals__)
def test_te_combo_uses_full_core_grid(self):
meta = {
"te_combo_meta": {"combo_num_kernels": 2},
"npu_num_x_nodes": 1,
"npu_dispatch_recipe": {
"lines": ["blocks = (xnumel + XBLOCK - 1) // XBLOCK"],
"factors": ["blocks"],
},
}
launcher, calls = self.make_launcher(
["xnumel", "ynumel"], meta,
blocks={"XBLOCK": 128}, is_a5=True, num_cores=48,
)
launcher(1, 10000, stream=17)
launcher(10000, 1, stream=19)
self.assertEqual([call[0] for call in calls], [48, 48])
self.assertNotIn("_grid_cache", launcher.__globals__)
def test_non_linearize_reduction_uses_exact_grid(self):
# The same shape as upstream's non-linearize sum regression: 64*128
# output rows. A physical-core cap misses rows; overlaunch can overread.
@@ -762,6 +762,10 @@ def _codegen_header_npu_for_tree(kernel, tree, code, outer_blocks=None):
_bal_sizes = {n.name: _size_hint(n) for n in _bal_nodes}
if _bal_nodes:
pfx = tree.prefix
# A combo keeps tree.prefix unchanged for axis semantics, but each
# member needs distinct greedy-budget constexprs in the shared body.
combo_slot = getattr(kernel, "_combo_num", None)
shared_pfx = f"{pfx}_{combo_slot}" if combo_slot is not None else pfx
# Most-contiguous first: by input-stride rank when the priority gate fired
# (reduction, >=2 free axes; T5 position-bias 91x), else by output-divisor
# hint (pointwise). No-hint axes sort last.
@@ -778,11 +782,11 @@ def _codegen_header_npu_for_tree(kernel, tree, code, outer_blocks=None):
rem_ref = _bal_budget
else:
# rem_i = rem_{i-1} // tile_{i-1}, floored to >=1.
rem_name = f"{pfx}_g_rem{idx}"
rem_name = f"{shared_pfx}_g_rem{idx}"
rem_raw = f"({prev_rem_ref}) // {prev_tile_name}"
_balanced_shared.append((rem_name, f"({rem_raw}) if ({rem_raw}) > 1 else 1"))
rem_ref = rem_name
tile_name = f"{pfx}_g_tile{idx}"
tile_name = f"{shared_pfx}_g_tile{idx}"
if s is None:
# Unknown size: eat all remaining budget (mask trims the tail).
tile_expr = f"({rem_ref})"
@@ -2315,6 +2315,10 @@ class NPUTritonKernel(TritonKernel):
force_linearize = True
self._npu_linearize: bool = bool(triton_codegen_linearize) or force_linearize
super().__init__(*args, **kwargs)
# Set by TEComboSubKernel after construction; ordinary kernels leave
# these unset and keep the existing dispatch behavior.
self._combo_num: Optional[int] = None
self._combo_local_tile: Optional[str] = None
self._axis_split_subs: Dict[sympy.Symbol, sympy.Expr] = {}
# A reduction pass is created at the same boundary where codegen_body()
# flushes a reduction loop. Alias expressions are attached later, after
@@ -4050,6 +4054,44 @@ class NPUTritonKernel(TritonKernel):
return None
return {"lines": lines, "factors": factors}
def _npu_free_blocks_names(self):
"""The ``<node>_blocks`` variable names that make up this kernel's tile count.
One entry per free (non-reduction, non-loop) x-tree node, in tree order.
Auxiliary axes -- a node whose length is the product of other free nodes'
lengths, i.e. a flattened view -- are excluded via ``tree_node_mapping`` so
they don't double-count. The product of these is the kernel's total tile
count, and the same list is what the combo path needs per sub-kernel
(``num_blocks_<k>``), so it is factored out of the dispatch prologue.
"""
all_blocks_names = []
for tree in self.range_trees:
if not tree.is_reduction and not tree.is_loop:
tree_node_mapping = getattr(tree, 'tree_node_mapping', {})
all_blocks_names.extend(
f"{n.name}_blocks" for n in tree.nodes.values()
if n.name not in tree_node_mapping
)
return all_blocks_names
def _npu_emit_total_blocks(self, code, var_name="total_blocks"):
"""Emit ``<var_name> = a * b * ...`` and return the name/expr of the product.
Returns ``var_name`` when a statement was emitted, a bare ``<node>_blocks``
name when there is exactly one factor (no statement needed), and ``"1"``
when there are none. Normal kernels keep ``var_name="total_blocks"`` so the
generated dispatch is byte-identical; the combo path passes
``"num_blocks_<k>"`` to get one tile count per sub-kernel.
"""
all_blocks_names = self._npu_free_blocks_names()
if not all_blocks_names:
return "1"
expr = " * ".join(all_blocks_names)
if len(all_blocks_names) > 1:
code.writeline(f"{var_name} = {expr}")
return var_name
return expr
def _codegen_npu_dispatch_prologue(self, code):
"""Emit the per-kernel intra-core block->core dispatch prologue.
@@ -4076,27 +4118,15 @@ class NPUTritonKernel(TritonKernel):
# 2. total_blocks = product of all free-node _blocks. Auxiliary axes (a
# node whose length is the product of other free nodes' lengths, i.e. a
# flattened view) are excluded via tree_node_mapping so they don't
# double-count.
all_blocks_names = []
for tree in self.range_trees:
if not tree.is_reduction and not tree.is_loop:
tree_node_mapping = getattr(tree, 'tree_node_mapping', {})
all_blocks_names.extend(
f"{n.name}_blocks" for n in tree.nodes.values()
if n.name not in tree_node_mapping
)
# double-count. Factored into _npu_emit_total_blocks so the combo path
# can emit one tile count per sub-kernel (num_blocks_<k>).
all_blocks_names = self._npu_free_blocks_names()
def emit_total_blocks():
"""Emit ``total_blocks = a * b * ...`` if needed; return the var/expr
naming the product (a bare single name when there's only one factor,
``"1"`` when there are none)."""
if not all_blocks_names:
return "1"
expr = " * ".join(all_blocks_names)
if len(all_blocks_names) > 1:
code.writeline(f"total_blocks = {expr}")
return "total_blocks"
return expr
return self._npu_emit_total_blocks(code, "total_blocks")
# 3. dispatch shape
if self.npu_rsplit_partial:
@@ -5370,6 +5400,179 @@ class NPUTritonScheduling(TritonScheduling):
def __init__(self, scheduler):
super().__init__(scheduler)
def _te_combo_reject_reason(self, nodes):
if not ncfg.enable_te_combo_kernel:
return "disabled"
if device_props.is_a5():
return "A5 dispatch is not supported"
if not triton_codegen_linearize:
return "linearize is required"
if not 2 <= len(nodes) <= ncfg.te_combo_max_members:
return "member count outside phase-one limit"
if V.graph.cpp_wrapper:
return "C++ wrapper is not supported"
dtypes = []
block_shapes = []
output_shapes = []
all_reads = []
all_writes = []
rw_arg_count = 0
for pn in nodes:
members = pn.get_nodes()
if not members or any(n.is_reduction() or n.is_foreach() or n.is_template() for n in members):
return "only pointwise members are supported"
numel, rnumel = members[0].group[1]
if not isinstance(numel, (int, sympy.Integer)) or rnumel != 1:
return "only static pointwise shapes are supported"
if int(numel) >= 2**31:
return "oversized static axis needs runtime numel argument"
if any(n.group[1] != (numel, rnumel) for n in members):
return "mixed member shapes"
block_shapes.append(int(numel))
rw = pn.read_writes
reads = {dep.name for dep in rw.reads}
writes = {dep.name for dep in rw.writes}
rw_arg_count += len(rw.reads) + len(rw.writes)
if reads & writes or getattr(pn, "mutations", None):
return "mutation or in-place access"
all_reads.append(reads)
all_writes.append(writes)
member_dtypes = set()
member_output_shapes = set()
for name in reads | writes:
try:
dtype = V.graph.get_dtype(name)
member_dtypes.add(dtype)
layout = V.graph.get_buffer(name).get_layout()
if not layout.is_contiguous():
return "non-contiguous layout"
if name in writes:
member_output_shapes.add(tuple(layout.size))
except (AttributeError, RuntimeError, KeyError):
return "unknown buffer layout or dtype"
if len(member_dtypes) != 1:
return "mixed dtype within member"
if len(member_output_shapes) != 1:
return "mixed output shapes within member"
dtypes.append(next(iter(member_dtypes)))
output_shapes.append(next(iter(member_output_shapes)))
if len(set(block_shapes)) != 1 or len(set(output_shapes)) != 1 or len(set(dtypes)) != 1:
return "mixed shapes or dtypes"
if any(dtype in (torch.int64, torch.float64) for dtype in dtypes):
return "dtype requires TE argument conversion"
for i, writes in enumerate(all_writes):
if any(writes & (reads | other_writes)
for j, (reads, other_writes) in enumerate(zip(all_reads, all_writes))
if i != j):
return "cross-member read/write dependency"
if rw_arg_count + 1 >= config.combo_kernel_max_num_args:
return "combined ABI exceeds argument limit"
# Estimate UB use for the fixed 256-element tile before codegen.
ub_bytes = device_props.get_npu_ub_size_bytes()
live_vectors = max(len(r) + len(w) for r, w in zip(all_reads, all_writes))
if 256 * dtypes[0].itemsize * max(2, live_vectors) * 2 > ub_bytes:
return "estimated UB use exceeds capacity"
return None
def codegen_combo_kernel(self, combo_kernel_node):
from .triton_combo_kernel import TEComboKernel, TEComboSubKernel
from torch._inductor.codegen.simd import NodeInfo
from torch._inductor.codegen.triton_combo_kernel import ComboKernel
from torch._inductor.codegen.simd_kernel_features import NodeScheduleMarker
nodes = combo_kernel_node.get_subkernel_nodes()
reason = self._te_combo_reject_reason(nodes)
if reason is not None:
log.debug("TE combo rejected: %s", reason)
self._codegen_combo_fallback(nodes)
return
infos = {}
for pn in nodes:
members = pn.get_nodes()
_, (numel, rnumel) = max(members, key=lambda n: int(n.is_reduction())).group
schedule = self.generate_node_schedule(members, numel, rnumel)
features = SIMDKernelFeatures(schedule, numel, rnumel)
tiling = self.select_tiling(schedule, numel, rnumel)
infos[pn] = NodeInfo(schedule, tiling, None, numel, rnumel, features, False)
partitions = ComboKernel.horizontal_partition(
nodes, self, infos, custom_algorithm=combo_kernel_node.use_custom_partition_algo
)
# Phase one accepts only one free x axis. The admission decision still
# precedes any node codegen or mark_run, including partition rejection.
if (
not partitions
or sum(map(len, partitions)) != len(nodes)
or any(
len(p) < 2
or len(p) > ncfg.te_combo_max_members
or any(
set(infos[n].tiling) != {"x", "r0_"}
or infos[n].tiling != infos[p[0]].tiling
for n in p
)
for p in partitions
)
):
log.debug("TE combo rejected: unsupported tiling or partition")
self._codegen_combo_fallback(nodes)
return
generated = []
for partition in partitions:
combo = TEComboKernel(xblock=256)
schedules = []
for slot, pn in enumerate(partition):
info = infos[pn]
sub = ComboKernel.create_triton_kernel(
info.tiling, info.features, True, TEComboSubKernel
)
if not sub._npu_linearize or sub.no_x_dim:
raise AssertionError("TE combo admission allowed a non-linearized member")
sub.set_combo_slot(slot, f"local_tile_{slot}")
combo.create_sub_kernel(sub)
schedules.append(info.node_schedule)
for sub in combo.sub_kernels:
self._npu_repermute_tensor_dims(sub, sub.features)
for sub, schedule in zip(combo.sub_kernels, schedules):
self.codegen_node_schedule_with_kernel(schedule, sub)
for sub, schedule in zip(combo.sub_kernels, schedules):
self._apply_linearize(sub, schedule)
with V.set_kernel_handler(combo):
src = combo.codegen_kernel()
generated.append((src, combo, schedules))
defined = [
(self.define_kernel(src, [combo_kernel_node], combo), combo, schedules)
for src, combo, schedules in generated
]
for kernel_name, combo, schedules in defined:
self.codegen_comment(combo_kernel_node.snodes, kernel_name)
for sub, schedule in zip(combo.sub_kernels, schedules):
with V.set_kernel_handler(sub):
for node in NodeScheduleMarker.only_nodes(schedule):
node.mark_run()
V.graph.removed_buffers |= sub.removed_buffers
V.graph.inplaced_to_remove |= sub.inplaced_to_remove
combo.call_kernel(kernel_name)
self.free_buffers_in_scheduler()
def _codegen_combo_fallback(self, nodes):
# The scheduler queues frees for the whole foreach node before calling
# us. Standalone codegen frees after each kernel, so keep those frees
# pending until every member has been launched.
pending_frees = self.scheduler.buffer_names_to_free.copy()
self.scheduler.buffer_names_to_free.clear()
try:
for node in nodes:
self.codegen_node(node)
finally:
self.scheduler.buffer_names_to_free.update(pending_frees)
self.free_buffers_in_scheduler()
def create_kernel_choices(self, kernel_features, kernel_args, kernel_kwargs):
"""Override to always use NPUTritonKernel."""
return [self.kernel_type(*kernel_args, **kernel_kwargs)]
@@ -0,0 +1,258 @@
# Copyright (c) 2026, Huawei Technologies Co., Ltd
#
# Licensed under the Apache-2.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/pytorch/pytorch/blob/main/LICENSE
#
# 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.
"""Code generation for TE combo kernels and their pointwise members.
Each member uses a local tile index and slot-specific range-tree names.
``TEComboKernel`` emits the shared dispatch over all members' tiles.
"""
import sympy
from torch._inductor.codegen.common import ArgName, ConstexprArg
from torch._inductor.codegen.simd import IterationRangesEntry, IterationRangesRoot
from torch._inductor.codegen.triton_combo_kernel import ComboKernel
from torch._inductor.codegen.triton_utils import config_of, signature_to_meta
from torch._inductor.runtime.hints import DeviceProperties
from torch._inductor.utils import IndentedBuffer, Placeholder
from torch._inductor.virtualized import V
from torch.utils._ordered_set import OrderedSet
from ..compat import IS_TRITON_36_PLUS
from ..device_props import get_npu_vector_core_count
from .triton import NPUTritonKernel
__all__ = ["TEComboSubKernel", "TEComboKernel"]
def _te_combo_rekey_entry(
tree: IterationRangesRoot,
node: IterationRangesEntry,
old_symbol: sympy.Symbol,
) -> None:
"""Update the symbol maps populated by ``tree.lookup`` after renaming.
``tree.nodes`` is keyed by the index expression, which does not change.
Other generated names are derived from ``node.name`` after this call.
"""
new_symbol = node.symbol()
if old_symbol == new_symbol:
return
range_tree_nodes = V.kernel.range_tree_nodes
range_tree_nodes.pop(old_symbol, None)
range_tree_nodes[new_symbol] = node
# Find the entry registered by lookup; do not rely on its position.
for i in range(len(tree.var_list) - 1, -1, -1):
if tree.var_list[i] == old_symbol:
tree.var_list[i] = new_symbol
break
if old_symbol in tree.var_ranges:
tree.var_ranges[new_symbol] = tree.var_ranges.pop(old_symbol)
def _te_combo_suffix_tree(tree: IterationRangesRoot, num: int) -> None:
"""Suffix range-tree entries as ``lookup`` creates them.
Keep ``tree.prefix`` unchanged because axis selection depends on it.
Entries are created lazily, so the hook is installed before body codegen.
"""
original = tree.lookup
if getattr(original, "_te_combo_suffixed", False):
# Avoid wrapping lookup twice and appending the slot suffix twice.
return
def lookup(divisor, length):
known = len(tree.nodes)
node = original(divisor, length)
if len(tree.nodes) == known:
# Existing entries already have their slot suffix.
return node
old_symbol = node.symbol()
# set_name() replaces codegen(), which reduction entries still need
# to emit their index assignment. Rename directly and clear its cache.
node.name = f"{node.name}_{num}"
node.codegen.cache_clear()
_te_combo_rekey_entry(tree, node, old_symbol)
return node
lookup._te_combo_suffixed = True # type: ignore[attr-defined]
tree.lookup = lookup # type: ignore[method-assign]
def _te_combo_suffix_nodes(kernel: NPUTritonKernel, num: int) -> None:
"""Install slot-specific naming on the member's range trees."""
for tree in kernel.range_trees:
_te_combo_suffix_tree(tree, num)
class TEComboSubKernel(NPUTritonKernel):
"""A TE pointwise kernel using slot-specific names and local tile indices."""
def __init__(self, *args, **kwargs):
self._combo_num = None
self._combo_local_tile = None
super().__init__(*args, **kwargs)
def set_combo_slot(self, num: int, local_tile_name: str) -> None:
"""Bind the member's slot before its range-tree entries are created."""
self._combo_num = num
self._combo_local_tile = local_tile_name
_te_combo_suffix_nodes(self, num)
def iteration_ranges_get_pid(self, entry: IterationRangesRoot) -> str:
"""Use the member-local tile for linearized combo dispatch."""
if self._combo_local_tile is not None and self._npu_linearize:
return self._combo_local_tile
return super().iteration_ranges_get_pid(entry)
class TEComboKernel(ComboKernel):
"""Assemble linearized TE members over one concatenated tile space."""
def __init__(self, xblock: int):
super().__init__(TEComboSubKernel, enable_autotune=False)
self.xblock = xblock
def codegen_kernel(self, name=None):
if len(self.sub_kernels) < 2:
raise AssertionError("TE combo needs at least two members")
code = IndentedBuffer()
code.splice(NPUTritonKernel.gen_common_triton_imports())
code.splice(self.sub_kernels[0].gen_triton_ext_imports())
seen_helpers = OrderedSet()
for sub in self.sub_kernels:
for helper in sub.helper_functions:
if helper not in seen_helpers:
code.writeline("")
code.splice(helper)
seen_helpers.add(helper)
argdefs, _, signature, _ = self.args.python_argdefs()
self.triton_meta = {
"signature": signature_to_meta(
signature, size_dtype=self.sub_kernels[0].index_dtype,
argdefs=argdefs,
),
"device": DeviceProperties.create(V.graph.get_current_device_or_throw()),
"constants": {},
"mix_mode": "aiv",
"configs": [config_of(signature)],
}
if IS_TRITON_36_PLUS:
signature.append(ConstexprArg("XBLOCK"))
argdefs.append(ArgName("XBLOCK", is_constexpr=True))
counts = []
for sub in self.sub_kernels:
free_nodes = [
node for tree in sub.range_trees
if not tree.is_reduction and not tree.is_loop
for node in tree.nodes.values()
if node.name not in tree.tree_node_mapping
]
count = 1
for node in free_nodes:
length = int(node.length)
count *= (length + min(length, self.xblock) - 1) // min(length, self.xblock) if length else 0
counts.append(count)
offsets = []
total = 0
for count in counts:
offsets.append(total)
total += count
self.inductor_meta = {
"grid_type": "Grid1D",
"autotune_hints": set(),
"kernel_name": str(Placeholder.DESCRIPTIVE_NAME),
"mutated_arg_names": [],
"optimize_mem": V.graph.is_inference or V.graph.is_backward,
"no_x_dim": False,
"num_load": sum(sub.num_load for sub in self.sub_kernels),
"num_reduction": 0,
"npu_num_x_nodes": sum(len(sub._npu_free_blocks_names()) for sub in self.sub_kernels),
"npu_linearize": False,
"te_combo_meta": {
"combo_num_kernels": len(self.sub_kernels),
"combo_tile_offsets": offsets,
"combo_tile_counts": counts,
"combo_no_x_dim": [sub.no_x_dim for sub in self.sub_kernels],
"combo_dynamic_args": [],
"combo_dispatch_kind": "group_dispatch",
"combo_xblock": self.xblock,
},
**NPUTritonKernel.inductor_meta_common(),
}
kernel_name = name or str(Placeholder.KERNEL_NAME)
size_hints = {"x": max(1, total * self.xblock)}
code.splice(
f"@npu_triton_heuristics.foreach(size_hints={size_hints!r}, "
f"filename=__file__, triton_meta={self.triton_meta!r}, "
f"inductor_meta={self.inductor_meta!r})\n@triton.jit"
)
code.writeline(
f"def {kernel_name}({', '.join(arg.full_name() for arg in argdefs)}):"
)
with code.indent():
code.writeline(f"total_thread = {get_npu_vector_core_count()}")
code.writeline("group_id = tl.program_id(0)")
for old, new in self.args.aliases():
code.writeline(f"{old} = {new}")
for num, sub in enumerate(self.sub_kernels):
for tree in sub.range_trees:
if tree.is_reduction or tree.is_loop:
continue
if not hasattr(tree, "pre_loop_code"):
raise AssertionError("TE combo member has no linearized header")
code.splice(tree.pre_loop_code)
blocks = sub._npu_emit_total_blocks(code, f"num_blocks_{num}")
if blocks != f"num_blocks_{num}":
code.writeline(f"num_blocks_{num} = {blocks}")
code.writeline(
f"S_{num + 1} = "
f"{'0' if num == 0 else f'S_{num}'} + num_blocks_{num}"
)
code.writeline(f"tiles_per_core = S_{len(self.sub_kernels)} // total_thread")
code.writeline(f"core_tail = S_{len(self.sub_kernels)} % total_thread")
code.writeline("group_size = tiles_per_core + (group_id < core_tail)")
code.writeline("group_base = group_id * tiles_per_core + tl.minimum(group_id, core_tail)")
code.writeline("for i in range(group_size):")
with code.indent():
code.writeline("tile = group_base + i")
for num, sub in enumerate(self.sub_kernels):
lo = "0" if num == 0 else f"S_{num}"
code.writeline(
f"{'if' if num == 0 else 'elif'} tile < S_{num + 1}:"
)
with code.indent():
code.writeline(f"local_tile_{num} = tile - {lo}")
sub.codegen_prologue(sub.body)
sub.codegen_body()
sub._filter_pdl(sub.body)
code.splice(sub.body)
return code.getvalue()
def call_kernel(self, name):
# The TE launcher takes its grid from te_combo_meta, not the upstream
# CUDA dispatch_class.
_, call_args, _, arg_types = self.args.python_argdefs()
V.graph.wrapper_code.generate_kernel_call(
name, call_args, triton=True, arg_types=arg_types,
triton_meta=self.triton_meta, inductor_meta=self.inductor_meta,
)
@@ -445,5 +445,23 @@ vf_fusion_mode: Optional[str] = None
vf_merge_level: Optional[int] = None
# TE ComboKernel configuration.
# 默认关闭;通过准入检查的静态同构 pointwise 成员才会合并。
enable_te_combo_kernel: bool = False
# 预留配置;当前准入逻辑始终拒绝动态 shape。
te_combo_allow_dynamic_shapes: bool = False
# 预留配置;当前准入逻辑始终拒绝 A5。
te_combo_allow_a5: bool = False
# 预留配置;当前组合 kernel 只使用一套固定配置。
te_combo_allow_autotune: bool = False
# 组合成员数上限;少于 2 个成员时使用普通 TE kernel。
te_combo_max_members: int = 8
# adds .patch(), .save_config(), attribute access, backend-hash serialization
install_config_module(sys.modules[__name__])
@@ -15,11 +15,16 @@ from torch._inductor.codegen.common import (
from torch._dynamo.device_interface import register_interface_for_device
from torch_npu.utils._dynamo_device import NpuInterface
from . import config as ncfg
def register_backend_for_npu():
from .codegen.triton import NPUTritonScheduling
from .codegen.wrapper import NPUWrapperCodeGen
register_backend_for_device('npu', NPUTritonScheduling, NPUWrapperCodeGen)
register_backend_for_device(
'npu', NPUTritonScheduling, NPUWrapperCodeGen,
device_custom_config=ncfg,
)
# Inherit the FULL NPU device-op overrides (device_guard / set_device /
@@ -55,9 +55,10 @@ def _gen_grid_code(scope, def_args, arg_names, cfg, inductor_meta, *, num_cores,
# aliases or drops tiles — odometer periodic modulo total_blocks). Codegen injects a
# recipe reproducing it host-side (references XBLOCK literal + <x>numel args); over
# 65535 coreDim folds logical→physical. Falls through to group-dispatch when absent.
is_te_combo = inductor_meta.get("te_combo_meta") is not None
_recipe = inductor_meta.get("npu_dispatch_recipe")
_grid_recipe_lines = None
if _recipe and is_a5:
if _recipe and is_a5 and not is_te_combo:
# Splice every tile-block constexpr the recipe may reference
# (XBLOCK / YBLOCK / ZBLOCK for Grid1D/2D/3D) as a literal, so the
# recipe lines exec with the same block sizes the kernel was JIT'd
@@ -70,7 +71,12 @@ def _gen_grid_code(scope, def_args, arg_names, cfg, inductor_meta, *, num_cores,
_rl.append(f" grid_0 = max(1, {_tb})")
_grid_recipe_lines = _rl
if _grid_recipe_lines is not None:
if is_te_combo:
# TE combo dispatch divides one concatenated tile space across every
# vector core inside the kernel, so it always launches the full core count.
grid_0_expr = str(num_cores)
grid_0_is_memoized = False
elif _grid_recipe_lines is not None:
# Not memoized: total_blocks depends on multiple <x>numel args, and
# the recipe arithmetic is cheap relative to correctness clarity.
grid_0_expr = None
@@ -1819,6 +1819,8 @@ _NPU_UB_CAPACITY_BYTES = get_npu_ub_size_bytes()
# 2.0 matches the observed "requires X bits" report on UB-overflow failures
# (e.g. a 256-elem fp32 tile with ~9 live broadcasts reported ~36KB used).
_NPU_UB_OVERHEAD_FACTOR = 2.0
# Fallback XBLOCK if combo metadata does not provide one; current codegen uses 256.
_TE_COMBO_DEFAULT_XBLOCK = 256
# Cap on how many input tiles the UB estimate treats as simultaneously live. A many-input
# pattern (26-way cat) doesn't hold every tile resident (the compiler streams them), so
# counting all num_load buffers over-estimates peak UB and rejects tiles that fit (XBLOCK
@@ -2943,6 +2945,26 @@ def persistent_reduction(
raise NotImplementedError(f"persistent_reduction size_hints: {size_hints}")
def foreach(size_hints, triton_meta, filename=None, inductor_meta=None):
"""Use one shared XBLOCK config for TE combo members.
Combo codegen supplies ``combo_xblock`` in metadata. The config kwarg also
supplies the XBLOCK constexpr expected by the generated kernel signature.
"""
inductor_meta = {} if inductor_meta is None else inductor_meta
combo_meta = inductor_meta.get("te_combo_meta") or {}
xblock = int(combo_meta.get("combo_xblock") or _TE_COMBO_DEFAULT_XBLOCK)
configs = [Config({"XBLOCK": xblock}, num_warps=8, num_stages=1)]
return cached_autotune(
size_hints,
configs,
triton_meta=triton_meta,
inductor_meta=inductor_meta,
heuristic_type=HeuristicType.POINTWISE,
filename=filename,
)
def grid(*numels):
"""
Helper function to compute triton grids for NPU.