-
Notifications
You must be signed in to change notification settings - Fork 76.3k
Expand file tree
/
Copy pathremapper.cc
More file actions
5406 lines (4739 loc) · 208 KB
/
Copy pathremapper.cc
File metadata and controls
5406 lines (4739 loc) · 208 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 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/optimizers/remapper.h"
#include <algorithm>
#include <cstdlib>
#include <map>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/graph_view.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/optimizers/constant_folding.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/grappler/utils/graph_view.h"
#include "tensorflow/core/grappler/utils/pattern_utils.h"
#include "tensorflow/core/grappler/utils/symbolic_shapes.h"
#include "tensorflow/core/grappler/utils/topological_sort.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
#include "tensorflow/core/util/env_var.h"
#include "tensorflow/core/util/use_cudnn.h"
#include "tsl/platform/errors.h"
#ifdef INTEL_MKL
#include "tensorflow/core/util/mkl_heuristics.h"
#endif // INTEL_MKL
#include "tensorflow/core/util/util.h"
#if GOOGLE_CUDA
#include "third_party/gpus/cudnn/cudnn.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
namespace grappler {
// Supported patterns:
//
// Conv2D + ... -> _FusedConv2D
// (1) Conv2D + BiasAdd + <Activation>
// (2) Conv2D + FusedBatchNorm + <Activation>
// (3) Conv2D + Squeeze + BiasAdd
//
// MatMul + ... -> _FusedMatMul:
// (1) MatMul + BiasAdd + <Activation>
//
// DepthwiseConv2dNative + ... -> _FusedDepthwiseConv2dNative:
// (1) DepthwiseConv2dNative + BiasAdd + <Activation>
//
// FusedBatchNorm[$is_training] + ... -> _FusedBatchNormEx[$is_training]
// (1) FusedBatchNorm + <Activation>
// (2) FusedBatchNorm + SideInput + <Activation>
//
// Sigmoid + Mul -> _MklSwish // This fusion only works on Intel CPU.
//
//
// In all cases, the supported activation functions are Relu, Relu6, and Elu.
//
// Both Conv2D and MatMul implemented as Tensor contraction (on CPU), so all the
// patterns are "ContractionWith...".
//
// _FusedConv2D/_FusedConv3D + <Activation> -> _FusedConv2D/_FusedConv3D
// Supported Activations: LeakyRelu, Mish
namespace {
constexpr char kFusedConv2D[] = "_FusedConv2D";
constexpr char kFusedConv3D[] = "_FusedConv3D";
constexpr char kFusedMatMul[] = "_FusedMatMul";
constexpr char kFusedDepthwiseConv2dNative[] = "_FusedDepthwiseConv2dNative";
constexpr char kFusedBatchNormEx[] = "_FusedBatchNormEx";
constexpr char kFusedBatchNormGradEx[] = "_FusedBatchNormGradEx";
constexpr char kTensorToHashBucket[] = "_TensorToHashBucketFast";
constexpr char kLeakyRelu[] = "LeakyRelu";
constexpr char kMklFusedMish[] = "_MklFusedMish";
constexpr char kRelu[] = "Relu";
constexpr char kRelu6[] = "Relu6";
constexpr char kElu[] = "Elu";
constexpr char kDataFormat[] = "data_format";
constexpr char kIsTraining[] = "is_training";
constexpr char kWidth[] = "width";
constexpr char kFill[] = "fill";
constexpr int kMissingIndex = -1;
struct RemapperContext {
explicit RemapperContext(GrapplerItem* item, absl::Status* status,
RewriterConfig::CpuLayout cpu_layout_conversion,
bool xla_auto_clustering_on,
bool xla_cpu_jit_disable_fusion)
: nodes_to_preserve(item->NodesToPreserve()),
graph_view(&item->graph, status),
graph_properties(*item),
inferred_graph_properties(false),
cpu_layout_conversion(cpu_layout_conversion),
xla_auto_clustering_on(xla_auto_clustering_on),
xla_cpu_jit_disable_fusion(xla_cpu_jit_disable_fusion) {}
std::unordered_set<std::string> nodes_to_preserve;
utils::MutableGraphView graph_view;
GraphProperties graph_properties;
bool inferred_graph_properties;
RewriterConfig::CpuLayout cpu_layout_conversion;
bool xla_auto_clustering_on;
bool xla_cpu_jit_disable_fusion;
};
// FusedBatchNorm that can be replaced with a cheaper set of primitives.
struct FusedBatchNorm {
FusedBatchNorm() = default;
explicit FusedBatchNorm(int fused_batch_norm)
: fused_batch_norm(fused_batch_norm) {}
int fused_batch_norm = kMissingIndex;
};
// FusedBatchNorm[$is_training] with fused side input and/or activation.
struct FusedBatchNormEx {
FusedBatchNormEx() = default;
int fused_batch_norm = kMissingIndex;
int side_input = kMissingIndex;
int activation = kMissingIndex;
// Add node that will be invalidated by fusing side input and fused batch norm
int invalidated = kMissingIndex;
};
// FusedBatchNormGrad with fused side output and/or activation.
struct FusedBatchNormGradEx {
int fused_batch_norm_grad = kMissingIndex;
int activation_grad = kMissingIndex;
int side_input_grad = kMissingIndex;
// Add node of the forward pass to access its "offset" input.
int fwd_fused_batch_norm = kMissingIndex;
};
// TensorToHashBucket that can be replaced with AsString + StringToHashBucket.
// We also include the fanin node of AsString ("pre_as_string") to determine the
// device.
struct TensorToHashBucket {
TensorToHashBucket() = default;
explicit TensorToHashBucket(int op1, int op2, int op3)
: pre_as_string(op1), as_string(op2), string_to_hash_bucket(op3) {}
int pre_as_string = kMissingIndex;
int as_string = kMissingIndex;
int string_to_hash_bucket = kMissingIndex;
};
// Pad followed by Conv3D/FusedConv3D
struct PadWithConv3D {
PadWithConv3D() = default;
PadWithConv3D(int contraction_idx, int pad_idx, int padding_const_idx)
: contraction_idx(contraction_idx),
pad_idx(pad_idx),
padding_const_idx(padding_const_idx) {}
int contraction_idx = kMissingIndex;
int pad_idx = kMissingIndex;
int padding_const_idx = kMissingIndex;
};
// Contraction node followed by a BiasAdd.
struct ContractionWithBiasAdd {
ContractionWithBiasAdd() = default;
ContractionWithBiasAdd(int contraction, int bias_add, int bias_port)
: contraction(contraction), bias_add(bias_add), bias_port(bias_port) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int bias_port = 1;
};
// Contraction node followed by Activation
struct ContractionWithActivation {
ContractionWithActivation() = default;
ContractionWithActivation(int contraction, int activation)
: contraction(contraction), activation(activation) {}
int contraction = kMissingIndex;
int activation = kMissingIndex;
};
// Contraction node followed by a BiasAdd and Activation.
struct ContractionWithBiasAddAndActivation {
ContractionWithBiasAddAndActivation() = default;
ContractionWithBiasAddAndActivation(int contraction, int bias_add,
int activation, int bias_port)
: contraction(contraction),
bias_add(bias_add),
activation(activation),
bias_port(bias_port) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int activation = kMissingIndex;
int bias_port = 1;
};
// Contraction node followed by a Squeeze and BiasAdd.
struct ContractionWithSqueezeAndBiasAdd {
ContractionWithSqueezeAndBiasAdd() = default;
ContractionWithSqueezeAndBiasAdd(int contraction, int squeeze, int bias_add)
: contraction(contraction), squeeze(squeeze), bias_add(bias_add) {}
int contraction = kMissingIndex;
int squeeze = kMissingIndex;
int bias_add = kMissingIndex;
};
// Contraction node followed by a FusedBatchNorm.
struct ContractionWithBatchNorm {
ContractionWithBatchNorm() = default;
ContractionWithBatchNorm(int contraction, int fused_batch_norm,
float epsilon = 0.0)
: contraction(contraction),
fused_batch_norm(fused_batch_norm),
epsilon(epsilon) {}
int contraction = kMissingIndex;
int fused_batch_norm = kMissingIndex;
float epsilon = 0.0;
};
// Contraction node followed by a FusedBatchNorm and Activation.
struct ContractionWithBatchNormAndActivation {
ContractionWithBatchNormAndActivation() = default;
ContractionWithBatchNormAndActivation(int contraction, int fused_batch_norm,
int activation, float epsilon = 0.0)
: contraction(contraction),
fused_batch_norm(fused_batch_norm),
activation(activation),
epsilon(epsilon) {}
int contraction = kMissingIndex;
int fused_batch_norm = kMissingIndex;
int activation = kMissingIndex;
float epsilon = 0.0;
};
// Contraction node followed by a BiasAdd and Add.
struct ContractionWithBiasAddAndAdd {
ContractionWithBiasAddAndAdd() = default;
ContractionWithBiasAddAndAdd(int contraction, int bias_add, int add,
int port_id, int bias_port)
: contraction(contraction),
bias_add(bias_add),
add(add),
port_id(port_id),
bias_port(bias_port) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int add = kMissingIndex;
int port_id = 0;
int bias_port = 1;
};
// Contraction node followed by a BiasAdd, Add and Relu.
// Plus Tanh and Sigmoid for MatMul in MKL
struct ContractionWithBiasAndAddActivation {
ContractionWithBiasAndAddActivation() = default;
ContractionWithBiasAndAddActivation(int contraction, int bias_add, int add,
int port_id, int activation,
int bias_port)
: contraction(contraction),
bias_add(bias_add),
add(add),
port_id(port_id),
activation(activation),
bias_port(bias_port) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int add = kMissingIndex;
int port_id = 0;
int activation = kMissingIndex;
int bias_port = 1;
};
bool IsInPreserveSet(const RemapperContext& ctx, const NodeDef* node) {
return ctx.nodes_to_preserve.count(node->name()) > 0;
}
bool HaveSameDataType(const NodeDef* lhs, const NodeDef* rhs,
const std::string& type_attr = "T") {
DataType lhs_attr = GetDataTypeFromAttr(*lhs, type_attr);
DataType rhs_attr = GetDataTypeFromAttr(*rhs, type_attr);
return lhs_attr != DT_INVALID && rhs_attr != DT_INVALID &&
lhs_attr == rhs_attr;
}
bool HasDataType(const NodeDef* node, const DataType& expected,
const std::string& type_attr = "T") {
DataType dtype = GetDataTypeFromAttr(*node, type_attr);
return dtype == expected;
}
bool IsCpuCompatibleDataType(const NodeDef* contraction,
const std::string& type_attr = "T") {
DataType dtype = GetDataTypeFromAttr(*contraction, type_attr);
// Stock TF without oneDNN build will always be `false`.
bool is_one_dnn_enabled = IsMKLEnabled();
if (is_one_dnn_enabled) {
// Currently, oneDNN based fused-kernel does not support transpose_a on
// MatMul. Since bfloat16 precision fused-kernel is only enabled through
// oneDNN, the fusion is disabled here. Float32 and float16 precisions,
// however, will use the Eigen library based kernel in case of transpose_a
// since the mkl_layout_pass will not rewrite for transpose_a. So for
// float32 and float16 precisions, the fusion is enabled for transpose_a.
bool is_supported_matmul = false;
if (IsMatMul(*contraction)) {
is_supported_matmul = (dtype == DT_BFLOAT16)
? contraction->attr().contains("transpose_a") &&
!contraction->attr().at("transpose_a").b()
: true;
}
return ((IsConv2D(*contraction) || IsDepthwiseConv2dNative(*contraction) ||
IsConv3D(*contraction) || IsAnyBatchMatMul(*contraction) ||
is_supported_matmul) &&
IsDataTypeSupportedByOneDNNOnThisCPU(dtype));
}
if (IsConv2D(*contraction)) {
return dtype == DT_FLOAT || dtype == DT_DOUBLE;
} else if (IsMatMul(*contraction)) {
return dtype == DT_FLOAT;
} else {
return false;
}
}
bool IsGpuCompatibleDataType(const NodeDef* contraction,
const std::string& type_attr = "T") {
DataType dtype = GetDataTypeFromAttr(*contraction, type_attr);
if (IsConv2D(*contraction) || IsMatMul(*contraction)) {
return dtype == DT_FLOAT || dtype == DT_HALF;
} else {
return false;
}
}
bool IsCpuCompatibleDataFormat(const RemapperContext& ctx,
const NodeDef* conv_node) {
const std::string& data_format = conv_node->attr().at(kDataFormat).s();
if (IsConv2D(*conv_node)) {
return data_format == "NHWC" || (IsMKLEnabled() && data_format == "NCHW") ||
(ctx.cpu_layout_conversion == RewriterConfig::NHWC_TO_NCHW &&
data_format == "NCHW");
} else if (IsConv3D(*conv_node)) {
return data_format == "NDHWC" || (IsMKLEnabled() && data_format == "NCDHW");
} else {
return false;
}
}
bool BlasLtMatmulEnabled() {
static bool is_enabled = [] {
bool is_enabled = false;
TF_CHECK_OK(tensorflow::ReadBoolFromEnvVar(
"TF_USE_CUBLASLT", /*default_val=*/false, &is_enabled));
return is_enabled;
}();
return is_enabled;
}
bool IsGpuCompatibleDataFormat(const RemapperContext& ctx,
const NodeDef* conv2d) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
const std::string& data_format = conv2d->attr().at(kDataFormat).s();
return data_format == "NHWC" || data_format == "NCHW";
}
bool IsCpuCompatibleConv2D(const RemapperContext& ctx, const NodeDef* conv2d) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
return NodeIsOnCpu(conv2d) && IsCpuCompatibleDataType(conv2d) &&
IsCpuCompatibleDataFormat(ctx, conv2d);
}
bool IsCpuCompatibleConv3D(const RemapperContext& ctx, const NodeDef* conv3d) {
DCHECK(IsConv3D(*conv3d)) << "Expected Conv3D op";
return NodeIsOnCpu(conv3d) && IsCpuCompatibleDataType(conv3d) &&
IsCpuCompatibleDataFormat(ctx, conv3d);
}
bool IsGpuCompatibleConv2D(const RemapperContext& ctx, const NodeDef* conv2d,
const NodeDef* activation) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
if (IsRelu(*activation)) {
return NodeIsOnGpu(conv2d) && IsGpuCompatibleDataType(conv2d) &&
IsGpuCompatibleDataFormat(ctx, conv2d);
} else if (IsRelu6(*activation) || IsElu(*activation) ||
IsLeakyRelu(*activation)) {
DataType dtype = GetDataTypeFromAttr(*conv2d, "T");
const std::string& data_format = conv2d->attr().at(kDataFormat).s();
return NodeIsOnGpu(conv2d) && dtype == DT_HALF && data_format == "NHWC";
}
return false;
}
bool IsGpuCompatibleMatMul(const RemapperContext& ctx, const NodeDef* matmul,
const NodeDef* activation) {
DCHECK(IsMatMul(*matmul)) << "Expected MatMul op";
if (activation == nullptr || IsRelu(*activation)) {
return BlasLtMatmulEnabled() && NodeIsOnGpu(matmul) &&
IsGpuCompatibleDataType(matmul);
} else if (IsTanh(*activation) || IsSigmoid(*activation)) {
DataType dtype = GetDataTypeFromAttr(*matmul, "T");
return NodeIsOnGpu(matmul) && dtype == DT_HALF;
}
return false;
}
bool IsCpuCompatibleMatMul(const RemapperContext& ctx, const NodeDef* matmul) {
DCHECK(IsMatMul(*matmul)) << "Expected MatMul op";
return NodeIsOnCpu(matmul) && IsCpuCompatibleDataType(matmul);
}
bool IsCpuCompatibleDepthwiseConv2dNative(const NodeDef* dw_conv2d) {
DCHECK(IsDepthwiseConv2dNative(*dw_conv2d))
<< "Expected DepthwiseConv2dNative op";
return NodeIsOnCpu(dw_conv2d) && IsCpuCompatibleDataType(dw_conv2d);
}
// Checks if we can rewrite a pattern to the `_Fused{Conv2D,MatMul}` on CPU.
template <typename Pattern>
bool IsCpuCompatible(const RemapperContext& ctx, const Pattern& matched) {
// Disable fusions on CPU when XLA JIT compilation enabled.
if (ctx.xla_cpu_jit_disable_fusion) return false;
const NodeDef& node = ctx.graph_view.graph()->node(matched.contraction);
if (IsConv2D(node)) {
return IsCpuCompatibleConv2D(ctx, &node);
} else if (IsDepthwiseConv2dNative(node)) {
return (IsMKLEnabled() && IsCpuCompatibleDepthwiseConv2dNative(&node));
} else if (IsMatMul(node)) {
return IsCpuCompatibleMatMul(ctx, &node);
} else if (IsConv3D(node)) {
return (IsMKLEnabled() && IsCpuCompatibleConv3D(ctx, &node));
} else {
return false;
}
}
bool RuntimeFusionEnabled(const Cluster* cluster) {
static bool is_enabled = [&] {
#if CUDNN_VERSION >= 8400
// Cudnn runtime fusion feature is recommended for Ampere GPUs or later.
// For pre-Ampere GPUs, the overhead of runtime compilation would be very
// large and there are more limitations of supported cases.
if (!cluster) return false;
auto devices = cluster->GetDevices();
int num_gpus = 0;
int num_ampere = 0;
for (const auto& d : devices) {
if (d.second.type() == "GPU") {
num_gpus++;
auto cc_it = d.second.environment().find("architecture");
if (cc_it != d.second.environment().end()) {
double compute_capability = 0.0;
if (absl::SimpleAtod(cc_it->second, &compute_capability) &&
compute_capability >= 8.0) {
num_ampere++;
}
}
}
}
bool runtime_fusion_enabled =
CudnnUseRuntimeFusion() && num_gpus > 0 && num_gpus == num_ampere;
if (CudnnUseRuntimeFusion() && !runtime_fusion_enabled) {
VLOG(1) << "Enabling Cudnn with runtime compilation requires "
<< "Ampere (sm_80) GPUs or later, but we got " << num_ampere
<< " sm_80+ GPU(s) out of total " << num_gpus << " GPU(s)";
}
return runtime_fusion_enabled;
#else
return false;
#endif
}();
return is_enabled;
}
bool IsSupportedActivation(const NodeDef& node, const Cluster* cluster) {
bool is_default_supported =
IsRelu(node) || IsRelu6(node) || IsElu(node) || IsLeakyRelu(node);
bool is_device_specific = (IsMKLEnabled() || RuntimeFusionEnabled(cluster)) &&
(IsTanh(node) || IsSigmoid(node));
return (is_default_supported || is_device_specific);
}
// Checks if we can rewrite a pattern to the `_FusedConv2D` on GPU device.
bool IsGpuCompatible(const RemapperContext& ctx,
const ContractionWithBiasAddAndActivation& matched,
const Cluster* cluster) {
#if TENSORFLOW_USE_ROCM
// TODO: add a hipblaslt pathway
return false;
#endif
// The TF->XLA bridge does not support `_Fused[Conv2D|MatMul]` so we avoid
// creating this op. Furthermore, XLA already does this fusion internally so
// there is no true benefit from doing this optimization if XLA is going to
// compile the unfused operations anyway.
if (ctx.xla_auto_clustering_on) return false;
const GraphDef* graph = ctx.graph_view.graph();
// We rely on cuDNN for fused convolution and cublasLt for fused matmul.
const NodeDef& activation_node = graph->node(matched.activation);
if (!IsSupportedActivation(activation_node, cluster)) return false;
const NodeDef& contraction_node = graph->node(matched.contraction);
if (IsConv2D(contraction_node)) {
const std::vector<OpInfo::TensorProperties>& input_props =
ctx.graph_properties.GetInputProperties(contraction_node.name());
const TensorShapeProto& filter_shape =
input_props.size() >= 2 ? input_props[1].shape() : TensorShapeProto();
// FusedConv2D on GPU with 1x1 convolution is marginally faster than
// in-graph computation in micro benchmarks (see kernels/conv_ops_test.cc),
// and significantly slower in large scale benchmarks.
bool is_spatial_conv = Rank(filter_shape) == 4 && //
IsKnown(filter_shape.dim(0)) && //
IsKnown(filter_shape.dim(1)) && //
filter_shape.dim(0).size() != 1 && //
filter_shape.dim(1).size() != 1;
// FusedConv2D on GPU will use cuDNN static kernels when the activation is
// Relu. For other activations, it will rely on cuDNN runtime funsion
// kernels which require 32-bit aligned data access. Here, we check if the
// in and out channels of filter are even numbers.
bool valid_channels = Rank(filter_shape) == 4 && //
IsKnown(filter_shape.dim(2)) && //
IsKnown(filter_shape.dim(3)) && //
filter_shape.dim(2).size() % 2 == 0 && //
filter_shape.dim(3).size() % 2 == 0;
return is_spatial_conv &&
(IsRelu(activation_node) ||
(RuntimeFusionEnabled(cluster) && valid_channels)) &&
IsGpuCompatibleConv2D(ctx, &contraction_node, &activation_node);
} else if (IsMatMul(contraction_node)) {
const std::vector<OpInfo::TensorProperties>& input_props =
ctx.graph_properties.GetInputProperties(contraction_node.name());
const TensorShapeProto& a_shape =
!input_props.empty() ? input_props[0].shape() : TensorShapeProto();
const TensorShapeProto& b_shape =
!input_props.empty() ? input_props[1].shape() : TensorShapeProto();
// FusedMatMul on GPU will use cublasLt when the activation is Relu. For
// other activations, it will rely on cuDNN runtime funsion kernels which
// require 32-bit aligned data access. Here, we check if the leading dims of
// input matrices are even numbers.
bool valid_dims = Rank(a_shape) == 2 && Rank(b_shape) == 2 &&
IsKnown(a_shape.dim(1)) && //
IsKnown(b_shape.dim(1)) && //
a_shape.dim(1).size() % 2 == 0 && //
b_shape.dim(1).size() % 2 == 0;
return (IsRelu(activation_node) ||
(RuntimeFusionEnabled(cluster) && valid_dims)) &&
IsGpuCompatibleMatMul(ctx, &contraction_node, &activation_node);
}
return false;
}
// Checks if we can rewrite a pattern to the `_FusedMatMul` on GPU device.
bool IsGpuCompatible(const RemapperContext& ctx,
const ContractionWithBiasAdd& matched,
const Cluster* cluster) {
// The TF->XLA bridge does not support `_FusedMatMul` so we avoid creating
// this op. Furthermore, XLA already does this fusion internally so there
// is no true benefit from doing this optimization if XLA is going to compile
// the unfused operations anyway.
if (ctx.xla_auto_clustering_on) return false;
const GraphDef* graph = ctx.graph_view.graph();
const NodeDef& contraction_node = graph->node(matched.contraction);
if (!IsMatMul(contraction_node)) return false;
return IsGpuCompatibleMatMul(ctx, &contraction_node, nullptr);
}
bool IsGpuCompatible(const RemapperContext& ctx,
const ContractionWithSqueezeAndBiasAdd& matched,
const Cluster* cluster) {
return false;
}
// Returns true if the given pattern is supported on the assigned device.
template <typename Pattern>
bool IsDeviceCompatible(const RemapperContext& ctx, Pattern& matched,
Cluster* cluster = nullptr) {
return IsCpuCompatible(ctx, matched) ||
IsGpuCompatible(ctx, matched, cluster);
}
// Returns the generic op name for an _Mkl activation op
std::string GetActivationName(const std::string& s) {
if (s == kMklFusedMish) {
return "Mish";
} else {
return s;
}
}
inline bool HasControlFaninOrFanout(const utils::MutableNodeView& node_view) {
return node_view.NumControllingFanins() > 0 ||
node_view.NumControlledFanouts() > 0;
}
// Returns true if at most one fanout reads output at port 0 (output used once).
inline bool HasAtMostOneFanoutAtPort0(const utils::MutableNodeView& node_view) {
return node_view.GetRegularFanout(0).size() <= 1;
}
// Returns true if at most one fanout reads actual tensor data at output port 0
// (output used once for any data computation).
inline bool HasAtMostOneDataFanoutAtPort0(
const utils::MutableNodeView& node_view) {
const auto predicate = [](const auto& fanout) -> bool {
const NodeDef* node = fanout.node_view()->node();
return !IsShape(*node) && !IsRank(*node);
};
return absl::c_count_if(node_view.GetRegularFanout(0), predicate) <= 1;
}
bool IsConvOrMatMul(const NodeDef& node) {
return IsConv2D(node) || IsDepthwiseConv2dNative(node) || IsMatMul(node) ||
IsConv3D(node);
}
// Returns true if one input to Add is Conv2D/3D or DepthwiseConv2dNative or
// MatMul, and the other input is semantically equivalent to BiasAdd.
bool IsBiasSemanticAdd(const RemapperContext& ctx,
const utils::MutableNodeView& node_view,
int& bias_port) {
if (!IsMKLEnabled()) return false;
const auto* node_def = node_view.node();
if (!NodeIsOnCpu(node_def)) return false;
if (!IsAdd(*node_def) || node_view.NumRegularFanins() != 2) return false;
const auto& props = ctx.graph_properties.GetInputProperties(node_def->name());
if (props.size() < 2) return false;
const auto& regular_fanin_0 = node_view.GetRegularFanin(0);
const auto* node_view_0 = regular_fanin_0.node_view();
const auto* node_def_0 = node_view_0->node();
const auto& regular_fanin_1 = node_view.GetRegularFanin(1);
const auto* node_view_1 = regular_fanin_1.node_view();
const auto* node_def_1 = node_view_1->node();
if (!IsConvOrMatMul(*node_def_0) && !IsConvOrMatMul(*node_def_1))
return false;
auto is_channel_last_format = [](const NodeDef& node) -> bool {
if (node.attr().contains("data_format")) {
const std::string data_format = node.attr().at("data_format").s();
return (data_format == "NHWC" || data_format == "NDHWC");
}
return true;
};
// Currently supported data formats are NHWC and NDHWC.
if (!is_channel_last_format(*node_def_0) ||
!is_channel_last_format(*node_def_1))
return false;
const TensorShapeProto& prot0_shape = props[0].shape();
const TensorShapeProto& prot1_shape = props[1].shape();
if (prot0_shape.unknown_rank() || prot1_shape.unknown_rank() ||
prot0_shape.dim_size() < 1 || prot1_shape.dim_size() < 1 ||
!IsKnown(prot0_shape.dim(prot0_shape.dim_size() - 1)) ||
!IsKnown(prot1_shape.dim(prot1_shape.dim_size() - 1)))
return false;
// Helper function to check Add/AddV2 could be replaced with BiasAdd.
const auto is_supported_shape =
[&](const TensorShapeProto& shape,
const TensorShapeProto& bcast_shape) -> bool {
int conv_channel_dim;
conv_channel_dim = shape.dim(shape.dim_size() - 1).size();
if (shape.dim_size() == 4 && bcast_shape.dim_size() > 4) return false;
if (shape.dim_size() == 5 && bcast_shape.dim_size() > 5) return false;
if (shape.dim_size() < 2) return false;
// Check that the conv node's channel dim is equal to the 1-dim add node's
// dim
if (conv_channel_dim != bcast_shape.dim(bcast_shape.dim_size() - 1).size())
return false;
// Check that add nodes dims are all 1's except the channel dim
for (int i = 0; i < bcast_shape.dim_size() - 1; i++) {
if (1 != bcast_shape.dim(i).size()) return false;
}
return true;
};
if (ShapesSymbolicallyEqual(prot0_shape, prot1_shape) ||
!ShapesBroadcastable(prot0_shape, prot1_shape))
return false;
if (IsConvOrMatMul(*node_def_0)) {
bias_port = 1;
return (is_supported_shape(prot0_shape, prot1_shape));
} else if (IsConvOrMatMul(*node_def_1)) {
bias_port = 0;
return (is_supported_shape(prot1_shape, prot0_shape));
}
return false;
}
void AddInputShapesAttr(const RemapperContext& ctx, int node_index) {
auto mutable_node = ctx.graph_view.graph()->mutable_node(node_index);
AttrValue attr_input_shape;
auto tensor_properties =
ctx.graph_properties.GetInputProperties(mutable_node->name());
for (const auto& tensor_property : tensor_properties) {
TensorShapeProto* proto = attr_input_shape.mutable_list()->add_shape();
*proto = tensor_property.shape();
}
if (IsMKLEnabled() && !tensor_properties.empty()) {
(*mutable_node->mutable_attr())["_input_shapes"] =
std::move(attr_input_shape);
}
}
bool FindContractionWithBias(const RemapperContext& ctx, int node_index,
ContractionWithBiasAdd* matched,
bool check_device_compatible = true) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
// Root of the pattern must be a BiasAdd.
// TODO(lyandy): Forward controls for patterns with control dependencies.
if (HasControlFaninOrFanout(*node_view)) return false;
const auto* node_def = node_view->node();
int bias_port = 1;
if (!IsBiasAdd(*node_def) && !IsBiasSemanticAdd(ctx, *node_view, bias_port))
return false;
// Input to the BiasAdd must be a Conv2D/3D or a MatMul.
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(1 - bias_port);
const auto* contraction_node_view = regular_fanin_0.node_view();
const auto* contraction_node_def = contraction_node_view->node();
// Conv2D/3D, MatMul or DepthwiseConv2D
bool is_contraction = IsConv2D(*contraction_node_def) ||
(IsConv3D(*contraction_node_def) && IsMKLEnabled()) ||
IsMatMul(*contraction_node_def) ||
IsDepthwiseConv2dNative(*contraction_node_def);
#ifdef DNNL_AARCH64_USE_ACL
if (IsDepthwiseConv2dNative(*contraction_node_def)) is_contraction = false;
#endif
if (!is_contraction || !HaveSameDataType(node_def, contraction_node_def) ||
HasControlFaninOrFanout(*contraction_node_view) ||
!HasAtMostOneFanoutAtPort0(*contraction_node_view) ||
IsInPreserveSet(ctx, contraction_node_def))
return false;
// Check that data type and data format are supported on assigned device.
const ContractionWithBiasAdd pattern{contraction_node_view->node_index(),
node_index, bias_port};
if (check_device_compatible && !IsDeviceCompatible(ctx, pattern))
return false;
// We successfully found a {Conv2D, MatMul}+BiasAdd pattern.
*matched = pattern;
return true;
}
// Fuse _FusedConv{2,3}D with elementwise ops that
// gets fused in the first iteration of remapper
// Currently supports: LeakyRelu, _MklFusedMish
bool FindFusedConvWithFusedActivation(const RemapperContext& ctx,
int node_index,
ContractionWithActivation* matched) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
if (HasControlFaninOrFanout(*node_view)) return false;
const auto* node_def = node_view->node();
// Root of the pattern must be on CPU with MKL enabled
if (!NodeIsOnCpu(node_def) && !IsMKLEnabled()) return false;
// Root of the pattern must be a LeakyRelu or _MklFusedMish
if (!IsLeakyRelu(*node_def) && !IsMklFusedMish(*node_def)) return false;
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* contraction_node_view = regular_fanin_0.node_view();
const auto* contraction_node_def = contraction_node_view->node();
// Input to the activation must be a _FusedConv2D or _FusedConv3D
if (!(contraction_node_def->op() == kFusedConv2D ||
contraction_node_def->op() == kFusedConv3D))
return false;
// Check if any activation is already fused into _FusedConv2D or _FusedConv3D
auto contraction_fused_ops_list =
contraction_node_def->attr().at("fused_ops").list().s();
for (auto it = contraction_fused_ops_list.begin();
it != contraction_fused_ops_list.end(); it++) {
if (*it == kLeakyRelu || *it == kMklFusedMish || *it == kRelu ||
*it == kRelu6 || *it == kElu) {
return false;
}
}
// We found the pattern
const ContractionWithActivation pattern{contraction_node_view->node_index(),
node_view->node_index()};
*matched = pattern;
return true;
}
bool FindContractionWithBiasAndActivation(
const RemapperContext& ctx, Cluster* cluster, int node_index,
ContractionWithBiasAddAndActivation* matched) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
// Root of the pattern must be an activation node.
// TODO(lyandy): Forward controls for patterns with control dependencies.
if (HasControlFaninOrFanout(*node_view)) return false;
const auto* node_def = node_view->node();
if (!IsSupportedActivation(*node_def, cluster)) return false;
// And input to the activation node must match ContractionWithBiasAdd pattern.
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* bias_add_node_view = regular_fanin_0.node_view();
const auto* bias_add_node_def = bias_add_node_view->node();
ContractionWithBiasAdd base;
if (!FindContractionWithBias(ctx, bias_add_node_view->node_index(), &base,
/*check_device_compatible=*/false) ||
!HasAtMostOneFanoutAtPort0(*bias_add_node_view) ||
!HaveSameDataType(node_def, bias_add_node_def) ||
IsInPreserveSet(ctx, bias_add_node_def))
return false;
// Get the contraction node
const auto* contraction_node_view =
bias_add_node_view->GetRegularFanin(1 - base.bias_port).node_view();
const auto* contraction_node_def = contraction_node_view->node();
// Currently, only matmul + bias + (tanh or Sigmoid) is enabled
if (!IsMatMul(*contraction_node_def) &&
(IsTanh(*node_def) || IsSigmoid(*node_def)))
return false;
// Currently, only (conv | matmul) + bias + leakyrelu is enabled
if (!(IsConv2D(*contraction_node_def) || IsMatMul(*contraction_node_def) ||
(IsConv3D(*contraction_node_def) && IsMKLEnabled())) &&
IsLeakyRelu(*node_def))
return false;
// Check that data type and data format are supported on assigned device.
const ContractionWithBiasAddAndActivation pattern{
base.contraction, base.bias_add, node_index, base.bias_port};
if (!IsDeviceCompatible(ctx, pattern, cluster)) return false;
// We successfully found a {Conv2D, MatMul}+BiasAdd+Activation pattern.
*matched = pattern;
return true;
}
bool FindConvWithSqueezeAndBias(const RemapperContext& ctx, int node_index,
ContractionWithSqueezeAndBiasAdd* matched) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
// TODO(lyandy): Forward controls for patterns with control dependencies.
if (HasControlFaninOrFanout(*node_view)) return false;
// Root of the pattern must be a BiasAdd.
const auto* node_def = node_view->node();
if (!IsBiasAdd(*node_def)) return false;
// Input to the BiasAdd must be a Squeeze.
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* squeeze_node_view = regular_fanin_0.node_view();
const auto* squeeze_node_def = squeeze_node_view->node();
if (!IsSqueeze(*squeeze_node_def) ||
!HaveSameDataType(node_def, squeeze_node_def, "T") ||
HasControlFaninOrFanout(*squeeze_node_view) ||
!HasAtMostOneFanoutAtPort0(*squeeze_node_view) ||
IsInPreserveSet(ctx, squeeze_node_def))
return false;
// Input to the Squeeze must be a Conv2D/3D.
if (squeeze_node_view->NumRegularFanins() < 1) return false;
const auto& squeeze_regular_fanin_0 = squeeze_node_view->GetRegularFanin(0);
const auto* conv_node_view = squeeze_regular_fanin_0.node_view();
const auto* conv_node_def = conv_node_view->node();
if (!(IsConv2D(*conv_node_def) ||
(IsConv3D(*conv_node_def) && IsMKLEnabled())) ||
!HaveSameDataType(node_def, conv_node_def, "T") ||
HasControlFaninOrFanout(*conv_node_view) ||
!HasAtMostOneFanoutAtPort0(*conv_node_view) ||
IsInPreserveSet(ctx, conv_node_def))
return false;
// Squeeze must not squeeze output channel dimension.
std::vector<int32_t> dims;
if (!TryGetNodeAttr(*squeeze_node_def, "squeeze_dims", &dims)) return false;
for (auto dim : dims) {
if ((dim == 3 && IsConv2D(*conv_node_def)) ||
(dim == 4 && IsConv3D(*conv_node_def)))
return false;
}
// Check that data type and data format are supported on assigned device.
const ContractionWithSqueezeAndBiasAdd pattern{
conv_node_view->node_index(), squeeze_node_view->node_index(),
node_index};
if (!IsDeviceCompatible(ctx, pattern)) return false;
// We successfully found a Conv2D+Squeeze+BiasAdd pattern.
*matched = pattern;
return true;
}
bool FindConv2DWithBatchNorm(const RemapperContext& ctx, int node_index,
ContractionWithBatchNorm* matched) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
const auto* node_def = node_view->node();
// Root of the pattern must be a FusedBatchNorm.
if (!IsFusedBatchNorm(*node_def)) return false;
// FusedBatchNormV2 and V3 have an extra type parameter.
// Conv2D + FusedBatchNormV2/V3 fusion is currently supported only for fp32.
// TODO(intel-tf): Enable the fusion for bf16 and fp16.
bool dtypeU_is_float = HasDataType(node_def, DT_FLOAT, "U");
bool dtypeT_is_bf16 = HasDataType(node_def, DT_BFLOAT16, "T");
bool dtypeT_is_mkl_fp16 =
IsMKLEnabled() && HasDataType(node_def, DT_HALF, "T");
if (node_view->GetOp() != "FusedBatchNorm" &&
(!dtypeU_is_float || dtypeT_is_bf16 || dtypeT_is_mkl_fp16)) {
return false;
}
// Check that batch normalization is in inference mode.
const auto* training_attr = node_view->GetAttr(kIsTraining);
if (training_attr != nullptr && training_attr->b()) return false;
// Check that only 0th output is consumed by other nodes.
// TODO(lyandy): Forward controls for patterns with control dependencies.
if (HasControlFaninOrFanout(*node_view) ||
!node_view->GetRegularFanout(1).empty() || // batch_mean
!node_view->GetRegularFanout(2).empty() || // batch_variance
!node_view->GetRegularFanout(3).empty() || // reserve_space_1
!node_view->GetRegularFanout(4).empty()) // reserve_space_2
return false;
// Input to the FusedBatchNorm must be a Conv2D.
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* conv2d_node_view = regular_fanin_0.node_view();
const auto* conv2d_node_def = conv2d_node_view->node();
// Disable fusions on CPU when XLA JIT compilation enabled.