forked from pytorch/executorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplace_ops.py
2184 lines (1908 loc) · 82 KB
/
replace_ops.py
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
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
# This file contains all the functions that replace one op with another in the
# graph. The functions replacing ops for models deployed with Jarvis are grouped
# together in class 'ReplaceOpsInGraph'. Some examples of functions in the class are
# 1. functions that replace an ATen op with a custom op that accepts extra arguments
# 2. functions that replace in-place variants of ATen ops with out-of-place version.
# 3. functions that replace an ATen op with another semantically equivalent ATen op.
# 4. functions that concretize optional args.
# pyre-unsafe
import copy
import math
from operator import neg
from typing import cast, Dict, Iterable, Sequence, Set, Tuple
import torch
import torch.fx
from executorch.backends.cadence.aot.compiler_utils import (
get_shape,
get_tensor_from_attr,
get_transposed_dims,
get_zero_point,
is_node_with_op,
is_quantized_tensor,
quantize_tensor_multiplier,
)
from executorch.backends.cadence.aot.fuse_ops import FuseCascadedViewOps
from executorch.backends.cadence.aot.pass_utils import (
CadencePassAttribute,
register_cadence_pass,
)
from executorch.backends.cadence.aot.remove_ops import RemoveNopSelectOpPass
from executorch.backends.cadence.aot.utils import get_edge_overload_packet
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.dialects.edge._ops import EdgeOpOverload, EdgeOpOverloadPacket
from executorch.exir.dim_order_utils import get_memory_format
from executorch.exir.pass_base import ExportPass, NodeMetadata, PassResult, ProxyValue
from executorch.exir.passes.dim_order_ops_registry import (
DimOrderOpsMap,
MemoryFormatOpsMap,
)
from torch._subclasses import FakeTensor
from torch.fx.node import Argument
# A map to represent ops that:
# (a) are functionally equivalent wrt. Jarvis; and
# (b) have identical arguments
# An op whose target is 'key' in this dict can be replaced by the functionally euivalent
# op whose target is 'value'. The replacement would just involve changing the op target.
functionally_equivalent_op_targets: Dict[EdgeOpOverload, EdgeOpOverload] = {
exir_ops.edge.aten.relu_.default: exir_ops.edge.aten.relu.default,
exir_ops.edge.aten.unsafe_split.Tensor: exir_ops.edge.aten.split_copy.Tensor,
}
def contains_placeholder_or_param(nodes: Iterable[torch.fx.Node]) -> bool:
"""
Return true if any of the node in the incoming nodes list is a placeholder
or parameter
"""
return any(
is_node_with_op(node, "placeholder") or is_node_with_op(node, "get_attr")
for node in nodes
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceLogicalNotBooleanWhereWithWherePass(ExportPass):
"""
A where op with a logical_not and a boolean tensor can be replaced
by a where op with flipped inputs and the initial boolean tensor.
"""
def replace_logical_nop_where_with_where(
self, graph_module: torch.fx.GraphModule
) -> None:
graph = graph_module.graph
for node in graph.nodes:
# We are only interested in where nodes
if node.target != exir_ops.edge.aten.where.self:
continue
# If the third arg is not a logical_not, bail.
if node.args[0].target != exir_ops.edge.aten.logical_not.default:
continue
# Get the third arg node and its input
logical_not_node = node.args[0]
logical_not_input_tensor = (
logical_not_node.args[0].to_tensor()
if isinstance(logical_not_node.args[0], ProxyValue)
else logical_not_node.args[0]
)
# If the logical_not input is not a boolean tensor, bail.
if logical_not_input_tensor.meta["spec"].dtype != torch.bool:
continue
# Replace the where op with another one, flipping the inputs and using the boolean
# tensor from logical_not.
with graph.inserting_before(node):
linear_node = graph.call_function(
exir_ops.edge.aten.where.self,
args=(logical_not_node.args[0], node.args[2], node.args[1]),
)
# Replace all the uses
node.replace_all_uses_with(linear_node)
graph_module.recompile()
graph_module.graph.eliminate_dead_code()
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
self.replace_logical_nop_where_with_where(graph_module)
result = super().call(graph_module)
return result
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceSafeSoftmaxWithSoftmax(ExportPass): # keep
"""
Replace _safe_softmax with _softmax
"""
def call_operator(
self,
op,
args: tuple[Argument, ...],
kwargs: dict[str, Argument],
meta: NodeMetadata,
) -> ProxyValue:
if op != torch.ops.aten._safe_softmax.default:
return super().call_operator(op, args, kwargs, meta)
# Add False for the half_to_float argument of softmax
softmax_args = list(args) + [False]
return super().call_operator(
torch.ops.aten._softmax.default,
tuple(softmax_args),
kwargs,
meta,
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplacePT2QuantWithCadenceQuantPass(ExportPass):
"""
Replace the pt2 quantization ops with cadence quantization ops.
We do not link kernels to the PT2 quantization ops, so we need to
replace them with cadence ops at all optimization levels.
"""
def call_operator(
self,
op,
args: Tuple[Argument, ...],
kwargs: Dict[str, Argument],
meta: NodeMetadata,
) -> ProxyValue:
if op not in {exir_ops.edge.quantized_decomposed.quantize_per_tensor.default}:
return super().call_operator(op, args, kwargs, meta)
return super().call_operator(
exir_ops.edge.cadence.quantize_per_tensor.default,
args,
kwargs,
meta,
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplacePT2DequantWithCadenceDequantPass(ExportPass):
"""
Replace the pt2 dequantization ops with cadence dequantization ops.
We do not link kernels to the PT2 quantization ops, so we need to
replace them with cadence ops at all optimization levels.
"""
def call_operator(
self,
op,
args: Tuple[Argument, ...],
kwargs: Dict[str, Argument],
meta: NodeMetadata,
) -> ProxyValue:
if op not in {exir_ops.edge.quantized_decomposed.dequantize_per_tensor.default}:
return super().call_operator(op, args, kwargs, meta)
return super().call_operator(
exir_ops.edge.cadence.dequantize_per_tensor.default,
args,
kwargs,
meta,
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceSqueezeAndUnsqueezeWithViewPass(ExportPass):
"""
When the shape is static, replace squeeze_copy and unsqueeze_copy ops with
view_copy op
"""
def call_operator(
self,
op,
args: Tuple[Argument, ...],
kwargs: Dict[str, Argument],
meta: NodeMetadata,
) -> ProxyValue:
# Instead of testing EdgeOpOverload, test EdgeOpOverloadPacket,
# which allows us to cover all overloads.
if get_edge_overload_packet(op) not in {
exir_ops.edge.aten.squeeze_copy,
exir_ops.edge.aten.unsqueeze_copy,
}:
return super().call_operator(op, args, kwargs, meta)
# Get the output tensor shape
out_shape = meta["val"].shape
# Bail out if any dim is not an int (dynamic shape)
for dim in list(out_shape):
if not isinstance(dim, int):
return super().call_operator(op, args, kwargs, meta)
# Return a view op with the new shape
view_args = (args[0], list(out_shape))
return super().call_operator(
exir_ops.edge.aten.view_copy.default, view_args, kwargs, meta
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceFunctionallyEquivalentOpTargets(ExportPass):
"""
Replace an op with a functionally equivalent op by just switching the op
target, but without incurring any change to the op args.
"""
def call_operator(self, op, args, kwargs, meta):
if op not in functionally_equivalent_op_targets:
return super().call_operator(op, args, kwargs, meta)
return super().call_operator(
functionally_equivalent_op_targets[op], args, kwargs, meta
)
@register_cadence_pass(CadencePassAttribute(opt_level=1))
class ReplaceSelectWithViewOpPass(ExportPass):
"""
If the size along the select dim is 1, then the select op can be replaced
by view op.
"""
def call_operator(self, op, args, kwargs, meta):
if op != exir_ops.edge.aten.select_copy.int:
return super().call_operator(op, args, kwargs, meta)
# Glean the shape of input and output tensor
in_tensor = args[0].to_tensor() if isinstance(args[0], ProxyValue) else args[0]
in_shape = in_tensor.shape
out_shape = meta["val"].shape
# Get the select dimension
select_dim = args[1] if args[1] >= 0 else args[1] + len(in_shape)
if in_shape[select_dim] == 1:
# Return a view op with the new shape
view_args = (args[0], list(out_shape))
return super().call_operator(
exir_ops.edge.aten.view_copy.default, view_args, kwargs, meta
)
return super().call_operator(op, args, kwargs, meta)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceTCopyWithTransposePass(ExportPass):
"""
Replace t_copy with transpose_copy.int. If the input is 1D, the t_copy is
a nop. t_copy is not supported, so this is an opt_level=0 pass.
"""
def call_operator(self, op, args, kwargs, meta):
if get_edge_overload_packet(op) != exir_ops.edge.aten.t_copy:
return super().call_operator(op, args, kwargs, meta)
# Get the input tensor shape
in_tensor = args[0].to_tensor() if isinstance(args[0], ProxyValue) else args[0]
# If the input is a 1D tensor, this t_copy is a nop, so return the input
if in_tensor.dim() <= 1:
return args[0]
assert in_tensor.dim() == 2, "t_copy expects a tensor with <= 2 dimensions"
transpose_args = (args[0], 0, 1)
return super().call_operator(
exir_ops.edge.aten.transpose_copy.int, transpose_args, kwargs, meta
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceMMWithAddMMPass(ExportPass):
"""
This pass replaces mm with addmm by introducing a zero bias.
mm is not supported, so this is an opt_level=0 pass.
"""
def call_operator(self, op, args, kwargs, meta):
if op != exir_ops.edge.aten.mm.default:
return super().call_operator(op, args, kwargs, meta)
# The mm op has two args: input, mat2
assert len(args) == 2
X, mat2 = args
# Create a zero bias tensor, and insert it as a graph buffer before the
# current node
mat2_tensor = mat2.to_tensor() if isinstance(mat2, ProxyValue) else mat2
bias_size = mat2_tensor.size(1)
zero_bias = super().call_operator(
exir_ops.edge.aten.full.default,
([bias_size], 0.0),
{"dtype": torch.float32},
meta,
)
# Replace mm with addmm
new_args = (zero_bias, X, mat2)
return super().call_operator(
exir_ops.edge.aten.addmm.default, new_args, kwargs, meta
)
@register_cadence_pass(CadencePassAttribute(opt_level=1))
class ReplaceAddMMWithLinearPass(ExportPass):
"""
This pass replaces addmm with linear op.
"""
def __init__(self):
super().__init__()
self.counter = 0
def replace_addmm_with_linear(self, graph_module: torch.fx.GraphModule):
graph = graph_module.graph
for node in graph.nodes:
# We are only interested in admm nodes
if node.target != exir_ops.edge.aten.addmm.default:
continue
# The addmm op has three concrete args: input, mat1, mat2
assert len(node.args) >= 3
(bias, mat1, mat2) = node.args[0:3]
# The other two args are optional scale args
beta = node.kwargs.get("beta", 1.0)
alpha = node.kwargs.get("alpha", 1.0)
# AddMM performs beta*bias + alpha*mm(mat1, mat2). We can convert
# it to linear op by multiplying beta to bias, and alpha to mat2.t().
# However, the following two conditions must hold:
# a. If bias is not a param, then beta must be 1.0
# b. If mat2 is not a param, then mat2 must be a transpose op. Also,
# the input to the transpose must be a param, or alpha must be 1.0.
fit_bias = is_node_with_op(bias, "get_attr") or beta == 1.0
fit_mat2 = is_node_with_op(mat2, "get_attr")
transposed_mat2 = False
if (
not fit_mat2
and is_node_with_op(mat2, "call_function")
and mat2.target == exir_ops.edge.aten.transpose_copy.int
):
mat2, transposed_mat2 = mat2.args[0], True
fit_mat2 = is_node_with_op(mat2, "get_attr") or alpha == 1.0
if not fit_bias or not fit_mat2:
continue
# Multiply bias by beta
if beta != 1.0:
assert is_node_with_op(bias, "get_attr")
bias_tensor = get_tensor_from_attr(graph_module, bias)
assert isinstance(bias_tensor, torch.Tensor)
bias_tensor = beta * bias_tensor
with graph.inserting_before(node):
bias_name = f"_bias_addmm_to_linear_{self.counter}"
graph_module.register_buffer(bias_name, bias_tensor)
bias = graph.get_attr(bias_name)
# Use associativity of scalar multiplication, and multiply alpha to mat2
if is_node_with_op(mat2, "get_attr"):
mat2_tensor = get_tensor_from_attr(graph_module, mat2)
assert isinstance(mat2_tensor, torch.Tensor)
mat2_tensor = alpha * mat2_tensor
# transpose mat2
mat2_tensor = mat2_tensor if transposed_mat2 else mat2_tensor.t()
with graph.inserting_before(node):
mat2_name = f"_mat2_addmm_to_linear_{self.counter}"
graph_module.register_buffer(mat2_name, mat2_tensor)
mat2 = graph.get_attr(mat2_name)
# Construct the linear node
linear_args = (mat1, mat2, bias)
with graph.inserting_before(node):
linear_node = graph.call_function(
exir_ops.edge.aten.linear.default, args=linear_args
)
linear_node.meta = node.meta
# Replace all the uses of the addmm op with linear op
node.replace_all_uses_with(linear_node)
self.counter += 1
graph_module.recompile()
graph_module.graph.eliminate_dead_code()
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
self.replace_addmm_with_linear(graph_module)
result = super().call(graph_module)
return result
@register_cadence_pass(CadencePassAttribute(opt_level=1))
class ReplacePermuteWithTransposePass(ExportPass):
"""
Replace permute op with transpose if the permutation is only along
two dimensions.
"""
def call_operator(self, op, args, kwargs, meta):
if op != exir_ops.edge.aten.permute_copy.default:
return super().call_operator(op, args, kwargs, meta)
# Get the old dim and new dim order
in_tensor = args[0].to_tensor() if isinstance(args[0], ProxyValue) else args[0]
old_dims = tuple(range(in_tensor.dim()))
new_dims = args[1]
# Compute the number of positions in which the old and new order differ
diff = [od for od, nd in zip(old_dims, new_dims) if od != nd]
# If the difference is in two dimensions, we can replace this permute op
# with transpose op.
if len(diff) == 2:
new_args = (args[0], diff[0], diff[1])
return super().call_operator(
exir_ops.edge.aten.transpose_copy.int, new_args, kwargs, meta
)
return (
args[0] if len(diff) == 0 else super().call_operator(op, args, kwargs, meta)
)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceConvolutionOptionalArgsWithConcreteArgsPass(ExportPass):
"""
Replace optional tensors with concrete tensors. Currently, we
replace the optional bias tensor with a zero tensor.
"""
def call_operator(self, op, args, kwargs, meta):
if get_edge_overload_packet(op) != exir_ops.edge.aten.convolution:
return super().call_operator(op, args, kwargs, meta)
# Check if the bias is already concrete
assert len(args) == 9
if args[2] is not None:
return super().call_operator(op, args, kwargs, meta)
# The bias length is the number of out channels.
out_shape = meta["val"].shape
bias_size = out_shape[1]
# Create a zero bias tensor (bias is not a constant tensor,
# so it needs to be the result of a graph operation).
zero_bias = super().call_operator(
exir_ops.edge.aten.full.default,
([bias_size], 0.0),
{"dtype": torch.float32},
meta,
)
# Replace bias with zero_bias
args = list(args)
args[2] = zero_bias
args = tuple(args)
return super().call_operator(op, args, kwargs, meta)
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceRepeatWithCatPass(ExportPass):
"""
Replace repeat op as successive cat ops along different dimensions.
repeat is not supported, so this is an opt_level=0 pass.
"""
def call_operator(self, op, args, kwargs, meta):
if op != exir_ops.edge.aten.repeat.default:
return super().call_operator(op, args, kwargs, meta)
# Extract the input tensor, and the repeats from the args
in_tensor = args[0]
repeats = args[1]
# Glean the shapes of input tensor
in_shape = list(
in_tensor.to_tensor().shape
if isinstance(in_tensor, ProxyValue)
else in_tensor.shape
)
# If the size of repeats is more than the dimensionality of the tensor,
# the output of repeat will be a higher-dimensional tensor. We reshape
# the input so that it has the same dimensionality as the output tensor.
diff = len(repeats) - len(in_shape)
assert (
diff >= 0
), "Repeat arg malformed: expected a repeat along each dimension of input tensor"
if diff > 0:
# Extend the input shape with 1's along the higher dimensions
in_shape = ([1] * diff) + in_shape
# Insert a view op that reshapes the input tensor to have same
# dimensionality as the output tensor.
in_tensor = super().call_operator(
exir_ops.edge.aten.view_copy.default,
(in_tensor, in_shape),
kwargs,
meta,
)
assert len(repeats) == len(in_shape)
# Repeat op is nothing but successive cat ops along each dimension.
for dim, repeat in reversed(list(enumerate(repeats))):
# We do not need to do anything if repeat factor is 1
if repeat == 1:
continue
cat_arg = [in_tensor] * repeat
in_tensor = super().call_operator(
exir_ops.edge.aten.cat.default, (cat_arg, dim), kwargs, meta
)
return in_tensor
@register_cadence_pass(CadencePassAttribute(opt_level=1))
class ReplacePadWithCatPass(ExportPass):
"""
Replace constant pad nd op that does padding on outer-most dimension
with Cat(left_padding_constant_tensor, X, right_padding_constant_tensor)
"""
def call_operator(self, op, args, kwargs, meta):
if op != exir_ops.edge.aten.constant_pad_nd.default:
return super().call_operator(op, args, kwargs, meta)
assert len(args) >= 2
input_node, orig_padding = args[:2]
# if there is no padding, this op will be treated in removal pass.
if not orig_padding:
return super().call_operator(op, args, kwargs, meta)
value = 0 if len(args) == 2 else args[2]
arg_shape = input_node.to_tensor().shape
padding = orig_padding + ([0] * (len(orig_padding) % 2 != 0))
assert len(padding) >= 2
(left_padding_size, right_padding_size) = padding[-2:]
# Replace only if constant_pad_nd is along the innermost padding dimension.
if (
any(x != 0 for x in padding[0:-2])
or left_padding_size < 0
or right_padding_size < 0
):
return super().call_operator(op, args, kwargs, meta)
cat_tensors = []
dim = len(arg_shape) - len(padding) // 2
# add left_padding
if left_padding_size > 0:
left_padding_shape = (
arg_shape[:dim] + (left_padding_size,) + arg_shape[dim + 1 :]
)
left_padding_node = super().call_operator(
exir_ops.edge.aten.full.default,
(
left_padding_shape,
value,
),
{"dtype": torch.float32},
meta,
)
cat_tensors.append(left_padding_node)
# input_node
cat_tensors.append(input_node)
# right_padding
if right_padding_size > 0:
right_padding_shape = (
arg_shape[:dim] + (right_padding_size,) + arg_shape[dim + 1 :]
)
right_padding_node = super().call_operator(
exir_ops.edge.aten.full.default,
(
right_padding_shape,
value,
),
{"dtype": torch.float32},
meta,
)
cat_tensors.append(right_padding_node)
assert len(cat_tensors) == 1 + (left_padding_size > 0) + (
right_padding_size > 0
)
new_args = (cat_tensors, dim)
return super().call_operator(
exir_ops.edge.aten.cat.default,
new_args,
kwargs,
meta,
)
@register_cadence_pass(CadencePassAttribute(opt_level=1))
class ReplaceConstantPadNdWithSlicePass(ExportPass):
"""
Replace constant pad nd op that does padding on outer-most dimension
with exir_ops slice(left_padding_constant_tensor, X, right_padding_constant_tensor)
"""
def call_operator(self, op, args, kwargs, meta):
if op != exir_ops.edge.aten.constant_pad_nd.default:
return super().call_operator(op, args, kwargs, meta)
assert len(args) >= 2
input_node, orig_padding = args[:2]
# if there is no padding, this op will be treated in removal pass.
if not orig_padding:
return super().call_operator(op, args, kwargs, meta)
padding = orig_padding + ([0] * (len(orig_padding) % 2 != 0))
assert len(padding) >= 2
(start, diff) = map(neg, padding[-2:])
# Replace only if constant_pad_nd is along the innermost padding dimension.
if any(x != 0 for x in padding[0:-2]) or start < 0 or diff < 0:
return super().call_operator(op, args, kwargs, meta)
arg_shape = input_node.to_tensor().shape
dim = len(arg_shape) - len(padding) // 2
stop = arg_shape[dim] - diff
assert start <= stop
new_args = (input_node, dim, start, stop)
return super().call_operator(
exir_ops.edge.aten.slice.Tensor,
new_args,
kwargs,
meta,
)
# Make that pass runnable standalone at opt level 0.
@register_cadence_pass(CadencePassAttribute(opt_level=0))
class ReplaceAtenConvolutionWithJarvisConvolutionPass(ExportPass):
"""
Replace aten convolution op with jarvis-specific convolution op, since the
aten version is not supported by jarvis.
Also remove convolution stride if the output size along the strided dimension
is 1. We can enable more transformations (e.g., conv -> linear replacement)
for unit-stride convolutions.
"""
def call_operator(self, op, args, kwargs, meta):
if get_edge_overload_packet(op) != exir_ops.edge.aten.convolution:
return super().call_operator(op, args, kwargs, meta)
# There must be 9 total args.
assert len(args) == 9
# Unpack the args
(
in_tensor,
weight,
bias,
stride,
padding,
dilation,
transposed,
output_padding,
groups,
) = args
# Currently we only handle conversion to conv1d and conv2d, therefore
# verify that the stride, padding, dilation, and output_padding have
# len <=2.
assert (
len(stride) == len(padding) == len(dilation) == len(output_padding) == 1
) or (
len(stride) == len(padding) == len(dilation) == len(output_padding) == 2
), "Can only map convolution to conv1d and conv2d at present"
target = (
exir_ops.edge.cadence.transposed_convolution.default
if transposed
else exir_ops.edge.cadence.convolution.default
)
if transposed:
# Flip the height and width dimensions of weight, since we apply a
# gather stencil. Also, the first two dimensions of weight must be
# transposed/interchanged.
# If weight is a ProxyValue, new_weight needs to be the output of a
# graph operation (in this case a transpose_copy op) to be an explicit
# ProxyValue as well. If not, the view op can be done directly on the
# tensor.
transposed_weight = (
super().call_operator(
exir_ops.edge.aten.transpose_copy.int,
(
weight,
0,
1,
),
kwargs,
meta,
)
if isinstance(weight, ProxyValue)
else weight.transpose(0, 1)
)
flipped_weight = (
super().call_operator(
exir_ops.edge.aten.flip.default,
(
transposed_weight,
[-1] if transposed_weight.to_tensor().dim() == 3 else [-1, -2],
),
kwargs,
meta,
)
if isinstance(transposed_weight, ProxyValue)
else (
transposed_weight.flip(-1)
if transposed_weight.dim() == 3
else transposed_weight.flip(-1, -2)
)
)
# From the previous checks, if flipped_weight is a FakeTensor, it has to be
# a constant (if not, it would be a ProxyValue). Mark it as such.
if isinstance(flipped_weight, FakeTensor):
flipped_weight.constant = flipped_weight
new_args = (
in_tensor,
flipped_weight,
bias,
stride,
padding,
dilation,
output_padding,
groups,
False,
)
else:
# Verify that output_padding is 0.
assert all(
x == 0 for x in output_padding
), "Cannot handle padded output in convolution"
# If the innermost dim of output tensor is 1, then the stride
# should be 1. Note that the first dimension of output tensor is
# channel
new_stride = stride.copy()
out_shape = meta["val"].shape
assert out_shape is not None
for i, e in enumerate(out_shape[2:]):
new_stride[i] = 1 if e == 1 else stride[i]
new_args = (
in_tensor,
weight,
bias,
new_stride,
padding,
dilation,
groups,
False,
)
return super().call_operator(target, new_args, kwargs, meta)
# TODO(matthiascremon): this is a fuse op, not a replace op
class ReplaceConvWithChannelLastConv:
"""
Convolution op in pytorch expects NCHW layout for input, weight, and output
tensors. However, if the input and output to the convolution op are originally
in NWHC layout, and are then permuted to conform to NCHW layout, we can fuse
the two permute ops with the convolution op, and call the NHWC layout
convolution op in Jarvis.
"""
def __init__(self):
self.counter = 0
self.graph_module = None
def __call__(self, graph_module: torch.fx.GraphModule):
self.replace_conv_with_nhwc_conv(graph_module)
def conv_layout_is_nhwc(self, node: torch.fx.Node) -> bool:
"""
Return true if the convolution input and output are connected to permute
ops, and the input/output to/from the permute ops is NHWC layout tensor.
"""
# There must only be a single user of the output node (which must be a
# permute/tranpsose op). The input of the convolution must be connected
# to a permute op, and that permute op should have a single user.
conv_inp = node.args[0]
assert isinstance(conv_inp, torch.fx.Node)
if len(node.users) != 1 or len(conv_inp.users) != 1:
return False
# Get the input and output (permute/transpose) nodes of the convolution
conv_user = list(node.users.keys())[0]
assert isinstance(conv_user, torch.fx.Node)
pt_nodes: Set[torch.fx.Node] = {conv_inp, conv_user}
# Any node in pt_nodes must not be a placeholder.
if contains_placeholder_or_param(pt_nodes):
return False
# Determine if the convolution is 1d or 2d. The output tensor must be
# 3- or 4-dimensional
out_shape = get_shape(self.graph_module, node)
assert out_shape is not None
out_dims = len(out_shape)
assert out_dims in {3, 4}, "Jarvis only supports conv1d and conv2d"
conv1d = out_dims == 3
# Get the possible targets for the nodes in pt_nodes. Since conv1d has
# 3-dimensional input and output tensors, the nodes in pt_nodes could
# be either permute or transpose op. For conv2d, the nodes in pt_nodes
# must be permute ops.
p_target = exir_ops.edge.aten.permute_copy.default
t_target = exir_ops.edge.aten.transpose_copy.int
pt_targets = [p_target] + ([t_target] if conv1d else [])
# If any node in pt_nodes is not permute op (or tranpose op for conv1d),
# bail.
if any(x.target not in pt_targets for x in pt_nodes):
return False
# Now we need to determine the dimension permutations:
# If the input had NHWC layout, which was then permuted/transposed
# by a permute/transpose op to NCHW layout, the permutation must be
# [0, 3, 2, 1] (or [0, 2, 1] for conv1d).
# If the output had NCHW layout, and was then permuted to NHWC layout,
# the permutation must be [0, 2, 3, 1] (or [0, 2, 1] for conv1d).
nhwc_permute_order = {
node.args[0]: [0, 2, 1] if conv1d else [0, 3, 1, 2],
list(node.users.keys())[0]: [0, 2, 1] if conv1d else [0, 2, 3, 1],
}
for x in pt_nodes:
order = (
x.args[1]
if x.target == p_target
else get_transposed_dims(x, list(range(out_dims)))
)
if order != nhwc_permute_order[x]:
return False
return True
def replace_conv_with_nhwc_conv(self, graph_module: torch.fx.GraphModule):
self.graph_module = graph_module
graph = graph_module.graph
for node in graph.nodes:
# We are only interested in convolution nodes that have NHWC layout
if node.target not in {
exir_ops.edge.cadence.quantized_conv.default,
exir_ops.edge.cadence.convolution.default,
exir_ops.edge.cadence.quantized_transposed_conv.default,
exir_ops.edge.cadence.transposed_convolution.default,
} or not self.conv_layout_is_nhwc(node):
continue
# Get the args of convolution op
args = list(node.args)
# The input is connected to a permute/transpose op that converts the
# NHWC layout to NCHW layout. The input of the permute op will become
# this convolution op's input.
in_tp = args[0]
args[0] = in_tp.args[0]
# The weight is in NHWC layout. Permute it to NHWC layout.
weight_tensor = get_tensor_from_attr(graph_module, args[1])
assert isinstance(weight_tensor, torch.Tensor)
# We cannot directly permute a per-channel quantized tensor. We will
# dequantize it, permute the fp32 tensor, and then requantize the
# permuted tensor.
if (
is_quantized_tensor(weight_tensor)
and weight_tensor.qscheme() == torch.per_channel_affine
):
# We have already asserted during quantizing conv op that the
# quantization axis is 0.
dequant_weight = weight_tensor.dequantize()
dequant_weight = (
dequant_weight.permute([0, 2, 1])
if dequant_weight.dim() == 3
else dequant_weight.permute([0, 2, 3, 1])
)
weight_tensor = torch.quantize_per_channel(
dequant_weight.contiguous(),
weight_tensor.q_per_channel_scales(),
weight_tensor.q_per_channel_zero_points(),
0,
weight_tensor.dtype,
)
else:
weight_tensor = (
weight_tensor.permute([0, 2, 1])
if weight_tensor.dim() == 3
else weight_tensor.permute([0, 2, 3, 1])
)
# Make the weight tensor contiguous, since we have permuted it.
weight_tensor = weight_tensor.contiguous()
# Add the permuted weight into the graph, and update the weight in
# args.
with graph.inserting_before(node):
weight_name = f"_weight_nhwc_{self.counter}"
graph_module.register_buffer(weight_name, weight_tensor)
weight = graph.get_attr(weight_name)
args[1] = weight
# The 'channel_last' arg is True. It is the last arg.
args[-1] = True
# Now update the convolution node args to mark it as NHWC convolution
node.args = tuple(args)
# Replace all the uses of the permute op connected to the output op
# with this convolution.
out_tp = list(node.users.keys())[0]
out_tp.replace_all_uses_with(node)
node.meta = out_tp.meta
# Erase the permute ops connected to the input and output of the
# convolution op.
graph.erase_node(in_tp)
graph.erase_node(out_tp)
self.counter += 1
graph_module.recompile()
# This pass needs to be reworked to be compatible with PT2. It is an optimization
# pass anyway, so move it to opt level 2.
# TODO(matthiascremon): update and improve this pass.
@register_cadence_pass(CadencePassAttribute(opt_level=2))
class ReplaceConvWithChannelLastConvPass(ExportPass):
"""
Replace the ATen convolution op with custom conv op with NCHW or NHWC layout
input tensors, depending on the presence of permute/transpose ops connected
to the input tensor.
"""
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
result = ReplaceAtenConvolutionWithJarvisConvolutionPass()(graph_module)
assert result is not None
ReplaceConvWithChannelLastConv()(result.graph_module)
return result
@register_cadence_pass(CadencePassAttribute(opt_level=1))
class ReplaceTrivialConvWithLinear(ExportPass):
"""
In nn.Conv1d, the operand shapes are:
input - [batch, in_channels, in_length]
weight - [out_channels, in_channels, weight_length]
output - [batch, out_channels, out_length]
When in_length == weight_length, out_length = 1. In this scenario, we can
view the input as a tensor shaped [batch, K], and weight as a tensor
shaped [out_channels, K], and replace nn.Conv1d with nn.Linear. This
optimization can be extended to nn.Conv2d as well, where in_length is a 2d
image, and weight_length can be replaced with a 2d filter the same shape as
the image.
"""
trivial_conv_op_to_linear_op: Dict[EdgeOpOverload, EdgeOpOverload] = {
exir_ops.edge.cadence.convolution.default: exir_ops.edge.aten.linear.default,
exir_ops.edge.cadence.quantized_conv.default: exir_ops.edge.cadence.quantized_linear.default,
}
def call_operator(self, op, args, kwargs, meta):
if op not in self.trivial_conv_op_to_linear_op:
return super().call_operator(op, args, kwargs, meta)
# Parse the necessary args of the convolution node. Both convolution
# and quantized_conv have the same first 8 args. The quantized op has