forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpasses.cpp
1435 lines (1291 loc) · 52.9 KB
/
passes.cpp
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
#include <torch/csrc/jit/runtime/static/passes.h>
#include <torch/csrc/jit/ir/alias_analysis.h>
#include <torch/csrc/jit/ir/subgraph_matcher.h>
#include <torch/csrc/jit/passes/constant_pooling.h>
#include <torch/csrc/jit/passes/constant_propagation.h>
#include <torch/csrc/jit/passes/subgraph_rewrite.h>
#include <torch/csrc/jit/passes/variadic_ops.h>
#include <torch/csrc/jit/runtime/graph_iterator.h>
#include <torch/csrc/jit/runtime/static/ops.h>
C10_DEFINE_bool(
enable_clip_ranges_gather_fusions,
true,
"If on, static runtime or optimize_sparse_nn_model will fuse clip ranges gather ops.");
namespace torch {
namespace jit {
bool graphHasOp(std::shared_ptr<Graph>& graph, const char* op_name) {
DepthFirstGraphNodeIterator graph_it(graph);
for (auto node = graph_it.next(); node != nullptr; node = graph_it.next()) {
const char* node_qual_string = node->kind().toQualString();
if (strcmp(node_qual_string, op_name) == 0) {
return true;
}
}
return false;
}
bool forwardHasOp(
const torch::jit::script::Module& module,
const char* op_name) {
using Method = ::torch::jit::Method;
Method method = module.get_method("forward");
auto graph = method.graph();
return graphHasOp(graph, op_name);
}
namespace {
C10_UNUSED
void ConcatAddMulReplaceNaNClip(std::shared_ptr<torch::jit::Graph>& graph) {
// TODO:: check restrictions for inputs; outputs not used elsewhere
std::string pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h, %i, %j):
%y0 = aten::cat(%a, %b)
%y1 = aten::add(%y0, %c, %d)
%y2 = aten::mul(%y1, %e)
%y3 = aten::nan_to_num(%y2, %f, %g, %h)
%res = aten::clamp(%y3, %i, %j)
return (%res))IR";
std::string pattern2 = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h, %i, %j):
%y0 = aten::cat(%a, %b)
%y1 = aten::add(%y0, %c, %d)
%y2 = aten::mul(%y1, %e)
%y3 = aten::nan_to_num_(%y2, %f, %g, %h)
%res = aten::clamp(%y3, %i, %j)
return (%res))IR";
std::string pattern3 = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h, %i, %j):
%y0 = aten::cat(%a, %b)
%y1 = aten::add(%y0, %c, %d)
%y2 = aten::mul(%y1, %e)
%y3 = aten::nan_to_num_(%y2, %f, %g, %h)
%res = aten::clamp_(%y3, %i, %j)
return (%res))IR";
std::string pattern4 = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h, %i, %j):
%y0 = aten::cat(%a, %b)
%y1 = aten::add(%y0, %c, %d)
%y2 = aten::mul(%y1, %e)
%y3 = aten::nan_to_num(%y2, %f, %g, %h)
%res = aten::clamp_(%y3, %i, %j)
return (%res))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h, %i, %j):
%res = fb::concat_add_mul_replacenan_clip(%c, %e, %a, %i, %j, %b)
return (%res))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
fuse.RegisterRewritePattern(pattern2, fused_pattern);
fuse.runOnGraph(graph);
fuse.RegisterRewritePattern(pattern3, fused_pattern);
fuse.runOnGraph(graph);
fuse.RegisterRewritePattern(pattern4, fused_pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED
void CastedBatchOneHotLengths(std::shared_ptr<torch::jit::Graph>& graph) {
// TODO:: check restrictions for inputs; outputs not used elsewhere
std::string pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g):
%y0 : Tensor = aten::to(%a, %b, %c, %c, %d)
%y1 : Tensor = fb::batch_one_hot_lengths(%y0, %e, %f)
%res : Tensor = aten::to(%y1, %g, %c, %c, %d)
return (%res))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g):
%res : Tensor = fb::casted_batch_one_hot_lengths(%a, %e, %f)
return (%res))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
std::string pattern2 = R"IR(
graph(%a, %b, %c, %d, %e, %f):
%y0 : Tensor = aten::to(%a, %b, %c, %c)
%y1 : Tensor = fb::batch_one_hot_lengths(%y0, %d, %e)
%res : Tensor = aten::to(%y1, %f, %c, %c)
return (%res))IR";
std::string fused_pattern2 = R"IR(
graph(%a, %b, %c, %d, %e, %f):
%res : Tensor = fb::casted_batch_one_hot_lengths(%a, %d, %e)
return (%res))IR";
fuse.RegisterRewritePattern(pattern2, fused_pattern2);
fuse.runOnGraph(graph);
}
C10_UNUSED
void ConcatBatchMatMulBatchGather(std::shared_ptr<torch::jit::Graph>& graph) {
std::string pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f):
%y0 : Tensor = aten::stack(%a, %b)
%y1 : Tensor = aten::transpose(%y0, %b, %c)
%y2 : Tensor = aten::bmm(%y0, %y1)
%y3 : Tensor = aten::flatten(%y2, %d, %e)
%res : Tensor = aten::index_select(%y3, %b, %f)
return (%res))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f):
%res : Tensor = fb::concat_batch_matmul_batch_gather(%f, %a)
return (%res))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
// this pattern found in several models has a redundant second `flatten`
std::string pattern_broadcast = R"IR(
graph(%a, %b, %c, %d, %e, %indices):
%y0 : Tensor = fb::broadcast_stack(%a, %b)
%y1 : Tensor = aten::transpose(%y0, %b, %c)
%y2 : Tensor = aten::matmul(%y0, %y1)
%y3 : Tensor = aten::flatten(%y2, %b, %e)
%y4 : Tensor = aten::flatten(%y3, %d, %d)
%res : Tensor = aten::index_select(%y4, %b, %indices)
return (%res))IR";
std::string fused_pattern_broadcast = R"IR(
graph(%a, %b, %c, %d, %e, %indices):
%res : Tensor = fb::broadcast_concat_batch_matmul_batch_gather(%indices, %a)
return (%res))IR";
fuse.RegisterRewritePattern(pattern_broadcast, fused_pattern_broadcast);
std::string pattern_broadcast2 = R"IR(
graph(%a, %b, %c, %d, %indices):
%y0 : Tensor = fb::broadcast_stack(%a, %b)
%y1 : Tensor = aten::transpose(%y0, %b, %c)
%y2 : Tensor = aten::matmul(%y0, %y1)
%y3 : Tensor = aten::flatten(%y2, %b, %d)
%res : Tensor = aten::index_select(%y3, %b, %indices)
return (%res))IR";
std::string fused_pattern_broadcast2 = R"IR(
graph(%a, %b, %c, %d, %indices):
%res : Tensor = fb::broadcast_concat_batch_matmul_batch_gather(%indices, %a)
return (%res))IR";
fuse.RegisterRewritePattern(pattern_broadcast2, fused_pattern_broadcast2);
fuse.runOnGraph(graph);
}
C10_UNUSED void ClipRangesGatherRangesLengthsToOffsets(
std::shared_ptr<torch::jit::Graph>& graph) {
// TODO:: check restrictions for inputs; outputs not used elsewhere
std::string pattern = R"IR(
graph(%a, %b, %c, %d):
%y0 : Tensor = fb::clip_ranges(%b, %c)
%y1 : Tensor, %y2 : Tensor = fb::gather_ranges(%a, %y0)
%y3 : Tensor = fb::lengths_to_offsets(%y2, %d)
return (%y3, %y1))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather_lengths_to_offsets(%a, %b, %c, %d)
return (%y1, %y0))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED void ClipRangesGather(std::shared_ptr<torch::jit::Graph>& graph) {
// TODO:: check restrictions for inputs; outputs not used elsewhere
// fuse without lengths-to-offsets
std::string pattern = R"IR(
graph(%a, %b, %c):
%y0 : Tensor = fb::clip_ranges(%b, %c)
%y1 : Tensor, %y2 : Tensor = fb::gather_ranges(%a, %y0)
return (%y2, %y1))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather(%a, %b, %c)
return (%y1, %y0))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED void PrecomputeMultiplierShiftForSigridHash(
std::shared_ptr<torch::jit::Graph>& graph) {
std::string pattern = R"IR(
graph(%a, %b, %c, %d):
%y0 : Tensor = fb::sigrid_hash(%a, %b, %c, %d)
return (%y0)
)IR";
std::string split_pattern = R"IR(
graph(%a, %b, %c, %d):
%y0 : Tensor = fb::sigrid_hash_compute_multipler_shift(%c)
%y2 : Tensor = fb::sigrid_hash_precompute(%a, %b, %c, %y0, %d)
return (%y2)
)IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, split_pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED void ClipRangesToGatherToOffsets(
std::shared_ptr<torch::jit::Graph>& graph) {
std::string pattern = R"IR(
graph(%a, %b, %c, %d, %to0_in0, %to0_in1, %to0_in2):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather(%a, %b, %c)
%y2 : Tensor = aten::to(%y1, %to0_in0, %to0_in1, %to0_in1, %to0_in2)
%y3 : Tensor = fb::lengths_to_offsets(%y2, %d)
return (%y3, %y0))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d, %to0_in0, %to0_in1, %to0_in2):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather_to_offsets(%a, %b, %c, %d, %to0_in0)
return (%y1, %y0))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
std::string pattern2 = R"IR(
graph(%a, %b, %c, %d, %to0_in0, %to0_in1):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather(%a, %b, %c)
%y2 : Tensor = aten::to(%y1, %to0_in0, %to0_in1, %to0_in1)
%y3 : Tensor = fb::lengths_to_offsets(%y2, %d)
return (%y3, %y0))IR";
std::string fused_pattern2 = R"IR(
graph(%a, %b, %c, %d, %to0_in0, %to0_in1):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather_to_offsets(%a, %b, %c, %d, %to0_in0)
return (%y1, %y0))IR";
fuse.RegisterRewritePattern(pattern2, fused_pattern2);
fuse.runOnGraph(graph);
}
C10_UNUSED void ToLengthsToOffsets(std::shared_ptr<torch::jit::Graph>& graph) {
std::string pattern = R"IR(
graph(%a, %includelastoffset, %dtype, %nonblocking, %copy, %memoryformat):
%y0 : Tensor = aten::to(%a, %dtype, %nonblocking, %copy, %memoryformat)
%y1 : Tensor = fb::lengths_to_offsets(%y0, %includelastoffset)
return (%y1))IR";
std::string fused_pattern = R"IR(
graph(%a, %includelastoffset, %dtype, %nonblocking, %copy, %memoryformat):
%y0 : Tensor = fb::to_lengths_to_offsets(%a, %includelastoffset, %dtype)
return (%y0))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
std::string pattern2 = R"IR(
graph(%a, %includelastoffset, %dtype, %nonblocking, %copy):
%y0 : Tensor = aten::to(%a, %dtype, %nonblocking, %copy)
%y1 : Tensor = fb::lengths_to_offsets(%y0, %includelastoffset)
return (%y1))IR";
std::string fused_pattern2 = R"IR(
graph(%a, %includelastoffset, %dtype, %nonblocking, %copy):
%y0 : Tensor = fb::to_lengths_to_offsets(%a, %includelastoffset, %dtype)
return (%y0))IR";
fuse.RegisterRewritePattern(pattern2, fused_pattern2);
fuse.runOnGraph(graph);
}
C10_UNUSED
void ClipRangesGatherSigridHash(std::shared_ptr<torch::jit::Graph>& graph) {
// TODO:: check restrictions for inputs; outputs not used elsewhere
std::string pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h):
%y0 : Tensor, %y1 : Tensor = fb::clip_ranges_gather_lengths_to_offsets(%a, %b, %c, %d)
%y2 : Tensor = fb::sigrid_hash_precompute(%y0, %e, %f, %g, %h)
return (%y2, %y1))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g, %h):
%off : Tensor, %out : Tensor = fb::clip_ranges_gather_sigrid_hash_precompute_offsets(%b, %a, %c, %e, %f, %g, %h, %d)
return (%out, %off))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED void ClipRangesGatherRangesSigridHash(
std::shared_ptr<torch::jit::Graph>& graph) {
std::string pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g):
%y0 : Tensor = fb::clip_ranges(%b, %c)
%y1 : Tensor, %y2 : Tensor = fb::gather_ranges(%a, %y0)
%y3 : Tensor = fb::sigrid_hash_precompute(%y1, %d, %e, %f, %g)
return (%y3, %y2))IR";
std::string fused_pattern = R"IR(
graph(%a, %b, %c, %d, %e, %f, %g):
%off : Tensor, %out : Tensor = fb::clip_ranges_gather_sigrid_hash_precompute_v3(%b, %a, %c, %d, %e, %f, %g)
return (%out, %off))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED void ClipRangesGatherRangesX2SigridHashPrecompute(
std::shared_ptr<torch::jit::Graph>& graph) {
// Placeholder is a dummy op used to capture the first subgraph
std::string pattern = R"IR(
graph(%ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32):
%clipped : Tensor = fb::clip_ranges(%ranges, %max_length)
%output : Tensor, %unused : Tensor = fb::gather_ranges(%values, %clipped)
%sigrid_hash_out : Tensor = fb::sigrid_hash_precompute(%output, %salt, %max_value, %mul_shift, %hash_into_int32)
return (%sigrid_hash_out, %clipped))IR";
std::string fused_pattern = R"IR(
graph(%ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32):
%sigrid_hash_out : Tensor, %clipped : Tensor = fb::placeholder(%ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32)
return (%sigrid_hash_out, %clipped))IR";
// the second gather_ranges can be eliminated because the `lengths` is
// produces is identical to the lengths produced by
// clip_ranges_gather_sigrid_hash_v3 (caveat, the fused ops makes some
// simplifying assumptions about the ranges input)
std::string pattern2 = R"IR(
graph(%gather2_values, %ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32):
%sigrid_hash_out : Tensor, %clipped : Tensor = fb::placeholder(%ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32)
%unused : Tensor, %lengths : Tensor = fb::gather_ranges(%gather2_values, %clipped)
return (%lengths, %sigrid_hash_out))IR";
std::string fused_pattern2 = R"IR(
graph(%gather2_values, %ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32):
%lengths : Tensor, %sigrid_hash_out : Tensor = fb::clip_ranges_gather_sigrid_hash_precompute_v3(%ranges, %values, %max_length, %salt, %max_value, %mul_shift, %hash_into_int32)
return (%lengths, %sigrid_hash_out))IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
fuse.RegisterRewritePattern(pattern2, fused_pattern2);
fuse.runOnGraph(graph);
// reverse the ops that got fused in step 1 but not in step2
fuse.RegisterRewritePattern(fused_pattern, pattern);
fuse.runOnGraph(graph);
}
C10_UNUSED void SplitOutPrecomputeOpsForSparseNN(
std::shared_ptr<torch::jit::Graph>& graph) {
#ifdef FBCODE_CAFFE2
PrecomputeMultiplierShiftForSigridHash(graph);
ConstantPropagation(graph);
ConstantPooling(graph);
#endif
}
} // namespace
void FuseInferenceOpsForSparseNN(std::shared_ptr<torch::jit::Graph>& graph) {
#ifdef FBCODE_CAFFE2
SplitOutPrecomputeOpsForSparseNN(graph);
ConcatAddMulReplaceNaNClip(graph);
CastedBatchOneHotLengths(graph);
ConcatBatchMatMulBatchGather(graph);
if (FLAGS_enable_clip_ranges_gather_fusions) {
ClipRangesGatherRangesLengthsToOffsets(graph);
}
ClipRangesGatherSigridHash(graph);
ClipRangesGatherRangesSigridHash(graph);
ClipRangesGatherRangesX2SigridHashPrecompute(graph);
if (FLAGS_enable_clip_ranges_gather_fusions) {
// prioritize clip_ranges+gather_ranges+sigrid_hash fusion over
// clip_ranges+gather_ranges
ClipRangesGather(graph);
ClipRangesToGatherToOffsets(graph);
}
ToLengthsToOffsets(graph);
#endif
}
TORCH_LIBRARY_FRAGMENT(static_runtime, m) {
m.def(torch::schema(
"static_runtime::permute_copy(Tensor self, int[] dims) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::reshape_copy(Tensor self, int[] shape) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::flatten_copy.using_ints(Tensor self, int start_dim=0, int end_dim=-1) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::expand_dims_copy(Tensor input, int[] dims) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::to_maybe_copy_out.prim_dtype(Tensor self, int? dtype=None, bool non_blocking=False, bool copy=False) -> (Tensor, bool)",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::to_maybe_copy_out.dtype(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> (Tensor, bool)",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::to_maybe_copy_out.other(Tensor self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> (Tensor, bool)",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::to_copy.prim_dtype(Tensor self, int? dtype=None, bool non_blocking=False, bool copy=False) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::to_copy.dtype(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::to_copy.other(Tensor self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::layer_norm(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> (Tensor, Tensor, Tensor)",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def("static_runtime::signed_log1p(Tensor input) -> Tensor");
m.def(torch::schema(
"static_runtime::dict_unpack(...) -> ...",
c10::AliasAnalysisKind::CONSERVATIVE));
m.def(torch::schema(
"static_runtime::VarTupleUnpack(...) -> ...",
c10::AliasAnalysisKind::CONSERVATIVE));
m.def(torch::schema(
"static_runtime::fused_equally_split(Tensor input, int num_split, int dim) -> ...",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::dequantize_copy.self(Tensor self) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::select_tensor(Tensor(a) a, Tensor(b) b, bool use_b) -> Tensor(a|b)",
c10::AliasAnalysisKind::FROM_SCHEMA));
m.def(torch::schema(
"static_runtime::create_owned_ref(...) -> ...",
c10::AliasAnalysisKind::CONSERVATIVE));
m.def(torch::schema(
"static_runtime::embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor)",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::embedding_bag.padding_idx(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, bool include_last_offset, int? padding_idx) -> (Tensor, Tensor, Tensor)",
c10::AliasAnalysisKind::PURE_FUNCTION));
m.def(torch::schema(
"static_runtime::clamp_nan_to_num(Tensor input, Scalar? min, Scalar? max, float? nan, float? posinf, float? posinf) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));
}
void FuseSignLog1P(std::shared_ptr<torch::jit::Graph>& graph) {
std::string pattern = R"IR(
graph(%input):
%0 : Tensor = aten::sign(%input)
%1 : Tensor = aten::abs(%input)
%2 : Tensor = aten::log1p(%1)
%res : Tensor = aten::mul(%0, %2)
return (%res)
)IR";
std::string fused_pattern = R"IR(
graph(%input):
%res : Tensor = static_runtime::signed_log1p(%input)
return (%res)
)IR";
SubgraphRewriter fuse;
fuse.RegisterRewritePattern(pattern, fused_pattern);
fuse.runOnGraph(graph);
}
namespace {
using TupleUnpackBlock = std::vector<Node*>;
std::vector<TupleUnpackBlock> CollectVariadicTupleUnpackFusionCandidates(
const std::shared_ptr<Graph>& graph) {
std::vector<TupleUnpackBlock> candidates;
auto nodes = graph->nodes();
std::vector<Node*> block;
for (Node* cur_node : nodes) {
if (cur_node->kind() == prim::TupleUnpack) {
block.push_back(cur_node);
continue;
}
if (block.size() > 1) {
candidates.emplace_back(std::move(block));
}
block.clear();
}
TORCH_CHECK(block.empty());
return candidates;
}
void FuseTupleUnpackBlock(const TupleUnpackBlock& nodes) {
TORCH_CHECK(nodes.size() > 0);
auto graph = nodes[0]->owningGraph();
auto var_unpack = graph->create(
fromQualString("static_runtime::VarTupleUnpack"),
/* num_outputs */ 0);
var_unpack->insertAfter(nodes[nodes.size() - 1]);
for (Node* node : nodes) {
TORCH_CHECK(
node->kind() == prim::TupleUnpack && node->inputs().size() == 1);
var_unpack->addInput(node->input());
for (Value* output : node->outputs()) {
auto new_output = var_unpack->addOutput();
new_output->copyMetadata(output);
output->replaceAllUsesWith(new_output);
}
node->destroy();
}
}
} // namespace
void UseVariadicTupleUnpack(const std::shared_ptr<Graph>& graph) {
for (auto& c : CollectVariadicTupleUnpackFusionCandidates(graph)) {
FuseTupleUnpackBlock(c);
}
}
// This macro makes maps from c10::Symbol -> c10::Symbol a lot easier to read.
#define OP_PAIR(first, second) \
{ fromQualString(first), fromQualString(second) }
// Out variants of ops cannot participate in memory planning if they
// have outputs that alias inputs. For ops that either return their
// input directly or copy it (most notably aten::to), we adopt the
// following strategy instead of directly making them out variants so
// that they can participate in memory planning anyway. Let `a` denote
// the input Tensor to the op.
//
// 1) Pass `a` (and the other operator inputs) to a special
// `static_runtime::$OP_maybe_copy_out` variant of the op. This op
// returns a normal output Tensor (call it `b_out` as well as a
// `did_copy` flag indicating whether the output should be used. If
// `did_copy` is false, the value of `b_out` is unspecified. Note that
// this operator is an ordinary out variant that is perfectly amenable
// to memory planning.
//
// 2) Pass `a`, `b_out`, and `did_copy` to a special
// `static_runtime::select_tensor` op, which returns `b_out` if
// `did_copy` is true and `a` otherwise. Note that this operator does
// not need to participate in memory planning because its output
// always aliases one of its inputs.
//
// Here is an illustration:
//
// |
// |----------------------+ a
// | v
// | +------------------------------------+
// | | |
// | | static_runtime::$OP_maybe_copy_out |
// | | |
// | +------------------+--------+--------+
// | | |
// +--------------+ | b_out | did_copy
// | a | |
// v v v
// +------------------------------------+
// | |
// | static_runtime::select_tensor |
// | |
// +------------------+-----------------+
// |
// |
// | either a or b_out
// |
// v
void ReplaceWithMaybeCopy(
std::shared_ptr<Graph>& graph,
bool outputs_are_immutable) {
AliasDb db(graph);
// for ops that have overloads, match the schema
static const std::array<std::pair<c10::FunctionSchema, c10::Symbol>, 3> supported_schema =
{{{torch::schema(
"aten::to.prim_dtype(Tensor(a) self, int? dtype=None, bool non_blocking=False, bool copy=False) -> Tensor(a|b)"),
fromQualString("static_runtime::to_maybe_copy_out")},
{torch::schema(
"aten::to.dtype(Tensor(a) self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)"),
fromQualString("static_runtime::to_maybe_copy_out")},
{torch::schema(
"aten::to.other(Tensor(a) self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)"),
fromQualString("static_runtime::to_maybe_copy_out")}}};
auto match_schema = [](const Node* node, c10::Symbol& out_matched_symbol) {
for (auto& schema : supported_schema) {
if (node->matches(schema.first)) {
out_matched_symbol = schema.second;
return true;
}
}
return false;
};
// old node, new node, select_tensor node
std::vector<std::tuple<Node*, Node*, Node*>> replacement;
DepthFirstGraphNodeIterator graph_it(graph);
for (auto n = graph_it.next(); n != nullptr; n = graph_it.next()) {
c10::Symbol new_symbol;
if (!match_schema(n, new_symbol)) {
continue;
}
TORCH_CHECK(n->outputs().size() == 1);
// Duplicate input writers guard from ReplaceWithCopy below.
if (db.hasInputWriters(n)) {
continue;
}
auto* out = n->output();
if (!outputs_are_immutable && db.mayContainAlias(out, graph->outputs())) {
continue;
}
// Add the did_copy flag to outputs.
auto* new_node = graph->create(new_symbol, n->outputs().size() + 1);
for (auto* input : n->inputs()) {
new_node->addInput(input);
}
new_node->outputs().at(1)->setType(c10::BoolType::get());
static const auto select_tensor_symbol =
fromQualString("static_runtime::select_tensor");
auto* select_tensor_node = graph->create(select_tensor_symbol, 1);
TORCH_DCHECK_EQ(new_node->outputs().size(), 2);
select_tensor_node->addInput(n->input(0));
for (auto* output : new_node->outputs()) {
select_tensor_node->addInput(output);
}
replacement.emplace_back(n, new_node, select_tensor_node);
}
for (const auto& tup : replacement) {
auto* const old_node = std::get<0>(tup);
auto* const new_node = std::get<1>(tup);
auto* const select_tensor_node = std::get<2>(tup);
new_node->insertBefore(old_node);
select_tensor_node->insertBefore(old_node);
new_node->outputs()[0]->copyMetadata(old_node->output());
select_tensor_node->output()->copyMetadata(old_node->output());
old_node->replaceAllUsesWith(select_tensor_node);
old_node->destroy();
}
#ifndef NDEBUG
graph->lint();
AliasDb db2(graph);
torch::jit::Lint(&db2);
#endif
}
void ReplaceWithCopyImpl(
std::shared_ptr<Graph>& graph,
const FastMap<c10::Symbol, c10::Symbol>& supported,
const std::vector<std::pair<c10::FunctionSchema, c10::Symbol>>&
supported_schema,
const std::function<bool(Node*)>& f_extra_checks,
bool outputs_are_immutable) {
AliasDb db(graph);
auto match_schema = [&supported_schema](
const Node* node, c10::Symbol& out_matched_symbol) {
for (auto& schema : supported_schema) {
if (node->matches(schema.first)) {
out_matched_symbol = schema.second;
return true;
}
}
return false;
};
std::vector<std::pair<Node*, Node*>> replacement;
DepthFirstGraphNodeIterator graph_it(graph);
for (auto n = graph_it.next(); n != nullptr; n = graph_it.next()) {
c10::Symbol new_symbol;
if (supported.count(n->kind()) && opIsRegistered(supported.at(n->kind()))) {
new_symbol = supported.at(n->kind());
} else if (!match_schema(n, new_symbol)) {
continue;
}
TORCH_CHECK(n->outputs().size() == 1);
// We do not want to replace operators with their copy variant when the
// inputs to the operators have writers (can be updated). With an output
// that aliases to the input, updates to the input will be visible to the
// operator's output as well. For example:
//
// def forward(self, inp: Tensor, shape: List[int]):
// a = inp + inp
// b = a.reshape(shape)
// c = b.sigmoid_()
// d = c + c
// e = a + a
// f = b + b
// return (d, e, f)
//
// b and c are aliases of a, sigmoid_ changes b, c, as well as a. e should
// equal to d in this case. If we replace reshape with the copy version, b
// and c are no longer aliases of a, the value of e would change as a
// result. To keep static runtime consistent with the jit interpreter, here
// we choose not to replace reshape with the copy version
if (db.hasInputWriters(n)) {
continue;
}
auto* out = n->output();
if (!outputs_are_immutable && db.mayContainAlias(out, graph->outputs())) {
continue;
}
if (!f_extra_checks(n)) {
continue;
}
auto* new_node = graph->create(new_symbol, n->outputs().size());
for (auto* input : n->inputs()) {
new_node->addInput(input);
}
replacement.emplace_back(n, new_node);
}
for (const auto& p : replacement) {
auto* old_node = p.first;
auto* new_node = p.second;
new_node->insertBefore(old_node);
new_node->output()->copyMetadata(old_node->output());
old_node->replaceAllUsesWith(new_node);
old_node->destroy();
}
#ifndef NDEBUG
graph->lint();
AliasDb db2(graph);
torch::jit::Lint(&db2);
#endif
}
// replace aten::permute with copy version only when it's followed by
// reshape/flatten. It's only enabled when ReplaceWithCopy is off.
void ReplacePermuteWithCopy(
std::shared_ptr<Graph>& graph,
bool outputs_are_immutable) {
AliasDb db(graph);
const FastMap<c10::Symbol, c10::Symbol> supported = {
#ifdef FBCODE_CAFFE2
OP_PAIR("aten::permute", "static_runtime::permute_copy"),
#endif
};
auto f_extra_checks = [](Node* n) {
Value* out = n->output();
Node* next_node = out->uses()[0].user;
if (next_node->kind() != aten::reshape ||
next_node->kind() != aten::flatten) {
return true;
}
return false;
};
ReplaceWithCopyImpl(
graph, supported, {}, f_extra_checks, outputs_are_immutable);
}
void ReplaceWithCopy(
std::shared_ptr<Graph>& graph,
bool outputs_are_immutable) {
AliasDb db(graph);
const FastMap<c10::Symbol, c10::Symbol> supported = {
#ifdef FBCODE_CAFFE2
OP_PAIR("aten::permute", "static_runtime::permute_copy"),
OP_PAIR("fb::expand_dims", "static_runtime::expand_dims_copy"),
#endif
OP_PAIR("aten::narrow", "aten::narrow_copy"),
OP_PAIR("aten::reshape", "static_runtime::reshape_copy"),
OP_PAIR("aten::flatten", "static_runtime::flatten_copy")};
static const std::vector<std::pair<c10::FunctionSchema, c10::Symbol>>
supported_schema = {
{{torch::schema("aten::dequantize.self(Tensor self) -> Tensor"),
fromQualString("static_runtime::dequantize_copy")}}};
ReplaceWithCopyImpl(
graph,
supported,
supported_schema,
[](Node* n) { return true; },
outputs_are_immutable);
}
void EliminateTrivialEquallySplit(std::shared_ptr<torch::jit::Graph>& graph) {
const auto equally_split = fromQualString("fb::equally_split");
std::vector<Node*> to_remove;
DepthFirstGraphNodeIterator graph_it(graph);
for (auto node = graph_it.next(); node != nullptr; node = graph_it.next()) {
if (node->kind() != equally_split) {
continue;
}
const Value* value_out = node->outputs()[0];
if (value_out->uses().size() != 1) {
continue;
}
Node* list_unpack_node = value_out->uses()[0].user;
if (list_unpack_node->kind() != prim::ListUnpack) {
continue;
}
auto list_unpack_outputs = list_unpack_node->outputs();
if (list_unpack_outputs.size() != 1) {
continue;
}
list_unpack_node->output()->replaceAllUsesWith(node->input(0));
to_remove.push_back(list_unpack_node);
to_remove.push_back(node);
}
for (Node* node : to_remove) {
node->destroy();
}
}
namespace {
bool shouldNotFuseListUnpackSpecialCase(const Node* node) {
const static std::array<c10::Symbol, 3> sigrid_transforms_symbols{
c10::Symbol::fromQualString("fb::variadic_sigrid_transforms_torch_bind"),
c10::Symbol::fromQualString("fb::sigrid_transforms_torch_bind"),
c10::Symbol::fromQualString("fb::sigrid_transforms")};
if (std::find(
sigrid_transforms_symbols.begin(),
sigrid_transforms_symbols.end(),
node->kind()) == sigrid_transforms_symbols.end()) {
return false;
}
// To fuse with sigrid transforms, we must be able to statically determine
// `instance` and `use_offsets` - these two together let us statically
// determine the types of the outputs. Rationale: it is a huge pain to write
// fused sigrid transforms without static type information, and these two
// arguments are indeed statically known in every model we've seen.
// The reason why trying to fuse the outputs is annoying without static type
// information is that, if one of the outputs is not managed, you need to
// reset to an empty tensor of the correct type each iteration. So, if we
// can't collect types ahead of time, we would have to do it lazily on the
// first iteration, which would could be wasteful in terms of time/memory
// - either each thread would have its own set of output types, or we would
// need a lock to prevent data races.
const auto num_inputs = node->inputs().size();
return !toIValue(node->input(0)).has_value() ||
!toIValue(node->input(num_inputs - 1)).has_value();
}
} // namespace
void FuseListUnpack(std::shared_ptr<torch::jit::Graph>& graph) {
const FastMap<c10::Symbol, c10::Symbol> unfused_to_fused = {
OP_PAIR(
"torcharrow::inference_wrapper_run_flat",
"static_runtime::fused_inference_wrapper_run_flat"),
OP_PAIR(
"torcharrow::variadic_inference_wrapper_run_flat",
"static_runtime::fused_variadic_inference_wrapper_run_flat"),
OP_PAIR("fb::equally_split", "static_runtime::fused_equally_split"),
OP_PAIR(
"fb::sigrid_transforms", "static_runtime::fused_sigrid_transforms"),
OP_PAIR(
"static_runtime::variadic_grouped_accessor_op_v2",
"static_runtime::fused_variadic_grouped_accessor_op_v2"),
OP_PAIR(
"fb::sigrid_transforms_torch_bind",
"static_runtime::fused_sigrid_transforms_torch_bind"),
OP_PAIR(
"fb::variadic_sigrid_transforms_torch_bind",
"static_runtime::fused_variadic_sigrid_transforms_torch_bind"),
OP_PAIR(
"fb::gather_ranges_to_dense",
"static_runtime::fused_gather_ranges_to_dense"),
OP_PAIR(
"fb::gather_ranges_to_dense_v2",
"static_runtime::fused_gather_ranges_to_dense_v2"),
OP_PAIR(
"fb::split_and_squeeze",
"static_runtime::fused_split_and_squeeze_copy")};
// replacement contains (old_node, new_node, list_unpack_node)
std::vector<std::tuple<Node*, Node*, Node*>> replacement;
DepthFirstGraphNodeIterator graph_it(graph);
for (auto node = graph_it.next(); node != nullptr; node = graph_it.next()) {
auto unfused_to_fused_it = unfused_to_fused.find(node->kind());
if (unfused_to_fused_it == unfused_to_fused.end()) {
continue;
}
const Value* value_out = node->outputs()[0];
if (value_out->uses().size() != 1) {
continue;
}
Node* list_unpack_node = value_out->uses()[0].user;
if (list_unpack_node->kind() != prim::ListUnpack) {
continue;
}
auto list_unpack_outputs = list_unpack_node->outputs();
if (list_unpack_outputs.empty()) {
continue;
}
if (shouldNotFuseListUnpackSpecialCase(node)) {
continue;
}
const auto& new_sym = unfused_to_fused_it->second;
auto* new_node = graph->create(new_sym, 0);
for (Value* in : node->inputs()) {
new_node->addInput(in);
}
for (Value* out : list_unpack_outputs) {
Value* new_out = new_node->addOutput();
new_out->copyMetadata(out);
out->replaceAllUsesWith(new_out);
}
replacement.emplace_back(node, new_node, list_unpack_node);
}
for (const auto& nodes : replacement) {
auto* old_node = std::get<0>(nodes);
auto* new_node = std::get<1>(nodes);
auto* list_unpack_node = std::get<2>(nodes);
new_node->insertAfter(old_node);
list_unpack_node->destroy();
old_node->destroy();
}
} // namespace jit
void RemoveImmutableInputDictLookups(
std::shared_ptr<torch::jit::Graph>& graph) {
auto nodes = graph->nodes();
AliasDb db(graph);
// Gather all dict -> getitems where dict is immutable and getitems use
// constant keys.
std::unordered_map<Value*, std::vector<Node*>> dict_to_getitems;
std::unordered_set<Node*> keys;
for (Node* node : nodes) {
// Find aten::__getitem__(%dict, %constant_key).
if (node->kind() != aten::__getitem__) {
continue;
}
Node* getitem_node = node;
Value* dict = getitem_node->input(0);
if (db.hasWriters(dict)) {
// Mutable dict. Skip this optimization.
continue;
}
if (dict->type()->kind() != TypeKind::DictType ||
dict->node() != graph->param_node()) {
continue;
}
DCHECK(getitem_node->inputs().size() == 2);
Node* key = getitem_node->input(1)->node();
if (key->kind() != prim::Constant) {
continue;
}
keys.insert(key);
auto iter = dict_to_getitems.find(dict);
if (iter == dict_to_getitems.end()) {
dict_to_getitems.emplace(dict, std::vector<Node*>{getitem_node});
continue;
}
iter->second.push_back(getitem_node);
}
if (keys.size() == 0) {
return;
}
// Move all keys to the beginning of the graph and insert new dict_unpack
// nodes after that.
auto* marker = graph->create(prim::Constant);
graph->prependNode(marker);
graph->setInsertPoint(marker);
for (Node* key : keys) {
DCHECK(key->inputs().size() == 0);
key->moveBefore(marker);