Repository navigation
Expand file tree
/
Copy pathremove_permutes_around_elementwise_ops.py
More file actions
1119 lines (1015 loc) · 47.6 KB
/
Copy pathremove_permutes_around_elementwise_ops.py
File metadata and controls
1119 lines (1015 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# Copyright 2026 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import math
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import cast
import torch
import torch.fx
from executorch.backends.transforms.channels_last_layout import (
is_permute_copy,
PERMUTE_COPY_TARGETS,
)
from executorch.backends.transforms.permute_pass_utils import get_arg, set_arg
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.dialects.edge._ops import EdgeOpOverload
from executorch.exir.pass_base import ExportPass, PassResult
class RemovePermutesAroundElementwiseOps(ExportPass):
"""
Looks for subgraphs of elementwise ops sandwiched between permutes and removes those
permutes if possible.
Allows special handling for certain non-elementwise ops that can be easily updated
based on the permute's parameter such as mean, cat, and slice.
The repeat_interleave idiom (unsqueeze -> expand_copy -> merging view_copy) is
recognised as a single rank-preserving unit; see _interleave_triple.
"""
@dataclass()
class Subgraph:
start_permute: list[int]
end_permute: list[int]
# Nodes in the subgraph, does not include permutes.
nodes: set[torch.fx.Node] = field(default_factory=set)
# Incoming edges to the subgraph from permute nodes.
edges_in: set[tuple[torch.fx.Node, torch.fx.Node]] = field(default_factory=set)
# Outgoing edges of the subgraph to permute nodes.
edges_out: set[tuple[torch.fx.Node, torch.fx.Node]] = field(default_factory=set)
# Outgoing edges to permutes that do not match end_permute. Those are
# kept and their permutation rewritten to absorb the removed start
# permute, as (producer, permute node, new permutation).
edges_out_to_update: set[
tuple[torch.fx.Node, torch.fx.Node, tuple[int, ...]]
] = field(default_factory=set)
# Incoming edges from constant nodes that need a compensating permute.
constant_edges_in: set[tuple[torch.fx.Node, torch.fx.Node]] = field(
default_factory=set
)
# Per-node expected end permutation (may differ from end_permute
# when the subgraph contains rank-changing views).
node_end_permute: dict[torch.fx.Node, list[int]] = field(default_factory=dict)
# Per-node expected start permutation for upstream traversal.
node_start_permute: dict[torch.fx.Node, list[int]] = field(default_factory=dict)
# repeat_interleave triples keyed by their unit-dim-inserting head node,
# mapping to (dim, scale, expand_node, view_node). See _interleave_triple.
interleaves: dict[
torch.fx.Node, tuple[int, int, torch.fx.Node, torch.fx.Node]
] = field(default_factory=dict)
# Views whose target shapes must change when the surrounding layout
# transforms are removed. Boundary views are inside the region; sink
# views feed it from layout-invariant single-non-unit tensors.
view_shape_overrides: dict[torch.fx.Node, list[int]] = field(
default_factory=dict
)
sink_edges_in: set[tuple[torch.fx.Node, torch.fx.Node]] = field(
default_factory=set
)
def __init__(
self,
extra_permutable_ops: set | None = None,
target_filters: (
dict[EdgeOpOverload, Callable[[torch.fx.Node], bool]] | None
) = None,
) -> None:
super().__init__()
self._permutable_ops = {
exir_ops.edge.aten.add.Tensor,
exir_ops.edge.aten.amax.default,
exir_ops.edge.aten.amin.default,
exir_ops.edge.aten.mul.Tensor,
exir_ops.edge.aten.sub.Tensor,
exir_ops.edge.aten.hardtanh.default,
exir_ops.edge.aten.clamp.default,
exir_ops.edge.aten.cat.default,
exir_ops.edge.aten.constant_pad_nd.default,
exir_ops.edge.aten.mean.dim,
exir_ops.edge.aten.pad.default,
exir_ops.edge.aten.sum.dim_IntList,
exir_ops.edge.aten.slice_copy.Tensor,
exir_ops.edge.aten.expand_copy.default,
}
try:
self._permutable_ops.add(
exir_ops.edge.quantized_decomposed.quantize_per_tensor.default
)
self._permutable_ops.add(
exir_ops.edge.quantized_decomposed.dequantize_per_tensor.default
)
except AttributeError:
pass
if extra_permutable_ops:
self._permutable_ops |= extra_permutable_ops
# Per-op predicates gating permutability. The pass only reasons about
# per-tensor quantization: a numel-1 qparam broadcasts identically under
# any permutation, while a per-channel one is tied to an axis this pass
# does not remap. Callers adding quantized ops supply a filter here.
self._target_filters: dict[EdgeOpOverload, Callable[[torch.fx.Node], bool]] = (
target_filters or {}
)
self._sq_unsq_cache: dict[torch.fx.Node, bool] = {}
self._interleave_cache: dict[
torch.fx.Node,
tuple[int, int, torch.fx.Node, torch.fx.Node] | None,
] = {}
self._pending_visits = None
self._bypassed_permutes: set[torch.fx.Node] = set()
_VIEW_OPS = (
exir_ops.edge.aten.view_copy.default,
exir_ops.edge.aten.view.default,
)
@staticmethod
def _concrete_shape(node: torch.fx.Node) -> list[int] | None:
"""Return a node's shape, or None if it is missing or symbolic."""
val = node.meta.get("val")
if val is None:
return None
shape = val.shape
if not all(isinstance(d, int) for d in shape):
return None
return [int(d) for d in shape]
def _view_shapes(self, node: torch.fx.Node) -> tuple[list[int], list[int]] | None:
"""Concrete (input, output) shapes of a view op, else None."""
if node.target not in self._VIEW_OPS:
return None
inp = node.args[0] if node.args else None
if not isinstance(inp, torch.fx.Node):
return None
in_shape = self._concrete_shape(inp)
out_shape = self._concrete_shape(node)
if in_shape is None or out_shape is None:
return None
return in_shape, out_shape
_PAD_OPS = (
exir_ops.edge.aten.constant_pad_nd.default,
exir_ops.edge.aten.pad.default,
)
@staticmethod
def _find_extra_ones(longer: list[int], shorter: list[int]) -> list[int] | None:
"""Positions in ``longer`` whose removal yields ``shorter``.
Every such position must hold a size-1 dim, so the two shapes differ by
unit dims alone. Returns None when no such set of positions exists.
"""
extra: list[int] = []
j = 0
for i, dim in enumerate(longer):
if j < len(shorter) and dim == shorter[j]:
j += 1
continue
if dim != 1:
return None
extra.append(i)
return extra if j == len(shorter) else None
def _is_squeeze_unsqueeze_view(self, node: torch.fx.Node) -> bool:
"""Check if a node is a view_copy that only adds or removes dims of
size 1."""
if node in self._sq_unsq_cache:
return self._sq_unsq_cache[node]
result = self._check_squeeze_unsqueeze_view(node)
self._sq_unsq_cache[node] = result
return result
def _check_squeeze_unsqueeze_view(self, node: torch.fx.Node) -> bool:
shapes = self._view_shapes(node)
if shapes is None:
return False
in_shape, out_shape = shapes
if len(out_shape) > len(in_shape):
return self._find_extra_ones(out_shape, in_shape) is not None
if len(in_shape) > len(out_shape):
return self._find_extra_ones(in_shape, out_shape) is not None
return False
def _is_permutation_sink_view(self, node: torch.fx.Node) -> bool:
"""True if ``node`` is a reshape whose input has at most one non-unit dim.
Flattening such a tensor -- e.g. the ``[1, C, 1, 1] -> [1, C]`` after a
global pool -- is permutation-invariant: every layout of the input
produces the identical output (the single non-unit run of elements is
contiguous regardless of which axis holds it). The region may terminate
here without a compensating permute when downstream consumers do not use
the output shape for layout-dependent broadcasting.
"""
if node.target not in self._VIEW_OPS:
return False
inp = node.args[0]
assert isinstance(inp, torch.fx.Node)
shape = inp.meta["val"].shape
# Count a dim as non-unit unless it is a concrete size-1 (symbolic dims
# are treated as non-unit, i.e. conservatively not a sink).
non_unit = [d for d in shape if not (isinstance(d, int) and d == 1)]
return len(non_unit) <= 1
def _remapped_sink_shape(
self, sink: torch.fx.Node, start_permute: list[int]
) -> list[int] | None:
"""Return the sink shape in the layout before ``start_permute``.
A sink input has at most one non-unit dimension, so changing the view's
shape does not change element order. The output rank must match the
region permutation so its broadcast axes can be remapped exactly.
"""
out_shape = self._concrete_shape(sink)
if out_shape is None or len(out_shape) != len(start_permute):
return None
# Reshape can relocate one contiguous non-unit run among singleton axes,
# but it cannot transpose multiple non-unit output axes.
if sum(dim != 1 for dim in out_shape) > 1:
return None
inverse = [start_permute.index(i) for i in range(len(start_permute))]
return [out_shape[index] for index in inverse]
def _singleton_view_boundary_shape(
self,
view: torch.fx.Node,
start_permute: list[int],
end_permute_node: torch.fx.Node,
) -> list[int] | None:
"""Compose a layout pair across a view that only inserts unit dims."""
shapes = self._view_shapes(view)
end_dims = self.get_permutation(end_permute_node)
end_shape = self._concrete_shape(end_permute_node)
if shapes is None or end_dims is None or end_shape is None:
return None
in_shape, out_shape = shapes
if len(start_permute) != len(in_shape) or len(end_dims) != len(out_shape):
return None
inserted = self._find_extra_ones(out_shape, in_shape)
if inserted is None:
return None
# Label each old view-output axis by the corresponding axis before the
# incoming permutation. The outgoing permutation must restore those
# labels to identity order; inserted singleton axes carry no label.
labels: list[int | None] = list(start_permute)
for index in inserted:
labels.insert(index, None)
output_labels = [labels[index] for index in end_dims]
if [label for label in output_labels if label is not None] != list(
range(len(in_shape))
):
return None
inverse = [start_permute.index(i) for i in range(len(start_permute))]
unpermuted_input = [in_shape[index] for index in inverse]
if self._find_extra_ones(end_shape, unpermuted_input) is None:
return None
return end_shape
def _inserted_unit_dim(self, node: torch.fx.Node) -> int | None:
"""Position of the size-1 dim ``node`` inserts, else None.
Accepts both an explicit unsqueeze and a view_copy that only adds a
single unit dim, matching how the rest of the pass treats the two
spellings interchangeably.
"""
is_unsqueeze = node.target == exir_ops.edge.aten.unsqueeze_copy.default
if not is_unsqueeze and node.target not in self._VIEW_OPS:
return None
inp = node.args[0]
if not isinstance(inp, torch.fx.Node):
return None
in_shape = self._concrete_shape(inp)
out_shape = self._concrete_shape(node)
if in_shape is None or out_shape is None:
return None
if len(out_shape) != len(in_shape) + 1:
return None
if is_unsqueeze:
dim = get_arg(node, "dim", int)
pos = dim if dim >= 0 else dim + len(out_shape)
if not 0 <= pos < len(out_shape) or out_shape[pos] != 1:
return None
return pos
positions = self._find_extra_ones(out_shape, in_shape)
if positions is None or len(positions) != 1:
return None
return positions[0]
def _interleave_triple(
self, node: torch.fx.Node
) -> tuple[int, int, torch.fx.Node, torch.fx.Node] | None:
"""Recognise a repeat_interleave and return (dim, scale, expand, view)."""
if node not in self._interleave_cache:
self._interleave_cache[node] = self._match_interleave_triple(node)
return self._interleave_cache[node]
def _match_interleave_triple(
self, node: torch.fx.Node
) -> tuple[int, int, torch.fx.Node, torch.fx.Node] | None:
"""Match a repeat_interleave lowered to three shape operations.
``repeat_interleave(scale, dim)`` lowers to::
unsqueeze(dim + 1) -> expand_copy(scale at dim + 1)
-> view_copy(merge dim, dim + 1)
(e.g. torchaudio's Stretch2d). The triple is rank-preserving overall, so
a permutation flows through it unchanged and only the dim it acts on has
to be remapped -- unlike the merging view_copy on its own, which is not
layout-invariant. Handling the three nodes as one unit also avoids having
to pick an un-permuted position for the intermediate unit dim, a choice
that would otherwise decide whether the merge stays legal.
"""
pos = self._inserted_unit_dim(node)
if pos is None or pos == 0 or len(node.users) != 1:
return None
dim = pos - 1
expand_node = next(iter(node.users))
if (
expand_node.target != exir_ops.edge.aten.expand_copy.default
or len(expand_node.users) != 1
):
return None
unsq_shape = self._concrete_shape(node)
if unsq_shape is None:
return None
size = get_arg(expand_node, "size")
if not isinstance(size, (list, tuple)) or len(size) != len(unsq_shape):
return None
size = list(size)
if not all(isinstance(s, int) for s in size):
return None
# Every dim other than the inserted one must pass through untouched.
if any(s != -1 and s != unsq_shape[k] for k, s in enumerate(size) if k != pos):
return None
scale = size[pos]
if scale < 1:
return None
view_node = next(iter(expand_node.users))
if view_node.target not in self._VIEW_OPS:
return None
in_shape = self._concrete_shape(cast(torch.fx.Node, node.args[0]))
if in_shape is None:
return None
merged = list(in_shape)
merged[dim] *= scale
if self._concrete_shape(view_node) != merged:
return None
return dim, scale, expand_node, view_node
def _adapt_permute_across_view(
self, permute: list[int], node: torch.fx.Node
) -> list[int] | None:
"""Adjust a permutation across a squeeze/unsqueeze boundary.
Adapts from input-rank to output-rank space (downstream direction).
Returns the adjusted permutation, or None if not possible.
"""
shapes = self._view_shapes(node)
if shapes is None:
return None
in_shape, out_shape = shapes
# ``permute`` must live in the view's input-rank space. It does not when
# the view is reached by upstream traversal, where the permutation is
# expressed at the view's output rank.
if len(permute) != len(in_shape):
return None
if len(out_shape) > len(in_shape):
# unsqueeze: insert an identity mapping at each added position.
# Positions are ascending and index into the output, so inserting
# them in order lands each one at its final index.
positions = self._find_extra_ones(out_shape, in_shape)
if positions is None:
return None
new_perm = list(permute)
for index in positions:
new_perm = [x + 1 if x >= index else x for x in new_perm]
new_perm.insert(index, index)
return new_perm
if len(in_shape) > len(out_shape):
positions = self._find_extra_ones(in_shape, out_shape)
# Positions index into the node's input rank, which can differ from
# the permutation's rank when the view is reached via upstream
# traversal after an earlier rank change.
if positions is None or positions[-1] >= len(permute):
return None
# A position is a POSITION in the tensor; the permutation VALUE at
# that position is the logical dim being removed.
squeezed_values = {permute[p] for p in positions}
return [
x - sum(1 for v in squeezed_values if v < x)
for x in permute
if x not in squeezed_values
]
return None
def call(self, graph_module: torch.fx.GraphModule) -> PassResult: # noqa: C901
self._sq_unsq_cache.clear()
self._interleave_cache.clear()
self._bypassed_permutes.clear()
subgraphs_found: list[RemovePermutesAroundElementwiseOps.Subgraph] = []
processed_nodes: set[torch.fx.Node] = set()
for node in graph_module.graph.nodes:
if not is_permute_copy(node):
continue
start_permute = self.get_permutation(node)
if start_permute is None:
continue
# Expected end permutation for the subgraph.
end_permute = [start_permute.index(i) for i in range(len(start_permute))]
for user in node.users:
if (
not self.is_node_permutable(user)
and self._interleave_triple(user) is None
):
continue
subgraph = self.Subgraph(start_permute, end_permute)
if self.visit(user, subgraph, processed_nodes):
subgraphs_found.append(subgraph)
for n in subgraph.nodes:
processed_nodes.add(n)
modified = False
for subgraph in subgraphs_found:
if self.permute_subgraph(subgraph):
modified = True
if modified:
graph_module.graph.eliminate_dead_code()
graph_module.recompile()
return super().call(graph_module)
return PassResult(graph_module, False)
def visit(
self,
node: torch.fx.Node,
subgraph: Subgraph,
processed_nodes: set[torch.fx.Node],
current_end_permute: list[int] | None = None,
current_start_permute: list[int] | None = None,
) -> bool:
visit = (
node,
subgraph,
processed_nodes,
current_end_permute,
current_start_permute,
)
if self._pending_visits is not None:
self._pending_visits.append(visit)
return True
pending = [visit]
try:
while pending:
self._pending_visits = []
if not self._visit(*pending.pop()):
return False
pending.extend(reversed(self._pending_visits))
finally:
self._pending_visits = None
return True
def _visit( # noqa: C901
self,
node: torch.fx.Node,
subgraph: Subgraph,
processed_nodes: set[torch.fx.Node],
current_end_permute: list[int] | None = None,
current_start_permute: list[int] | None = None,
) -> bool:
if current_end_permute is None:
current_end_permute = subgraph.end_permute
if current_start_permute is None:
current_start_permute = subgraph.start_permute
if node in subgraph.nodes:
return True
if node in processed_nodes:
return False
# Explicit unsqueeze nodes are not generally permutable after shape-op
# canonicalization, but a guarded repeat_interleave triple is handled as
# one rank-preserving unit.
triple = self._interleave_triple(node)
if triple is None and not self.is_node_permutable(node):
return False
if triple is not None:
inp = node.args[0] if node.args else None
if not isinstance(inp, torch.fx.Node):
return False
in_shape = self._concrete_shape(inp)
if in_shape is None or len(current_start_permute) != len(in_shape):
return False
else:
# A permutable op can still change rank via broadcasting (e.g.
# [8, 1] + [1, 1, 1] -> [1, 8, 1]), which would leave the node
# carrying a permutation of the wrong rank. Squeeze/unsqueeze views
# are exempt because _adapt_permute_across_view checks their ranks.
if not self._is_squeeze_unsqueeze_view(node):
node_shape = getattr(node.meta.get("val"), "shape", None)
if node_shape is not None and len(node_shape) != len(
current_start_permute
):
return False
subgraph.nodes.add(node)
subgraph.node_end_permute[node] = current_end_permute
subgraph.node_start_permute[node] = current_start_permute
# A repeat_interleave triple is absorbed whole: its interior nodes are
# not layout-invariant individually, but the triple is rank-preserving.
users_source = node
if triple is not None:
users_source = self._absorb_interleave(
node,
triple,
subgraph,
processed_nodes,
current_end_permute,
current_start_permute,
)
if users_source is None:
return False
# If this is a squeeze/unsqueeze view, adapt permutations for
# traversal across the rank change boundary.
downstream_end = current_end_permute
downstream_start = current_start_permute
if triple is None and self._is_squeeze_unsqueeze_view(node):
# Adapt start permute for downstream (input-rank → output-rank)
adapted_start = self._adapt_permute_across_view(current_start_permute, node)
if adapted_start is None:
return False
downstream_start = adapted_start
# Derive end permute as the inverse of adapted start to ensure
# consistency. Computing start and end independently via
# _adapt_permute_across_view can produce mismatched results for
# squeeze views because the formula differs for "forward" vs
# "inverse" permutations.
downstream_end = [adapted_start.index(i) for i in range(len(adapted_start))]
# Traverse downstream:
for user in users_source.users:
if user.target in PERMUTE_COPY_TARGETS:
user_perm = self.get_permutation(user)
boundary_shape = None
if (
triple is None
and self._is_squeeze_unsqueeze_view(node)
and len(node.users) == 1
):
boundary_shape = self._singleton_view_boundary_shape(
node, current_start_permute, user
)
if boundary_shape is not None:
subgraph.view_shape_overrides[node] = boundary_shape
subgraph.edges_out.add((users_source, user))
elif user_perm == downstream_end:
subgraph.edges_out.add((users_source, user))
else:
# Non-matching permute: keep it and fold the start permute into it
# rather than discarding the region.
if user_perm is None or len(user_perm) != len(downstream_start):
return False
subgraph.edges_out_to_update.add(
(
users_source,
user,
tuple(downstream_start[d] for d in user_perm),
)
)
elif user.op == "output":
return False
elif self._is_permutation_sink_view(user):
# A sink with no other path into this region can terminate it:
# its single non-unit run has layout-invariant element order.
# If a later consumer is reached through another region branch,
# upstream traversal records and remaps the sink via
# ``sink_edges_in`` before any boundary is removed.
continue
elif not self.visit(
user, subgraph, processed_nodes, downstream_end, downstream_start
):
return False
# Traverse upstream:
for inp in node.all_input_nodes:
if inp.target in PERMUTE_COPY_TARGETS:
if self.get_permutation(inp) != current_start_permute:
return False
subgraph.edges_in.add((inp, node))
elif not isinstance(inp_val := inp.meta.get("val"), torch.Tensor | None):
# A symbolic scalar such as sym_size may read a dim of a region
# tensor, which removing the permutes would change.
return False
elif inp_val is not None and inp_val.numel() == 1:
# A numel-1 input (per-tensor quant scale / zero_point, scalar
# constant, ...) is layout-invariant: it broadcasts identically
# under any permutation, so it needs no compensating permute and
# stays wired directly. Notably this keeps lifted per-tensor
# qparam placeholders as placeholders, which lowering requires.
continue
elif inp in subgraph.nodes:
# Already part of the region; it is rewritten as a region node.
continue
elif self._is_permutation_sink_view(inp):
remapped_shape = self._remapped_sink_shape(inp, current_start_permute)
if remapped_shape is None or len(inp.users) != 1:
return False
subgraph.view_shape_overrides[inp] = remapped_shape
subgraph.sink_edges_in.add((inp, node))
elif self._is_constant(inp):
const_rank = self._get_node_rank(inp)
permute_rank = len(current_end_permute)
if const_rank is None:
return False
if const_rank > permute_rank:
return False
if const_rank < permute_rank and inp.meta.get("val") is None:
return False
subgraph.constant_edges_in.add((inp, node))
elif not self.visit(
inp,
subgraph,
processed_nodes,
current_end_permute,
current_start_permute,
):
return False
return True
def _absorb_interleave(
self,
head: torch.fx.Node,
triple: tuple[int, int, torch.fx.Node, torch.fx.Node],
subgraph: Subgraph,
processed_nodes: set[torch.fx.Node],
current_end_permute: list[int],
current_start_permute: list[int],
) -> torch.fx.Node | None:
"""Add a matched interleave's interior nodes and return its tail."""
_, _, expand_node, view_node = triple
if expand_node in processed_nodes or view_node in processed_nodes:
return None
for interior in (expand_node, view_node):
subgraph.nodes.add(interior)
subgraph.node_end_permute[interior] = current_end_permute
subgraph.node_start_permute[interior] = current_start_permute
subgraph.interleaves[head] = triple
return view_node
def _is_constant(self, node: torch.fx.Node) -> bool:
"""Check if a node's value is available at compile time.
Only considers direct constants (get_attr, parameter/buffer/constant
placeholders, full ops producing scalar constants) — does not recurse
into call_function chains to avoid stack overflow on deep graphs."""
if node.op == "get_attr":
return True
if node.op == "placeholder":
target = str(node.target)
return target.startswith(("b_", "p_", "c_"))
# full.default creates scalar constants (e.g. epsilon in LayerNorm)
if (
node.op == "call_function"
and node.target == exir_ops.edge.aten.full.default
):
return True
return False
def _get_node_rank(self, node: torch.fx.Node) -> int | None:
"""Return the tensor rank of a node's output, or None if unknown."""
val = node.meta.get("val")
if val is None:
return None
return len(val.shape)
@staticmethod
def _is_pointwise(target) -> bool:
"""Check if a target op is tagged as pointwise in ATen."""
op = getattr(target, "_op", None)
if op is not None and hasattr(op, "tags"):
return torch.Tag.pointwise in op.tags
return False
def is_node_permutable(self, node: torch.fx.Node) -> bool:
if node.target in self._PAD_OPS and not self._is_constant_pad(node):
return False
target_filter = self._target_filters.get(node.target)
if target_filter is not None and not target_filter(node):
return False
if node.target in self._permutable_ops:
if node.target in (
exir_ops.edge.aten.amax.default,
exir_ops.edge.aten.amin.default,
exir_ops.edge.aten.mean.dim,
exir_ops.edge.aten.sum.dim_IntList,
):
if not get_arg(node, "keepdim", bool):
return False
return True
if self._is_squeeze_unsqueeze_view(node):
return True
return self._is_pointwise(node.target)
def _is_constant_pad(self, node: torch.fx.Node) -> bool:
if len(node.args) < 2:
return False
pad = node.args[1]
if not isinstance(pad, (list, tuple)):
return False
if len(pad) % 2 != 0:
return False
if node.target == exir_ops.edge.aten.pad.default:
mode = node.args[2] if len(node.args) > 2 else node.kwargs.get("mode")
if mode not in (None, "constant"):
return False
return True
def _removes_a_permute(self, subgraph: Subgraph) -> bool:
"""Whether rewriting this region reduces the number of permutes."""
if subgraph.edges_out:
return True
rewired = set(subgraph.edges_in)
for permute, _ in subgraph.edges_in:
if all((permute, user) in rewired for user in permute.users):
return True
return False
def permute_subgraph(self, subgraph: Subgraph) -> bool: # noqa: C901
# Ensure that the subgraph's edges have not been modified by an earlier rewrite before applying changes.
if not self._subgraph_edges_are_current(subgraph):
return False
# Folding an end permute only pays for itself if some permute goes away.
# Otherwise the region is rewritten for nothing, and the composed
# permutation is a worse fusion candidate for the passes downstream.
if subgraph.edges_out_to_update and not self._removes_a_permute(subgraph):
return False
# Nodes belonging to a repeat_interleave triple are rewritten as a unit
# below, so they must skip the per-node dim handling and the view rank
# check (the triple's interior ranks intentionally differ from the
# region's permutation rank).
interleave_nodes: set[torch.fx.Node] = set()
for head, (_, _, expand_node, view_node) in subgraph.interleaves.items():
interleave_nodes.update((head, expand_node, view_node))
perm = subgraph.node_start_permute.get(head, subgraph.start_permute)
inp = head.args[0] if head.args else None
if not isinstance(inp, torch.fx.Node):
return False
in_shape = self._concrete_shape(inp)
if in_shape is None or len(perm) != len(in_shape):
return False
# Validate: every view_copy node's permutation rank must match its
# input tensor rank. A mismatch can occur when a squeeze/unsqueeze
# view is reached via upstream traversal with a permutation that was
# already adapted to a different rank. Applying the optimisation in
# this case would produce an invalid graph, so skip the subgraph.
for node in subgraph.nodes:
if node in interleave_nodes:
continue
if node.target in self._VIEW_OPS:
perm = subgraph.node_start_permute.get(node, subgraph.start_permute)
inp = node.args[0]
if isinstance(inp, torch.fx.Node) and inp.meta.get("val") is not None:
if len(perm) != len(inp.meta["val"].shape):
return False
# Validate: no node in the region may broadcast operands of different
# rank. Broadcasting right-aligns shapes, so once the boundary permutes
# are removed a lower-rank operand lines up against different axes of
# the others and the region silently computes a differently shaped
# result -- a [216, 1] that met a [1, 1, 216, 1] now meets a
# [1, 216, 1, 1] and yields 216 * 216 elements. The mismatch only
# surfaces later, as a downstream view whose recorded shape no longer
# fits its input. Same-rank broadcasting is safe: every operand carries
# the region's permutation, and broadcasting commutes with applying one
# permutation to all operands. numel-1 operands broadcast identically
# under any permutation, and cat never broadcasts. Constant operands
# are exempt: they are reshaped or permuted into the region's layout
# below.
for node in subgraph.nodes:
if (
node in interleave_nodes
or node.target in self._VIEW_OPS
or node.target == exir_ops.edge.aten.cat.default
):
continue
operand_ranks = {
len(shape)
for shape in (
self._concrete_shape(inp)
for inp in node.all_input_nodes
if isinstance(inp.meta.get("val"), torch.Tensor)
and (inp, node) not in subgraph.constant_edges_in
)
if shape is not None and math.prod(shape) > 1
}
if len(operand_ranks) > 1:
return False
# Handle dimension related node arguments FIRST, before
# bypassing permutes (which changes node inputs/metadata).
for node in subgraph.nodes:
if node in interleave_nodes:
continue
node_start_perm = subgraph.node_start_permute.get(
node, subgraph.start_permute
)
if node.target == exir_ops.edge.aten.cat.default:
self.update_cat(node, node_start_perm)
elif node.target in (
exir_ops.edge.aten.amax.default,
exir_ops.edge.aten.amin.default,
exir_ops.edge.aten.mean.dim,
exir_ops.edge.aten.sum.dim_IntList,
):
self.update_reduction_dim(node, node_start_perm)
elif node.target == exir_ops.edge.aten.slice_copy.Tensor:
self.update_slice_copy(node, node_start_perm)
elif node.target == exir_ops.edge.aten.expand_copy.default:
self.update_expand_copy(node, node_start_perm)
elif node.target in self._PAD_OPS:
self.update_pad(node, node_start_perm)
elif node.target in self._VIEW_OPS:
if node in subgraph.view_shape_overrides:
node.update_arg(1, subgraph.view_shape_overrides[node])
else:
self.update_view_copy(node, node_start_perm)
for sink, _ in subgraph.sink_edges_in:
sink.update_arg(1, subgraph.view_shape_overrides[sink])
for head, triple in subgraph.interleaves.items():
self.update_interleave(
head,
triple,
subgraph.node_start_permute.get(head, subgraph.start_permute),
)
# Skip incoming permutes.
for inp, out in subgraph.edges_in:
assert inp.target in PERMUTE_COPY_TARGETS
self._bypassed_permutes.add(inp)
if len(inp.args) >= 1:
out.replace_input_with(inp, cast(torch.fx.Node, inp.args[0]))
else:
out.replace_input_with(inp, cast(torch.fx.Node, inp.kwargs["input"]))
# Insert compensating permute on constant inputs.
for const_node, user_node in subgraph.constant_edges_in:
graph = const_node.graph
const_rank = self._get_node_rank(const_node)
# Use the node-specific end_permute for the correct rank
node_end_perm = subgraph.node_end_permute.get(
user_node, subgraph.end_permute
)
permute_rank = len(node_end_perm)
with graph.inserting_after(const_node):
if const_rank is not None and const_rank == permute_rank:
new_node = graph.create_node(
"call_function",
exir_ops.edge.aten.permute_copy.default,
args=(const_node, node_end_perm),
)
elif (
const_rank is not None
and const_rank < permute_rank
and const_node.meta.get("val") is not None
):
original_shape = list(const_node.meta["val"].shape)
padded = [1] * (permute_rank - const_rank) + original_shape
moved = [d for d in node_end_perm if padded[d] != 1]
view = exir_ops.edge.aten.view_copy.default
if moved == sorted(moved):
# Only unit dims move, so a reshape is exact.
permuted = [padded[d] for d in node_end_perm]
while len(permuted) > const_rank and permuted[0] == 1:
permuted.pop(0)
new_node = graph.call_function(view, (const_node, permuted))
else:
new_node = graph.call_function(view, (const_node, padded))
with graph.inserting_after(new_node):
new_node = graph.call_function(
exir_ops.edge.aten.permute_copy.default,
(new_node, node_end_perm),
)
else:
continue
user_node.replace_input_with(const_node, new_node)
# Skip outgoing permutes.
for inp, out in subgraph.edges_out:
assert out.target in PERMUTE_COPY_TARGETS
out.replace_all_uses_with(inp)
# Update outgoing permutes that can't be eliminated.
for _, out, new_permutation in subgraph.edges_out_to_update:
assert out.target in PERMUTE_COPY_TARGETS
set_arg(out, "dims", list(new_permutation))
return True
def _subgraph_edges_are_current(self, subgraph: Subgraph) -> bool:
"""Return false if an earlier rewrite invalidated this candidate."""
for inp, out in subgraph.edges_in:
if (
inp.target not in PERMUTE_COPY_TARGETS
or inp not in out.all_input_nodes
# edges_out_to_update can rewrite a permute in place, leaving it wired.
or self.get_permutation(inp)
!= subgraph.node_start_permute.get(out, subgraph.start_permute)
):
return False
outgoing = list(subgraph.edges_out) + [
(inp, out) for inp, out, _ in subgraph.edges_out_to_update
]
for inp, out in outgoing:
# A bypassed permute stays wired to its producer, but an earlier
# region now reads that producer directly and relies on its layout.
if (
out.target not in PERMUTE_COPY_TARGETS
or out not in inp.users
or out in self._bypassed_permutes
):
return False
for const_node, user_node in subgraph.constant_edges_in:
if const_node not in user_node.all_input_nodes:
return False
for sink, user_node in subgraph.sink_edges_in:
if sink not in user_node.all_input_nodes or len(sink.users) != 1:
return False
for head, (_, _, expand_node, view_node) in subgraph.interleaves.items():
if (
len(head.users) != 1
or len(expand_node.users) != 1
or expand_node not in head.users
or view_node not in expand_node.users
):
return False
return True
def update_interleave(
self,
head: torch.fx.Node,
triple: tuple[int, int, torch.fx.Node, torch.fx.Node],
start_permute: list[int],
) -> None:
"""Retarget a repeat_interleave triple at the un-permuted layout.
After the boundary permutes are removed the triple's input is in the
original layout, so the dim it interleaves moves from ``dim`` to
``start_permute[dim]`` and all three shape arguments are rebuilt there.
"""
dim, scale, expand_node, view_node = triple
inp = cast(torch.fx.Node, head.args[0])
in_shape = [int(d) for d in inp.meta["val"].shape]
inverse_permute = [start_permute.index(i) for i in range(len(start_permute))]
unpermuted_in = [in_shape[inverse_permute[i]] for i in range(len(in_shape))]
target_dim = start_permute[dim]
if head.target == exir_ops.edge.aten.unsqueeze_copy.default:
set_arg(head, "dim", target_dim + 1)