Merged
feat(pass): Add slice contract feature for pass with some cases #5568
niulinkaiAdd on Aug 20
feat(pass): Add slice contract feature for pass with some cases #5568
Merged
niulinkaiAdd on Aug 20
Total: 450 files changed+27118-9974
@@ -64,6 +64,21 @@ def pytest_addoption(parser: pytest.Parser):
64 )64 )
65 65 
66 66 
67+def pytest_configure(config):
68+ """pytest 启动时在 root scope 上设置 enable_slice=true。
69+ 
70+ 覆盖 tile_fwk_config.json 的 false 默认值。root scope 不受 config::Reset() / reset_options()
71+ 影响,所以 UT SetUp 中的 Clear() 不会清除该设置。
72+ 单个测试用例仍可通过 @pypto.options(pass_options={"enable_slice": False}) 覆盖此设置。
73+ """
74+ try:
75+ import pypto.pypto_impl
76+ 
77+ pypto.pypto_impl.SetGlobalConfig({"pass.enable_slice": True})
78+ except Exception:
79+ pass
80+ 
81+ 
67def _is_case_match_cards(item, target_cards) -> bool:82def _is_case_match_cards(item, target_cards) -> bool:
68 """83 """
69 判断测试用例是否匹配目标卡数84 判断测试用例是否匹配目标卡数
@@ -33,6 +33,7 @@ def add_kernel(
33 out[:] = (a + b) * 2.033 out[:] = (a + b) * 2.0
34 34 
35 35 
36+@pypto.options(pass_options={"enable_slice": True})
36def test_add(device):37def test_add(device):
37 shape = (64, 64)38 shape = (64, 64)
38 39 
@@ -50,6 +51,7 @@ def erfc_kernel(x: pypto.Tensor[[...], pypto.DT_FP32], out: pypto.Tensor[[...],
50 out[:] = pypto.erfc(x)51 out[:] = pypto.erfc(x)
51 52 
52 53 
54+@pypto.options(pass_options={"enable_slice": True})
53def test_erfc(device):55def test_erfc(device):
54 shape = (64, 64)56 shape = (64, 64)
55 57 
@@ -70,6 +72,7 @@ def matmul_kernel(
70 out.move(pypto.matmul(a, b, a.dtype))72 out.move(pypto.matmul(a, b, a.dtype))
71 73 
72 74 
75+@pypto.options(pass_options={"enable_slice": True})
73def test_matmul(device):76def test_matmul(device):
74 m, k, n = 64, 128, 6477 m, k, n = 64, 128, 64
75 78 
@@ -87,6 +90,7 @@ def sum_kernel(a: pypto.Tensor[[...], pypto.DT_FP32], out: pypto.Tensor[[...], p
87 out[:] = pypto.sum(a, dim=-1, keepdim=False)90 out[:] = pypto.sum(a, dim=-1, keepdim=False)
88 91 
89 92 
93+@pypto.options(pass_options={"enable_slice": True})
90def test_sum(device):94def test_sum(device):
91 a = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32, device=device)95 a = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32, device=device)
92 out = torch.empty((2), dtype=torch.float32, device=device)96 out = torch.empty((2), dtype=torch.float32, device=device)
@@ -129,6 +133,7 @@ def dynamic_add_kernel(
129 pypto.assemble(tile, [m * block_m, n * block_n], output)133 pypto.assemble(tile, [m * block_m, n * block_n], output)
130 134 
131 135 
136+@pypto.options(pass_options={"enable_slice": True})
132def test_dynamic_add(device):137def test_dynamic_add(device):
133 m, n = 512, 512138 m, n = 512, 512
134 block_m, block_n = 128, 128139 block_m, block_n = 128, 128
@@ -80,6 +80,7 @@ def abs_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.D
80 out[:] = pypto.abs(x)80 out[:] = pypto.abs(x)
81 81 
82 82 
83+@pypto.options(pass_options={"enable_slice": True})
83def test_abs_basic(device_id: int = None):84def test_abs_basic(device_id: int = None):
84 """Test basic usage of abs function"""85 """Test basic usage of abs function"""
85 print("=" * 60)86 print("=" * 60)
@@ -114,6 +115,7 @@ def add_kernel(
114 out[:] = pypto.add(a, b)115 out[:] = pypto.add(a, b)
115 116 
116 117 
118+@pypto.options(pass_options={"enable_slice": True})
117def test_add_basic(device_id: int = None):119def test_add_basic(device_id: int = None):
118 """Test basic usage of add function"""120 """Test basic usage of add function"""
119 print("=" * 60)121 print("=" * 60)
@@ -144,6 +146,7 @@ def add_broadcast_kernel(
144 out[:] = pypto.add(a, b)146 out[:] = pypto.add(a, b)
145 147 
146 148 
149+@pypto.options(pass_options={"enable_slice": True})
147def test_add_broadcast(device_id: int = None):150def test_add_broadcast(device_id: int = None):
148 """Test broadcasting between tensors of different shapes"""151 """Test broadcasting between tensors of different shapes"""
149 print("=" * 60)152 print("=" * 60)
@@ -172,6 +175,7 @@ def add_scalar_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([],
172 out[:] = pypto.add(x, scalar)175 out[:] = pypto.add(x, scalar)
173 176 
174 177 
178+@pypto.options(pass_options={"enable_slice": True})
175def test_add_scalar(device_id: int = None):179def test_add_scalar(device_id: int = None):
176 """Test adding a scalar to a tensor"""180 """Test adding a scalar to a tensor"""
177 print("=" * 60)181 print("=" * 60)
@@ -210,6 +214,7 @@ def clip_kernel(
210 out[:] = pypto.clip(a, min_, max_)214 out[:] = pypto.clip(a, min_, max_)
211 215 
212 216 
217+@pypto.options(pass_options={"enable_slice": True})
213def test_clip_basic(device_id: int = None):218def test_clip_basic(device_id: int = None):
214 """Test basic usage of clip function"""219 """Test basic usage of clip function"""
215 print("=" * 60)220 print("=" * 60)
@@ -244,6 +249,7 @@ def clip_broadcast_kernel(
244 out[:] = pypto.clip(a, min_, max_)249 out[:] = pypto.clip(a, min_, max_)
245 250 
246 251 
252+@pypto.options(pass_options={"enable_slice": True})
247def test_clip_broadcast(device_id: int = None):253def test_clip_broadcast(device_id: int = None):
248 """Test broadcasting between tensors of different shapes"""254 """Test broadcasting between tensors of different shapes"""
249 print("=" * 60)255 print("=" * 60)
@@ -280,6 +286,7 @@ def div_kernel(
280 out[:] = pypto.div(a, b)286 out[:] = pypto.div(a, b)
281 287 
282 288 
289+@pypto.options(pass_options={"enable_slice": True})
283def test_div_basic(device_id: int = None):290def test_div_basic(device_id: int = None):
284 """Test basic usage of div function"""291 """Test basic usage of div function"""
285 print("=" * 60)292 print("=" * 60)
@@ -310,6 +317,7 @@ def div_broadcast_kernel(
310 out[:] = pypto.div(a, b)317 out[:] = pypto.div(a, b)
311 318 
312 319 
320+@pypto.options(pass_options={"enable_slice": True})
313def test_div_broadcast(device_id: int = None):321def test_div_broadcast(device_id: int = None):
314 """Test broadcasting between tensors of different shapes"""322 """Test broadcasting between tensors of different shapes"""
315 print("=" * 60)323 print("=" * 60)
@@ -338,6 +346,7 @@ def div_scalar_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([],
338 out[:] = pypto.div(a, scalar)346 out[:] = pypto.div(a, scalar)
339 347 
340 348 
349+@pypto.options(pass_options={"enable_slice": True})
341def test_div_scalar(device_id: int = None):350def test_div_scalar(device_id: int = None):
342 """Test diving a scalar to a tensor"""351 """Test diving a scalar to a tensor"""
343 print("=" * 60)352 print("=" * 60)
@@ -371,6 +380,7 @@ def exp_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.D
371 out[:] = pypto.exp(x)380 out[:] = pypto.exp(x)
372 381 
373 382 
383+@pypto.options(pass_options={"enable_slice": True})
374def test_exp_basic(device_id: int = None):384def test_exp_basic(device_id: int = None):
375 """Test basic usage of exp function"""385 """Test basic usage of exp function"""
376 print("=" * 60)386 print("=" * 60)
@@ -403,6 +413,7 @@ def exp2_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.
403 out[:] = pypto.exp2(x)413 out[:] = pypto.exp2(x)
404 414 
405 415 
416+@pypto.options(pass_options={"enable_slice": True})
406def test_exp2_basic(device_id: int = None):417def test_exp2_basic(device_id: int = None):
407 """Test basic usage of exp2 function"""418 """Test basic usage of exp2 function"""
408 print("=" * 60)419 print("=" * 60)
@@ -435,6 +446,7 @@ def expm1_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto
435 out[:] = pypto.expm1(x)446 out[:] = pypto.expm1(x)
436 447 
437 448 
449+@pypto.options(pass_options={"enable_slice": True})
438def test_expm1_basic(device_id: int = None):450def test_expm1_basic(device_id: int = None):
439 """Test basic usage of expm1 function"""451 """Test basic usage of expm1 function"""
440 print("=" * 60)452 print("=" * 60)
@@ -467,6 +479,7 @@ def log_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.D
467 out[:] = pypto.log(a)479 out[:] = pypto.log(a)
468 480 
469 481 
482+@pypto.options(pass_options={"enable_slice": True})
470def test_log_basic(device_id: int = None):483def test_log_basic(device_id: int = None):
471 """Test basic usage of log function"""484 """Test basic usage of log function"""
472 print("=" * 60)485 print("=" * 60)
@@ -501,6 +514,7 @@ def mul_kernel(
501 out[:] = pypto.mul(a, b)514 out[:] = pypto.mul(a, b)
502 515 
503 516 
517+@pypto.options(pass_options={"enable_slice": True})
504def test_mul_basic(device_id: int = None):518def test_mul_basic(device_id: int = None):
505 """Test basic usage of mul function"""519 """Test basic usage of mul function"""
506 print("=" * 60)520 print("=" * 60)
@@ -531,6 +545,7 @@ def mul_broadcast_kernel(
531 out[:] = pypto.mul(a, b)545 out[:] = pypto.mul(a, b)
532 546 
533 547 
548+@pypto.options(pass_options={"enable_slice": True})
534def test_mul_broadcast(device_id: int = None):549def test_mul_broadcast(device_id: int = None):
535 """Test broadcasting between tensors of different shapes"""550 """Test broadcasting between tensors of different shapes"""
536 print("=" * 60)551 print("=" * 60)
@@ -559,6 +574,7 @@ def mul_scalar_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([],
559 out[:] = pypto.mul(a, scalar)574 out[:] = pypto.mul(a, scalar)
560 575 
561 576 
577+@pypto.options(pass_options={"enable_slice": True})
562def test_mul_scalar(device_id: int = None):578def test_mul_scalar(device_id: int = None):
563 """Test muling a scalar to a tensor"""579 """Test muling a scalar to a tensor"""
564 print("=" * 60)580 print("=" * 60)
@@ -592,6 +608,7 @@ def neg_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.D
592 out[:] = pypto.neg(a)608 out[:] = pypto.neg(a)
593 609 
594 610 
611+@pypto.options(pass_options={"enable_slice": True})
595def test_neg_basic(device_id: int = None):612def test_neg_basic(device_id: int = None):
596 """Test basic usage of neg function"""613 """Test basic usage of neg function"""
597 print("=" * 60)614 print("=" * 60)
@@ -624,6 +641,7 @@ def pow_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.D
624 out[:] = pypto.pow(a, b)641 out[:] = pypto.pow(a, b)
625 642 
626 643 
644+@pypto.options(pass_options={"enable_slice": True})
627def test_pow_basic(device_id: int = None):645def test_pow_basic(device_id: int = None):
628 """Test basic usage of pow function"""646 """Test basic usage of pow function"""
629 print("=" * 60)647 print("=" * 60)
@@ -657,6 +675,7 @@ def round_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto
657 out[:] = pypto.round(a, decimals=decimals)675 out[:] = pypto.round(a, decimals=decimals)
658 676 
659 677 
678+@pypto.options(pass_options={"enable_slice": True})
660def test_round_basic(device_id: int = None):679def test_round_basic(device_id: int = None):
661 """Test basic usage of round function"""680 """Test basic usage of round function"""
662 print("=" * 60)681 print("=" * 60)
@@ -690,6 +709,7 @@ def rsqrt_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto
690 out[:] = pypto.rsqrt(a)709 out[:] = pypto.rsqrt(a)
691 710 
692 711 
712+@pypto.options(pass_options={"enable_slice": True})
693def test_rsqrt_basic(device_id: int = None):713def test_rsqrt_basic(device_id: int = None):
694 """Test basic usage of rsqrt function"""714 """Test basic usage of rsqrt function"""
695 print("=" * 60)715 print("=" * 60)
@@ -722,6 +742,7 @@ def ceil_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.
722 out[:] = pypto.ceil(a)742 out[:] = pypto.ceil(a)
723 743 
724 744 
745+@pypto.options(pass_options={"enable_slice": True})
725def test_ceil_basic(device_id: int = None):746def test_ceil_basic(device_id: int = None):
726 """Test basic usage of ceil function"""747 """Test basic usage of ceil function"""
727 print("=" * 60)748 print("=" * 60)
@@ -754,6 +775,7 @@ def floor_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto
754 out[:] = pypto.floor(a)775 out[:] = pypto.floor(a)
755 776 
756 777 
778+@pypto.options(pass_options={"enable_slice": True})
757def test_floor_basic(device_id: int = None):779def test_floor_basic(device_id: int = None):
758 """Test basic usage of floor function"""780 """Test basic usage of floor function"""
759 print("=" * 60)781 print("=" * 60)
@@ -786,6 +808,7 @@ def trunc_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto
786 out[:] = pypto.trunc(a)808 out[:] = pypto.trunc(a)
787 809 
788 810 
811+@pypto.options(pass_options={"enable_slice": True})
789def test_trunc_basic(device_id: int = None):812def test_trunc_basic(device_id: int = None):
790 """Test basic usage of trunc function"""813 """Test basic usage of trunc function"""
791 print("=" * 60)814 print("=" * 60)
@@ -818,6 +841,7 @@ def sqrt_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.
818 out[:] = pypto.sqrt(a)841 out[:] = pypto.sqrt(a)
819 842 
820 843 
844+@pypto.options(pass_options={"enable_slice": True})
821def test_sqrt_basic(device_id: int = None):845def test_sqrt_basic(device_id: int = None):
822 """Test basic usage of sqrt function"""846 """Test basic usage of sqrt function"""
823 print("=" * 60)847 print("=" * 60)
@@ -852,6 +876,7 @@ def sub_kernel(
852 out[:] = pypto.sub(a, b)876 out[:] = pypto.sub(a, b)
853 877 
854 878 
879+@pypto.options(pass_options={"enable_slice": True})
855def test_sub_basic(device_id: int = None):880def test_sub_basic(device_id: int = None):
856 """Test basic usage of sub function"""881 """Test basic usage of sub function"""
857 print("=" * 60)882 print("=" * 60)
@@ -882,6 +907,7 @@ def sub_broadcast_kernel(
882 out[:] = pypto.sub(a, b)907 out[:] = pypto.sub(a, b)
883 908 
884 909 
910+@pypto.options(pass_options={"enable_slice": True})
885def test_sub_broadcast(device_id: int = None):911def test_sub_broadcast(device_id: int = None):
886 """Test broadcasting between tensors of different shapes"""912 """Test broadcasting between tensors of different shapes"""
887 print("=" * 60)913 print("=" * 60)
@@ -910,6 +936,7 @@ def sub_scalar_kernel(a: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([],
910 out[:] = pypto.sub(a, scalar)936 out[:] = pypto.sub(a, scalar)
911 937 
912 938 
939+@pypto.options(pass_options={"enable_slice": True})
913def test_sub_scalar(device_id: int = None):940def test_sub_scalar(device_id: int = None):
914 """Test subing a scalar to a tensor"""941 """Test subing a scalar to a tensor"""
915 print("=" * 60)942 print("=" * 60)
@@ -82,6 +82,7 @@ def matmul_kernel(
82 out[:] = pypto.matmul(a, b, pypto.DT_FP32)82 out[:] = pypto.matmul(a, b, pypto.DT_FP32)
83 83 
84 84 
85+@pypto.options(pass_options={"enable_slice": True})
85def test_matmul_basic(device_id: int = None):86def test_matmul_basic(device_id: int = None):
86 """Test basic matrix multiplication"""87 """Test basic matrix multiplication"""
87 print("=" * 60)88 print("=" * 60)
@@ -112,6 +113,7 @@ def matmul_batch_kernel(
112 out[:] = pypto.matmul(a, b, pypto.DT_FP32)113 out[:] = pypto.matmul(a, b, pypto.DT_FP32)
113 114 
114 115 
116+@pypto.options(pass_options={"enable_slice": True})
115def test_matmul_batch(device_id: int = None):117def test_matmul_batch(device_id: int = None):
116 """Test batch matrix multiplication"""118 """Test batch matrix multiplication"""
117 print("=" * 60)119 print("=" * 60)
@@ -142,6 +144,7 @@ def matmul_broadcast_kernel(
142 out[:] = pypto.matmul(a, b, pypto.DT_FP32)144 out[:] = pypto.matmul(a, b, pypto.DT_FP32)
143 145 
144 146 
147+@pypto.options(pass_options={"enable_slice": True})
145def test_matmul_broadcast(device_id: int = None):148def test_matmul_broadcast(device_id: int = None):
146 """Test batch matrix multiplication with broadcasting"""149 """Test batch matrix multiplication with broadcasting"""
147 print("=" * 60)150 print("=" * 60)
@@ -180,6 +183,7 @@ def matmul_trans_left_kernel(
180 out[:] = pypto.matmul(a, b, pypto.DT_FP32, a_trans=True)183 out[:] = pypto.matmul(a, b, pypto.DT_FP32, a_trans=True)
181 184 
182 185 
186+@pypto.options(pass_options={"enable_slice": True})
183def test_matmul_trans(device_id: int = None):187def test_matmul_trans(device_id: int = None):
184 """Test matrix multiplication with transposition"""188 """Test matrix multiplication with transposition"""
185 print("=" * 60)189 print("=" * 60)
@@ -242,6 +246,7 @@ def matmul_bias_kernel(
242 out[:] = pypto.matmul(a, b, pypto.DT_FP32, extend_params=extend_params)246 out[:] = pypto.matmul(a, b, pypto.DT_FP32, extend_params=extend_params)
243 247 
244 248 
249+@pypto.options(pass_options={"enable_slice": True})
245def test_matmul_bias(device_id: int = None):250def test_matmul_bias(device_id: int = None):
246 """Test matrix multiplication with bias"""251 """Test matrix multiplication with bias"""
247 print("=" * 60)252 print("=" * 60)
@@ -99,6 +99,7 @@ def sum_op(a: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor:
99 return out99 return out
100 100 
101 101 
102+@pypto.options(pass_options={"enable_slice": True})
102def test_sum_basic(device_id: int = None):103def test_sum_basic(device_id: int = None):
103 """Test basic usage of sum function"""104 """Test basic usage of sum function"""
104 print("=" * 60)105 print("=" * 60)
@@ -132,6 +133,7 @@ def test_sum_basic(device_id: int = None):
132 print("✓ Basic usage of sum function completed successfully")133 print("✓ Basic usage of sum function completed successfully")
133 134 
134 135 
136+@pypto.options(pass_options={"enable_slice": True})
135def test_sum_different_dimensions(device_id: int = None):137def test_sum_different_dimensions(device_id: int = None):
136 """Test reducing along different dimensions"""138 """Test reducing along different dimensions"""
137 print("=" * 60)139 print("=" * 60)
@@ -204,6 +206,7 @@ def amax_op(a: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor:
204 return out206 return out
205 207 
206 208 
209+@pypto.options(pass_options={"enable_slice": True})
207def test_amax_basic(device_id: int = None):210def test_amax_basic(device_id: int = None):
208 """Test basic usage of amax function"""211 """Test basic usage of amax function"""
209 print("=" * 60)212 print("=" * 60)
@@ -241,6 +244,7 @@ def test_amax_basic(device_id: int = None):
241 print("✓ Basic usage of amax function completed successfully")244 print("✓ Basic usage of amax function completed successfully")
242 245 
243 246 
247+@pypto.options(pass_options={"enable_slice": True})
244def test_amax_different_dimensions(device_id: int = None):248def test_amax_different_dimensions(device_id: int = None):
245 """Test reducing along different dimensions"""249 """Test reducing along different dimensions"""
246 print("=" * 60)250 print("=" * 60)
@@ -313,6 +317,7 @@ def amin_op(a: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor:
313 return out317 return out
314 318 
315 319 
320+@pypto.options(pass_options={"enable_slice": True})
316def test_amin_basic(device_id: int = None):321def test_amin_basic(device_id: int = None):
317 """Test basic usage of amin function"""322 """Test basic usage of amin function"""
318 print("=" * 60)323 print("=" * 60)
@@ -350,6 +355,7 @@ def test_amin_basic(device_id: int = None):
350 print("✓ Basic usage of amin function completed successfully")355 print("✓ Basic usage of amin function completed successfully")
351 356 
352 357 
358+@pypto.options(pass_options={"enable_slice": True})
353def test_amin_different_dimensions(device_id: int = None):359def test_amin_different_dimensions(device_id: int = None):
354 """Test reducing along different dimensions"""360 """Test reducing along different dimensions"""
355 print("=" * 60)361 print("=" * 60)
@@ -421,6 +427,7 @@ def maximum_op(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
421 return out427 return out
422 428 
423 429 
430+@pypto.options(pass_options={"enable_slice": True})
424def test_maximum_basic(device_id: int = None):431def test_maximum_basic(device_id: int = None):
425 """Test basic usage of maximum function"""432 """Test basic usage of maximum function"""
426 print("=" * 60)433 print("=" * 60)
@@ -480,6 +487,7 @@ def minimum_op(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
480 return out487 return out
481 488 
482 489 
490+@pypto.options(pass_options={"enable_slice": True})
483def test_minimum_basic(device_id: int = None):491def test_minimum_basic(device_id: int = None):
484 """Test basic usage of minimum function"""492 """Test basic usage of minimum function"""
485 print("=" * 60)493 print("=" * 60)
@@ -83,6 +83,7 @@ def compute_with_cube_tile_shapes_kernel(
83 out.move(pypto.matmul(a, b, a.dtype))83 out.move(pypto.matmul(a, b, a.dtype))
84 84 
85 85 
86+@pypto.options(pass_options={"enable_slice": True})
86def test_set_cube_tile_shapes_basic(device_id: int = None):87def test_set_cube_tile_shapes_basic(device_id: int = None):
87 """Test basic usage of set_cube_tile_shapes function"""88 """Test basic usage of set_cube_tile_shapes function"""
88 print("=" * 60)89 print("=" * 60)
@@ -151,6 +152,7 @@ def create_different_tile_shapes_kernel(run_mode=global_run_mode):
151 return compute_with_different_tile_shapes152 return compute_with_different_tile_shapes
152 153 
153 154 
155+@pypto.options(pass_options={"enable_slice": True})
154def test_set_different_tile_shapes_result(device_id: int = None):156def test_set_different_tile_shapes_result(device_id: int = None):
155 """Test the impact of different tile shape settings on calculation results"""157 """Test the impact of different tile shape settings on calculation results"""
156 print("=" * 60)158 print("=" * 60)
@@ -200,6 +202,7 @@ def compute_with_tile_64_kernel(
200 out.move(pypto.matmul(a, b, a.dtype, b_trans=True))202 out.move(pypto.matmul(a, b, a.dtype, b_trans=True))
201 203 
202 204 
205+@pypto.options(pass_options={"enable_slice": True})
203def test_set_different_tile_shapes_runtime(device_id: int = None):206def test_set_different_tile_shapes_runtime(device_id: int = None):
204 """Test the impact of different tile shape settings on runtime"""207 """Test the impact of different tile shape settings on runtime"""
205 print("=" * 60)208 print("=" * 60)
@@ -246,6 +249,7 @@ def compute_with_vec_tile_shapes_kernel(
246 out.move(pypto.add(a, b))249 out.move(pypto.add(a, b))
247 250 
248 251 
252+@pypto.options(pass_options={"enable_slice": True})
249def test_set_vec_tile_shapes_basic(device_id: int = None):253def test_set_vec_tile_shapes_basic(device_id: int = None):
250 """Test basic usage of set_vec_tile_shapes function"""254 """Test basic usage of set_vec_tile_shapes function"""
251 print("=" * 60)255 print("=" * 60)
@@ -310,6 +314,7 @@ def compute_with_vec_different_tile_shapes_kernel(
310 out3.move(pypto.add(a, b))314 out3.move(pypto.add(a, b))
311 315 
312 316 
317+@pypto.options(pass_options={"enable_slice": True})
313def test_set_vec_different_tile_shapes_result(device_id: int = None):318def test_set_vec_different_tile_shapes_result(device_id: int = None):
314 """Test the impact of different tile shape settings on calculation results"""319 """Test the impact of different tile shape settings on calculation results"""
315 print("=" * 60)320 print("=" * 60)
@@ -344,6 +349,7 @@ def compute_with_vec_tile_kernel(a: pypto.Tensor(), b: pypto.Tensor(), out: pypt
344 out.move(pypto.add(a, b))349 out.move(pypto.add(a, b))
345 350 
346 351 
352+@pypto.options(pass_options={"enable_slice": True})
347def test_set_vec_different_tile_shapes_runtime(device_id: int = None):353def test_set_vec_different_tile_shapes_runtime(device_id: int = None):
348 """Test the impact of different tile shape settings on runtime"""354 """Test the impact of different tile shape settings on runtime"""
349 print("=" * 60)355 print("=" * 60)
@@ -94,6 +94,7 @@ def add_scalar_loop_view_assemble_kernel(
94 pypto.assemble(t3_sub, [b_offset, 0, 0, 0], output)94 pypto.assemble(t3_sub, [b_offset, 0, 0, 0], output)
95 95 
96 96 
97+@pypto.options(pass_options={"enable_slice": True})
97def test_add_scalar_loop_view_assemble(device_id=None, dynamic: bool = True) -> None:98def test_add_scalar_loop_view_assemble(device_id=None, dynamic: bool = True) -> None:
98 device = f'npu:{device_id}' if global_run_mode == pypto.RunMode.NPU and device_id is not None else 'cpu'99 device = f'npu:{device_id}' if global_run_mode == pypto.RunMode.NPU and device_id is not None else 'cpu'
99 100 
@@ -82,6 +82,7 @@ def assemble_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], py
82 pypto.assemble(x, offsets, out)82 pypto.assemble(x, offsets, out)
83 83 
84 84 
85+@pypto.options(pass_options={"enable_slice": True})
85def test_assemble_basic(device_id: int = None):86def test_assemble_basic(device_id: int = None):
86 """Test basic usage of assemble function"""87 """Test basic usage of assemble function"""
87 print("=" * 60)88 print("=" * 60)
@@ -107,6 +108,7 @@ def test_assemble_basic(device_id: int = None):
107 assert_allclose(out.cpu().numpy(), expected.cpu().numpy(), rtol=1e-3, atol=1e-3)108 assert_allclose(out.cpu().numpy(), expected.cpu().numpy(), rtol=1e-3, atol=1e-3)
108 109 
109 110 
111+@pypto.options(pass_options={"enable_slice": True})
110def test_assemble_different_offsets_shapes(device_id: int = None):112def test_assemble_different_offsets_shapes(device_id: int = None):
111 """Test basic usage of assemble function"""113 """Test basic usage of assemble function"""
112 print("=" * 60)114 print("=" * 60)
@@ -172,6 +174,7 @@ def gather_kernel(
172 out[:] = pypto.gather(input_tensor, dim, index_tensor)174 out[:] = pypto.gather(input_tensor, dim, index_tensor)
173 175 
174 176 
177+@pypto.options(pass_options={"enable_slice": True})
175def test_gather_basic(device_id: int = None):178def test_gather_basic(device_id: int = None):
176 """Test basic usage of gather function"""179 """Test basic usage of gather function"""
177 print("=" * 60)180 print("=" * 60)
@@ -198,6 +201,7 @@ def test_gather_basic(device_id: int = None):
198 print("✓ Basic usage of gather function completed successfully")201 print("✓ Basic usage of gather function completed successfully")
199 202 
200 203 
204+@pypto.options(pass_options={"enable_slice": True})
201def test_gather_different_dimensions(device_id: int = None):205def test_gather_different_dimensions(device_id: int = None):
202 """Test gathering tensors along different dimensions"""206 """Test gathering tensors along different dimensions"""
203 print("=" * 60)207 print("=" * 60)
@@ -232,6 +236,7 @@ def test_gather_different_dimensions(device_id: int = None):
232 print("✓ Test gatherenating tensors along different dimensions completed successfully")236 print("✓ Test gatherenating tensors along different dimensions completed successfully")
233 237 
234 238 
239+@pypto.options(pass_options={"enable_slice": True})
235def test_gather_negative_indexing(device_id: int = None):240def test_gather_negative_indexing(device_id: int = None):
236 """Test handling negative indexing"""241 """Test handling negative indexing"""
237 print("=" * 60)242 print("=" * 60)
@@ -276,6 +281,7 @@ def scatter_kernel(
276 out[:] = pypto.scatter(x, dim, y, src)281 out[:] = pypto.scatter(x, dim, y, src)
277 282 
278 283 
284+@pypto.options(pass_options={"enable_slice": True})
279def test_scatter(device_id: int = None):285def test_scatter(device_id: int = None):
280 """Test basic usage of scatter function"""286 """Test basic usage of scatter function"""
281 print("=" * 60)287 print("=" * 60)
@@ -319,6 +325,7 @@ def scatter_update_kernel(
319 out[:] = pypto.scatter(x, dim, y, src)325 out[:] = pypto.scatter(x, dim, y, src)
320 326 
321 327 
328+@pypto.options(pass_options={"enable_slice": True})
322def test_scatter_update(device_id: int = None) -> None:329def test_scatter_update(device_id: int = None) -> None:
323 """Test basic usage of scatter_update function"""330 """Test basic usage of scatter_update function"""
324 print("=" * 60)331 print("=" * 60)
@@ -385,6 +392,7 @@ def concat_multiple_op(a_shape: tuple, b_shape: tuple, c_shape: tuple, dim: int)
385 return concat_multiple_kernel392 return concat_multiple_kernel
386 393 
387 394 
395+@pypto.options(pass_options={"enable_slice": True})
388def test_concat_basic(device_id: int = None):396def test_concat_basic(device_id: int = None):
389 """Test basic usage of concat function"""397 """Test basic usage of concat function"""
390 print("=" * 60)398 print("=" * 60)
@@ -410,6 +418,7 @@ def test_concat_basic(device_id: int = None):
410 print("✓ Basic usage of concat function completed successfully")418 print("✓ Basic usage of concat function completed successfully")
411 419 
412 420 
421+@pypto.options(pass_options={"enable_slice": True})
413def test_concat_different_dimensions(device_id: int = None):422def test_concat_different_dimensions(device_id: int = None):
414 """Test concatenating tensors along different dimensions"""423 """Test concatenating tensors along different dimensions"""
415 print("=" * 60)424 print("=" * 60)
@@ -436,6 +445,7 @@ def test_concat_different_dimensions(device_id: int = None):
436 print("✓ Test concatenating tensors along different dimensions completed successfully")445 print("✓ Test concatenating tensors along different dimensions completed successfully")
437 446 
438 447 
448+@pypto.options(pass_options={"enable_slice": True})
439def test_concat_multiple_tensors(device_id: int = None):449def test_concat_multiple_tensors(device_id: int = None):
440 """Test concatenating multiple tensors"""450 """Test concatenating multiple tensors"""
441 print("=" * 60)451 print("=" * 60)
@@ -463,6 +473,7 @@ def test_concat_multiple_tensors(device_id: int = None):
463 print("✓ Test concatenating multiple tensors completed successfully")473 print("✓ Test concatenating multiple tensors completed successfully")
464 474 
465 475 
476+@pypto.options(pass_options={"enable_slice": True})
466def test_concat_different_shapes(device_id: int = None):477def test_concat_different_shapes(device_id: int = None):
467 """Test concatenating tensors of different shapes"""478 """Test concatenating tensors of different shapes"""
468 print("=" * 60)479 print("=" * 60)
@@ -500,6 +511,7 @@ def view_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.
500 out[:] = pypto.view(x, shape, offsets)511 out[:] = pypto.view(x, shape, offsets)
501 512 
502 513 
514+@pypto.options(pass_options={"enable_slice": True})
503def test_view_basic(device_id: int = None):515def test_view_basic(device_id: int = None):
504 """Test basic usage of view function"""516 """Test basic usage of view function"""
505 print("=" * 60)517 print("=" * 60)
@@ -543,6 +555,7 @@ def view_with_valid_shape_kernel(
543 out[:] = pypto.view(x, shape, offsets, valid_shape=valid_shape)555 out[:] = pypto.view(x, shape, offsets, valid_shape=valid_shape)
544 556 
545 557 
558+@pypto.options(pass_options={"enable_slice": True})
546def test_view_with_valid_shape(device_id: int = None):559def test_view_with_valid_shape(device_id: int = None):
547 """Test using the valid_shape parameter"""560 """Test using the valid_shape parameter"""
548 print("=" * 60)561 print("=" * 60)
@@ -586,6 +599,7 @@ def transpose_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], p
586 out[:] = pypto.transpose(x, dim0, dim1)599 out[:] = pypto.transpose(x, dim0, dim1)
587 600 
588 601 
602+@pypto.options(pass_options={"enable_slice": True})
589def test_transpose(device_id: int = None):603def test_transpose(device_id: int = None):
590 """Test basic usage of transpose function"""604 """Test basic usage of transpose function"""
591 print("=" * 60)605 print("=" * 60)
@@ -639,6 +653,7 @@ def cast_kernel(x: pypto.Tensor([], pypto.DT_FP32), out: pypto.Tensor([], pypto.
639 out[:] = pypto.cast(x, pypto.DT_FP16)653 out[:] = pypto.cast(x, pypto.DT_FP16)
640 654 
641 655 
656+@pypto.options(pass_options={"enable_slice": True})
642def test_cast(device_id: int = None):657def test_cast(device_id: int = None):
643 """Test basic usage of cast function"""658 """Test basic usage of cast function"""
644 print("=" * 60)659 print("=" * 60)
@@ -266,6 +266,7 @@ def ffn_activation_kernel(
266 pypto.assemble(result, [0, 0], output)266 pypto.assemble(result, [0, 0], output)
267 267 
268 268 
269+@pypto.options(pass_options={"enable_slice": True})
269def test_ffn_static_gelu(device_id=None):270def test_ffn_static_gelu(device_id=None):
270 """Test static FFN with GELU activation."""271 """Test static FFN with GELU activation."""
271 print("=" * 60)272 print("=" * 60)
@@ -321,6 +322,7 @@ def test_ffn_static_gelu(device_id=None):
321 print()322 print()
322 323 
323 324 
325+@pypto.options(pass_options={"enable_slice": True})
324def test_ffn_static_swiglu(device_id=None):326def test_ffn_static_swiglu(device_id=None):
325 """Test static FFN with SwiGLU activation."""327 """Test static FFN with SwiGLU activation."""
326 print("=" * 60)328 print("=" * 60)
@@ -378,6 +380,7 @@ def test_ffn_static_swiglu(device_id=None):
378 print()380 print()
379 381 
380 382 
383+@pypto.options(pass_options={"enable_slice": True})
381def test_ffn_dynamic_gelu(device_id: int = None, dynamic: bool = True):384def test_ffn_dynamic_gelu(device_id: int = None, dynamic: bool = True):
382 """Test dynamic FFN with GELU activation."""385 """Test dynamic FFN with GELU activation."""
383 print("=" * 60)386 print("=" * 60)
@@ -429,9 +432,7 @@ def test_ffn_dynamic_gelu(device_id: int = None, dynamic: bool = True):
429 432 
430 output = torch.empty(batch_size, hidden_size, dtype=dtype, device=device)433 output = torch.empty(batch_size, hidden_size, dtype=dtype, device=device)
431 if config.use_dynamic_shape and config.activation == "gelu":434 if config.use_dynamic_shape and config.activation == "gelu":
432- dynamic_gelu_activation_core(435+ dynamic_gelu_activation_core(hidden_states_torch, up_proj_weight_torch, down_proj_weight_torch, output, config)
433- hidden_states_torch, up_proj_weight_torch, down_proj_weight_torch, output, config
434- )
435 else:436 else:
436 ffn_activation_kernel(437 ffn_activation_kernel(
437 hidden_states_torch, gate_proj_weight_torch, up_proj_weight_torch, down_proj_weight_torch, output, config438 hidden_states_torch, gate_proj_weight_torch, up_proj_weight_torch, down_proj_weight_torch, output, config
@@ -443,6 +444,7 @@ def test_ffn_dynamic_gelu(device_id: int = None, dynamic: bool = True):
443 print()444 print()
444 445 
445 446 
447+@pypto.options(pass_options={"enable_slice": True})
446def test_ffn_static_relu(device_id: int = None):448def test_ffn_static_relu(device_id: int = None):
447 """Test static FFN with ReLU activation."""449 """Test static FFN with ReLU activation."""
448 print("=" * 60)450 print("=" * 60)
@@ -120,6 +120,7 @@ def layer_norm_kernel(
120 pypto.assemble(out, [0, 0], output)120 pypto.assemble(out, [0, 0], output)
121 121 
122 122 
123+@pypto.options(pass_options={"enable_slice": True})
123def test_layer_norm(device_id=None, dynamic: bool = False):124def test_layer_norm(device_id=None, dynamic: bool = False):
124 """Test LayerNorm."""125 """Test LayerNorm."""
125 print("=" * 60)126 print("=" * 60)
@@ -175,6 +176,7 @@ def rms_norm_kernel(x: pypto.Tensor(), gamma: pypto.Tensor(), output: pypto.Tens
175 pypto.assemble(out, [0, 0], output)176 pypto.assemble(out, [0, 0], output)
176 177 
177 178 
179+@pypto.options(pass_options={"enable_slice": True})
178def test_rms_norm(device_id=None, dynamic: bool = False) -> None:180def test_rms_norm(device_id=None, dynamic: bool = False) -> None:
179 """Test RMSNorm."""181 """Test RMSNorm."""
180 print("=" * 60)182 print("=" * 60)
@@ -96,6 +96,7 @@ def nested_loops_with_conditions_kernel(
96 y[i:i + 1, j:j + 1] = a_view - b_view96 y[i:i + 1, j:j + 1] = a_view - b_view
97 97 
98 98 
99+@pypto.options(pass_options={"enable_slice": True})
99def test_nested_loops_with_conditions(device_id=None, dynamic: bool = True) -> None:100def test_nested_loops_with_conditions(device_id=None, dynamic: bool = True) -> None:
100 """Test nested loops with conditional statements."""101 """Test nested loops with conditional statements."""
101 print("=" * 60)102 print("=" * 60)
@@ -166,6 +167,7 @@ def add_scalar_loop_dyn_axis_static_cond_kernel_dynamic(
166 add_core(input0, input1, output, val, flag)167 add_core(input0, input1, output, val, flag)
167 168 
168 169 
170+@pypto.options(pass_options={"enable_slice": True})
169def test_add_scalar_loop_dyn_axis_static_cond(device_id=None) -> None:171def test_add_scalar_loop_dyn_axis_static_cond(device_id=None) -> None:
170 """Test dynamic axis with static (compile-time) condition."""172 """Test dynamic axis with static (compile-time) condition."""
171 print("=" * 60)173 print("=" * 60)
@@ -229,6 +231,7 @@ def add_scalar_loop_dyn_axis_dyn_cond_kernel(
229 output[b_offset:b_offset_end, ...] = t3_sub231 output[b_offset:b_offset_end, ...] = t3_sub
230 232 
231 233 
234+@pypto.options(pass_options={"enable_slice": True})
232def test_add_scalar_loop_dynamic_axis_dynamic_cond(device_id=None) -> None:235def test_add_scalar_loop_dynamic_axis_dynamic_cond(device_id=None) -> None:
233 """Test dynamic axis with dynamic (runtime) condition."""236 """Test dynamic axis with dynamic (runtime) condition."""
234 print("=" * 60)237 print("=" * 60)
@@ -288,6 +291,7 @@ def add_scalar_loop_dyn_axis_dyn_loop_cond_kernel(
288 output[b_offset:b_offset_end, ...] = t3_sub291 output[b_offset:b_offset_end, ...] = t3_sub
289 292 
290 293 
294+@pypto.options(pass_options={"enable_slice": True})
291def test_add_scalar_loop_dynamic_axis_dynamic_loop_cond(device_id=None) -> None:295def test_add_scalar_loop_dynamic_axis_dynamic_loop_cond(device_id=None) -> None:
292 """Test dynamic axis with loop boundary conditions (is_loop_begin / is_loop_end)."""296 """Test dynamic axis with loop boundary conditions (is_loop_begin / is_loop_end)."""
293 print("=" * 60)297 print("=" * 60)
@@ -95,6 +95,7 @@ def loop_basic_kernel(
95 out1[bs_idx * s:(bs_idx + new_step) * s, :] = pypto.add(t0s, t1s)95 out1[bs_idx * s:(bs_idx + new_step) * s, :] = pypto.add(t0s, t1s)
96 96 
97 97 
98+@pypto.options(pass_options={"enable_slice": True})
98def test_loop_basic(device_id: int = None, dynamic: bool = False) -> None:99def test_loop_basic(device_id: int = None, dynamic: bool = False) -> None:
99 """Test basic loop usage."""100 """Test basic loop usage."""
100 print("=" * 60)101 print("=" * 60)
@@ -128,9 +129,7 @@ def test_loop_basic(device_id: int = None, dynamic: bool = False) -> None:
128# ============================================================================129# ============================================================================
129 130 
130 131 
131-@pypto.frontend.jit(132+@pypto.frontend.jit(runtime_options={"run_mode": global_run_mode})
132- runtime_options={"run_mode": global_run_mode}
133-)
134def loop_compile_phase_print_kernel(133def loop_compile_phase_print_kernel(
135 in_t0: pypto.Tensor(), in_t1: pypto.Tensor(), out_t0: pypto.Tensor(), out_t1: pypto.Tensor()134 in_t0: pypto.Tensor(), in_t1: pypto.Tensor(), out_t0: pypto.Tensor(), out_t1: pypto.Tensor()
136):135):
@@ -168,6 +167,7 @@ def loop_compile_phase_print_kernel(
168 print(separator)167 print(separator)
169 168 
170 169 
170+@pypto.options(pass_options={"enable_slice": True})
171def test_loop_compile_phase_print(device_id: int = None, dynamic: bool = False) -> None:171def test_loop_compile_phase_print(device_id: int = None, dynamic: bool = False) -> None:
172 """Test loop compile phase print"""172 """Test loop compile phase print"""
173 print("=" * 60)173 print("=" * 60)
@@ -222,6 +222,7 @@ def add_kernel(
222 pypto.assemble(t3_sub, [b_offset, 0, 0, 0], output)222 pypto.assemble(t3_sub, [b_offset, 0, 0, 0], output)
223 223 
224 224 
225+@pypto.options(pass_options={"enable_slice": True})
225def test_add_scalar_loop(device_id=None, dynamic: bool = True) -> None:226def test_add_scalar_loop(device_id=None, dynamic: bool = True) -> None:
226 """Test loop-based scalar addition."""227 """Test loop-based scalar addition."""
227 print("=" * 60)228 print("=" * 60)
@@ -279,6 +280,7 @@ def add_scalar_loop_dynamic_axis_kernel(
279 pypto.assemble(t3_sub, [b_offset, 0, 0, 0], output)280 pypto.assemble(t3_sub, [b_offset, 0, 0, 0], output)
280 281 
281 282 
283+@pypto.options(pass_options={"enable_slice": True})
282def test_add_scalar_loop_dyn_axis(device_id: int = None) -> None:284def test_add_scalar_loop_dyn_axis(device_id: int = None) -> None:
283 """Test loop with dynamic axis."""285 """Test loop with dynamic axis."""
284 print("=" * 60)286 print("=" * 60)
@@ -124,6 +124,7 @@ def dynamic_mul_kernel(
124 pypto.assemble(result, [b_offset, 0], output)124 pypto.assemble(result, [b_offset, 0], output)
125 125 
126 126 
127+@pypto.options(pass_options={"enable_slice": True})
127def test_dynamic_mul(device_id: int = None):128def test_dynamic_mul(device_id: int = None):
128 """Test dynamic mul with different batch sizes - same kernel, no recompilation."""129 """Test dynamic mul with different batch sizes - same kernel, no recompilation."""
129 print("=" * 60)130 print("=" * 60)
@@ -186,6 +187,7 @@ def softmax_kernel(
186 output_tensor[b_offset:b_offset_end, ...] = softmax_out187 output_tensor[b_offset:b_offset_end, ...] = softmax_out
187 188 
188 189 
190+@pypto.options(pass_options={"enable_slice": True})
189def test_dynamic_partial(device_id: int = None):191def test_dynamic_partial(device_id: int = None):
190 """Test softmax with partial dynamic dimensions (only batch is dynamic)."""192 """Test softmax with partial dynamic dimensions (only batch is dynamic)."""
191 print("=" * 60)193 print("=" * 60)
@@ -310,6 +312,7 @@ def attention_kernel(
310 pypto.assemble(res, [bs_offset, 0, 0, 0], output_tensor)312 pypto.assemble(res, [bs_offset, 0, 0, 0], output_tensor)
311 313 
312 314 
315+@pypto.options(pass_options={"enable_slice": True})
313def test_dynamic_attention(device_id: int = None):316def test_dynamic_attention(device_id: int = None):
314 """Test attention with dynamic batch sizes."""317 """Test attention with dynamic batch sizes."""
315 print("=" * 60)318 print("=" * 60)
@@ -393,6 +396,7 @@ def dynamic_add_kernel(
393 pypto.assemble(result, [b_offset, h_offset], output)396 pypto.assemble(result, [b_offset, h_offset], output)
394 397 
395 398 
399+@pypto.options(pass_options={"enable_slice": True})
396def test_dynamic_multi_dim(device_id: int = None):400def test_dynamic_multi_dim(device_id: int = None):
397 """Test kernel with multiple dynamic dimensions."""401 """Test kernel with multiple dynamic dimensions."""
398 print("=" * 60)402 print("=" * 60)
@@ -142,6 +142,7 @@ def scaled_dot_product_attention_kernel(
142 pypto.assemble(res, [b_offset, 0, 0, 0], output_tensor)142 pypto.assemble(res, [b_offset, 0, 0, 0], output_tensor)
143 143 
144 144 
145+@pypto.options(pass_options={"enable_slice": True})
145def test_unordered_input_attention(device_id: int = None, dynamic: bool = True) -> None:146def test_unordered_input_attention(device_id: int = None, dynamic: bool = True) -> None:
146 """Test attention with kenel_unordered_input."""147 """Test attention with kenel_unordered_input."""
147 print("=" * 60)148 print("=" * 60)
@@ -190,6 +191,7 @@ def op_unordered_input_kernel(
190 out2.move(a * b)191 out2.move(a * b)
191 192 
192 193 
194+@pypto.options(pass_options={"enable_slice": True})
193def test_unordered_input_op(device_id: int = None, dynamic: bool = False) -> None:195def test_unordered_input_op(device_id: int = None, dynamic: bool = False) -> None:
194 """Test op with kenel_unordered_input"""196 """Test op with kenel_unordered_input"""
195 print("=" * 60)197 print("=" * 60)
@@ -119,6 +119,7 @@ def silu_activation_kernel(x: pypto.Tensor(), out: pypto.Tensor()):
119 out[:] = x * pypto.sigmoid(x)119 out[:] = x * pypto.sigmoid(x)
120 120 
121 121 
122+@pypto.options(pass_options={"enable_slice": True})
122def test_silu(device_id: int = None, dynamic: bool = False) -> None:123def test_silu(device_id: int = None, dynamic: bool = False) -> None:
123 """Test SiLU activation."""124 """Test SiLU activation."""
124 print("=" * 60)125 print("=" * 60)
@@ -161,6 +162,7 @@ def gelu_activation_kernel(x: pypto.Tensor(), out: pypto.Tensor()):
161 out[:] = x * pypto.sigmoid(x_scaled)162 out[:] = x * pypto.sigmoid(x_scaled)
162 163 
163 164 
165+@pypto.options(pass_options={"enable_slice": True})
164def test_gelu(device_id: int = None, dynamic: bool = False) -> None:166def test_gelu(device_id: int = None, dynamic: bool = False) -> None:
165 """Test GELU activation."""167 """Test GELU activation."""
166 print("=" * 60)168 print("=" * 60)
@@ -205,6 +207,7 @@ def swiglu_activation_kernel(gate: pypto.Tensor(), up: pypto.Tensor(), out: pypt
205 out[:] = swish * up207 out[:] = swish * up
206 208 
207 209 
210+@pypto.options(pass_options={"enable_slice": True})
208def test_swiglu(device_id: int = None, dynamic: bool = False) -> None:211def test_swiglu(device_id: int = None, dynamic: bool = False) -> None:
209 """Test SwiGLU activation."""212 """Test SwiGLU activation."""
210 print("=" * 60)213 print("=" * 60)
@@ -251,6 +254,7 @@ def geglu_activation_kernel(gate: pypto.Tensor(), up: pypto.Tensor(), out: pypto
251 out[:] = gelu_gate * up254 out[:] = gelu_gate * up
252 255 
253 256 
257+@pypto.options(pass_options={"enable_slice": True})
254def test_geglu(device_id: int = None, dynamic: bool = False) -> None:258def test_geglu(device_id: int = None, dynamic: bool = False) -> None:
255 """Test GeGLU activation."""259 """Test GeGLU activation."""
256 print("=" * 60)260 print("=" * 60)
@@ -111,6 +111,7 @@ def softmax_kernel(
111 output_tensor[b_offset:, ...] = softmax_out111 output_tensor[b_offset:, ...] = softmax_out
112 112 
113 113 
114+@pypto.options(pass_options={"enable_slice": True})
114def test_softmax(device_id: int = None, dynamic: bool = True) -> None:115def test_softmax(device_id: int = None, dynamic: bool = True) -> None:
115 device = f'npu:{device_id}' if global_run_mode == pypto.RunMode.NPU and device_id is not None else 'cpu'116 device = f'npu:{device_id}' if global_run_mode == pypto.RunMode.NPU and device_id is not None else 'cpu'
116 117 
@@ -123,6 +123,7 @@ class MM(torch.nn.Module):
123 return out123 return out
124 124 
125 125 
126+@pypto.options(pass_options={"enable_slice": True})
126def test_softmax_capture(device_id=None, dynamic: bool = True) -> None:127def test_softmax_capture(device_id=None, dynamic: bool = True) -> None:
127 if not device_id:128 if not device_id:
128 device_id = torch.npu.current_device()129 device_id = torch.npu.current_device()
@@ -141,6 +141,7 @@ def scaled_dot_product_attention_kernel(
141 output.move(pypto.matmul(attn_weights, v, out_dtype=pypto.DT_BF16))141 output.move(pypto.matmul(attn_weights, v, out_dtype=pypto.DT_BF16))
142 142 
143 143 
144+@pypto.options(pass_options={"enable_slice": True})
144def test_scaled_dot_product_attention(device_id=None, dynamic: bool = False) -> None:145def test_scaled_dot_product_attention(device_id=None, dynamic: bool = False) -> None:
145 """Test attention function with dynamic shapes."""146 """Test attention function with dynamic shapes."""
146 print("=" * 60)147 print("=" * 60)
@@ -272,6 +273,7 @@ def attention_with_projection_golden(
272 return output273 return output
273 274 
274 275 
276+@pypto.options(pass_options={"enable_slice": True})
275def test_attention_with_projection(device_id=None, dynamic: bool = False) -> None:277def test_attention_with_projection(device_id=None, dynamic: bool = False) -> None:
276 """Test complete attention with input/output projections."""278 """Test complete attention with input/output projections."""
277 print("=" * 60)279 print("=" * 60)
@@ -116,6 +116,7 @@ def softmax(input_tensor: pypto.Tensor(), output_tensor: pypto.Tensor()):
116 pypto.assemble(softmax_out, [b_offset, 0, 0, 0], output_tensor)116 pypto.assemble(softmax_out, [b_offset, 0, 0, 0], output_tensor)
117 117 
118 118 
119+@pypto.options(pass_options={"enable_slice": True})
119def test_softmax(cost_model_enable=True):120def test_softmax(cost_model_enable=True):
120 """121 """
121 Run softmax with optional cost model.122 Run softmax with optional cost model.
@@ -178,6 +178,7 @@ def attention_kernel(q: pypto.tensor(), k: pypto.tensor(), v: pypto.tensor(), ou
178 out[:] = pypto.matmul(attn_weights, v, out_dtype=out.dtype)178 out[:] = pypto.matmul(attn_weights, v, out_dtype=out.dtype)
179 179 
180 180 
181+@pypto.options(pass_options={"enable_slice": True})
181def test_sequential_functions(device_id: int = None, dynamic: bool = False) -> None:182def test_sequential_functions(device_id: int = None, dynamic: bool = False) -> None:
182 """Test multiple functions in sequence."""183 """Test multiple functions in sequence."""
183 print("=" * 60)184 print("=" * 60)
@@ -221,6 +222,7 @@ def test_sequential_functions(device_id: int = None, dynamic: bool = False) -> N
221 print()222 print()
222 223 
223 224 
225+@pypto.options(pass_options={"enable_slice": True})
224def test_residual_connection(device_id: int = None, dynamic: bool = False) -> None:226def test_residual_connection(device_id: int = None, dynamic: bool = False) -> None:
225 """Test residual connection pattern."""227 """Test residual connection pattern."""
226 print("=" * 60)228 print("=" * 60)
@@ -254,6 +256,7 @@ def test_residual_connection(device_id: int = None, dynamic: bool = False) -> No
254 print()256 print()
255 257 
256 258 
259+@pypto.options(pass_options={"enable_slice": True})
257def test_transformer_block(device_id: int = None, dynamic: bool = False) -> None:260def test_transformer_block(device_id: int = None, dynamic: bool = False) -> None:
258 """Test a complete transformer block using multiple functions."""261 """Test a complete transformer block using multiple functions."""
259 print("=" * 60)262 print("=" * 60)
@@ -322,6 +325,7 @@ def test_transformer_block(device_id: int = None, dynamic: bool = False) -> None
322 print()325 print()
323 326 
324 327 
328+@pypto.options(pass_options={"enable_slice": True})
325def test_function_reuse(device_id: int = None, dynamic: bool = True) -> None:329def test_function_reuse(device_id: int = None, dynamic: bool = True) -> None:
326 """Test reusing the same function multiple times."""330 """Test reusing the same function multiple times."""
327 print("=" * 60)331 print("=" * 60)
@@ -89,6 +89,7 @@ def add_kernel(
89 out[:] = add_core(input0, input1, add1_flag)89 out[:] = add_core(input0, input1, add1_flag)
90 90 
91 91 
92+@pypto.options(pass_options={"enable_slice": True})
92def test_add_scalar_loop_multi_jit(device_id=None) -> None:93def test_add_scalar_loop_multi_jit(device_id=None) -> None:
93 device = f'npu:{device_id}' if global_run_mode == pypto.RunMode.NPU and device_id is not None else 'cpu'94 device = f'npu:{device_id}' if global_run_mode == pypto.RunMode.NPU and device_id is not None else 'cpu'
94 95 
@@ -543,9 +543,15 @@ std::string CodeGenOpNPU::PrintMemCopyWithL0CTileTensor(const PrintMemCopyWithL0
543 return oss.str();543 return oss.str();
544}544}
545 545 
546-std::vector<std::string> CodeGenOpNPU::GenTileOpParamForNormalCopyTileTensor(unsigned gmIdx) const546+std::vector<std::string> CodeGenOpNPU::GenTileOpParamForNormalCopyTileTensor(unsigned gmIdx,
547+ bool useOffsetFromAttr) const
547{548{
548- std::vector<std::string> gmOffsetExpr = GetGmOffsetForTileTensor(gmIdx);549+ std::vector<std::string> gmOffsetExpr;
550+ if (useOffsetFromAttr || functionType == FunctionType::STATIC) {
551+ gmOffsetExpr = GetGmOffsetForTileTensor(gmIdx);
552+ } else {
553+ gmOffsetExpr = GenGetParamMacroPacked(gmIdx, static_cast<int>(rawShape[gmIdx].size()), PREFIX_STR_OFFSET);
554+ }
549 // e.g. ((RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 0)),(RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 1)))555 // e.g. ((RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 0)),(RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 1)))
550 std::string coordCp = WrapParamByParentheses(gmOffsetExpr);556 std::string coordCp = WrapParamByParentheses(gmOffsetExpr);
551 // e.g. Coord4Dim((RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 0)),(RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 1)))557 // e.g. Coord4Dim((RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 0)),(RUNTIME_COA_GET_PARAM_OFFSET(2, 136, 1)))
@@ -362,7 +362,7 @@ protected:
362 std::string PrintCompact(const PrintUnaryTmpBuffParam& param) const;362 std::string PrintCompact(const PrintUnaryTmpBuffParam& param) const;
363 std::string PrintCompactStatic(const PrintUnaryTmpBuffParam& param) const;363 std::string PrintCompactStatic(const PrintUnaryTmpBuffParam& param) const;
364 364 
365- std::vector<std::string> GenTileOpParamForNormalCopyTileTensor(unsigned gmIdx) const;365+ std::vector<std::string> GenTileOpParamForNormalCopyTileTensor(unsigned gmIdx, bool useOffsetFromAttr = true) const;
366 void AppendGmValidShapeForReshapeCopy(std::vector<std::string>& tileOpParamList, unsigned gmIdx) const;366 void AppendGmValidShapeForReshapeCopy(std::vector<std::string>& tileOpParamList, unsigned gmIdx) const;
367 std::string PrintMemCopyWithL0C(const PrintMemCopyWithL0CParam& param) const;367 std::string PrintMemCopyWithL0C(const PrintMemCopyWithL0CParam& param) const;
368 std::string PrintMemCopyWithL0CStatic(const PrintMemCopyWithL0CParam& param) const;368 std::string PrintMemCopyWithL0CStatic(const PrintMemCopyWithL0CParam& param) const;
@@ -52,6 +52,7 @@ void ExecuteOpAssemble(ExecuteOperationContext* ctx)
52 }52 }
53}53}
54REGISTER_CALC_OP(OP_ASSEMBLE, Opcode::OP_ASSEMBLE, ExecuteOpAssemble);54REGISTER_CALC_OP(OP_ASSEMBLE, Opcode::OP_ASSEMBLE, ExecuteOpAssemble);
55+REGISTER_CALC_OP(OP_CONTRACT, Opcode::OP_CONTRACT, ExecuteOpAssemble);
55REGISTER_CALC_OP(OP_ASSEMBLE_SSA, Opcode::OP_ASSEMBLE_SSA, ExecuteOpAssemble);56REGISTER_CALC_OP(OP_ASSEMBLE_SSA, Opcode::OP_ASSEMBLE_SSA, ExecuteOpAssemble);
56 57 
57void ExecuteOpAtomicRMW(ExecuteOperationContext* ctx)58void ExecuteOpAtomicRMW(ExecuteOperationContext* ctx)
@@ -213,6 +214,7 @@ void ExecuteOpView(ExecuteOperationContext* ctx)
213 }214 }
214}215}
215REGISTER_CALC_OP(OP_VIEW, Opcode::OP_VIEW, ExecuteOpView);216REGISTER_CALC_OP(OP_VIEW, Opcode::OP_VIEW, ExecuteOpView);
217+REGISTER_CALC_OP(OP_SLICE, Opcode::OP_SLICE, ExecuteOpView);
216 218 
217void ExecuteOpCopyOut(ExecuteOperationContext* ctx)219void ExecuteOpCopyOut(ExecuteOperationContext* ctx)
218{220{
@@ -412,7 +412,7 @@ void FunctionInterpreter::FillOperationOutputInfo(
412 if (k < ooperandDataViewList->size()) {412 if (k < ooperandDataViewList->size()) {
413 auto dataView = ooperandDataViewList->at(k);413 auto dataView = ooperandDataViewList->at(k);
414 std::string dumpTensorFileName = GetDumpTensorFileName(op->GetOOperands()[k], op, frame);414 std::string dumpTensorFileName = GetDumpTensorFileName(op->GetOOperands()[k], op, frame);
415- bool isRaw = (op->GetOpcode() == Opcode::OP_COPY_OUT || op->GetOpcode() == Opcode::OP_ASSEMBLE);415+ bool isRaw = (op->GetOpcode() == Opcode::OP_COPY_OUT || IsAssembleLike(op->GetOpcode()));
416 DumpTensorBinary(dataView, dumpTensorFileName, isRaw);416 DumpTensorBinary(dataView, dumpTensorFileName, isRaw);
417 if (execDumpFile) {417 if (execDumpFile) {
418 fprintf(execDumpFile, "<div class=\"detail indent_%d\">%s</a></div>\n", indent,418 fprintf(execDumpFile, "<div class=\"detail indent_%d\">%s</a></div>\n", indent,
@@ -344,8 +344,8 @@ struct FunctionFrame {
344private:344private:
345 bool IsAllowedInplaceChainOpcode(Opcode opcode) const345 bool IsAllowedInplaceChainOpcode(Opcode opcode) const
346 {346 {
347- return opcode == Opcode::OP_INDEX_OUTCAST || opcode == Opcode::OP_VIEW || opcode == Opcode::OP_RESHAPE ||347+ return opcode == Opcode::OP_INDEX_OUTCAST || IsViewLike(opcode) || opcode == Opcode::OP_RESHAPE ||
348- opcode == Opcode::OP_ASSEMBLE || opcode == Opcode::OP_PRINT || opcode == Opcode::OP_INDEX_ADD;348+ IsAssembleLike(opcode) || opcode == Opcode::OP_PRINT || opcode == Opcode::OP_INDEX_ADD;
349 }349 }
350 350 
351 void TryEraseOpIndex(Operation* op, const std::unordered_map<Operation*, int>& opIndexMap)351 void TryEraseOpIndex(Operation* op, const std::unordered_map<Operation*, int>& opIndexMap)
@@ -1081,7 +1081,7 @@ struct FunctionInterpreter {
1081 ASSERT(ControlFlowScene::INVALID_INPLACE_CHAIN, index != -1);1081 ASSERT(ControlFlowScene::INVALID_INPLACE_CHAIN, index != -1);
1082 auto iop = op.GetInputOperand(index);1082 auto iop = op.GetInputOperand(index);
1083 ASSERT(ControlFlowScene::INVALID_INPLACE_CHAIN, iOpDataList[index] != nullptr);1083 ASSERT(ControlFlowScene::INVALID_INPLACE_CHAIN, iOpDataList[index] != nullptr);
1084- if (op.GetOpcode() == Opcode::OP_VIEW) {1084+ if (IsViewLike(op.GetOpcode())) {
1085 if (iOpDataList[0]->IsShmTensor()) {1085 if (iOpDataList[0]->IsShmTensor()) {
1086 auto ret = AllocateDataView(frame, oop);1086 auto ret = AllocateDataView(frame, oop);
1087 ret->GetData()->SetAsShmTensor();1087 ret->GetData()->SetAsShmTensor();
@@ -267,8 +267,10 @@ void Operation::InitTensorGraphMetadata()
267 267 
268void Operation::InitLatency(Opcode opcode)268void Operation::InitLatency(Opcode opcode)
269{269{
270- const auto& latencyOperands = (opcode == Opcode::OP_COPY_IN || opcode == Opcode::OP_VIEW) ? GetOOperands() :270+ const auto& latencyOperands = (opcode == Opcode::OP_COPY_IN || opcode == Opcode::OP_VIEW ||
271- GetIOperands();271+ opcode == Opcode::OP_SLICE) ?
272+ GetOOperands() :
273+ GetIOperands();
272 if (!latencyOperands.empty()) {274 if (!latencyOperands.empty()) {
273 // Get operation latency275 // Get operation latency
274 latency_ = GetLatencyByOperands(latencyOperands, GetOpcodeStr());276 latency_ = GetLatencyByOperands(latencyOperands, GetOpcodeStr());
@@ -619,9 +621,11 @@ void Operation::LoadOpAttributeFromJson(const Json& opDump, Opcode opcode)
619 std::shared_ptr<OpAttribute> opAttribute;621 std::shared_ptr<OpAttribute> opAttribute;
620 switch (opcode) {622 switch (opcode) {
621 case Opcode::OP_VIEW:623 case Opcode::OP_VIEW:
624+ case Opcode::OP_SLICE:
622 opAttribute = DeserializeFrom<ViewOpAttribute>(attrJson);625 opAttribute = DeserializeFrom<ViewOpAttribute>(attrJson);
623 break;626 break;
624 case Opcode::OP_ASSEMBLE:627 case Opcode::OP_ASSEMBLE:
628+ case Opcode::OP_CONTRACT:
625 opAttribute = DeserializeFrom<AssembleOpAttribute>(attrJson);629 opAttribute = DeserializeFrom<AssembleOpAttribute>(attrJson);
626 break;630 break;
627 case Opcode::OP_CALL:631 case Opcode::OP_CALL:
@@ -1189,31 +1193,12 @@ bool Operation::IsNeedStackGM() const
1189 (OpcodeManager::Inst().IsCopyOut(opcode_) && std::any_of(oOperand.cbegin(), oOperand.cend(), isStack));1193 (OpcodeManager::Inst().IsCopyOut(opcode_) && std::any_of(oOperand.cbegin(), oOperand.cend(), isStack));
1190}1194}
1191 1195 
1192-static void AppendFromDynValidShapeRefs(CopyOpAttribute& copyAttr,
1193- std::vector<std::reference_wrapper<SymbolicScalar>>& dynamicAttributeList)
1194-{
1195- for (auto& shape : copyAttr.GetFromDynValidShape()) {
1196- if (shape.IsSpecified()) {
1197- dynamicAttributeList.push_back(std::reference_wrapper<SymbolicScalar>(shape.GetSpecifiedValue()));
1198- }
1199- }
1200-}
1201- 
1202-static void AppendToDynValidShapeRefs(CopyOpAttribute& copyAttr,
1203- std::vector<std::reference_wrapper<SymbolicScalar>>& dynamicAttributeList)
1204-{
1205- for (auto& shape : copyAttr.GetToDynValidShape()) {
1206- if (shape.IsSpecified()) {
1207- dynamicAttributeList.push_back(std::reference_wrapper<SymbolicScalar>(shape.GetSpecifiedValue()));
1208- }
1209- }
1210-}
1211- 
1212std::vector<std::reference_wrapper<SymbolicScalar>> Operation::GetDynamicAttributeList()1196std::vector<std::reference_wrapper<SymbolicScalar>> Operation::GetDynamicAttributeList()
1213{1197{
1214 std::vector<std::reference_wrapper<SymbolicScalar>> dynamicAttributeList;1198 std::vector<std::reference_wrapper<SymbolicScalar>> dynamicAttributeList;
1215 switch (GetOpcode()) {1199 switch (GetOpcode()) {
1216- case Opcode::OP_VIEW: {1200+ case Opcode::OP_VIEW:
1201+ case Opcode::OP_SLICE: {
1217 auto viewAttr = std::static_pointer_cast<ViewOpAttribute>(GetOpAttribute());1202 auto viewAttr = std::static_pointer_cast<ViewOpAttribute>(GetOpAttribute());
1218 if (viewAttr != nullptr) {1203 if (viewAttr != nullptr) {
1219 std::vector<SymbolicScalar>& viewFromDynOffset = viewAttr->GetFromDynOffset();1204 std::vector<SymbolicScalar>& viewFromDynOffset = viewAttr->GetFromDynOffset();
@@ -1230,6 +1215,7 @@ std::vector<std::reference_wrapper<SymbolicScalar>> Operation::GetDynamicAttribu
1230 }1215 }
1231 } break;1216 } break;
1232 case Opcode::OP_ASSEMBLE:1217 case Opcode::OP_ASSEMBLE:
1218+ case Opcode::OP_CONTRACT:
1233 [[fallthrough]];1219 [[fallthrough]];
1234 case Opcode::OP_ATOMIC_RMW: {1220 case Opcode::OP_ATOMIC_RMW: {
1235 auto assembleAttr = std::static_pointer_cast<AssembleOpAttribute>(GetOpAttribute());1221 auto assembleAttr = std::static_pointer_cast<AssembleOpAttribute>(GetOpAttribute());
@@ -1258,7 +1244,12 @@ std::vector<std::reference_wrapper<SymbolicScalar>> Operation::GetDynamicAttribu
1258 std::reference_wrapper<SymbolicScalar>(offset.GetSpecifiedValue()));1244 std::reference_wrapper<SymbolicScalar>(offset.GetSpecifiedValue()));
1259 }1245 }
1260 }1246 }
1261- AppendToDynValidShapeRefs(*copyAttr, dynamicAttributeList);1247+ for (auto& shape : copyAttr->GetToDynValidShape()) {
1248+ if (shape.IsSpecified()) {
1249+ dynamicAttributeList.push_back(
1250+ std::reference_wrapper<SymbolicScalar>(shape.GetSpecifiedValue()));
1251+ }
1252+ }
1262 }1253 }
1263 } break;1254 } break;
1264 case Opcode::OP_COPY_OUT:1255 case Opcode::OP_COPY_OUT:
@@ -1272,7 +1263,12 @@ std::vector<std::reference_wrapper<SymbolicScalar>> Operation::GetDynamicAttribu
1272 std::reference_wrapper<SymbolicScalar>(offset.GetSpecifiedValue()));1263 std::reference_wrapper<SymbolicScalar>(offset.GetSpecifiedValue()));
1273 }1264 }
1274 }1265 }
1275- AppendFromDynValidShapeRefs(*copyAttr, dynamicAttributeList);1266+ for (auto& shape : copyAttr->GetFromDynValidShape()) {
1267+ if (shape.IsSpecified()) {
1268+ dynamicAttributeList.push_back(
1269+ std::reference_wrapper<SymbolicScalar>(shape.GetSpecifiedValue()));
1270+ }
1271+ }
1276 }1272 }
1277 } break;1273 } break;
1278 case Opcode::OP_VEC_DUP: {1274 case Opcode::OP_VEC_DUP: {
@@ -1351,8 +1347,18 @@ std::vector<std::reference_wrapper<SymbolicScalar>> Operation::GetDynamicAttribu
1351 case Opcode::OP_RESHAPE_COPY_IN: {1347 case Opcode::OP_RESHAPE_COPY_IN: {
1352 auto copyAttr = std::static_pointer_cast<CopyOpAttribute>(GetOpAttribute());1348 auto copyAttr = std::static_pointer_cast<CopyOpAttribute>(GetOpAttribute());
1353 if (copyAttr) {1349 if (copyAttr) {
1354- AppendFromDynValidShapeRefs(*copyAttr, dynamicAttributeList);1350+ for (auto& shape : copyAttr->GetFromDynValidShape()) {
1355- AppendToDynValidShapeRefs(*copyAttr, dynamicAttributeList);1351+ if (shape.IsSpecified()) {
1352+ dynamicAttributeList.push_back(
1353+ std::reference_wrapper<SymbolicScalar>(shape.GetSpecifiedValue()));
1354+ }
1355+ }
1356+ for (auto& shape : copyAttr->GetToDynValidShape()) {
1357+ if (shape.IsSpecified()) {
1358+ dynamicAttributeList.push_back(
1359+ std::reference_wrapper<SymbolicScalar>(shape.GetSpecifiedValue()));
1360+ }
1361+ }
1356 }1362 }
1357 } break;1363 } break;
1358 default:1364 default:
@@ -1686,16 +1686,12 @@ Tensor Cat(const std::vector<Tensor>& tensors, int axis)
1686 1686 
1687 auto format = tensors[0].Format();1687 auto format = tensors[0].Format();
1688 Tensor result(tensors[0].GetDataType(), resultShape, "", format);1688 Tensor result(tensors[0].GetDataType(), resultShape, "", format);
1689- Tensor tmp(tensors[0].GetDataType(), resultShape, "", format);1689+ std::vector<SymbolicScalar> offset(shapeSize, 0);
1690- auto& function = *Program::GetInstance().GetCurrentFunction();
1691- std::vector<int64_t> offset(shapeSize, 0);
1692 for (auto tensor : tensors) {1690 for (auto tensor : tensors) {
1693- auto tmpView = tmp.GetStorage()->View(function, tensor.GetShape(), offset);1691+ auto materialized = Assign(tensor);
1694- InnerConcatNew(*Program::GetInstance().GetCurrentFunction(), tensor.GetStorage(), tmpView);1692+ Assemble(materialized, offset, result);
1695- offset[axis] += tensor.GetShape()[axis];1693+ offset[axis] = offset[axis] + tensor.GetShape()[axis];
1696 }1694 }
1697- auto& op = function.AddOperation(Opcode::OP_ASSEMBLE, {tmp.GetStorage()}, {result.GetStorage()});
1698- op.SetOpAttribute(std::make_shared<AssembleOpAttribute>(std::vector<int64_t>(shapeSize, 0)));
1699 1695 
1700 return result;1696 return result;
1701}1697}
@@ -36,6 +36,86 @@ std::string InferParamIndex::DumpParamIndex(const std::map<std::string, DynParam
36 }36 }
37 return ss.str();37 return ss.str();
38}38}
39+// 从 "sym_<magic>_dim_<idx>" 格式的符号名中解析出 tensor magic 与维度下标。
40+// 该格式由 ResetOutputDynValidShape 创建,用于给 CopyIn/CopyOut 的输出 valid shape 命名符号。
41+static bool ParseSymDimSymbolName(const std::string& name, int& magic, int& dimIdx)
42+{
43+ static const std::string kPrefix = "sym_";
44+ static const std::string kMid = "_dim_";
45+ if (name.rfind(kPrefix, 0) != 0) {
46+ return false;
47+ }
48+ size_t midPos = name.find(kMid, kPrefix.size());
49+ if (midPos == std::string::npos || midPos <= kPrefix.size() || midPos + kMid.size() >= name.size()) {
50+ return false;
51+ }
52+ try {
53+ magic = std::stoi(name.substr(kPrefix.size(), midPos - kPrefix.size()));
54+ dimIdx = std::stoi(name.substr(midPos + kMid.size()));
55+ } catch (...) {
56+ return false;
57+ }
58+ return true;
59+}
60+ 
61+// 递归收集 valid shape 表达式中引用的 sym_ 符号并注册到 DynParamTable。
62+// CopyIn/CopyOut 输出的 valid shape 可能被后续 InferShape(如 AssembleInferFunc 的 max 组合)
63+// 覆盖为复合表达式,此时其自身符号不再以顶层符号形式出现,若不同样注册,
64+// codegen 生成的表达式会引用未声明符号导致内核编译失败。
65+static void CollectNestedDynParamSymbols(const SymbolicScalar& scalar, const std::map<int, int>& magic2Coa,
66+ const std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
67+ const std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified,
68+ const std::map<int, int>& coa2TensorIndex,
69+ std::set<std::string>& visitedSymbol, Function& subFunc)
70+{
71+ auto raw = scalar.Raw();
72+ if (raw == nullptr) {
73+ return;
74+ }
75+ if (raw->IsSymbol()) {
76+ std::string name = raw->GetSymbolName();
77+ if (visitedSymbol.count(name) > 0) {
78+ return;
79+ }
80+ int magic = 0;
81+ int dimIdx = 0;
82+ if (!ParseSymDimSymbolName(name, magic, dimIdx)) {
83+ return;
84+ }
85+ auto magicIter = magic2Coa.find(magic);
86+ if (magicIter == magic2Coa.end()) {
87+ return;
88+ }
89+ int coa = magicIter->second;
90+ auto shapeIter = addr2ValidShape.find(coa);
91+ auto tensorIndexIter = coa2TensorIndex.find(coa);
92+ if (shapeIter == addr2ValidShape.end() || tensorIndexIter == coa2TensorIndex.end()) {
93+ return;
94+ }
95+ int dimSize = static_cast<int>(shapeIter->second.size());
96+ if (dimIdx < 0 || dimIdx >= dimSize) {
97+ return;
98+ }
99+ SymbolicScalar dynDim;
100+ auto specifiedIter = addr2ValidShapeSpecified.find(coa);
101+ if (specifiedIter != addr2ValidShapeSpecified.end() &&
102+ dimIdx < static_cast<int>(specifiedIter->second.size())) {
103+ dynDim = specifiedIter->second[dimIdx];
104+ }
105+ auto paramInfo = DynParamInfo{
106+ dimSize, tensorIndexIter->second, coa, DynParamInfoType::VALID_SHAPE, dimIdx, dynDim, false, ""};
107+ subFunc.InsertDynParam(name, paramInfo);
108+ visitedSymbol.insert(name);
109+ return;
110+ }
111+ if (raw->IsExpression()) {
112+ for (const auto& operand : raw->GetExpressionOperandList()) {
113+ CollectNestedDynParamSymbols(SymbolicScalar(operand), magic2Coa, addr2ValidShape, addr2ValidShapeSpecified,
114+ coa2TensorIndex, visitedSymbol, subFunc);
115+ }
116+ }
117+}
118+ 
39static bool IsInGMSpill(Operation& op)119static bool IsInGMSpill(Operation& op)
40{120{
41 if (OpcodeManager::Inst().IsCopyIn(op.GetOpcode())) {121 if (OpcodeManager::Inst().IsCopyIn(op.GetOpcode())) {
@@ -198,7 +278,7 @@ Status InferParamIndex::InferShape(Function& function)
198 278 
199Status InferParamIndex::InsertAddr2ValidShapeSpecified(279Status InferParamIndex::InsertAddr2ValidShapeSpecified(
200 Operation& op, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,280 Operation& op, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
201- std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified)281+ std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified, std::map<int, int>& magic2Coa)
202{282{
203 bool* distCopyType = op.GetAttr<bool>(OpAttributeKey::isDistCopyOut);283 bool* distCopyType = op.GetAttr<bool>(OpAttributeKey::isDistCopyOut);
204 // 暂不处理输入个数小于输出个数的copyIn,原因是coaIndex不够分284 // 暂不处理输入个数小于输出个数的copyIn,原因是coaIndex不够分
@@ -218,6 +298,9 @@ Status InferParamIndex::InsertAddr2ValidShapeSpecified(
218 if (tensorBaseAddrCoaIndex == -1) {298 if (tensorBaseAddrCoaIndex == -1) {
219 continue;299 continue;
220 }300 }
301+ if (OpcodeManager::Inst().IsCopyInOrOut(op.GetOpcode()) || setSymDimOps.count(op.GetOpcode())) {
302+ magic2Coa[op.GetOOperands()[i]->GetMagic()] = tensorBaseAddrCoaIndex;
303+ }
221 if (addr2ValidShape.find(tensorBaseAddrCoaIndex) == addr2ValidShape.end()) {304 if (addr2ValidShape.find(tensorBaseAddrCoaIndex) == addr2ValidShape.end()) {
222 addr2ValidShape[tensorBaseAddrCoaIndex] = op.GetOOperands()[i]->GetDynValidShape();305 addr2ValidShape[tensorBaseAddrCoaIndex] = op.GetOOperands()[i]->GetDynValidShape();
223 if (IsCopyIn(op.GetOpcode())) {306 if (IsCopyIn(op.GetOpcode())) {
@@ -240,10 +323,11 @@ Status InferParamIndex::InsertAddr2ValidShapeSpecified(
240}323}
241 324 
242Status InferParamIndex::UpdateValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,325Status InferParamIndex::UpdateValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
243- std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified)326+ std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified,
327+ std::map<int, int>& magic2Coa)
244{328{
245 for (auto& op : subFunc.Operations(false)) {329 for (auto& op : subFunc.Operations(false)) {
246- if (InsertAddr2ValidShapeSpecified(op, addr2ValidShape, addr2ValidShapeSpecified) != SUCCESS) {330+ if (InsertAddr2ValidShapeSpecified(op, addr2ValidShape, addr2ValidShapeSpecified, magic2Coa) != SUCCESS) {
247 APASS_LOG_ERROR_F(Elements::Function, "InsertAddr2ValidShapeSpecified failed");331 APASS_LOG_ERROR_F(Elements::Function, "InsertAddr2ValidShapeSpecified failed");
248 return FAILED;332 return FAILED;
249 }333 }
@@ -252,11 +336,14 @@ Status InferParamIndex::UpdateValidShape(Function& subFunc, std::map<int, std::v
252}336}
253 337 
254Status InferParamIndex::SetSubValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,338Status InferParamIndex::SetSubValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
255- std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified)339+ std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified,
340+ const std::map<int, int>& magic2Coa)
256{341{
257 std::set<std::string> visitedSymbol;342 std::set<std::string> visitedSymbol;
343+ std::map<int, int> coa2TensorIndex;
258 int tensorIndex{0};344 int tensorIndex{0};
259 for (auto validShape : addr2ValidShape) {345 for (auto validShape : addr2ValidShape) {
346+ coa2TensorIndex[validShape.first] = tensorIndex;
260 int dimIdx{0};347 int dimIdx{0};
261 for (auto dim : validShape.second) {348 for (auto dim : validShape.second) {
262 if (!dim.IsSymbol()) {349 if (!dim.IsSymbol()) {
@@ -283,6 +370,15 @@ Status InferParamIndex::SetSubValidShape(Function& subFunc, std::map<int, std::v
283 }370 }
284 tensorIndex++;371 tensorIndex++;
285 }372 }
373+ for (const auto& validShape : addr2ValidShape) {
374+ for (const auto& dim : validShape.second) {
375+ if (dim.IsSymbol()) {
376+ continue;
377+ }
378+ CollectNestedDynParamSymbols(dim, magic2Coa, addr2ValidShape, addr2ValidShapeSpecified, coa2TensorIndex,
379+ visitedSymbol, subFunc);
380+ }
381+ }
286 return SUCCESS;382 return SUCCESS;
287}383}
288 384 
@@ -302,13 +398,14 @@ Status InferParamIndex::UpdateParamIndex(Function& function)
302 APASS_LOG_DEBUG_F(Elements::Function, "Print function before update: %s\n", subFunc.Dump().c_str());398 APASS_LOG_DEBUG_F(Elements::Function, "Print function before update: %s\n", subFunc.Dump().c_str());
303 std::map<int, std::vector<SymbolicScalar>> addr2ValidShape;399 std::map<int, std::vector<SymbolicScalar>> addr2ValidShape;
304 std::map<int, std::vector<SymbolicScalar>> addr2ValidShapeSpecified;400 std::map<int, std::vector<SymbolicScalar>> addr2ValidShapeSpecified;
305- if (UpdateValidShape(subFunc, addr2ValidShape, addr2ValidShapeSpecified) != SUCCESS) {401+ std::map<int, int> magic2Coa;
402+ if (UpdateValidShape(subFunc, addr2ValidShape, addr2ValidShapeSpecified, magic2Coa) != SUCCESS) {
306 APASS_LOG_ERROR_F(Elements::Function,403 APASS_LOG_ERROR_F(Elements::Function,
307 "Update valid shape for the function %s failed. Please check above for more information.",404 "Update valid shape for the function %s failed. Please check above for more information.",
308 function.GetRawName().c_str());405 function.GetRawName().c_str());
309 return FAILED;406 return FAILED;
310 }407 }
311- if (SetSubValidShape(subFunc, addr2ValidShape, addr2ValidShapeSpecified) != SUCCESS) {408+ if (SetSubValidShape(subFunc, addr2ValidShape, addr2ValidShapeSpecified, magic2Coa) != SUCCESS) {
312 APASS_LOG_ERROR_F(Elements::Function,409 APASS_LOG_ERROR_F(Elements::Function,
313 "Update valid shape for the function %s failed. Please check above for more information.",410 "Update valid shape for the function %s failed. Please check above for more information.",
314 function.GetRawName().c_str());411 function.GetRawName().c_str());
@@ -45,11 +45,14 @@ private:
45 Status ResetAssembleDynValidShape(const Operation& op);45 Status ResetAssembleDynValidShape(const Operation& op);
46 Status ResetDynValidShape(Function& function);46 Status ResetDynValidShape(Function& function);
47 Status InsertAddr2ValidShapeSpecified(Operation& op, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,47 Status InsertAddr2ValidShapeSpecified(Operation& op, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
48- std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified);48+ std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified,
49+ std::map<int, int>& magic2Coa);
49 Status UpdateValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,50 Status UpdateValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
50- std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified);51+ std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified,
52+ std::map<int, int>& magic2Coa);
51 Status SetSubValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,53 Status SetSubValidShape(Function& subFunc, std::map<int, std::vector<SymbolicScalar>>& addr2ValidShape,
52- std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified);54+ std::map<int, std::vector<SymbolicScalar>>& addr2ValidShapeSpecified,
55+ const std::map<int, int>& magic2Coa);
53 Status UpdateParamIndex(Function& function);56 Status UpdateParamIndex(Function& function);
54 Status InferShape(Function& function);57 Status InferShape(Function& function);
55};58};
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include "assign_memory_type_checker.h"16#include "assign_memory_type_checker.h"
17+#include "interface/configs/config_manager.h"
17#include "passes/pass_log/pass_log.h"18#include "passes/pass_log/pass_log.h"
18#include "passes/pass_utils/graph_utils.h"19#include "passes/pass_utils/graph_utils.h"
19#include "tilefwk/error_code.h"20#include "tilefwk/error_code.h"
@@ -24,8 +25,8 @@
24namespace npu {25namespace npu {
25namespace tile_fwk {26namespace tile_fwk {
26const std::unordered_set<Opcode> AssignMemoryTypeChecker::kValidProducerOpcodes = {27const std::unordered_set<Opcode> AssignMemoryTypeChecker::kValidProducerOpcodes = {
27- Opcode::OP_L1_TO_L0A, Opcode::OP_L1_TO_L0B, Opcode::OP_L1_TO_L0_AT,28+ Opcode::OP_L1_TO_L0A, Opcode::OP_L1_TO_L0B, Opcode::OP_L1_TO_L0_AT, Opcode::OP_L1_TO_L0_BT,
28- Opcode::OP_L1_TO_L0_BT, Opcode::OP_VIEW, Opcode::OP_VEC_DUP};29+ Opcode::OP_VIEW, Opcode::OP_SLICE, Opcode::OP_VEC_DUP};
29const std::unordered_set<MemoryType> AssignMemoryTypeChecker::kValidViewToTypes = {30const std::unordered_set<MemoryType> AssignMemoryTypeChecker::kValidViewToTypes = {
30 MemoryType::MEM_BT, MemoryType::MEM_FIX_QUANT_PRE, MemoryType::MEM_L0A, MemoryType::MEM_L0B,31 MemoryType::MEM_BT, MemoryType::MEM_FIX_QUANT_PRE, MemoryType::MEM_L0A, MemoryType::MEM_L0B,
31 MemoryType::MEM_L0AMX, MemoryType::MEM_L0BMX, MemoryType::MEM_UNKNOWN};32 MemoryType::MEM_L0AMX, MemoryType::MEM_L0BMX, MemoryType::MEM_UNKNOWN};
@@ -69,8 +70,9 @@ Status AssignMemoryTypeChecker::DoPreCheck(Function& function)
69 70 
70Status AssignMemoryTypeChecker::CheckAmulBInputProducers(Operation& operation)71Status AssignMemoryTypeChecker::CheckAmulBInputProducers(Operation& operation)
71{72{
72- auto inputs = operation.GetIOperands();
73 auto producerOps = operation.ProducerOps();73 auto producerOps = operation.ProducerOps();
74+ const Opcode expectedViewLikeOpcode = config::EnableSlice() ? Opcode::OP_SLICE : Opcode::OP_VIEW;
75+ const auto& expectedViewLikeOpcodeStr = OpcodeManager::Inst().GetOpcodeStr(expectedViewLikeOpcode);
74 for (auto& producerOp : producerOps) {76 for (auto& producerOp : producerOps) {
75 auto producerOpcode = producerOp->GetOpcode();77 auto producerOpcode = producerOp->GetOpcode();
76 if (!kValidProducerOpcodes.count(producerOpcode)) {78 if (!kValidProducerOpcodes.count(producerOpcode)) {
@@ -82,16 +84,34 @@ Status AssignMemoryTypeChecker::CheckAmulBInputProducers(Operation& operation)
82 GetFormatBacktrace(operation).c_str());84 GetFormatBacktrace(operation).c_str());
83 return FAILED;85 return FAILED;
84 }86 }
85- if (producerOpcode == Opcode::OP_VIEW) {87+ if (producerOpcode == Opcode::OP_VIEW || producerOpcode == Opcode::OP_SLICE) {
88+ if (producerOpcode != expectedViewLikeOpcode) {
89+ APASS_LOG_ERROR_C(OperationErr::OP_SPECIAL_CONSTRAINT, Elements::Operation,
90+ "Memory error, %s[%d] has invalid input %s; "
91+ "Please check input %s[%d]. %s",
92+ operation.GetOpcodeStr().c_str(), operation.GetOpMagic(),
93+ producerOp->GetOpcodeStr().c_str(), expectedViewLikeOpcodeStr.c_str(),
94+ producerOp->GetOpMagic(), GetFormatBacktrace(operation).c_str());
95+ return FAILED;
96+ }
86 auto viewOpAttribute = dynamic_cast<ViewOpAttribute*>(producerOp->GetOpAttribute().get());97 auto viewOpAttribute = dynamic_cast<ViewOpAttribute*>(producerOp->GetOpAttribute().get());
98+ if (viewOpAttribute == nullptr) {
99+ APASS_LOG_ERROR_C(OperationErr::OP_SPECIAL_CONSTRAINT, Elements::Operation,
100+ "Slice attribute error, %s[%d] has input %s without ViewOpAttribute; "
101+ "Please check input view %s[%d]. %s",
102+ operation.GetOpcodeStr().c_str(), operation.GetOpMagic(),
103+ producerOp->GetOpcodeStr().c_str(), producerOp->GetOpcodeStr().c_str(),
104+ producerOp->GetOpMagic(), GetFormatBacktrace(operation).c_str());
105+ return FAILED;
106+ }
87 MemoryType attrToType = viewOpAttribute->GetTo();107 MemoryType attrToType = viewOpAttribute->GetTo();
88 if (!kValidViewToTypes.count(attrToType)) {108 if (!kValidViewToTypes.count(attrToType)) {
89 APASS_LOG_ERROR_C(OperationErr::OP_SPECIAL_CONSTRAINT, Elements::Operation,109 APASS_LOG_ERROR_C(OperationErr::OP_SPECIAL_CONSTRAINT, Elements::Operation,
90- "View attribute error, %s[%d] has invalid input OP_VIEW(toType: %d); "110+ "Slice attribute error, %s[%d] has invalid input %s(toType: %d); "
91 "Please check input view %s[%d]. %s",111 "Please check input view %s[%d]. %s",
92- operation.GetOpcodeStr().c_str(), operation.GetOpMagic(), attrToType,112+ operation.GetOpcodeStr().c_str(), operation.GetOpMagic(),
93- producerOp->GetOpcodeStr().c_str(), producerOp->GetOpMagic(),113+ producerOp->GetOpcodeStr().c_str(), attrToType, producerOp->GetOpcodeStr().c_str(),
94- GetFormatBacktrace(operation).c_str());114+ producerOp->GetOpMagic(), GetFormatBacktrace(operation).c_str());
95 return FAILED;115 return FAILED;
96 }116 }
97 }117 }
@@ -104,8 +124,14 @@ void AssignMemoryTypeChecker::CheckPattern(Operation* operation, std::queue<std:
104 int depth, std::unordered_set<Operation*>& visited)124 int depth, std::unordered_set<Operation*>& visited)
105{125{
106 for (auto& tensor : operation->oOperand) {126 for (auto& tensor : operation->oOperand) {
127+ if (tensor == nullptr) {
128+ continue;
129+ }
107 for (auto& consumerOp : tensor->GetConsumers()) {130 for (auto& consumerOp : tensor->GetConsumers()) {
108- if (consumerOp->GetOpcode() == Opcode::OP_VIEW || consumerOp->GetOpcode() == Opcode::OP_ASSEMBLE ||131+ if (consumerOp == nullptr) {
132+ continue;
133+ }
134+ if (IsViewLike(consumerOp->GetOpcode()) || IsAssembleLike(consumerOp->GetOpcode()) ||
109 consumerOp->GetOpcode() == Opcode::OP_RESHAPE) {135 consumerOp->GetOpcode() == Opcode::OP_RESHAPE) {
110 Operation* consumerOpPtr = consumerOp;136 Operation* consumerOpPtr = consumerOp;
111 if (visited.find(consumerOpPtr) == visited.end()) {137 if (visited.find(consumerOpPtr) == visited.end()) {
@@ -24,8 +24,8 @@
24 24 
25namespace npu {25namespace npu {
26namespace tile_fwk {26namespace tile_fwk {
27-std::unordered_set<Opcode> inplaceNodes{Opcode::OP_VIEW, Opcode::OP_ASSEMBLE, Opcode::OP_RESHAPE,27+std::unordered_set<Opcode> inplaceNodes{Opcode::OP_VIEW, Opcode::OP_SLICE, Opcode::OP_ASSEMBLE,
28- Opcode::OP_INDEX_OUTCAST};28+ Opcode::OP_CONTRACT, Opcode::OP_RESHAPE, Opcode::OP_INDEX_OUTCAST};
29 29 
30Status checkAssemble(const std::unordered_map<LogicalTensorPtr, int64_t>& tensorMap,30Status checkAssemble(const std::unordered_map<LogicalTensorPtr, int64_t>& tensorMap,
31 const std::unordered_map<LogicalTensorPtr, std::pair<Offset, Offset>>& offsetMap,31 const std::unordered_map<LogicalTensorPtr, std::pair<Offset, Offset>>& offsetMap,
@@ -65,7 +65,7 @@ Status checkView(Operation* op)
65{65{
66 for (const auto& logicTensor : op->GetIOperands()) {66 for (const auto& logicTensor : op->GetIOperands()) {
67 auto producers = logicTensor->GetProducers();67 auto producers = logicTensor->GetProducers();
68- if (producers.size() != 1 || (*producers.begin())->GetOpcode() != Opcode::OP_VIEW) {68+ if (producers.size() != 1 || (*producers.begin())->GetOpcode() != Opcode::OP_SLICE) {
69 continue;69 continue;
70 }70 }
71 auto shape = logicTensor->GetShape();71 auto shape = logicTensor->GetShape();
@@ -75,7 +75,7 @@ Status checkView(Operation* op)
75 if (logicTensor->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR) {75 if (logicTensor->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR) {
76 APASS_LOG_ERROR_C(76 APASS_LOG_ERROR_C(
77 TensorErr::TENSOR_INVALID_MEMORY_TYPE, Elements::Tensor,77 TensorErr::TENSOR_INVALID_MEMORY_TYPE, Elements::Tensor,
78- "Tensor(%d) memory type is MEM_DEVICE_DDR, which is not supported for VIEW->ASSEMBLE case.",78+ "Tensor(%d) memory type is MEM_DEVICE_DDR, which is not supported for view-like->assemble-like case.",
79 logicTensor->GetMagic());79 logicTensor->GetMagic());
80 return FAILED;80 return FAILED;
81 }81 }
@@ -93,7 +93,7 @@ Status checkTensor(const LogicalTensorPtr& tensor)
93 if (inplaceNodes.find(producer->GetOpcode()) == inplaceNodes.end()) {93 if (inplaceNodes.find(producer->GetOpcode()) == inplaceNodes.end()) {
94 continue;94 continue;
95 }95 }
96- if (producer->GetOpcode() != Opcode::OP_ASSEMBLE) {96+ if (!IsAssembleLike(producer->GetOpcode())) {
97 allAssemble = false;97 allAssemble = false;
98 continue;98 continue;
99 }99 }
@@ -90,7 +90,7 @@ Status GraphPartitionChecker::PostOperationCheck(Function& function)
90 if (isStartNodeInSubgraph) {90 if (isStartNodeInSubgraph) {
91 APASS_LOG_DEBUG_F(Elements::Operation, "Operation (opmagic: %d) is start node in subgraph.",91 APASS_LOG_DEBUG_F(Elements::Operation, "Operation (opmagic: %d) is start node in subgraph.",
92 op.GetOpMagic());92 op.GetOpMagic());
93- if (op.GetOpcode() == Opcode::OP_ASSEMBLE || op.GetOpcode() == Opcode::OP_COPY_OUT) {93+ if (IsAssembleLike(op.GetOpcode()) || op.GetOpcode() == Opcode::OP_COPY_OUT) {
94 APASS_LOG_ERROR_F(94 APASS_LOG_ERROR_F(
95 Elements::Operation,95 Elements::Operation,
96 "Operation (opmagic: %d) is the start node of the subgraph, opcode should not be %s.%s",96 "Operation (opmagic: %d) is the start node of the subgraph, opcode should not be %s.%s",
@@ -112,7 +112,7 @@ Status GraphPartitionChecker::PostOperationCheck(Function& function)
112 }112 }
113 if (isEndNodeInSubgraph) {113 if (isEndNodeInSubgraph) {
114 APASS_LOG_DEBUG_F(Elements::Operation, "Operation (opmagic: %d) is end node in subgraph.", op.GetOpMagic());114 APASS_LOG_DEBUG_F(Elements::Operation, "Operation (opmagic: %d) is end node in subgraph.", op.GetOpMagic());
115- if (op.GetOpcode() == Opcode::OP_VIEW || op.GetOpcode() == Opcode::OP_COPY_IN) {115+ if (IsViewLike(op.GetOpcode()) || op.GetOpcode() == Opcode::OP_COPY_IN) {
116 APASS_LOG_ERROR_F(Elements::Operation,116 APASS_LOG_ERROR_F(Elements::Operation,
117 "Operation (opmagic: %d) is the end node of the subgraph, opcode should not be %s.%s",117 "Operation (opmagic: %d) is the end node of the subgraph, opcode should not be %s.%s",
118 op.GetOpMagic(), op.GetOpcodeStr().c_str(), GetFormatBacktrace(op).c_str());118 op.GetOpMagic(), op.GetOpcodeStr().c_str(), GetFormatBacktrace(op).c_str());
@@ -31,9 +31,7 @@ const std::unordered_set<Opcode>& CommonOperationEliminateUtils::GetSkipEliminat
31{31{
32 // Opcodes in this set are excluded from common operation elimination on purpose:32 // Opcodes in this set are excluded from common operation elimination on purpose:
33 // - OP_VIEW: works with GraphPartition processing logic.33 // - OP_VIEW: works with GraphPartition processing logic.
34- static const std::unordered_set<Opcode> skipOpcodes = {34+ static const std::unordered_set<Opcode> skipOpcodes = {Opcode::OP_VIEW, Opcode::OP_SLICE};
35- Opcode::OP_VIEW,
36- };
37 return skipOpcodes;35 return skipOpcodes;
38}36}
39 37 
@@ -16,9 +16,12 @@
16#include "graph_utils.h"16#include "graph_utils.h"
17#include "pass_utils.h"17#include "pass_utils.h"
18#include "interface/tensor/irbuilder.h"18#include "interface/tensor/irbuilder.h"
19+#include "passes/pass_log/pass_log.h"
19#include "passes/pass_utils/pass_attr_defs.h"20#include "passes/pass_utils/pass_attr_defs.h"
20#include "passes/pass_utils/pass_operation_utils.h"21#include "passes/pass_utils/pass_operation_utils.h"
21 22 
23+#define MODULE_NAME "GraphUtils"
24+ 
22namespace npu {25namespace npu {
23namespace tile_fwk {26namespace tile_fwk {
24 27 
@@ -47,7 +50,12 @@ Operation& GraphUtils::AddAssembleOperation(Function& function, const AssembleOp
47 const std::vector<std::vector<SymbolicScalar>>& outDynShape)50 const std::vector<std::vector<SymbolicScalar>>& outDynShape)
48{51{
49 IRBuilder builder;52 IRBuilder builder;
50- auto& newOp = builder.CreateTensorOpStmt(function, Opcode::OP_ASSEMBLE, {assemble.input}, {assemble.output});53+ if (!IsAssembleLike(assemble.opcode)) {
54+ APASS_LOG_WARN_F(Elements::Operation,
55+ "Invalid assemble-family opcode for AddAssembleOperation, fallback to OP_ASSEMBLE.");
56+ }
57+ const auto opcode = IsAssembleLike(assemble.opcode) ? assemble.opcode : Opcode::OP_ASSEMBLE;
58+ auto& newOp = builder.CreateTensorOpStmt(function, opcode, {assemble.input}, {assemble.output});
51 if (assemble.originOp != nullptr) {59 if (assemble.originOp != nullptr) {
52 newOp.SetScopeInfo(assemble.originOp->GetScopeInfo());60 newOp.SetScopeInfo(assemble.originOp->GetScopeInfo());
53 newOp.CopyAttrFrom(*assemble.originOp, "");61 newOp.CopyAttrFrom(*assemble.originOp, "");
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include "passes/pass_utils/infer_discontinuous_input_utils.h"16#include "passes/pass_utils/infer_discontinuous_input_utils.h"
17+#include "interface/configs/config_manager_ng.h"
17#include "passes/pass_log/pass_log.h"18#include "passes/pass_log/pass_log.h"
18#include "passes/pass_utils/infer_shape_utils.h"19#include "passes/pass_utils/infer_shape_utils.h"
19#include "passes/pass_utils/pass_utils.h"20#include "passes/pass_utils/pass_utils.h"
@@ -105,7 +106,7 @@ inline bool NoViewConflict(Function& function,
105 for (size_t i = 0; i < inplaceTensors.size(); i++) {106 for (size_t i = 0; i < inplaceTensors.size(); i++) {
106 auto tensor = inplaceTensors[i].first;107 auto tensor = inplaceTensors[i].first;
107 for (auto& producer : tensor->GetProducers()) {108 for (auto& producer : tensor->GetProducers()) {
108- if (producer->GetOpcode() == Opcode::OP_VIEW) {109+ if (IsViewLike(producer->GetOpcode())) {
109 viewOps[i] = producer;110 viewOps[i] = producer;
110 }111 }
111 }112 }
@@ -131,8 +132,9 @@ inline bool NoViewConflict(Function& function,
131std::vector<std::pair<LogicalTensorPtr, Operation*>> InferDiscontinuousInputUtils::GetInplacedTileTensors(132std::vector<std::pair<LogicalTensorPtr, Operation*>> InferDiscontinuousInputUtils::GetInplacedTileTensors(
132 LogicalTensorPtr targetTensor)133 LogicalTensorPtr targetTensor)
133{134{
134- static const std::unordered_set<Opcode> inplaceNodes{Opcode::OP_VIEW, Opcode::OP_ASSEMBLE, Opcode::OP_RESHAPE,135+ static const std::unordered_set<Opcode> inplaceNodes{Opcode::OP_VIEW, Opcode::OP_SLICE,
135- Opcode::OP_INDEX_OUTCAST};136+ Opcode::OP_ASSEMBLE, Opcode::OP_CONTRACT,
137+ Opcode::OP_RESHAPE, Opcode::OP_INDEX_OUTCAST};
136 std::vector<std::pair<LogicalTensorPtr, Operation*>> inplacedTensor;138 std::vector<std::pair<LogicalTensorPtr, Operation*>> inplacedTensor;
137 for (auto& producer : targetTensor->GetProducers()) {139 for (auto& producer : targetTensor->GetProducers()) {
138 if (inplaceNodes.count(producer->GetOpcode()) == 0) {140 if (inplaceNodes.count(producer->GetOpcode()) == 0) {
@@ -145,7 +147,7 @@ std::vector<std::pair<LogicalTensorPtr, Operation*>> InferDiscontinuousInputUtil
145 continue;147 continue;
146 }148 }
147 auto consumerOp = *consumers.begin();149 auto consumerOp = *consumers.begin();
148- if (consumerOp == nullptr || consumerOp->GetOpcode() == Opcode::OP_ASSEMBLE) {150+ if (consumerOp == nullptr || IsAssembleLike(consumerOp->GetOpcode())) {
149 continue;151 continue;
150 }152 }
151 constexpr int kIndexOutcastInplaceInputIdx = 2;153 constexpr int kIndexOutcastInplaceInputIdx = 2;
@@ -212,7 +214,7 @@ void InferDiscontinuousInputUtils::DDRTensorAssignUB(
212 insertedNodes.reserve(opList.size());214 insertedNodes.reserve(opList.size());
213 for (size_t i = 0; i < opList.size(); ++i) {215 for (size_t i = 0; i < opList.size(); ++i) {
214 Operation* currOp = opList[i];216 Operation* currOp = opList[i];
215- if (currOp->GetOpcode() != Opcode::OP_ASSEMBLE) {217+ if (!IsAssembleLike(currOp->GetOpcode())) {
216 continue;218 continue;
217 }219 }
218 for (LogicalTensorPtr ioperand : currOp->GetIOperands()) {220 for (LogicalTensorPtr ioperand : currOp->GetIOperands()) {
@@ -220,7 +222,7 @@ void InferDiscontinuousInputUtils::DDRTensorAssignUB(
220 continue;222 continue;
221 }223 }
222 auto& producers = ioperand->GetProducers();224 auto& producers = ioperand->GetProducers();
223- if (producers.size() != 1 || (*producers.begin())->GetOpcode() != Opcode::OP_VIEW) {225+ if (producers.size() != 1 || !IsViewLike((*producers.begin())->GetOpcode())) {
224 continue;226 continue;
225 }227 }
226 auto& inOp = *producers.begin();228 auto& inOp = *producers.begin();
@@ -321,23 +323,26 @@ Status InferDiscontinuousInputUtils::InferFromIncast(Function& function, bool ch
321void InferDiscontinuousInputUtils::InsertViewOp(Function& function, LogicalTensorPtr iOperand,323void InferDiscontinuousInputUtils::InsertViewOp(Function& function, LogicalTensorPtr iOperand,
322 LogicalTensorPtr oOperand)324 LogicalTensorPtr oOperand)
323{325{
324- auto& insertViewOp = irBuilder_.CreateTensorOpStmt(function, Opcode::OP_VIEW, {iOperand}, {oOperand});326+ auto& insertViewOp = irBuilder_.CreateTensorOpStmt(function, config::GetSliceOpcode(), {iOperand}, {oOperand});
325 newOps_.push_back(&insertViewOp);327 newOps_.push_back(&insertViewOp);
326 insertViewOp.SetOpAttribute(328 insertViewOp.SetOpAttribute(
327 std::make_shared<ViewOpAttribute>(iOperand->GetOffset(), oOperand->GetMemoryTypeOriginal(),329 std::make_shared<ViewOpAttribute>(iOperand->GetOffset(), oOperand->GetMemoryTypeOriginal(),
328 iOperand->GetDynOffset(), iOperand->GetDynValidShape()));330 iOperand->GetDynOffset(), iOperand->GetDynValidShape()));
329- APASS_LOG_DEBUG_F(Elements::Operation, "Insert view op [%d].", insertViewOp.GetOpMagic());331+ APASS_LOG_DEBUG_F(Elements::Operation, "Insert %s op [%d].", insertViewOp.GetOpcodeStr().c_str(),
332+ insertViewOp.GetOpMagic());
330}333}
331 334 
332void InferDiscontinuousInputUtils::InsertAssembleOp(Function& function, LogicalTensorPtr iOperand,335void InferDiscontinuousInputUtils::InsertAssembleOp(Function& function, LogicalTensorPtr iOperand,
333 LogicalTensorPtr oOperand)336 LogicalTensorPtr oOperand)
334{337{
335- auto& insertAssembleOp = irBuilder_.CreateTensorOpStmt(function, Opcode::OP_ASSEMBLE, {iOperand}, {oOperand});338+ auto& insertAssembleOp = irBuilder_.CreateTensorOpStmt(function, config::GetContractOpcode(), {iOperand},
339+ {oOperand});
336 newOps_.push_back(&insertAssembleOp);340 newOps_.push_back(&insertAssembleOp);
337 insertAssembleOp.SetOpAttribute(341 insertAssembleOp.SetOpAttribute(
338 std::make_shared<AssembleOpAttribute>(iOperand->GetMemoryTypeOriginal(), oOperand->GetOffset(),342 std::make_shared<AssembleOpAttribute>(iOperand->GetMemoryTypeOriginal(), oOperand->GetOffset(),
339 oOperand->GetDynOffset(), oOperand->GetDynValidShape()));343 oOperand->GetDynOffset(), oOperand->GetDynValidShape()));
340- APASS_LOG_DEBUG_F(Elements::Operation, "Insert assemble op [%d].", insertAssembleOp.GetOpMagic());344+ APASS_LOG_DEBUG_F(Elements::Operation, "Insert %s op [%d].", insertAssembleOp.GetOpcodeStr().c_str(),
345+ insertAssembleOp.GetOpMagic());
341}346}
342 347 
343void InferDiscontinuousInputUtils::InsertCopyOp(Function& function, LogicalTensorPtr iOperand,348void InferDiscontinuousInputUtils::InsertCopyOp(Function& function, LogicalTensorPtr iOperand,
@@ -99,6 +99,40 @@ std::string GetRmwModeAttrKey(const RmwModeAttrState& rmwModeAttr)
99 return "";99 return "";
100 }100 }
101}101}
102+ 
103+bool IsViewLikeOpcode(Opcode opcode) { return opcode == Opcode::OP_VIEW || opcode == Opcode::OP_SLICE; }
104+ 
105+bool IsAssembleLikeOpcode(Opcode opcode) { return opcode == Opcode::OP_ASSEMBLE || opcode == Opcode::OP_CONTRACT; }
106+ 
107+bool ChainHasOpcode(const std::vector<Operation*>& chain, Opcode opcode)
108+{
109+ for (const auto* op : chain) {
110+ if (op != nullptr && op->GetOpcode() == opcode) {
111+ return true;
112+ }
113+ }
114+ return false;
115+}
116+ 
117+bool CanMergeViewLikeChain(const std::vector<Operation*>& chain, Opcode nextOpcode)
118+{
119+ return !(ChainHasOpcode(chain, Opcode::OP_SLICE) && nextOpcode == Opcode::OP_SLICE);
120+}
121+ 
122+bool CanMergeAssembleLikeChain(const std::vector<Operation*>& chain, Opcode nextOpcode)
123+{
124+ return !(ChainHasOpcode(chain, Opcode::OP_CONTRACT) && nextOpcode == Opcode::OP_CONTRACT);
125+}
126+ 
127+Opcode GetMergedViewOpcode(const std::vector<Operation*>& chain)
128+{
129+ return ChainHasOpcode(chain, Opcode::OP_SLICE) ? Opcode::OP_SLICE : Opcode::OP_VIEW;
130+}
131+ 
132+Opcode GetMergedAssembleOpcode(const std::vector<Operation*>& chain)
133+{
134+ return ChainHasOpcode(chain, Opcode::OP_CONTRACT) ? Opcode::OP_CONTRACT : Opcode::OP_ASSEMBLE;
135+}
102} // namespace136} // namespace
103 137 
104Status MergeViewAssembleUtils::MergeViewAssemble(Function& function)138Status MergeViewAssembleUtils::MergeViewAssemble(Function& function)
@@ -158,10 +192,10 @@ const MergeViewAssembleUtils::ConsumerCacheEntry& MergeViewAssembleUtils::BuildT
158 if (consumer == nullptr || consumer->BelongTo() != &function || consumer->IsDeleted()) {192 if (consumer == nullptr || consumer->BelongTo() != &function || consumer->IsDeleted()) {
159 continue;193 continue;
160 }194 }
161- if (consumer->GetOpcode() == Opcode::OP_VIEW) {195+ if (IsViewLikeOpcode(consumer->GetOpcode())) {
162 cacheEntry.viewConsumers.emplace_back(consumer);196 cacheEntry.viewConsumers.emplace_back(consumer);
163 cacheEntry.hasAssembleChainStopper = true;197 cacheEntry.hasAssembleChainStopper = true;
164- } else if (consumer->GetOpcode() == Opcode::OP_ASSEMBLE) {198+ } else if (IsAssembleLikeOpcode(consumer->GetOpcode())) {
165 cacheEntry.assembleConsumers.emplace_back(consumer);199 cacheEntry.assembleConsumers.emplace_back(consumer);
166 } else {200 } else {
167 cacheEntry.hasAssembleChainStopper = true;201 cacheEntry.hasAssembleChainStopper = true;
@@ -177,7 +211,7 @@ Status MergeViewAssembleUtils::BuildConsumerCache(Function& function)
177 tensorConsumerCache_.reserve(operations.size());211 tensorConsumerCache_.reserve(operations.size());
178 candidateOps_.reserve(operations.size());212 candidateOps_.reserve(operations.size());
179 for (auto& operation : operations) {213 for (auto& operation : operations) {
180- if (operation.GetOpcode() != Opcode::OP_VIEW && operation.GetOpcode() != Opcode::OP_ASSEMBLE) {214+ if (!IsViewLikeOpcode(operation.GetOpcode()) && !IsAssembleLikeOpcode(operation.GetOpcode())) {
181 continue;215 continue;
182 }216 }
183 candidateOps_.emplace_back(&operation);217 candidateOps_.emplace_back(&operation);
@@ -201,6 +235,7 @@ const MergeViewAssembleUtils::ConsumerCacheEntry& MergeViewAssembleUtils::GetCon
201 235 
202Status MergeViewAssembleUtils::ProcessOperations(Function& function)236Status MergeViewAssembleUtils::ProcessOperations(Function& function)
203{237{
238+ function.SortOperations(SortOperationsMode::LIGHTWEIGHT);
204 Status status = BuildConsumerCache(function);239 Status status = BuildConsumerCache(function);
205 if (status != SUCCESS) {240 if (status != SUCCESS) {
206 APASS_LOG_ERROR_F(Elements::Function, "BuildConsumerCache failed.");241 APASS_LOG_ERROR_F(Elements::Function, "BuildConsumerCache failed.");
@@ -215,9 +250,9 @@ Status MergeViewAssembleUtils::ProcessOperations(Function& function)
215 }250 }
216 Status processStatus = SUCCESS;251 Status processStatus = SUCCESS;
217 std::vector<Operation*> chain;252 std::vector<Operation*> chain;
218- if (op->GetOpcode() == Opcode::OP_VIEW) {253+ if (IsViewLikeOpcode(op->GetOpcode())) {
219 processStatus = MergeViewChain(function, *op, chain);254 processStatus = MergeViewChain(function, *op, chain);
220- } else if (op->GetOpcode() == Opcode::OP_ASSEMBLE) {255+ } else if (IsAssembleLikeOpcode(op->GetOpcode())) {
221 processStatus = MergeAssembleChain(function, *op, chain);256 processStatus = MergeAssembleChain(function, *op, chain);
222 }257 }
223 if (processStatus != SUCCESS) {258 if (processStatus != SUCCESS) {
@@ -248,7 +283,7 @@ Status MergeViewAssembleUtils::AppendMergedViewOperations(Function& function)
248 APASS_LOG_ERROR_F(Elements::Function, "Failed to create ViewOpAttribute.");283 APASS_LOG_ERROR_F(Elements::Function, "Failed to create ViewOpAttribute.");
249 return FAILED;284 return FAILED;
250 }285 }
251- auto& mergedViewOp = irBuilder_.CreateTensorOpStmt(function, Opcode::OP_VIEW, {viewOp.input}, {viewOp.output},286+ auto& mergedViewOp = irBuilder_.CreateTensorOpStmt(function, viewOp.opcode, {viewOp.input}, {viewOp.output},
252 viewOp.span);287 viewOp.span);
253 mergedViewOp.SetScopeInfo(viewOp.scopeInfo);288 mergedViewOp.SetScopeInfo(viewOp.scopeInfo);
254 mergedViewOp.SetOpAttribute(attr);289 mergedViewOp.SetOpAttribute(attr);
@@ -276,7 +311,7 @@ Status MergeViewAssembleUtils::AppendMergedAssembleOperations(Function& function
276 if (!attr) {311 if (!attr) {
277 return FAILED;312 return FAILED;
278 }313 }
279- auto& mergedAssembleOp = irBuilder_.CreateTensorOpStmt(function, Opcode::OP_ASSEMBLE, {assembleOp.input},314+ auto& mergedAssembleOp = irBuilder_.CreateTensorOpStmt(function, assembleOp.opcode, {assembleOp.input},
280 {assembleOp.output}, assembleOp.span);315 {assembleOp.output}, assembleOp.span);
281 mergedAssembleOp.SetScopeInfo(assembleOp.scopeInfo);316 mergedAssembleOp.SetScopeInfo(assembleOp.scopeInfo);
282 mergedAssembleOp.SetOpAttribute(attr);317 mergedAssembleOp.SetOpAttribute(attr);
@@ -375,32 +410,35 @@ Status MergeViewAssembleUtils::ProcessConsumerChain(Function& function, const Co
375 if (!op) {410 if (!op) {
376 return FAILED;411 return FAILED;
377 }412 }
378- auto viewOpAttribute = std::dynamic_pointer_cast<ViewOpAttribute>(op->GetOpAttribute());413+ if (IsViewLikeOpcode(op->GetOpcode())) {
379- if (viewOpAttribute == nullptr) {414+ auto viewOpAttribute = std::dynamic_pointer_cast<ViewOpAttribute>(op->GetOpAttribute());
380- APASS_LOG_ERROR_F(Elements::Function, "View operation has null viewOpAttribute.");415+ if (viewOpAttribute == nullptr) {
381- return FAILED;416+ APASS_LOG_ERROR_F(Elements::Function, "View operation has null viewOpAttribute.");
382- }417+ return FAILED;
383- auto memoryTo = viewOpAttribute->GetTo();418+ }
384- // 根据新的合并原则判断是否可以合并419+ auto memoryTo = viewOpAttribute->GetTo();
385- bool canMerge = false;420+ // 根据新的合并原则判断是否可以合并
386- if (currentMemType == MemoryType::MEM_UNKNOWN || currentMemType == memoryTo) {421+ bool canMerge = false;
387- // 1.unknown memType 可以向它之后的view合并 2.相同memType的view可以合并422+ if (currentMemType == MemoryType::MEM_UNKNOWN || currentMemType == memoryTo) {
388- canMerge = true;423+ // 1.unknown memType 可以向它之后的view合并 2.相同memType的view可以合并
389- }424+ canMerge = true;
390- if (canMerge) {425+ }
391- int consumerScopeId = op->GetScopeId();426+ canMerge = canMerge && CanMergeViewLikeChain(chain, op->GetOpcode());
392- if (effectiveScopeId != -1 && consumerScopeId != -1 && effectiveScopeId != consumerScopeId) {427+ if (canMerge) {
428+ int consumerScopeId = op->GetScopeId();
429+ if (effectiveScopeId != -1 && consumerScopeId != -1 && effectiveScopeId != consumerScopeId) {
430+ chainEnd = true;
431+ continue;
432+ }
433+ chainEnd = false;
434+ Status status = MergeViewChain(function, *op, chain, effectiveScopeId);
435+ if (status != SUCCESS) {
436+ return status;
437+ }
438+ chain.pop_back();
439+ } else {
393 chainEnd = true;440 chainEnd = true;
394- continue;
395 }441 }
396- chainEnd = false;
397- Status status = MergeViewChain(function, *op, chain, effectiveScopeId);
398- if (status != SUCCESS) {
399- return status;
400- }
401- chain.pop_back();
402- } else {
403- chainEnd = true;
404 }442 }
405 }443 }
406 return SUCCESS;444 return SUCCESS;
@@ -441,7 +479,7 @@ Status MergeViewAssembleUtils::ProcessChainEnd(Function& function, std::vector<O
441 Operation::ScopeInfo chainScopeInfo = GetChainScopeInfo(chain);479 Operation::ScopeInfo chainScopeInfo = GetChainScopeInfo(chain);
442 // 记录合并操作480 // 记录合并操作
443 RecordMergedViewOperation(endOp, startTensor, endTensor, newOffset, newDynOffset, newDynValidShape, firstSpan,481 RecordMergedViewOperation(endOp, startTensor, endTensor, newOffset, newDynOffset, newDynValidShape, firstSpan,
444- chainScopeInfo);482+ chainScopeInfo, GetMergedViewOpcode(chain));
445 483 
446 // 清理链尾484 // 清理链尾
447 endOp->oOperand.clear();485 endOp->oOperand.clear();
@@ -489,13 +527,11 @@ Status MergeViewAssembleUtils::CalculateMergedOffsets(const std::vector<Operatio
489 return SUCCESS;527 return SUCCESS;
490}528}
491 529 
492-void MergeViewAssembleUtils::RecordMergedViewOperation(Operation* lastViewOp,530+void MergeViewAssembleUtils::RecordMergedViewOperation(
493- const std::shared_ptr<LogicalTensor>& startTensor,531+ Operation* lastViewOp, const std::shared_ptr<LogicalTensor>& startTensor,
494- const std::shared_ptr<LogicalTensor>& endTensor,532+ const std::shared_ptr<LogicalTensor>& endTensor, const std::vector<int64_t>& newOffset,
495- const std::vector<int64_t>& newOffset,533+ const std::vector<SymbolicScalar>& newDynOffset, const std::vector<SymbolicScalar>& newDynValidShape,
496- const std::vector<SymbolicScalar>& newDynOffset,534+ const ir::Span& span, const Operation::ScopeInfo& scopeInfo, Opcode opcode)
497- const std::vector<SymbolicScalar>& newDynValidShape,
498- const ir::Span& span, const Operation::ScopeInfo& scopeInfo)
499{535{
500 // 获取最后一个VIEW的属性536 // 获取最后一个VIEW的属性
501 auto lastViewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(lastViewOp->GetOpAttribute());537 auto lastViewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(lastViewOp->GetOpAttribute());
@@ -514,9 +550,10 @@ void MergeViewAssembleUtils::RecordMergedViewOperation(Operation* lastViewOp,
514 // 清理消费者关系550 // 清理消费者关系
515 endTensor->GetProducers().clear();551 endTensor->GetProducers().clear();
516 // 记录合并op552 // 记录合并op
517- viewOpToAppend_.emplace_back(ViewOp{553+ viewOpToAppend_.emplace_back(ViewOp{startTensor, endTensor, newOffset, newDynOffset, newDynValidShape,
518- startTensor, endTensor, newOffset, newDynOffset, newDynValidShape, lastViewAttr->GetTo(), hasCopyInMode,554+ lastViewAttr->GetTo(), hasCopyInMode, std::move(copyInModeValue),
519- std::move(copyInModeValue), hasL1PaddingMode, std::move(l1PaddingMode), hasKIndex, kIndex, span, scopeInfo});555+ hasL1PaddingMode, std::move(l1PaddingMode), hasKIndex, kIndex, span, scopeInfo,
556+ opcode});
520}557}
521 558 
522Status MergeViewAssembleUtils::MergeAssembleChain(Function& function, Operation& operation,559Status MergeViewAssembleUtils::MergeAssembleChain(Function& function, Operation& operation,
@@ -568,20 +605,28 @@ Status MergeViewAssembleUtils::ProcessAssembleConsumers(Function& function, cons
568 APASS_LOG_ERROR_F(Elements::Function, "Null consumer operation found.");605 APASS_LOG_ERROR_F(Elements::Function, "Null consumer operation found.");
569 return FAILED;606 return FAILED;
570 }607 }
571- int consumerScopeId = op->GetScopeId();608+ if (IsAssembleLikeOpcode(op->GetOpcode())) {
572- if (effectiveScopeId != -1 && consumerScopeId != -1 && effectiveScopeId != consumerScopeId) {609+ int consumerScopeId = op->GetScopeId();
573- chainEnd = true;610+ if (effectiveScopeId != -1 && consumerScopeId != -1 && effectiveScopeId != consumerScopeId) {
611+ chainEnd = true;
612+ continue;
613+ }
614+ if (!CanMergeAssembleLikeChain(chain, op->GetOpcode())) {
615+ chainEnd = true;
616+ continue;
617+ }
618+ if (!IsRmwModeAttrCompatible(chain, *op)) {
619+ chainEnd = true;
620+ continue;
621+ }
622+ Status status = MergeAssembleChain(function, *op, chain, effectiveScopeId);
623+ if (status != SUCCESS) {
624+ APASS_LOG_ERROR_F(Elements::Function, "Run MergeAssembleChain failed.");
625+ return status;
626+ }
574 continue;627 continue;
575 }628 }
576- if (!IsRmwModeAttrCompatible(chain, *op)) {629+ chainEnd = true;
577- chainEnd = true;
578- continue;
579- }
580- Status status = MergeAssembleChain(function, *op, chain, effectiveScopeId);
581- if (status != SUCCESS) {
582- APASS_LOG_ERROR_F(Elements::Function, "Run MergeAssembleChain failed.");
583- return status;
584- }
585 }630 }
586 return SUCCESS;631 return SUCCESS;
587}632}
@@ -612,7 +657,7 @@ Status MergeViewAssembleUtils::ProcessAssembleChainEnd(Function& function, std::
612 }657 }
613 // 4. 记录并清理658 // 4. 记录并清理
614 RecordAssembleOperation(startTensor, endTensor, newOffset, newDynOffset, firstSpan, chainScopeInfo,659 RecordAssembleOperation(startTensor, endTensor, newOffset, newDynOffset, firstSpan, chainScopeInfo,
615- GetRmwModeAttrKey(rmwModeAttr));660+ GetRmwModeAttrKey(rmwModeAttr), GetMergedAssembleOpcode(chain));
616 function.GetTensorMap().Erase(endTensor);661 function.GetTensorMap().Erase(endTensor);
617 operation.SetAsDeleted();662 operation.SetAsDeleted();
618 663 
@@ -653,9 +698,10 @@ void MergeViewAssembleUtils::RecordAssembleOperation(const std::shared_ptr<Logic
653 const std::vector<int64_t>& offset,698 const std::vector<int64_t>& offset,
654 const std::vector<SymbolicScalar>& dynOffset, const ir::Span& span,699 const std::vector<SymbolicScalar>& dynOffset, const ir::Span& span,
655 const Operation::ScopeInfo& scopeInfo,700 const Operation::ScopeInfo& scopeInfo,
656- const std::string& rmwModeAttr)701+ const std::string& rmwModeAttr, Opcode opcode)
657{702{
658- assembleOpToAppend_.emplace_back(AssembleOp{input, output, offset, dynOffset, span, scopeInfo, rmwModeAttr});703+ assembleOpToAppend_.emplace_back(
704+ AssembleOp{input, output, offset, dynOffset, span, scopeInfo, rmwModeAttr, opcode});
659}705}
660 706 
661Status MergeViewAssembleUtils::EraseRedundantAssemble(Function& function) const707Status MergeViewAssembleUtils::EraseRedundantAssemble(Function& function) const
@@ -44,6 +44,7 @@ public:
44 std::any kIndex; // copy_in_l1_k_index属性值(K维度在dynValidShape中的索引,0或1)44 std::any kIndex; // copy_in_l1_k_index属性值(K维度在dynValidShape中的索引,0或1)
45 ir::Span span; // 链路最早操作的span45 ir::Span span; // 链路最早操作的span
46 Operation::ScopeInfo scopeInfo;46 Operation::ScopeInfo scopeInfo;
47+ Opcode opcode = Opcode::OP_VIEW;
47 };48 };
48 struct AssembleOp {49 struct AssembleOp {
49 std::shared_ptr<LogicalTensor> input;50 std::shared_ptr<LogicalTensor> input;
@@ -53,6 +54,7 @@ public:
53 ir::Span span; // 链路最早操作的span54 ir::Span span; // 链路最早操作的span
54 Operation::ScopeInfo scopeInfo;55 Operation::ScopeInfo scopeInfo;
55 std::string rmwModeAttr;56 std::string rmwModeAttr;
57+ Opcode opcode = Opcode::OP_ASSEMBLE;
56 };58 };
57 struct ConsumerCacheEntry {59 struct ConsumerCacheEntry {
58 std::vector<Operation*> viewConsumers;60 std::vector<Operation*> viewConsumers;
@@ -121,7 +123,7 @@ public:
121 const std::vector<int64_t>& newOffset,123 const std::vector<int64_t>& newOffset,
122 const std::vector<SymbolicScalar>& newDynOffset,124 const std::vector<SymbolicScalar>& newDynOffset,
123 const std::vector<SymbolicScalar>& newDynValidShape, const ir::Span& span,125 const std::vector<SymbolicScalar>& newDynValidShape, const ir::Span& span,
124- const Operation::ScopeInfo& scopeInfo);126+ const Operation::ScopeInfo& scopeInfo, Opcode opcode);
125 127 
126 // Assemble chain processing methods128 // Assemble chain processing methods
127 /**129 /**
@@ -157,7 +159,7 @@ public:
157 void RecordAssembleOperation(const std::shared_ptr<LogicalTensor>& input,159 void RecordAssembleOperation(const std::shared_ptr<LogicalTensor>& input,
158 const std::shared_ptr<LogicalTensor>& output, const std::vector<int64_t>& offset,160 const std::shared_ptr<LogicalTensor>& output, const std::vector<int64_t>& offset,
159 const std::vector<SymbolicScalar>& dynOffset, const ir::Span& span,161 const std::vector<SymbolicScalar>& dynOffset, const ir::Span& span,
160- const Operation::ScopeInfo& scopeInfo, const std::string& rmwModeAttr);162+ const Operation::ScopeInfo& scopeInfo, const std::string& rmwModeAttr, Opcode opcode);
161 163 
162 // Common methods164 // Common methods
163 Status Initialize();165 Status Initialize();
@@ -20,12 +20,14 @@
20 20 
21namespace npu {21namespace npu {
22namespace tile_fwk {22namespace tile_fwk {
23+enum class Opcode;
23struct AssembleOp {24struct AssembleOp {
24 MemoryType from;25 MemoryType from;
25 std::vector<int64_t> toOffset;26 std::vector<int64_t> toOffset;
26 LogicalTensorPtr input;27 LogicalTensorPtr input;
27 LogicalTensorPtr output;28 LogicalTensorPtr output;
28 const Operation* originOp = nullptr;29 const Operation* originOp = nullptr;
30+ Opcode opcode;
29};31};
30 32 
31struct ViewOp {33struct ViewOp {
@@ -0,0 +1,65 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file remove_redundant_op_utils.h
13+ * \brief utils for redundant view/assemble and slice/contract elimination
14+ */
15+ 
16+#ifndef PASS_REMOVE_REDUNDANT_OP_UTILS_H_
17+#define PASS_REMOVE_REDUNDANT_OP_UTILS_H_
18+ 
19+#include "interface/function/function.h"
20+#include "interface/tensor/irbuilder.h"
21+#include "interface/tensor/logical_tensor.h"
22+ 
23+namespace npu {
24+namespace tile_fwk {
25+class RemoveRedundantOpUtils {
26+public:
27+ RemoveRedundantOpUtils() = default;
28+ ~RemoveRedundantOpUtils() = default;
29+ 
30+ static Status Process(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
31+ static Status ProcessViewAssembleLike(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
32+ static Status ProcessContractSlice(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
33+ static Status ProcessViewCopyout(Function& function, bool& operationUpdated);
34+ static Status ProcessCopyinAssemble(Function& function, bool& operationUpdated);
35+ 
36+private:
37+ Status ProcessImpl(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
38+ Status ProcessViewAssembleLikeImpl(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
39+ Status ProcessContractSliceImpl(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
40+ Status ProcessMultiContractSingleSlice(Function& function, bool& operationUpdated);
41+ Status ProcessSingleContractMultiSlice(Function& function, std::vector<Operation*>& newOps, bool& operationUpdated);
42+ 
43+ void ProcessPerfectMatch(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor, bool endTensorIsOutcast,
44+ bool& operationUpdated);
45+ void RemoveViewAssembleForOutcast(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor,
46+ bool& operationUpdated);
47+ void CalculateViewOffset(Operation& op, LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor,
48+ std::vector<int64_t>& newOffset, std::vector<SymbolicScalar>& newDynOffset);
49+ void GenerateNewViewLike(Function& function, Operation& op, LogicalTensorPtr& startTensor,
50+ LogicalTensorPtr& endTensor, Opcode newOpcode, std::vector<Operation*>& newOps,
51+ bool& operationUpdated);
52+ void GenerateContractSliceView(Function& function, Operation& sliceOp, const LogicalTensorPtr& inputTensor,
53+ const std::vector<int64_t>& fromOffset,
54+ const std::vector<SymbolicScalar>& fromDynOffset, std::vector<Operation*>& newOps,
55+ bool& operationUpdated);
56+ 
57+ bool IsNotSameViewInput(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor) const;
58+ bool IsDataReplace(LogicalTensorPtr& endTensor) const;
59+ bool IsValidViewAssemble(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor) const;
60+ 
61+ IRBuilder irBuilder_;
62+};
63+} // namespace tile_fwk
64+} // namespace npu
65+#endif // PASS_REMOVE_REDUNDANT_OP_UTILS_H_
@@ -16,7 +16,7 @@
16#ifndef TILE_FWK_ASSIGN_MEMORY_TYPE_H16#ifndef TILE_FWK_ASSIGN_MEMORY_TYPE_H
17#define TILE_FWK_ASSIGN_MEMORY_TYPE_H17#define TILE_FWK_ASSIGN_MEMORY_TYPE_H
18 18 
19-#include <queue>19+#include <set>
20#include <string>20#include <string>
21#include <unordered_set>21#include <unordered_set>
22#include <vector>22#include <vector>
@@ -32,7 +32,6 @@ namespace npu::tile_fwk {
32class AssignMemoryType : public Pass {32class AssignMemoryType : public Pass {
33public:33public:
34 AssignMemoryType() : Pass("AssignMemoryType") {}34 AssignMemoryType() : Pass("AssignMemoryType") {}
35- void SpecialCallInterfaceToBeDeleted(Function& function) { RunOnFunction(function); }
36 35 
37private:36private:
38 Status PreCheck(Function& function) override;37 Status PreCheck(Function& function) override;
@@ -50,6 +49,8 @@ private:
50 49 
51 Status AssignViewAttrMemoryType(Operation& operation);50 Status AssignViewAttrMemoryType(Operation& operation);
52 51 
52+ Status AssignSliceInputRequirement(Operation& operation);
53+ 
53 Status AssignAssembleAttrMemoryType(Operation& operation);54 Status AssignAssembleAttrMemoryType(Operation& operation);
54 55 
55 Status AssignInOutCastMemoryTypes(Function& function);56 Status AssignInOutCastMemoryTypes(Function& function);
@@ -63,16 +64,19 @@ private:
63 64 
64 Status InferViewMemoryType(Operation& operation);65 Status InferViewMemoryType(Operation& operation);
65 66 
66- Status InferViewOutputFromRequirement(const LogicalTensorPtr& output, MemoryType& outputOriginal);67+ Status InferSliceMemoryType(Operation& operation);
67 68 
68- Status InferViewKnownInputOutput(Operation& operation, const LogicalTensorPtr& input, MemoryType inputOriginal,69+ Status InferContractMemoryType(Operation& operation);
69- MemoryType outputOriginal);
70 70 
71- Status InferViewKnownInputUnknownOutput(Operation& operation, const LogicalTensorPtr& input,71+ MemoryType InferOriginalFromOutputRequirements(const LogicalTensorPtr& tensor) const;
72- const LogicalTensorPtr& output, MemoryType inputOriginal);
73 72 
74- bool TryHandleUnalignedView(Operation& operation, const LogicalTensorPtr& input, MemoryType inputOriginal,73+ MemoryType InferOriginalFromOutputRequirements(const LogicalTensorPtr& tensor,
75- MemoryType outputOriginal);74+ std::unordered_set<const LogicalTensor*>& visitedTensors) const;
75+ 
76+ MemoryType InferRequirementFromInputOriginals(const LogicalTensorPtr& tensor) const;
77+ 
78+ MemoryType InferRequirementFromInputOriginals(const LogicalTensorPtr& tensor,
79+ std::unordered_set<const LogicalTensor*>& visitedTensors) const;
76 80 
77 bool CanUseDirectViewPath(Operation& operation, MemoryType from, MemoryType to);81 bool CanUseDirectViewPath(Operation& operation, MemoryType from, MemoryType to);
78 82 
@@ -82,51 +86,21 @@ private:
82 86 
83 bool HasParallelDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;87 bool HasParallelDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;
84 88 
85- bool IsViewFromOffsetAligned(Operation& operation) const;89+ bool HasDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;
86 90 
87- bool HasDynOffsetViewAndReshape(Operation& operation, const LogicalTensorPtr& output) const;91+ Status InferAssembleMemoryType(Operation& operation, std::unordered_set<LogicalTensorPtr>& inferredAssembleOutputs);
88- 
89- bool HasTransDataConsumer(const LogicalTensorPtr& tensor) const;
90- 
91- bool HasPermuteProducerAndTransDataDownstream(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
92- 
93- Status InferAssembleMemoryType(Function& function, Operation& operation,
94- std::unordered_set<LogicalTensorPtr>& inferredAssembleOutputs);
95 92 
96 Status InferAssembleMemoryType(Operation& operation);93 Status InferAssembleMemoryType(Operation& operation);
97 94 
98- Status AssignAssembleToOutCastRequirement(Operation& operation);95+ MemoryType InferParallelAssembleInputRequirement(const LogicalTensorPtr& output) const;
99 96 
100- Status InferAssembleOutputMemoryType(const LogicalTensorPtr& output);97+ Status SetParallelAssembleInputRequirements(const LogicalTensorPtr& output, MemoryType memoryType,
101- 98+ const std::string& reason);
102- bool HasAssembleInputOutputElementCountMismatch(const LogicalTensorPtr& output) const;
103- 
104- Status TryInferAssembleOutputByTempOriginal(const LogicalTensorPtr& output, MemoryType tempOriginal, bool& handled);
105- 
106- bool AreAssembleDirectPathsSupported(const LogicalTensorPtr& output, MemoryType targetOriginal);
107 99 
108 bool IsAssembleProducer(Operation* operation) const;100 bool IsAssembleProducer(Operation* operation) const;
109 101 
110 MemoryType GetAssembleInputType(Operation& operation) const;102 MemoryType GetAssembleInputType(Operation& operation) const;
111 103 
112- Status ApplyAssembleDirectOutputOriginal(const LogicalTensorPtr& output, MemoryType targetOriginal);
113- 
114- Status SyncAssembleInputRequirementAndAttr(Operation& operation, MemoryType fallbackType,
115- const std::string& reason);
116- 
117- Status ApplyAssembleDdrOutputWithInputOriginals(const LogicalTensorPtr& output, const std::string& originalReason,
118- const std::string& inputReason);
119- 
120- Status FillAssembleInputRequirementsFromOriginal(const LogicalTensorPtr& output, const std::string& reason);
121- 
122- Status TryInferAssembleOutputByProducerCandidate(const LogicalTensorPtr& output, bool& handled);
123- 
124- MemoryType InferAssembleProducerCandidate(const LogicalTensorPtr& output, bool& hasConflict) const;
125- 
126- Status ApplyAssembleProducerCandidate(const LogicalTensorPtr& output, MemoryType producerCandidate);
127- 
128- MemoryType InferAssembleTempOriginal(const LogicalTensorPtr& output) const;
129- 
130 bool CanUseDirectAssemblePath(Operation& operation, MemoryType from, MemoryType to);104 bool CanUseDirectAssemblePath(Operation& operation, MemoryType from, MemoryType to);
131 105 
132 bool IsAssembleToOffsetAligned(Operation& operation, const LogicalTensorPtr& output);106 bool IsAssembleToOffsetAligned(Operation& operation, const LogicalTensorPtr& output);
@@ -170,8 +144,8 @@ private:
170 144 
171 Status InferViewTypeMemoryType(Operation& operation);145 Status InferViewTypeMemoryType(Operation& operation);
172 146 
173- Status TryInferViewTypeFromProducerView(Operation& operation, const LogicalTensorPtr& input,147+ Status TryInferViewTypeFromProducerSlice(Operation& operation, const LogicalTensorPtr& input,
174- const LogicalTensorPtr& output, MemoryType targetType, bool& handled);148+ const LogicalTensorPtr& output, MemoryType targetType, bool& handled);
175 149 
176 Status InferViewTypeInput(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output,150 Status InferViewTypeInput(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output,
177 MemoryType targetType);151 MemoryType targetType);
@@ -182,6 +156,14 @@ private:
182 MemoryType InferTargetTypeThroughForwardViews(const LogicalTensorPtr& tensor,156 MemoryType InferTargetTypeThroughForwardViews(const LogicalTensorPtr& tensor,
183 std::unordered_set<LogicalTensorPtr>& visitedTensors) const;157 std::unordered_set<LogicalTensorPtr>& visitedTensors) const;
184 158 
159+ bool CanKeepContractProducersInUb(const LogicalTensorPtr& tensor);
160+ 
161+ bool IsSliceFromOffsetAligned(Operation& sliceOp, const LogicalTensorPtr& input);
162+ 
163+ bool CanKeepSliceConsumersInUb(const LogicalTensorPtr& tensor);
164+ 
165+ bool HasNonZeroSliceFromOffset(const LogicalTensorPtr& tensor);
166+ 
185 bool KeepSplitReshapeUb(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output);167 bool KeepSplitReshapeUb(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output);
186 168 
187 bool IsDynamicReshape(Operation& operation, const LogicalTensorPtr& output) const;169 bool IsDynamicReshape(Operation& operation, const LogicalTensorPtr& output) const;
@@ -196,14 +178,14 @@ private:
196 178 
197 Status ApplyOversizedLocalBufferFallback(Operation& operation);179 Status ApplyOversizedLocalBufferFallback(Operation& operation);
198 180 
199- bool IsOversizedLocalBuffer(const LogicalTensorPtr& tensor, MemoryType memoryType, bool useAssembleUbLimit,181+ bool IsOversizedLocalBuffer(const LogicalTensorPtr& tensor, MemoryType memoryType, bool useStrictUbLimit,
200 bool allowL1Fallback) const;182 bool allowL1Fallback) const;
201 183 
202- Status DowngradeOversizedViewInputRequirement(Operation& operation);184+ Status DowngradeOversizedSliceInputRequirement(Operation& operation);
203 185 
204 bool ExceedsMemoryLimit(const LogicalTensorPtr& tensor, size_t threshold) const;186 bool ExceedsMemoryLimit(const LogicalTensorPtr& tensor, size_t threshold) const;
205 187 
206- Status ApplyPlatformPathFallbackRules(Function& function);188+ Status ApplyPlatformPathUpgradeRules(Function& function);
207 189 
208 Status ResolveMemoryUnknowns(Function& function);190 Status ResolveMemoryUnknowns(Function& function);
209 191 
@@ -219,6 +201,8 @@ private:
219 201 
220 Status SyncTensorToBe(Function& function);202 Status SyncTensorToBe(Function& function);
221 203 
204+ Status FallbackSameMemoryMoveOps(Function& function);
205+ 
222 Status SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,206 Status SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,
223 const std::string& reason = "unknown", bool allowOverride = false);207 const std::string& reason = "unknown", bool allowOverride = false);
224 208 
@@ -231,21 +215,39 @@ private:
231 const std::string& reason = "unknown");215 const std::string& reason = "unknown");
232 216 
233 void FillUnknownRequirementsWith(const LogicalTensorPtr& tensor, MemoryType memoryType, const char* reason);217 void FillUnknownRequirementsWith(const LogicalTensorPtr& tensor, MemoryType memoryType, const char* reason);
234- bool AreAllConsumerRequirements(const LogicalTensorPtr& tensor, MemoryType memoryType) const;218+ Status ProcessL0C2L1SmallToLarge(Function& function);
235- void DowngradeConsumerRequirements(const LogicalTensorPtr& tensor, MemoryType fromType);219+ Status ProcessL0C2L1LargeToSmall(Function& function);
236- void ProcessL0C2L1SmallToLarge(Function& function);
237- void ProcessL0C2L1LargeToSmall(Function& function);
238 bool CheckUBTileShape(const LogicalTensorPtr& output);220 bool CheckUBTileShape(const LogicalTensorPtr& output);
239- bool CheckConsumerViewShapeMultiple(const LogicalTensorPtr& output, const LogicalTensorPtr& input);221+ bool CheckConsumerSliceShapeMultiple(const LogicalTensorPtr& output, const LogicalTensorPtr& input);
240- void ProcessL0C2UBSmallToLarge(Function& function);222+ Status ProcessL0C2UBSmallToLarge(Function& function);
241- void ProcessL0C2UBLargeToSmall(Function& function);223+ Status ProcessL0C2UBLargeToSmall(Function& function);
242- void ProcessUB2L1SmallToLarge(Function& function);224+ Status ProcessUB2UBContractSlice(Function& function);
243- void ProcessUB2L1LargeToSmall(Function& function);225+ Status ProcessUB2L1SmallToLarge(Function& function);
226+ Status ProcessUB2L1LargeToSmall(Function& function);
227+ Status ProcessL1DdrL1(Function& function);
228+ Status ProcessDdrMultiReshape(Function& function);
244 bool ShouldSkipUB2L1SmallToLarge(const LogicalTensorPtr& iOperand, const LogicalTensorPtr& oOperand) const;229 bool ShouldSkipUB2L1SmallToLarge(const LogicalTensorPtr& iOperand, const LogicalTensorPtr& oOperand) const;
230+ Status TryUpgradeSingleSliceContractPath(Operation& sliceOp, MemoryType sourceType, MemoryType targetType,
231+ const std::string& reason, bool requireMatrixShape, bool checkUbTileShape,
232+ bool checkUb2L1Constraints);
233+ Status TryUpgradeSingleContractSlicePath(Operation& contractOp, MemoryType sourceType, MemoryType targetType,
234+ const std::string& reason, bool requireMatrixShape, bool checkUbTileShape,
235+ bool checkUb2L1Constraints);
236+ bool CanUseMiddleTensorForUpgrade(const LogicalTensorPtr& middle, MemoryType targetType) const;
237+ bool HasOnlyContractProducers(const LogicalTensorPtr& tensor) const;
238+ bool HasOnlySliceConsumers(const LogicalTensorPtr& tensor) const;
239+ bool IsSliceOutputTarget(Operation& sliceOp, MemoryType targetType) const;
240+ Status EnsureSliceOutputTarget(Operation& sliceOp, MemoryType targetType, const std::string& reason);
241+ Status ApplySingleSliceContractUpgrade(Operation& sliceOp, MemoryType sourceType, MemoryType targetType,
242+ const std::string& reason);
243+ Status ApplySingleContractSliceUpgrade(Operation& contractOp, MemoryType sourceType, MemoryType targetType,
244+ const std::string& reason);
245+ bool CanUseL0C2L1UpgradePath(Operation& operation);
245 bool IsDimMultiple(const Shape& shape1, const Shape& shape2);246 bool IsDimMultiple(const Shape& shape1, const Shape& shape2);
246 bool CheckInnerAxisC0Size(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;247 bool CheckInnerAxisC0Size(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
247 size_t CalcNZTensorSize(const LogicalTensorPtr& tensor) const;248 size_t CalcNZTensorSize(const LogicalTensorPtr& tensor) const;
248- int64_t CalcLineOffset(const Shape& shape, const Offset& offset) const;249+ int64_t CalcLineOffset(const Shape& shape, const Offset& offset);
250+ Status RunOnFunctionLegacy(Function& function);
249 ConvertInserter inserter;251 ConvertInserter inserter;
250 AssignMemoryTypeChecker checker;252 AssignMemoryTypeChecker checker;
251};253};
@@ -0,0 +1,258 @@
1+/**
2+ * Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file assign_memory_type.h
13+ * \brief
14+ */
15+ 
16+#ifndef TILE_FWK_ASSIGN_MEMORY_TYPE_LEGACY_H
17+#define TILE_FWK_ASSIGN_MEMORY_TYPE_LEGACY_H
18+ 
19+#include <queue>
20+#include <string>
21+#include <unordered_set>
22+#include <vector>
23+#include "passes/pass_interface/pass.h"
24+#include "interface/operation/opcode.h"
25+#include "passes/tile_graph_pass/data_path/convert_op_inserter_legacy.h"
26+#include "tilefwk/platform.h"
27+#include "tilefwk/data_type.h"
28+#include "passes/pass_check/assign_memory_type_checker.h"
29+#include "passes/pass_utils/infer_shape_utils.h"
30+ 
31+namespace npu::tile_fwk::legacy {
32+class AssignMemoryType : public Pass {
33+public:
34+ AssignMemoryType() : Pass("AssignMemoryType") {}
35+ Status RunLegacy(Function& function) { return RunOnFunction(function); }
36+ 
37+private:
38+ Status PreCheck(Function& function) override;
39+ Status PostCheck(Function& function) override;
40+ Status RunOnFunction(Function& function) override;
41+ Status InsertConvertOpsAndInferShape(Function& function);
42+ 
43+ Status AssignConfirmedMemoryTypes(Function& function);
44+ 
45+ Status AssignOpcodeDefinedMemoryTypes(Operation& operation);
46+ 
47+ Status AssignMatmulInputRequirements(Operation& operation);
48+ 
49+ Status AssignReduceAccInputRequirements(Operation& operation);
50+ 
51+ Status AssignViewAttrMemoryType(Operation& operation);
52+ 
53+ Status AssignAssembleAttrMemoryType(Operation& operation);
54+ 
55+ Status AssignInOutCastMemoryTypes(Function& function);
56+ 
57+ Status EnsureAllConsumerRequirementsExist(Function& function);
58+ 
59+ Status InferUncertainMemoryTypes(Function& function);
60+ 
61+ Status GetFirstInputOutputIfOpcode(Operation& operation, Opcode expectedOpcode, const std::string& action,
62+ LogicalTensorPtr& input, LogicalTensorPtr& output, bool& shouldHandle) const;
63+ 
64+ Status InferViewMemoryType(Operation& operation);
65+ 
66+ Status InferViewOutputFromRequirement(const LogicalTensorPtr& output, MemoryType& outputOriginal);
67+ 
68+ Status InferViewKnownInputOutput(Operation& operation, const LogicalTensorPtr& input, MemoryType inputOriginal,
69+ MemoryType outputOriginal);
70+ 
71+ Status InferViewKnownInputUnknownOutput(Operation& operation, const LogicalTensorPtr& input,
72+ const LogicalTensorPtr& output, MemoryType inputOriginal);
73+ 
74+ bool TryHandleUnalignedView(Operation& operation, const LogicalTensorPtr& input, MemoryType inputOriginal,
75+ MemoryType outputOriginal);
76+ 
77+ bool CanUseDirectViewPath(Operation& operation, MemoryType from, MemoryType to);
78+ 
79+ bool TryHandleSpecialDirectMemoryPath(Operation& operation, MemoryType from, MemoryType to, bool& directPath);
80+ 
81+ bool IsAdvancedMemoryPath(MemoryType from, MemoryType to) const;
82+ 
83+ bool HasParallelDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;
84+ 
85+ bool IsViewFromOffsetAligned(Operation& operation) const;
86+ 
87+ bool HasDynOffsetViewAndReshape(Operation& operation, const LogicalTensorPtr& output) const;
88+ 
89+ bool HasTransDataConsumer(const LogicalTensorPtr& tensor) const;
90+ 
91+ bool HasPermuteProducerAndTransDataDownstream(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
92+ 
93+ Status InferAssembleMemoryType(Function& function, Operation& operation,
94+ std::unordered_set<LogicalTensorPtr>& inferredAssembleOutputs);
95+ 
96+ Status InferAssembleMemoryType(Operation& operation);
97+ 
98+ Status AssignAssembleToOutCastRequirement(Operation& operation);
99+ 
100+ Status InferAssembleOutputMemoryType(const LogicalTensorPtr& output);
101+ 
102+ bool HasAssembleInputOutputElementCountMismatch(const LogicalTensorPtr& output) const;
103+ 
104+ Status TryInferAssembleOutputByTempOriginal(const LogicalTensorPtr& output, MemoryType tempOriginal, bool& handled);
105+ 
106+ bool AreAssembleDirectPathsSupported(const LogicalTensorPtr& output, MemoryType targetOriginal);
107+ 
108+ bool IsAssembleProducer(Operation* operation) const;
109+ 
110+ MemoryType GetAssembleInputType(Operation& operation) const;
111+ 
112+ Status ApplyAssembleDirectOutputOriginal(const LogicalTensorPtr& output, MemoryType targetOriginal);
113+ 
114+ Status SyncAssembleInputRequirementAndAttr(Operation& operation, MemoryType fallbackType,
115+ const std::string& reason);
116+ 
117+ Status ApplyAssembleDdrOutputWithInputOriginals(const LogicalTensorPtr& output, const std::string& originalReason,
118+ const std::string& inputReason);
119+ 
120+ Status FillAssembleInputRequirementsFromOriginal(const LogicalTensorPtr& output, const std::string& reason);
121+ 
122+ Status TryInferAssembleOutputByProducerCandidate(const LogicalTensorPtr& output, bool& handled);
123+ 
124+ MemoryType InferAssembleProducerCandidate(const LogicalTensorPtr& output, bool& hasConflict) const;
125+ 
126+ Status ApplyAssembleProducerCandidate(const LogicalTensorPtr& output, MemoryType producerCandidate);
127+ 
128+ MemoryType InferAssembleTempOriginal(const LogicalTensorPtr& output) const;
129+ 
130+ bool CanUseDirectAssemblePath(Operation& operation, MemoryType from, MemoryType to);
131+ 
132+ bool IsAssembleToOffsetAligned(Operation& operation, const LogicalTensorPtr& output);
133+ 
134+ bool FitsAssembleOutputMemoryLimit(const LogicalTensorPtr& output, MemoryType memoryType) const;
135+ 
136+ Status InferReshapeMemoryType(Operation& operation);
137+ 
138+ MemoryType GetReshapeInputRequirement(Operation& operation, const LogicalTensorPtr& input,
139+ MemoryType inputOriginal);
140+ 
141+ Status InferReshapeOutputFromRequirement(const LogicalTensorPtr& output, MemoryType& outputOriginal);
142+ 
143+ MemoryType InferUniqueRequirementThroughViewConsumers(const LogicalTensorPtr& tensor) const;
144+ 
145+ MemoryType InferUniqueRequirementThroughViewConsumers(
146+ const LogicalTensorPtr& tensor, std::unordered_set<const LogicalTensor*>& visitedTensors) const;
147+ 
148+ bool HasRequirementThroughViewConsumers(const LogicalTensorPtr& tensor, MemoryType targetRequirement,
149+ std::unordered_set<const LogicalTensor*>& visitedTensors) const;
150+ 
151+ bool CanUseUbForReshape(const LogicalTensorPtr& input, const LogicalTensorPtr& output, MemoryType inputRequirement,
152+ MemoryType outputOriginal) const;
153+ 
154+ Status ApplyReshapeMemoryType(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output,
155+ bool isDynamic, bool canUseUb);
156+ 
157+ Status InferReshapeL0C2UBAndUB2L1PatternLiteNPU(Operation& op);
158+ 
159+ bool IsReshapeCubeToVecL0C2UBPattern(Operation& op);
160+ 
161+ bool IsReshapeVecToCubeUB2L1Pattern(Operation& op);
162+ 
163+ bool IsReshapeVecToCubeUB2L1ProducerPattern(const std::set<Operation*, LogicalTensor::CompareOp>& producers);
164+ 
165+ bool IsReshapeVecToCubeUB2L1ConsumerPattern(const std::set<Operation*, LogicalTensor::CompareOp>& consumers);
166+ 
167+ void CollectProducerAIVFlags(Operation* op, std::vector<bool>& isProducerVector);
168+ 
169+ void CollectConsumerAICFlags(Operation* op, std::vector<bool>& isConsumerCube);
170+ 
171+ Status InferViewTypeMemoryType(Operation& operation);
172+ 
173+ Status TryInferViewTypeFromProducerView(Operation& operation, const LogicalTensorPtr& input,
174+ const LogicalTensorPtr& output, MemoryType targetType, bool& handled);
175+ 
176+ Status InferViewTypeInput(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output,
177+ MemoryType targetType);
178+ 
179+ // 当 tensor 的 toBeMap 未知时,沿后续未推导的视图链向前查找有效内存类型
180+ MemoryType InferTargetTypeThroughForwardViews(const LogicalTensorPtr& tensor) const;
181+ 
182+ MemoryType InferTargetTypeThroughForwardViews(const LogicalTensorPtr& tensor,
183+ std::unordered_set<LogicalTensorPtr>& visitedTensors) const;
184+ 
185+ bool KeepSplitReshapeUb(Operation& operation, const LogicalTensorPtr& input, const LogicalTensorPtr& output);
186+ 
187+ bool IsDynamicReshape(Operation& operation, const LogicalTensorPtr& output) const;
188+ 
189+ bool FitsTensorInUb(const LogicalTensorPtr& tensor) const;
190+ 
191+ Status ApplyOtherSpecialOpcodeRules(Function& function);
192+ 
193+ Status HandleNopMemoryType(Operation& operation);
194+ 
195+ Status ApplyOversizedLocalBufferFallback(Function& function);
196+ 
197+ Status ApplyOversizedLocalBufferFallback(Operation& operation);
198+ 
199+ bool IsOversizedLocalBuffer(const LogicalTensorPtr& tensor, MemoryType memoryType, bool useAssembleUbLimit,
200+ bool allowL1Fallback) const;
201+ 
202+ Status DowngradeOversizedViewInputRequirement(Operation& operation);
203+ 
204+ bool ExceedsMemoryLimit(const LogicalTensorPtr& tensor, size_t threshold) const;
205+ 
206+ Status ApplyPlatformPathFallbackRules(Function& function);
207+ 
208+ Status ResolveMemoryUnknowns(Function& function);
209+ 
210+ Status ResolveTensorMemoryUnknowns(const LogicalTensorPtr& tensor);
211+ 
212+ Status SyncViewAssembleMemoryAttrs(Function& function);
213+ 
214+ Status SyncViewMemoryAttr(Operation& operation);
215+ 
216+ Status SyncAssembleMemoryAttr(Operation& operation);
217+ 
218+ MemoryType InferOriginalFromRequirements(const LogicalTensorPtr& tensor) const;
219+ 
220+ Status SyncTensorToBe(Function& function);
221+ 
222+ Status SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,
223+ const std::string& reason = "unknown", bool allowOverride = false);
224+ 
225+ void ForceSetOriginal(const LogicalTensorPtr& tensor, MemoryType memoryType, const std::string& reason = "unknown");
226+ 
227+ Status SetRequirementChecked(const LogicalTensorPtr& tensor, Operation& operation, MemoryType memoryType,
228+ const std::string& reason = "unknown", bool allowOverride = false);
229+ 
230+ void ForceSetRequirement(const LogicalTensorPtr& tensor, Operation& operation, MemoryType memoryType,
231+ const std::string& reason = "unknown");
232+ 
233+ void FillUnknownRequirementsWith(const LogicalTensorPtr& tensor, MemoryType memoryType, const char* reason);
234+ bool AreAllConsumerRequirements(const LogicalTensorPtr& tensor, MemoryType memoryType) const;
235+ void DowngradeConsumerRequirements(const LogicalTensorPtr& tensor, MemoryType fromType);
236+ void ProcessL0C2L1SmallToLarge(Function& function);
237+ void ProcessL0C2L1LargeToSmall(Function& function);
238+ bool CheckUBTileShape(const LogicalTensorPtr& output);
239+ bool CheckConsumerViewShapeMultiple(const LogicalTensorPtr& output, const LogicalTensorPtr& input);
240+ void ProcessL0C2UBSmallToLarge(Function& function);
241+ void ProcessL0C2UBLargeToSmall(Function& function);
242+ void ProcessUB2L1SmallToLarge(Function& function);
243+ void ProcessUB2L1LargeToSmall(Function& function);
244+ bool ShouldSkipUB2L1SmallToLarge(const LogicalTensorPtr& iOperand, const LogicalTensorPtr& oOperand) const;
245+ bool IsDimMultiple(const Shape& shape1, const Shape& shape2);
246+ bool CheckInnerAxisC0Size(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
247+ size_t CalcNZTensorSize(const LogicalTensorPtr& tensor) const;
248+ int64_t CalcLineOffset(const Shape& shape, const Offset& offset) const;
249+ ConvertInserter inserter;
250+ AssignMemoryTypeChecker checker;
251+};
252+static constexpr double UB_THRESHOLD_ASSEMBLE = 0.35;
253+static constexpr double UB_THRESHOLD_NORMAL = 1.0;
254+static constexpr double L1_THRESHOLD = 0.5;
255+static constexpr uint16_t L0C_TILE_SIZE = 16;
256+} // namespace npu::tile_fwk::legacy
257+ 
258+#endif // TILE_FWK_ASSIGN_MEMORY_TYPE_LEGACY_H
@@ -223,7 +223,7 @@ void ConvertInserter::UpdateConsumerAndReconnect(std::shared_ptr<LogicalTensor>
223 for (size_t i = 0; i < op->iOperand.size(); ++i) {223 for (size_t i = 0; i < op->iOperand.size(); ++i) {
224 if ((op->iOperand[i]->magic == oldTensor->magic) &&224 if ((op->iOperand[i]->magic == oldTensor->magic) &&
225 (op->iOperand[i]->tensor->rawmagic == oldTensor->tensor->rawmagic)) {225 (op->iOperand[i]->tensor->rawmagic == oldTensor->tensor->rawmagic)) {
226- if (op->GetOpcode() == Opcode::OP_VIEW) {226+ if (op->GetOpcode() == Opcode::OP_VIEW || op->GetOpcode() == Opcode::OP_SLICE) {
227 updateViewOffset(oldTensor, newTensor, op);227 updateViewOffset(oldTensor, newTensor, op);
228 }228 }
229 op->ReplaceIOperand(i, newTensor);229 op->ReplaceIOperand(i, newTensor);
@@ -293,25 +293,25 @@ void ConvertInserter::InsertConvertOpForEachConsumer(Function& function, const O
293 }293 }
294}294}
295 295 
296-// 特殊场景处理:生成者均为Assemble或者消费者均为View/Assemble,且mem路径中经过DDR296+// 特殊场景处理:生成者均为Contract或者消费者均为Slice/Contract,且mem路径中经过DDR
297void ConvertInserter::ProcessSpecialProducersOrConsumers(Function& function, const Operation& op,297void ConvertInserter::ProcessSpecialProducersOrConsumers(Function& function, const Operation& op,
298 const std::shared_ptr<LogicalTensor>& oOperand,298 const std::shared_ptr<LogicalTensor>& oOperand,
299 std::set<Operation*, OpMagicComparator>& consumers,299 std::set<Operation*, OpMagicComparator>& consumers,
300 MemoryType& requiredMemoryType)300 MemoryType& requiredMemoryType)
301{301{
302- // case1:当tensor的生产者都是assemble,并且tensor的mem路径需要经过DDR,则将tensor的ori刷成DDR302+ // case1:当tensor的生产者都是contract,并且tensor的mem路径需要经过DDR,则将tensor的ori刷成DDR
303 APASS_LOG_DEBUG_F(Elements::Operation, "Operation %s[%d] has output %d original and requirement conflict.",303 APASS_LOG_DEBUG_F(Elements::Operation, "Operation %s[%d] has output %d original and requirement conflict.",
304 op.GetOpcodeStr().c_str(), op.GetOpMagic(), oOperand->magic);304 op.GetOpcodeStr().c_str(), op.GetOpMagic(), oOperand->magic);
305 const auto& items = tensorTobeMap.at(oOperand);305 const auto& items = tensorTobeMap.at(oOperand);
306 bool crossCore = std::all_of(items.begin(), items.end(), [this, &oOperand](const auto& item) {306 bool crossCore = std::all_of(items.begin(), items.end(), [this, &oOperand](const auto& item) {
307 return CrossCore(oOperand->GetMemoryTypeOriginal(), item.second.second);307 return CrossCore(oOperand->GetMemoryTypeOriginal(), item.second.second);
308 });308 });
309- bool producedByAssemble = isAllProducerAssemble(oOperand);309+ bool producedByContract = IsAllProducerContract(oOperand);
310- if (producedByAssemble && crossCore) {310+ if (producedByContract && crossCore) {
311 oOperand->SetMemoryTypeOriginal(MemoryType::MEM_DEVICE_DDR, true);311 oOperand->SetMemoryTypeOriginal(MemoryType::MEM_DEVICE_DDR, true);
312 }312 }
313- // case2:当tensor的消费者都是view或者assemble,并且tensor的mem路径需要经过DDR时,将需求降级为DDR313+ // case2:当tensor的消费者都是slice或者contract,并且tensor的mem路径需要经过DDR时,将需求降级为DDR
314- bool canSetBoth = isAllConsumersValid(function, consumers);314+ bool canSetBoth = IsAllMoveConsumersValid(function, consumers);
315 if (canSetBoth && crossCore) {315 if (canSetBoth && crossCore) {
316 requiredMemoryType = MEM_DEVICE_DDR;316 requiredMemoryType = MEM_DEVICE_DDR;
317 }317 }
@@ -462,21 +462,21 @@ bool ConvertInserter::SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand
462 (visitedTensor.find(oOperand->magic) != visitedTensor.end()));462 (visitedTensor.find(oOperand->magic) != visitedTensor.end()));
463}463}
464 464 
465-bool ConvertInserter::isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const465+bool ConvertInserter::IsAllProducerContract(const std::shared_ptr<LogicalTensor>& oOperand) const
466{466{
467 auto producers = oOperand->GetProducers();467 auto producers = oOperand->GetProducers();
468 return std::all_of(producers.begin(), producers.end(),468 return std::all_of(producers.begin(), producers.end(),
469- [](const Operation* producerOp) { return producerOp->GetOpcode() == Opcode::OP_ASSEMBLE; });469+ [](const Operation* producerOp) { return producerOp->GetOpcode() == Opcode::OP_CONTRACT; });
470}470}
471 471 
472-bool ConvertInserter::isAllConsumersValid(Function& function,472+bool ConvertInserter::IsAllMoveConsumersValid(Function& function,
473- const std::set<Operation*, OpMagicComparator>& consumers) const473+ const std::set<Operation*, OpMagicComparator>& consumers) const
474{474{
475 for (const auto consumer : consumers) {475 for (const auto consumer : consumers) {
476- if (consumer->GetOpcode() != Opcode::OP_VIEW && consumer->GetOpcode() != Opcode::OP_ASSEMBLE) {476+ if (consumer->GetOpcode() != Opcode::OP_SLICE && consumer->GetOpcode() != Opcode::OP_CONTRACT) {
477 return false;477 return false;
478 }478 }
479- if (consumer->GetOpcode() == Opcode::OP_ASSEMBLE &&479+ if (consumer->GetOpcode() == Opcode::OP_CONTRACT &&
480 FunctionUtils::GetNodeType(*(consumer->GetOOperands().front()), function) != NodeType::OUTCAST) {480 FunctionUtils::GetNodeType(*(consumer->GetOOperands().front()), function) != NodeType::OUTCAST) {
481 return false;481 return false;
482 }482 }
@@ -535,8 +535,8 @@ bool ConvertInserter::CreateMoveOpForConvert(Operation& op)
535 auto [from, to] = convertOpAttribute->GetConvertPath();535 auto [from, to] = convertOpAttribute->GetConvertPath();
536 536 
537 if (from == MemoryType::MEM_DEVICE_DDR) {537 if (from == MemoryType::MEM_DEVICE_DDR) {
538- op.SetOpCode(Opcode::OP_VIEW); // 将convert根据View, 后续GenerateMoveOp Pass会转化为copyin538+ op.SetOpCode(Opcode::OP_SLICE); // 将convert改为搬入操作,后续GenerateMoveOp Pass会转化为copyin
539- op.SetOpAttribute(BuildViewAttrForConvert(op, to));539+ op.SetOpAttribute(BuildSliceAttrForConvert(op, to));
540 auto childOp = *op.oOperand.front()->GetConsumers().begin();540 auto childOp = *op.oOperand.front()->GetConsumers().begin();
541 op.UpdateSubgraphID(childOp->GetSubgraphID());541 op.UpdateSubgraphID(childOp->GetSubgraphID());
542 op.SetScopeInfo(childOp->GetScopeInfo());542 op.SetScopeInfo(childOp->GetScopeInfo());
@@ -544,8 +544,8 @@ bool ConvertInserter::CreateMoveOpForConvert(Operation& op)
544 }544 }
545 545 
546 if (to == MemoryType::MEM_DEVICE_DDR) {546 if (to == MemoryType::MEM_DEVICE_DDR) {
547- op.SetOpCode(Opcode::OP_ASSEMBLE); // 将convert根据Assemble, 后续GenerateMoveOp Pass会转化为copyout547+ op.SetOpCode(Opcode::OP_CONTRACT); // 将convert改为搬出操作,后续GenerateMoveOp Pass会转化为copyout
548- op.SetOpAttribute(BuildAssembleAttrForConvert(op, from));548+ op.SetOpAttribute(BuildContractAttrForConvert(op, from));
549 auto parentOp = *op.iOperand.front()->GetProducers().begin();549 auto parentOp = *op.iOperand.front()->GetProducers().begin();
550 op.UpdateSubgraphID(parentOp->GetSubgraphID());550 op.UpdateSubgraphID(parentOp->GetSubgraphID());
551 op.SetScopeInfo(parentOp->GetScopeInfo());551 op.SetScopeInfo(parentOp->GetScopeInfo());
@@ -568,13 +568,13 @@ void ConvertInserter::InsertConvertOps(Function& function)
568 }568 }
569}569}
570 570 
571-std::shared_ptr<ViewOpAttribute> ConvertInserter::BuildViewAttrForConvert(const Operation& op, MemoryType to) const571+std::shared_ptr<ViewOpAttribute> ConvertInserter::BuildSliceAttrForConvert(const Operation& op, MemoryType to) const
572{572{
573 auto input = op.iOperand.front();573 auto input = op.iOperand.front();
574 return std::make_shared<ViewOpAttribute>(input->GetOffset(), to, input->GetDynOffset(), input->GetDynValidShape());574 return std::make_shared<ViewOpAttribute>(input->GetOffset(), to, input->GetDynOffset(), input->GetDynValidShape());
575}575}
576 576 
577-std::shared_ptr<AssembleOpAttribute> ConvertInserter::BuildAssembleAttrForConvert(const Operation& op,577+std::shared_ptr<AssembleOpAttribute> ConvertInserter::BuildContractAttrForConvert(const Operation& op,
578 MemoryType from) const578 MemoryType from) const
579{579{
580 auto input = op.iOperand.front();580 auto input = op.iOperand.front();
@@ -94,7 +94,7 @@ public:
94 // 根据已记录的converts插入OP_CONVERT94 // 根据已记录的converts插入OP_CONVERT
95 void InsertConvertOps(Function& function);95 void InsertConvertOps(Function& function);
96 96 
97- // 将插入的OP_CONVERT转化为View和Assemble,后续GenerateMoveOp时会转化为copy类Op97+ // 将插入的OP_CONVERT转化为Slice和Contract,后续GenerateMoveOp时会转化为copy类Op
98 bool CreateMoveOpForConvert(Operation& op);98 bool CreateMoveOpForConvert(Operation& op);
99 99 
100 // 判断是否跨Memory层级100 // 判断是否跨Memory层级
@@ -115,11 +115,11 @@ public:
115 bool SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand,115 bool SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand,
116 const std::unordered_set<int>& visitedTensor) const;116 const std::unordered_set<int>& visitedTensor) const;
117 117 
118- // 检查tensor生产者是否都是assemble118+ // 检查tensor生产者是否都是contract
119- bool isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const;119+ bool IsAllProducerContract(const std::shared_ptr<LogicalTensor>& oOperand) const;
120 120 
121- // 检查tensor所有的消费者是否都有效121+ // 检查tensor所有的消费者是否都是有效的move-like消费者
122- bool isAllConsumersValid(Function& function, const std::set<Operation*, OpMagicComparator>& consumers) const;122+ bool IsAllMoveConsumersValid(Function& function, const std::set<Operation*, OpMagicComparator>& consumers) const;
123 123 
124 // 为每个存在内存冲突的消费者插入convert op124 // 为每个存在内存冲突的消费者插入convert op
125 void InsertConvertOpForEachConsumer(Function& function, const Operation& op,125 void InsertConvertOpForEachConsumer(Function& function, const Operation& op,
@@ -136,11 +136,11 @@ public:
136 std::shared_ptr<LogicalTensor> CreateTensorLikeForConvert(const std::shared_ptr<LogicalTensor>& input,136 std::shared_ptr<LogicalTensor> CreateTensorLikeForConvert(const std::shared_ptr<LogicalTensor>& input,
137 MemoryType outputMemoryType) const;137 MemoryType outputMemoryType) const;
138 138 
139- // 构造convert转view时使用的ViewOpAttribute139+ // 构造convert转slice时使用的ViewOpAttribute
140- std::shared_ptr<ViewOpAttribute> BuildViewAttrForConvert(const Operation& op, MemoryType to) const;140+ std::shared_ptr<ViewOpAttribute> BuildSliceAttrForConvert(const Operation& op, MemoryType to) const;
141 141 
142- // 构造convert转assemble时使用的AssembleOpAttribute142+ // 构造convert转contract时使用的AssembleOpAttribute
143- std::shared_ptr<AssembleOpAttribute> BuildAssembleAttrForConvert(const Operation& op, MemoryType from) const;143+ std::shared_ptr<AssembleOpAttribute> BuildContractAttrForConvert(const Operation& op, MemoryType from) const;
144 144 
145 // graph重连145 // graph重连
146 void GraphReconnect(const std::shared_ptr<LogicalTensor>& oOperand, std::shared_ptr<LogicalTensor> output,146 void GraphReconnect(const std::shared_ptr<LogicalTensor>& oOperand, std::shared_ptr<LogicalTensor> output,
@@ -161,7 +161,7 @@ public:
161 // 判断同一源 tensor 是否有并行 consumer 需要不同的 memory 去向161 // 判断同一源 tensor 是否有并行 consumer 需要不同的 memory 去向
162 bool HasParallelDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;162 bool HasParallelDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;
163 163 
164- // 特殊场景处理:生成者均为Assemble或者消费者均为View/Assemble,且mem路径中经过DDR164+ // 特殊场景处理:生成者均为Contract或者消费者均为Slice/Contract,且mem路径中经过DDR
165 void ProcessSpecialProducersOrConsumers(Function& function, const Operation& op,165 void ProcessSpecialProducersOrConsumers(Function& function, const Operation& op,
166 const std::shared_ptr<LogicalTensor>& oOperand,166 const std::shared_ptr<LogicalTensor>& oOperand,
167 std::set<Operation*, OpMagicComparator>& consumers,167 std::set<Operation*, OpMagicComparator>& consumers,
@@ -0,0 +1,602 @@
1+/**
2+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file convert_op_inserter.cpp
13+ * \brief
14+ */
15+#include "convert_op_inserter_legacy.h"
16+ 
17+#include <algorithm>
18+#include <unordered_set>
19+ 
20+#include "interface/tensor/irbuilder.h"
21+#include "interface/tensor/logical_tensor.h"
22+#include "passes/pass_utils/graph_utils.h"
23+#include "passes/pass_utils/pass_utils.h"
24+#include "passes/pass_log/pass_log.h"
25+#include "passes/tile_graph_pass/data_path/memory_path_utils.h"
26+ 
27+#define MODULE_NAME "AssignMemoryType"
28+ 
29+namespace npu {
30+namespace tile_fwk {
31+namespace legacy {
32+ 
33+const std::unordered_set<DataType> kA2A3SupportedDtypes = {DT_INT4, DT_INT8, DT_UINT8, DT_FP16, DT_BF16, DT_INT16};
34+const std::unordered_set<DataType> kA5SupportedDtypes = {DT_INT4, DT_INT8, DT_UINT8, DT_FP16,
35+ DT_BF16, DT_HF8, DT_FP8, DT_FP32};
36+const std::unordered_set<DataType> l0c2l1SupportedDtypes = {DT_FP16, DT_BF16};
37+ 
38+const static std::unordered_map<NPUArch, std::unordered_set<DataType>> kArch2SupportedDtypes = {
39+ {NPUArch::DAV_1001, kA2A3SupportedDtypes},
40+ {NPUArch::DAV_2201, kA2A3SupportedDtypes},
41+ {NPUArch::DAV_3510, kA5SupportedDtypes},
42+ {NPUArch::DAV_UNKNOWN, kA2A3SupportedDtypes}};
43+ 
44+void ConvertInserter::UpdateTensorTobeMap(const LogicalTensorPtr& tensor, Operation& operation, MemoryType t,
45+ const char* reason)
46+{
47+ bool hasReason = reason != nullptr && reason[0] != '\0';
48+ if (!tensor->HasConsumer(operation)) {
49+ if (hasReason) {
50+ APASS_LOG_ERROR_F(Elements::Tensor,
51+ "Operation %d is not a consumer of tensor %d; "
52+ "Please make sure the operation is relative to the tensor to be mapped. reason: %s.",
53+ operation.GetOpMagic(), tensor->GetMagic(), reason);
54+ } else {
55+ APASS_LOG_ERROR_F(Elements::Tensor,
56+ "Operation %d is not a consumer of tensor %d; "
57+ "Please make sure the operation is relative to the tensor to be mapped.",
58+ operation.GetOpMagic(), tensor->GetMagic());
59+ }
60+ return;
61+ }
62+ int opMagic = operation.GetOpMagic();
63+ auto& tobeMap = tensorTobeMap[tensor];
64+ auto [opIt, inserted] = tobeMap.emplace(opMagic, std::make_pair(&operation, t));
65+ if (inserted) {
66+ return;
67+ }
68+ MemoryType& currentType = opIt->second.second;
69+ if (currentType == MemoryType::MEM_UNKNOWN && t != MemoryType::MEM_UNKNOWN) {
70+ currentType = t;
71+ return;
72+ }
73+ if (currentType == t) {
74+ return;
75+ }
76+ MemoryType oldType = currentType;
77+ currentType = t;
78+ if (hasReason) {
79+ APASS_LOG_DEBUG_F(Elements::Tensor, "Update tensor %d toBeMap(%s[%d]) from %s to %s, reason: %s.",
80+ tensor->GetMagic(), operation.GetOpcodeStr().c_str(), operation.GetOpMagic(),
81+ BriefMemoryTypeToString(oldType).c_str(), BriefMemoryTypeToString(t).c_str(), reason);
82+ } else {
83+ APASS_LOG_DEBUG_F(Elements::Tensor, "Update tensor %d toBeMap(%s[%d]) from %s to %s,", tensor->GetMagic(),
84+ operation.GetOpcodeStr().c_str(), operation.GetOpMagic(),
85+ BriefMemoryTypeToString(oldType).c_str(), BriefMemoryTypeToString(t).c_str());
86+ }
87+}
88+ 
89+std::map<MemoryType, std::set<Operation*, OpMagicComparator>> ConvertInserter::GetRequiredTobe(
90+ LogicalTensorPtr& tensor) const
91+{
92+ if (tensorTobeMap.count(tensor) == 0) {
93+ APASS_LOG_INFO_F(Elements::Tensor,
94+ "Tensor %d has not been inserted yet; "
95+ "Please make sure tensor in the tobe map.",
96+ tensor->GetMagic());
97+ return {};
98+ }
99+ std::map<MemoryType, std::set<Operation*, OpMagicComparator>> result;
100+ for (const auto& item : tensorTobeMap.at(tensor)) {
@@ -0,0 +1,181 @@
1+/**
2+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file convert_op_inserter.h
13+ * \brief
14+ */
15+ 
16+#ifndef PASS_CONVERT_OP_INSERTER_LEGACY_H_
17+#define PASS_CONVERT_OP_INSERTER_LEGACY_H_
18+ 
19+#include <unordered_map>
20+#include <unordered_set>
21+#include <set>
22+ 
23+#include "interface/function/function.h"
24+#include "interface/operation/attribute.h"
25+#include "interface/operation/opcode.h"
26+#include "tilefwk/data_type.h"
27+#include "tilefwk/tilefwk.h"
28+#include "tilefwk/platform.h"
29+#include "interface/inner/tilefwk.h"
30+ 
31+namespace npu {
32+namespace tile_fwk {
33+namespace legacy {
34+ 
35+struct OpMagicComparator {
36+ bool operator()(const Operation* a, const Operation* b) const { return a->GetOpMagic() < b->GetOpMagic(); }
37+};
38+ 
39+struct ConvertOpInfo {
40+ MemoryType from;
41+ MemoryType to;
42+ std::shared_ptr<LogicalTensor> input;
43+ std::shared_ptr<LogicalTensor> output;
44+};
45+ 
46+class ConvertInserter {
47+public:
48+ ConvertInserter() = default;
49+ ~ConvertInserter() = default;
50+ 
51+ std::vector<ConvertOpInfo> converts;
52+ std::unordered_map<int, std::shared_ptr<RawTensor>> oldRawToNewRaw;
53+ 
54+ /*
55+ key: Tensor 指针
56+ value: Opmagic到consumer op的指针和该op所需内存类型对的映射map
57+ */
58+ std::map<LogicalTensorPtr, std::map<int, std::pair<Operation*, MemoryType>>> tensorTobeMap;
59+ std::unordered_map<int, std::map<MemoryType, std::set<Operation*, OpMagicComparator>>> conflictMap;
60+ 
61+ // 设置指定tensor的指定consumer op所需的mem tobe 类型
62+ void UpdateTensorTobeMap(const LogicalTensorPtr& tensor, Operation& operation, MemoryType t,
63+ const char* reason = nullptr);
64+ 
65+ std::map<MemoryType, std::set<Operation*, OpMagicComparator>> GetRequiredTobe(LogicalTensorPtr& tensor) const;
66+ 
67+ // 查询指定tensor是否存在指定consumer op所需的mem类型
68+ bool HasRequirement(const LogicalTensorPtr& tensor, const Operation& operation) const;
69+ 
70+ // 安全提取指定tensor的指定consumer op所需的mem类型,不存在时返回MEM_UNKNOWN
71+ MemoryType GetRequirementOrUnknown(const LogicalTensorPtr& tensor, const Operation& operation) const;
72+ 
73+ // 提取指定tensor的所有consumer op和所需的mem类型
74+ std::map<Operation*, MemoryType, OpMagicComparator> GetConsumerRequirements(const LogicalTensorPtr& tensor) const;
75+ 
76+ // 提取指定tensor的所有已知consumer需求mem类型
77+ std::set<MemoryType> GetKnownRequiredTypes(const LogicalTensorPtr& tensor) const;
78+ 
79+ // 如果指定tensor的已知consumer需求mem类型唯一则返回该类型,否则返回MEM_UNKNOWN
80+ MemoryType TryGetUniqueKnownRequiredType(const LogicalTensorPtr& tensor) const;
81+ 
82+ // 清空convert插入规划态,不清空tensorTobeMap
83+ void ClearPlanningState();
84+ 
85+ // 过滤得到所有有conflict的tensor信息
86+ void FilterConflictTensor();
87+ 
88+ // tobe Map转换类型,以memory type为key
89+ std::map<MemoryType, std::set<Operation*, OpMagicComparator>> ReformMap(
90+ const std::map<int, std::pair<Operation*, MemoryType>>& oriMap) const;
91+ 
92+ // 遍历所有tensor,如果有Mem conflict,记录到converts中
93+ Status RecordConflict(Function& function);
94+ 
95+ // 根据已记录的converts插入OP_CONVERT
96+ void InsertConvertOps(Function& function);
97+ 
98+ // 将插入的OP_CONVERT转化为View和Assemble,后续GenerateMoveOp时会转化为copy类Op
99+ bool CreateMoveOpForConvert(Operation& op);
100+ 
101+ // 判断是否跨Memory层级
102+ bool CrossCore(const MemoryType from, const MemoryType to) const;
103+ 
104+ // 更新消费者并重连graph
105+ void UpdateConsumerAndReconnect(std::shared_ptr<LogicalTensor> oldTensor, std::shared_ptr<LogicalTensor> newTensor,
106+ Operation* op) const;
107+ 
108+ // 对外总接口
109+ Status DoInsertion(Function& function);
110+ 
111+ // 构建转换路径
112+ Status ConstructPath(MemoryType from, MemoryType to, std::vector<MemoryType>& paths,
113+ const std::shared_ptr<LogicalTensor>& oOperand, const Operation& op) const;
114+ 
115+ // 检查tensor是否需要跳过
116+ bool SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand,
117+ const std::unordered_set<int>& visitedTensor) const;
118+ 
119+ // 检查tensor生产者是否都是assemble
120+ bool isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const;
121+ 
122+ // 检查tensor所有的消费者是否都有效
123+ bool isAllConsumersValid(Function& function, const std::set<Operation*, OpMagicComparator>& consumers) const;
124+ 
125+ // 为每个存在内存冲突的消费者插入convert op
126+ void InsertConvertOpForEachConsumer(Function& function, const Operation& op,
127+ const std::shared_ptr<LogicalTensor>& oOperand,
128+ std::set<Operation*, OpMagicComparator>& consumers,
129+ std::vector<MemoryType>& paths);
130+ 
131+ // 记录需要插入的convert op
132+ std::shared_ptr<LogicalTensor> RecordInsertConvertOp(const std::shared_ptr<LogicalTensor>& oOperand,
133+ const std::vector<MemoryType>& paths, Function& function,
134+ const Operation& op);
135+ 
136+ // 创建convert链路上的中间tensor,并继承输入tensor的动态shape状态
137+ std::shared_ptr<LogicalTensor> CreateTensorLikeForConvert(const std::shared_ptr<LogicalTensor>& input,
138+ MemoryType outputMemoryType) const;
139+ 
140+ // 构造convert转view时使用的ViewOpAttribute
141+ std::shared_ptr<ViewOpAttribute> BuildViewAttrForConvert(const Operation& op, MemoryType to) const;
142+ 
143+ // 构造convert转assemble时使用的AssembleOpAttribute
144+ std::shared_ptr<AssembleOpAttribute> BuildAssembleAttrForConvert(const Operation& op, MemoryType from) const;
145+ 
146+ // graph重连
147+ void GraphReconnect(const std::shared_ptr<LogicalTensor>& oOperand, std::shared_ptr<LogicalTensor> output,
148+ const std::set<Operation*, OpMagicComparator>& consumers, Function& function) const;
149+ 
150+ // cube级联场景
151+ bool IsNotValidDataType(const std::shared_ptr<LogicalTensor>& firstCVOutput) const;
152+ 
153+ // l0c2l1场景,限制数据类型和数据对齐
154+ bool FitL0C2L1(const LogicalTensorPtr& tensor);
155+ 
156+ // l0c2l1场景规避条件检查,检查op输入是否满足无非立即数的validShape
157+ bool FitL0C2L1(const Operation& op);
158+ 
159+ // 检查是否适合 UB2L1 小搬大
160+ bool FitUB2L1(const LogicalTensorPtr& tensor) const;
161+ 
162+ // 判断同一源 tensor 是否有并行 consumer 需要不同的 memory 去向
163+ bool HasParallelDifferentConsumerRequirement(const LogicalTensorPtr& tensor, MemoryType targetType) const;
164+ 
165+ // 特殊场景处理:生成者均为Assemble或者消费者均为View/Assemble,且mem路径中经过DDR
166+ void ProcessSpecialProducersOrConsumers(Function& function, const Operation& op,
167+ const std::shared_ptr<LogicalTensor>& oOperand,
168+ std::set<Operation*, OpMagicComparator>& consumers,
169+ MemoryType& requiredMemoryType);
170+ 
171+ // 构造转换路径
172+ Status ProcessConvertPath(const Operation& op, const std::shared_ptr<LogicalTensor>& oOperand,
173+ MemoryType requiredMemoryType, std::vector<MemoryType>& paths);
174+};
175+static constexpr int MATMUL_DIM_NUM = 2;
176+static constexpr int L0C2L1_DIM1_SHAPE_RESTICT = 16; // l0c2l1要求输入的外轴(第一轴)元素数量必须是16的倍数
177+static constexpr int L0C2L1_DIM2_BYTE_RESTICT = 32; // l0c2l1要求输入的内轴(第二轴)必须是32Byte对齐
178+} // namespace legacy
179+} // namespace tile_fwk
180+} // namespace npu
181+#endif // PASS_CONVERT_OP_INSERTER_LEGACY_H_
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include "passes/tile_graph_pass/data_path/generate_move_op.h"16#include "passes/tile_graph_pass/data_path/generate_move_op.h"
17+#include "interface/configs/config_manager_ng.h"
17#include "interface/function/function.h"18#include "interface/function/function.h"
18#include "interface/tensor/irbuilder.h"19#include "interface/tensor/irbuilder.h"
19#include "interface/operation/operation.h"20#include "interface/operation/operation.h"
@@ -412,20 +413,21 @@ void GenerateMoveOp::ProcessUB2L1(Function& function, Operation& op) const
412 413 
413Status GenerateMoveOp::CreateMoveOp(Function& function) const414Status GenerateMoveOp::CreateMoveOp(Function& function) const
414{415{
416+ const Opcode sliceOpcode = config::GetSliceOpcode();
417+ const Opcode contractOpcode = config::GetContractOpcode();
415 for (auto& op : function.Operations()) {418 for (auto& op : function.Operations()) {
419+ if (op.GetOpcode() == Opcode::OP_ASSEMBLE_SSA || op.GetOpcode() == contractOpcode) {
420+ CreateMoveOpForAssemble(function, op);
421+ continue;
422+ }
423+ if (op.GetOpcode() == sliceOpcode) {
424+ Status status = ProcessViewOp(function, op);
425+ if (status != SUCCESS) {
426+ return status;
427+ }
428+ continue;
429+ }
416 switch (op.GetOpcode()) {430 switch (op.GetOpcode()) {
417- case Opcode::OP_ASSEMBLE_SSA:
418- case Opcode::OP_ASSEMBLE: {
419- CreateMoveOpForAssemble(function, op);
420- break;
421- }
422- case Opcode::OP_VIEW: {
423- Status status = ProcessViewOp(function, op);
424- if (status != SUCCESS) {
425- return status;
426- }
427- break;
428- }
429 case Opcode::OP_CONVERT: {431 case Opcode::OP_CONVERT: {
430 Status createMoveOpForConvert = CreateMoveOpForConvert(function, op);432 Status createMoveOpForConvert = CreateMoveOpForConvert(function, op);
431 if (createMoveOpForConvert != SUCCESS) {433 if (createMoveOpForConvert != SUCCESS) {
@@ -464,7 +466,7 @@ Status GenerateMoveOp::CreateMoveOp(Function& function) const
464 466 
465Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const467Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
466{468{
467- // 1. 获取 L1_COPY_IN_CONV 的 producer VIEW469+ // 1. 获取 L1_COPY_IN_CONV 的 producer view-family op
468 auto inputTensor = op.GetIOperands()[0];470 auto inputTensor = op.GetIOperands()[0];
469 const auto& producers = inputTensor->GetProducers();471 const auto& producers = inputTensor->GetProducers();
470 if (producers.empty()) {472 if (producers.empty()) {
@@ -472,19 +474,19 @@ Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
472 }474 }
473 475 
474 auto producerOp = *producers.begin();476 auto producerOp = *producers.begin();
475- if (producerOp->GetOpcode() != Opcode::OP_VIEW) {477+ if (producerOp->GetOpcode() != config::GetSliceOpcode()) {
476 return SUCCESS;478 return SUCCESS;
477 }479 }
478 480 
479- // 2. 获取 VIEW 的 fromOffset 属性481+ // 2. 获取 view-family op 的 fromOffset 属性
480 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(producerOp->GetOpAttribute());482 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(producerOp->GetOpAttribute());
481 if (viewAttr == nullptr) {483 if (viewAttr == nullptr) {
482- APASS_LOG_ERROR_F(Elements::Operation, "L1_COPY_IN_CONV op[%d]: VIEW producer[%d] has null ViewOpAttribute.",484+ APASS_LOG_ERROR_F(Elements::Operation, "L1_COPY_IN_CONV op[%d]: %s producer[%d] has null ViewOpAttribute.",
483- op.GetOpMagic(), producerOp->GetOpMagic());485+ op.GetOpMagic(), producerOp->GetOpcodeStr().c_str(), producerOp->GetOpMagic());
484 return FAILED;486 return FAILED;
485 }487 }
486 488 
487- // 3. 将 VIEW 的 fromOffset 累加到 L1_COPY_IN_CONV 的 CopyOpAttribute 的 fromOffset489+ // 3. 将 view-family op 的 fromOffset 累加到 L1_COPY_IN_CONV 的 CopyOpAttribute 的 fromOffset
488 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());490 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());
489 if (copyAttr == nullptr) {491 if (copyAttr == nullptr) {
490 APASS_LOG_ERROR_F(Elements::Operation, "L1_COPY_IN_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());492 APASS_LOG_ERROR_F(Elements::Operation, "L1_COPY_IN_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());
@@ -492,7 +494,7 @@ Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
492 }494 }
493 std::vector<OpImmediate> curFromOffset = copyAttr->GetFromOffset();495 std::vector<OpImmediate> curFromOffset = copyAttr->GetFromOffset();
494 496 
495- // 如果当前 offset 为空,直接使用 VIEW 的 offset497+ // 如果当前 offset 为空,直接使用 view-family op 的 offset
496 if (curFromOffset.empty()) {498 if (curFromOffset.empty()) {
497 copyAttr->SetFromOffset(OpImmediate::Specified(viewAttr->GetFromTensorOffset()));499 copyAttr->SetFromOffset(OpImmediate::Specified(viewAttr->GetFromTensorOffset()));
498 } else {500 } else {
@@ -516,7 +518,7 @@ Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
516 copyAttr->SetRawShape(OpImmediate::Specified(viewInput->GetRawTensor()->GetDynRawShape()));518 copyAttr->SetRawShape(OpImmediate::Specified(viewInput->GetRawTensor()->GetDynRawShape()));
517 op.SetOpAttribute(copyAttr);519 op.SetOpAttribute(copyAttr);
518 520 
519- // 4. 标记删除 VIEW521+ // 4. 标记删除 view-family op
520 op.ReplaceIOperand(0, viewInput);522 op.ReplaceIOperand(0, viewInput);
521 producerOp->SetAsDeleted();523 producerOp->SetAsDeleted();
522 return SUCCESS;524 return SUCCESS;
@@ -524,7 +526,7 @@ Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
524 526 
525Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const527Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const
526{528{
527- // 1. 获取 L0C_COPY_OUT_CONV 的 consumer ASSEMBLE529+ // 1. 获取 L0C_COPY_OUT_CONV 的 consumer assemble-family op
528 auto outputTensor = op.GetOOperands()[0];530 auto outputTensor = op.GetOOperands()[0];
529 const auto& consumers = outputTensor->GetConsumers();531 const auto& consumers = outputTensor->GetConsumers();
530 if (consumers.empty()) {532 if (consumers.empty()) {
@@ -532,20 +534,20 @@ Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const
532 }534 }
533 535 
534 auto consumerOp = *consumers.begin();536 auto consumerOp = *consumers.begin();
535- if (consumerOp->GetOpcode() != Opcode::OP_ASSEMBLE) {537+ if (consumerOp->GetOpcode() != config::GetContractOpcode()) {
536 return SUCCESS;538 return SUCCESS;
537 }539 }
538 540 
539- // 2. 获取 ASSEMBLE 的 toOffset 属性541+ // 2. 获取 assemble-family op 的 toOffset 属性
540 auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(consumerOp->GetOpAttribute());542 auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(consumerOp->GetOpAttribute());
541 if (assembleAttr == nullptr) {543 if (assembleAttr == nullptr) {
542 APASS_LOG_ERROR_F(Elements::Operation,544 APASS_LOG_ERROR_F(Elements::Operation,
543- "L0C_COPY_OUT_CONV op[%d]: ASSEMBLE consumer[%d] has null AssembleOpAttribute.",545+ "L0C_COPY_OUT_CONV op[%d]: %s consumer[%d] has null AssembleOpAttribute.", op.GetOpMagic(),
544- op.GetOpMagic(), consumerOp->GetOpMagic());546+ consumerOp->GetOpcodeStr().c_str(), consumerOp->GetOpMagic());
545 return FAILED;547 return FAILED;
546 }548 }
547 549 
548- // 3. 将 ASSEMBLE 的 toOffset 累加到 L0C_COPY_OUT_CONV 的 toOffset550+ // 3. 将 assemble-family op 的 toOffset 累加到 L0C_COPY_OUT_CONV 的 toOffset
549 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());551 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());
550 if (copyAttr == nullptr) {552 if (copyAttr == nullptr) {
551 APASS_LOG_ERROR_F(Elements::Operation, "L0C_COPY_OUT_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());553 APASS_LOG_ERROR_F(Elements::Operation, "L0C_COPY_OUT_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());
@@ -553,7 +555,7 @@ Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const
553 }555 }
554 std::vector<OpImmediate> curToOffset = copyAttr->GetToOffset();556 std::vector<OpImmediate> curToOffset = copyAttr->GetToOffset();
555 557 
556- // 如果当前 offset 为空,直接使用 ASSEMBLE 的 offset558+ // 如果当前 offset 为空,直接使用 assemble-family op 的 offset
557 if (curToOffset.empty()) {559 if (curToOffset.empty()) {
558 copyAttr->SetToOffset(560 copyAttr->SetToOffset(
559 OpImmediate::Specified(TensorOffset(assembleAttr->GetToOffset(), assembleAttr->GetToDynOffset())));561 OpImmediate::Specified(TensorOffset(assembleAttr->GetToOffset(), assembleAttr->GetToDynOffset())));
@@ -578,7 +580,7 @@ Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const
578 copyAttr->SetRawShape(OpImmediate::Specified(assembleOutput->GetRawTensor()->GetDynRawShape()));580 copyAttr->SetRawShape(OpImmediate::Specified(assembleOutput->GetRawTensor()->GetDynRawShape()));
579 op.SetOpAttribute(copyAttr);581 op.SetOpAttribute(copyAttr);
580 582 
581- // 4. 标记删除 ASSEMBLE583+ // 4. 标记删除 assemble-family op
582 op.ReplaceOOperand(0, assembleOutput);584 op.ReplaceOOperand(0, assembleOutput);
583 consumerOp->SetAsDeleted();585 consumerOp->SetAsDeleted();
584 return SUCCESS;586 return SUCCESS;
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include <unordered_set>16#include <unordered_set>
17+#include "interface/configs/config_manager_ng.h"
17#include "passes/pass_utils/graph_utils.h"18#include "passes/pass_utils/graph_utils.h"
18#include "interface/tensor/irbuilder.h"19#include "interface/tensor/irbuilder.h"
19#include "intra_subgraph_adapter.h"20#include "intra_subgraph_adapter.h"
@@ -43,6 +44,49 @@ inline std::string IntSetToStr(const std::set<T>& colorSet)
43 return ss.str();44 return ss.str();
44}45}
45 46 
47+static bool IsAssembleWithDifferentMemoryType(const Operation& op, MemoryType outputMemoryType)
48+{
49+ if (!IsAssembleLike(op.GetOpcode()) || op.GetOpcode() == config::GetContractOpcode() || op.GetIOperands().empty() ||
50+ op.GetOOperands().empty()) {
51+ return false;
52+ }
53+ auto input = op.GetIOperands().front();
54+ auto output = op.GetOOperands().front();
55+ if (input == nullptr || output == nullptr) {
56+ return false;
57+ }
58+ auto inputType = input->GetMemoryTypeOriginal();
59+ return inputType != MemoryType::MEM_UNKNOWN && outputMemoryType != MemoryType::MEM_UNKNOWN &&
60+ inputType != outputMemoryType;
61+}
62+ 
63+static bool IsViewWithDifferentMemoryType(const Operation& op, MemoryType inputMemoryType)
64+{
65+ if (!IsViewLike(op.GetOpcode()) || op.GetOpcode() == config::GetSliceOpcode() || op.GetIOperands().empty() ||
66+ op.GetOOperands().empty()) {
67+ return false;
68+ }
69+ auto input = op.GetIOperands().front();
70+ auto output = op.GetOOperands().front();
71+ if (input == nullptr || output == nullptr) {
72+ return false;
73+ }
74+ auto outputType = output->GetMemoryTypeOriginal();
75+ return inputMemoryType != MemoryType::MEM_UNKNOWN && outputType != MemoryType::MEM_UNKNOWN &&
76+ inputMemoryType != outputType;
77+}
78+ 
79+static void SetConfiguredOpcode(Operation& op, Opcode opcode)
80+{
81+ if (op.GetOpcode() == opcode) {
82+ return;
83+ }
84+ std::string oldOpcode = op.GetOpcodeStr();
85+ op.SetOpCode(opcode);
86+ APASS_LOG_DEBUG_F(Elements::Operation, "Change %s[%d] opcode to %s.", oldOpcode.c_str(), op.GetOpMagic(),
87+ op.GetOpcodeStr().c_str());
88+}
89+ 
46Status IntraSubgraphAdapter::RunOnFunction(Function& function)90Status IntraSubgraphAdapter::RunOnFunction(Function& function)
47{91{
48 LogicalTensors boundaryTensors = CollectBoundaryTensors(function);92 LogicalTensors boundaryTensors = CollectBoundaryTensors(function);
@@ -157,7 +201,7 @@ Status IntraSubgraphAdapter::CheckBoundaryTensor(LogicalTensorPtr tensor)
157Status IntraSubgraphAdapter::SplitBoundaryTensor(Function& function, LogicalTensorPtr tensor, int mainSubgraphID,201Status IntraSubgraphAdapter::SplitBoundaryTensor(Function& function, LogicalTensorPtr tensor, int mainSubgraphID,
158 LogicalTensors& newBoundaryTensors)202 LogicalTensors& newBoundaryTensors)
159{203{
160- // if the tensor has multiple producers in different subgraph, then the producers must be OP_ASSEMBLE/OP_COPY_OUT.204+ // If the tensor has multiple producers in different subgraph, producers must be assemble-family or OP_COPY_OUT.
161 for (const auto& producer : tensor->GetProducers()) {205 for (const auto& producer : tensor->GetProducers()) {
162 if (producer->GetSubgraphID() != mainSubgraphID) {206 if (producer->GetSubgraphID() != mainSubgraphID) {
163 Opcode producerOpcode = producer->GetOpcode();207 Opcode producerOpcode = producer->GetOpcode();
@@ -166,7 +210,7 @@ Status IntraSubgraphAdapter::SplitBoundaryTensor(Function& function, LogicalTens
166 APASS_LOG_ERROR_F(210 APASS_LOG_ERROR_F(
167 Elements::Operation,211 Elements::Operation,
168 "OpCalcType error, boundary tensor magic : %d, producer op magic : %d, producer op : %s; If the "212 "OpCalcType error, boundary tensor magic : %d, producer op magic : %d, producer op : %s; If the "
169- "tensor has multiple producers, then the producers can only be OP_ASSEMBLE/OP_COPY_OUT.%s",213+ "tensor has multiple producers, then the producers can only be assemble-family/OP_COPY_OUT.%s",
170 tensor->GetMagic(), producer->GetOpMagic(), producer->GetOpcodeStr().c_str(),214 tensor->GetMagic(), producer->GetOpMagic(), producer->GetOpcodeStr().c_str(),
171 GetFormatBacktrace(*producer).c_str());215 GetFormatBacktrace(*producer).c_str());
172 return FAILED;216 return FAILED;
@@ -176,7 +220,7 @@ Status IntraSubgraphAdapter::SplitBoundaryTensor(Function& function, LogicalTens
176 APASS_LOG_ERROR_F(220 APASS_LOG_ERROR_F(
177 Elements::Operation,221 Elements::Operation,
178 "Producer input error, boundary tensor magic : %d, producer op magic : %d, producer op : %s; The "222 "Producer input error, boundary tensor magic : %d, producer op magic : %d, producer op : %s; The "
179- "OP_ASSEMBLE should have one input operand.%s",223+ "Assemble-family producer should have one input operand.%s",
180 tensor->GetMagic(), producer->GetOpMagic(), producer->GetOpcodeStr().c_str(),224 tensor->GetMagic(), producer->GetOpMagic(), producer->GetOpcodeStr().c_str(),
181 GetFormatBacktrace(*producer).c_str());225 GetFormatBacktrace(*producer).c_str());
182 return FAILED;226 return FAILED;
@@ -187,10 +231,11 @@ Status IntraSubgraphAdapter::SplitBoundaryTensor(Function& function, LogicalTens
187 LogicalTensorPtr assembleInput = producer->GetIOperands()[0];231 LogicalTensorPtr assembleInput = producer->GetIOperands()[0];
188 APASS_LOG_DEBUG_F(Elements::Tensor, "SplitBoundaryTensor output of %s[%d]",232 APASS_LOG_DEBUG_F(Elements::Tensor, "SplitBoundaryTensor output of %s[%d]",
189 producer->GetOpcodeStr().c_str(), producer->GetOpMagic());233 producer->GetOpcodeStr().c_str(), producer->GetOpMagic());
190- LogicalTensorPtr newTensor = InsertOpBetween(function, Opcode::OP_ASSEMBLE, assembleInput, {producer});234+ LogicalTensorPtr newTensor = InsertOpBetween(function, config::GetContractOpcode(), assembleInput,
235+ {producer});
191 producer->UpdateSubgraphID(mainSubgraphID);236 producer->UpdateSubgraphID(mainSubgraphID);
192- APASS_LOG_INFO_F(Elements::Tensor, "Adjust OP_ASSEMBLE(magic : %d) to subgraph %d.",237+ APASS_LOG_INFO_F(Elements::Tensor, "Adjust %s(magic : %d) to subgraph %d.",
193- producer->GetOpMagic(), mainSubgraphID);238+ producer->GetOpcodeStr().c_str(), producer->GetOpMagic(), mainSubgraphID);
194 // The intermediate tensor become a new boundary tensor.239 // The intermediate tensor become a new boundary tensor.
195 newBoundaryTensors.push_back(newTensor);240 newBoundaryTensors.push_back(newTensor);
196 APASS_LOG_INFO_F(Elements::Tensor, "Add new tensor(magic : %d) to boundary tensors.",241 APASS_LOG_INFO_F(Elements::Tensor, "Add new tensor(magic : %d) to boundary tensors.",
@@ -213,12 +258,12 @@ Status IntraSubgraphAdapter::SplitBoundaryTensor(Function& function, LogicalTens
213 }258 }
214 }259 }
215 260 
216- // For consumers from other subgraph, we insert a new ASSEMBLE before them,261+ // For consumers from other subgraph, we insert a new CONTRACT before them,
217 // the intermediate tensor become a new boundary tensor.262 // the intermediate tensor become a new boundary tensor.
218 if (subsidiaryConsumers.size() != 0) {263 if (subsidiaryConsumers.size() != 0) {
219 APASS_LOG_DEBUG_F(Elements::Operation,264 APASS_LOG_DEBUG_F(Elements::Operation,
220 "=========== multi subsidiaryConsumers size: %zu ==========", subsidiaryConsumers.size());265 "=========== multi subsidiaryConsumers size: %zu ==========", subsidiaryConsumers.size());
221- LogicalTensorPtr newTensor = InsertOpBetween(function, Opcode::OP_ASSEMBLE, tensor, subsidiaryConsumers,266+ LogicalTensorPtr newTensor = InsertOpBetween(function, config::GetContractOpcode(), tensor, subsidiaryConsumers,
222 mainSubgraphID);267 mainSubgraphID);
223 newBoundaryTensors.push_back(newTensor);268 newBoundaryTensors.push_back(newTensor);
224 }269 }
@@ -244,7 +289,7 @@ Status IntraSubgraphAdapter::ProcessBoundaryTensor(Function& function, LogicalTe
244 APASS_LOG_INFO_F(Elements::Tensor, "Process boundary tensor, tensor magic : %d, info: %s, mem: %s",289 APASS_LOG_INFO_F(Elements::Tensor, "Process boundary tensor, tensor magic : %d, info: %s, mem: %s",
245 tensor->GetMagic(), tensor->Dump().c_str(),290 tensor->GetMagic(), tensor->Dump().c_str(),
246 BriefMemoryTypeToString(tensor->GetMemoryTypeOriginal()).c_str());291 BriefMemoryTypeToString(tensor->GetMemoryTypeOriginal()).c_str());
247- // Insert OP_ASSEMBLE before the boundary tensor, if the producer is not OP_ASSEMBLE/OP_COPY_OUT292+ // Adapt the producer so that it can write the boundary tensor to DDR.
248 if (AdapteTensorProducers(function, tensor) == FAILED) {293 if (AdapteTensorProducers(function, tensor) == FAILED) {
249 APASS_LOG_ERROR_F(294 APASS_LOG_ERROR_F(
250 Elements::Tensor,295 Elements::Tensor,
@@ -252,7 +297,7 @@ Status IntraSubgraphAdapter::ProcessBoundaryTensor(Function& function, LogicalTe
252 tensor->GetMagic());297 tensor->GetMagic());
253 return FAILED;298 return FAILED;
254 }299 }
255- // Insert OP_VIEW after the boundary tensor, if the consumer is not OP_VIEW/OP_COPY_IN300+ // Adapt the consumer so that it can read the boundary tensor from DDR.
256 if (AdapteTensorConsumers(function, tensor) == FAILED) {301 if (AdapteTensorConsumers(function, tensor) == FAILED) {
257 APASS_LOG_ERROR_F(302 APASS_LOG_ERROR_F(
258 Elements::Tensor,303 Elements::Tensor,
@@ -296,10 +341,11 @@ bool IntraSubgraphAdapter::IsCrossCoreMoveOps(Operation* op)
296Status IntraSubgraphAdapter::AdapteTensorProducers(Function& function, LogicalTensorPtr tensor)341Status IntraSubgraphAdapter::AdapteTensorProducers(Function& function, LogicalTensorPtr tensor)
297{342{
298 if (tensor->GetProducers().size() > 1) {343 if (tensor->GetProducers().size() > 1) {
299- for (const Operation* producer : tensor->GetProducers()) {344+ auto producers = tensor->GetProducers();
345+ for (Operation* producer : producers) {
300 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Producer %s[%d].", producer->GetOpcodeStr().c_str(),346 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Producer %s[%d].", producer->GetOpcodeStr().c_str(),
301 producer->GetOpMagic());347 producer->GetOpMagic());
302- if (producer->GetOpcode() == Opcode::OP_ASSEMBLE) {348+ if (producer->GetOpcode() == config::GetContractOpcode()) {
303 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Op Attr: %s", producer->Dump().c_str());349 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Op Attr: %s", producer->Dump().c_str());
304 }350 }
305 if (OpcodeManager::Inst().GetOpCalcType(producer->GetOpcode()) != OpCalcType::MOVE_OUT &&351 if (OpcodeManager::Inst().GetOpCalcType(producer->GetOpcode()) != OpCalcType::MOVE_OUT &&
@@ -307,10 +353,13 @@ Status IntraSubgraphAdapter::AdapteTensorProducers(Function& function, LogicalTe
307 APASS_LOG_ERROR_F(353 APASS_LOG_ERROR_F(
308 Elements::Operation,354 Elements::Operation,
309 "OpCalcType error; If the tensor has multiple producers, then the producers can only be "355 "OpCalcType error; If the tensor has multiple producers, then the producers can only be "
310- "OP_ASSEMBLE/OP_COPY_OUT.%s",356+ "assemble-family/OP_COPY_OUT.%s",
311 GetFormatBacktrace(*producer).c_str());357 GetFormatBacktrace(*producer).c_str());
312 return FAILED;358 return FAILED;
313 }359 }
360+ if (IsAssembleWithDifferentMemoryType(*producer, MemoryType::MEM_DEVICE_DDR)) {
361+ SetConfiguredOpcode(*producer, config::GetContractOpcode());
362+ }
314 }363 }
315 return SUCCESS;364 return SUCCESS;
316 }365 }
@@ -318,7 +367,7 @@ Status IntraSubgraphAdapter::AdapteTensorProducers(Function& function, LogicalTe
318 Operation* producer = *(tensor->GetProducers().begin());367 Operation* producer = *(tensor->GetProducers().begin());
319 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Producer %s[%d].", producer->GetOpcodeStr().c_str(),368 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Producer %s[%d].", producer->GetOpcodeStr().c_str(),
320 producer->GetOpMagic());369 producer->GetOpMagic());
321- if (producer->GetOpcode() == Opcode::OP_ASSEMBLE) {370+ if (producer->GetOpcode() == config::GetContractOpcode()) {
322 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Op Attr: %s", producer->Dump().c_str());371 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Op Attr: %s", producer->Dump().c_str());
323 }372 }
324 if (IsCrossCoreMoveOps(producer)) {373 if (IsCrossCoreMoveOps(producer)) {
@@ -334,8 +383,11 @@ Status IntraSubgraphAdapter::AdapteTensorProducers(Function& function, LogicalTe
334 APASS_LOG_DEBUG_F(Elements::Operation, "change %s[%d] opcode to OP_COPY_OUT.",383 APASS_LOG_DEBUG_F(Elements::Operation, "change %s[%d] opcode to OP_COPY_OUT.",
335 producer->GetOpcodeStr().c_str(), producer->GetOpMagic());384 producer->GetOpcodeStr().c_str(), producer->GetOpMagic());
336 }385 }
337- if (producer->GetOpcode() != Opcode::OP_ASSEMBLE && producer->GetOpcode() != Opcode::OP_COPY_OUT) {386+ if (IsAssembleWithDifferentMemoryType(*producer, MemoryType::MEM_DEVICE_DDR)) {
338- InsertOpBetween(function, Opcode::OP_ASSEMBLE, *producer, tensor);387+ SetConfiguredOpcode(*producer, config::GetContractOpcode());
388+ }
389+ if (producer->GetOpcode() != config::GetContractOpcode() && producer->GetOpcode() != Opcode::OP_COPY_OUT) {
390+ InsertOpBetween(function, config::GetContractOpcode(), *producer, tensor);
339 }391 }
340 return SUCCESS;392 return SUCCESS;
341 }393 }
@@ -345,7 +397,7 @@ Status IntraSubgraphAdapter::AdapteTensorProducers(Function& function, LogicalTe
345 397 
346static bool IsIndirectView(Operation* op)398static bool IsIndirectView(Operation* op)
347{399{
348- if (op->GetOpcode() != Opcode::OP_VIEW) {400+ if (op->GetOpcode() != config::GetSliceOpcode()) {
349 return false;401 return false;
350 }402 }
351 if (op->GetOOperands().size() == 0) {403 if (op->GetOOperands().size() == 0) {
@@ -368,7 +420,7 @@ Status IntraSubgraphAdapter::AdapteTensorConsumers(Function& function, LogicalTe
368 for (const auto& consumer : tensor->GetConsumers()) {420 for (const auto& consumer : tensor->GetConsumers()) {
369 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Consumer %s[%d].", consumer->GetOpcodeStr().c_str(),421 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Consumer %s[%d].", consumer->GetOpcodeStr().c_str(),
370 consumer->GetOpMagic());422 consumer->GetOpMagic());
371- if (consumer->GetOpcode() == Opcode::OP_VIEW) {423+ if (consumer->GetOpcode() == config::GetSliceOpcode()) {
372 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Op Attr: %s", consumer->Dump().c_str());424 APASS_LOG_DEBUG_F(Elements::Operation, "|---- Op Attr: %s", consumer->Dump().c_str());
373 }425 }
374 if (IsCrossCoreMoveOps(consumer)) {426 if (IsCrossCoreMoveOps(consumer)) {
@@ -377,26 +429,30 @@ Status IntraSubgraphAdapter::AdapteTensorConsumers(Function& function, LogicalTe
377 consumer->GetOpcodeStr().c_str(), consumer->GetOpMagic());429 consumer->GetOpcodeStr().c_str(), consumer->GetOpMagic());
378 return FAILED;430 return FAILED;
379 }431 }
380- if ((consumer->GetOpcode() != Opcode::OP_VIEW && consumer->GetOpcode() != Opcode::OP_COPY_IN) ||432+ if (IsViewWithDifferentMemoryType(*consumer, MemoryType::MEM_DEVICE_DDR)) {
433+ SetConfiguredOpcode(*consumer, config::GetSliceOpcode());
434+ continue;
435+ }
436+ if ((consumer->GetOpcode() != config::GetSliceOpcode() && consumer->GetOpcode() != Opcode::OP_COPY_IN) ||
381 IsIndirectView(consumer)) {437 IsIndirectView(consumer)) {
382 consumerColor2OpsMap[consumer->GetSubgraphID()].push_back(consumer);438 consumerColor2OpsMap[consumer->GetSubgraphID()].push_back(consumer);
383 }439 }
384 }440 }
385 for (auto& [color, consumers] : consumerColor2OpsMap) {441 for (auto& [color, consumers] : consumerColor2OpsMap) {
386 (void)color;442 (void)color;
387- InsertOpBetween(function, Opcode::OP_VIEW, tensor, consumers);443+ InsertOpBetween(function, config::GetSliceOpcode(), tensor, consumers);
388 }444 }
389 return SUCCESS;445 return SUCCESS;
390}446}
391 447 
392-// For Assemble448+// For Contract
393LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcode opcode, Operation& op,449LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcode opcode, Operation& op,
394 LogicalTensorPtr tensor)450 LogicalTensorPtr tensor)
395{451{
396 APASS_LOG_DEBUG_F(Elements::Operation, "intraSubgraphAdapter::InsertOpBetween %s 1.",452 APASS_LOG_DEBUG_F(Elements::Operation, "intraSubgraphAdapter::InsertOpBetween %s 1.",
397 OpcodeManager::Inst().GetOpcodeStr(opcode).c_str());453 OpcodeManager::Inst().GetOpcodeStr(opcode).c_str());
398- ASSERT(opcode == Opcode::OP_ASSEMBLE) << "[IntraSubgraphAdapter][Operation][ERROR]: Opcode for "454+ ASSERT(opcode == config::GetContractOpcode()) << "[IntraSubgraphAdapter][Operation][ERROR]: Opcode for "
399- "IntraSubgraphAdapter::InsertOpBetween must be OP_ASSEMBLE.";455+ "IntraSubgraphAdapter::InsertOpBetween is invalid.";
400 auto newRawTensor = std::make_shared<RawTensor>(tensor->Datatype(), tensor->GetRawTensor()->rawshape,456 auto newRawTensor = std::make_shared<RawTensor>(tensor->Datatype(), tensor->GetRawTensor()->rawshape,
401 tensor->Format());457 tensor->Format());
402 LogicalTensorPtr newTensor = irBuilder_.CreateTensorVar(newRawTensor, tensor->GetOffset(), tensor->GetShape(),458 LogicalTensorPtr newTensor = irBuilder_.CreateTensorVar(newRawTensor, tensor->GetOffset(), tensor->GetShape(),
@@ -423,7 +479,7 @@ LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcod
423 return newTensor;479 return newTensor;
424}480}
425 481 
426-// For View482+// For Slice
427LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcode opcode, LogicalTensorPtr tensor,483LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcode opcode, LogicalTensorPtr tensor,
428 const std::vector<Operation*>& ops, int newOpSubgraphID)484 const std::vector<Operation*>& ops, int newOpSubgraphID)
429{485{
@@ -438,9 +494,9 @@ LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcod
438 "Insert op between tensor and ops failed; The ops to be inserted can't be empty.");494 "Insert op between tensor and ops failed; The ops to be inserted can't be empty.");
439 return nullptr;495 return nullptr;
440 }496 }
441- ASSERT(opcode == Opcode::OP_VIEW || opcode == Opcode::OP_ASSEMBLE)497+ ASSERT(opcode == config::GetSliceOpcode() || opcode == config::GetContractOpcode())
442- << "[IntraSubgraphAdapter][Operation][ERROR]: Opcode for IntraSubgraphAdapter::InsertOpBetween must be OP_VIEW "498+ << "[IntraSubgraphAdapter][Operation][ERROR]: Opcode for IntraSubgraphAdapter::InsertOpBetween must be "
443- "or OP_ASSEMBLE.";499+ "current view-family or assemble-family opcode.";
444 auto newRawTensor = std::make_shared<RawTensor>(tensor->Datatype(), tensor->GetRawTensor()->rawshape,500 auto newRawTensor = std::make_shared<RawTensor>(tensor->Datatype(), tensor->GetRawTensor()->rawshape,
445 tensor->Format());501 tensor->Format());
446 LogicalTensorPtr newTensor = irBuilder_.CreateTensorVar(newRawTensor, tensor->GetOffset(), tensor->GetShape(),502 LogicalTensorPtr newTensor = irBuilder_.CreateTensorVar(newRawTensor, tensor->GetOffset(), tensor->GetShape(),
@@ -458,13 +514,14 @@ LogicalTensorPtr IntraSubgraphAdapter::InsertOpBetween(Function& function, Opcod
458 std::vector<int64_t> offset(tensor->GetShape().size(), 0);514 std::vector<int64_t> offset(tensor->GetShape().size(), 0);
459 Operation* newOp = &irBuilder_.CreateTensorOpStmt(function, opcode, {tensor}, {newTensor});515 Operation* newOp = &irBuilder_.CreateTensorOpStmt(function, opcode, {tensor}, {newTensor});
460 newOps.push_back(newOp);516 newOps.push_back(newOp);
461- if (opcode == Opcode::OP_ASSEMBLE) {517+ if (opcode == config::GetContractOpcode()) {
462 newOp->SetOpAttribute(std::make_shared<AssembleOpAttribute>(518 newOp->SetOpAttribute(std::make_shared<AssembleOpAttribute>(
463 newTensor->GetMemoryTypeOriginal(), offset, tensor->GetDynOffset(), tensor->GetDynValidShape()));519 newTensor->GetMemoryTypeOriginal(), offset, tensor->GetDynOffset(), tensor->GetDynValidShape()));
464 if (!tensor->GetProducers().empty()) {520 if (!tensor->GetProducers().empty()) {
465 newOp->SetScopeInfo((*tensor->GetProducers().begin())->GetScopeInfo());521 newOp->SetScopeInfo((*tensor->GetProducers().begin())->GetScopeInfo());
466 }522 }
467- } else {523+ }
524+ if (opcode == config::GetSliceOpcode()) {
468 newOp->SetOpAttribute(std::make_shared<ViewOpAttribute>(offset, newTensor->GetMemoryTypeToBe(),525 newOp->SetOpAttribute(std::make_shared<ViewOpAttribute>(offset, newTensor->GetMemoryTypeToBe(),
469 tensor->GetDynOffset(), tensor->GetDynValidShape()));526 tensor->GetDynOffset(), tensor->GetDynValidShape()));
470 newOp->SetScopeInfo(ops[0]->GetScopeInfo());527 newOp->SetScopeInfo(ops[0]->GetScopeInfo());
@@ -46,7 +46,8 @@ MemoryType MemoryPathUtils::ResolveEffectiveConsumerRequirement(
46 return directRequirement;46 return directRequirement;
47 }47 }
48 auto opcode = consumerOp->GetOpcode();48 auto opcode = consumerOp->GetOpcode();
49- if (opcode != Opcode::OP_VIEW && opcode != Opcode::OP_ASSEMBLE) {49+ if (opcode != Opcode::OP_VIEW && opcode != Opcode::OP_SLICE && opcode != Opcode::OP_ASSEMBLE &&
50+ opcode != Opcode::OP_CONTRACT) {
50 return directRequirement;51 return directRequirement;
51 }52 }
52 std::set<MemoryType> branchRequirements;53 std::set<MemoryType> branchRequirements;
@@ -55,13 +56,13 @@ MemoryType MemoryPathUtils::ResolveEffectiveConsumerRequirement(
55 branchRequirements.insert(requirement);56 branchRequirements.insert(requirement);
56 }57 }
57 };58 };
58- if (opcode == Opcode::OP_VIEW) {59+ if (opcode == Opcode::OP_VIEW || opcode == Opcode::OP_SLICE) {
59 auto viewOpAttribute = std::dynamic_pointer_cast<ViewOpAttribute>(consumerOp->GetOpAttribute());60 auto viewOpAttribute = std::dynamic_pointer_cast<ViewOpAttribute>(consumerOp->GetOpAttribute());
60 if (viewOpAttribute != nullptr) {61 if (viewOpAttribute != nullptr) {
61 addRequirement(viewOpAttribute->GetTo());62 addRequirement(viewOpAttribute->GetTo());
62 }63 }
63 }64 }
64- if (opcode == Opcode::OP_ASSEMBLE) {65+ if (opcode == Opcode::OP_ASSEMBLE || opcode == Opcode::OP_CONTRACT) {
65 auto assembleOpAttribute = std::dynamic_pointer_cast<AssembleOpAttribute>(consumerOp->GetOpAttribute());66 auto assembleOpAttribute = std::dynamic_pointer_cast<AssembleOpAttribute>(consumerOp->GetOpAttribute());
66 if (assembleOpAttribute != nullptr) {67 if (assembleOpAttribute != nullptr) {
67 MemoryType fromType = assembleOpAttribute->GetFrom();68 MemoryType fromType = assembleOpAttribute->GetFrom();
@@ -34,10 +34,10 @@ public:
34 34 
35 static bool ShouldUseDdrForSpecialPath(bool hasParallelDifferentRequirement, MemoryType from, MemoryType to);35 static bool ShouldUseDdrForSpecialPath(bool hasParallelDifferentRequirement, MemoryType from, MemoryType to);
36 36 
37- // 在判断直接搬运路径冲突前,解析 OP_VIEW/OP_ASSEMBLE 背后的有效消费者需求。37+ // 在判断直接搬运路径冲突前,解析 view/assemble 语义 op 背后的有效消费者需求。
38- // OP_VIEW: 通过 ViewOpAttribute.GetTo() 获取目的地类型。38+ // OP_VIEW/OP_SLICE: 通过 ViewOpAttribute.GetTo() 获取目的地类型。
39- // OP_ASSEMBLE: 若处于特殊直连路径且 output 有下游消费者,推断 targetType;39+ // OP_ASSEMBLE/OP_CONTRACT: 若处于特殊直连路径且 output 有下游消费者,推断 targetType;
40- // 无下游消费者(如 outcast)则保留 output MemoryTypeOriginal。40+ // 无下游消费者(如 outcast)则保留 output MemoryTypeOriginal。
41 // resolver 的语义与阶段相关:AssignMemoryType 阶段可递归穿透 view 消费者,41 // resolver 的语义与阶段相关:AssignMemoryType 阶段可递归穿透 view 消费者,
42 // ConvertInserter 阶段应基于 tensorTobeMap 中已经规划好的直接需求判断。42 // ConvertInserter 阶段应基于 tensorTobeMap 中已经规划好的直接需求判断。
43 static MemoryType ResolveEffectiveConsumerRequirement(Operation* consumerOp, MemoryType directRequirement,43 static MemoryType ResolveEffectiveConsumerRequirement(Operation* consumerOp, MemoryType directRequirement,
@@ -611,6 +611,16 @@ static Status ProcessVisitedViewOps(Function& function, const std::unordered_map
611 auto oOperand = op->GetOutputOperand(0);611 auto oOperand = op->GetOutputOperand(0);
612 if (iOperand == srcTensor)612 if (iOperand == srcTensor)
613 continue; // 开头的VIEW不需要插入NOP来控制顺序613 continue; // 开头的VIEW不需要插入NOP来控制顺序
614+ bool hasNonInplaceConsumer = false;
615+ for (auto consumer : oOperand->GetConsumers()) {
616+ if (consumer->GetOpcode() != Opcode::OP_NOP && !consumer->HasAttribute(OpAttributeKey::inplaceIdx)) {
617+ hasNonInplaceConsumer = true;
618+ break;
619+ }
620+ }
621+ if (hasNonInplaceConsumer) {
622+ continue;
623+ }
614 if (iOperand->GetRawTensor() != srcTensor->GetRawTensor()) {624 if (iOperand->GetRawTensor() != srcTensor->GetRawTensor()) {
615 APASS_LOG_ERROR_F(Elements::Operation, "RawTensor mismatch for input operand of operation %d",625 APASS_LOG_ERROR_F(Elements::Operation, "RawTensor mismatch for input operand of operation %d",
616 op->GetOpMagic());626 op->GetOpMagic());
@@ -195,6 +195,11 @@ Status PreGraphProcess::RunOnFunction(Function& function)
195 setBoundary.SetTensorBoundary(function);195 setBoundary.SetTensorBoundary(function);
196 // Processing Special Ops196 // Processing Special Ops
197 SetCopyAttr setCopyAttr;197 SetCopyAttr setCopyAttr;
198+ RemoveRedundantAssemble removeRedundantAssemble;
199+ if (removeRedundantAssemble.ProcessViewToCopyIn(function) != SUCCESS) {
200+ APASS_LOG_ERROR_F(Elements::Function, "ProcessViewToCopyIn failed.");
201+ return FAILED;
202+ }
198 for (auto& op : opList) {203 for (auto& op : opList) {
199 bool* distCopyType = op.GetAttr<bool>(OpAttributeKey::isDistCopyOut);204 bool* distCopyType = op.GetAttr<bool>(OpAttributeKey::isDistCopyOut);
200 if (IsCopyOut(op.GetOpcode()) && (op.GetOpAttribute() == nullptr) &&205 if (IsCopyOut(op.GetOpcode()) && (op.GetOpAttribute() == nullptr) &&
@@ -206,8 +211,10 @@ Status PreGraphProcess::RunOnFunction(Function& function)
206 setCopyAttr.ProcessMoveInOperation(op);211 setCopyAttr.ProcessMoveInOperation(op);
207 }212 }
208 }213 }
209- RemoveRedundantAssemble removeRedundantAssemble;214+ if (removeRedundantAssemble.DeleteRedundantAssemble(function) != SUCCESS) {
210- removeRedundantAssemble.DeleteRedundantAssemble(function);215+ APASS_LOG_ERROR_F(Elements::Function, "DeleteRedundantAssemble failed.");
216+ return FAILED;
217+ }
211 CubeProcess cubeProcess;218 CubeProcess cubeProcess;
212 if (cubeProcess.UpdateCubeOp(function) != SUCCESS) {219 if (cubeProcess.UpdateCubeOp(function) != SUCCESS) {
213 APASS_LOG_ERROR_F(Elements::Function, "Update Cube attr failed.");220 APASS_LOG_ERROR_F(Elements::Function, "Update Cube attr failed.");
@@ -19,12 +19,17 @@
19#include "passes/pass_utils/pass_utils.h"19#include "passes/pass_utils/pass_utils.h"
20#include "passes/pass_utils/subgraph_utils.h"20#include "passes/pass_utils/subgraph_utils.h"
21#include "passes/pass_utils/graph_utils.h"21#include "passes/pass_utils/graph_utils.h"
22+#include "passes/pass_utils/remove_redundant_op_utils.h"
23+#include "interface/configs/config_manager.h"
22 24 
23#include <sstream>25#include <sstream>
24 26 
25#define MODULE_NAME "PreGraphProcess"27#define MODULE_NAME "PreGraphProcess"
26 28 
27namespace npu::tile_fwk {29namespace npu::tile_fwk {
30+namespace {
31+constexpr const char* KEY_ENABLE_TRUE = "enable_true";
32+}
28 33 
29std::string OpImmediateVecToStr(const std::vector<OpImmediate>& values)34std::string OpImmediateVecToStr(const std::vector<OpImmediate>& values)
30{35{
@@ -49,6 +54,94 @@ std::vector<OpImmediate> SumOffset(const std::vector<OpImmediate> offset1, const
49 return res;54 return res;
50}55}
51 56 
57+bool GetViewOffset(const ViewOpAttribute& viewAttr, std::vector<OpImmediate>& viewOffset)
58+{
59+ if (!viewAttr.GetFromDynOffset().empty()) {
60+ viewOffset = OpImmediate::Specified(viewAttr.GetFromDynOffset());
61+ } else {
62+ viewOffset = OpImmediate::Specified(viewAttr.GetFromOffset());
63+ }
64+ return !viewOffset.empty();
65+}
66+ 
67+bool CanMergeViewToCopyIn(const Operation& viewOp, std::vector<Operation*>& copyIns,
68+ std::vector<std::vector<OpImmediate>>& mergedOffsets)
69+{
70+ if (viewOp.GetIOperands().size() != 1 || viewOp.GetOOperands().size() != 1) {
71+ return false;
72+ }
73+ const auto& viewInput = viewOp.GetIOperands().front();
74+ const auto& viewOutput = viewOp.GetOOperands().front();
75+ if (viewInput == nullptr || viewOutput == nullptr || viewInput->GetRawTensor() == nullptr ||
76+ viewInput->GetMemoryTypeOriginal() != MemoryType::MEM_DEVICE_DDR ||
77+ viewInput->GetShape().size() != viewOutput->GetShape().size() || viewOutput->GetConsumers().empty()) {
78+ return false;
79+ }
80+ auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(viewOp.GetOpAttribute());
81+ std::vector<OpImmediate> viewOffset;
82+ if (viewAttr == nullptr || !GetViewOffset(*viewAttr, viewOffset) ||
83+ viewOffset.size() != viewInput->GetShape().size()) {
84+ return false;
85+ }
86+ for (auto* consumer : viewOutput->GetConsumers()) {
87+ if (consumer == nullptr || consumer->GetOpcode() != Opcode::OP_COPY_IN ||
88+ consumer->GetIOperands().size() != 1 || consumer->GetOOperands().size() != 1) {
89+ return false;
90+ }
91+ auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(consumer->GetOpAttribute());
92+ if (copyAttr == nullptr) {
93+ mergedOffsets.push_back(viewOffset);
94+ } else {
95+ const auto& copyOffset = copyAttr->GetFromOffset();
96+ if (copyAttr->IsCopyOut() || copyOffset.size() != viewOffset.size() ||
97+ (!copyAttr->GetRawShape().empty() && copyAttr->GetRawShape().size() != viewOffset.size())) {
98+ return false;
99+ }
100+ mergedOffsets.push_back(SumOffset(viewOffset, copyOffset));
101+ }
102+ copyIns.push_back(consumer);
103+ }
104+ return true;
105+}
106+ 
107+Status RemoveRedundantAssemble::ProcessViewToCopyIn(Function& function) const
108+{
109+ for (auto& op : function.Operations()) {
110+ if (op.GetOpcode() != Opcode::OP_VIEW || op.IsDeleted()) {
111+ continue;
112+ }
113+ std::vector<Operation*> copyIns;
114+ std::vector<std::vector<OpImmediate>> mergedOffsets;
115+ if (!CanMergeViewToCopyIn(op, copyIns, mergedOffsets)) {
116+ continue;
117+ }
118+ auto viewInput = op.GetIOperands().front();
119+ for (size_t idx = 0; idx < copyIns.size(); ++idx) {
120+ auto& copyIn = *copyIns[idx];
121+ auto copyOutput = copyIn.GetOOperands().front();
122+ auto copyShape = OpImmediate::Specified(copyOutput->GetShape());
123+ auto rawShape = OpImmediate::Specified(viewInput->tensor->GetDynRawShape());
124+ auto toDynValidShape = OpImmediate::Specified(copyOutput->GetDynValidShape());
125+ auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(copyIn.GetOpAttribute());
126+ if (copyAttr == nullptr) {
127+ copyAttr = std::make_shared<CopyOpAttribute>(mergedOffsets[idx], copyOutput->GetMemoryTypeOriginal(),
128+ copyShape, rawShape, toDynValidShape);
129+ copyIn.SetOpAttribute(copyAttr);
130+ } else {
131+ copyAttr->SetFromOffset(mergedOffsets[idx]);
132+ copyAttr->SetShape(copyShape);
133+ copyAttr->SetRawShape(rawShape);
134+ copyAttr->SetToDynValidShape(toDynValidShape);
135+ }
136+ copyIn.ReplaceIOperand(0, viewInput);
137+ }
138+ APASS_LOG_DEBUG_F(Elements::Operation, "Remove View op:%s[%d] before CopyIn.", op.GetOpcodeStr().c_str(),
139+ op.GetOpMagic());
140+ op.SetAsDeleted();
141+ }
142+ return SUCCESS;
143+}
144+ 
52// 当前op为Copy Out时,需要将后继Assemble上的offset累加到当前op的CopyOpAttr上145// 当前op为Copy Out时,需要将后继Assemble上的offset累加到当前op的CopyOpAttr上
53void UpdateCopyOutAttr(Operation& op, Operation& opNext)146void UpdateCopyOutAttr(Operation& op, Operation& opNext)
54{147{
@@ -950,6 +1043,20 @@ Status RemoveRedundantAssemble::HanldeForSingleAssemble(Function& function, Logi
950*/1043*/
951Status RemoveRedundantAssemble::DeleteRedundantAssemble(Function& function) const1044Status RemoveRedundantAssemble::DeleteRedundantAssemble(Function& function) const
952{1045{
1046+ bool operationUpdated = false;
1047+ if (config::GetPassGlobalConfig(KEY_ENABLE_TRUE, false)) {
1048+ if (RemoveRedundantOpUtils::ProcessViewCopyout(function, operationUpdated) != SUCCESS) {
1049+ APASS_LOG_ERROR_F(Elements::Function, "ProcessViewCopyout failed.");
1050+ return FAILED;
1051+ }
1052+ if (RemoveRedundantOpUtils::ProcessCopyinAssemble(function, operationUpdated) != SUCCESS) {
1053+ APASS_LOG_ERROR_F(Elements::Function, "ProcessCopyinAssemble failed.");
1054+ return FAILED;
1055+ }
1056+ if (operationUpdated) {
1057+ function.EraseOperations(true, false);
1058+ }
1059+ }
953 for (auto& op : function.Operations()) {1060 for (auto& op : function.Operations()) {
954 if (!IsCandidateAssembleOp(function, op)) {1061 if (!IsCandidateAssembleOp(function, op)) {
955 continue;1062 continue;
@@ -33,6 +33,7 @@ public:
33 void HanldeForMultiAssemble(Function& function, std::unordered_set<Operation*>& concurrentAssembles) const;33 void HanldeForMultiAssemble(Function& function, std::unordered_set<Operation*>& concurrentAssembles) const;
34 Status HanldeForSingleAssemble(Function& function, LogicalTensorPtr input, LogicalTensorPtr output,34 Status HanldeForSingleAssemble(Function& function, LogicalTensorPtr input, LogicalTensorPtr output,
35 Operation& op) const;35 Operation& op) const;
36+ Status ProcessViewToCopyIn(Function& function) const;
36 Status ProcessView(Function& function) const;37 Status ProcessView(Function& function) const;
37 38 
38private:39private:
@@ -761,6 +761,16 @@ Status ReplaceTensor::RefactorViewConnectForReplace(Function& function)
761 if (iOperand == srcTensor) { // 开头的VIEW不需要插入NOP来控制顺序761 if (iOperand == srcTensor) { // 开头的VIEW不需要插入NOP来控制顺序
762 continue;762 continue;
763 }763 }
764+ bool hasNonInplaceConsumer = false;
765+ for (auto consumer : oOperand->GetConsumers()) {
766+ if (consumer->GetOpcode() != Opcode::OP_NOP && !consumer->HasAttribute(OpAttributeKey::inplaceIdx)) {
767+ hasNonInplaceConsumer = true;
768+ break;
769+ }
770+ }
771+ if (hasNonInplaceConsumer) {
772+ continue;
773+ }
764 ASSERT(TensorErr::TENSOR_SHAPE_MISMATCH, iOperand->GetRawTensor() == srcTensor->GetRawTensor());774 ASSERT(TensorErr::TENSOR_SHAPE_MISMATCH, iOperand->GetRawTensor() == srcTensor->GetRawTensor());
765 ASSERT(TensorErr::TENSOR_SHAPE_MISMATCH, oOperand->GetRawTensor() == srcTensor->GetRawTensor());775 ASSERT(TensorErr::TENSOR_SHAPE_MISMATCH, oOperand->GetRawTensor() == srcTensor->GetRawTensor());
766 op->ReplaceIOperand(0, srcTensor);776 op->ReplaceIOperand(0, srcTensor);
@@ -25,6 +25,10 @@
25#define MODULE_NAME "DuplicateOp"25#define MODULE_NAME "DuplicateOp"
26 26 
27namespace npu::tile_fwk {27namespace npu::tile_fwk {
28+namespace {
29+bool IsViewLikeOpcode(Opcode opcode) { return opcode == Opcode::OP_VIEW || opcode == Opcode::OP_SLICE; }
30+} // namespace
31+ 
28Status DuplicateOp::PreCheck(Function& function)32Status DuplicateOp::PreCheck(Function& function)
29{33{
30 DuplicateOpChecker checker;34 DuplicateOpChecker checker;
@@ -110,7 +114,7 @@ Status DuplicateOp::ProcessGatherIn(Function& function, Operation& operation, st
110 return SUCCESS;114 return SUCCESS;
111}115}
112 116 
113-Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::vector<Operation*>& newOps) const117+Status DuplicateOp::ProcessViewLike(Function& function, Operation& operation, std::vector<Operation*>& newOps) const
114{118{
115 auto viewAttr = dynamic_cast<ViewOpAttribute*>(operation.GetOpAttribute().get());119 auto viewAttr = dynamic_cast<ViewOpAttribute*>(operation.GetOpAttribute().get());
116 if (viewAttr != nullptr &&120 if (viewAttr != nullptr &&
@@ -138,7 +142,7 @@ Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::v
138 oOperand->magic);142 oOperand->magic);
139 return FAILED;143 return FAILED;
140 }144 }
141- if (consumer->GetOpcode() == Opcode::OP_VIEW) {145+ if (IsViewLikeOpcode(consumer->GetOpcode())) {
142 continue;146 continue;
143 }147 }
144 auto dst = oOperand->Clone(function, true);148 auto dst = oOperand->Clone(function, true);
@@ -148,15 +152,11 @@ Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::v
148 }152 }
149 consumer->ReplaceInput(dst, oOperand);153 consumer->ReplaceInput(dst, oOperand);
150 IRBuilder builder;154 IRBuilder builder;
151- auto& newOp = builder.CreateTensorOpStmt(function, Opcode::OP_VIEW, {iOperand}, {dst}, operation.GetSpan());155+ auto& newOp = builder.CreateTensorOpStmt(function, operation.GetOpcode(), {iOperand}, {dst},
156+ operation.GetSpan());
152 newOp.SetScopeInfo(operation.GetScopeInfo());157 newOp.SetScopeInfo(operation.GetScopeInfo());
153- auto oriViewAttr = dynamic_cast<ViewOpAttribute*>(operation.GetOpAttribute().get());158+ if (operation.GetOpAttribute() != nullptr) {
154- if (oriViewAttr != nullptr) {159+ newOp.SetOpAttribute(operation.GetOpAttribute()->Clone());
155- auto newOffset = oriViewAttr->GetFromOffset();
156- auto newDynOffset = oriViewAttr->GetFromDynOffset();
157- auto newDynValidShape = oriViewAttr->GetToDynValidShape();
158- auto newViewAttr = std::make_shared<ViewOpAttribute>(newOffset, newDynOffset, newDynValidShape);
159- newOp.SetOpAttribute(newViewAttr);
160 }160 }
161 newOps.push_back(&newOp);161 newOps.push_back(&newOp);
162 }162 }
@@ -167,7 +167,7 @@ Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::v
167Status DuplicateOp::ProcessOp(Function& function, Operation& operation, std::vector<Operation*>& newOps) const167Status DuplicateOp::ProcessOp(Function& function, Operation& operation, std::vector<Operation*>& newOps) const
168{168{
169 auto opcode = operation.GetOpcode();169 auto opcode = operation.GetOpcode();
170- if (opcode != Opcode::OP_GATHER_IN_L1 && opcode != Opcode::OP_VIEW) {170+ if (opcode != Opcode::OP_GATHER_IN_L1 && !IsViewLikeOpcode(opcode)) {
171 return SUCCESS;171 return SUCCESS;
172 }172 }
173 if (opcode == Opcode::OP_GATHER_IN_L1) {173 if (opcode == Opcode::OP_GATHER_IN_L1) {
@@ -176,9 +176,9 @@ Status DuplicateOp::ProcessOp(Function& function, Operation& operation, std::vec
176 return FAILED;176 return FAILED;
177 }177 }
178 }178 }
179- if (opcode == Opcode::OP_VIEW) {179+ if (IsViewLikeOpcode(opcode)) {
180- if (ProcessView(function, operation, newOps) != SUCCESS) {180+ if (ProcessViewLike(function, operation, newOps) != SUCCESS) {
181- APASS_LOG_ERROR_F(Elements::Operation, "ProcessView failed.%s", GetFormatBacktrace(operation).c_str());181+ APASS_LOG_ERROR_F(Elements::Operation, "ProcessViewLike failed.%s", GetFormatBacktrace(operation).c_str());
182 return FAILED;182 return FAILED;
183 }183 }
184 }184 }
@@ -38,7 +38,7 @@ private:
38 void PushProducers(const LogicalTensors& operands, std::stack<Operation*>& stack,38 void PushProducers(const LogicalTensors& operands, std::stack<Operation*>& stack,
39 std::unordered_set<int>& visitedOps, std::unordered_set<int>& visitedTensors) const;39 std::unordered_set<int>& visitedOps, std::unordered_set<int>& visitedTensors) const;
40 Status ProcessGatherIn(Function& function, Operation& operation, std::vector<Operation*>& newOps) const;40 Status ProcessGatherIn(Function& function, Operation& operation, std::vector<Operation*>& newOps) const;
41- Status ProcessView(Function& function, Operation& operation, std::vector<Operation*>& newOps) const;41+ Status ProcessViewLike(Function& function, Operation& operation, std::vector<Operation*>& newOps) const;
42};42};
43 43 
44} // namespace npu::tile_fwk44} // namespace npu::tile_fwk
@@ -13,6 +13,7 @@
13 * \brief13 * \brief
14 */14 */
15#include "insert_op_for_viewassemble.h"15#include "insert_op_for_viewassemble.h"
16+#include "interface/configs/config_manager_ng.h"
16#include "interface/tensor/irbuilder.h"17#include "interface/tensor/irbuilder.h"
17#include "passes/pass_log/pass_log.h"18#include "passes/pass_log/pass_log.h"
18 19 
@@ -34,11 +35,12 @@ void InsertOpForViewAssemble::InsertViewAssemble(Function& function, Operation*
34 moveInTensorPtr->UpdateDynValidShape(moveOutTensorPtr->GetDynValidShape());35 moveInTensorPtr->UpdateDynValidShape(moveOutTensorPtr->GetDynValidShape());
35 std::vector<int64_t> offset(moveOutTensorPtr->GetShape().size(), 0);36 std::vector<int64_t> offset(moveOutTensorPtr->GetShape().size(), 0);
36 std::vector<SymbolicScalar> dynOffset(moveOutTensorPtr->GetShape().size(), 0);37 std::vector<SymbolicScalar> dynOffset(moveOutTensorPtr->GetShape().size(), 0);
37- Operation& assemble = irBuilder_.CreateTensorOpStmt(function, Opcode::OP_ASSEMBLE, {moveOutTensorPtr},38+ Operation& assemble = irBuilder_.CreateTensorOpStmt(function, config::GetContractOpcode(), {moveOutTensorPtr},
38 {ddrTensorPtr});39 {ddrTensorPtr});
39 assemble.SetOpAttribute(std::make_shared<AssembleOpAttribute>(moveOutTensorPtr->GetMemoryTypeOriginal(), offset,40 assemble.SetOpAttribute(std::make_shared<AssembleOpAttribute>(moveOutTensorPtr->GetMemoryTypeOriginal(), offset,
40 dynOffset, moveOutTensorPtr->GetDynValidShape()));41 dynOffset, moveOutTensorPtr->GetDynValidShape()));
41- Operation& view = irBuilder_.CreateTensorOpStmt(function, Opcode::OP_VIEW, {ddrTensorPtr}, {moveInTensorPtr});42+ Operation& view = irBuilder_.CreateTensorOpStmt(function, config::GetSliceOpcode(), {ddrTensorPtr},
43+ {moveInTensorPtr});
42 view.SetOpAttribute(std::make_shared<ViewOpAttribute>(offset, moveOutTensorPtr->GetMemoryTypeOriginal(), dynOffset,44 view.SetOpAttribute(std::make_shared<ViewOpAttribute>(offset, moveOutTensorPtr->GetMemoryTypeOriginal(), dynOffset,
43 moveOutTensorPtr->GetDynValidShape()));45 moveOutTensorPtr->GetDynValidShape()));
44 assembleOp->ReplaceInput(moveInTensorPtr, moveOutTensorPtr);46 assembleOp->ReplaceInput(moveInTensorPtr, moveOutTensorPtr);
@@ -47,6 +49,9 @@ void InsertOpForViewAssemble::InsertViewAssemble(Function& function, Operation*
47Status InsertOpForViewAssemble::InsertCopy(Function& function, Operation* viewOp, Operation* assOp)49Status InsertOpForViewAssemble::InsertCopy(Function& function, Operation* viewOp, Operation* assOp)
48{50{
49 if (assOp->GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR) {51 if (assOp->GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR) {
52+ if (viewOp->GetOpcode() != config::GetSliceOpcode() || assOp->GetOpcode() != config::GetContractOpcode()) {
53+ return SUCCESS;
54+ }
50 assOp->GetIOperands()[0]->SetMemoryTypeBoth(MemoryType::MEM_UB, true);55 assOp->GetIOperands()[0]->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
51 auto viewOpAttr = std::dynamic_pointer_cast<ViewOpAttribute>(viewOp->GetOpAttribute());56 auto viewOpAttr = std::dynamic_pointer_cast<ViewOpAttribute>(viewOp->GetOpAttribute());
52 if (viewOpAttr != nullptr) {57 if (viewOpAttr != nullptr) {
@@ -75,7 +80,7 @@ bool InsertOpForViewAssemble::NeedInsertCopy(LogicalTensorPtr& assembleOut)
75 bool isNeedInsert = false;80 bool isNeedInsert = false;
76 for (auto& assOp : assembleOut->GetProducers()) {81 for (auto& assOp : assembleOut->GetProducers()) {
77 auto& prodOp = *assOp->GetIOperands()[0]->GetProducers().begin();82 auto& prodOp = *assOp->GetIOperands()[0]->GetProducers().begin();
78- if (prodOp->GetOpcode() != Opcode::OP_VIEW) {83+ if (!IsViewLike(prodOp->GetOpcode())) {
79 isNeedInsert = true;84 isNeedInsert = true;
80 APASS_LOG_INFO_F(Elements::Operation, "assOp[%d] producerOp %s[%d] is not viewOp.", assOp->GetOpMagic(),85 APASS_LOG_INFO_F(Elements::Operation, "assOp[%d] producerOp %s[%d] is not viewOp.", assOp->GetOpMagic(),
81 prodOp->GetOpcodeStr().c_str(), prodOp->GetOpMagic());86 prodOp->GetOpcodeStr().c_str(), prodOp->GetOpMagic());
@@ -138,7 +143,7 @@ bool InsertOpForViewAssemble::NeedInsertCopy(LogicalTensorPtr& assembleOut)
138Status InsertOpForViewAssemble::JudgedViewAssemble(Function& function)143Status InsertOpForViewAssemble::JudgedViewAssemble(Function& function)
139{144{
140 for (auto& op : function.Operations()) {145 for (auto& op : function.Operations()) {
141- if (op.GetOpcode() != Opcode::OP_ASSEMBLE) {146+ if (!IsAssembleLike(op.GetOpcode())) {
142 continue;147 continue;
143 }148 }
144 auto& prodOp = *op.GetIOperands()[0]->GetProducers().begin();149 auto& prodOp = *op.GetIOperands()[0]->GetProducers().begin();
@@ -148,8 +153,7 @@ Status InsertOpForViewAssemble::JudgedViewAssemble(Function& function)
148 }153 }
149 continue;154 continue;
150 }155 }
151- if (prodOp->GetOpcode() == Opcode::OP_VIEW &&156+ if (IsViewLike(prodOp->GetOpcode()) && assembleOutSet_.find(op.GetOOperands()[0]) == assembleOutSet_.end() &&
152- assembleOutSet_.find(op.GetOOperands()[0]) == assembleOutSet_.end() &&
153 prodOp->GetIOperands()[0]->GetMemoryTypeOriginal() == prodOp->GetOOperands()[0]->GetMemoryTypeOriginal() &&157 prodOp->GetIOperands()[0]->GetMemoryTypeOriginal() == prodOp->GetOOperands()[0]->GetMemoryTypeOriginal() &&
154 notProcessOut_.find(op.GetOOperands()[0]) == notProcessOut_.end()) {158 notProcessOut_.find(op.GetOOperands()[0]) == notProcessOut_.end()) {
155 assembleOutSet_.insert(op.GetOOperands()[0]);159 assembleOutSet_.insert(op.GetOOperands()[0]);
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include "process_atomic.h"16#include "process_atomic.h"
17+#include "interface/configs/config_manager_ng.h"
17#include "passes/pass_check/process_atomic_checker.h"18#include "passes/pass_check/process_atomic_checker.h"
18#include "interface/operation/attribute.h"19#include "interface/operation/attribute.h"
19#include "tilefwk/tilefwk_op.h"20#include "tilefwk/tilefwk_op.h"
@@ -39,6 +40,10 @@ std::vector<SymbolicScalar> GetSymbolicShapeOrStatic(const std::shared_ptr<Logic
39 return dynShape.size() == tensor->GetShape().size() ? dynShape : SymbolicScalar::FromConcrete(tensor->GetShape());40 return dynShape.size() == tensor->GetShape().size() ? dynShape : SymbolicScalar::FromConcrete(tensor->GetShape());
40}41}
41 42 
43+bool IsContractOpcode(Opcode opcode)
44+{
45+ return opcode == config::GetContractOpcode() || (!config::EnableSlice() && opcode == Opcode::OP_ASSEMBLE_SSA);
46+}
42} // namespace47} // namespace
43 48 
44Status ProcessAtomic::PreCheck(Function& function)49Status ProcessAtomic::PreCheck(Function& function)
@@ -176,15 +181,15 @@ Status ProcessAtomic::ProcessSingleAtomicRMW(Operation& op)
176 APASS_LOG_INFO_F(Elements::Operation, "ATOMIC_RMW, opmagic: %d", op.GetOpMagic());181 APASS_LOG_INFO_F(Elements::Operation, "ATOMIC_RMW, opmagic: %d", op.GetOpMagic());
177 182 
178 auto rmwOut = op.GetOOperands().front();183 auto rmwOut = op.GetOOperands().front();
179- auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());184+ auto contractAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());
180- if (assembleAttr == nullptr) {185+ if (contractAttr == nullptr) {
181- APASS_LOG_ERROR_F(Elements::Operation, "Op[%d] missing AssembleOpAttribute; Cannot eliminate.",186+ APASS_LOG_ERROR_F(Elements::Operation, "Op[%d] missing contract op attribute; Cannot eliminate.",
182 op.GetOpMagic());187 op.GetOpMagic());
183 return FAILED;188 return FAILED;
184 }189 }
185 190 
186- auto& rmwOffset = assembleAttr->GetToOffset();191+ auto& rmwOffset = contractAttr->GetToOffset();
187- auto& rmwDynOffset = assembleAttr->GetToDynOffset();192+ auto& rmwDynOffset = contractAttr->GetToDynOffset();
188 193 
189 int rmwModeValue = op.GetIntAttribute(OpAttributeKey::rmwMode);194 int rmwModeValue = op.GetIntAttribute(OpAttributeKey::rmwMode);
190 AtomicRMWMode rmwMode = static_cast<AtomicRMWMode>(rmwModeValue);195 AtomicRMWMode rmwMode = static_cast<AtomicRMWMode>(rmwModeValue);
@@ -207,34 +212,34 @@ Status ProcessAtomic::ProcessAtomicInput(Operation& atomicOp, const std::shared_
207 const std::vector<int64_t>& rmwOffset,212 const std::vector<int64_t>& rmwOffset,
208 const std::vector<SymbolicScalar>& rmwDynOffset)213 const std::vector<SymbolicScalar>& rmwDynOffset)
209{214{
210- bool hasAssembleProducer = false;215+ bool hasContractProducer = false;
211 auto producersBackup = input->GetProducers();216 auto producersBackup = input->GetProducers();
212 for (auto* producerOp : producersBackup) {217 for (auto* producerOp : producersBackup) {
213- if (producerOp->GetOpcode() != Opcode::OP_ASSEMBLE && producerOp->GetOpcode() != Opcode::OP_ASSEMBLE_SSA) {218+ if (!IsContractOpcode(producerOp->GetOpcode())) {
214 continue;219 continue;
215 }220 }
216- if (ProcessAtomicAssembleProducer(atomicOp, *producerOp, output, rmwMode, rmwOffset, rmwDynOffset) != SUCCESS) {221+ if (ProcessAtomicContractProducer(atomicOp, *producerOp, output, rmwMode, rmwOffset, rmwDynOffset) != SUCCESS) {
217 return FAILED;222 return FAILED;
218 }223 }
219- hasAssembleProducer = true;224+ hasContractProducer = true;
220 }225 }
221- if (hasAssembleProducer || !HasReshapeProducer(input)) {226+ if (hasContractProducer || !HasReshapeProducer(input)) {
222 return SUCCESS;227 return SUCCESS;
223 }228 }
224 return ProcessAtomicThroughReshape(atomicOp, input, output, rmwMode, rmwOffset, rmwDynOffset);229 return ProcessAtomicThroughReshape(atomicOp, input, output, rmwMode, rmwOffset, rmwDynOffset);
225}230}
226 231 
227-Status ProcessAtomic::ProcessAtomicAssembleProducer(Operation& atomicOp, Operation& producerOp,232+Status ProcessAtomic::ProcessAtomicContractProducer(Operation& atomicOp, Operation& producerOp,
228 const std::shared_ptr<LogicalTensor>& output, AtomicRMWMode rmwMode,233 const std::shared_ptr<LogicalTensor>& output, AtomicRMWMode rmwMode,
229 const std::vector<int64_t>& rmwOffset,234 const std::vector<int64_t>& rmwOffset,
230 const std::vector<SymbolicScalar>& rmwDynOffset)235 const std::vector<SymbolicScalar>& rmwDynOffset)
231{236{
232 if (producerOp.GetIOperands().size() != 1 || !HasReshapeProducer(producerOp.GetInputOperand(0))) {237 if (producerOp.GetIOperands().size() != 1 || !HasReshapeProducer(producerOp.GetInputOperand(0))) {
233- return ProcessAssembleProducer(producerOp, output, rmwMode, rmwOffset, rmwDynOffset);238+ return ProcessContractProducer(producerOp, output, rmwMode, rmwOffset, rmwDynOffset);
234 }239 }
235 std::vector<int64_t> combinedOffset;240 std::vector<int64_t> combinedOffset;
236 std::vector<SymbolicScalar> combinedDynOffset;241 std::vector<SymbolicScalar> combinedDynOffset;
237- if (CombineAssembleOffset(producerOp, rmwOffset, rmwDynOffset, combinedOffset, combinedDynOffset) != SUCCESS) {242+ if (CombineContractOffset(producerOp, rmwOffset, rmwDynOffset, combinedOffset, combinedDynOffset) != SUCCESS) {
238 return FAILED;243 return FAILED;
239 }244 }
240 return ProcessAtomicThroughReshape(atomicOp, producerOp.GetInputOperand(0), output, rmwMode, combinedOffset,245 return ProcessAtomicThroughReshape(atomicOp, producerOp.GetInputOperand(0), output, rmwMode, combinedOffset,
@@ -253,8 +258,8 @@ Status ProcessAtomic::ProcessAtomicThroughReshape(Operation& atomicOp, const std
253 atomicOp.GetOpMagic());258 atomicOp.GetOpMagic());
254 return FAILED;259 return FAILED;
255 }260 }
256- for (auto* assemble : remapResult.assembles) {261+ for (auto* contract : remapResult.assembles) {
257- if (MarkAssembleProducerAtomic(*assemble, rmwMode, remapResult.mappedOffset, remapResult.mappedDynOffset) !=262+ if (MarkContractProducerAtomic(*contract, rmwMode, remapResult.mappedOffset, remapResult.mappedDynOffset) !=
258 SUCCESS) {263 SUCCESS) {
259 return FAILED;264 return FAILED;
260 }265 }
@@ -325,8 +330,7 @@ Status ProcessAtomic::CollectTerminalAssembles(const std::shared_ptr<LogicalTens
325 return FAILED;330 return FAILED;
326 }331 }
327 bool allAssemble = std::all_of(producers.begin(), producers.end(), [](const Operation* producer) {332 bool allAssemble = std::all_of(producers.begin(), producers.end(), [](const Operation* producer) {
328- return producer != nullptr &&333+ return producer != nullptr && IsContractOpcode(producer->GetOpcode());
329- (producer->GetOpcode() == Opcode::OP_ASSEMBLE || producer->GetOpcode() == Opcode::OP_ASSEMBLE_SSA);
330 });334 });
331 if (!allAssemble) {335 if (!allAssemble) {
332 return SUCCESS;336 return SUCCESS;
@@ -412,12 +416,12 @@ Status ProcessAtomic::RetargetReshapeChain(Operation& atomicOp, const std::share
412 return SUCCESS;416 return SUCCESS;
413}417}
414 418 
415-Status ProcessAtomic::CombineAssembleOffset(const Operation& assemble, const std::vector<int64_t>& offset,419+Status ProcessAtomic::CombineContractOffset(const Operation& contract, const std::vector<int64_t>& offset,
416 const std::vector<SymbolicScalar>& dynOffset,420 const std::vector<SymbolicScalar>& dynOffset,
417 std::vector<int64_t>& combinedOffset,421 std::vector<int64_t>& combinedOffset,
418 std::vector<SymbolicScalar>& combinedDynOffset) const422 std::vector<SymbolicScalar>& combinedDynOffset) const
419{423{
420- auto attr = std::dynamic_pointer_cast<AssembleOpAttribute>(assemble.GetOpAttribute());424+ auto attr = std::dynamic_pointer_cast<AssembleOpAttribute>(contract.GetOpAttribute());
421 if (attr == nullptr || attr->GetToOffset().size() != offset.size()) {425 if (attr == nullptr || attr->GetToOffset().size() != offset.size()) {
422 return FAILED;426 return FAILED;
423 }427 }
@@ -438,7 +442,7 @@ Status ProcessAtomic::CombineAssembleOffset(const Operation& assemble, const std
438 return SUCCESS;442 return SUCCESS;
439}443}
440 444 
441-bool ProcessAtomic::HasAssembleProducer(const std::shared_ptr<LogicalTensor>& input) const445+bool ProcessAtomic::HasContractProducer(const std::shared_ptr<LogicalTensor>& input) const
442{446{
443 if (input == nullptr) {447 if (input == nullptr) {
444 return false;448 return false;
@@ -447,7 +451,7 @@ bool ProcessAtomic::HasAssembleProducer(const std::shared_ptr<LogicalTensor>& in
447 if (producerOp == nullptr) {451 if (producerOp == nullptr) {
448 continue;452 continue;
449 }453 }
450- if (producerOp->GetOpcode() == Opcode::OP_ASSEMBLE || producerOp->GetOpcode() == Opcode::OP_ASSEMBLE_SSA) {454+ if (IsContractOpcode(producerOp->GetOpcode())) {
451 return true;455 return true;
452 }456 }
453 }457 }
@@ -489,7 +493,7 @@ Status ProcessAtomic::PrepareAtomicRMWSharedInputs(Function& function,
489std::shared_ptr<LogicalTensor> ProcessAtomic::PrepareExclusiveAtomicInput(493std::shared_ptr<LogicalTensor> ProcessAtomic::PrepareExclusiveAtomicInput(
490 Function& function, Operation& atomicOp, const std::shared_ptr<LogicalTensor>& input) const494 Function& function, Operation& atomicOp, const std::shared_ptr<LogicalTensor>& input) const
491{495{
492- if (input == nullptr || !HasConsumerExcept(input, atomicOp) || !HasAssembleProducer(input)) {496+ if (input == nullptr || !HasConsumerExcept(input, atomicOp) || !HasContractProducer(input)) {
493 return input;497 return input;
494 }498 }
495 499 
@@ -507,7 +511,7 @@ std::shared_ptr<LogicalTensor> ProcessAtomic::PrepareExclusiveAtomicInput(
507 input->GetMagic());511 input->GetMagic());
508 return nullptr;512 return nullptr;
509 }513 }
510- if (producerOp->GetOpcode() != Opcode::OP_ASSEMBLE && producerOp->GetOpcode() != Opcode::OP_ASSEMBLE_SSA) {514+ if (!IsContractOpcode(producerOp->GetOpcode())) {
511 continue;515 continue;
512 }516 }
513 auto& clonedProducer = producerOp->CloneOperation(function, producerOp->GetIOperands(),517 auto& clonedProducer = producerOp->CloneOperation(function, producerOp->GetIOperands(),
@@ -538,7 +542,7 @@ std::string ProcessAtomic::GetRmwAttrKey(AtomicRMWMode mode)
538 }542 }
539}543}
540 544 
541-Status ProcessAtomic::ProcessAssembleProducer(Operation& producerOp, std::shared_ptr<LogicalTensor> rmwOut,545+Status ProcessAtomic::ProcessContractProducer(Operation& producerOp, std::shared_ptr<LogicalTensor> rmwOut,
542 AtomicRMWMode rmwMode, const std::vector<int64_t>& rmwOffset,546 AtomicRMWMode rmwMode, const std::vector<int64_t>& rmwOffset,
543 const std::vector<SymbolicScalar>& rmwDynOffset)547 const std::vector<SymbolicScalar>& rmwDynOffset)
544{548{
@@ -549,15 +553,15 @@ Status ProcessAtomic::ProcessAssembleProducer(Operation& producerOp, std::shared
549 553 
550 producerOp.ReplaceOOperand(0, rmwOut);554 producerOp.ReplaceOOperand(0, rmwOut);
551 555 
552- auto producerAssembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(producerOp.GetOpAttribute());556+ auto producerContractAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(producerOp.GetOpAttribute());
553- if (producerAssembleAttr != nullptr &&557+ if (producerContractAttr != nullptr &&
554- AccumulateAssembleOffset(producerAssembleAttr, rmwOffset, rmwDynOffset) != SUCCESS) {558+ AccumulateContractOffset(producerContractAttr, rmwOffset, rmwDynOffset) != SUCCESS) {
555 return FAILED;559 return FAILED;
556 }560 }
557 return SUCCESS;561 return SUCCESS;
558}562}
559 563 
560-Status ProcessAtomic::MarkAssembleProducerAtomic(Operation& producerOp, AtomicRMWMode rmwMode,564+Status ProcessAtomic::MarkContractProducerAtomic(Operation& producerOp, AtomicRMWMode rmwMode,
561 const std::vector<int64_t>& rmwOffset,565 const std::vector<int64_t>& rmwOffset,
562 const std::vector<SymbolicScalar>& rmwDynOffset)566 const std::vector<SymbolicScalar>& rmwDynOffset)
563{567{
@@ -566,7 +570,7 @@ Status ProcessAtomic::MarkAssembleProducerAtomic(Operation& producerOp, AtomicRM
566 return FAILED;570 return FAILED;
567 }571 }
568 auto producerAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(producerOp.GetOpAttribute());572 auto producerAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(producerOp.GetOpAttribute());
569- if (producerAttr != nullptr && AccumulateAssembleOffset(producerAttr, rmwOffset, rmwDynOffset) != SUCCESS) {573+ if (producerAttr != nullptr && AccumulateContractOffset(producerAttr, rmwOffset, rmwDynOffset) != SUCCESS) {
570 return FAILED;574 return FAILED;
571 }575 }
572 return SUCCESS;576 return SUCCESS;
@@ -595,15 +599,15 @@ Status ProcessAtomic::CheckAndSetRmwAttr(Operation& producerOp, AtomicRMWMode rm
595 existingAttrType = "atomic_min";599 existingAttrType = "atomic_min";
596 600 
597 APASS_LOG_ERROR_F(Elements::Operation,601 APASS_LOG_ERROR_F(Elements::Operation,
598- "Op[%d] rmwMode conflict: producer assemble op already has '%s' attribute, "602+ "Op[%d] rmwMode conflict: producer contract op already has '%s' attribute, "
599- "but current wants to set '%s'. Cannot set different rmwMode to the same assemble op.",603+ "but current wants to set '%s'. Cannot set different rmwMode to the same contract op.",
600 producerOp.GetOpMagic(), existingAttrType.c_str(), rmwAttrKey.c_str());604 producerOp.GetOpMagic(), existingAttrType.c_str(), rmwAttrKey.c_str());
601 return FAILED;605 return FAILED;
602 }606 }
603 return SUCCESS;607 return SUCCESS;
604}608}
605 609 
606-Status ProcessAtomic::AccumulateAssembleOffset(std::shared_ptr<AssembleOpAttribute> producerAttr,610+Status ProcessAtomic::AccumulateContractOffset(std::shared_ptr<AssembleOpAttribute> producerAttr,
607 const std::vector<int64_t>& rmwOffset,611 const std::vector<int64_t>& rmwOffset,
608 const std::vector<SymbolicScalar>& rmwDynOffset)612 const std::vector<SymbolicScalar>& rmwDynOffset)
609{613{
@@ -697,8 +701,7 @@ Status ProcessAtomic::RemoveVecDupBranchFromCubeOp(Operation& cubeOp, bool& anyR
697 if (producer == nullptr || producer->IsDeleted()) {701 if (producer == nullptr || producer->IsDeleted()) {
698 continue;702 continue;
699 }703 }
700- if ((producer->GetOpcode() == Opcode::OP_ASSEMBLE || producer->GetOpcode() == Opcode::OP_ASSEMBLE_SSA) &&704+ if (IsContractOpcode(producer->GetOpcode()) && IsVecDupContractInput(*producer)) {
701- IsVecDupAssembleInput(*producer)) {
702 input->RemoveConsumer(&cubeOp);705 input->RemoveConsumer(&cubeOp);
703 cubeOp.EraseInput(input);706 cubeOp.EraseInput(input);
704 anyRemoved = true;707 anyRemoved = true;
@@ -709,9 +712,9 @@ Status ProcessAtomic::RemoveVecDupBranchFromCubeOp(Operation& cubeOp, bool& anyR
709 return SUCCESS;712 return SUCCESS;
710}713}
711 714 
712-bool ProcessAtomic::IsVecDupAssembleInput(const Operation& assembleOp) const715+bool ProcessAtomic::IsVecDupContractInput(const Operation& contractOp) const
713{716{
714- for (const auto& input : assembleOp.GetIOperands()) {717+ for (const auto& input : contractOp.GetIOperands()) {
715 for (auto* producer : input->GetProducers()) {718 for (auto* producer : input->GetProducers()) {
716 if (producer != nullptr && producer->GetOpcode() == Opcode::OP_VEC_DUP) {719 if (producer != nullptr && producer->GetOpcode() == Opcode::OP_VEC_DUP) {
717 return true;720 return true;
@@ -746,8 +749,8 @@ Status ProcessAtomic::EliminateVecDupBranch(Function& function, bool& hasReduceA
746 if (!anyRemoved) {749 if (!anyRemoved) {
747 return SUCCESS;750 return SUCCESS;
748 }751 }
749- APASS_LOG_INFO_F(Elements::Function, "EliminateVecDupBranch removed VecDup assemble input branch.");752+ APASS_LOG_INFO_F(Elements::Function, "EliminateVecDupBranch removed VecDup contract input branch.");
750- function.EraseOperations(true, true, SortOperationsMode::LIGHTWEIGHT);753+ function.EraseOperations(true);
751 if (DeadOperationEliminator::EliminateDeadOperation(function) != SUCCESS) {754 if (DeadOperationEliminator::EliminateDeadOperation(function) != SUCCESS) {
752 APASS_LOG_ERROR_F(Elements::Function, "Eliminate dead operation failed for VecDup branch.");755 APASS_LOG_ERROR_F(Elements::Function, "Eliminate dead operation failed for VecDup branch.");
753 return FAILED;756 return FAILED;
@@ -58,16 +58,16 @@ private:
58 Status CheckAtomicRMWUnsupportedMode(Function& function);58 Status CheckAtomicRMWUnsupportedMode(Function& function);
59 std::string GetRmwAttrKey(AtomicRMWMode mode);59 std::string GetRmwAttrKey(AtomicRMWMode mode);
60 Status CheckAndSetRmwAttr(Operation& producerOp, AtomicRMWMode rmwMode, const std::string& rmwAttrKey);60 Status CheckAndSetRmwAttr(Operation& producerOp, AtomicRMWMode rmwMode, const std::string& rmwAttrKey);
61- Status AccumulateAssembleOffset(std::shared_ptr<AssembleOpAttribute> producerAttr,61+ Status AccumulateContractOffset(std::shared_ptr<AssembleOpAttribute> producerAttr,
62 const std::vector<int64_t>& rmwOffset,62 const std::vector<int64_t>& rmwOffset,
63 const std::vector<SymbolicScalar>& rmwDynOffset);63 const std::vector<SymbolicScalar>& rmwDynOffset);
64- Status ProcessAssembleProducer(Operation& producerOp, std::shared_ptr<LogicalTensor> rmwOut, AtomicRMWMode rmwMode,64+ Status ProcessContractProducer(Operation& producerOp, std::shared_ptr<LogicalTensor> rmwOut, AtomicRMWMode rmwMode,
65 const std::vector<int64_t>& rmwOffset,65 const std::vector<int64_t>& rmwOffset,
66 const std::vector<SymbolicScalar>& rmwDynOffset);66 const std::vector<SymbolicScalar>& rmwDynOffset);
67- Status MarkAssembleProducerAtomic(Operation& producerOp, AtomicRMWMode rmwMode,67+ Status MarkContractProducerAtomic(Operation& producerOp, AtomicRMWMode rmwMode,
68 const std::vector<int64_t>& rmwOffset,68 const std::vector<int64_t>& rmwOffset,
69 const std::vector<SymbolicScalar>& rmwDynOffset);69 const std::vector<SymbolicScalar>& rmwDynOffset);
70- bool HasAssembleProducer(const std::shared_ptr<LogicalTensor>& input) const;70+ bool HasContractProducer(const std::shared_ptr<LogicalTensor>& input) const;
71 bool HasConsumerExcept(const std::shared_ptr<LogicalTensor>& input, const Operation& op) const;71 bool HasConsumerExcept(const std::shared_ptr<LogicalTensor>& input, const Operation& op) const;
72 Status PrepareAtomicRMWSharedInputs(Function& function, const std::vector<Operation*>& atomicRmwOps) const;72 Status PrepareAtomicRMWSharedInputs(Function& function, const std::vector<Operation*>& atomicRmwOps) const;
73 std::shared_ptr<LogicalTensor> PrepareExclusiveAtomicInput(Function& function, Operation& atomicOp,73 std::shared_ptr<LogicalTensor> PrepareExclusiveAtomicInput(Function& function, Operation& atomicOp,
@@ -76,7 +76,7 @@ private:
76 Status ProcessAtomicInput(Operation& atomicOp, const std::shared_ptr<LogicalTensor>& input,76 Status ProcessAtomicInput(Operation& atomicOp, const std::shared_ptr<LogicalTensor>& input,
77 const std::shared_ptr<LogicalTensor>& output, AtomicRMWMode rmwMode,77 const std::shared_ptr<LogicalTensor>& output, AtomicRMWMode rmwMode,
78 const std::vector<int64_t>& rmwOffset, const std::vector<SymbolicScalar>& rmwDynOffset);78 const std::vector<int64_t>& rmwOffset, const std::vector<SymbolicScalar>& rmwDynOffset);
79- Status ProcessAtomicAssembleProducer(Operation& atomicOp, Operation& producerOp,79+ Status ProcessAtomicContractProducer(Operation& atomicOp, Operation& producerOp,
80 const std::shared_ptr<LogicalTensor>& output, AtomicRMWMode rmwMode,80 const std::shared_ptr<LogicalTensor>& output, AtomicRMWMode rmwMode,
81 const std::vector<int64_t>& rmwOffset,81 const std::vector<int64_t>& rmwOffset,
82 const std::vector<SymbolicScalar>& rmwDynOffset);82 const std::vector<SymbolicScalar>& rmwDynOffset);
@@ -97,13 +97,13 @@ private:
97 ReshapeRemapResult& result) const;97 ReshapeRemapResult& result) const;
98 Status RetargetReshapeChain(Operation& atomicOp, const std::shared_ptr<LogicalTensor>& output,98 Status RetargetReshapeChain(Operation& atomicOp, const std::shared_ptr<LogicalTensor>& output,
99 const ReshapeRemapResult& remapResult);99 const ReshapeRemapResult& remapResult);
100- Status CombineAssembleOffset(const Operation& assemble, const std::vector<int64_t>& offset,100+ Status CombineContractOffset(const Operation& contract, const std::vector<int64_t>& offset,
101 const std::vector<SymbolicScalar>& dynOffset, std::vector<int64_t>& combinedOffset,101 const std::vector<SymbolicScalar>& dynOffset, std::vector<int64_t>& combinedOffset,
102 std::vector<SymbolicScalar>& combinedDynOffset) const;102 std::vector<SymbolicScalar>& combinedDynOffset) const;
103 void CollectReduceAccUpstream(Operation& op, std::set<int>& visited, std::vector<Operation*>& result) const;103 void CollectReduceAccUpstream(Operation& op, std::set<int>& visited, std::vector<Operation*>& result) const;
104 Status TraceBackAndRemoveVecDup(Function& function, Operation& op, std::set<int>& visited, bool& anyRemoved);104 Status TraceBackAndRemoveVecDup(Function& function, Operation& op, std::set<int>& visited, bool& anyRemoved);
105 Status RemoveVecDupBranchFromCubeOp(Operation& cubeOp, bool& anyRemoved);105 Status RemoveVecDupBranchFromCubeOp(Operation& cubeOp, bool& anyRemoved);
106- bool IsVecDupAssembleInput(const Operation& assembleOp) const;106+ bool IsVecDupContractInput(const Operation& contractOp) const;
107 107 
108 IRBuilder irBuilder_;108 IRBuilder irBuilder_;
109};109};
@@ -22,12 +22,18 @@
22#include "passes/pass_utils/merge_view_assemble_utils.h"22#include "passes/pass_utils/merge_view_assemble_utils.h"
23#include "passes/pass_utils/pass_operation_utils.h"23#include "passes/pass_utils/pass_operation_utils.h"
24#include "passes/pass_utils/pass_utils.h"24#include "passes/pass_utils/pass_utils.h"
25+#include "passes/pass_utils/remove_redundant_op_utils.h"
25#include "passes/pass_log/pass_log.h"26#include "passes/pass_log/pass_log.h"
26 27 
27#define MODULE_NAME "RemoveRedundantOp"28#define MODULE_NAME "RemoveRedundantOp"
28 29 
29namespace npu {30namespace npu {
30namespace tile_fwk {31namespace tile_fwk {
32+namespace {
33+bool IsAssembleLikeOpcode(Opcode opcode) { return opcode == Opcode::OP_ASSEMBLE || opcode == Opcode::OP_CONTRACT; }
34+ 
35+} // namespace
36+ 
31bool EqualInOutShape(const Operation& op)37bool EqualInOutShape(const Operation& op)
32{38{
33 auto in = op.GetIOperands().front();39 auto in = op.GetIOperands().front();
@@ -79,17 +85,18 @@ bool RemoveRedundantOp::ProcessRedundantOpWithoutDynShape(Operation& op) const
79 op.opmagic);85 op.opmagic);
80 return false;86 return false;
81 }87 }
82- if (op.GetOpcode() == Opcode::OP_ASSEMBLE) {88+ if (IsAssembleLikeOpcode(op.GetOpcode())) {
83 auto assembleOutput = op.GetOOperands().front();89 auto assembleOutput = op.GetOOperands().front();
84 if (assembleOutput->GetProducers().size() > 1) {90 if (assembleOutput->GetProducers().size() > 1) {
85- APASS_LOG_DEBUG_F(Elements::Operation, "assembleOutput[%d] has more than one producer, skip removing.",91+ APASS_LOG_DEBUG_F(Elements::Operation,
92+ "assemble-like output[%d] has more than one producer, skip removing.",
86 assembleOutput->GetMagic());93 assembleOutput->GetMagic());
87 return false;94 return false;
88 }95 }
89 auto assembleInput = op.GetIOperands().front();96 auto assembleInput = op.GetIOperands().front();
90 bool hasParallelAssemble = false;97 bool hasParallelAssemble = false;
91 for (const auto& consumer : assembleInput->GetConsumers()) {98 for (const auto& consumer : assembleInput->GetConsumers()) {
92- if (consumer->GetOpcode() == Opcode::OP_ASSEMBLE && consumer->GetOpMagic() != op.GetOpMagic()) {99+ if (IsAssembleLikeOpcode(consumer->GetOpcode()) && consumer->GetOpMagic() != op.GetOpMagic()) {
93 hasParallelAssemble = true;100 hasParallelAssemble = true;
94 break;101 break;
95 }102 }
@@ -211,285 +218,13 @@ Status RemoveRedundantOp::RemoveDummyOps(Function& function)
211 218 
212Status RemoveRedundantOp::ProcessViewAssemble(Function& function)219Status RemoveRedundantOp::ProcessViewAssemble(Function& function)
213{220{
214- auto opList = function.Operations().DuplicatedOpList();221+ if (RemoveRedundantOpUtils::ProcessViewAssembleLike(function, newOps_, operationUpdated) != SUCCESS) {
215- bool anyRemoved = false;222+ APASS_LOG_ERROR_F(Elements::Function, "ProcessViewAssembleLike failed.");
216- for (auto& op : opList) {223+ return FAILED;
217- auto opcode = op->GetOpcode();
218- if (opcode != Opcode::OP_VIEW) {
219- // 跳过非view的op
220- continue;
221- }
222- auto& startTensor = op->iOperand.front();
223- auto inputMemtype = startTensor->GetMemoryTypeOriginal();
224- auto consumers = op->oOperand.front()->GetConsumers();
225- // 获取view级联的assemble消费者
226- for (const auto& consumer : consumers) {
227- if (consumer->GetOpcode() != Opcode::OP_ASSEMBLE) {
228- // 跳过不是assemble的消费者
229- continue;
230- }
231- auto& endTensor = consumer->oOperand.front();
232- if (function.IsFromInCast(startTensor) && function.IsFromOutCast(endTensor)) {
233- continue;
234- }
235- if (function.IsFromOutCast(startTensor) && function.IsFromOutCast(endTensor)) {
236- continue;
237- }
238- auto outputMemtype = endTensor->GetMemoryTypeOriginal();
239- if (inputMemtype != outputMemtype) {
240- // 跳过view输入和 assemble输出 mem类型不同的场景
241- continue;
242- }
243- if (startTensor->shape == endTensor->shape && startTensor->offset == endTensor->offset) {
244- // case1:view输入和assemble输出tensor shape和offset完全匹配
245- // startTensor(inshape) ---> view1 ---> tempTensor1 ---> assemble1 ---> endTensor(outshape =
246- // inshape)
247- // ---> view2 ---> tempTensor2 ---> assemble2
248- APASS_LOG_DEBUG_F(Elements::Operation,
249- "CASE1: Process OP_VIEW[%d]'s input and OP_ASSEMBLE[%d]'s output perfectMatch.",
250- op->opmagic, consumer->GetOpMagic());
251- ProcessPerfectMatch(function, startTensor, endTensor);
252- anyRemoved = true;
253- } else {
254- // 对于输入输出存在动轴的场景无法做级联的冗余删除
255- if ((function.IsFromInCast(startTensor) && CommonUtils::ContainsNegativeOne(startTensor->GetShape())) ||
256- (function.IsFromOutCast(endTensor) && CommonUtils::ContainsNegativeOne(endTensor->GetShape()))) {
257- continue;
258- }
259- // case2:assemble的输出tensor是view输入tensor的一部分
260- // startTensor(inshape) ---> view1 ---> tempTensor1 ---> assemble1 ---> endTensor(outshape <
261- // inshape)
262- // ---> view2 ---> tempTensor2 ---> assemble2
263- APASS_LOG_DEBUG_F(Elements::Operation,
264- "CASE2: Process OP_VIEW[%d]'s input is a part of OP_ASSEMBLE[%d]'s output.",
265- op->opmagic, consumer->GetOpMagic());
266- GenerateNewView(function, *op, startTensor, endTensor);
267- anyRemoved = true;
268- }
269- }
270- }
271- if (anyRemoved) {
272- DeadOperationEliminator::EliminateDeadOperation(function);
273 }224 }
274 return SUCCESS;225 return SUCCESS;
275}226}
276 227 
277-void RemoveRedundantOp::RemoveViewAssembleForOutcast(Function& function, LogicalTensorPtr& startTensor,
278- LogicalTensorPtr& endTensor)
279-{
280- bool canRemove;
281- std::set<Operation*> removeOp;
282- for (auto& startConsumer : startTensor->GetConsumers()) {
283- if (startConsumer->GetOpcode() != Opcode::OP_VIEW) {
284- continue;
285- }
286- canRemove = true;
287- for (auto& endProducer : startConsumer->ConsumerOps()) {
288- if (endProducer->GetOOperands().front() != endTensor || endProducer->GetOpcode() != Opcode::OP_ASSEMBLE) {
289- canRemove = false;
290- } else {
291- removeOp.insert(endProducer);
292- operationUpdated = true;
293- }
294- }
295- if (canRemove) {
296- removeOp.insert(startConsumer);
297- }
298- }
299- for (auto& op : removeOp) {
300- function.UpdateOperandBeforeRemoveOp(*op, false);
301- operationUpdated = true;
302- }
303-}
304- 
305-// 处理view输入和assemble输出完美匹配场景
306-void RemoveRedundantOp::ProcessPerfectMatch(Function& function, LogicalTensorPtr& startTensor,
307- LogicalTensorPtr& endTensor)
308-{
309- if (!IsValidViewAssemble(startTensor, endTensor)) {
310- APASS_LOG_DEBUG_F(Elements::Tensor, "Not valid view-assemble case.");
311- return;
312- }
313- // 图重连逻辑
314- if (endTensor->GetConsumers().size() == 0) {
315- RemoveViewAssembleForOutcast(function, startTensor, endTensor);
316- } else {
317- for (auto& assembleConsumer : endTensor->GetConsumers()) {
318- assembleConsumer->iOperand = {startTensor};
319- startTensor->AddConsumer(assembleConsumer);
320- }
321- endTensor->GetConsumers().clear();
322- operationUpdated = true;
323- }
324-}
325- 
326-// 判断view输入是否非同源
327-bool RemoveRedundantOp::IsNotSameViewInput(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor) const
328-{
329- for (auto& assembleOp : endTensor->GetProducers()) {
330- if (assembleOp->GetIOperands().empty()) {
331- continue;
332- }
333- auto& tempTensor = assembleOp->GetIOperands().front();
334- auto producers = tempTensor->GetProducers();
335- if (producers.empty()) {
336- return true;
337- }
338- for (auto& producerOp : tempTensor->GetProducers()) {
339- if (producerOp->GetOpcode() != Opcode::OP_VIEW) {
340- return true;
341- }
342- if (producerOp->GetIOperands().empty()) {
343- continue;
344- }
345- auto& inTensor = producerOp->GetIOperands().front();
346- if (inTensor != startTensor) {
347- return true;
348- }
349- }
350- }
351- return false;
352-}
353- 
354-// 判断assemble数据是否是重排场景
355-bool RemoveRedundantOp::IsDataReplace(LogicalTensorPtr& endTensor) const
356-{
357- for (auto& assembleOp : endTensor->GetProducers()) {
358- if (assembleOp->GetIOperands().empty()) {
359- continue;
360- }
361- auto& tempTensor = assembleOp->GetIOperands().front();
362- auto producers = tempTensor->GetProducers();
363- if (producers.empty()) {
364- return true;
365- } else {
366- auto& viewOps = tempTensor->GetProducers();
367- for (auto& viewOp : viewOps) {
368- if (viewOp->GetIOperands().empty()) {
369- continue;
370- }
371- if (viewOp->GetOpcode() != Opcode::OP_VIEW) {
372- continue;
373- }
374- auto viewOpAttribute = dynamic_cast<ViewOpAttribute*>(viewOp->GetOpAttribute().get());
375- auto viewOffset = viewOpAttribute->GetFrom();
376- auto assembleOpAttribute = dynamic_cast<AssembleOpAttribute*>(assembleOp->GetOpAttribute().get());
377- auto assembleOffset = assembleOpAttribute->GetToOffset();
378- if (viewOffset != assembleOffset) { // 跳过assemble数据重排场景
379- return true;
380- }
381- }
382- }
383- }
384- return false;
385-}
386- 
387-bool RemoveRedundantOp::IsValidViewAssemble(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor) const
388-{
389- // step1:排除view输入非同源场景
390- bool isNotSameViewInput = IsNotSameViewInput(startTensor, endTensor); // true表示view的输入非同源
391- if (isNotSameViewInput) {
392- APASS_LOG_DEBUG_F(Elements::Tensor,
393- "OP_ASSEMBLE'S output endTensor[%d] has different input except startTesnor[%d].",
394- startTensor->magic, endTensor->magic);
395- return false;
396- }
397- // step2:排除endTensor不是startTensor一部分的场景,每个维度的shape应小于等于startTensor
398- if (endTensor->shape.size() > startTensor->shape.size()) {
399- return false;
400- }
401- for (size_t i = 0; i < endTensor->shape.size(); ++i) {
402- if (endTensor->shape[i] > startTensor->shape[i]) {
403- return false;
404- }
405- }
406- // step3:排除assemble数据重排场景
407- bool isDataRepalce = IsDataReplace(endTensor); // true表示assemble后数据重排布
408- if (isDataRepalce) {
409- APASS_LOG_DEBUG_F(Elements::Tensor,
410- "OP_ASSEMBLE'S output endTensor[%d] is repalced comparing with startTesnor[%d].",
411- startTensor->magic, endTensor->magic);
412- return false;
413- }
414- return true;
415-}
416- 
417-void RemoveRedundantOp::CalculateViewOffset(Operation& op, LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor,
418- std::vector<long>& newoffset, std::vector<SymbolicScalar>& newDynoffset)
419-{
420- for (size_t m = 0; m < op.iOperand[0]->offset.size(); m++) {
421- for (auto& comsumerView : startTensor->GetConsumers()) {
422- auto opcode = comsumerView->GetOpcode();
423- if (opcode != Opcode::OP_VIEW || comsumerView->GetOOperands().empty()) {
424- continue;
425- }
426- auto& tempTensor = comsumerView->GetOOperands().front();
427- // 检查view输出的消费者,寻找assemble操作
428- bool leadsToCurrentEndTesnor = false;
429- for (auto& consumerAssemble : tempTensor->GetConsumers()) {
430- if (consumerAssemble->GetOpcode() != Opcode::OP_ASSEMBLE) {
431- continue;
432- }
433- // 检查assemble的输出是否是当前的endTensor
434- if (!consumerAssemble->GetOOperands().empty() &&
435- consumerAssemble->GetOOperands().front() == endTensor) {
436- leadsToCurrentEndTesnor = true;
437- break;
438- }
439- }
440- // 如果当前view不经过assemble连接到当前endTensor,跳过不处理
441- if (!leadsToCurrentEndTesnor) {
442- continue;
443- }
444- // 只处理satrtTensor->view->tempTensor->assemble->endTensor
445- auto viewOpAttribute = dynamic_cast<ViewOpAttribute*>(comsumerView->GetOpAttribute().get());
446- if (viewOpAttribute != nullptr) {
447- auto viewOffset = viewOpAttribute->GetFromOffset();
448- auto viewDynOffset = viewOpAttribute->GetFromDynOffset();
449- newoffset[m] = std::min(newoffset[m], viewOffset[m]);
450- newDynoffset[m] = std::min(newDynoffset[m], viewDynOffset[m]);
451- }
452- }
453- }
454-}
455- 
456-void RemoveRedundantOp::GenerateNewView(Function& function, Operation& op, LogicalTensorPtr& startTensor,
457- LogicalTensorPtr& endTensor)
458-{
459- // 查找最小的offset
460- if (!IsValidViewAssemble(startTensor, endTensor)) {
461- APASS_LOG_DEBUG_F(Elements::Tensor, "Not valid view-assemble case.");
462- return;
463- }
464- // endTensor 是 outcast(无消费者)时不处理,避免图断裂
465- if (endTensor->GetConsumers().empty()) {
466- return;
467- }
468- std::vector<long> newoffset(op.iOperand[0]->offset.size(), INT_MAX);
469- std::vector<SymbolicScalar> newDynoffset(op.iOperand[0]->offset.size(), INT_MAX);
470- CalculateViewOffset(op, startTensor, endTensor, newoffset, newDynoffset);
471- // 新建一个logical tensor并更新图链接关系:清除endTensor的消费者,清除endTensor,将assemble的消费者连接到newView
472- LogicalTensorPtr newViewTensor;
473- std::vector<long> curOffset(endTensor->shape.size(), 0);
474- newViewTensor = irBuilder_.CreateTensorVar(endTensor->GetRawTensor(), curOffset, endTensor->shape,
475- std::vector<SymbolicScalar>{});
476- newViewTensor->SetMemoryTypeBoth(endTensor->GetMemoryTypeOriginal());
477- for (auto& assembleConsumer : endTensor->GetConsumers()) {
478- assembleConsumer->iOperand = {newViewTensor};
479- newViewTensor->AddConsumer(assembleConsumer);
480- }
481- endTensor->GetConsumers().clear();
482- // 新建一个view op
483- std::shared_ptr<ViewOpAttribute> viewAttribute = std::make_shared<ViewOpAttribute>(
484- newoffset, newDynoffset, newViewTensor->GetDynValidShape());
485- viewAttribute->SetToType(endTensor->GetMemoryTypeToBe());
486- auto& newViewOp = PassOperationUtils::AddOperation(
487- function, Opcode::OP_VIEW, {startTensor}, {newViewTensor},
488- [&viewAttribute](Operation& newOp) { newOp.SetOpAttribute(viewAttribute); });
489- newOps_.push_back(&newViewOp);
490- operationUpdated = true;
491-}
492- 
493Status RemoveRedundantOp::ProcessReshape(Function& function)228Status RemoveRedundantOp::ProcessReshape(Function& function)
494{229{
495 bool anyRemoved = false;230 bool anyRemoved = false;
@@ -33,8 +33,9 @@
33 33 
34namespace npu {34namespace npu {
35namespace tile_fwk {35namespace tile_fwk {
36-const std::unordered_set<Opcode> matchOpcodeWithDynshape = {Opcode::OP_VIEW, Opcode::OP_EXPAND};36+const std::unordered_set<Opcode> matchOpcodeWithDynshape = {Opcode::OP_VIEW, Opcode::OP_SLICE, Opcode::OP_EXPAND};
37-const std::unordered_set<Opcode> matchOpcodeWithoutDynshape = {Opcode::OP_REGISTER_COPY, Opcode::OP_ASSEMBLE};37+const std::unordered_set<Opcode> matchOpcodeWithoutDynshape = {Opcode::OP_REGISTER_COPY, Opcode::OP_ASSEMBLE,
38+ Opcode::OP_CONTRACT};
38class RemoveRedundantOp : public Pass {39class RemoveRedundantOp : public Pass {
39public:40public:
40 RemoveRedundantOp() : Pass("RemoveRedundantOp") {}41 RemoveRedundantOp() : Pass("RemoveRedundantOp") {}
@@ -48,14 +49,6 @@ private:
48 Status ProcessViewAssemble(Function& function);49 Status ProcessViewAssemble(Function& function);
49 Status ProcessReshape(Function& function);50 Status ProcessReshape(Function& function);
50 Status RemoveDummyOps(Function& function);51 Status RemoveDummyOps(Function& function);
51- void ProcessPerfectMatch(Function& function, LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor);
52- void RemoveViewAssembleForOutcast(Function& function, LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor);
53- void CalculateViewOffset(Operation& op, LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor,
54- std::vector<long>& newoffset, std::vector<SymbolicScalar>& newDynoffset);
55- void GenerateNewView(Function& function, Operation& op, LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor);
56- bool IsNotSameViewInput(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor) const;
57- bool IsDataReplace(LogicalTensorPtr& endTensor) const;
58- bool IsValidViewAssemble(LogicalTensorPtr& startTensor, LogicalTensorPtr& endTensor) const;
59 bool ProcessRedundantOpWithDynShape(Operation& op) const;52 bool ProcessRedundantOpWithDynShape(Operation& op) const;
60 bool ProcessRedundantOpWithoutDynShape(Operation& op) const;53 bool ProcessRedundantOpWithoutDynShape(Operation& op) const;
61 54 
@@ -68,10 +68,10 @@ private:
68 Status RunOnFunction(Function& function) override;68 Status RunOnFunction(Function& function) override;
69 void Init();69 void Init();
70 void EraseRedundantAssembleOp(Function& function);70 void EraseRedundantAssembleOp(Function& function);
71- void EraseRedundantViewOp(Function& function);
72 void RemoveOps(Function& function, std::vector<Operation*>& opList) const;71 void RemoveOps(Function& function, std::vector<Operation*>& opList) const;
73 void UpdateForRedundantAssemble(Operation& op);72 void UpdateForRedundantAssemble(Operation& op);
74 void UpdateForRedundantView(Operation& op, Operation& consumer);73 void UpdateForRedundantView(Operation& op, Operation& consumer);
74+ void EraseRedundantViewOp(Function& function);
75 int64_t GCD(int64_t x, int64_t y);75 int64_t GCD(int64_t x, int64_t y);
76 Status LCM(int64_t x, int64_t y, int64_t& lcm);76 Status LCM(int64_t x, int64_t y, int64_t& lcm);
77 Status CalLcmShape(const Shape& toShape, const Shape& fromShape, Shape& lcmShape);77 Status CalLcmShape(const Shape& toShape, const Shape& fromShape, Shape& lcmShape);
@@ -87,31 +87,37 @@ private:
87 LogicalTensors& tensors) const;87 LogicalTensors& tensors) const;
88 bool IsTensorCoveredByTile(const Offset& tensorOffset, const Shape& tensorShape, const Offset& tileOffset,88 bool IsTensorCoveredByTile(const Offset& tensorOffset, const Shape& tensorShape, const Offset& tileOffset,
89 const Shape& tileShape) const;89 const Shape& tileShape) const;
90- void CreateOpFor1toM(Function& function, LogicalTensorPtr largeTensor, Shape lcmTileShape, Offset lcmTileOffset,90+ void CreateOpFor1toM(Function& function, const LogicalTensorPtr& largeTensor, const Shape& lcmTileShape,
91- LogicalTensors overlaps, LogicalTensors dualOverlaps);91+ const Offset& lcmTileOffset, const LogicalTensors& overlaps,
92- void ExtractDualOverlapTiles(Function& function, LogicalTensorPtr largeTensor, const LogicalTensors& dualOverlaps,92+ const LogicalTensors& dualOverlaps);
93- LogicalTensors& dualOverlapTiles, LogicalTensors& filteredDualOverlaps);93+ void ExtractDualOverlapTiles(Function& function, const LogicalTensorPtr& largeTensor,
94- bool HasIntersectionWithAnyDualOverlap(LogicalTensorPtr overlapTile, const LogicalTensors& dualOverlapTiles);94+ const LogicalTensors& dualOverlaps,
95- void FilterOverlaps(Function& function, LogicalTensorPtr largeTensor, LogicalTensors& overlaps,95+ std::vector<std::pair<Offset, Shape>>& dualOverlapTileInfos,
96+ LogicalTensors& filteredDualOverlaps);
97+ bool HasIntersectionWithAnyDualOverlap(const Offset& overlapOffset, const Shape& overlapShape,
98+ const std::vector<std::pair<Offset, Shape>>& dualOverlapTileInfos);
99+ void FilterOverlaps(Function& function, const LogicalTensorPtr& largeTensor, LogicalTensors& overlaps,
96 const LogicalTensors& dualOverlaps);100 const LogicalTensors& dualOverlaps);
97- void CreateOpForMtoM(Function& function, LogicalTensorPtr largeTensor, Shape lcmTileShape, Offset lcmTileOffset,101+ void CreateOpForMtoM(Function& function, const LogicalTensorPtr& largeTensor, const Shape& lcmTileShape,
98- LogicalTensors overlaps, LogicalTensors dualOverlaps);102+ const Offset& lcmTileOffset, const LogicalTensors& overlaps,
99- void MoreSplit(Function& function, LogicalTensorPtr largeTensor, LogicalTensors overlaps,103+ const LogicalTensors& dualOverlaps);
100- LogicalTensors dualOverlaps);104+ void MoreSplit(Function& function, const LogicalTensorPtr& largeTensor, const LogicalTensors& overlaps,
101- void CreateOpForMoreSplit(Function& function, LogicalTensorPtr largeTensor, LogicalTensors overlaps, Shape gcdShape,105+ const LogicalTensors& dualOverlaps);
102- LogicalTensorPtr dualOverlap, std::vector<Shape> gcdTileOffsets, Offset viewOpOffset);106+ void CreateOpForMoreSplit(Function& function, const LogicalTensorPtr& largeTensor, const LogicalTensors& overlaps,
103- void FindOverlapAndCreateViewOp(Function& function, LogicalTensorPtr largeTensor, const LogicalTensors& overlaps,107+ const Shape& gcdShape, const LogicalTensorPtr& dualOverlap,
104- LogicalTensorPtr newGcdTensor, const Shape& gcdTileOffsetForLarge,108+ const std::vector<Shape>& gcdTileOffsets, const Offset& viewOpOffset);
109+ void FindOverlapAndCreateViewOp(Function& function, const LogicalTensors& overlaps,
110+ const LogicalTensorPtr& newGcdTensor, const Shape& gcdTileOffsetForLarge,
105 Shape& newViewOffset);111 Shape& newViewOffset);
106 void CollectLargeTensor(Function& function);112 void CollectLargeTensor(Function& function);
107 void SplitLargeTensor(Function& function);113 void SplitLargeTensor(Function& function);
108- bool IsBeCovered(Function& function, LogicalTensorPtr largeTensor,114+ bool IsBeCovered(Function& function, const LogicalTensorPtr& largeTensor,
109- std::vector<std::pair<LogicalTensorPtr, Offset>> toTensorInfos);115+ const std::vector<std::pair<LogicalTensorPtr, Offset>>& toTensorInfos);
110- bool HasDuplicateToTile(std::vector<std::pair<LogicalTensorPtr, Offset>> toTensorInfos);116+ bool HasDuplicateToTile(const std::vector<std::pair<LogicalTensorPtr, Offset>>& toTensorInfos);
111 Shape AdjustLcmTileShapeForTailBlock(const Shape& lcmShape, const Shape& tileOffset,117 Shape AdjustLcmTileShapeForTailBlock(const Shape& lcmShape, const Shape& tileOffset,
112 const LogicalTensorPtr& largeTensor);118 const LogicalTensorPtr& largeTensor);
113 bool CheckOverlapCoverage(const LogicalTensors& overlaps, const Shape& lcmTileShape);119 bool CheckOverlapCoverage(const LogicalTensors& overlaps, const Shape& lcmTileShape);
114- void ProcessTileSplit(Function& function, LogicalTensorPtr largeTensor, const Shape& lcmTileShape,120+ void ProcessTileSplit(Function& function, const LogicalTensorPtr& largeTensor, const Shape& lcmTileShape,
115 const Shape& tileOffset, const OverlapSearchIndex& toIndex,121 const Shape& tileOffset, const OverlapSearchIndex& toIndex,
116 const OverlapSearchIndex& fromIndex, LogicalTensors& overlaps, LogicalTensors& dualOverlaps);122 const OverlapSearchIndex& fromIndex, LogicalTensors& overlaps, LogicalTensors& dualOverlaps);
117 void TryToSplitLargeTensor(Function& function, const Shape& lcmShape, const LogicalTensorPtr& largeTensor);123 void TryToSplitLargeTensor(Function& function, const Shape& lcmShape, const LogicalTensorPtr& largeTensor);
@@ -80,13 +80,13 @@ void SplitRawTensor::UpdateConsumerView(Function& function, const LogicalTensorP
80 /* 1. 更新View相关的属性 */80 /* 1. 更新View相关的属性 */
81 TensorOffset tensorOffset = logicalTensor->GetTensorOffset();81 TensorOffset tensorOffset = logicalTensor->GetTensorOffset();
82 for (const auto& viewOp : logicalTensor->GetConsumers()) {82 for (const auto& viewOp : logicalTensor->GetConsumers()) {
83- if (viewOp->GetOpcode() != Opcode::OP_VIEW) {83+ if (!IsViewLike(viewOp->GetOpcode())) {
84 continue;84 continue;
85 }85 }
86 auto& output = viewOp->oOperand[0];86 auto& output = viewOp->oOperand[0];
87 if (function.IsFromOutCast(output)) {87 if (function.IsFromOutCast(output)) {
88 APASS_LOG_WARN_F(Elements::Tensor,88 APASS_LOG_WARN_F(Elements::Tensor,
89- "OP_VIEW oOperand tensor[%d] is outCast; Please check if it is an external output.",89+ "View-like op oOperand tensor[%d] is outCast; Please check if it is an external output.",
90 output->GetMagic());90 output->GetMagic());
91 continue;91 continue;
92 }92 }
@@ -105,7 +105,7 @@ void SplitRawTensor::UpdateConsumerView(Function& function, const LogicalTensorP
105 }105 }
106 }106 }
107 }107 }
108- APASS_LOG_DEBUG_F(Elements::Operation, "Update View op needs fromOffset: %d.", viewOp->GetOpMagic());108+ APASS_LOG_DEBUG_F(Elements::Operation, "Update View-like op needs fromOffset: %d.", viewOp->GetOpMagic());
109 }109 }
110}110}
111 111 
@@ -117,13 +117,13 @@ void SplitRawTensor::UpdateProducerAssemble(Function& function, const LogicalTen
117 // Assemble2 ->117 // Assemble2 ->
118 TensorOffset tensorOffset = logicalTensor->GetTensorOffset();118 TensorOffset tensorOffset = logicalTensor->GetTensorOffset();
119 for (const auto& assembleOp : logicalTensor->GetProducers()) {119 for (const auto& assembleOp : logicalTensor->GetProducers()) {
120- if (assembleOp->GetOpcode() != Opcode::OP_ASSEMBLE) {120+ if (!IsAssembleLike(assembleOp->GetOpcode())) {
121 continue;121 continue;
122 }122 }
123 auto& input = assembleOp->iOperand[0];123 auto& input = assembleOp->iOperand[0];
124 if (function.IsFromInCast(input)) {124 if (function.IsFromInCast(input)) {
125 APASS_LOG_WARN_F(Elements::Operation,125 APASS_LOG_WARN_F(Elements::Operation,
126- "OP_ASSEMBLE iOperand tensor[%d] is inCast; Please check if it is an external input.",126+ "Assemble-like op iOperand tensor[%d] is inCast; Please check if it is an external input.",
127 input->GetMagic());127 input->GetMagic());
128 continue;128 continue;
129 }129 }
@@ -142,7 +142,7 @@ void SplitRawTensor::UpdateProducerAssemble(Function& function, const LogicalTen
142 }142 }
143 }143 }
144 }144 }
145- APASS_LOG_DEBUG_F(Elements::Operation, "Update Assemble op needs toOffset: %d.", assembleOp->GetOpMagic());145+ APASS_LOG_DEBUG_F(Elements::Operation, "Update Assemble-like op needs toOffset: %d.", assembleOp->GetOpMagic());
146 }146 }
147}147}
148 148 
@@ -52,6 +52,20 @@ std::string GetStr(const std::vector<SymbolicScalar>& vec)
52 }52 }
53 return "{" + ret + "}";53 return "{" + ret + "}";
54}54}
55+ 
56+Opcode InferAssembleOpcode(const Operation* originOp)
57+{
58+ if (originOp == nullptr) {
59+ APASS_LOG_WARN_F(Elements::Operation, "Origin assemble-family op is nullptr, fallback to OP_ASSEMBLE.");
60+ return Opcode::OP_ASSEMBLE;
61+ }
62+ if (!IsAssembleLike(originOp->GetOpcode())) {
63+ APASS_LOG_WARN_F(Elements::Operation, "Origin op[%d] is not assemble-family, fallback to OP_ASSEMBLE.",
64+ originOp->GetOpMagic());
65+ return Opcode::OP_ASSEMBLE;
66+ }
67+ return originOp->GetOpcode();
68+}
55} // namespace69} // namespace
56 70 
57Status SplitReshape::RunOnFunction(Function& function)71Status SplitReshape::RunOnFunction(Function& function)
@@ -355,32 +369,6 @@ std::vector<int64_t> SplitReshape::ObtainMapOffset(const LogicalTensorPtr& input
355 return it->second;369 return it->second;
356}370}
357 371 
358-bool SplitReshape::HasAssembleInputProducedByReduceAcc(const LogicalTensorPtr& reshapeSource,
359- int& assembleOpMagic) const
360-{
361- if (reshapeSource == nullptr || reshapeSource->GetRawTensor() == nullptr) {
362- return false;
363- }
364- auto it = assembleOutToInput_.find(reshapeSource->GetRawTensor()->GetRawMagic());
365- if (it == assembleOutToInput_.end()) {
366- return false;
367- }
368- for (const auto& input : it->second) {
369- if (input == nullptr) {
370- continue;
371- }
372- const bool hasReduceAccProducer = std::any_of(
373- input->GetProducers().begin(), input->GetProducers().end(),
374- [](const auto* producer) { return producer != nullptr && producer->GetOpcode() == Opcode::OP_REDUCE_ACC; });
375- if (hasReduceAccProducer) {
376- auto assembleIt = assembleOpPtrs_.find({input->GetMagic(), reshapeSource->GetMagic()});
377- assembleOpMagic = assembleIt == assembleOpPtrs_.end() ? -1 : assembleIt->second->GetOpMagic();
378- return true;
379- }
380- }
381- return false;
382-}
383- 
384Status SplitReshape::CollectReshapeInfo(const Operation& op)372Status SplitReshape::CollectReshapeInfo(const Operation& op)
385{373{
386 auto input = op.GetIOperands().front();374 auto input = op.GetIOperands().front();
@@ -447,7 +435,7 @@ Status SplitReshape::CollectCopyOut(Function& function)
447 if (op.GetOpcode() == Opcode::OP_RESHAPE && CollectReshapeInfo(op) != SUCCESS) {435 if (op.GetOpcode() == Opcode::OP_RESHAPE && CollectReshapeInfo(op) != SUCCESS) {
448 return FAILED;436 return FAILED;
449 }437 }
450- if (op.GetOpcode() == Opcode::OP_ASSEMBLE && CollectAssembleInfo(op) != SUCCESS) {438+ if (IsAssembleLike(op.GetOpcode()) && CollectAssembleInfo(op) != SUCCESS) {
451 return FAILED;439 return FAILED;
452 }440 }
453 }441 }
@@ -1165,6 +1153,34 @@ Status SplitReshape::UpdateReshapeOp(Function& function, Operation& op, const Ov
1165 return SUCCESS;1153 return SUCCESS;
1166}1154}
1167 1155 
1156+bool SplitReshape::HasAssembleLikeInputProducedByReduceAcc(const LogicalTensorPtr& reshapeSource,
1157+ int& assembleLikeOpMagic) const
1158+{
1159+ if (reshapeSource == nullptr || reshapeSource->GetRawTensor() == nullptr) {
1160+ return false;
1161+ }
1162+ // assembleOutToInput_ 由 CollectAssembleInfo 填充,其门控 CollectCopyOut 已用 IsAssembleLike,
1163+ // 故 OP_ASSEMBLE 与 OP_CONTRACT 均已记录,本函数天然覆盖 reduce_acc-contract-reshape 场景。
1164+ auto it = assembleOutToInput_.find(reshapeSource->GetRawTensor()->GetRawMagic());
1165+ if (it == assembleOutToInput_.end()) {
1166+ return false;
1167+ }
1168+ for (const auto& input : it->second) {
1169+ if (input == nullptr) {
1170+ continue;
1171+ }
1172+ const bool hasReduceAccProducer = std::any_of(
1173+ input->GetProducers().begin(), input->GetProducers().end(),
1174+ [](const auto* producer) { return producer != nullptr && producer->GetOpcode() == Opcode::OP_REDUCE_ACC; });
1175+ if (hasReduceAccProducer) {
1176+ auto assembleIt = assembleOpPtrs_.find({input->GetMagic(), reshapeSource->GetMagic()});
1177+ assembleLikeOpMagic = assembleIt == assembleOpPtrs_.end() ? -1 : assembleIt->second->GetOpMagic();
1178+ return true;
1179+ }
1180+ }
1181+ return false;
1182+}
1183+ 
1168Status SplitReshape::CheckReshapeSkip(const LogicalTensorPtr& input, const LogicalTensorPtr& output,1184Status SplitReshape::CheckReshapeSkip(const LogicalTensorPtr& input, const LogicalTensorPtr& output,
1169 CheckOutputParam& checkOutputParam)1185 CheckOutputParam& checkOutputParam)
1170{1186{
@@ -1181,30 +1197,31 @@ Status SplitReshape::CheckReshapeSkip(const LogicalTensorPtr& input, const Logic
1181 return WARNING;1197 return WARNING;
1182 }1198 }
1183 checkOutputParam.reshapeSource = reshapeSourceIter->second;1199 checkOutputParam.reshapeSource = reshapeSourceIter->second;
1184- int assembleOpMagic = -1;1200+ int assembleLikeOpMagic = -1;
1185- if (HasAssembleInputProducedByReduceAcc(checkOutputParam.reshapeSource, assembleOpMagic)) {1201+ if (HasAssembleLikeInputProducedByReduceAcc(checkOutputParam.reshapeSource, assembleLikeOpMagic)) {
1186- APASS_LOG_DEBUG_F(1202+ APASS_LOG_DEBUG_F(Elements::Tensor,
1187- Elements::Tensor,1203+ "Skip splitreshape because one assemble-like input is produced by ReduceAcc, op magic is %d.",
1188- "Skip splitreshape because one assemble input is produced by ReduceAcc, assemble op magic is %d.",1204+ assembleLikeOpMagic);
1189- assembleOpMagic);
1190 return WARNING;1205 return WARNING;
1191 }1206 }
1192- size_t assembleProducerCount = 0;1207+ size_t assembleLikeProducerCount = 0;
1193 for (const auto& producer : checkOutputParam.reshapeSource->GetProducers()) {1208 for (const auto& producer : checkOutputParam.reshapeSource->GetProducers()) {
1194- if (producer != nullptr && producer->GetOpcode() == Opcode::OP_ASSEMBLE) {1209+ if (producer != nullptr && IsAssembleLike(producer->GetOpcode())) {
1195- ++assembleProducerCount;1210+ ++assembleLikeProducerCount;
1196 }1211 }
1197 }1212 }
1198- if (assembleProducerCount <= 1) {1213+ if (assembleLikeProducerCount <= 1) {
1199- APASS_LOG_DEBUG_F(Elements::Tensor, "Skip splitreshape because reshape source has only one assemble producer.");1214+ APASS_LOG_DEBUG_F(Elements::Tensor,
1215+ "Skip splitreshape because reshape source has only one assemble-like producer.");
1200 return WARNING;1216 return WARNING;
1201 }1217 }
1202 for (const auto& consumer : input->GetConsumers()) {1218 for (const auto& consumer : input->GetConsumers()) {
1203 if (consumer == nullptr) {1219 if (consumer == nullptr) {
1204 continue;1220 continue;
1205 }1221 }
1206- if (consumer->GetOpcode() != Opcode::OP_VIEW) {1222+ if (!IsViewLike(consumer->GetOpcode())) {
1207- APASS_LOG_DEBUG_F(Elements::Tensor, "Skip splitreshape because reshape output has non-view consumers.");1223+ APASS_LOG_DEBUG_F(Elements::Tensor,
1224+ "Skip splitreshape because reshape output has non-view-like consumers.");
1208 return WARNING;1225 return WARNING;
1209 }1226 }
1210 }1227 }
@@ -1223,9 +1240,8 @@ Status SplitReshape::CheckReshapeSkip(const LogicalTensorPtr& input, const Logic
1223Status SplitReshape::CheckValidOp(const CheckParam& para, CheckOutputParam& checkOutputParam)1240Status SplitReshape::CheckValidOp(const CheckParam& para, CheckOutputParam& checkOutputParam)
1224{1241{
1225 auto input = para.input;1242 auto input = para.input;
1226- auto output = para.output;
1227 auto inputView = para.inputView;1243 auto inputView = para.inputView;
1228- if (CheckReshapeSkip(input, output, checkOutputParam) == WARNING) {1244+ if (CheckReshapeSkip(input, para.output, checkOutputParam) == WARNING) {
1229 return WARNING;1245 return WARNING;
1230 }1246 }
1231 const int inputRawMagic = input->GetRawTensor()->GetRawMagic();1247 const int inputRawMagic = input->GetRawTensor()->GetRawMagic();
@@ -1339,7 +1355,7 @@ Status SplitReshape::CheckOp(Function& function, Operation& op)
1339Status SplitReshape::CheckCopyIn(Function& function)1355Status SplitReshape::CheckCopyIn(Function& function)
1340{1356{
1341 for (auto& op : function.Operations(false)) {1357 for (auto& op : function.Operations(false)) {
1342- if (op.GetOpcode() != Opcode::OP_VIEW) {1358+ if (!IsViewLike(op.GetOpcode())) {
1343 continue;1359 continue;
1344 }1360 }
1345 if (CheckOp(function, op) == FAILED) {1361 if (CheckOp(function, op) == FAILED) {
@@ -1381,7 +1397,8 @@ Status SplitReshape::AddAssembleOp(const MemoryType& memoryType, const std::vect
1381 const LogicalTensorPtr& input, const LogicalTensorPtr& output,1397 const LogicalTensorPtr& input, const LogicalTensorPtr& output,
1382 const Operation* originOp)1398 const Operation* originOp)
1383{1399{
1384- assembles_.emplace_back(AssembleOp{memoryType, outputOffset, input, output, originOp});1400+ assembles_.emplace_back(
1401+ AssembleOp{memoryType, outputOffset, input, output, originOp, InferAssembleOpcode(originOp)});
1385 auto iter = reshapeOffset_.find(output);1402 auto iter = reshapeOffset_.find(output);
1386 if (iter == reshapeOffset_.end()) {1403 if (iter == reshapeOffset_.end()) {
1387 reshapeOffset_[output] = outputOffset;1404 reshapeOffset_[output] = outputOffset;
@@ -1442,11 +1459,10 @@ Status SplitReshape::AddOperation(Function& function)
1442 return FAILED;1459 return FAILED;
1443 }1460 }
1444 auto& newCopyOut = GraphUtils::AddAssembleOperation(function, a, {dynValidShape});1461 auto& newCopyOut = GraphUtils::AddAssembleOperation(function, a, {dynValidShape});
1445- APASS_LOG_INFO_F(1462+ APASS_LOG_INFO_F(Elements::Operation,
1446- Elements::Operation,1463+ "ADD %s, magic %d, IOperand tensor magic %d OOperand tensor magic %d, dynValidShape %s.",
1447- "ADD OP_ASSEMBLE, magic %d, IOperand tensor magic %d OOperand tensor magic %d, dynValidShape %s.",1464+ newCopyOut.GetOpcodeStr().c_str(), newCopyOut.opmagic, a.input->GetMagic(),
1448- newCopyOut.opmagic, a.input->GetMagic(), a.output->GetMagic(),1465+ a.output->GetMagic(), GetStr(a.output->GetDynValidShape()).c_str());
1449- GetStr(a.output->GetDynValidShape()).c_str());
1450 }1466 }
1451 for (const auto& b : reshapes_) {1467 for (const auto& b : reshapes_) {
1452 dynValidShape.clear();1468 dynValidShape.clear();
@@ -1468,7 +1484,7 @@ Status SplitReshape::AddOperation(Function& function)
1468Status SplitReshape::SetMemoryType(Function& function)1484Status SplitReshape::SetMemoryType(Function& function)
1469{1485{
1470 for (const auto& op : function.Operations(false)) {1486 for (const auto& op : function.Operations(false)) {
1471- if (op.GetOpcode() != Opcode::OP_VIEW) {1487+ if (!IsViewLike(op.GetOpcode())) {
1472 continue;1488 continue;
1473 }1489 }
1474 for (const auto consumerOp : op.ConsumerOps()) {1490 for (const auto consumerOp : op.ConsumerOps()) {
@@ -182,7 +182,7 @@ private:
182 unsigned long ComputeReshapeHash(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;182 unsigned long ComputeReshapeHash(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
183 unsigned long ComputeReshapeHashOrderless(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;183 unsigned long ComputeReshapeHashOrderless(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
184 std::vector<int64_t> ObtainMapOffset(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;184 std::vector<int64_t> ObtainMapOffset(const LogicalTensorPtr& input, const LogicalTensorPtr& output) const;
185- bool HasAssembleInputProducedByReduceAcc(const LogicalTensorPtr& reshapeSource, int& assembleOpMagic) const;185+ bool HasAssembleLikeInputProducedByReduceAcc(const LogicalTensorPtr& reshapeSource, int& assembleLikeOpMagic) const;
186 186 
187 Status AddAssembleOp(const MemoryType& memoryType, const std::vector<int64_t>& outputOffset,187 Status AddAssembleOp(const MemoryType& memoryType, const std::vector<int64_t>& outputOffset,
188 const LogicalTensorPtr& input, const LogicalTensorPtr& output, const Operation* originOp);188 const LogicalTensorPtr& input, const LogicalTensorPtr& output, const Operation* originOp);
@@ -16,6 +16,7 @@
16#include "l1_copy_reuse.h"16#include "l1_copy_reuse.h"
17#include <algorithm>17#include <algorithm>
18 18 
19+#include "interface/configs/config_manager_ng.h"
19#include "interface/tensor/irbuilder.h"20#include "interface/tensor/irbuilder.h"
20#include "passes/pass_utils/pass_utils.h"21#include "passes/pass_utils/pass_utils.h"
21 22 
@@ -103,7 +104,7 @@ inline std::vector<uint64_t> GetGMInputFeature(const Operation& op)
103 }104 }
104 std::vector<uint64_t> vec = {static_cast<uint64_t>(ioperand->GetRawTensor()->GetRawMagic())};105 std::vector<uint64_t> vec = {static_cast<uint64_t>(ioperand->GetRawTensor()->GetRawMagic())};
105 std::vector<OpImmediate> opImmList;106 std::vector<OpImmediate> opImmList;
106- if (op.GetOpcode() == Opcode::OP_VIEW) {107+ if (op.GetOpcode() == config::GetSliceOpcode()) {
107 std::shared_ptr<ViewOpAttribute> attr = std::static_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());108 std::shared_ptr<ViewOpAttribute> attr = std::static_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());
108 opImmList = OpImmediate::Specified(attr->GetFromTensorOffset());109 opImmList = OpImmediate::Specified(attr->GetFromTensorOffset());
109 } else if (op.GetOpcode() == Opcode::OP_CONVERT) {110 } else if (op.GetOpcode() == Opcode::OP_CONVERT) {
@@ -134,7 +135,7 @@ bool L1CopyInReuseRunner::CanReuse(const Operation& op)
134{135{
135 if (op.GetIOperands().size() != 0 && op.GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR &&136 if (op.GetIOperands().size() != 0 && op.GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR &&
136 op.GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1) {137 op.GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1) {
137- if (op.GetOpcode() == Opcode::OP_VIEW || op.GetOpcode() == Opcode::OP_CONVERT) {138+ if (op.GetOpcode() == config::GetSliceOpcode() || op.GetOpcode() == Opcode::OP_CONVERT) {
138 return true;139 return true;
139 }140 }
140 }141 }
@@ -1116,7 +1117,8 @@ Status L1CopyInReuseRunner::Run(Function& func, int color, std::vector<std::vect
1116void L1CopyInReuseRunner::RemoveUselessViews(Function& func) const1117void L1CopyInReuseRunner::RemoveUselessViews(Function& func) const
1117{1118{
1118 for (auto& op : func.Operations(false)) {1119 for (auto& op : func.Operations(false)) {
1119- if (op.GetOpcode() == Opcode::OP_VIEW && op.GetIOperands().size() == 1 && op.GetOOperands().size() == 1) {1120+ if (op.GetOpcode() == config::GetSliceOpcode() && op.GetIOperands().size() == 1 &&
1121+ op.GetOOperands().size() == 1) {
1120 auto input = op.GetIOperands()[0];1122 auto input = op.GetIOperands()[0];
1121 auto output = op.GetOOperands()[0];1123 auto output = op.GetOOperands()[0];
1122 if (func.IsFromInCast(input) || func.IsFromOutCast(output)) {1124 if (func.IsFromInCast(input) || func.IsFromOutCast(output)) {
@@ -1180,7 +1182,8 @@ Status L1CopyInReuseMerge::CheckOpListValid(Function& func) const
1180 if (opOriList[i].GetIOperands().size() != 0 &&1182 if (opOriList[i].GetIOperands().size() != 0 &&
1181 opOriList[i].GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR &&1183 opOriList[i].GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_DEVICE_DDR &&
1182 opOriList[i].GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1) {1184 opOriList[i].GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1) {
1183- if (opOriList[i].GetOpcode() == Opcode::OP_VIEW || opOriList[i].GetOpcode() == Opcode::OP_CONVERT ||1185+ if (opOriList[i].GetOpcode() == config::GetSliceOpcode() ||
1186+ opOriList[i].GetOpcode() == Opcode::OP_CONVERT ||
1184 opOriList[i].GetOpcode() == Opcode::OP_L1_COPY_IN_CONV) {1187 opOriList[i].GetOpcode() == Opcode::OP_L1_COPY_IN_CONV) {
1185 // 符合预期且合法1188 // 符合预期且合法
1186 continue;1189 continue;
@@ -97,7 +97,7 @@ void ReduceCopyMerge::CombineForkSubgraph(Function& function, MergeInput& mergeI
97 std::unordered_map<int, std::unordered_set<int>> forkSubgraphsMap;97 std::unordered_map<int, std::unordered_set<int>> forkSubgraphsMap;
98 for (auto& op : function.Operations()) {98 for (auto& op : function.Operations()) {
99 std::unordered_set<int> forkSubgraphIds;99 std::unordered_set<int> forkSubgraphIds;
100- if (op.GetOpcode() == Opcode::OP_ASSEMBLE) {100+ if (IsAssembleLike(op.GetOpcode())) {
101 for (auto& prod : op.ProducerOps()) {101 for (auto& prod : op.ProducerOps()) {
102 forkSubgraphIds.insert(prod->GetSubgraphID());102 forkSubgraphIds.insert(prod->GetSubgraphID());
103 }103 }
@@ -24,7 +24,8 @@
24 24 
25namespace npu::tile_fwk {25namespace npu::tile_fwk {
26 26 
27-const std::unordered_set<Opcode> nodeScopeSkipCode{Opcode::OP_ASSEMBLE, Opcode::OP_VIEW};27+const std::unordered_set<Opcode> nodeScopeSkipCode{Opcode::OP_CONTRACT, Opcode::OP_SLICE, Opcode::OP_ASSEMBLE,
28+ Opcode::OP_VIEW};
28 29 
29uint64_t OperationGraphInfo::GetHash(const Operation* op) const30uint64_t OperationGraphInfo::GetHash(const Operation* op) const
30{31{
@@ -194,9 +195,9 @@ Status NodeGraphInfo::MergeSrcToDstIsland(const std::shared_ptr<OperationGraphIn
194 operationGraphInfo->opCoreType_[dstParent]};195 operationGraphInfo->opCoreType_[dstParent]};
195 bool isAICPUandVIEW = false;196 bool isAICPUandVIEW = false;
196 isAICPUandVIEW = isAICPUandVIEW || (operationGraphInfo->opCoreType_[src] == OpCoreType::AICPU &&197 isAICPUandVIEW = isAICPUandVIEW || (operationGraphInfo->opCoreType_[src] == OpCoreType::AICPU &&
197- operationGraphInfo->opList_[dst]->GetOpcode() == Opcode::OP_VIEW);198+ IsViewLike(operationGraphInfo->opList_[dst]->GetOpcode()));
198 isAICPUandVIEW = isAICPUandVIEW || (operationGraphInfo->opCoreType_[dst] == OpCoreType::AICPU &&199 isAICPUandVIEW = isAICPUandVIEW || (operationGraphInfo->opCoreType_[dst] == OpCoreType::AICPU &&
199- operationGraphInfo->opList_[src]->GetOpcode() == Opcode::OP_VIEW);200+ IsViewLike(operationGraphInfo->opList_[src]->GetOpcode()));
200 bool isAICPUandAssemble = false;201 bool isAICPUandAssemble = false;
201 // HUB只能和View/Assemble在一张子图中202 // HUB只能和View/Assemble在一张子图中
202 bool hubWithViewAssemble = false;203 bool hubWithViewAssemble = false;
@@ -207,16 +208,16 @@ Status NodeGraphInfo::MergeSrcToDstIsland(const std::shared_ptr<OperationGraphIn
207 auto srcOpCode = operationGraphInfo->opList_[src]->GetOpcode();208 auto srcOpCode = operationGraphInfo->opList_[src]->GetOpcode();
208 auto dstOpCode = operationGraphInfo->opList_[dst]->GetOpcode();209 auto dstOpCode = operationGraphInfo->opList_[dst]->GetOpcode();
209 if (srcOpCoreType != OpCoreType::HUB) {210 if (srcOpCoreType != OpCoreType::HUB) {
210- hubWithViewAssemble = (srcOpCode == Opcode::OP_VIEW || srcOpCode == Opcode::OP_ASSEMBLE);211+ hubWithViewAssemble = IsViewLike(srcOpCode) || IsAssembleLike(srcOpCode);
211 }212 }
212 if (dstOpCoreType != OpCoreType::HUB) {213 if (dstOpCoreType != OpCoreType::HUB) {
213- hubWithViewAssemble = (dstOpCode == Opcode::OP_VIEW || dstOpCode == Opcode::OP_ASSEMBLE);214+ hubWithViewAssemble = IsViewLike(dstOpCode) || IsAssembleLike(dstOpCode);
214 }215 }
215 }216 }
216 isAICPUandAssemble = isAICPUandAssemble || (operationGraphInfo->opCoreType_[src] == OpCoreType::AICPU &&217 isAICPUandAssemble = isAICPUandAssemble || (operationGraphInfo->opCoreType_[src] == OpCoreType::AICPU &&
217- operationGraphInfo->opList_[dst]->GetOpcode() == Opcode::OP_ASSEMBLE);218+ IsAssembleLike(operationGraphInfo->opList_[dst]->GetOpcode()));
218 isAICPUandAssemble = isAICPUandAssemble || (operationGraphInfo->opCoreType_[dst] == OpCoreType::AICPU &&219 isAICPUandAssemble = isAICPUandAssemble || (operationGraphInfo->opCoreType_[dst] == OpCoreType::AICPU &&
219- operationGraphInfo->opList_[src]->GetOpcode() == Opcode::OP_ASSEMBLE);220+ IsAssembleLike(operationGraphInfo->opList_[src]->GetOpcode()));
220 if ((!hubWithViewAssemble) && (!isAICPUandVIEW) && (!isAICPUandAssemble) &&221 if ((!hubWithViewAssemble) && (!isAICPUandVIEW) && (!isAICPUandAssemble) &&
221 (!operationGraphInfo->CoreTypeMergeable(coreTypes))) {222 (!operationGraphInfo->CoreTypeMergeable(coreTypes))) {
222 APASS_LOG_ERROR_F(Elements::Operation,223 APASS_LOG_ERROR_F(Elements::Operation,
@@ -364,7 +365,7 @@ bool NodeGraphInfo::CheckScopeNotMergeable(Operation& op)
364 365 
365bool NodeGraphInfo::CheckUbToUbWithDynOffset(Operation& op)366bool NodeGraphInfo::CheckUbToUbWithDynOffset(Operation& op)
366{367{
367- if (op.GetOpcode() != Opcode::OP_VIEW && op.GetOpcode() != Opcode::OP_ASSEMBLE) {368+ if (!IsViewLike(op.GetOpcode()) && !IsAssembleLike(op.GetOpcode())) {
368 return false;369 return false;
369 }370 }
370 371 
@@ -381,12 +382,12 @@ bool NodeGraphInfo::CheckUbToUbWithDynOffset(Operation& op)
381 }382 }
382 383 
383 bool hasDynOffset = false;384 bool hasDynOffset = false;
384- if (op.GetOpcode() == Opcode::OP_VIEW) {385+ if (IsViewLike(op.GetOpcode())) {
385 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());386 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());
386 if (viewAttr && !viewAttr->GetFromDynOffset().empty()) {387 if (viewAttr && !viewAttr->GetFromDynOffset().empty()) {
387 hasDynOffset = true;388 hasDynOffset = true;
388 }389 }
389- } else if (op.GetOpcode() == Opcode::OP_ASSEMBLE) {390+ } else if (IsAssembleLike(op.GetOpcode())) {
390 auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());391 auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());
391 if (assembleAttr && !assembleAttr->GetToDynOffset().empty()) {392 if (assembleAttr && !assembleAttr->GetToDynOffset().empty()) {
392 hasDynOffset = true;393 hasDynOffset = true;
@@ -405,14 +406,14 @@ bool NodeGraphInfo::CheckUbToUbWithDynOffset(Operation& op)
405 406 
406bool NodeGraphInfo::CheckViewAssembleOffset(Operation& op)407bool NodeGraphInfo::CheckViewAssembleOffset(Operation& op)
407{408{
408- if (op.GetOpcode() != Opcode::OP_VIEW && op.GetOpcode() != Opcode::OP_ASSEMBLE) {409+ if (!IsViewLike(op.GetOpcode()) && !IsAssembleLike(op.GetOpcode())) {
409 return false;410 return false;
410 }411 }
411 412 
412 std::string offsetStr;413 std::string offsetStr;
413 std::string dynOffsetStr;414 std::string dynOffsetStr;
414 415 
415- if (op.GetOpcode() == Opcode::OP_VIEW) {416+ if (IsViewLike(op.GetOpcode())) {
416 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());417 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());
417 if (!viewAttr) {418 if (!viewAttr) {
418 return false;419 return false;
@@ -425,7 +426,7 @@ bool NodeGraphInfo::CheckViewAssembleOffset(Operation& op)
425 for (auto& val : fromDynOffset) {426 for (auto& val : fromDynOffset) {
426 dynOffsetStr += val.Dump() + ",";427 dynOffsetStr += val.Dump() + ",";
427 }428 }
428- } else if (op.GetOpcode() == Opcode::OP_ASSEMBLE) {429+ } else if (IsAssembleLike(op.GetOpcode())) {
429 auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());430 auto assembleAttr = std::dynamic_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());
430 if (!assembleAttr) {431 if (!assembleAttr) {
431 return false;432 return false;
@@ -601,9 +602,8 @@ Status SuperNodeGraphBuilder::BuildOpGraph(const std::vector<Operation*>& opList
601 602 
602inline bool IsL0cToL1MoveOp(Operation* op)603inline bool IsL0cToL1MoveOp(Operation* op)
603{604{
604- return (op->GetOpcode() == Opcode::OP_VIEW || op->GetOpcode() == Opcode::OP_ASSEMBLE) &&605+ return (IsViewLike(op->GetOpcode()) || IsAssembleLike(op->GetOpcode())) && op->GetOOperands().size() > 0 &&
605- op->GetOOperands().size() > 0 && op->GetIOperands().size() > 0 &&606+ op->GetIOperands().size() > 0 && op->GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L0C &&
606- op->GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L0C &&
607 op->GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1;607 op->GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1;
608}608}
609 609 
@@ -628,7 +628,7 @@ bool SuperNodeGraphBuilder::L1CopyInCombine(const std::shared_ptr<OperationGraph
628 }628 }
629 if (IsL0cToL1MoveOp(opList[i])) {629 if (IsL0cToL1MoveOp(opList[i])) {
630 for (auto outNode : operationInfo->outGraph_[i]) {630 for (auto outNode : operationInfo->outGraph_[i]) {
631- if (opList[i]->GetOpcode() == Opcode::OP_ASSEMBLE && IsCubeLocalLoad(opList[outNode])) {631+ if (IsAssembleLike(opList[i]->GetOpcode()) && IsCubeLocalLoad(opList[outNode])) {
632 continue;632 continue;
633 }633 }
634 mergePair.emplace_back(outNode, i);634 mergePair.emplace_back(outNode, i);
@@ -702,7 +702,7 @@ bool SuperNodeGraphBuilder::AssembleCombine(const std::shared_ptr<OperationGraph
702 return false;702 return false;
703 }703 }
704 // assemble 特殊处理, assemble到local tensor,需要将这些assemble统一island704 // assemble 特殊处理, assemble到local tensor,需要将这些assemble统一island
705- if (opList[i]->GetOpcode() == Opcode::OP_ASSEMBLE) {705+ if (IsAssembleLike(opList[i]->GetOpcode())) {
706 if (opList[i]->GetOOperands().empty()) {706 if (opList[i]->GetOOperands().empty()) {
707 return false;707 return false;
708 }708 }
@@ -783,7 +783,7 @@ bool SuperNodeGraphBuilder::MulAccCombine(const std::shared_ptr<OperationGraphIn
783 }783 }
784 }784 }
785 for (auto outOp : operationInfo->outGraph_[i]) {785 for (auto outOp : operationInfo->outGraph_[i]) {
786- if (opList[outOp]->GetOpcode() == Opcode::OP_VIEW && !opList[outOp]->GetOOperands().empty() &&786+ if (IsViewLike(opList[outOp]->GetOpcode()) && !opList[outOp]->GetOOperands().empty() &&
787 opList[outOp]->GetOOperands().front()->GetMemoryTypeOriginal() == MemoryType::MEM_L0C) {787 opList[outOp]->GetOOperands().front()->GetMemoryTypeOriginal() == MemoryType::MEM_L0C) {
788 mergePair.emplace_back(i, outOp);788 mergePair.emplace_back(i, outOp);
789 APASS_LOG_DEBUG_F(Elements::Operation, "Combine MatMul %d and View %d in building SuperNode.",789 APASS_LOG_DEBUG_F(Elements::Operation, "Combine MatMul %d and View %d in building SuperNode.",
@@ -860,12 +860,12 @@ inline bool FindScopeFromConsumers(Operation* op, Operation::ScopeInfo& foundSco
860 860 
861inline void PropagateScopeInfo(std::vector<Operation*>& opList)861inline void PropagateScopeInfo(std::vector<Operation*>& opList)
862{862{
863- // ASSEMBLE inherits scope from producers, VIEW from consumers.863+ // Assemble-like ops inherit scope from producers, view-like ops from consumers.
864 // Pending list is in topological order; reversing deferred before retry864 // Pending list is in topological order; reversing deferred before retry
865- // resolves VIEW chains (tail-first) in one additional pass.865+ // resolves view-like chains (tail-first) in one additional pass.
866 std::vector<Operation*> pending;866 std::vector<Operation*> pending;
867 for (Operation* op : opList) {867 for (Operation* op : opList) {
868- if (op->GetOpcode() != Opcode::OP_ASSEMBLE && op->GetOpcode() != Opcode::OP_VIEW) {868+ if (!IsAssembleLike(op->GetOpcode()) && !IsViewLike(op->GetOpcode())) {
869 continue;869 continue;
870 }870 }
871 if (op->GetScopeId() == -1) {871 if (op->GetScopeId() == -1) {
@@ -873,8 +873,8 @@ inline void PropagateScopeInfo(std::vector<Operation*>& opList)
873 continue;873 continue;
874 }874 }
875 Operation::ScopeInfo neighbourScope{};875 Operation::ScopeInfo neighbourScope{};
876- bool found = (op->GetOpcode() == Opcode::OP_ASSEMBLE) ? FindScopeFromProducers(op, neighbourScope) :876+ bool found = IsAssembleLike(op->GetOpcode()) ? FindScopeFromProducers(op, neighbourScope) :
877- FindScopeFromConsumers(op, neighbourScope);877+ FindScopeFromConsumers(op, neighbourScope);
878 if (found && neighbourScope.scopeId != op->GetScopeId()) {878 if (found && neighbourScope.scopeId != op->GetScopeId()) {
879 pending.push_back(op);879 pending.push_back(op);
880 }880 }
@@ -884,8 +884,8 @@ inline void PropagateScopeInfo(std::vector<Operation*>& opList)
884 std::vector<Operation*> deferred;884 std::vector<Operation*> deferred;
885 for (Operation* op : pending) {885 for (Operation* op : pending) {
886 Operation::ScopeInfo foundScope{};886 Operation::ScopeInfo foundScope{};
887- bool found = (op->GetOpcode() == Opcode::OP_ASSEMBLE) ? FindScopeFromProducers(op, foundScope) :887+ bool found = IsAssembleLike(op->GetOpcode()) ? FindScopeFromProducers(op, foundScope) :
888- FindScopeFromConsumers(op, foundScope);888+ FindScopeFromConsumers(op, foundScope);
889 if (found && foundScope.scopeId != op->GetScopeId()) {889 if (found && foundScope.scopeId != op->GetScopeId()) {
890 op->SetScopeInfo(foundScope);890 op->SetScopeInfo(foundScope);
891 } else if (!found) {891 } else if (!found) {
@@ -25,6 +25,7 @@
25#include <sched.h>25#include <sched.h>
26#include <algorithm>26#include <algorithm>
27#include "utils/test_cost_macro.h"27#include "utils/test_cost_macro.h"
28+#include "interface/configs/config_manager_ng.h"
28 29 
29#if defined(ENABLE_STEST)30#if defined(ENABLE_STEST)
30#include "adapter/api/runtime_api.h"31#include "adapter/api/runtime_api.h"
@@ -252,6 +253,12 @@ int main(int argc, char** argv)
252 return 0;253 return 0;
253 }254 }
254 255 
256+ // 总开关:在 root scope 上设置 enable_slice=true(覆盖 tile_fwk_config.json 的 false 默认值)
257+ // root scope 不受 config::Reset() 影响,所以 UT SetUp 中的 Clear() 不会清除该设置
258+ // 单个测试用例仍可通过 config::SetPassOption(ENABLE_SLICE, false) 覆盖此设置
259+ const std::string enableSliceKey = "pass." + std::string(npu::tile_fwk::ENABLE_SLICE);
260+ npu::tile_fwk::ConfigManagerNg::GlobalScope()->UpdateValue(enableSliceKey, true);
261+ 
255 auto ret = RUN_ALL_TESTS();262 auto ret = RUN_ALL_TESTS();
256 263 
257 // 后检查264 // 后检查
@@ -15,6 +15,7 @@
15#include <gtest/gtest.h>15#include <gtest/gtest.h>
16#include "tilefwk/tilefwk.h"16#include "tilefwk/tilefwk.h"
17#include "interface/inner/tilefwk.h"17#include "interface/inner/tilefwk.h"
18+#include "interface/configs/config_manager_ng.h"
18#include "distributed_test_framework.h"19#include "distributed_test_framework.h"
19#include "test_distributed.h"20#include "test_distributed.h"
20#include "adapter/api/hcomm_api.h"21#include "adapter/api/hcomm_api.h"
@@ -113,5 +114,9 @@ void GegisterOps()
113}114}
114 115 
115INSTANTIATE_TEST_SUITE_P(TestDistributedOps, DistributedTest, ::testing::ValuesIn(GetOpMetaData<OpMetaData>()));116INSTANTIATE_TEST_SUITE_P(TestDistributedOps, DistributedTest, ::testing::ValuesIn(GetOpMetaData<OpMetaData>()));
116-TEST_P(DistributedTest, TestOps) { RunDistributedTestGeneric(GetParam().testData_, GetParam().fileName_); }117+TEST_P(DistributedTest, TestOps)
118+{
119+ config::SetPassOption(ENABLE_SLICE, false);
120+ RunDistributedTestGeneric(GetParam().testData_, GetParam().fileName_);
121+}
117} // namespace npu::tile_fwk::Distributed122} // namespace npu::tile_fwk::Distributed
@@ -3894,8 +3894,13 @@ def _quantmx_build_exp(x_shape: tuple, rows: int, scale_group_cols: int, group_c
3894 3894 
3895 3895 
3896def _quantmx_axis_last_golden(3896def _quantmx_axis_last_golden(
3897- x: np.ndarray, src_dtype_name: str, is_fp4_e2m1: bool, is_nv: bool, use_plain_fp8_max_abs: bool, dp: dict,3897+ x: np.ndarray,
3898- impl: dict3898+ src_dtype_name: str,
3899+ is_fp4_e2m1: bool,
3900+ is_nv: bool,
3901+ use_plain_fp8_max_abs: bool,
3902+ dp: dict,
3903+ impl: dict,
3899):3904):
3900 group_size = 323905 group_size = 32
3901 grouped = _quantmx_group_input(x, group_size)3906 grouped = _quantmx_group_input(x, group_size)
@@ -3914,8 +3919,13 @@ def _quantmx_axis_last_golden(
3914 3919 
3915 3920 
3916def _quantmx_axis_dn_golden(3921def _quantmx_axis_dn_golden(
3917- x: np.ndarray, src_dtype_name: str, is_fp4_e2m1: bool, is_nv: bool, use_plain_fp8_max_abs: bool, dp: dict,3922+ x: np.ndarray,
3918- impl: dict3923+ src_dtype_name: str,
3924+ is_fp4_e2m1: bool,
3925+ is_nv: bool,
3926+ use_plain_fp8_max_abs: bool,
3927+ dp: dict,
3928+ impl: dict,
3919):3929):
3920 group_size = 323930 group_size = 32
3921 m_dim = x.shape[-2]3931 m_dim = x.shape[-2]
@@ -3931,9 +3941,7 @@ def _quantmx_axis_dn_golden(
3931 x_grouped = x_3d.reshape(prefix_rows, group_rows, group_size, n_dim)3941 x_grouped = x_3d.reshape(prefix_rows, group_rows, group_size, n_dim)
3932 x_grouped = x_grouped.transpose(0, 3, 1, 2).reshape(prefix_rows * n_dim, group_rows, group_size)3942 x_grouped = x_grouped.transpose(0, 3, 1, 2).reshape(prefix_rows * n_dim, group_rows, group_size)
3933 3943 
3934- max_source = _quantmx_golden_max_source(3944+ max_source = _quantmx_golden_max_source(x_grouped, src_dtype_name, is_fp4_e2m1, is_nv, use_plain_fp8_max_abs)
3935- x_grouped, src_dtype_name, is_fp4_e2m1, is_nv, use_plain_fp8_max_abs
3936- )
3937 max_abs = np.max(max_source, axis=2).astype(np.float32)3945 max_abs = np.max(max_source, axis=2).astype(np.float32)
3938 e8m0, group_scaling = _quantmx_compute_exp_scaling(max_abs, dp, is_fp4_e2m1, is_nv)3946 e8m0, group_scaling = _quantmx_compute_exp_scaling(max_abs, dp, is_fp4_e2m1, is_nv)
3939 scaled = _quantmx_scale_grouped(x_grouped, group_scaling, src_dtype_name, is_fp4_e2m1, is_nv)3947 scaled = _quantmx_scale_grouped(x_grouped, group_scaling, src_dtype_name, is_fp4_e2m1, is_nv)
@@ -3969,9 +3977,7 @@ def gen_quantmx_op_golden(case_name: str, output: Path, case_index: int = None)
3969 3977 
3970 normalized_axis = _quantmx_normalize_axis(axis, x.ndim)3978 normalized_axis = _quantmx_normalize_axis(axis, x.ndim)
3971 if normalized_axis == x.ndim - 2:3979 if normalized_axis == x.ndim - 2:
3972- return _quantmx_axis_dn_golden(3980+ return _quantmx_axis_dn_golden(x, src_dtype_name, is_fp4_e2m1, is_nv, use_plain_fp8_max_abs, dp, impl)
3973- x, src_dtype_name, is_fp4_e2m1, is_nv, use_plain_fp8_max_abs, dp, impl
3974- )
3975 return _quantmx_axis_last_golden(x, src_dtype_name, is_fp4_e2m1, is_nv, use_plain_fp8_max_abs, dp, impl)3981 return _quantmx_axis_last_golden(x, src_dtype_name, is_fp4_e2m1, is_nv, use_plain_fp8_max_abs, dp, impl)
3976 3982 
3977 logging.debug("Case(%s), Golden creating...", case_name)3983 logging.debug("Case(%s), Golden creating...", case_name)
@@ -796,6 +796,8 @@ TEST_P(GatherOperationTest, TestGather)
796 {4, {{1, GatherOperationExeFunc4_1Dims}, {2, GatherOperationExeFunc4_2Dims}}},796 {4, {{1, GatherOperationExeFunc4_1Dims}, {2, GatherOperationExeFunc4_2Dims}}},
797 };797 };
798 auto test_data = GetParam().test_data_;798 auto test_data = GetParam().test_data_;
799+ ConfigManagerNg::JitScopeGuard configGuard(
800+ "matmul_test", std::map<std::string, std::any>{{"pass." + std::string(ENABLE_SLICE), false}});
799 auto axis = static_cast<CastMode>(GetValueByName<int>(test_data, "axis"));801 auto axis = static_cast<CastMode>(GetValueByName<int>(test_data, "axis"));
800 auto args = GatherOpFuncArgs(GetViewShape(test_data), GetTileShape(test_data), axis);802 auto args = GatherOpFuncArgs(GetViewShape(test_data), GetTileShape(test_data), axis);
801 auto testCase = CreateTestCaseDesc<GatherOpMetaData>(GetParam(), &args);803 auto testCase = CreateTestCaseDesc<GatherOpMetaData>(GetParam(), &args);
@@ -381,6 +381,8 @@ TEST_P(MatmulOperationTest, TestMatmul)
381{381{
382 TestCaseDesc testCase;382 TestCaseDesc testCase;
383 auto test_data = GetParam().test_data_;383 auto test_data = GetParam().test_data_;
384+ ConfigManagerNg::JitScopeGuard configGuard(
385+ "matmul_test", std::map<std::string, std::any>{{"pass." + std::string(ENABLE_SLICE), false}});
384 testCase.inputTensors = GetMatmulTensors(test_data, "input_tensors");386 testCase.inputTensors = GetMatmulTensors(test_data, "input_tensors");
385 testCase.outputTensors = GetMatmulTensors(test_data, "output_tensors");387 testCase.outputTensors = GetMatmulTensors(test_data, "output_tensors");
386 auto args = MatmulOpFuncArgs(GetViewShape(test_data), GetMatmulTileShape(test_data), GetMatmulParam(test_data));388 auto args = MatmulOpFuncArgs(GetViewShape(test_data), GetMatmulTileShape(test_data), GetMatmulParam(test_data));
@@ -33,9 +33,12 @@
33namespace npu::tile_fwk {33namespace npu::tile_fwk {
34class TestCodegenDynIndexOutCast : public CodegenTestBase {34class TestCodegenDynIndexOutCast : public CodegenTestBase {
35public:35public:
36- TestCodegenDynIndexOutCast() : CodegenTestBase({.compileStage = CS_EXECUTE_GRAPH, .setIdGen = true}) {}36+ TestCodegenDynIndexOutCast()
37+ : CodegenTestBase(
38+ {.compileStage = CS_EXECUTE_GRAPH, .setTileTensor = true, .tileTensorValue = false, .setIdGen = true})
39+ {}
37 40 
38- static void SetUpTestCase() { config::SetCodeGenConfig(KEY_CODEGEN_SUPPORT_TILE_TENSOR, false); }41+ static void SetUpTestCase() {}
39 42 
40 static void TearDownTestCase() { config::SetCodeGenConfig(KEY_CODEGEN_SUPPORT_TILE_TENSOR, true); }43 static void TearDownTestCase() { config::SetCodeGenConfig(KEY_CODEGEN_SUPPORT_TILE_TENSOR, true); }
41};44};
@@ -98,7 +98,7 @@ TEST_F(TestCodegenGatherInUB, gather_in_a_)
98 auto function = GatherInUBUT(cfg);98 auto function = GatherInUBUT(cfg);
99 std::string res = GetResultFromCpp(*function);99 std::string res = GetResultFromCpp(*function);
100 std::string expect =100 std::string expect =
101- R"!!!(TileOp::GatherInUB<half, int32_t, int32_t, 8, 16, 4>((__ubuf__ half*)UB_S0_E256, (__gm__ half*)(RUNTIME_GET_PARAM_ADDR(RUNTIME_param, 2, 1)), (__gm__ int32_t*)(RUNTIME_GET_PARAM_ADDR(RUNTIME_param, 2, 10)), (__gm__ int32_t*)(RUNTIME_GET_PARAM_ADDR(RUNTIME_param, 2, 19)), sym_58_dim_1, GET_PARAM_RAWSHAPE_BY_IDX(param, 2, 1, 2, 1), GET_PARAM_OFFSET_BY_IDX(param, 2, 1, 2, 0), GET_PARAM_OFFSET_BY_IDX(param, 2, 1, 2, 1), sym_58_dim_0, GET_PARAM_RAWSHAPE_BY_IDX(param, 2, 10, 2, 1), GET_PARAM_OFFSET_BY_IDX(param, 2, 10, 2, 0), GET_PARAM_OFFSET_BY_IDX(param, 2, 10, 2, 1), GET_PARAM_RAWSHAPE_BY_IDX(param, 2, 19, 2, 1), GET_PARAM_OFFSET_BY_IDX(param, 2, 19, 2, 0), GET_PARAM_OFFSET_BY_IDX(param, 2, 19, 2, 1));)!!!";101+ R"!!!(TileOp::GatherInUB<half, int32_t, int32_t, 8, 16, 4>((__ubuf__ half*)UB_S0_E256, (__gm__ half*)(RUNTIME_GET_PARAM_ADDR(RUNTIME_param, 2, 1)), (__gm__ int32_t*)(RUNTIME_GET_PARAM_ADDR(RUNTIME_param, 2, 10)), (__gm__ int32_t*)(RUNTIME_GET_PARAM_ADDR(RUNTIME_param, 2, 19)), sym_60_dim_1, GET_PARAM_RAWSHAPE_BY_IDX(param, 2, 1, 2, 1), GET_PARAM_OFFSET_BY_IDX(param, 2, 1, 2, 0), GET_PARAM_OFFSET_BY_IDX(param, 2, 1, 2, 1), sym_60_dim_0, GET_PARAM_RAWSHAPE_BY_IDX(param, 2, 10, 2, 1), GET_PARAM_OFFSET_BY_IDX(param, 2, 10, 2, 0), GET_PARAM_OFFSET_BY_IDX(param, 2, 10, 2, 1), GET_PARAM_RAWSHAPE_BY_IDX(param, 2, 19, 2, 1), GET_PARAM_OFFSET_BY_IDX(param, 2, 19, 2, 0), GET_PARAM_OFFSET_BY_IDX(param, 2, 19, 2, 1));)!!!";
102 CheckStringExist(expect, res);102 CheckStringExist(expect, res);
103}103}
104 104 
@@ -15,6 +15,8 @@
15 15 
16#include "gtest/gtest.h"16#include "gtest/gtest.h"
17 17 
18+#include <regex>
19+ 
18#include "tilefwk/tilefwk.h"20#include "tilefwk/tilefwk.h"
19#include "interface/configs/config_manager.h"21#include "interface/configs/config_manager.h"
20#include "interface/inner/tilefwk.h"22#include "interface/inner/tilefwk.h"
@@ -329,6 +331,9 @@ TStoreVec<TStoreConfigVec<pto::AtomicType::AtomicNone>>(gmTensor_8, ubTensor_1,
329}331}
330)!!!";332)!!!";
331#endif333#endif
334+ const std::regex dynamicSymbolPattern(R"(sym_[0-9]+_dim_)");
335+ res = std::regex_replace(res, dynamicSymbolPattern, "sym_dynamic_dim_");
336+ expect = std::regex_replace(expect, dynamicSymbolPattern, "sym_dynamic_dim_");
332 CheckStringExist(expect, res);337 CheckStringExist(expect, res);
333}338}
334 339 
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include "gtest/gtest.h"16#include "gtest/gtest.h"
17+#include <fstream>
17#include "tilefwk/tilefwk.h"18#include "tilefwk/tilefwk.h"
18#include "interface/inner/tilefwk.h"19#include "interface/inner/tilefwk.h"
19#include "interface/configs/config_manager.h"20#include "interface/configs/config_manager.h"
@@ -25,6 +26,30 @@
25 26 
26namespace npu::tile_fwk {27namespace npu::tile_fwk {
27 28 
29+namespace {
30+std::string GenAllCodeByFunction(Function& function)
31+{
32+ CodeGenCtx ctx;
33+ CodeGenCloudNPU codeGen(ctx);
34+ codeGen.GenCode(function);
35+ 
36+ std::string results;
37+ for (const auto& subFunc : function.rootFunc_->programs_) {
38+ auto leafFuncAttr = subFunc.second->GetLeafFuncAttribute();
39+ ASSERT(FwkErr::INVALID_FUNCTION, leafFuncAttr != nullptr) << "can not find leaf func attribute";
40+ const auto& binPath = leafFuncAttr->binPath;
41+ if (binPath.empty()) {
42+ continue;
43+ }
44+ std::string cppFile = binPath.substr(0, binPath.rfind('.')) + ".cpp";
45+ std::ifstream ifs(cppFile);
46+ results.append(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
47+ results.push_back('\n');
48+ }
49+ return results;
50+}
51+} // namespace
52+ 
28class TestCodegenDynTransData : public CodegenTestBase {53class TestCodegenDynTransData : public CodegenTestBase {
29public:54public:
30 TestCodegenDynTransData() : CodegenTestBase({.compileStage = CS_CODEGEN_INSTRUCTION}) {}55 TestCodegenDynTransData() : CodegenTestBase({.compileStage = CS_CODEGEN_INSTRUCTION}) {}
@@ -40,6 +65,7 @@ public:
40 int tileOpFormat;65 int tileOpFormat;
41 std::vector<SymbolicScalar> validShape;66 std::vector<SymbolicScalar> validShape;
42 std::string expect;67 std::string expect;
68+ bool checkAllSubKernels = false;
43 };69 };
44 70 
45 void RunTransDataTest(const TransDataTestCase& tc)71 void RunTransDataTest(const TransDataTestCase& tc)
@@ -59,7 +85,7 @@ public:
59 }85 }
60 auto function = Program::GetInstance().GetFunctionByRawName(FUNCTION_PREFIX + tc.caseName + SUB_FUNC_SUFFIX +86 auto function = Program::GetInstance().GetFunctionByRawName(FUNCTION_PREFIX + tc.caseName + SUB_FUNC_SUFFIX +
61 HIDDEN_FUNC_SUFFIX);87 HIDDEN_FUNC_SUFFIX);
62- std::string res = GenCodeByFunction(*function);88+ std::string res = tc.checkAllSubKernels ? GenAllCodeByFunction(*function) : GenCodeByFunction(*function);
63 CheckStringExist(tc.expect, res);89 CheckStringExist(tc.expect, res);
64 }90 }
65};91};
@@ -75,7 +101,7 @@ TEST_F(TestCodegenDynTransData, TestTransData2)
75 .tileOpFormat = 2,101 .tileOpFormat = 2,
76 .validShape = {1, 1, 1, 8, 8},102 .validShape = {1, 1, 1, 8, 8},
77 .expect =103 .expect =
78- R"!!!(TTransDataNCHW2NC1HWC0<(int)(1), (int)(8), (int)(1), (int)(8)>(gmTensor_3, Coord5Dim((RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 3)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 4))), ubTensor_4, ubTensor_5, (int)(0), (int)(0), (int)(0), (int)(0));)!!!"});104+ R"!!!(TTransDataNCHW2NC1HWC0<(int)(1), (int)(8), (int)(1), (int)(8)>(gmTensor_9, Coord5Dim((RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 3)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 18, 4))), ubTensor_10, ubTensor_7, (int)(0), (int)(0), (int)(0), (int)(0));)!!!"});
79}105}
80 106 
81TEST_F(TestCodegenDynTransData, TestTransData4)107TEST_F(TestCodegenDynTransData, TestTransData4)
@@ -89,8 +115,8 @@ TEST_F(TestCodegenDynTransData, TestTransData4)
89 .tileOpFormat = 4,115 .tileOpFormat = 4,
90 .validShape = {32, 1, 16, 16},116 .validShape = {32, 1, 16, 16},
91 .expect =117 .expect =
92- R"!!!(TTransDataNCHW2Fractal_Z<(int)(16), (int)(16), (int)(2), (int)(16)>(gmTensor_4, Coord4Dim((RUNTIME_COA_GET_PARAM_OFFSET(4, 18, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 18, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 18, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 18, 3))), ubTensor_5, ubTensor_6, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(1));118+ R"!!!(TTransDataNCHW2Fractal_Z<(int)(16), (int)(16), (int)(2), (int)(16)>(gmTensor_6, Coord4Dim((RUNTIME_COA_GET_PARAM_OFFSET(4, 52, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 52, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 52, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 52, 3))), ubTensor_7, ubTensor_4, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(1));)!!!",
93-)!!!"});119+ .checkAllSubKernels = true});
94}120}
95 121 
96TEST_F(TestCodegenDynTransData, TestTransData3)122TEST_F(TestCodegenDynTransData, TestTransData3)
@@ -104,7 +130,7 @@ TEST_F(TestCodegenDynTransData, TestTransData3)
104 .tileOpFormat = 3,130 .tileOpFormat = 3,
105 .validShape = {1, 1, 1, 1, 8, 8},131 .validShape = {1, 1, 1, 1, 8, 8},
106 .expect =132 .expect =
107- R"!!!(TTransDataNCDHW2NDC1HWC0<(int)(1), (int)(1), (int)(8), (int)(1), (int)(8)>(gmTensor_7, Coord6Dim((RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 3)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 4)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 5))), ubTensor_8, ubTensor_9, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0));133+ R"!!!(TTransDataNCDHW2NDC1HWC0<(int)(1), (int)(1), (int)(8), (int)(1), (int)(8)>(gmTensor_9, Coord6Dim((RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 3)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 4)), (RUNTIME_COA_GET_PARAM_OFFSET(6, 22, 5))), ubTensor_10, ubTensor_7, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0));
108)!!!"});134)!!!"});
109}135}
110 136 
@@ -119,8 +145,8 @@ TEST_F(TestCodegenDynTransData, TestTransData5)
119 .tileOpFormat = 5,145 .tileOpFormat = 5,
120 .validShape = {8, 1, 16, 8},146 .validShape = {8, 1, 16, 8},
121 .expect =147 .expect =
122- R"!!!(TTransDataNCDHW2FRACTAL_Z_3D<(int)(16), (int)(8), (int)(1), (int)(1), (int)(8)>(gmTensor_4, Coord4Dim((RUNTIME_COA_GET_PARAM_OFFSET(4, 22, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 22, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 22, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 22, 3))), ubTensor_5, ubTensor_6, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(1));148+ R"!!!(TTransDataNCDHW2FRACTAL_Z_3D<(int)(16), (int)(8), (int)(1), (int)(1), (int)(8)>(gmTensor_6, Coord4Dim((RUNTIME_COA_GET_PARAM_OFFSET(4, 64, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 64, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 64, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(4, 64, 3))), ubTensor_7, ubTensor_4, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(1));)!!!",
123-)!!!"});149+ .checkAllSubKernels = true});
124}150}
125 151 
126TEST_F(TestCodegenDynTransData, TestTransData0_3)152TEST_F(TestCodegenDynTransData, TestTransData0_3)
@@ -148,7 +174,7 @@ TEST_F(TestCodegenDynTransData, TestTransData0_6)
148 .tileOpFormat = 0,174 .tileOpFormat = 0,
149 .validShape = {1, 7, 1, 1, 8},175 .validShape = {1, 7, 1, 1, 8},
150 .expect =176 .expect =
151- R"!!!(TTransDataNDC1HWC02NCDHW<(int)(1), (int)(1), (int)(7), (int)(1), (int)(8)>(gmTensor_2, Coord5Dim((RUNTIME_COA_GET_PARAM_OFFSET(5, 47, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 47, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 47, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 47, 3)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 47, 4))), ubTensor_3, ubTensor_0, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(1), (int)(1));177+ R"!!!(TTransDataNDC1HWC02NCDHW<(int)(1), (int)(1), (int)(7), (int)(1), (int)(8)>(gmTensor_2, Coord5Dim((RUNTIME_COA_GET_PARAM_OFFSET(5, 26, 0)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 26, 1)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 26, 2)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 26, 3)), (RUNTIME_COA_GET_PARAM_OFFSET(5, 26, 4))), ubTensor_3, ubTensor_4, (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(0), (int)(1), (int)(1));
152)!!!"});178)!!!"});
153}179}
154} // namespace npu::tile_fwk180} // namespace npu::tile_fwk
@@ -76,10 +76,10 @@ void TopKOnBoardFunc(TopKParams& params)
76 expect = R"(TMrgSort<1, 32, 32>(ubTensor_2, ubTensor_2, ubTensor_6); // [opMagic:10007])";76 expect = R"(TMrgSort<1, 32, 32>(ubTensor_2, ubTensor_2, ubTensor_6); // [opMagic:10007])";
77 CheckStringExist(expect, res);77 CheckStringExist(expect, res);
78 78 
79- expect = R"(TExtract<32, 1, 1>(ubTensor_8, ubTensor_2); // [opMagic:10010])";79+ expect = R"(TExtract<32, 0, 1>(ubTensor_8, ubTensor_2); // [opMagic:10008])";
80 CheckStringExist(expect, res);80 CheckStringExist(expect, res);
81 81 
82- expect = R"(TExtract<32, 0, 1>(ubTensor_10, ubTensor_2); // [opMagic:10008])";82+ expect = R"(TExtract<32, 1, 1>(ubTensor_10, ubTensor_2); // [opMagic:10010])";
83 CheckStringExist(expect, res);83 CheckStringExist(expect, res);
84}84}
85 85