已合并
【硬件解耦任务】fix(inductor-TE): 生成 aten.contiguous 拷贝 lowering #4933 #47274
【硬件解耦任务】fix(inductor-TE): 生成 aten.contiguous 拷贝 lowering #4933 #47274
已合并
王刚创建于 9月28日
共 3 个文件变更+124-0
@@ -0,0 +1,106 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+#
3+# Owner(s): ["module: inductor"]
4+"""triton_experimental must lower aten.contiguous to a generated copy kernel.
5+ 
6+``aten.contiguous.default`` has no upstream lowering -- unlike ``as_strided`` it
7+is not already in the ``lowerings`` table -- so the bulk fallback pass in
8+``_register_npu_inductor_fallbacks`` never sees it, and a strict-mode compile of
9+any graph that emits a bare contiguous node fails with
10+``MissingOperatorWithoutDecomp`` (issue #4933: all six diag_embed opinfo dtype
11+variants, whose decomposition chain ends in ``mask_tensor(...).contiguous()``).
12+The fix registers ``npu_contiguous`` (delegating to ``npu_clone``) and lists
13+``aten.contiguous`` in ``GENERATE_LIST`` so the bulk pass does not clobber that
14+new lowering back into a fallback. These tests pin the registration and check
15+the compiled diag_embed matches eager across the six reported dtypes.
16+"""
17+ 
18+import os
19+import unittest
20+ 
21+os.environ.setdefault("TORCHINDUCTOR_NPU_BACKEND", "triton_experimental")
22+ 
23+import torch
24+from torch._inductor import config
25+from torch._inductor.lowering import lowerings
26+from torch.testing._internal.common_utils import TestCase, run_tests
27+ 
28+import torch_npu # noqa: F401
29+import torch_npu._inductor # noqa: F401
30+from torch_npu._inductor.triton_experimental import (
31+ lowering,
32+ lowering_override_list,
33+)
34+ 
35+aten = torch.ops.aten
36+ 
37+requires_npu = unittest.skipUnless(torch.npu.is_available(), "requires an NPU")
38+ 
39+CONTIGUOUS = aten.contiguous.default
40+ 
41+ 
42+class TestTeContiguousLoweringRegistration(TestCase):
43+ def test_contiguous_listed_for_generation(self):
44+ self.assertIn(aten.contiguous, lowering_override_list.GENERATE_LIST)
45+ 
46+ def test_npu_contiguous_is_registered_as_a_lowering(self):
47+ self.assertIn(CONTIGUOUS, lowerings)
48+ 
49+ def test_contiguous_is_exempted_from_the_bulk_fallback_pass(self):
50+ # Re-implement the exemption invariant the bulk pass uses, instead of
51+ # re-running the global pass (which would re-scan every lowering and
52+ # append to the global FALLBACK_LIST -- order-dependent and polluting).
53+ gen_set = set()
54+ for fn in lowering_override_list.GENERATE_LIST:
55+ gen_set.add(fn)
56+ if isinstance(fn, torch._ops.OpOverloadPacket):
57+ gen_set |= {getattr(fn, o) for o in fn.overloads()}
58+ self.assertIn(CONTIGUOUS, gen_set)
59+ self.assertNotIn(CONTIGUOUS, lowering.FALLBACK_LIST)
60+ 
61+ 
62+class TestTeDiagEmbedMatchesEager(TestCase):
63+ @requires_npu
64+ def test_diag_embed_forward(self):
65+ # The six dtype variants reported in issue #4933.
66+ for dtype in (
67+ torch.bool,
68+ torch.float16,
69+ torch.float32,
70+ torch.float64,
71+ torch.int32,
72+ torch.int64,
73+ ):
74+ with self.subTest(dtype=dtype):
75+ if dtype == torch.bool:
76+ x = torch.randint(0, 2, (3, 4), device="npu", dtype=torch.int64).to(
77+ torch.bool
78+ )
79+ elif dtype in (torch.int32, torch.int64):
80+ x = torch.randint(0, 10, (3, 4), device="npu", dtype=torch.int64).to(
81+ dtype
82+ )
83+ else:
84+ x = torch.randn(3, 4, device="npu", dtype=dtype)
85+ eager = torch.diag_embed(x, offset=0, dim1=-2, dim2=-1)
86+ torch._dynamo.reset()
87+ try:
88+ with config.patch("force_disable_caches", True), config.patch(
89+ "implicit_fallbacks", False
90+ ):
91+ compiled = torch.compile(
92+ lambda a: torch.diag_embed(a, offset=0, dim1=-2, dim2=-1),
93+ backend="inductor",
94+ fullgraph=True,
95+ options={"npu_backend": "triton_experimental"},
96+ )
97+ out = compiled(x)
98+ finally:
99+ torch._dynamo.reset()
100+ self.assertEqual(out.dtype, eager.dtype)
101+ self.assertEqual(out.shape, eager.shape)
102+ torch.testing.assert_close(out, eager)
103+ 
104+ 
105+if __name__ == "__main__":
106+ run_tests()
@@ -791,6 +791,23 @@ def npu_clone(x, *, memory_format=None):
791 791 
792 792 
793overwrite_lowering(aten.clone, npu_clone, type_promotion_kind=None)793overwrite_lowering(aten.clone, npu_clone, type_promotion_kind=None)
794+ 
795+ 
796+def npu_contiguous(x, memory_format=torch.contiguous_format):
797+ """NPU contiguous -- delegate to npu_clone.
798+ 
799+ aten.contiguous has no upstream lowering (unlike as_strided), so the bulk
800+ fallback pass never sees it and a strict-mode compile of any graph that
801+ emits a bare contiguous node (e.g. inside the diag_embed decomposition
802+ chain) fails with MissingOperatorWithoutDecomp. contiguous is exactly a
803+ clone with a memory_format contract, so reuse npu_clone: for an already
804+ row-major input fold_verdict folds it to a no-op view, and a non-contiguous
805+ input lowers to one on-device copy (generated or vendor DMA) -- keeping the
806+ copy fuseable instead of a device-side FallbackKernel round-trip."""
807+ return npu_clone(x, memory_format=memory_format)
808+ 
809+ 
810+overwrite_lowering(aten.contiguous, npu_contiguous, type_promotion_kind=None)
794# --- P1: separable aclnn index_select for aten._unsafe_index / aten.index ---811# --- P1: separable aclnn index_select for aten._unsafe_index / aten.index ---
795# msprof: the aclnn Index fallback costs 10ms/iter on yolov3's head (2812# msprof: the aclnn Index fallback costs 10ms/iter on yolov3's head (2
796# launches), while eager runs the same x[:, :, ih[:,None], iw] near-zero via813# launches), while eager runs the same x[:, :, ih[:,None], iw] near-zero via
@@ -64,6 +64,7 @@ GENERATE_LIST = [
64 aten.expand,64 aten.expand,
65 aten.repeat,65 aten.repeat,
66 aten.clone,66 aten.clone,
67+ aten.contiguous,
67 aten.reshape,68 aten.reshape,
68 aten.var_mean,69 aten.var_mean,
69 aten.sum,70 aten.sum,