forked from tensorflow/tensorflow
/
mkl_conv_ops.cc
2815 lines (2595 loc) · 128 KB
/
mkl_conv_ops.cc
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 2015 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.
==============================================================================*/
// See docs in ../ops/nn_ops.cc.
#ifdef INTEL_MKL
#include "tensorflow/core/kernels/mkl/mkl_conv_ops.h"
#include <algorithm>
#include <map>
#include <string>
#include <unordered_map>
#include "absl/strings/str_join.h"
#include "tensorflow/core/kernels/mkl/mkl_quantized_conv_ops.h"
#include "tensorflow/core/kernels/no_op.h"
#ifdef DNNL_AARCH64_USE_ACL
#include "tensorflow/core/platform/mutex.h"
#endif
using dnnl::convolution_forward;
using dnnl::prop_kind;
using dnnl::stream;
using ConvFwdPd = dnnl::convolution_forward::primitive_desc;
using ReorderPd = dnnl::reorder::primitive_desc;
namespace tensorflow {
// TODO(intel-tf) Remove this once old API of quantized ops is abandoned
namespace quantized_fusions {
string none[] = {""};
string bias[] = {"BiasAdd"};
string relu[] = {"Relu"};
string requantize[] = {"Requantize"};
string bias_relu[] = {"BiasAdd", "Relu"};
string bias_requantize[] = {"BiasAdd", "Requantize"};
string relu_requantize[] = {"Relu", "Requantize"};
string bias_relu_requantize[] = {"BiasAdd", "Relu", "Requantize"};
string bias_sum_relu[] = {"BiasAdd", "Sum", "Relu"};
string bias_sum_relu_requantize[] = {"BiasAdd", "Sum", "Relu", "Requantize"};
} // namespace quantized_fusions
// This structure aggregates multiple inputs to Conv2DFwd* methods.
struct MklConvFwdParams {
memory::dims src_dims;
memory::dims filter_dims;
memory::dims bias_dims;
memory::dims dst_dims;
memory::dims strides;
memory::dims dilations;
memory::dims padding_left;
memory::dims padding_right;
memory::dims fuse_bn_dims;
MklTensorFormat tf_fmt;
bool native_format;
string dtypes = string("");
struct PostOpParam {
string name;
dnnl::algorithm alg;
std::vector<float> param;
std::string partial_key;
};
std::vector<PostOpParam> post_op_params;
MklConvFwdParams(memory::dims src_dims, memory::dims filter_dims,
memory::dims bias_dims, memory::dims dst_dims,
memory::dims strides, memory::dims dilations,
memory::dims padding_left, memory::dims padding_right,
memory::dims fuse_bn_dims, MklTensorFormat tf_fmt,
bool native_format)
: src_dims(src_dims),
filter_dims(filter_dims),
bias_dims(bias_dims),
dst_dims(dst_dims),
strides(strides),
dilations(dilations),
padding_left(padding_left),
padding_right(padding_right),
fuse_bn_dims(fuse_bn_dims),
tf_fmt(tf_fmt),
native_format(native_format) {}
};
// With quantization, input, filter, and output can have different types
// so we use different template parameter for each type
template <typename Tinput, typename Tfilter, typename Tbias, typename Toutput>
class MklConvFwdPrimitive : public MklPrimitive {
public:
explicit MklConvFwdPrimitive(const MklConvFwdParams& convFwdDims)
: MklPrimitive(engine(engine::kind::cpu, 0)) {
// Create convolution primitive
if (context_.conv_fwd == nullptr) {
Setup(convFwdDims);
}
}
~MklConvFwdPrimitive() {}
dnnl::memory::desc GetScratchPadDesc() {
return context_.fwd_pd->scratchpad_desc();
}
// Convolution forward execute with bias
// src_data: input data buffer of src
// filter_data: input data buffer of filter (weights)
// bias_data: input data buffer of bias
// dst_data: output data buffer of dst
void Execute(const Tinput* src_data, const Tfilter* filter_data,
const Tbias* bias_data, const Toutput* dst_data,
std::shared_ptr<stream> fwd_stream, void* sp_data = nullptr) {
Execute(src_data, filter_data, bias_data, dst_data, nullptr, nullptr,
nullptr, nullptr, fwd_stream, sp_data);
}
void Execute(const Tinput* src_data, const Tfilter* filter_data,
const Tbias* bias_data, const Toutput* dst_data,
const Tinput* bn_scale_data, const Tinput* bn_mean_data,
const Tinput* bn_offset_data, const Tinput* bn_rsqrt_data,
std::shared_ptr<stream> fwd_stream, void* sp_data) {
#ifdef DNNL_AARCH64_USE_ACL
// When we are using single global cache then in this case we can have
// multiple threads running the same primitive that we created so this
// should happen under the lock.
mutex_lock lock(primitive_execution_mu_);
#endif
#ifndef ENABLE_ONEDNN_OPENMP
// TODO(intel-tf): Create a common function and avoid the duplicate code
context_.src_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(src_data)), *fwd_stream);
context_.filter_mem->set_data_handle(
static_cast<void*>(const_cast<Tfilter*>(filter_data)), *fwd_stream);
if (bias_data != nullptr) {
context_.bias_mem->set_data_handle(
static_cast<void*>(const_cast<Tbias*>(bias_data)), *fwd_stream);
}
if (bn_scale_data != nullptr) {
context_.bn_scale_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_scale_data)), *fwd_stream);
context_.bn_mean_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_mean_data)), *fwd_stream);
context_.bn_rsqrt_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_rsqrt_data)), *fwd_stream);
context_.bn_offset_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_offset_data)), *fwd_stream);
}
context_.dst_mem->set_data_handle(
static_cast<void*>(const_cast<Toutput*>(dst_data)), *fwd_stream);
#else
context_.src_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(src_data)));
context_.filter_mem->set_data_handle(
static_cast<void*>(const_cast<Tfilter*>(filter_data)));
if (bias_data != nullptr) {
context_.bias_mem->set_data_handle(
static_cast<void*>(const_cast<Tbias*>(bias_data)));
}
if (bn_scale_data != nullptr) {
context_.bn_scale_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_scale_data)));
context_.bn_mean_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_mean_data)));
context_.bn_rsqrt_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_rsqrt_data)));
context_.bn_offset_mem->set_data_handle(
static_cast<void*>(const_cast<Tinput*>(bn_offset_data)));
}
context_.dst_mem->set_data_handle(
static_cast<void*>(const_cast<Toutput*>(dst_data)));
#endif // !ENABLE_ONEDNN_OPENMP
if (sp_data) {
context_.sp_mem->set_data_handle(static_cast<void*>(sp_data),
*fwd_stream);
}
DCHECK_EQ(context_.fwd_primitives.size(),
context_.fwd_primitives_args.size());
for (size_t i = 0; i < context_.fwd_primitives.size(); ++i) {
context_.fwd_primitives.at(i).execute(*fwd_stream,
context_.fwd_primitives_args.at(i));
}
// After execution, set data handle back
context_.src_mem->set_data_handle(DummyData);
context_.filter_mem->set_data_handle(DummyData);
if (bias_data != nullptr) {
context_.bias_mem->set_data_handle(DummyData);
}
if (bn_scale_data != nullptr) {
context_.bn_scale_mem->set_data_handle(DummyData);
context_.bn_mean_mem->set_data_handle(DummyData);
context_.bn_rsqrt_mem->set_data_handle(DummyData);
context_.bn_offset_mem->set_data_handle(DummyData);
}
context_.dst_mem->set_data_handle(DummyData);
if (sp_data) {
context_.sp_mem->set_data_handle(DummyData);
}
}
// Convolution forward execute without bias
// src_data: input data buffer of src
// filter_data: input data buffer of filter (weights)
// dst_data: output data buffer of dst
void Execute(const Tinput* src_data, const Tfilter* filter_data,
const Toutput* dst_data, std::shared_ptr<stream> fwd_stream,
void* sp_data) {
Execute(src_data, filter_data, nullptr, dst_data, nullptr, nullptr, nullptr,
nullptr, fwd_stream, sp_data);
}
std::shared_ptr<ConvFwdPd> GetPrimitiveDesc() const {
return context_.fwd_pd;
}
private:
// Primitive reuse context for Conv2D Fwd op
struct ConvFwdContext {
// MKL-DNN memory
std::shared_ptr<dnnl::memory> src_mem;
std::shared_ptr<dnnl::memory> filter_mem;
std::shared_ptr<dnnl::memory> bias_mem;
std::shared_ptr<dnnl::memory> dst_mem;
std::shared_ptr<dnnl::memory> sp_mem;
// FusedBatchNorm related memory
std::shared_ptr<dnnl::memory> bn_scale_mem;
std::shared_ptr<dnnl::memory> bn_mean_mem;
std::shared_ptr<dnnl::memory> bn_rsqrt_mem;
std::shared_ptr<dnnl::memory> bn_offset_mem;
// Desc & primitive desc
std::shared_ptr<dnnl::convolution_forward::desc> fwd_desc;
// Memory desc
std::shared_ptr<dnnl::memory::desc> src_md;
std::shared_ptr<dnnl::memory::desc> filter_md;
std::shared_ptr<dnnl::memory::desc> bias_md;
std::shared_ptr<dnnl::memory::desc> dst_md;
// TODO(intel-tf): Only need one? FusedBatchNorm related.
std::shared_ptr<dnnl::memory::desc> bn_scale_md;
std::shared_ptr<dnnl::memory::desc> bn_mean_md;
std::shared_ptr<dnnl::memory::desc> bn_rsqrt_md;
std::shared_ptr<dnnl::memory::desc> bn_offset_md;
// Convolution primitive
std::shared_ptr<ConvFwdPd> fwd_pd;
std::shared_ptr<dnnl::primitive> conv_fwd;
std::vector<dnnl::primitive> fwd_primitives;
std::vector<std::unordered_map<int, memory>> fwd_primitives_args;
ConvFwdContext()
: src_mem(nullptr),
filter_mem(nullptr),
bias_mem(nullptr),
dst_mem(nullptr),
sp_mem(nullptr),
bn_scale_mem(nullptr),
bn_mean_mem(nullptr),
bn_rsqrt_mem(nullptr),
bn_offset_mem(nullptr),
fwd_desc(nullptr),
src_md(nullptr),
filter_md(nullptr),
bias_md(nullptr),
dst_md(nullptr),
bn_scale_md(nullptr),
bn_mean_md(nullptr),
bn_rsqrt_md(nullptr),
bn_offset_md(nullptr),
fwd_pd(nullptr),
conv_fwd(nullptr) {}
};
void Setup(const MklConvFwdParams& convFwdDims) {
memory::format_tag user_data_fmt;
if (convFwdDims.native_format) {
user_data_fmt = MklTensorFormatToMklDnnDataFormat(convFwdDims.tf_fmt);
} else {
// Create memory descriptors for convolution data w/ no specified format
user_data_fmt = memory::format_tag::any;
}
context_.src_md.reset(new memory::desc(
{convFwdDims.src_dims}, MklDnnType<Tinput>(), user_data_fmt));
context_.filter_md.reset(new memory::desc({convFwdDims.filter_dims},
MklDnnType<Tfilter>(),
memory::format_tag::any));
context_.dst_md.reset(new memory::desc(
{convFwdDims.dst_dims}, MklDnnType<Toutput>(), user_data_fmt));
if (!convFwdDims.bias_dims.empty()) {
context_.bias_md.reset(new memory::desc({convFwdDims.bias_dims},
MklDnnType<Tbias>(),
memory::format_tag::any));
// Create a convolution descriptor
context_.fwd_desc.reset(new convolution_forward::desc(
prop_kind::forward, dnnl::algorithm::convolution_direct,
*context_.src_md, *context_.filter_md, *context_.bias_md,
*context_.dst_md, convFwdDims.strides, convFwdDims.dilations,
convFwdDims.padding_left, convFwdDims.padding_right));
} else {
context_.fwd_desc.reset(new convolution_forward::desc(
prop_kind::forward, dnnl::algorithm::convolution_direct,
*context_.src_md, *context_.filter_md, *context_.dst_md,
convFwdDims.strides, convFwdDims.dilations, convFwdDims.padding_left,
convFwdDims.padding_right));
}
if (!convFwdDims.fuse_bn_dims.empty()) {
const memory::format_tag fused_bn_arg_fmt =
convFwdDims.native_format
? user_data_fmt
: MklTensorFormatToMklDnnDataFormat(convFwdDims.tf_fmt);
context_.bn_scale_md.reset(new memory::desc(
{convFwdDims.fuse_bn_dims}, MklDnnType<Tinput>(), fused_bn_arg_fmt));
context_.bn_mean_md.reset(new memory::desc(
{convFwdDims.fuse_bn_dims}, MklDnnType<Tinput>(), fused_bn_arg_fmt));
context_.bn_rsqrt_md.reset(new memory::desc(
{convFwdDims.fuse_bn_dims}, MklDnnType<Tinput>(), fused_bn_arg_fmt));
context_.bn_offset_md.reset(new memory::desc(
{convFwdDims.fuse_bn_dims}, MklDnnType<Tinput>(), fused_bn_arg_fmt));
}
// Check if there is any fusions as post-ops
auto const& post_op_params = convFwdDims.post_op_params;
dnnl::primitive_attr post_ops_attr;
dnnl::post_ops post_ops;
post_ops_attr.set_scratchpad_mode(dnnl::scratchpad_mode::user);
if (!post_op_params.empty()) {
for (auto const& post_op_param : post_op_params) {
if (post_op_param.name == "activation") {
DCHECK_EQ(post_op_param.param.size(), 3);
float op_scale = post_op_param.param[0];
float op_alpha = post_op_param.param[1];
float op_beta = post_op_param.param[2];
post_ops.append_eltwise(op_scale, post_op_param.alg, op_alpha,
op_beta);
} else if (post_op_param.name == "sum") {
DCHECK_EQ(post_op_param.param.size(), 1);
float op_scale = post_op_param.param[0];
post_ops.append_sum(op_scale);
} else if (post_op_param.name == "output_scale") {
if (post_op_param.param.size() == 1) {
post_ops_attr.set_output_scales(0, post_op_param.param);
} else {
post_ops_attr.set_output_scales(2, post_op_param.param);
}
} else if (post_op_param.name == "fuse_bn") {
post_ops.append_binary(dnnl::algorithm::binary_sub,
*context_.bn_mean_md);
post_ops.append_binary(dnnl::algorithm::binary_mul,
*context_.bn_rsqrt_md);
post_ops.append_binary(dnnl::algorithm::binary_mul,
*context_.bn_scale_md);
post_ops.append_binary(dnnl::algorithm::binary_add,
*context_.bn_offset_md);
} else {
DCHECK((post_op_param.name == "activation") ||
(post_op_param.name == "sum") ||
(post_op_param.name == "output_scale") ||
(post_op_param.name == "fuse_bn"));
}
}
post_ops_attr.set_post_ops(post_ops);
}
context_.fwd_pd.reset(
new ConvFwdPd(*context_.fwd_desc, post_ops_attr, cpu_engine_));
// Create memory primitive based on dummy data
context_.src_mem.reset(
new memory(context_.fwd_pd.get()->src_desc(), cpu_engine_, DummyData));
context_.filter_mem.reset(new memory(context_.fwd_pd.get()->weights_desc(),
cpu_engine_, DummyData));
context_.dst_mem.reset(
new memory(context_.fwd_pd.get()->dst_desc(), cpu_engine_, DummyData));
context_.conv_fwd.reset(new convolution_forward(*context_.fwd_pd));
auto scratchpad_md = context_.fwd_pd->scratchpad_desc();
context_.sp_mem.reset(
new dnnl::memory(scratchpad_md, cpu_engine_, DummyData));
// Create convolution primitive and add it to net
if (!convFwdDims.bias_dims.empty()) {
context_.bias_mem.reset(new memory(
{{convFwdDims.bias_dims}, MklDnnType<Tbias>(), memory::format_tag::x},
cpu_engine_, DummyData));
context_.fwd_primitives_args.push_back(
{{DNNL_ARG_SRC, *context_.src_mem},
{DNNL_ARG_WEIGHTS, *context_.filter_mem},
{DNNL_ARG_BIAS, *context_.bias_mem},
{DNNL_ARG_SCRATCHPAD, *context_.sp_mem},
{DNNL_ARG_DST, *context_.dst_mem}});
} else if (!convFwdDims.fuse_bn_dims.empty()) {
context_.bn_scale_mem.reset(
new memory(*context_.bn_scale_md, cpu_engine_, DummyData));
context_.bn_mean_mem.reset(
new memory(*context_.bn_mean_md, cpu_engine_, DummyData));
context_.bn_offset_mem.reset(
new memory(*context_.bn_offset_md, cpu_engine_, DummyData));
context_.bn_rsqrt_mem.reset(
new memory(*context_.bn_rsqrt_md, cpu_engine_, DummyData));
context_.fwd_primitives_args.push_back(
{{DNNL_ARG_SRC, *context_.src_mem},
{DNNL_ARG_WEIGHTS, *context_.filter_mem},
{DNNL_ARG_DST, *context_.dst_mem},
{DNNL_ARG_SCRATCHPAD, *context_.sp_mem},
{DNNL_ARG_ATTR_MULTIPLE_POST_OP(0) | DNNL_ARG_SRC_1,
*context_.bn_mean_mem},
{DNNL_ARG_ATTR_MULTIPLE_POST_OP(1) | DNNL_ARG_SRC_1,
*context_.bn_rsqrt_mem},
{DNNL_ARG_ATTR_MULTIPLE_POST_OP(2) | DNNL_ARG_SRC_1,
*context_.bn_scale_mem},
{DNNL_ARG_ATTR_MULTIPLE_POST_OP(3) | DNNL_ARG_SRC_1,
*context_.bn_offset_mem}});
} else {
context_.fwd_primitives_args.push_back(
{{DNNL_ARG_SRC, *context_.src_mem},
{DNNL_ARG_WEIGHTS, *context_.filter_mem},
{DNNL_ARG_SCRATCHPAD, *context_.sp_mem},
{DNNL_ARG_DST, *context_.dst_mem}});
}
context_.fwd_primitives.push_back(*context_.conv_fwd);
}
struct ConvFwdContext context_;
#ifdef DNNL_AARCH64_USE_ACL
// Guards Execution()
mutex primitive_execution_mu_;
#endif
};
// TODO(intel-tf): We should not require passing a type to MklPrimitiveFactory.
// But removing the need for type in MklPrimitiveFactory is going to require
// change to every MKL op. So not doing it now. Instead passing float.
template <typename Tinput, typename Tfilter, typename Tbias, typename Toutput>
class MklConvFwdPrimitiveFactory : public MklPrimitiveFactory<float> {
public:
static MklConvFwdPrimitive<Tinput, Tfilter, Tbias, Toutput>* Get(
const MklConvFwdParams& convFwdDims, bool do_not_cache) {
MklConvFwdPrimitive<Tinput, Tfilter, Tbias, Toutput>* conv_fwd = nullptr;
if (do_not_cache) {
// Always create a new primitive
conv_fwd =
new MklConvFwdPrimitive<Tinput, Tfilter, Tbias, Toutput>(convFwdDims);
} else {
// Try to find a suitable one in pool
conv_fwd =
dynamic_cast<MklConvFwdPrimitive<Tinput, Tfilter, Tbias, Toutput>*>(
MklConvFwdPrimitiveFactory<Tinput, Tfilter, Tbias,
Toutput>::GetInstance()
.GetConvFwd(convFwdDims));
if (conv_fwd == nullptr) {
conv_fwd = new MklConvFwdPrimitive<Tinput, Tfilter, Tbias, Toutput>(
convFwdDims);
MklConvFwdPrimitiveFactory<Tinput, Tfilter, Tbias,
Toutput>::GetInstance()
.SetConvFwd(convFwdDims, conv_fwd);
}
}
return conv_fwd;
}
private:
MklConvFwdPrimitiveFactory() {}
~MklConvFwdPrimitiveFactory() {}
static const int kDilationH = 0, kDilationW = 1;
static MklConvFwdPrimitiveFactory& GetInstance() {
static MklConvFwdPrimitiveFactory instance_;
return instance_;
}
static string CreateKey(const MklConvFwdParams& convFwdDims) {
string prefix = "conv_fwd_";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(convFwdDims.src_dims);
key_creator.AddAsKey(convFwdDims.filter_dims);
key_creator.AddAsKey(convFwdDims.bias_dims);
key_creator.AddAsKey(convFwdDims.dst_dims);
key_creator.AddAsKey(convFwdDims.strides);
key_creator.AddAsKey(convFwdDims.dilations);
key_creator.AddAsKey(convFwdDims.padding_left);
key_creator.AddAsKey(convFwdDims.padding_right);
key_creator.AddAsKey(convFwdDims.dtypes);
if (convFwdDims.native_format) {
key_creator.AddAsKey(convFwdDims.tf_fmt);
}
// Generate keys for post-ops
for (auto const& post_op_param : convFwdDims.post_op_params) {
key_creator.AddAsKey(post_op_param.name);
if (post_op_param.name == "activation") {
key_creator.AddAsKey(post_op_param.alg);
DCHECK_EQ(post_op_param.param.size(), 3);
for (auto& param : post_op_param.param) {
key_creator.AddAsKey(param);
}
} else if (post_op_param.name == "sum") {
DCHECK_EQ(post_op_param.param.size(), 1);
for (auto& param : post_op_param.param) {
key_creator.AddAsKey(param);
}
} else if (post_op_param.name == "output_scale") {
key_creator.AddAsKey(post_op_param.partial_key);
} else if (post_op_param.name == "fuse_bn") {
key_creator.AddAsKey(post_op_param.name);
key_creator.AddAsKey(convFwdDims.fuse_bn_dims);
} else {
return string("not_a_key");
}
}
return key_creator.GetKey();
}
MklPrimitive* GetConvFwd(const MklConvFwdParams& convFwdDims) {
string key = CreateKey(convFwdDims);
return this->GetOp(key);
}
void SetConvFwd(const MklConvFwdParams& convFwdDims, MklPrimitive* op) {
string key = CreateKey(convFwdDims);
this->SetOp(key, op);
}
};
// Base class for convolution forward operations
template <typename Device, typename Tinput, typename Tfilter, typename Tbias,
typename Toutput, typename Ttemp_output, typename Tpadding,
bool bias_enabled, bool pad_enabled, bool is_depthwise,
bool native_format>
class MklConvOp : public OpKernel {
public:
~MklConvOp() {}
explicit MklConvOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("dilations", &dilations_));
// Conv and QuantizedConv ops have different padding attributes
// (`padding_list` versus `explicit_paddings`). But one and only one
// attribute is expected.
OP_REQUIRES(
context,
!(context->HasAttr("padding_list") &&
context->HasAttr("explicit_paddings")),
errors::InvalidArgument("Can only have 1 `padding` list at most"));
if (context->HasAttr("padding_list")) {
OP_REQUIRES_OK(context, context->GetAttr("padding_list", &padding_list_));
}
if (context->HasAttr("explicit_paddings")) {
OP_REQUIRES_OK(context,
context->GetAttr("explicit_paddings", &padding_list_));
}
OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_));
OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format_str_));
OP_REQUIRES(context, FormatFromString(data_format_str_, &data_format_),
errors::InvalidArgument("Invalid data format"));
OP_REQUIRES(context, (strides_.size() == 4 || strides_.size() == 5),
errors::InvalidArgument("Sliding window strides field must "
"specify 4 or 5 dimensions"));
const int64 stride_n = GetTensorDim(strides_, data_format_, 'N');
const int64 stride_c = GetTensorDim(strides_, data_format_, 'C');
OP_REQUIRES(
context, stride_n == 1 && stride_c == 1,
errors::Unimplemented("Current implementation does not yet support "
"strides in the batch and depth dimensions."));
OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
is_filter_const_ = false;
if (AreWeightsFrozen()) {
is_filter_const_ = true;
} else if (context->HasAttr("is_filter_const")) {
OP_REQUIRES_OK(context,
context->GetAttr("is_filter_const", &is_filter_const_));
}
if (strides_.size() == 4) {
OP_REQUIRES(context, dilations_.size() == 4,
errors::InvalidArgument("Sliding window dilations field must "
"specify 4 dimensions"));
const int64 dilation_n = GetTensorDim(dilations_, data_format_, 'N');
const int64 dilation_c = GetTensorDim(dilations_, data_format_, 'C');
const int64 dilation_h = GetTensorDim(dilations_, data_format_, 'H');
const int64 dilation_w = GetTensorDim(dilations_, data_format_, 'W');
OP_REQUIRES(context, dilation_n == 1 && dilation_c == 1,
errors::InvalidArgument(
"Current implementation does not yet support "
"dilations in the batch and depth dimensions."));
OP_REQUIRES(
context, dilation_h > 0 && dilation_w > 0,
errors::InvalidArgument("Dilated rates should be larger than 0."));
} else if (strides_.size() == 5) {
OP_REQUIRES(context, dilations_.size() == 5,
errors::InvalidArgument("Dilation rates field must "
"specify 5 dimensions"));
OP_REQUIRES(context,
(GetTensorDim(dilations_, data_format_, 'N') == 1 &&
GetTensorDim(dilations_, data_format_, 'C') == 1),
errors::InvalidArgument(
"Current implementation does not yet support "
"dilations rates in the batch and depth dimensions."));
OP_REQUIRES(
context,
(GetTensorDim(dilations_, data_format_, '0') > 0 &&
GetTensorDim(dilations_, data_format_, '1') > 0 &&
GetTensorDim(dilations_, data_format_, '2') > 0),
errors::InvalidArgument("Dilated rates should be larger than 0."));
}
}
void Compute(OpKernelContext* context) override {
try {
// Input tensors
const Tensor& src_tensor = MklGetInput(context, kInputIndex_Src);
const Tensor& filter_tensor = MklGetInput(context, kInputIndex_Filter);
OP_REQUIRES(
context, filter_tensor.NumElements() > 0,
errors::InvalidArgument("filter must not have zero elements "
"(i.e. all dimensions must be non-zero)"));
MklDnnShape src_mkl_shape, filter_mkl_shape;
GetMklShape(context, kInputIndex_Src, &src_mkl_shape, native_format);
GetMklShape(context, kInputIndex_Filter, &filter_mkl_shape,
native_format);
OP_REQUIRES(context, !filter_mkl_shape.IsMklTensor(),
errors::InvalidArgument("Filter should not be in "
"Mkl Layout"));
MklDnnData<Tinput> src(&cpu_engine_);
MklDnnData<Tfilter> filter(&cpu_engine_);
memory::dims src_dims, filter_dims, padding_left, padding_right,
dilations, strides;
memory::dims dst_dims_tf_order, dst_dims_mkl_order;
// For any Conv with `EXPLICIT` padding, get padding from `padding_list`
// attribute. Otherwise, get it from one of the inputs.
bool pad_attr_enabled = false;
for (auto const& padding_val : padding_list_) {
if (padding_val) {
pad_attr_enabled = true;
break;
}
}
if (fuse_pad_ || pad_attr_enabled) {
PadWithConvFusion(context, padding_left, padding_right,
pad_attr_enabled, data_format_str_);
}
// Get shapes of input tensors in MKL-DNN order
MklDnnConvUtil conv_utl(context, strides_, padding_, data_format_,
dilations_);
auto src_tf_shape = GetTfShape(context, kInputIndex_Src, native_format);
auto filter_tf_shape =
GetTfShape(context, kInputIndex_Filter, native_format);
bool is_grouped_convolution = false;
conv_utl.GetConvFwdSizesInMklOrder(
src_tf_shape, filter_tf_shape, &src_dims, &filter_dims, &strides,
&dilations, &dst_dims_tf_order, &dst_dims_mkl_order, &padding_left,
&padding_right, &is_grouped_convolution,
(fuse_pad_ || pad_attr_enabled), is_depthwise);
if (!context->status().ok()) return;
// Check for corner case - if there is nothing to compute, return.
TensorShape dst_tf_shape = MklDnnDimsToTFShape(dst_dims_tf_order);
// Corner cases: output with 0 elements and 0 batch size.
Tensor* dst_tensor = nullptr;
bool emit_filter_output = (typeid(Tinput) == typeid(Tfilter) &&
typeid(Tinput) == typeid(Toutput) &&
(typeid(Tinput) == typeid(float) ||
typeid(Tinput) == typeid(bfloat16))) &&
!native_format;
if (dst_tf_shape.num_elements() == 0 || dst_dims_tf_order[0] == 0) {
MklDnnShape dst_mkl_shape;
dst_mkl_shape.SetMklTensor(false);
AllocateOutputSetMklShape(context, kOutputIndex_Dst, &dst_tensor,
src_tf_shape, dst_mkl_shape, native_format);
// MklConv2D/3D also outputs converted filter as 2nd output.
filter_mkl_shape.SetMklTensor(false);
Tensor* output_filter_tensor = nullptr;
if (emit_filter_output) {
filter_mkl_shape.SetMklTensor(false);
AllocateOutputSetMklShape(context, kOutputIndex_Filter,
&output_filter_tensor, filter_tf_shape,
filter_mkl_shape);
}
return;
}
bool is_conv2d = (strides_.size() == 4);
bool is_conv3d = (strides_.size() == 5);
if (!is_conv2d && !is_conv3d) {
OP_REQUIRES(
context, !pad_enabled,
errors::InvalidArgument("Pad + Conv fusion only works for 2D/3D"));
OP_REQUIRES(
context, !fuse_pad_,
errors::InvalidArgument("Pad+Conv fusion only works for 2D/3D"));
}
// TODO(intel-tf) 3-D support for Depthwise is not there
if (is_depthwise) {
OP_REQUIRES(context, is_conv2d,
errors::InvalidArgument(
"Only 2D convolution is supported for depthwise."));
}
// Create memory for user data.
// Describe how the inputs and outputs of Convolution look like. Also
// specify buffers containing actual input and output data.
auto tf_fmt = is_conv2d ? TFDataFormatToMklDnnDataFormat(data_format_)
: TFDataFormatToMklDnn3DDataFormat(data_format_);
auto mkl_fmt_tag = MklTensorFormatToMklDnnDataFormat(tf_fmt);
// NOTE: `mkl_fmt_tag` will be `format_tag::undef` for ReLU
OP_REQUIRES(context, mkl_fmt_tag != memory::format_tag::undef,
errors::InvalidArgument("Invalid data format"));
// If input is in MKL layout, then simply grab the layout; otherwise,
// construct TF layout for input.
// For constructing TF layout for input, although input shape (src_dims)
// is required to be in MKL-DNN order, the input layout is actually in
// TF layout depending on the data format:
// Conv2D: NHWC or NCHW
// Conv3D: NDHWC or NCDHW
auto src_md =
src_mkl_shape.IsMklTensor()
? src_mkl_shape.GetMklLayout()
: memory::desc(src_dims, MklDnnType<Tinput>(), mkl_fmt_tag);
src.SetUsrMem(src_md, &src_tensor);
// Although filter shape (filter_dims) required is in MKL-DNN order,
// the layout is Tensorflow's layout (HWIO) and (HWIGO) for
// depthwise/group convolutions.
auto filter_format = is_conv2d ? ((is_depthwise || is_grouped_convolution)
? memory::format_tag::hwigo
: memory::format_tag::hwio)
: memory::format_tag::dhwio;
DCHECK(!filter_mkl_shape.IsMklTensor());
auto filter_md =
filter_mkl_shape.IsMklTensor()
? filter_mkl_shape.GetMklLayout()
: memory::desc(filter_dims, MklDnnType<Tfilter>(), filter_format);
filter.SetUsrMem(filter_md, &filter_tensor);
// MKL-DNN dilations start from 0.
for (int i = 0; i < dilations.size(); ++i) --dilations[i];
// In some cases, primitive descriptor could potentially contain
// large buffers. As a result, we don't cache these primitives if the
// environment variable `TF_MKL_OPTIMIZE_PRIMITIVE_MEMUSE` is set to True.
// MKL-DNN allocates buffers in the following cases:
// 1. Legacy CPU without AVX512/AVX2, or
// 2. 1x1 convolution with strides != 1
bool do_not_cache =
MklPrimitiveFactory<Tinput>::IsPrimitiveMemOptEnabled() &&
(src_dims[MklDnnDims::Dim_N] > kSmallBatchSize) &&
(MklPrimitiveFactory<Tinput>::IsLegacyPlatform() ||
IsConv1x1StrideNot1(filter_dims, strides));
// Get a conv2d fwd from primitive pool
MklConvFwdPrimitive<Tinput, Tfilter, Tbias, Ttemp_output>* conv_fwd =
nullptr;
memory::dims bias_dims = {};
if (fuse_biasadd_) {
conv_utl.GetBiasSizeInMklOrder(kInputIndex_Bias, &bias_dims);
}
memory::dims fuse_bn_dims = {};
TensorShape fuse_bn_shape;
if (fuse_bn_) {
// Inputs to FusedBatchNorm have same 1D shape
fuse_bn_shape = MklGetInput(context, kInputIndex_BN_Mean).shape();
OP_REQUIRES(context, fuse_bn_shape.dims() == 1,
errors::InvalidArgument("FusedBatchNorm must be 1D, not: ",
fuse_bn_shape.DebugString()));
// Note - MKL-DNN expects {1, C, 1, 1} for binary post-op even for NHWC
fuse_bn_dims = {1, fuse_bn_shape.dim_size(0), 1, 1};
}
MklConvFwdParams convFwdDims(
src_dims, filter_dims, fuse_biasadd_ ? bias_dims : NONE_DIMS,
dst_dims_mkl_order, strides, dilations, padding_left, padding_right,
fuse_bn_dims, tf_fmt, native_format);
// TODO(intel-tf): Extend the basic parameters for data types and fusions
this->ExtendConvFwdParams(context, convFwdDims);
conv_fwd =
MklConvFwdPrimitiveFactory<Tinput, Tfilter, Tbias, Ttemp_output>::Get(
convFwdDims, do_not_cache);
// Allocate output tensors `dst_tensor` and `filter_out_tensor`
MklDnnShape output_mkl_shape;
std::shared_ptr<ConvFwdPd> conv_fwd_pd = conv_fwd->GetPrimitiveDesc();
AllocateOutputTensor(context, *conv_fwd_pd, dst_dims_mkl_order, tf_fmt,
&output_mkl_shape, &dst_tensor);
Tensor* filter_out_tensor = nullptr;
if (emit_filter_output) {
AllocateFilterOutputTensor(context, *conv_fwd_pd,
TFShapeToMklDnnDims(filter_tf_shape),
&filter_out_tensor);
}
Ttemp_output* dst_data =
reinterpret_cast<Ttemp_output*>(dst_tensor->flat<Toutput>().data());
// Check whether src and filter need to be reordered.
Tinput* src_data = nullptr;
if (src_md != conv_fwd_pd->src_desc()) {
src.SetUsrMem(src_md, &src_tensor);
src.CheckReorderToOpMem(conv_fwd_pd->src_desc(), cpu_engine_, context);
src_data = static_cast<Tinput*>(src.GetOpMem().get_data_handle());
} else {
src_data = static_cast<Tinput*>(
const_cast<Tinput*>(src_tensor.flat<Tinput>().data()));
}
Tfilter* filter_data = nullptr;
if (filter_md != conv_fwd_pd->weights_desc()) {
bool is_filter_cached = false;
// If filter is a constant, we can avoid the conversion of filter from
// Tensorflow format to MKL format by caching the filter when it is
// converted for the first time. This cached filter can then be reused
// in subsequent iterations.
if (is_filter_const_) {
if (IsFilterCacheEmpty(context)) {
// Cache filter if it is not already cached.
CacheFilter(context, conv_fwd_pd, filter_data, filter_tensor,
filter, filter_md, filter_mkl_shape);
}
filter_data = GetCachedFilter(context, conv_fwd_pd->weights_desc());
is_filter_cached = (filter_data != nullptr);
}
if (!is_filter_cached) {
filter.SetUsrMem(filter_md, &filter_tensor);
if (filter_out_tensor == nullptr) {
filter.CheckReorderToOpMem(conv_fwd_pd->weights_desc(), cpu_engine_,
context);
} else {
filter.CheckReorderToOpMem(
conv_fwd_pd->weights_desc(),
filter.GetTensorBuffer(filter_out_tensor), cpu_engine_,
context);
}
filter_data =
static_cast<Tfilter*>(filter.GetOpMem().get_data_handle());
}
} else {
filter_data = static_cast<Tfilter*>(
const_cast<Tfilter*>(filter_tensor.flat<Tfilter>().data()));
}
UserScratchPad<unsigned char> scratch_pad;
scratch_pad.AllocateSPTensor(conv_fwd, context);
// Execute convolution
std::shared_ptr<stream> fwd_cpu_stream;
MklDnnThreadPool eigen_tp(context);
fwd_cpu_stream.reset(CreateStream(&eigen_tp, conv_fwd->GetEngine()));
if (fuse_biasadd_) {
const Tensor& bias_tensor = MklGetInput(context, kInputIndex_Bias);
Tbias* bias_data =
this->GetBiasHandle(context, conv_fwd_pd, bias_tensor);
conv_fwd->Execute(src_data, filter_data, bias_data, dst_data,
fwd_cpu_stream, scratch_pad.Get());
} else if (fuse_bn_) {
const Tensor& bn_scale_tensor =
MklGetInput(context, kInputIndex_BN_Scale);
Tinput* bn_scale_data = static_cast<Tinput*>(
const_cast<Tinput*>(bn_scale_tensor.flat<Tinput>().data()));
const Tensor& bn_mean_tensor =
MklGetInput(context, kInputIndex_BN_Mean);
Tinput* bn_mean_data = static_cast<Tinput*>(
const_cast<Tinput*>(bn_mean_tensor.flat<Tinput>().data()));
const Tensor& bn_offset_tensor =
MklGetInput(context, kInputIndex_BN_Offset);
Tinput* bn_offset_data = static_cast<Tinput*>(
const_cast<Tinput*>(bn_offset_tensor.flat<Tinput>().data()));
Tensor bn_rsqrt_tensor;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<Tinput>::v(),
fuse_bn_shape, &bn_rsqrt_tensor));
Tinput* bn_rsqrt_data = static_cast<Tinput*>(
const_cast<Tinput*>(bn_rsqrt_tensor.flat<Tinput>().data()));
this->ComputeBNScale(context, epsilon_, kInputIndex_BN_Variance,
bn_rsqrt_data);
conv_fwd->Execute(src_data, filter_data, nullptr, dst_data,
bn_scale_data, bn_mean_data, bn_offset_data,
bn_rsqrt_data, fwd_cpu_stream, scratch_pad.Get());
} else {
conv_fwd->Execute(src_data, filter_data, dst_data, fwd_cpu_stream,
scratch_pad.Get());
}
// Delete primitive since it is not cached.
if (do_not_cache) delete conv_fwd;
} catch (dnnl::error& e) {
string error_msg = tensorflow::strings::StrCat(
"Status: ", e.status, ", message: ", string(e.message), ", in file ",
__FILE__, ":", __LINE__);
OP_REQUIRES_OK(
context,
errors::Aborted("Operation received an exception:", error_msg));
}
}
void PadWithConvFusion(OpKernelContext* context, memory::dims& padding_left,
memory::dims& padding_right, bool pad_attr_enabled,
string data_format_str_) {
Tpadding* paddings = nullptr;
if (pad_attr_enabled) {
paddings = padding_list_.data();
} else {
const Tensor& paddings_tf = MklGetInput(context, input_index_pad_);
OP_REQUIRES(context, paddings_tf.dims() == 2,
errors::InvalidArgument("paddings must be 2-dimensional: ",
paddings_tf.shape().DebugString()));
// Flatten tensor to get individual paddings.
paddings = static_cast<Tpadding*>(
const_cast<Tpadding*>(paddings_tf.flat<Tpadding>().data()));
}
// If the data format is NHWC, indices 0, 1, 6 and 7 of paddings(_tf)
// will be zero.
// Example:
// paddings_tf = [ [0, 0] [1, 2] [3, 4] [0, 0] ],
// flat method = row-major, then:
// paddings = {0, 0, 1, 2, 3, 4, 0, 0}.
// Hence, the values are: top = 1, bottom = 2, left = 3, right = 4.
//
// Similarly, if the data format is NCHW, indices 0, 1, 2 and 3 of
// paddings(_tf) will be zero.
// i.e. for the above example, paddings = {0, 0, 0, 0, 1, 2, 3, 4}.
int64 pad_top = 0, pad_left = 0, pad_front = 0;
int64 pad_bottom = 0, pad_right = 0, pad_back = 0;
if (data_format_str_ == "NHWC") {
pad_top = paddings[2];
pad_bottom = paddings[3];
pad_left = paddings[4];
pad_right = paddings[5];
} else if (data_format_str_ == "NCHW") {
pad_top = paddings[4];
pad_bottom = paddings[5];
pad_left = paddings[6];
pad_right = paddings[7];
} else if (data_format_str_ == "NDHWC") {
pad_front = paddings[2];
pad_back = paddings[3];
pad_top = paddings[4];
pad_bottom = paddings[5];
pad_left = paddings[6];
pad_right = paddings[7];
} else if (data_format_str_ == "NCDHW") {
pad_front = paddings[4];
pad_back = paddings[5];
pad_top = paddings[6];
pad_bottom = paddings[7];
pad_left = paddings[8];
pad_right = paddings[9];
}
// Create padding arrays for MKL-DNN convolutions.
// MKL-DNN uses asymmetric padding.
if (data_format_str_ == "NHWC" || data_format_str_ == "NCHW") {
padding_left = {static_cast<int>(pad_top), static_cast<int>(pad_left)};
padding_right = {static_cast<int>(pad_bottom),
static_cast<int>(pad_right)};
} else if (data_format_str_ == "NDHWC" || data_format_str_ == "NCDHW") {