-
Notifications
You must be signed in to change notification settings - Fork 76.3k
Expand file tree
/
Copy pathremapper.cc
More file actions
1854 lines (1568 loc) · 70.6 KB
/
Copy pathremapper.cc
File metadata and controls
1854 lines (1568 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 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 "absl/container/flat_hash_set.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/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/util/env_var.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>
//
// FusedBatchNorm[$is_training] + ... -> _FusedBatchNormEx[$is_training]
// (1) FusedBatchNorm + <Activation>
// (2) FusedBatchNorm + SideInput + <Activation>
//
// Both Conv2D and MatMul implemented as Tensor contraction (on CPU), so all the
// patterns are "ContractionWith...".
namespace {
constexpr char kFusedConv2D[] = "_FusedConv2D";
constexpr char kFusedMatMul[] = "_FusedMatMul";
constexpr char kFusedDepthwiseConv2dNative[] = "_FusedDepthwiseConv2dNative";
constexpr char kFusedBatchNormEx[] = "_FusedBatchNormEx";
constexpr char kDataFormat[] = "data_format";
constexpr char kIsTraining[] = "is_training";
constexpr int kMissingIndex = -1;
struct RemapperContext {
explicit RemapperContext(GrapplerItem* item, Status* status)
: nodes_to_preserve(item->NodesToPreserve()),
graph_view(&item->graph, status),
graph_properties(*item),
inferred_graph_properties(false) {}
std::unordered_set<string> nodes_to_preserve;
utils::MutableGraphView graph_view;
GraphProperties graph_properties;
bool inferred_graph_properties;
};
// 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;
};
// Contraction node followed by a BiasAdd.
struct ContractionWithBiasAdd {
ContractionWithBiasAdd() = default;
ContractionWithBiasAdd(int contraction, int bias_add)
: contraction(contraction), bias_add(bias_add) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
};
// Contraction node followed by a BiasAdd and Activation.
struct ContractionWithBiasAddAndActivation {
ContractionWithBiasAddAndActivation() = default;
ContractionWithBiasAddAndActivation(int contraction, int bias_add,
int activation)
: contraction(contraction), bias_add(bias_add), activation(activation) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int activation = kMissingIndex;
};
// 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;
};
#ifdef INTEL_MKL
// Contraction node followed by a BiasAdd and Add.
struct ContractionWithBiasAddAndAdd {
ContractionWithBiasAddAndAdd() = default;
ContractionWithBiasAddAndAdd(int contraction, int bias_add, int add,
int port_id)
: contraction(contraction),
bias_add(bias_add),
add(add),
port_id(port_id) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int add = kMissingIndex;
int port_id = 0;
};
// Contraction node followed by a BiasAdd, Add and Relu.
struct ContractionWithBiasAndAddActivation {
ContractionWithBiasAndAddActivation() = default;
ContractionWithBiasAndAddActivation(int contraction, int bias_add, int add,
int port_id, int activation)
: contraction(contraction),
bias_add(bias_add),
add(add),
port_id(port_id),
activation(activation) {}
int contraction = kMissingIndex;
int bias_add = kMissingIndex;
int add = kMissingIndex;
int port_id = 0;
int activation = kMissingIndex;
};
#endif // INTEL_MKL
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 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 string& type_attr = "T") {
DataType dtype = GetDataTypeFromAttr(*node, type_attr);
return dtype == expected;
}
bool IsCpuCompatibleDataType(const NodeDef* contraction,
const string& type_attr = "T") {
DataType dtype = GetDataTypeFromAttr(*contraction, type_attr);
#if defined(INTEL_MKL)
#if defined(ENABLE_INTEL_MKL_BFLOAT16)
if (IsConv2D(*contraction) || IsDepthwiseConv2dNative(*contraction) ||
IsMatMul(*contraction)) {
return dtype == DT_FLOAT || dtype == DT_BFLOAT16;
#else
if (IsConv2D(*contraction) || IsDepthwiseConv2dNative(*contraction) ||
IsMatMul(*contraction)) {
return dtype == DT_FLOAT;
#endif // ENABLE_INTEL_MKL_BFLOAT16
#else
if (IsConv2D(*contraction)) {
return dtype == DT_FLOAT || dtype == DT_DOUBLE;
} else if (IsMatMul(*contraction)) {
return dtype == DT_FLOAT;
#endif // INTEL_MKL
} else {
return false;
}
}
bool IsGpuCompatibleDataType(const NodeDef* contraction,
const string& type_attr = "T") {
DataType dtype = GetDataTypeFromAttr(*contraction, type_attr);
if (IsConv2D(*contraction)) {
return dtype == DT_FLOAT;
} else {
return false;
}
}
bool IsCpuCompatibleDataFormat(const NodeDef* conv2d) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
const string& data_format = conv2d->attr().at(kDataFormat).s();
#ifndef INTEL_MKL
return data_format == "NHWC";
#else
return data_format == "NHWC" || data_format == "NCHW";
#endif // !INTEL_MKL
}
bool IsGpuCompatibleDataFormat(const NodeDef* conv2d) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
const string& data_format = conv2d->attr().at(kDataFormat).s();
return data_format == "NHWC" || data_format == "NCHW";
}
bool IsCpuCompatibleConv2D(const NodeDef* conv2d) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
return NodeIsOnCpu(conv2d) && IsCpuCompatibleDataType(conv2d) &&
IsCpuCompatibleDataFormat(conv2d);
}
bool IsGpuCompatibleConv2D(const NodeDef* conv2d) {
DCHECK(IsConv2D(*conv2d)) << "Expected Conv2D op";
return NodeIsOnGpu(conv2d) && IsGpuCompatibleDataType(conv2d) &&
IsGpuCompatibleDataFormat(conv2d);
}
bool IsCpuCompatibleMatMul(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) {
const NodeDef& node = ctx.graph_view.graph()->node(matched.contraction);
if (IsConv2D(node)) {
return IsCpuCompatibleConv2D(&node);
} else if (IsDepthwiseConv2dNative(node)) {
#ifdef INTEL_MKL
return IsCpuCompatibleDepthwiseConv2dNative(&node);
#else
return false;
#endif // INTEL_MKL
} else if (IsMatMul(node)) {
return IsCpuCompatibleMatMul(&node);
} else {
return false;
}
}
// Checks if we can rewrite a pattern to the `_FusedConv2D` on GPU device.
bool IsGpuCompatible(const RemapperContext& ctx,
const ContractionWithBiasAddAndActivation& matched) {
#if TENSORFLOW_USE_ROCM
// ROCm does not support _FusedConv2D
return false;
#endif
const GraphDef* graph = ctx.graph_view.graph();
const NodeDef& contraction_node = graph->node(matched.contraction);
if (!IsConv2D(contraction_node)) return false;
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(1)) && //
IsKnown(filter_shape.dim(2)) && //
filter_shape.dim(1).size() != 1 && //
filter_shape.dim(2).size() != 1;
// We rely on cuDNN for fused convolution, and it currently supports only Relu
// activation.
const NodeDef& activation_node = graph->node(matched.activation);
bool is_relu = IsRelu(activation_node);
return is_relu && is_spatial_conv && IsGpuCompatibleConv2D(&contraction_node);
}
bool IsGpuCompatible(const RemapperContext& ctx,
const ContractionWithBiasAdd& matched) {
return false;
}
bool IsGpuCompatible(const RemapperContext& ctx,
const ContractionWithSqueezeAndBiasAdd& matched) {
return false;
}
// Returns true if the given pattern is supported on the assigned device.
template <typename Pattern>
bool IsDeviceCompatible(const RemapperContext& ctx, Pattern& matched) {
return IsCpuCompatible(ctx, matched) || IsGpuCompatible(ctx, matched);
}
bool IsSupportedActivation(const NodeDef& node) {
return IsRelu(node) || IsRelu6(node) || IsElu(node);
}
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 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();
if (!IsBiasAdd(*node_def)) return false;
// Input to the BiasAdd must be a Conv2D or a MatMul.
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();
// Conv2D, MatMul or DepthwiseConv2D
bool is_contraction = IsConv2D(*contraction_node_def) ||
IsMatMul(*contraction_node_def) ||
IsDepthwiseConv2dNative(*contraction_node_def);
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};
if (check_device_compatible && !IsDeviceCompatible(ctx, pattern))
return false;
// We successfully found a {Conv2D, MatMul}+BiasAdd pattern.
*matched = pattern;
return true;
}
bool FindContractionWithBiasAndActivation(
const RemapperContext& ctx, 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)) 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;
// Check that data type and data format are supported on assigned device.
const ContractionWithBiasAddAndActivation pattern{base.contraction,
base.bias_add, node_index};
if (!IsDeviceCompatible(ctx, pattern)) return false;
// We successfully found a {Conv2D, MatMul}+BiasAdd+Activation pattern.
*matched = pattern;
return true;
}
bool FindConv2DWithSqueezeAndBias(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;
// Squeeze must not squeeze output channel dimension.
std::vector<int32> dims;
if (!TryGetNodeAttr(*squeeze_node_def, "squeeze_dims", &dims)) return false;
for (auto dim : dims) {
if (dim == 3) return false;
}
// Input to the Squeeze must be a Conv2D.
if (squeeze_node_view->NumRegularFanins() < 1) return false;
const auto& squeeze_regular_fanin_0 = squeeze_node_view->GetRegularFanin(0);
const auto* conv2d_node_view = squeeze_regular_fanin_0.node_view();
const auto* conv2d_node_def = conv2d_node_view->node();
if (!IsConv2D(*conv2d_node_def) ||
!HaveSameDataType(node_def, conv2d_node_def, "T") ||
HasControlFaninOrFanout(*conv2d_node_view) ||
!HasAtMostOneFanoutAtPort0(*conv2d_node_view) ||
IsInPreserveSet(ctx, conv2d_node_def))
return false;
// Check that data type and data format are supported on assigned device.
const ContractionWithSqueezeAndBiasAdd pattern{
conv2d_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.
if (node_view->GetOp() != "FusedBatchNorm" &&
!HasDataType(node_def, DT_FLOAT, "U"))
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();
if (!IsConv2D(*conv2d_node_def) || !NodeIsOnCpu(conv2d_node_def) ||
!HaveSameDataType(node_def, conv2d_node_def) ||
!IsCpuCompatibleDataType(conv2d_node_def) ||
!IsCpuCompatibleDataFormat(conv2d_node_def) ||
HasControlFaninOrFanout(*conv2d_node_view) ||
!HasAtMostOneFanoutAtPort0(*conv2d_node_view) ||
IsInPreserveSet(ctx, conv2d_node_def))
return false;
// We successfully found a Conv2D+FusedBatchNorm pattern.
matched->contraction = conv2d_node_view->node_index();
matched->fused_batch_norm = node_index;
if (!TryGetNodeAttr(*node_def, "epsilon", &matched->epsilon)) return false;
return true;
}
bool FindConv2DWithBatchNormAndActivation(
const RemapperContext& ctx, int node_index,
ContractionWithBatchNormAndActivation* 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 an activation node.
const auto* node_def = node_view->node();
if (!IsSupportedActivation(*node_def)) return false;
// And input to the activation node must match Conv2DWithBatchNorm pattern.
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* batch_norm_node_view = regular_fanin_0.node_view();
ContractionWithBatchNorm base;
if (!FindConv2DWithBatchNorm(ctx, batch_norm_node_view->node_index(), &base))
return false;
const auto* fused_batch_norm_node_view =
ctx.graph_view.GetNode(base.fused_batch_norm);
const auto* fused_batch_norm_node_def = fused_batch_norm_node_view->node();
if (!HasAtMostOneFanoutAtPort0(*fused_batch_norm_node_view) ||
!HaveSameDataType(node_def, fused_batch_norm_node_def) ||
IsInPreserveSet(ctx, fused_batch_norm_node_def))
return false;
// We successfully found a Conv2D+FusedBatchNorm+Activation pattern.
matched->contraction = base.contraction;
matched->fused_batch_norm = base.fused_batch_norm;
matched->activation = node_index;
matched->epsilon = base.epsilon;
return true;
}
#ifdef INTEL_MKL
// As AddN has multiple inputs, this function tries to find Conv2D + Bias
// pattern in specific input port.
bool FindContractionWithBiasInPort(const RemapperContext& ctx,
const utils::MutableNodeView& add_node_view,
const NodeDef& add_node_def, int port_id,
ContractionWithBiasAdd* base) {
// Input to AddN must match ContractionWithBiasAdd pattern.
if (add_node_view.NumRegularFanins() < port_id + 1) return false;
const auto& bias_add_node_view =
add_node_view.GetRegularFanin(port_id).node_view();
if (bias_add_node_view == nullptr) return false;
const auto* bias_add_node_def = bias_add_node_view->node();
if (!FindContractionWithBias(ctx, bias_add_node_view->node_index(), base,
/*check_device_compatible=*/false))
return false;
if (!HasAtMostOneFanoutAtPort0(*bias_add_node_view) ||
!HaveSameDataType(&add_node_def, bias_add_node_def) ||
IsInPreserveSet(ctx, bias_add_node_def))
return false;
return true;
}
bool IsAddWithNoBroadcast(const RemapperContext& ctx, const NodeDef& node) {
if (!IsAdd(node)) return false;
// Check if this is case of broadcasting - Add node supports broadcasting.
const auto& props = ctx.graph_properties.GetInputProperties(node.name());
if (props.size() == 2 &&
ShapesSymbolicallyEqual(props[0].shape(), props[1].shape())) {
return true;
}
return false;
}
bool FindContractionWithBiasAddAndAdd(const RemapperContext& ctx,
const utils::MutableNodeView& node_view,
ContractionWithBiasAddAndAdd* matched) {
// Fusion with AddN is supported only when it has two inputs.
// TODO(lyandy): Forward controls for patterns with control dependencies.
if (HasControlFaninOrFanout(node_view) || node_view.NumRegularFanins() != 2)
return false;
// Root of the pattern must be a AddN or Add with same input shapes
// (no broadcasting).
const auto* node_def = node_view.node();
if (!IsAddN(*node_def) && !IsAddWithNoBroadcast(ctx, *node_def)) return false;
#ifdef ENABLE_INTEL_MKL_BFLOAT16
// MKL AddN ops only support float and bfloat16 data types.
if (!HasDataType(node_def, DT_FLOAT) && !HasDataType(node_def, DT_BFLOAT16))
return false;
#else
// MKL AddN ops only support float data type.
if (!HasDataType(node_def, DT_FLOAT)) return false;
#endif // ENABLE_INTEL_MKL_BFLOAT16
ContractionWithBiasAdd base;
matched->port_id = 0;
// Find the conv+bias pattern in specific port.
if (!FindContractionWithBiasInPort(ctx, node_view, *node_def,
matched->port_id, &base)) {
matched->port_id = 1;
if (!FindContractionWithBiasInPort(ctx, node_view, *node_def,
matched->port_id, &base)) {
return false;
}
}
// We successfully found a Conv2D+BiasAdd+{AddN,Add} pattern.
matched->contraction = base.contraction;
matched->bias_add = base.bias_add;
matched->add = node_view.node_index();
return true;
}
bool FindContractionWithBiasAddAndAdd(const RemapperContext& ctx,
int node_index,
ContractionWithBiasAddAndAdd* matched) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
return FindContractionWithBiasAddAndAdd(ctx, *node_view, matched);
}
bool FindContractionWithBiasAndAddActivation(
const RemapperContext& ctx, int node_index,
ContractionWithBiasAndAddActivation* 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 an activation node.
const auto* node_def = node_view->node();
if (node_def == nullptr) return false;
if (!IsSupportedActivation(*node_def)) return false;
#ifdef ENABLE_INTEL_MKL_BFLOAT16
// MKL activation op only supports float and bfloat16 data types.
if (!HasDataType(node_def, DT_FLOAT) && !HasDataType(node_def, DT_BFLOAT16))
return false;
#else
// MKL activation op only supports float data type.
if (!HasDataType(node_def, DT_FLOAT)) return false;
#endif // ENABLE_INTEL_MKL_BFLOAT16
// And input to activation must match ContractionWithBiasAddAndAdd pattern.
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* add_node_view = regular_fanin_0.node_view();
ContractionWithBiasAddAndAdd base;
if (!FindContractionWithBiasAddAndAdd(ctx, *add_node_view, &base)) {
return false;
}
// We successfully found a Conv2D+BiasAdd+AddN+activation pattern.
const ContractionWithBiasAndAddActivation pattern{
base.contraction, base.bias_add, base.add, base.port_id, node_index};
*matched = pattern;
return true;
}
#endif
bool FindFusedBatchNorm(const RemapperContext& ctx, int node_index,
FusedBatchNorm* matched) {
const auto* node_view = ctx.graph_view.GetNode(node_index);
const auto* node_def = node_view->node();
if (!IsFusedBatchNorm(*node_def)) return false;
if (GetDataTypeFromAttr(*node_def, "T") != DT_FLOAT) return false;
// Check that the node is in inference mode.
bool is_training = true;
if (!TryGetNodeAttr(*node_def, kIsTraining, &is_training)) return false;
if (is_training) return false;
const auto& props = ctx.graph_properties.GetInputProperties(node_def->name());
// a. Scaling factor can be const folded:
// scaling_factor = (variance + epsilon).rsqrt() * scale
bool const_scaling_factor =
props.size() == 5 && // [x, scale, offset, mean, variance]
props[1].has_value() && // scale
props[4].has_value(); // variance aka estimated variance
// b. Or input can be const folded into some other expression.
auto const_inputs = std::count_if(
props.begin(), props.end(),
[](const OpInfo::TensorProperties& props) { return props.has_value(); });
// TODO(bsteiner): use the cost model to compare the cost of fused batch
// norm against that of the optimized form.
bool can_remap = const_scaling_factor || const_inputs >= 4;
if (!can_remap) return false;
// The optimized version only generates the first output.
if (node_view->GetRegularFanouts().size() > 1) {
return false;
}
// We found a fused batch norm node that can be replaced with primitive ops.
matched->fused_batch_norm = node_index;
return true;
}
// NOTE(ezhulenev): See `BatchnormSpatialPersistentEnabled` documentation in the
// `tensorflow/stream_executor/cuda/cuda_dnn.cc` for details.
bool BatchnormSpatialPersistentEnabled() {
#if CUDNN_VERSION >= 7402
static bool is_enabled = [] {
bool is_enabled = false;
TF_CHECK_OK(tensorflow::ReadBoolFromEnvVar(
"TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT",
/*default_val=*/false, &is_enabled));
return is_enabled;
}();
return is_enabled;
#else
return false;
#endif
}
bool FindFusedBatchNormEx(const RemapperContext& ctx, int node_index,
FusedBatchNormEx* matched) {
// Root of the pattern must be a Relu.
// TODO(ezhulenev): Forward control dependencies.
const auto* node_view = ctx.graph_view.GetNode(node_index);
const auto* node_def = node_view->node();
// TODO(lyandy): Forward controls for patterns with control dependencies.
if (!IsRelu(*node_def) || HasControlFaninOrFanout(*node_view)) return false;
// Returns true iff the node is a compatible FusedBatchNorm node.
const auto valid_batch_norm =
[&](const utils::MutableNodeView& fused_batch_norm) -> bool {
const auto* fused_batch_norm_node_def = fused_batch_norm.node();
if (!IsFusedBatchNorm(*fused_batch_norm_node_def)) return false;
#ifndef ENABLE_MKLDNN_V1
// We fuse FusedBatchNorm on GPU or MKL CPU.
if (!NodeIsOnGpu(fused_batch_norm_node_def)) return false;
#endif
DataType t_dtype = GetDataTypeFromAttr(*fused_batch_norm_node_def, "T");
#ifndef ENABLE_MKLDNN_V1
if (t_dtype != DT_FLOAT && t_dtype != DT_HALF) return false;
#else
if (t_dtype != DT_FLOAT && t_dtype != DT_BFLOAT16) return false;
#endif
// Get the FusedBatchNorm training mode.
bool is_training;
if (!GetNodeAttr(*fused_batch_norm_node_def, kIsTraining, &is_training)
.ok())
return false;
// In training mode we rely on cuDNN for computing FusedBatchNorm with side
// inputs and activation, and it has its own limitations. In inference mode
// we have a custom CUDA kernel that doesn't not have these constraints.
if (is_training && NodeIsOnGpu(fused_batch_norm_node_def)) {
// cuDNN only supports NHWC data layout.
string data_format;
if (!GetNodeAttr(*fused_batch_norm_node_def, kDataFormat, &data_format)
.ok())
return false;
if (data_format != "NHWC") return false;
// Data type must be DT_HALF.
if (t_dtype != DT_HALF) return false;
// Channel dimension must be a multiple of 4.
const auto& props = ctx.graph_properties.GetInputProperties(
fused_batch_norm_node_def->name());
const bool valid_channel_dim = !props.empty() &&
props[0].shape().dim_size() == 4 &&
props[0].shape().dim(3).size() % 4 == 0;
if (!valid_channel_dim) return false;
// cuDNN must support CUDNN_BATCHNORM_SPATIAL_PERSISTENT mode.
if (!BatchnormSpatialPersistentEnabled()) return false;
}
// FusedBatchNormV2 and V3 have an extra type parameter.
if ((fused_batch_norm_node_def->op() != "FusedBatchNorm") &&
!HasDataType(fused_batch_norm_node_def, DT_FLOAT, "U"))
return false;
// Check that only one node consumes the 0-th output of a FusedBatchNorm.
if (HasControlFaninOrFanout(fused_batch_norm) ||
!HasAtMostOneDataFanoutAtPort0(fused_batch_norm) ||
IsInPreserveSet(ctx, fused_batch_norm_node_def))
return false;
return true;
};
if (node_view->NumRegularFanins() < 1) return false;
const auto& regular_fanin_0 = node_view->GetRegularFanin(0);
const auto* relu_fanin_0_node_view = regular_fanin_0.node_view();
const auto* relu_fanin_0_node_def = relu_fanin_0_node_view->node();
// Input to a Relu can be a FusedBatchNorm.
if (valid_batch_norm(*relu_fanin_0_node_view)) {
matched->activation = node_index;
matched->fused_batch_norm = regular_fanin_0.node_index();
return true;
}
// Input to a Relu can be an Add node with FusedBatchNorm as one of the inputs
if (IsAdd(*relu_fanin_0_node_def)) {
// Currently no CPU implementation for "FusedBatchNorm + SideInput +
// <Activation>""
#ifdef ENABLE_MKLDNN_V1
return false;
#endif
// Check that only Relu node consumes the output of an Add node.
if (HasControlFaninOrFanout(*relu_fanin_0_node_view) ||
!HasAtMostOneFanoutAtPort0(*relu_fanin_0_node_view) ||
IsInPreserveSet(ctx, relu_fanin_0_node_def))
return false;
// Add node supports broadcasting, FusedBatchNormEx does not.
const auto& props =
ctx.graph_properties.GetInputProperties(relu_fanin_0_node_def->name());
if (props.size() < 2 ||
!ShapesSymbolicallyEqual(props[0].shape(), props[1].shape()))
return false;
if (relu_fanin_0_node_view->NumRegularFanins() < 2) return false;
const auto& add_regular_fanin_0 =
relu_fanin_0_node_view->GetRegularFanin(0);
const auto& add_regular_fanin_1 =
relu_fanin_0_node_view->GetRegularFanin(1);
if (valid_batch_norm(*add_regular_fanin_0.node_view())) {
matched->activation = node_index;
matched->side_input = add_regular_fanin_1.node_index();
matched->fused_batch_norm = add_regular_fanin_0.node_index();
matched->invalidated = regular_fanin_0.node_index();
return true;
}
if (valid_batch_norm(*add_regular_fanin_1.node_view())) {
matched->activation = node_index;
matched->side_input = add_regular_fanin_0.node_index();
matched->fused_batch_norm = add_regular_fanin_1.node_index();
matched->invalidated = regular_fanin_0.node_index();
return true;
}
}
return false;
}
void CopyConv2DAttributes(const NodeDef& conv2d, NodeDef* fused_conv2d) {
DCHECK(IsConv2D(conv2d)) << "Input node must be a Conv2D";
auto* attr = fused_conv2d->mutable_attr();
auto& src_attr = conv2d.attr();
(*attr)["T"] = src_attr.at("T");
(*attr)["strides"] = src_attr.at("strides");
(*attr)["padding"] = src_attr.at("padding");
(*attr)["explicit_paddings"] = src_attr.at("explicit_paddings");
(*attr)["dilations"] = src_attr.at("dilations");
(*attr)["data_format"] = src_attr.at("data_format");
(*attr)["use_cudnn_on_gpu"] = src_attr.at("use_cudnn_on_gpu");
}
void CopyDepthwiseConv2dNativeAttributes(const NodeDef& dw_conv2d,
NodeDef* fused_dw_conv2d) {
DCHECK(IsDepthwiseConv2dNative(dw_conv2d))
<< "Input node must be a DepthwiseConv2dNative";
auto* attr = fused_dw_conv2d->mutable_attr();
auto& src_attr = dw_conv2d.attr();
(*attr)["T"] = src_attr.at("T");
(*attr)["strides"] = src_attr.at("strides");
(*attr)["padding"] = src_attr.at("padding");
(*attr)["dilations"] = src_attr.at("dilations");
(*attr)["data_format"] = src_attr.at("data_format");
}
void CopyFusedBatchNormAttributes(const NodeDef& fused_batch_norm,
NodeDef* fused_batch_norm_ex) {
DCHECK(IsFusedBatchNorm(fused_batch_norm))
<< "Input node must be a FusedBatchNorm";
auto* attr = fused_batch_norm_ex->mutable_attr();
auto src_attr = fused_batch_norm.attr();
(*attr)["T"] = src_attr.at("T");
(*attr)["is_training"] = src_attr.at("is_training");
(*attr)["data_format"] = src_attr.at("data_format");
(*attr)["epsilon"] = src_attr.at("epsilon");
(*attr)["exponential_avg_factor"] = src_attr.at("exponential_avg_factor");
// FusedBatchNormV2 and V3 have an extra type parameter.
if (fused_batch_norm.op() != "FusedBatchNorm") {
SetAttrValue(src_attr.at("U"), &(*attr)["U"]);
} else {
#ifndef ENABLE_MKLDNN_V1
SetAttrValue(src_attr.at("T"), &(*attr)["U"]);
#else
SetAttrValue(DT_FLOAT, &(*attr)["U"]);
#endif
}
}
void CopyMatMulAttributes(const NodeDef& matmul, NodeDef* fused_matmul) {
DCHECK(IsMatMul(matmul)) << "Input node must be a MatMul";
auto* attr = fused_matmul->mutable_attr();
auto& src_attr = matmul.attr();
(*attr)["T"] = src_attr.at("T");
(*attr)["transpose_a"] = src_attr.at("transpose_a");
(*attr)["transpose_b"] = src_attr.at("transpose_b");
}
void SetFusedOpAttributes(NodeDef* fused,
const absl::Span<const absl::string_view> fused_ops,
int num_args = 1, float epsilon = 0.0) {
auto* attr = fused->mutable_attr();
SetAttrValue(fused_ops, &(*attr)["fused_ops"]);
SetAttrValue(num_args, &(*attr)["num_args"]);
SetAttrValue(epsilon, &(*attr)["epsilon"]); // required only for BatchNorm
}
Status AddFusedContractionNode(RemapperContext* ctx,
const ContractionWithBiasAdd& matched,
std::vector<bool>* invalidated_nodes,
std::vector<bool>* nodes_to_delete) {
DCHECK(IsDeviceCompatible(*ctx, matched)) << "Unsupported fusion pattern";
const GraphDef* graph = ctx->graph_view.graph();
const NodeDef& contraction = graph->node(matched.contraction);