depthwise_conv2d.h 19.3 KB
Newer Older
L
Liangliang He 已提交
1
// Copyright 2018 Xiaomi, Inc.  All rights reserved.
2
//
L
Liangliang He 已提交
3 4 5
// 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
6
//
L
Liangliang He 已提交
7 8 9 10 11 12 13
//     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.
14

15 16
#ifndef MACE_KERNELS_DEPTHWISE_CONV2D_H_
#define MACE_KERNELS_DEPTHWISE_CONV2D_H_
17

18 19 20
#if defined(MACE_ENABLE_NEON) && defined(__aarch64__)
#include <arm_neon.h>
#endif
W
wuchenghui 已提交
21
#include <algorithm>
Y
yejianwu 已提交
22
#include <memory>
W
wuchenghui 已提交
23
#include <vector>
24

25
#include "mace/core/future.h"
26
#include "mace/core/runtime/opencl/cl2_header.h"
L
Liangliang He 已提交
27
#include "mace/kernels/conv_pool_2d_util.h"
李寅 已提交
28
#include "mace/kernels/activation.h"
29
#include "mace/public/mace.h"
30 31 32 33

namespace mace {
namespace kernels {

L
Liangliang He 已提交
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
template <typename T>
void DepthwiseConv2dKernel(const T *input_ptr,
                           const T *filter_ptr,
                           const T *bias_ptr,
                           T *output_ptr,
                           int batch,
                           int height,
                           int width,
                           int channels,
                           int input_height,
                           int input_width,
                           int input_channels,
                           int multiplier,
                           int padded_h_start,
                           int padded_h_stop,
                           int padded_w_start,
                           int padded_w_stop,
                           int kernel_h,
                           int kernel_w,
                           int stride_h,
                           int stride_w,
                           int dilation_h,
                           int dilation_w,
                           int h_start,
                           int h_stop,
                           int w_start,
                           int w_stop) {
#pragma omp parallel for collapse(4)
  for (int n = 0; n < batch; ++n) {
    for (int h = h_start; h < h_stop; ++h) {
      for (int w = w_start; w < w_stop; ++w) {
        for (int c = 0; c < channels; ++c) {
          const index_t inc = c / multiplier;
          const index_t m = c % multiplier;
          T bias_channel = bias_ptr ? bias_ptr[c] : 0;
          index_t offset = n * height * width * channels +
                           h * width * channels + w * channels + c;
          output_ptr[offset] = bias_channel;
          T sum = 0;
          const T *filter_base = filter_ptr + inc * multiplier + m;
          for (int kh = 0; kh < kernel_h; ++kh) {
            for (int kw = 0; kw < kernel_w; ++kw) {
              int inh = padded_h_start + h * stride_h + dilation_h * kh;
              int inw = padded_w_start + w * stride_w + dilation_w * kw;
              if (inh < 0 || inh >= input_height || inw < 0 ||
                  inw >= input_width) {
                MACE_CHECK(inh >= padded_h_start && inh < padded_h_stop &&
                               inw >= padded_w_start && inw < padded_w_stop,
82 83 84
                           "Out of range read from input: ", padded_h_start,
                           " <= ", inh, " < ", padded_h_stop, ", ",
                           padded_w_start, " <= ", inw, " < ", padded_w_stop);
L
Liangliang He 已提交
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
              } else {
                index_t input_offset =
                    n * input_height * input_width * input_channels +
                    inh * input_width * input_channels + inw * input_channels +
                    inc;
                sum += input_ptr[input_offset] * filter_base[0];  // HWIM
              }
              filter_base += input_channels * multiplier;
            }
          }
          output_ptr[offset] += sum;
        }
      }
    }
  }
}
template <typename T>
void DepthwiseConv2dNoOOBCheckKernel(const T *input_ptr,
                                     const T *filter_ptr,
                                     const T *bias_ptr,
                                     T *output_ptr,
                                     int batch,
                                     int height,
                                     int width,
                                     int channels,
                                     int input_height,
                                     int input_width,
                                     int input_channels,
                                     int multiplier,
                                     int padded_h_start,
                                     int padded_h_stop,
                                     int padded_w_start,
                                     int padded_w_stop,
                                     int kernel_h,
                                     int kernel_w,
                                     int stride_h,
                                     int stride_w,
                                     int dilation_h,
                                     int dilation_w,
                                     int h_start,
                                     int h_stop,
                                     int w_start,
                                     int w_stop) {
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
  if (multiplier == 1) {
    constexpr int c_tile_size = 4;

#pragma omp parallel for collapse(3)
    for (int n = 0; n < batch; ++n) {
      for (int h = h_start; h < h_stop; ++h) {
        for (int w = w_start; w < w_stop; ++w) {
          int c;
          for (c = 0; c + c_tile_size <= channels; c += c_tile_size) {
#if defined(MACE_ENABLE_NEON) && defined(__aarch64__)
            static_assert(c_tile_size == 4, "channels tile size must be 4");
            float32x4_t sum = vdupq_n_f32(0);
            if (bias_ptr != nullptr) {
              sum = vld1q_f32(bias_ptr + c);
            }
#else
            T sum[c_tile_size] = {0};
            if (bias_ptr != nullptr) {
              for (int ci = 0; ci < c_tile_size; ++ci) {
                sum[ci] = bias_ptr[c + ci];
              }
            }
#endif
            const T *filter_base = filter_ptr + c;
            for (int kh = 0; kh < kernel_h; ++kh) {
              for (int kw = 0; kw < kernel_w; ++kw) {
                int inh = padded_h_start + h * stride_h + dilation_h * kh;
                int inw = padded_w_start + w * stride_w + dilation_w * kw;
                MACE_ASSERT(inh >= 0 && inh < input_height && inw >= 0 &&
                            inw < input_width);
                index_t input_offset =
                    n * input_height * input_width * input_channels +
                    inh * input_width * input_channels + inw * input_channels +
                    c;
#if defined(MACE_ENABLE_NEON) && defined(__aarch64__)
                float32x4_t in = vld1q_f32(input_ptr + input_offset);
                float32x4_t weights = vld1q_f32(filter_base);
                sum = vfmaq_f32(sum, in, weights);
#else
                for (int ci = 0; ci < c_tile_size; ++ci) {
                  sum[ci] +=
                      input_ptr[input_offset + ci] * filter_base[ci];  // HWIM
                }
#endif
                filter_base += input_channels;
              }
            }

            index_t offset = n * height * width * channels +
                             h * width * channels + w * channels + c;
#if defined(MACE_ENABLE_NEON) && defined(__aarch64__)
            vst1q_f32(output_ptr + offset, sum);
#else
            for (int ci = 0; ci < c_tile_size; ++ci) {
              output_ptr[offset + ci] = sum[ci];
            }
#endif
          }
          for (; c < channels; ++c) {
            T bias_channel = bias_ptr ? bias_ptr[c] : 0;
            index_t offset = n * height * width * channels +
                             h * width * channels + w * channels + c;
            output_ptr[offset] = bias_channel;
            T sum = 0;
            const T *filter_base = filter_ptr + c;
            for (int kh = 0; kh < kernel_h; ++kh) {
              for (int kw = 0; kw < kernel_w; ++kw) {
                int inh = padded_h_start + h * stride_h + dilation_h * kh;
                int inw = padded_w_start + w * stride_w + dilation_w * kw;
                MACE_ASSERT(inh >= 0 && inh < input_height && inw >= 0 &&
                            inw < input_width);
                index_t input_offset =
                    n * input_height * input_width * input_channels +
                    inh * input_width * input_channels + inw * input_channels +
                    c;
                sum += input_ptr[input_offset] * filter_base[0];  // HWIM
                filter_base += input_channels * multiplier;
              }
            }
            output_ptr[offset] += sum;
          }
        }
      }
    }
  } else {
L
Liangliang He 已提交
213
#pragma omp parallel for collapse(4)
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
    for (int n = 0; n < batch; ++n) {
      for (int h = h_start; h < h_stop; ++h) {
        for (int w = w_start; w < w_stop; ++w) {
          for (int c = 0; c < channels; ++c) {
            const index_t inc = c / multiplier;
            const index_t m = c % multiplier;
            T bias_channel = bias_ptr ? bias_ptr[c] : 0;
            index_t offset = n * height * width * channels +
                             h * width * channels + w * channels + c;
            output_ptr[offset] = bias_channel;
            T sum = 0;
            const T *filter_base = filter_ptr + inc * multiplier + m;
            for (int kh = 0; kh < kernel_h; ++kh) {
              for (int kw = 0; kw < kernel_w; ++kw) {
                int inh = padded_h_start + h * stride_h + dilation_h * kh;
                int inw = padded_w_start + w * stride_w + dilation_w * kw;
                MACE_ASSERT(inh >= 0 && inh < input_height && inw >= 0 &&
                            inw < input_width);
                index_t input_offset =
                    n * input_height * input_width * input_channels +
                    inh * input_width * input_channels + inw * input_channels +
                    inc;
                sum += input_ptr[input_offset] * filter_base[0];  // HWIM
                filter_base += input_channels * multiplier;
              }
L
Liangliang He 已提交
239
            }
240
            output_ptr[offset] += sum;
L
Liangliang He 已提交
241 242 243 244 245 246 247
          }
        }
      }
    }
  }
}

248 249
struct DepthwiseConv2dFunctorBase {
  DepthwiseConv2dFunctorBase(const int *strides,
250 251
                             const Padding padding_type,
                             const std::vector<int> &paddings,
252 253
                             const int *dilations,
                             const ActivationType activation,
L
liuqi 已提交
254
                             const float relux_max_limit)
255
      : strides_(strides),
256 257
        padding_type_(padding_type),
        paddings_(paddings),
258 259
        dilations_(dilations),
        activation_(activation),
260
        relux_max_limit_(relux_max_limit) {}
261

L
Liangliang He 已提交
262
  const int *strides_;  // [stride_h, stride_w]
263 264
  const Padding padding_type_;
  std::vector<int> paddings_;
265 266 267 268 269
  const int *dilations_;  // [dilation_h, dilation_w]
  const ActivationType activation_;
  const float relux_max_limit_;
};

L
Liangliang He 已提交
270
template <DeviceType D, typename T>
271
struct DepthwiseConv2dFunctor : public DepthwiseConv2dFunctorBase {
L
liuqi 已提交
272
  DepthwiseConv2dFunctor(const int *strides,
273 274
                         const Padding padding_type,
                         const std::vector<int> &paddings,
275 276
                         const int *dilations,
                         const ActivationType activation,
L
liuqi 已提交
277
                         const float relux_max_limit)
278
      : DepthwiseConv2dFunctorBase(strides,
279 280
                                   padding_type,
                                   paddings,
281 282
                                   dilations,
                                   activation,
L
liuqi 已提交
283
                                   relux_max_limit) {}
284 285 286 287

  void operator()(const Tensor *input,   // NHWC
                  const Tensor *filter,  // HWIM
                  const Tensor *bias,    // O
288 289
                  Tensor *output,
                  StatsFuture *future) {
290 291
    MACE_CHECK_NOTNULL(input);
    MACE_CHECK_NOTNULL(filter);
292 293
    MACE_CHECK_NOTNULL(output);

294 295 296 297
    // Create a fake conv_2d filter to calculate the paddings and output size
    std::vector<index_t> fake_filter_shape(4);
    fake_filter_shape[0] = filter->shape()[0];
    fake_filter_shape[1] = filter->shape()[1];
298 299
    fake_filter_shape[2] = filter->shape()[2] * filter->shape()[3];
    fake_filter_shape[3] = 1;
300 301

    std::vector<index_t> output_shape(4);
L
liuqi 已提交
302
    std::vector<int> paddings(2);
303 304 305 306 307
    if (paddings_.empty()) {
      kernels::CalcNHWCPaddingAndOutputSize(
          input->shape().data(), fake_filter_shape.data(), dilations_, strides_,
          padding_type_, output_shape.data(), paddings.data());
    } else {
L
liuqi 已提交
308
      paddings = paddings_;
309 310 311
      CalcOutputSize(input->shape().data(), fake_filter_shape.data(),
                     paddings_.data(), dilations_, strides_, RoundType::FLOOR,
                     output_shape.data());
312
    }
313 314 315
    auto input_shape = fake_filter_shape;
    output->Resize(output_shape);

316
    index_t batch = output->dim(0);
317 318 319
    index_t height = output->dim(1);
    index_t width = output->dim(2);
    index_t channels = output->dim(3);
320

321
    index_t input_batch = input->dim(0);
322 323 324
    index_t input_height = input->dim(1);
    index_t input_width = input->dim(2);
    index_t input_channels = input->dim(3);
325

326 327 328
    index_t kernel_h = filter->dim(0);
    index_t kernel_w = filter->dim(1);
    index_t multiplier = filter->dim(3);
L
Liangliang He 已提交
329 330
    MACE_CHECK(filter->dim(2) == input_channels, filter->dim(2), "!=",
               input_channels);
331
    MACE_CHECK(channels == input_channels * multiplier);
332 333 334 335 336 337 338 339 340 341

    int stride_h = strides_[0];
    int stride_w = strides_[1];

    int dilation_h = dilations_[0];
    int dilation_w = dilations_[1];

    MACE_CHECK(batch == input_batch, "Input/Output batch size mismatch");

    // The left-upper most offset of the padded input
L
liuqi 已提交
342 343 344 345
    int paddings_top = paddings[0] / 2;
    int paddings_bottom = paddings[0] - paddings_top;
    int paddings_left = paddings[1] / 2;
    int paddings_right = paddings[1] - paddings_left;
346 347 348 349 350

    int padded_h_start = 0 - paddings_top;
    int padded_w_start = 0 - paddings_left;
    index_t padded_h_stop = input_height + paddings_bottom;
    index_t padded_w_stop = input_width + paddings_right;
351

352 353 354 355 356 357
    Tensor::MappingGuard input_mapper(input);
    Tensor::MappingGuard filter_mapper(filter);
    Tensor::MappingGuard bias_mapper(bias);
    Tensor::MappingGuard output_mapper(output);
    const T *input_ptr = input->data<T>();
    const T *filter_ptr = filter->data<T>();
358
    const T *bias_ptr = bias == nullptr ? nullptr : bias->data<T>();
359
    T *output_ptr = output->mutable_data<T>();
360

361 362 363 364 365 366 367 368 369 370 371
    int valid_h_start =
        paddings_top == 0 ? 0 : (paddings_top - 1) / stride_h + 1;
    int valid_h_stop = paddings_bottom == 0
                           ? height
                           : height - ((paddings_bottom - 1) / stride_h + 1);
    int valid_w_start =
        paddings_left == 0 ? 0 : (paddings_left - 1) / stride_w + 1;
    int valid_w_stop = paddings_right == 0
                           ? width
                           : width - ((paddings_right - 1) / stride_w + 1);

L
Liangliang He 已提交
372
    // Calculate border elements with out-of-boundary checking
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
    if (valid_h_start > 0) {
      DepthwiseConv2dKernel<T>(
          input_ptr, filter_ptr, bias_ptr, output_ptr, batch, height, width,
          channels, input_height, input_width, input_channels, multiplier,
          padded_h_start, padded_h_stop, padded_w_start, padded_w_stop,
          kernel_h, kernel_w, stride_h, stride_w, dilation_h, dilation_w, 0,
          valid_h_start, 0, width);
    }
    if (valid_h_stop < height) {
      DepthwiseConv2dKernel<T>(
          input_ptr, filter_ptr, bias_ptr, output_ptr, batch, height, width,
          channels, input_height, input_width, input_channels, multiplier,
          padded_h_start, padded_h_stop, padded_w_start, padded_w_stop,
          kernel_h, kernel_w, stride_h, stride_w, dilation_h, dilation_w,
          std::max(valid_h_start, valid_h_stop), height, 0, width);
    }
    if (valid_w_start > 0) {
      DepthwiseConv2dKernel<T>(
          input_ptr, filter_ptr, bias_ptr, output_ptr, batch, height, width,
          channels, input_height, input_width, input_channels, multiplier,
          padded_h_start, padded_h_stop, padded_w_start, padded_w_stop,
          kernel_h, kernel_w, stride_h, stride_w, dilation_h, dilation_w,
          valid_h_start, valid_h_stop, 0, valid_w_start);
    }
    if (valid_w_stop < width) {
      DepthwiseConv2dKernel<T>(
          input_ptr, filter_ptr, bias_ptr, output_ptr, batch, height, width,
          channels, input_height, input_width, input_channels, multiplier,
          padded_h_start, padded_h_stop, padded_w_start, padded_w_stop,
          kernel_h, kernel_w, stride_h, stride_w, dilation_h, dilation_w,
          valid_h_start, valid_h_stop, std::max(valid_w_start, valid_w_stop),
          width);
    }
L
Liangliang He 已提交
406 407 408 409 410 411

    // Calculate border elements without out-of-boundary checking
    DepthwiseConv2dNoOOBCheckKernel<T>(
        input_ptr, filter_ptr, bias_ptr, output_ptr, batch, height, width,
        channels, input_height, input_width, input_channels, multiplier,
        padded_h_start, padded_h_stop, padded_w_start, padded_w_stop, kernel_h,
412 413
        kernel_w, stride_h, stride_w, dilation_h, dilation_w, valid_h_start,
        valid_h_stop, valid_w_start, valid_w_stop);
414 415

    output_ptr = output->mutable_data<T>();
416
    DoActivation(output_ptr, output_ptr, output->size(), activation_,
L
liuqi 已提交
417
                 relux_max_limit_);
418 419 420
  }
};

L
Liangliang He 已提交
421
template <>
李寅 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
struct DepthwiseConv2dFunctor<DeviceType::NEON, float>
  : DepthwiseConv2dFunctorBase {
  DepthwiseConv2dFunctor(const int *strides,
                         const Padding padding_type,
                         const std::vector<int> &paddings,
                         const int *dilations,
                         const ActivationType activation,
                         const float relux_max_limit)
    : DepthwiseConv2dFunctorBase(strides,
                                 padding_type,
                                 paddings,
                                 dilations,
                                 activation,
                                 relux_max_limit) {}

  void operator()(const Tensor *input,
                  const Tensor *filter,
                  const Tensor *bias,
                  Tensor *output,
                  StatsFuture *future);
};
443

444 445 446 447
template <typename T>
struct DepthwiseConv2dFunctor<DeviceType::OPENCL, T>
    : DepthwiseConv2dFunctorBase {
  DepthwiseConv2dFunctor(const int *strides,
448 449
                         const Padding padding_type,
                         const std::vector<int> &paddings,
450 451
                         const int *dilations,
                         const ActivationType activation,
L
liuqi 已提交
452
                         const float relux_max_limit)
453
      : DepthwiseConv2dFunctorBase(strides,
454 455
                                   padding_type,
                                   paddings,
456 457
                                   dilations,
                                   activation,
L
liuqi 已提交
458
                                   relux_max_limit) {}
459 460 461 462 463 464

  void operator()(const Tensor *input,
                  const Tensor *filter,
                  const Tensor *bias,
                  Tensor *output,
                  StatsFuture *future);
465 466

  cl::Kernel kernel_;
Y
yejianwu 已提交
467
  uint32_t kwg_size_;
468
  std::unique_ptr<BufferBase> kernel_error_;
L
liuqi 已提交
469
  std::vector<index_t> input_shape_;
470
};
471

472 473
}  // namespace kernels
}  // namespace mace
L
Liangliang He 已提交
474

475
#endif  // MACE_KERNELS_DEPTHWISE_CONV2D_H_