-
Notifications
You must be signed in to change notification settings - Fork 74k
/
depthwise_conv_op_gpu.h
1758 lines (1596 loc) · 75.7 KB
/
depthwise_conv_op_gpu.h
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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_KERNELS_DEPTHWISE_CONV_OP_GPU_H_
#define TENSORFLOW_CORE_KERNELS_DEPTHWISE_CONV_OP_GPU_H_
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/kernels/depthwise_conv_op.h"
#include "tensorflow/core/kernels/gpu_prim.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/determinism.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow/core/util/tensor_format.h"
#if defined(_MSC_VER) && !defined(__clang__)
#define UNROLL
#define NOUNROLL
#else
#define UNROLL _Pragma("unroll")
#define NOUNROLL _Pragma("nounroll")
#endif
namespace tensorflow {
namespace detail {
template <typename T>
struct PseudoHalfType {
using Type = T;
};
template <>
struct PseudoHalfType<Eigen::half> {
using Type = float;
};
template <>
struct PseudoHalfType<Eigen::bfloat16> {
using Type = float;
};
} // namespace detail
using Eigen::GpuDevice;
// Returns whether depthwise convolution forward or backward input pass can be
// performed using the faster ('Small') variant of the kernel.
inline EIGEN_DEVICE_FUNC bool CanLaunchDepthwiseConv2dGPUSmall(
const DepthwiseArgs& args) {
return args.depth_multiplier == 1 && args.stride == 1 && args.in_rows <= 32 &&
args.in_cols <= 32 && args.in_rows == args.out_rows &&
args.in_cols == args.out_cols && args.pad_rows >= 0 &&
args.pad_rows < args.filter_rows && args.pad_cols >= 0 &&
args.pad_cols < args.filter_cols &&
args.filter_rows * args.filter_cols <=
(args.in_rows + 1) / 2 * args.in_cols;
}
// Returns whether depthwise convolution backward filter pass can be performed
// using the faster ('Small') variant of the kernel.
inline EIGEN_DEVICE_FUNC bool CanLaunchDepthwiseConv2dBackpropFilterGPUSmall(
const DepthwiseArgs& args, const int block_height) {
return args.depth_multiplier == 1 && args.stride == 1 && args.in_rows <= 32 &&
args.in_cols <= 32 && args.in_rows == args.out_rows &&
args.in_cols == args.out_cols && args.pad_rows >= 0 &&
args.pad_rows < args.filter_rows && args.pad_cols >= 0 &&
args.pad_cols < args.filter_cols && block_height <= args.in_rows &&
args.filter_rows * args.filter_cols <= args.in_cols * block_height;
}
// The DepthwiseConv2dGPUKernels perform either forward or backprop input
// convolution depending on a template argument of this enum.
enum DepthwiseConv2dDirection { DIRECTION_FORWARD, DIRECTION_BACKWARD };
// A GPU kernel to compute the depthwise convolution forward pass
// in NHWC format.
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight,
int kKnownDepthMultiplier>
__global__ void __launch_bounds__(1024, 2)
DepthwiseConv2dGPUKernelNHWC(const DepthwiseArgs args,
const T* __restrict__ input,
const T* __restrict__ filter,
T* __restrict__ output, int num_outputs) {
typedef typename detail::PseudoHalfType<T>::Type S;
const int in_height = args.in_rows;
const int in_width = args.in_cols;
const int in_depth = args.in_depth;
const int filter_height =
kKnownFilterHeight < 0 ? args.filter_rows : kKnownFilterHeight;
const int filter_width =
kKnownFilterWidth < 0 ? args.filter_cols : kKnownFilterWidth;
const int depth_multiplier =
kKnownDepthMultiplier < 0 ? args.depth_multiplier : kKnownDepthMultiplier;
const int stride = args.stride;
const int pad_height = args.pad_rows;
const int pad_width = args.pad_cols;
const int out_height = args.out_rows;
const int out_width = args.out_cols;
const int out_depth = args.out_depth;
GPU_1D_KERNEL_LOOP(thread_id, num_outputs) {
// Compute the indexes of this thread in the output.
const int out_channel = thread_id % out_depth;
const int out_col = (thread_id / out_depth) % out_width;
const int out_row = (thread_id / out_depth / out_width) % out_height;
const int batch = thread_id / out_depth / out_width / out_height;
// Compute the input depth and the index of depth multiplier.
const int in_channel = out_channel / depth_multiplier;
const int multiplier = out_channel % depth_multiplier;
// Decide if all input is valid, if yes, we can skip the boundary checks
// for each input.
const int input_row_start = out_row * stride - pad_height;
const int input_col_start = out_col * stride - pad_width;
const int input_row_end = input_row_start + filter_height;
const int input_col_end = input_col_start + filter_width;
S sum = static_cast<S>(0);
const int input_offset_temp = in_height * batch;
if (input_row_start >= 0 && input_col_start >= 0 &&
input_row_end < in_height && input_col_end < in_width) {
UNROLL for (int filter_row = 0; filter_row < filter_height;
++filter_row) {
const int in_row = input_row_start + filter_row;
const int filter_offset_temp = filter_width * filter_row;
UNROLL for (int filter_col = 0; filter_col < filter_width;
++filter_col) {
const int in_col = input_col_start + filter_col;
const int input_offset =
in_channel +
in_depth * (in_col + in_width * (in_row + input_offset_temp));
const int filter_offset =
multiplier +
depth_multiplier *
(in_channel + in_depth * (filter_col + filter_offset_temp));
sum += static_cast<S>(ldg(input + input_offset)) *
static_cast<S>(ldg(filter + filter_offset));
}
}
} else {
UNROLL for (int filter_row = 0; filter_row < filter_height;
++filter_row) {
const int in_row = input_row_start + filter_row;
const int filter_offset_temp = filter_width * filter_row;
UNROLL for (int filter_col = 0; filter_col < filter_width;
++filter_col) {
const int in_col = input_col_start + filter_col;
if (in_row >= 0 && in_row < in_height && in_col >= 0 &&
in_col < in_width) {
const int in_col = input_col_start + filter_col;
const int input_offset =
in_channel +
in_depth * (in_col + in_width * (in_row + input_offset_temp));
const int filter_offset =
multiplier +
depth_multiplier *
(in_channel + in_depth * (filter_col + filter_offset_temp));
sum += static_cast<S>(ldg(input + input_offset)) *
static_cast<S>(ldg(filter + filter_offset));
}
}
}
}
output[thread_id] = static_cast<T>(sum);
}
}
// CUDA kernel to compute the depthwise convolution forward pass in NHWC format,
// tailored for small images up to 32x32. Stride and depth multiplier must be 1.
// Padding must be 'SAME', which allows to reuse the index computation. Only
// use this kernel if CanLaunchDepthwiseConv2dGPUSmall(args) returns true.
// Tiles of the input and filter tensors are loaded into shared memory before
// performing the convolution. Each thread handles two elements per iteration,
// one each in the lower and upper half of a tile.
// Backprop input direction is the same as forward direction with the filter
// rotated by 180°.
// T is the tensors' data type. S is the math type the kernel uses. This is the
// same as T for all cases but pseudo half (which has T=Eigen::half, S=float).
template <typename T, DepthwiseConv2dDirection kDirection,
int kKnownFilterWidth, int kKnownFilterHeight, int kBlockDepth,
bool kKnownEvenHeight>
__global__ __launch_bounds__(1024, 2) void DepthwiseConv2dGPUKernelNHWCSmall(
const DepthwiseArgs args, const T* __restrict__ input,
const T* __restrict__ filter, T* __restrict__ output) {
typedef typename detail::PseudoHalfType<T>::Type S;
assert(CanLaunchDepthwiseConv2dGPUSmall(args));
// Holds block plus halo and filter data for blockDim.x depths.
GPU_DYNAMIC_SHARED_MEM_DECL(8, unsigned char, shared_memory);
static_assert(sizeof(S) <= 8, "Insufficient alignment detected");
S* const shared_data = reinterpret_cast<S*>(shared_memory);
const int num_batches = args.batch;
const int in_height = args.in_rows;
const int in_width = args.in_cols;
const int in_depth = args.in_depth;
const int filter_height =
kKnownFilterHeight < 0 ? args.filter_rows : kKnownFilterHeight;
const int filter_width =
kKnownFilterWidth < 0 ? args.filter_cols : kKnownFilterWidth;
const int pad_height = args.pad_rows;
const int pad_width = args.pad_cols;
assert(blockDim.x == kBlockDepth);
assert(blockDim.y == args.in_cols);
const int block_height = blockDim.z;
// These values are the same for all threads and could
// be precomputed on the CPU.
const int block_size = block_height * in_width * kBlockDepth;
const int in_row_size = in_width * in_depth;
const int in_size = in_height * in_row_size;
const int in_increment = (in_width - 1) * kBlockDepth;
const int filter_pixels = filter_height * filter_width;
const int tile_width = in_width + filter_width - 1;
const int even_height = kKnownEvenHeight || (1 & ~in_height);
const int tile_height = in_height + filter_height - even_height;
const int tile_row_size = tile_width * kBlockDepth;
const int tile_size = tile_height * tile_row_size;
const int tile_offset = block_height * tile_row_size;
const int pad_offset = pad_height * tile_width + pad_width;
const int batch_blocks = (in_depth + kBlockDepth - 1) / kBlockDepth;
const int in_blocks = batch_blocks * num_batches;
const int tensor_offset =
kKnownEvenHeight ? in_size / 2 : block_height * in_row_size;
const int thread_depth = threadIdx.x;
const int thread_col = threadIdx.y;
const int thread_row = threadIdx.z;
// Position in block.
const int thread_pix = thread_row * in_width + thread_col;
const int thread_idx = thread_pix * kBlockDepth + thread_depth;
// Initialize tile, in particular the padding.
for (int i = thread_idx; i < tile_size; i += block_size) {
shared_data[i] = S();
}
__syncthreads();
// Position in tensors.
const int tensor_idx = thread_pix * in_depth + thread_depth;
// Position in (padded) shared memory.
const int data_pix = thread_row * tile_width + thread_col;
const int data_idx = data_pix * kBlockDepth + thread_depth;
// Position in shared memory, offset by pad_height / pad_width.
const int tile_pix = data_pix + pad_offset;
const int tile_idx = tile_pix * kBlockDepth + thread_depth;
const int max_channel = in_depth - thread_depth;
const int filter_write_offset =
thread_pix < filter_pixels ? tile_size + thread_idx : 0;
const int filter_read_offset =
tile_size + thread_depth +
(kDirection == DIRECTION_FORWARD ? 0 : filter_pixels * kBlockDepth);
const bool skip_second =
!kKnownEvenHeight && thread_row + (in_height & 1) == block_height;
for (int b = blockIdx.x; b < in_blocks; b += gridDim.x) {
const int batch = b / batch_blocks;
const int block = b - batch * batch_blocks;
const int start_channel = block * kBlockDepth;
const int filter_offset = tensor_idx + start_channel;
const int inout_offset = batch * in_size + filter_offset;
const bool channel_in_range = start_channel < max_channel;
if (channel_in_range) {
const T* const in_ptr = inout_offset + input;
S* const tile_ptr = tile_idx + shared_data;
tile_ptr[0] = static_cast<S>(ldg(in_ptr));
if (!skip_second) {
tile_ptr[tile_offset] = static_cast<S>(ldg(tensor_offset + in_ptr));
}
if (filter_write_offset != 0) {
shared_data[filter_write_offset] =
static_cast<S>(ldg(filter_offset + filter));
}
}
// Note: the condition to reach this is uniform across the entire block.
__syncthreads();
if (channel_in_range) {
S sum1 = S();
S sum2 = S();
int shared_offset = data_idx;
const S* filter_ptr = filter_read_offset + shared_data;
UNROLL for (int r = 0; r < filter_height; ++r) {
UNROLL for (int c = 0; c < filter_width; ++c) {
if (kDirection == DIRECTION_BACKWARD) {
filter_ptr -= kBlockDepth;
}
const S filter_value = *filter_ptr;
const S* const tile_ptr = shared_offset + shared_data;
sum1 += filter_value * tile_ptr[0];
sum2 += filter_value * tile_ptr[tile_offset];
shared_offset += kBlockDepth;
if (kDirection == DIRECTION_FORWARD) {
filter_ptr += kBlockDepth;
}
}
shared_offset += in_increment;
}
T* const out_ptr = inout_offset + output;
out_ptr[0] = static_cast<T>(sum1);
if (!skip_second) {
out_ptr[tensor_offset] = static_cast<T>(sum2);
}
}
// Note: the condition to reach this is uniform across the entire block.
__syncthreads();
}
}
// A GPU kernel to compute the depthwise convolution forward pass
// in NCHW format.
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight,
int kKnownDepthMultiplier>
__global__ void __launch_bounds__(1024, 2)
DepthwiseConv2dGPUKernelNCHW(const DepthwiseArgs args,
const T* __restrict__ input,
const T* __restrict__ filter,
T* __restrict__ output, int num_outputs) {
typedef typename detail::PseudoHalfType<T>::Type S;
const int in_height = args.in_rows;
const int in_width = args.in_cols;
const int in_depth = args.in_depth;
const int filter_height =
kKnownFilterHeight < 0 ? args.filter_rows : kKnownFilterHeight;
const int filter_width =
kKnownFilterWidth < 0 ? args.filter_cols : kKnownFilterWidth;
const FastDividerUint32 depth_multiplier =
kKnownDepthMultiplier < 0 ? args.depth_multiplier : kKnownDepthMultiplier;
const int stride = args.stride;
const int pad_height = args.pad_rows;
const int pad_width = args.pad_cols;
const int out_width = args.out_cols;
const FastDividerUint32 out_height = args.out_rows;
const FastDividerUint32 out_depth = args.out_depth;
GPU_1D_KERNEL_LOOP(thread_id, num_outputs) {
// Compute the indexes of this thread in the output.
//
// We want coalesced reads so we make sure that each warp reads
// a contiguous chunk of memory.
//
// THIS IS PROBABLY WRONG, we are not doing coalesced reads
// into the input, because of the depth multiplier division...
const int out_col = thread_id % out_width;
const int out_row = (thread_id / out_width) % out_height;
const int out_channel = (thread_id / out_width / out_height) % out_depth;
const int batch = thread_id / out_width / out_height / out_depth;
// Compute the input depth and the index of depth multiplier
// based off the output depth index that this thread is
// computing n.
const int in_channel = out_channel / depth_multiplier;
const int multiplier = out_channel % depth_multiplier;
// Data is stored in the following format (let's assume we
// flatten the height and width into one contiguous dimension
// called "P".
//
// B1C1P1 B1C1P2 ..... B1C2P1 B1C2P2 ....
// B2C1P1 B2C1P2 ..... B2C2P1 B2C2P2 ....
//
// Each row contains in_depth * in_height * in_width values
// for each sample in the batch.
//
// We can further flatten it into:
//
// B1C1P1 B1C1P2 .....
// B1C2P1 B1C2P2 ....
// B2C1P1 B2C1P2 .....
// B2C2P1 B2C2P2 ....
//
// where each row is a contiguous array of all of the spatial
// pixels for a given batch and input depth. The following
// loop unrolls across the filter dimensions for a given thread,
// indexing into the filter value and the corresponding input
// patch.
//
// We can compute the index into the patch once right here.
const int input_offset_temp =
(batch * in_depth + in_channel) * (in_height * in_width);
// Finally, we can iterate over the spatial dimensions and perform the
// convolution, writing into the output at the end.
//
// We perform an additional optimization, where we can determine
// whether the patch fits within the image indices statically, and
// avoid boundary checking within the loop.
const int input_row_start = out_row * stride - pad_height;
const int input_col_start = out_col * stride - pad_width;
const int input_row_end = input_row_start + filter_height;
const int input_col_end = input_col_start + filter_width;
S sum = static_cast<S>(0);
if (input_row_start >= 0 && input_col_start >= 0 &&
input_row_end < in_height && input_col_end < in_width) {
// Loop that doesn't need to check for boundary conditions.
UNROLL for (int filter_row = 0; filter_row < filter_height;
++filter_row) {
const int in_row = input_row_start + filter_row;
const int filter_offset_temp = filter_width * filter_row;
UNROLL for (int filter_col = 0; filter_col < filter_width;
++filter_col) {
const int in_col = input_col_start + filter_col;
const int input_offset =
(input_offset_temp) + (in_row * in_width) + in_col;
const int filter_offset =
multiplier +
depth_multiplier *
(in_channel + in_depth * (filter_col + filter_offset_temp));
sum += static_cast<S>(ldg(input + input_offset)) *
static_cast<S>(ldg(filter + filter_offset));
}
}
} else {
// Loop that needs to check for boundary conditions.
UNROLL for (int filter_row = 0; filter_row < filter_height;
++filter_row) {
const int in_row = input_row_start + filter_row;
const int filter_offset_temp = filter_width * filter_row;
UNROLL for (int filter_col = 0; filter_col < filter_width;
++filter_col) {
const int in_col = input_col_start + filter_col;
// TODO(vrv): the in_row check can be done outside of this loop;
// benchmark both methods to determine the better decision.
if (in_row >= 0 && in_row < in_height && in_col >= 0 &&
in_col < in_width) {
const int in_col = input_col_start + filter_col;
// input_offset_temp indexes into the start of memory
// where the spatial data starts.
const int input_offset =
(input_offset_temp) + (in_row * in_width) + in_col;
const int filter_offset =
multiplier +
depth_multiplier *
(in_channel + in_depth * (filter_col + filter_offset_temp));
sum += static_cast<S>(ldg(input + input_offset)) *
static_cast<S>(ldg(filter + filter_offset));
}
}
}
}
output[thread_id] = static_cast<T>(sum);
}
}
// CUDA kernel to compute the depthwise convolution forward pass in NCHW format,
// tailored for small images up to 32x32. Stride and depth multiplier must be 1.
// Padding must be 'SAME', which allows to reuse the index computation. Only
// use this kernel if CanLaunchDepthwiseConv2dGPUSmall(args) returns true.
// Tiles of the input and filter tensors are loaded into shared memory before
// performing the convolution. Each thread handles two elements per iteration,
// one each in the lower and upper half of a tile.
// Backprop input direction is the same as forward direction with the filter
// rotated by 180°.
// T is the tensors' data type. S is the math type the kernel uses. This is the
// same as T for all cases but pseudo half (which has T=Eigen::half, S=float).
template <typename T, DepthwiseConv2dDirection kDirection,
int kKnownFilterWidth, int kKnownFilterHeight, int kBlockDepth,
bool kKnownEvenHeight>
__global__ __launch_bounds__(1024, 2) void DepthwiseConv2dGPUKernelNCHWSmall(
const DepthwiseArgs args, const T* __restrict__ input,
const T* __restrict__ filter, T* __restrict__ output) {
typedef typename detail::PseudoHalfType<T>::Type S;
assert(CanLaunchDepthwiseConv2dGPUSmall(args));
// Holds block plus halo and filter data for blockDim.z depths.
GPU_DYNAMIC_SHARED_MEM_DECL(8, unsigned char, shared_memory);
static_assert(sizeof(S) <= 8, "Insufficient alignment detected");
S* const shared_data = reinterpret_cast<S*>(shared_memory);
const int num_batches = args.batch;
const int in_height = args.in_rows;
const int in_width = args.in_cols;
const int in_depth = args.in_depth;
const int filter_height =
kKnownFilterHeight < 0 ? args.filter_rows : kKnownFilterHeight;
const int filter_width =
kKnownFilterWidth < 0 ? args.filter_cols : kKnownFilterWidth;
const int pad_height = args.pad_rows;
const int pad_width = args.pad_cols;
// Fixed blockDim.z, tailored for maximum grid size for images of size 16x16.
assert(blockDim.x == args.in_cols);
assert(blockDim.z == kBlockDepth);
const int block_height = blockDim.y;
// These values are the same for all threads and could
// be precomputed on the CPU.
const int block_pixels = in_width * block_height;
const int block_size = block_pixels * kBlockDepth;
const int in_pixels = in_width * in_height;
const int in_increment = in_width - 1;
const int filter_pixels = filter_height * filter_width;
const int tile_width = in_width + filter_width - 1;
const int even_height = kKnownEvenHeight || (1 & ~in_height);
const int tile_height = in_height + filter_height - even_height;
const int tile_pixels = tile_width * tile_height;
const int tile_size = tile_pixels * kBlockDepth;
const int tile_offset = block_height * tile_width;
const int pad_offset = pad_height * tile_width + pad_width;
const int in_total_depth = in_depth * num_batches;
const int in_blocks = (in_total_depth + kBlockDepth - 1) / kBlockDepth;
const int thread_col = threadIdx.x;
const int thread_row = threadIdx.y;
const int thread_depth = threadIdx.z;
// Position in block.
const int thread_pix = thread_row * in_width + thread_col;
const int thread_idx = thread_depth * block_pixels + thread_pix;
// Initialize tile, in particular the padding.
for (int i = thread_idx; i < tile_size; i += block_size) {
shared_data[i] = S();
}
__syncthreads();
// Position in tensors.
const int tensor_idx = thread_depth * in_pixels + thread_pix;
// Position in (padded) shared memory.
const int data_pix = thread_row * tile_width + thread_col;
const int data_idx = thread_depth * tile_pixels + data_pix;
// Position in shared memory, offset by pad_height / pad_width.
const int tile_idx = data_idx + pad_offset;
// Filter is always in HWCK format, irrespective of the input/output format.
const int filter_pix = thread_idx / kBlockDepth;
const int filter_channel = thread_idx % kBlockDepth;
const int filter_idx = filter_pix * in_depth;
const int max_channel = in_total_depth - thread_depth;
const int filter_write_offset =
filter_pix < filter_pixels ? tile_size + thread_idx : 0;
const int filter_read_offset =
tile_size + thread_depth +
(kDirection == DIRECTION_FORWARD ? 0 : filter_pixels * kBlockDepth);
const bool skip_second =
!kKnownEvenHeight && thread_row + (in_height & 1) == block_height;
for (int b = blockIdx.x; b < in_blocks; b += gridDim.x) {
const int channel = b * kBlockDepth;
const int inout_offset = channel * in_pixels + tensor_idx;
const bool channel_in_range = channel < max_channel;
if (channel_in_range) {
const T* const in_ptr = inout_offset + input;
S* const tile_ptr = tile_idx + shared_data;
tile_ptr[0] = static_cast<S>(ldg(in_ptr));
if (!skip_second) {
tile_ptr[tile_offset] = static_cast<S>(ldg(block_pixels + in_ptr));
}
}
if (filter_write_offset != 0) {
const int filter_offset =
filter_idx + (channel + filter_channel) % in_depth;
shared_data[filter_write_offset] =
static_cast<S>(ldg(filter_offset + filter));
}
// Note: the condition to reach this is uniform across the entire block.
__syncthreads();
if (channel_in_range) {
S sum1 = S();
S sum2 = S();
int shared_offset = data_idx;
const S* filter_ptr = filter_read_offset + shared_data;
UNROLL for (int r = 0; r < filter_height; ++r) {
UNROLL for (int c = 0; c < filter_width; ++c) {
if (kDirection == DIRECTION_BACKWARD) {
filter_ptr -= kBlockDepth;
}
const S filter_value = *filter_ptr;
const S* const tile_ptr = shared_offset + shared_data;
sum1 += filter_value * tile_ptr[0];
sum2 += filter_value * tile_ptr[tile_offset];
++shared_offset;
if (kDirection == DIRECTION_FORWARD) {
filter_ptr += kBlockDepth;
}
}
shared_offset += in_increment;
}
T* const out_ptr = inout_offset + output;
out_ptr[0] = static_cast<T>(sum1);
if (!skip_second) {
out_ptr[block_pixels] = static_cast<T>(sum2);
}
}
// Note: the condition to reach this is uniform across the entire block.
__syncthreads();
}
}
template <typename T, DepthwiseConv2dDirection kDirection,
int kKnownFilterWidth, int kKnownFilterHeight, int kBlockDepth,
bool kKnownEvenHeight>
Status LaunchDepthwiseConv2dGPUSmall(OpKernelContext* ctx,
const DepthwiseArgs& args, const T* input,
const T* filter, T* output,
TensorFormat data_format) {
typedef typename detail::PseudoHalfType<T>::Type S;
const int block_height = (args.in_rows + 1) / 2;
dim3 block_dim;
int block_count;
void (*kernel)(const DepthwiseArgs, const T*, const T*, T*);
switch (data_format) {
case FORMAT_NHWC:
block_dim = dim3(kBlockDepth, args.in_cols, block_height);
block_count =
args.batch * DivUp(args.out_depth, kBlockDepth) * kBlockDepth;
kernel =
DepthwiseConv2dGPUKernelNHWCSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, kBlockDepth,
kKnownEvenHeight>;
break;
case FORMAT_NCHW:
block_dim = dim3(args.in_cols, block_height, kBlockDepth);
block_count =
DivUp(args.batch * args.out_depth, kBlockDepth) * kBlockDepth;
kernel =
DepthwiseConv2dGPUKernelNCHWSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, kBlockDepth,
kKnownEvenHeight>;
break;
default:
return errors::InvalidArgument("FORMAT_", ToString(data_format),
" is not supported");
}
const int tile_width = args.in_cols + args.filter_cols - 1;
const int tile_height = block_height * 2 + args.filter_rows - 1;
const int tile_pixels = tile_height * tile_width;
const int filter_pixels = args.filter_rows * args.filter_cols;
const int shared_memory_size =
kBlockDepth * (tile_pixels + filter_pixels) * sizeof(S);
const int num_outputs = args.out_rows * args.out_cols * block_count;
auto device = ctx->eigen_gpu_device();
GpuLaunchConfig config = GetGpuLaunchConfigFixedBlockSize(
num_outputs, device, kernel, shared_memory_size,
block_dim.x * block_dim.y * block_dim.z);
TF_CHECK_OK(GpuLaunchKernel(kernel, config.block_count, block_dim,
shared_memory_size, device.stream(), args, input,
filter, output));
return OkStatus();
}
// Returns whether the context's GPU supports efficient fp16 math.
inline bool HasFastHalfMath(OpKernelContext* ctx) {
se::CudaComputeCapability compute_capability =
ctx->op_device_context()->stream()->GetCudaComputeCapability();
// GPUs before sm_53 don't support fp16 math, and sm_61's fp16 math is slow.
return compute_capability.IsAtLeast(5, 3) &&
compute_capability != se::CudaComputeCapability{6, 1};
}
template <typename T, DepthwiseConv2dDirection kDirection,
int kKnownFilterWidth, int kKnownFilterHeight, int kBlockDepth>
Status LaunchDepthwiseConv2dGPUSmall(OpKernelContext* ctx,
const DepthwiseArgs& args, const T* input,
const T* filter, T* output,
TensorFormat data_format) {
if (args.in_rows & 1) {
return LaunchDepthwiseConv2dGPUSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, kBlockDepth,
false>(ctx, args, input, filter,
output, data_format);
} else {
return LaunchDepthwiseConv2dGPUSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, kBlockDepth, true>(
ctx, args, input, filter, output, data_format);
}
}
template <typename T, DepthwiseConv2dDirection kDirection,
int kKnownFilterWidth, int kKnownFilterHeight>
Status LaunchDepthwiseConv2dGPUSmall(OpKernelContext* ctx,
const DepthwiseArgs& args, const T* input,
const T* filter, T* output,
TensorFormat data_format) {
// Maximize (power of two) kBlockDepth while keeping a block within 1024
// threads (2 pixels per thread).
const int block_pixels = (args.in_rows + 1) / 2 * args.in_cols;
if (block_pixels > 256) {
return LaunchDepthwiseConv2dGPUSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, 2>(
ctx, args, input, filter, output, data_format);
} else if (block_pixels > 128) {
return LaunchDepthwiseConv2dGPUSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, 4>(
ctx, args, input, filter, output, data_format);
} else {
return LaunchDepthwiseConv2dGPUSmall<T, kDirection, kKnownFilterWidth,
kKnownFilterHeight, 8>(
ctx, args, input, filter, output, data_format);
}
}
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight,
int kKnownDepthMultiplier>
Status LaunchDepthwiseConv2dGPU(OpKernelContext* ctx, const DepthwiseArgs& args,
const T* input, const T* filter, T* output,
TensorFormat data_format) {
void (*kernel)(const DepthwiseArgs, const T*, const T*, T*, int);
switch (data_format) {
case FORMAT_NHWC:
kernel =
DepthwiseConv2dGPUKernelNHWC<T, kKnownFilterWidth, kKnownFilterHeight,
kKnownDepthMultiplier>;
break;
case FORMAT_NCHW:
kernel =
DepthwiseConv2dGPUKernelNCHW<T, kKnownFilterWidth, kKnownFilterHeight,
kKnownDepthMultiplier>;
break;
default:
return errors::InvalidArgument("FORMAT_", ToString(data_format),
" is not supported");
}
const int num_outputs =
args.batch * args.out_rows * args.out_cols * args.out_depth;
auto device = ctx->eigen_gpu_device();
GpuLaunchConfig config =
GetGpuLaunchConfig(num_outputs, device, kernel, 0, 0);
// The compile-time constant version runs faster with a single block.
const int max_block_count = kKnownFilterWidth < 0 || kKnownFilterHeight < 0 ||
kKnownDepthMultiplier < 0
? std::numeric_limits<int>::max()
: device.getNumGpuMultiProcessors();
TF_CHECK_OK(GpuLaunchKernel(kernel,
std::min(max_block_count, config.block_count),
config.thread_per_block, 0, device.stream(), args,
input, filter, output, num_outputs));
return OkStatus();
}
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight>
Status LaunchDepthwiseConv2dGPU(OpKernelContext* ctx, const DepthwiseArgs& args,
const T* input, const T* filter, T* output,
TensorFormat data_format) {
if (args.depth_multiplier == 1) {
if (CanLaunchDepthwiseConv2dGPUSmall(args)) {
return LaunchDepthwiseConv2dGPUSmall<
T, DIRECTION_FORWARD, kKnownFilterWidth, kKnownFilterHeight>(
ctx, args, input, filter, output, data_format);
}
return LaunchDepthwiseConv2dGPU<T, kKnownFilterWidth, kKnownFilterHeight,
1>(ctx, args, input, filter, output,
data_format);
} else {
return LaunchDepthwiseConv2dGPU<T, kKnownFilterWidth, kKnownFilterHeight,
-1>(ctx, args, input, filter, output,
data_format);
}
}
// A simple launch pad to launch the GPU kernel for depthwise convolution.
template <typename T>
void LaunchDepthwiseConvOp<GpuDevice, T>::operator()(OpKernelContext* ctx,
const DepthwiseArgs& args,
const T* input,
const T* filter, T* output,
TensorFormat data_format) {
if (args.filter_rows == 3 && args.filter_cols == 3) {
OP_REQUIRES_OK(ctx, LaunchDepthwiseConv2dGPU<T, 3, 3>(
ctx, args, input, filter, output, data_format));
} else {
OP_REQUIRES_OK(ctx, LaunchDepthwiseConv2dGPU<T, -1, -1>(
ctx, args, input, filter, output, data_format));
}
}
// A GPU kernel to compute the depthwise convolution backprop w.r.t. input.
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight,
int kKnownDepthMultiplier>
__global__ void __launch_bounds__(640, 2)
DepthwiseConv2dBackpropInputGPUKernelNHWC(
const DepthwiseArgs args, const T* __restrict__ out_backprop,
const T* __restrict__ filter, T* __restrict__ in_backprop,
int num_in_backprop) {
const int in_height = args.in_rows;
const int in_width = args.in_cols;
const int in_depth = args.in_depth;
const int filter_height =
kKnownFilterHeight < 0 ? args.filter_rows : kKnownFilterHeight;
const int filter_width =
kKnownFilterWidth < 0 ? args.filter_cols : kKnownFilterWidth;
const int depth_multiplier =
kKnownDepthMultiplier < 0 ? args.depth_multiplier : kKnownDepthMultiplier;
const int stride = args.stride;
const int pad_height = args.pad_rows;
const int pad_width = args.pad_cols;
const int out_height = args.out_rows;
const int out_width = args.out_cols;
const int out_depth = args.out_depth;
GPU_1D_KERNEL_LOOP(thread_id, num_in_backprop) {
// Compute the indexes of this thread in the output.
const int in_channel = thread_id % in_depth;
const int in_col = (thread_id / in_depth) % in_width;
const int in_row = (thread_id / in_depth / in_width) % in_height;
const int batch = thread_id / in_depth / in_width / in_height;
T sum = static_cast<T>(0);
const int out_row_start =
tf_max<int>(0, (in_row - filter_height + pad_height + stride) / stride);
const int out_row_end =
tf_min(out_height - 1, (in_row + pad_height) / stride);
const int out_col_start =
tf_max(0, (in_col - filter_width + pad_width + stride) / stride);
const int out_col_end =
tf_min(out_width - 1, (in_col + pad_width) / stride);
NOUNROLL for (int out_row = out_row_start; out_row <= out_row_end;
++out_row) {
const int filter_row = in_row + pad_height - out_row * stride;
const int temp_out_backprop_offset =
out_depth * out_width * (out_row + out_height * batch);
const int temp_filter_offset = filter_width * filter_row;
NOUNROLL for (int out_col = out_col_start; out_col <= out_col_end;
++out_col) {
const int filter_col = in_col + pad_width - out_col * stride;
int filter_offset =
depth_multiplier *
(in_channel + in_depth * (filter_col + temp_filter_offset));
const int out_backprop_offset =
out_depth * out_col + temp_out_backprop_offset;
#pragma unroll 6
for (int i = 0; i < depth_multiplier; ++i) {
sum += ldg(out_backprop + out_backprop_offset +
in_channel * depth_multiplier + i) *
ldg(filter + filter_offset + i);
}
}
}
const int in_backprop_offset =
in_channel +
in_depth * (in_col + in_width * (in_row + in_height * batch));
in_backprop[in_backprop_offset] = sum;
}
}
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight,
int kKnownDepthMultiplier>
__global__ void __launch_bounds__(640, 2)
DepthwiseConv2dBackpropInputGPUKernelNCHW(
const DepthwiseArgs args, const T* __restrict__ out_backprop,
const T* __restrict__ filter, T* __restrict__ in_backprop,
int num_in_backprop) {
const FastDividerUint32 in_height = args.in_rows;
const FastDividerUint32 in_width = args.in_cols;
const FastDividerUint32 in_depth = args.in_depth;
const int filter_height =
kKnownFilterHeight < 0 ? args.filter_rows : kKnownFilterHeight;
const int filter_width =
kKnownFilterWidth < 0 ? args.filter_cols : kKnownFilterWidth;
const int depth_multiplier =
kKnownDepthMultiplier < 0 ? args.depth_multiplier : kKnownDepthMultiplier;
const int stride = args.stride;
const int pad_height = args.pad_rows;
const int pad_width = args.pad_cols;
const int out_height = args.out_rows;
const int out_width = args.out_cols;
const int out_depth = args.out_depth;
// TODO(vrv): Consider assigning threads to output and using
// atomics for accumulation, similar to the filter case.
GPU_1D_KERNEL_LOOP(thread_id, num_in_backprop) {
// Compute the indexes of this thread in the input.
const int in_col = thread_id % in_width;
const int in_row = (thread_id / in_width) % in_height;
const int in_channel = (thread_id / in_width / in_height) % in_depth;
const int batch = thread_id / in_depth / in_width / in_height;
T sum = static_cast<T>(0);
const int out_channel_start = in_channel * depth_multiplier;
const int out_channel_end = out_channel_start + depth_multiplier;
const int out_row_start =
tf_max<int>(0, (in_row - filter_height + pad_height + stride) / stride);
const int out_row_end =
tf_min<int>(out_height - 1, (in_row + pad_height) / stride);
const int out_col_start =
tf_max<int>(0, (in_col - filter_width + pad_width + stride) / stride);
const int out_col_end =
tf_min<int>(out_width - 1, (in_col + pad_width) / stride);
UNROLL for (int out_channel = out_channel_start;
out_channel < out_channel_end; ++out_channel) {
UNROLL for (int out_row = out_row_start; out_row <= out_row_end;
++out_row) {
const int filter_row = in_row + pad_height - out_row * stride;
const int filter_dm = out_channel - out_channel_start;
const int temp_filter_offset = filter_width * filter_row;
for (int out_col = out_col_start; out_col <= out_col_end; ++out_col) {
const int filter_col = in_col + pad_width - out_col * stride;
const int filter_offset =
filter_dm +
args.depth_multiplier *
(in_channel + in_depth * (filter_col + temp_filter_offset));
const int out_backprop_offset =
(batch * out_depth * out_height * out_width) +
(out_channel * out_height * out_width) + (out_row * out_width) +
(out_col);
sum += ldg(out_backprop + out_backprop_offset) *
ldg(filter + filter_offset);
}
}
}
const int in_backprop_offset = (batch * in_height * in_width * in_depth) +
(in_channel * in_height * in_width) +
(in_row * in_width) + (in_col);
in_backprop[in_backprop_offset] = sum;
}
}
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight,
int kKnownDepthMultiplier>
Status LaunchDepthwiseConv2dBackpropInputGPU(OpKernelContext* ctx,
const DepthwiseArgs& args,
const T* out_backprop,
const T* filter, T* in_backprop,
TensorFormat data_format) {
void (*kernel)(const DepthwiseArgs, const T*, const T*, T*, int);
switch (data_format) {
case FORMAT_NHWC:
kernel = DepthwiseConv2dBackpropInputGPUKernelNHWC<
T, kKnownFilterWidth, kKnownFilterHeight, kKnownDepthMultiplier>;
break;
case FORMAT_NCHW:
kernel = DepthwiseConv2dBackpropInputGPUKernelNCHW<
T, kKnownFilterWidth, kKnownFilterHeight, kKnownDepthMultiplier>;
break;
default:
return errors::InvalidArgument("FORMAT_", ToString(data_format),
" is not supported");
}
const int num_in_backprop =
args.batch * args.in_rows * args.in_cols * args.in_depth;
auto device = ctx->eigen_gpu_device();
int launch_bounds_value = 640;
GpuLaunchConfig config = GetGpuLaunchConfig(num_in_backprop, device, kernel,
0, launch_bounds_value);
TF_CHECK_OK(GpuLaunchKernel(
kernel, config.block_count, config.thread_per_block, 0, device.stream(),
args, out_backprop, filter, in_backprop, num_in_backprop));
return OkStatus();
}
template <typename T, int kKnownFilterWidth, int kKnownFilterHeight>
Status LaunchDepthwiseConv2dBackpropInputGPU(OpKernelContext* ctx,
const DepthwiseArgs& args,
const T* out_backprop,
const T* filter, T* in_backprop,
TensorFormat data_format) {
if (args.depth_multiplier == 1) {
// This kernel doesn't currently work in all cases so it is disabled.
// TODO(b/150988950): Fix and reenable this kernel.
if (/* CanLaunchDepthwiseConv2dGPUSmall(args) */ false) {
return LaunchDepthwiseConv2dGPUSmall<
T, DIRECTION_BACKWARD, kKnownFilterWidth, kKnownFilterHeight>(
ctx, args, out_backprop, filter, in_backprop, data_format);
}