conv_op.h 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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. */

#pragma once

H
hedaoyuan 已提交
17
#include "paddle/framework/eigen.h"
18 19 20
#include "paddle/framework/op_registry.h"
#include "paddle/operators/math/im2col.h"
#include "paddle/operators/math/math_function.h"
C
chengduoZH 已提交
21
#include "paddle/operators/math/vol2col.h"
22 23 24 25 26 27

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

武毅 已提交
28 29
// Base convolution operator definations for other conv
// like operators to reuse the implementation.
C
chengduoZH 已提交
30 31 32 33 34 35
inline int OutputSize(int input_size, int filter_size, int dilation,
                      int padding_up, int padding_down, int stride) {
  int output_size = (input_size + padding_up + padding_down -
                     (dilation * (filter_size - 1) + 1)) /
                        stride +
                    1;
武毅 已提交
36 37
  return output_size;
}
C
chengduoZH 已提交
38 39 40 41 42 43 44 45 46 47 48 49
inline bool NotExpand(std::vector<int64_t>& filter_dim,
                      std::vector<int>& strides, std::vector<int>& paddings,
                      std::vector<int>& dilations) {
  bool filter_1 = true, strides_1 = true, padding_0 = true, dilation_1 = true;
  for (size_t j = 0; j < strides.size(); ++j) {
    filter_1 &= (static_cast<int>(filter_dim[j]) == 1);
    strides_1 &= (strides[j] == 1);
    padding_0 &= (paddings[j] == 0);
    dilation_1 &= (dilations[j] == 1);
  }
  return filter_1 && strides_1 && padding_0 && dilation_1;
}
武毅 已提交
50 51 52 53 54 55 56 57 58

// Define Op classes in .h file so that other conv
// operator implementations can reuse the code.
class Conv2DOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  Conv2DOpMaker(framework::OpProto* proto,
                framework::OpAttrChecker* op_checker);
};

C
chengduoZH 已提交
59 60 61 62 63 64 65
class Conv3DOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  Conv3DOpMaker(framework::OpProto* proto,
                framework::OpAttrChecker* op_checker);
};

class ConvOp : public framework::OperatorWithKernel {
武毅 已提交
66 67 68 69 70 71
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override;
};

C
chengduoZH 已提交
72
class ConvOpGrad : public framework::OperatorWithKernel {
武毅 已提交
73 74 75 76 77 78
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override;
};

79
template <typename Place, typename T>
C
chengduoZH 已提交
80
class GemmConvKernel : public framework::OpKernel<T> {
81 82 83
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const Tensor* input = context.Input<Tensor>("Input");
H
hedaoyuan 已提交
84 85 86 87
    // The filter will be reshaped in the calculations,
    // so here use an assignment operation,
    // that avoids modifying the variable in the Scope.
    Tensor filter = *context.Input<Tensor>("Filter");
88 89 90 91 92
    Tensor* output = context.Output<Tensor>("Output");
    output->mutable_data<T>(context.GetPlace());

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
H
hedaoyuan 已提交
93
    int groups = context.Attr<int>("groups");
C
chengduoZH 已提交
94
    std::vector<int> dilations = context.Attr<std::vector<int>>("dilations");
95

C
chengduoZH 已提交
96 97 98 99 100 101 102 103 104 105 106
    const int batch_size = static_cast<int>(input->dims()[0]);

    // filter_shape_vec: {k_h, k_w} or {k_d, k_h, k_w}
    std::vector<int64_t> filter_shape_vec(framework::vectorize(filter.dims()));
    filter_shape_vec.erase(filter_shape_vec.begin(),
                           filter_shape_vec.begin() + 2);

    // output_shape_vec: {o_h, o_w} or {o_d, o_h, o_w}
    std::vector<int64_t> output_shape_vec(framework::vectorize(output->dims()));
    output_shape_vec.erase(output_shape_vec.begin(),
                           output_shape_vec.begin() + 2);
107

H
hedaoyuan 已提交
108
    // use col_shape in the im2col calculation
C
chengduoZH 已提交
109 110 111 112 113 114 115 116 117 118
    // col_shape_vec: {i_c/g, k_h, k_w, o_h, o_w} or {i_c/g, k_d, k_h, k_w, o_d,
    // o_h, o_w}
    std::vector<int64_t> col_shape_vec;
    col_shape_vec.push_back(input->dims()[1] / groups);
    col_shape_vec.insert(col_shape_vec.end(), filter_shape_vec.begin(),
                         filter_shape_vec.end());
    col_shape_vec.insert(col_shape_vec.end(), output_shape_vec.begin(),
                         output_shape_vec.end());
    framework::DDim col_shape(framework::make_ddim(col_shape_vec));

H
hedaoyuan 已提交
119
    // use col_matrix_shape in the gemm calculation
C
chengduoZH 已提交
120 121 122 123 124
    // size: (i_c/g * k_h * k_w, o_h * o_w) or (i_c/g * k_d * k_h * k_w, o_d *
    // o_h * o_w)
    framework::DDim col_matrix_shape =
        framework::flatten_to_2d(col_shape, filter_shape_vec.size() + 1);

C
chengduoZH 已提交
125
    bool not_expand = NotExpand(filter_shape_vec, strides, paddings, dilations);
H
hedaoyuan 已提交
126
    Tensor col;
H
hedaoyuan 已提交
127 128 129
    // col_matrix shares the same piece of data with col,
    // but will be reshaped into a two-dimensional matrix shape
    // to call the matrix multiplication interface.
C
chengduoZH 已提交
130
    Tensor col_matrix;
C
chengduoZH 已提交
131 132 133 134 135
    if (!not_expand) {
      col.mutable_data<T>(col_shape, context.GetPlace());
      col_matrix.ShareDataWith(col);
      col_matrix.Resize(col_matrix_shape);
    }
136

C
chengduoZH 已提交
137 138 139
    framework::DDim input_shape = framework::slice_ddim(
        input->dims(), 1, static_cast<int>(input->dims().size()));

H
hedaoyuan 已提交
140 141
    framework::DDim filter_matrix_shape = {filter.dims()[0],
                                           filter.numel() / filter.dims()[0]};
H
hedaoyuan 已提交
142 143
    filter.Resize(filter_matrix_shape);

C
chengduoZH 已提交
144 145 146 147 148 149 150 151
    framework::DDim output_matrix_shape = {
        output->dims()[1],
        output->numel() / (output->dims()[0] * output->dims()[1])};

    // convolution operator: im2col(or vol2col) + gemm
    int in_step = static_cast<int>(input->dims()[1]) / groups;
    int out_step = static_cast<int>(output->dims()[1]) / groups;

C
chengduoZH 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    if (!not_expand) {
      for (int i = 0; i < batch_size; i++) {
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
        Tensor out_batch = output->Slice(i, i + 1).Resize(output_matrix_shape);
        for (int g = 0; g < groups; g++) {
          Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);

          if (filter_shape_vec.size() == 2) {
            // im2col
            math::Im2ColFunctor<math::ColFormat::kCFO, Place, T> im2col;
            im2col(context.device_context(), in_slice, col, dilations[0],
                   dilations[1], strides[0], strides[1], paddings[0],
                   paddings[0], paddings[1], paddings[1]);
          } else if (filter_shape_vec.size() == 3) {
            // vol2col
            math::Vol2ColFunctor<Place, T> vol2col;
C
chengduoZH 已提交
168 169 170
            vol2col(context.device_context(), in_slice, col, dilations[0],
                    dilations[1], dilations[2], strides[0], strides[1],
                    strides[2], paddings[0], paddings[1], paddings[2]);
C
chengduoZH 已提交
171 172 173 174 175 176 177
          }

          // gemm
          Tensor out_slice = out_batch.Slice(g * out_step, (g + 1) * out_step);
          Tensor filter_slice = filter.Slice(g * out_step, (g + 1) * out_step);
          math::matmul<Place, T>(context.device_context(), filter_slice, false,
                                 col_matrix, false, T(1.0), &out_slice, T(0.0));
C
chengduoZH 已提交
178
        }
C
chengduoZH 已提交
179 180 181 182 183 184 185
      }
    } else {
      for (int i = 0; i < batch_size; i++) {
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
        Tensor out_batch = output->Slice(i, i + 1).Resize(output_matrix_shape);
        for (int g = 0; g < groups; g++) {
          Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);
H
hedaoyuan 已提交
186

C
chengduoZH 已提交
187 188 189 190 191 192 193 194 195 196
          col.ShareDataWith(in_slice);
          col_matrix.ShareDataWith(col);
          col_matrix.Resize(col_matrix_shape);

          // gemm
          Tensor out_slice = out_batch.Slice(g * out_step, (g + 1) * out_step);
          Tensor filter_slice = filter.Slice(g * out_step, (g + 1) * out_step);
          math::matmul<Place, T>(context.device_context(), filter_slice, false,
                                 col_matrix, false, T(1.0), &out_slice, T(0.0));
        }
H
hedaoyuan 已提交
197
      }
198 199 200 201 202
    }
  }
};

template <typename Place, typename T>
C
chengduoZH 已提交
203
class GemmConvGradKernel : public framework::OpKernel<T> {
204 205
 public:
  void Compute(const framework::ExecutionContext& context) const override {
H
hedaoyuan 已提交
206 207 208 209 210
    const Tensor* input = context.Input<Tensor>("Input");
    const Tensor* output_grad =
        context.Input<Tensor>(framework::GradVarName("Output"));
    Tensor* input_grad =
        context.Output<Tensor>(framework::GradVarName("Input"));
H
hedaoyuan 已提交
211
    Tensor* filter_grad =
H
hedaoyuan 已提交
212
        context.Output<Tensor>(framework::GradVarName("Filter"));
H
hedaoyuan 已提交
213 214 215 216
    // The filter and filter_grad will be reshaped in the calculations,
    // so here use an assignment operation,
    // that avoids modifying the variable in the Scope.
    Tensor filter = *context.Input<Tensor>("Filter");
H
hedaoyuan 已提交
217

C
chengduoZH 已提交
218 219
    if (!input_grad && !filter_grad) return;

H
hedaoyuan 已提交
220 221
    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
222
    int groups = context.Attr<int>("groups");
C
chengduoZH 已提交
223
    std::vector<int> dilations = context.Attr<std::vector<int>>("dilations");
H
hedaoyuan 已提交
224

C
chengduoZH 已提交
225
    const int batch_size = static_cast<int>(input->dims()[0]);
H
hedaoyuan 已提交
226

C
chengduoZH 已提交
227 228 229 230
    // filter_shape_vec: {k_h, k_w} or {k_d, k_h, k_w}
    std::vector<int64_t> filter_shape_vec(framework::vectorize(filter.dims()));
    filter_shape_vec.erase(filter_shape_vec.begin(),
                           filter_shape_vec.begin() + 2);
231

C
chengduoZH 已提交
232 233 234 235 236
    // output_shape_vec: {o_h, o_w} or {o_d, o_h, o_w}
    std::vector<int64_t> output_shape_vec(
        framework::vectorize(output_grad->dims()));
    output_shape_vec.erase(output_shape_vec.begin(),
                           output_shape_vec.begin() + 2);
C
chengduoZH 已提交
237

C
chengduoZH 已提交
238 239 240 241 242 243 244 245 246 247
    // use col_shape in the im2col calculation
    // col_shape_vec: {i_c/g, k_h, k_w, o_h, o_w} or {i_c/g, k_d, k_h, k_w, o_d,
    // o_h, o_w}
    std::vector<int64_t> col_shape_vec;
    col_shape_vec.push_back(input->dims()[1] / groups);
    col_shape_vec.insert(col_shape_vec.end(), filter_shape_vec.begin(),
                         filter_shape_vec.end());
    col_shape_vec.insert(col_shape_vec.end(), output_shape_vec.begin(),
                         output_shape_vec.end());
    framework::DDim col_shape(framework::make_ddim(col_shape_vec));
C
chengduoZH 已提交
248 249

    // use col_matrix_shape in the gemm calculation
C
chengduoZH 已提交
250 251 252 253 254 255 256 257
    // size: (i_c/g * k_h * k_w, o_h * o_w)
    // or
    // (i_c/g * k_d * k_h * k_w, o_d * o_h * o_w)
    framework::DDim col_matrix_shape =
        framework::flatten_to_2d(col_shape, filter_shape_vec.size() + 1);

    framework::DDim input_shape = framework::slice_ddim(
        input->dims(), 1, static_cast<int>(input->dims().size()));
C
chengduoZH 已提交
258

C
chengduoZH 已提交
259 260
    framework::DDim filter_matrix_shape = {filter.dims()[0],
                                           filter.numel() / filter.dims()[0]};
C
chengduoZH 已提交
261 262 263
    filter.Resize(filter_matrix_shape);

    framework::DDim output_matrix_shape = {
C
chengduoZH 已提交
264 265 266
        output_grad->dims()[1],
        output_grad->numel() /
            (output_grad->dims()[0] * output_grad->dims()[1])};
C
chengduoZH 已提交
267

C
chengduoZH 已提交
268 269 270 271
    // convolution backward input operator:  gemm + col2im(or col2vol)
    // convolution backward weight operator: im2col(or vol2col) + gemm
    int in_step = static_cast<int>(input->dims()[1]) / groups;
    int out_step = static_cast<int>(output_grad->dims()[1]) / groups;
C
chengduoZH 已提交
272

C
chengduoZH 已提交
273
    bool not_expand = NotExpand(filter_shape_vec, strides, paddings, dilations);
C
chengduoZH 已提交
274 275 276 277
    Tensor col;
    // col_matrix shares the same piece of data with col,
    // but will be reshaped into a two-dimensional matrix shape
    // to call the matrix multiplication interface.
C
chengduoZH 已提交
278
    Tensor col_matrix;
C
chengduoZH 已提交
279 280 281 282 283
    if (!not_expand) {
      col.mutable_data<T>(col_shape, context.GetPlace());
      col_matrix.ShareDataWith(col);
      col_matrix.Resize(col_matrix_shape);
    }
C
chengduoZH 已提交
284

C
chengduoZH 已提交
285
    math::SetConstant<Place, T> set_zero;
C
chengduoZH 已提交
286 287 288

    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
289
      set_zero(context.device_context(), input_grad, static_cast<T>(0));
C
chengduoZH 已提交
290

C
chengduoZH 已提交
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
      if (!not_expand) {
        for (int i = 0; i < batch_size; i++) {
          Tensor out_grad_batch =
              output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
          Tensor in_grad_batch =
              input_grad->Slice(i, i + 1).Resize(input_shape);
          for (int g = 0; g < groups; g++) {
            // gemm
            Tensor out_grad_slice =
                out_grad_batch.Slice(g * out_step, (g + 1) * out_step);
            Tensor filter_slice =
                filter.Slice(g * out_step, (g + 1) * out_step);
            math::matmul<Place, T>(context.device_context(), filter_slice, true,
                                   out_grad_slice, false, T(1.0), &col_matrix,
                                   T(0.0));
            Tensor in_grad_slice =
                in_grad_batch.Slice(g * in_step, (g + 1) * in_step);

            if (filter_shape_vec.size() == 2) {
              math::Col2ImFunctor<math::ColFormat::kCFO, Place, T> col2im;
              col2im(context.device_context(), in_grad_slice, col, dilations[0],
                     dilations[1], strides[0], strides[1], paddings[0],
                     paddings[0], paddings[1], paddings[1]);

            } else if (filter_shape_vec.size() == 3) {
              math::Col2VolFunctor<Place, T> col2vol;
C
chengduoZH 已提交
317 318
              col2vol(context.device_context(), in_grad_slice, col,
                      dilations[0], dilations[1], dilations[2], strides[0],
C
chengduoZH 已提交
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
                      strides[1], strides[2], paddings[0], paddings[1],
                      paddings[2]);
            }
          }
        }
      } else {
        for (int i = 0; i < batch_size; i++) {
          Tensor out_grad_batch =
              output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
          Tensor in_grad_batch =
              input_grad->Slice(i, i + 1).Resize(input_shape);
          for (int g = 0; g < groups; g++) {
            // gemm
            Tensor out_grad_slice =
                out_grad_batch.Slice(g * out_step, (g + 1) * out_step);
            Tensor filter_slice =
                filter.Slice(g * out_step, (g + 1) * out_step);

            Tensor in_grad_slice =
                in_grad_batch.Slice(g * in_step, (g + 1) * in_step);

            col_matrix.ShareDataWith(in_grad_slice);
            col_matrix.Resize(col_matrix_shape);

            math::matmul<Place, T>(context.device_context(), filter_slice, true,
                                   out_grad_slice, false, T(1.0), &col_matrix,
                                   T(0.0));
C
chengduoZH 已提交
346
          }
C
chengduoZH 已提交
347 348 349 350 351 352 353 354
        }
      }
    }

    if (filter_grad) {
      filter_grad->mutable_data<T>(context.GetPlace());
      Tensor filter_grad_ = *filter_grad;
      filter_grad_.Resize(filter_matrix_shape);
C
chengduoZH 已提交
355
      set_zero(context.device_context(), filter_grad, static_cast<T>(0));
C
chengduoZH 已提交
356

C
chengduoZH 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
      if (!not_expand) {
        for (int i = 0; i < batch_size; i++) {
          Tensor out_grad_batch =
              output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
          Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
          for (int g = 0; g < groups; g++) {
            // im2col
            Tensor out_grad_slice =
                out_grad_batch.Slice(g * out_step, (g + 1) * out_step);
            Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);

            if (filter_shape_vec.size() == 2) {
              math::Im2ColFunctor<math::ColFormat::kCFO, Place, T> im2col;
              im2col(context.device_context(), in_slice, col, dilations[0],
                     dilations[1], strides[0], strides[1], paddings[0],
                     paddings[0], paddings[1], paddings[1]);
            } else if (filter_shape_vec.size() == 3) {
              math::Vol2ColFunctor<Place, T> vol2col;
C
chengduoZH 已提交
375 376 377
              vol2col(context.device_context(), in_slice, col, dilations[0],
                      dilations[1], dilations[2], strides[0], strides[1],
                      strides[2], paddings[0], paddings[1], paddings[2]);
C
chengduoZH 已提交
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
            }

            // gemm
            Tensor filter_grad_slice =
                filter_grad_.Slice(g * out_step, (g + 1) * out_step);
            math::matmul<Place, T>(context.device_context(), out_grad_slice,
                                   false, col_matrix, true, T(1.0),
                                   &filter_grad_slice, T(1.0));
          }
        }
      } else {
        for (int i = 0; i < batch_size; i++) {
          Tensor out_grad_batch =
              output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
          Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
          for (int g = 0; g < groups; g++) {
            // im2col
            Tensor out_grad_slice =
                out_grad_batch.Slice(g * out_step, (g + 1) * out_step);
            Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);

            col.ShareDataWith(in_slice);
            col_matrix.ShareDataWith(col);
            col_matrix.Resize(col_matrix_shape);

            // gemm
            Tensor filter_grad_slice =
                filter_grad_.Slice(g * out_step, (g + 1) * out_step);
            math::matmul<Place, T>(context.device_context(), out_grad_slice,
                                   false, col_matrix, true, T(1.0),
                                   &filter_grad_slice, T(1.0));
C
chengduoZH 已提交
409
          }
C
chengduoZH 已提交
410 411 412 413 414
        }
      }
    }
  }
};
415 416
}  // namespace operators
}  // namespace paddle