forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconv_transpose_op_mobile_impl.h
701 lines (587 loc) · 19.2 KB
/
conv_transpose_op_mobile_impl.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
// conv_transpose_op_impl.h is the templated implementation of the
// conv_transpose_op.h file.
#ifndef CAFFE2_OPERATORS_CONV_TRANSPOSE_MOBILE_OP_IMPL_H_
#define CAFFE2_OPERATORS_CONV_TRANSPOSE_MOBILE_OP_IMPL_H_
#include "caffe2/core/common.h"
#ifdef C10_MOBILE
#include "caffe2/core/logging.h"
#include "caffe2/operators/conv_op_shared.h"
#include "caffe2/operators/conv_transpose_op_mobile.h"
#include "caffe2/utils/cpu_neon.h"
#include "caffe2/utils/eigen_utils.h"
#include "caffe2/utils/fixed_divisor.h"
#include "caffe2/utils/math.h"
#include "caffe2/utils/math/utils.h"
C10_DECLARE_bool(caffe2_force_shared_col_buffer);
namespace caffe2 {
template <typename T, typename Context>
void runTileContiguous(
int tileId,
int N,
int M,
int H,
int W,
int outputH,
int outputW,
int C,
int kernelH,
int kernelW,
int strideH,
int strideW,
int padT,
const T* filterData,
const T* Xdata,
T* colBufferData,
T* Ydata,
Context* context) {
// The tile size is exactly the length of a single row
int tileSize = W;
auto kernelDataSize = C * kernelH * kernelW;
auto currentTileStart = tileSize * tileId;
// gemm tile
math::GemmEx<T, Context>(
CblasTrans,
CblasNoTrans,
kernelDataSize,
tileSize,
M,
1,
filterData,
kernelDataSize,
Xdata + currentTileStart,
H * W,
0,
colBufferData,
tileSize,
context);
// col2im tile
// We assume that there is no padding in the columns (padL and padR
// == 0).
// FIXME: it is actually possible for us to handle padding, figure
// out how to adjust the bounds
// We write into Y in a de-interleaved fashion; in other words,
// every column (mod strideW) == 0 together in one block,
// every column (mod strideW) == 1 in another,
// ... and so on.
int colBlockSize = (W + kernelW / strideW);
int numColBlocks = strideW;
for (const auto c : c10::irange(kernelDataSize)) {
int w_offset = c % kernelW;
int h_offset = (c / kernelW) % kernelH;
int c_im = c / kernelH / kernelW;
// Each row is a separate tile that we handle. First determine the
// row into which we are writing the output.
// We can properly handle padding for the rows.
int rowY = tileId * strideH - padT + h_offset;
// If this row is out of bounds, then skip it
if (!math::utils::IsAGeZeroAndALtB(rowY, outputH)) {
continue;
}
// FIXME: we don't actually handle a dynamic padL > 0
constexpr int kPadL = 0;
int colOffsetStart = -kPadL + w_offset;
int colBlockY = colOffsetStart % strideW;
// However, within a block we may not start writing at offset
// 0. The offset at which we begin writing is determined by
// colOffsetStart
int colWithinBlockOffsetY = colOffsetStart / strideW;
// So, this is where we begin reading/writing in Y
int colY = colBlockY * colBlockSize + colWithinBlockOffsetY;
// This is the complete offset into Y from the start
// Each row has strideW blocks of size colBlockSize
int offsetY = rowY * colBlockSize * numColBlocks + colY;
T* colBufferPointer = colBufferData + c * tileSize;
T* yPointer =
Ydata + c_im * outputH * (colBlockSize * numColBlocks) + offsetY;
int b = 0;
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
// We vectorize the loop within the row
{
constexpr int kUnroll = (sizeof(float32x4_t) / sizeof(float)) * 4;
int limit = (tileSize / kUnroll) * kUnroll;
for (; b < limit; b += kUnroll) {
float32x4_t cb0 = vld1q_f32(colBufferPointer + 0);
float32x4_t cb1 = vld1q_f32(colBufferPointer + 4);
float32x4_t cb2 = vld1q_f32(colBufferPointer + 8);
float32x4_t cb3 = vld1q_f32(colBufferPointer + 12);
float32x4_t y0 = vld1q_f32(yPointer + 0);
float32x4_t y1 = vld1q_f32(yPointer + 4);
float32x4_t y2 = vld1q_f32(yPointer + 8);
float32x4_t y3 = vld1q_f32(yPointer + 12);
y0 = vaddq_f32(y0, cb0);
y1 = vaddq_f32(y1, cb1);
y2 = vaddq_f32(y2, cb2);
y3 = vaddq_f32(y3, cb3);
vst1q_f32(yPointer + 0, y0);
vst1q_f32(yPointer + 4, y1);
vst1q_f32(yPointer + 8, y2);
vst1q_f32(yPointer + 12, y3);
colBufferPointer += kUnroll;
yPointer += kUnroll;
}
}
{
constexpr int kUnroll = (sizeof(float32x4_t) / sizeof(float));
int limit = (tileSize / kUnroll) * kUnroll;
for (; b < limit; b += kUnroll) {
float32x4_t cb0 = vld1q_f32(colBufferPointer);
float32x4_t y0 = vld1q_f32(yPointer);
y0 = vaddq_f32(y0, cb0);
vst1q_f32(yPointer, y0);
colBufferPointer += kUnroll;
yPointer += kUnroll;
}
}
#endif
// Handle un-vectorizable epilogue
for (; b < tileSize; ++b) {
*yPointer += *colBufferPointer;
++yPointer;
++colBufferPointer;
}
}
}
template <typename T, int N>
struct StoreInterleaved {};
template <>
struct StoreInterleaved<float, 1> {
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
inline static void store(float* p, float32x4_t v[1]) {
vst1q_f32(p, v[0]);
}
#endif
inline static void store(float* p, float v[1]) {
p[0] = v[0];
}
};
template <>
struct StoreInterleaved<float, 2> {
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
inline static void store(float* p, float32x4_t v[2]) {
float32x4x2_t x = {{v[0], v[1]}};
vst2q_f32(p, x);
}
#endif
inline static void store(float* p, float v[2]) {
p[0] = v[0];
p[1] = v[1];
}
};
template <>
struct StoreInterleaved<float, 3> {
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
inline static void store(float* p, float32x4_t v[3]) {
float32x4x3_t x = {{v[0], v[1], v[2]}};
vst3q_f32(p, x);
}
#endif
inline static void store(float* p, float v[3]) {
p[0] = v[0];
p[1] = v[1];
p[2] = v[2];
}
};
template <>
struct StoreInterleaved<float, 4> {
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
inline static void store(float* p, float32x4_t v[4]) {
float32x4x4_t x = {{v[0], v[1], v[2], v[3]}};
vst4q_f32(p, x);
}
#endif
inline static void store(float* p, float v[4]) {
p[0] = v[0];
p[1] = v[1];
p[2] = v[2];
p[3] = v[3];
}
};
template <int kStrideW>
void reinterleaveRows(
const float* src,
const float* bias,
int c,
int h,
float* dst,
int outputC,
int outputH,
int outputW,
int inputW,
int kernelW,
int strideW,
int adjH) {
// Each row in src is of the form:
// [w mod strideW == 0 elements]...[w mod strideW == strideW - 1
// elements]
// We need to re-interleave the values and write them in the output
int colBlockSize = inputW + kernelW / kStrideW;
int noAdjOutputW = (inputW - 1) * kStrideW + kernelW;
int point = c * outputH + h;
src += point * colBlockSize * kStrideW;
dst += point * outputW;
float b = bias ? bias[c] : 0;
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
float32x4_t biasV = vdupq_n_f32(b);
#endif
int w = 0;
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
constexpr int kUnroll = (sizeof(float32x4_t) / sizeof(float)) * 2;
int limit = ((inputW - 1) / kUnroll) * kUnroll;
for (; w < limit; w += kUnroll) {
// We need to interleave in terms of kStrideW units
float32x4_t v0[kStrideW];
float32x4_t v1[kStrideW];
for (const auto i : c10::irange(kStrideW)) {
v0[i] = vld1q_f32(src + i * colBlockSize);
v1[i] = vld1q_f32(src + i * colBlockSize + 4);
}
// add per-channel bias
for (const auto i : c10::irange(kStrideW)) {
v0[i] = vaddq_f32(v0[i], biasV);
v1[i] = vaddq_f32(v1[i], biasV);
}
// Write interleaved into the output
StoreInterleaved<float, kStrideW>::store(dst + 0 * kStrideW, v0);
StoreInterleaved<float, kStrideW>::store(dst + 4 * kStrideW, v1);
src += kUnroll;
dst += kUnroll * kStrideW;
}
#endif
// Handle non-vectorizable remainder
for (; w < inputW - 1; ++w) {
float v[kStrideW];
for (const auto i : c10::irange(kStrideW)) {
v[i] = src[i * colBlockSize];
}
// add per-channel bias
for (const auto i : c10::irange(kStrideW)) {
v[i] += b;
}
// Write interleaved into the output
StoreInterleaved<float, kStrideW>::store(dst, v);
src += 1;
dst += kStrideW;
}
// We have handled 0 .. (inputW - 1) * stride inclusive so far.
// Handle the remainder
int outputPoint = (inputW - 1) * kStrideW;
int block = 0;
// Output width may include adjustment into which we don't
// write; ignore it
while (outputPoint < noAdjOutputW) {
float v = src[block * colBlockSize];
dst[0] = v + b;
++outputPoint;
dst += 1;
++block;
if (block >= kStrideW) {
block = 0;
src += 1;
}
}
// Remainder of the buffer comprised of just the `adj` must have
// bias added
for (; outputPoint < outputW; ++outputPoint) {
dst[0] = b;
dst += 1;
}
}
template <int N, typename T, typename Context>
void reinterleaveMultithreaded(
const T* y0,
const T* bias_data,
T* y,
int outputC,
int outputH,
int outputW,
int inputW,
int kernelW,
int strideW,
int adjH,
ThreadPool* pool) {
// # channels times height
size_t totalTiles = (size_t)outputC * outputH;
FixedDivisor<int> divOutputH(outputH);
#define REINTERLEAVE(N) \
do { \
reinterleaveRows<N>( \
y0, \
bias_data, \
c, \
h, \
y, \
outputC, \
outputH, \
outputW, \
inputW, \
kernelW, \
strideW, \
adjH); \
} while (false)
std::function<void(int, size_t)> fnReinterleave = [&](int threadId,
size_t tileId) {
int h;
int c;
divOutputH.DivMod((int)tileId, &c, &h);
REINTERLEAVE(N);
};
#undef REINTERLEAVE
pool->run(fnReinterleave, totalTiles);
}
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
template <int N>
struct SumMultiple {
static void sumInto(float* acc, float** toSum, size_t size);
};
template <>
struct SumMultiple<1> {
static void sumInto(float* acc, float** toSum, size_t size) {
constexpr int kUnroll = (sizeof(float32x4_t) / sizeof(float));
int limit = (size / kUnroll) * kUnroll;
auto toSum0 = toSum[0];
size_t i = 0;
for (; i < limit; i += kUnroll) {
float32x4_t v0 = vld1q_f32_aligned(acc + i);
float32x4_t v1 = vld1q_f32_aligned(toSum0 + i);
v0 = vaddq_f32(v0, v1);
vst1q_f32_aligned(acc + i, v0);
}
for (; i < size; ++i) {
float v0 = acc[i];
float v1 = toSum0[i];
v0 += v1;
acc[i] = v0;
}
}
};
template <>
struct SumMultiple<2> {
static void sumInto(float* acc, float** toSum, size_t size) {
constexpr int kUnroll = (sizeof(float32x4_t) / sizeof(float));
int limit = (size / kUnroll) * kUnroll;
auto toSum0 = toSum[0];
auto toSum1 = toSum[1];
size_t i = 0;
for (; i < limit; i += kUnroll) {
float32x4_t v0 = vld1q_f32_aligned(acc + i);
float32x4_t v1 = vld1q_f32_aligned(toSum0 + i);
float32x4_t v2 = vld1q_f32_aligned(toSum1 + i);
v0 = vaddq_f32(v0, v1);
v0 = vaddq_f32(v0, v2);
vst1q_f32_aligned(acc + i, v0);
}
for (; i < size; ++i) {
float v0 = acc[i];
float v1 = toSum0[i];
float v2 = toSum1[i];
v0 += v1;
v0 += v2;
acc[i] = v0;
}
}
};
template <>
struct SumMultiple<3> {
static void sumInto(float* acc, float** toSum, size_t size) {
constexpr int kUnroll = (sizeof(float32x4_t) / sizeof(float));
int limit = (size / kUnroll) * kUnroll;
auto toSum0 = toSum[0];
auto toSum1 = toSum[1];
auto toSum2 = toSum[2];
size_t i = 0;
for (; i < limit; i += kUnroll) {
float32x4_t v0 = vld1q_f32_aligned(acc + i);
float32x4_t v1 = vld1q_f32_aligned(toSum0 + i);
float32x4_t v2 = vld1q_f32_aligned(toSum1 + i);
float32x4_t v3 = vld1q_f32_aligned(toSum2 + i);
v0 = vaddq_f32(v0, v1);
v2 = vaddq_f32(v2, v3);
v0 = vaddq_f32(v0, v2);
vst1q_f32_aligned(acc + i, v0);
}
for (; i < size; ++i) {
float v0 = acc[i];
float v1 = toSum0[i];
float v2 = toSum1[i];
float v3 = toSum2[i];
v0 += v1;
v2 += v3;
v0 += v2;
acc[i] = v0;
}
}
};
#endif
// Performs acc[i] += sum_j toSum_j[i] pointwise
void sumInto(float* acc, std::vector<float*>& toSum, size_t size) {
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
if (toSum.size() == 1) {
SumMultiple<1>::sumInto(acc, toSum.data(), size);
return;
} else if (toSum.size() == 2) {
SumMultiple<2>::sumInto(acc, toSum.data(), size);
return;
} else if (toSum.size() == 3) {
SumMultiple<3>::sumInto(acc, toSum.data(), size);
return;
}
#endif
// Otherwise, use fallback implementation
EigenVectorArrayMap<float> accT(acc, size);
for (auto p : toSum) {
accT += ConstEigenVectorArrayMap<float>(p, size);
}
}
template <typename T, class Context>
bool ConvTransposeMobileOp<T, Context>::RunOnDeviceWithOrderNCHW() {
const Tensor& X = Input(INPUT);
auto& filter = Input(FILTER);
const int N = X.dim32(0), M = X.dim32(1), H = X.dim32(2), W = X.dim32(3);
CAFFE_ENFORCE(filter.ndim() == 4, "filter must be 4D tensor");
CAFFE_ENFORCE(
filter.dim32(0) == M,
"filter number must be equal to input channel number");
const int C = filter.dim32(1);
CAFFE_ENFORCE(
filter.dim32(2) == this->kernel_h(),
"filter height must be equal to kernel height");
CAFFE_ENFORCE(
filter.dim32(3) == this->kernel_w(),
"filter width must be equal to kernel width");
if (InputSize() == 3) {
auto& bias = Input(BIAS);
CAFFE_ENFORCE(bias.ndim() == 1, "bias must be 1D tensor");
CAFFE_ENFORCE(
bias.dim32(0) == C,
"bias dimension must be equal to output channel number");
}
auto sizes = ConvTransposeUnpoolBase<Context>::GetOutputSize(X, C);
Tensor* Y = Output(0, sizes, at::dtype<T>());
if (X.numel() == 0) {
VLOG(2) << "Number of elements is 0 in ConvTrasposeOp";
return true;
}
const int outputH = Y->dim32(2);
const int outputW = Y->dim32(3);
const int outputPlaneSize = outputH * outputW;
const int outputBatchElementSize = Y->dim32(1) * outputPlaneSize;
auto Xdata = X.template data<T>();
auto Ydata = Y->template mutable_data<T>();
auto pool = ws_->GetThreadPool();
auto numThreads = pool->getNumThreads();
// Initialize per-thread buffers for output
// The main thread will write directly into the output Y, we just
// need buffers for the worker threads
size_t colBlockSize = W + this->kernel_w() / this->stride_w();
size_t threadYBufferSize = C * outputH * colBlockSize * this->stride_w();
// Require 16 byte alignment, so 4-element alignment as these are floats.
size_t threadYBufferSizeAligned =
((C * outputH * colBlockSize * this->stride_w() + 3) / 4) * 4;
size_t threadColBufferSize = C * this->kernel_h() * this->kernel_w() * W;
// Work around GCC 4.9 bug when this is declared inside the inner lambda.
auto runLocalTile = [&](TensorCPU* threadBuffer,
int threadId,
size_t tileId) {
auto localYData = threadBuffer->template mutable_data<T>() +
threadId * threadYBufferSizeAligned;
auto localColBufferData = threadBuffer->template mutable_data<T>() +
numThreads * threadYBufferSizeAligned + threadId * threadColBufferSize;
runTileContiguous<T, Context>(
tileId,
N,
M,
H,
W,
outputH,
outputW,
C,
this->kernel_h(),
this->kernel_w(),
this->stride_h(),
this->stride_w(),
this->pad_t(),
filter.template data<T>(),
Xdata,
localColBufferData,
localYData,
&context_);
};
auto f = [&](Tensor* threadBuffer) {
threadBuffer->Resize(
numThreads * threadYBufferSizeAligned +
numThreads * threadColBufferSize);
// Group together thread buffers for accumulation
std::vector<T*> toSum(numThreads - 1);
for (const auto i : c10::irange(1, numThreads)) {
toSum[i - 1] = threadBuffer->template mutable_data<T>() +
i * threadYBufferSizeAligned;
}
for (const auto image_id : c10::irange(N)) {
// Each time through, we have to reset all per-thread output
// buffers, since the output buffer is only per-batch element
// The column buffers are overwritten by the matrix multiplication
// each time, so we need not clear them out each round
math::Set<T, Context>(
numThreads * threadYBufferSizeAligned,
0,
threadBuffer->template mutable_data<T>(),
&context_);
// Run tiled gemm and col2im in our threadpool; all of these tiles
// are guaranteed to be full tiles
// Each tile handles a single row of the input
pool->run(
[&](int threadId, int tileId) {
runLocalTile(threadBuffer, threadId, tileId);
},
H);
// We need to accumulate the per-thread results into the output
// Y; the first worker thread (main thread) already produced its
// results in Y
sumInto(
threadBuffer->template mutable_data<T>(), toSum, threadYBufferSize);
// y0 now contains the final output, but it is in deinterleaved
// form. We have to re-interleave it to produce the final form in Y
// This operation also handles adding the per-channel bias.
#define REINTERLEAVE(N) \
do { \
reinterleaveMultithreaded<N, T, Context>( \
threadBuffer->template mutable_data<T>(), \
InputSize() == 3 ? Input(BIAS).template data<T>() : nullptr, \
Ydata, \
Y->dim32(1), \
Y->dim32(2), \
Y->dim32(3), \
W, \
this->kernel_w(), \
this->stride_w(), \
this->adj_h(), \
pool); \
} while (false)
if (this->stride_w() == 1) {
REINTERLEAVE(1);
} else if (this->stride_w() == 2) {
REINTERLEAVE(2);
} else if (this->stride_w() == 3) {
REINTERLEAVE(3);
} else if (this->stride_w() == 4) {
REINTERLEAVE(4);
}
#undef REINTERLEAVE
Xdata += M * H * W;
Ydata += Y->size() / Y->dim32(0);
}
};
if (FLAGS_caffe2_force_shared_col_buffer || shared_buffer_) {
runWithSharedBuffer<Context>(ws_, f);
} else {
f(&threadBuffer_);
}
return true;
}
template <typename T, class Context>
bool ConvTransposeMobileOp<T, Context>::RunOnDeviceWithOrderNHWC() {
CAFFE_THROW("Not implemented.");
}
} // namespace caffe2
#endif // C10_MOBILE
#endif // CAFFE2_OPERATORS_CONV_TRANSPOSE_MOBILE_OP_IMPL_H_