conv_op.h 19.5 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43
// Base convolution operator definations for other conv
// like operators to reuse the implementation.
inline int OutputSize(int input_size, int filter_size, int padding,
                      int stride) {
  int output_size = (input_size - filter_size + 2 * padding) / stride + 1;
  return output_size;
}

// 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 已提交
44 45 46 47 48 49 50
class Conv3DOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  Conv3DOpMaker(framework::OpProto* proto,
                framework::OpAttrChecker* op_checker);
};

class ConvOp : public framework::OperatorWithKernel {
武毅 已提交
51 52 53 54 55 56
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

C
chengduoZH 已提交
57
class ConvOpGrad : public framework::OperatorWithKernel {
武毅 已提交
58 59 60 61 62 63
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

64
template <typename Place, typename T>
Y
Yu Yang 已提交
65
class GemmConv2DKernel : public framework::OpKernel<T> {
66 67 68
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const Tensor* input = context.Input<Tensor>("Input");
H
hedaoyuan 已提交
69 70 71 72
    // 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");
73 74 75 76 77
    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 已提交
78
    int groups = context.Attr<int>("groups");
79 80 81

    int batch_size = input->dims()[0];
    int input_channels = input->dims()[1];
H
hedaoyuan 已提交
82 83 84
    int filter_height = filter.dims()[filter.dims().size() - 2];
    int filter_width = filter.dims()[filter.dims().size() - 1];
    int output_channels = output->dims()[1];
85 86 87
    int output_height = output->dims()[2];
    int output_width = output->dims()[3];

C
chengduoZH 已提交
88
    math::Im2ColFunctor<math::ColFormat::kCFO, Place, T> im2col;
H
hedaoyuan 已提交
89
    // use col_shape in the im2col calculation
H
hedaoyuan 已提交
90 91
    framework::DDim col_shape = {input_channels / groups, filter_height,
                                 filter_width, output_height, output_width};
H
hedaoyuan 已提交
92 93
    // use col_matrix_shape in the gemm calculation
    framework::DDim col_matrix_shape = {
H
hedaoyuan 已提交
94
        input_channels / groups * filter_height * filter_width,
H
hedaoyuan 已提交
95
        output_height * output_width};
H
hedaoyuan 已提交
96
    Tensor col;
H
hedaoyuan 已提交
97
    col.mutable_data<T>(col_shape, context.GetPlace());
H
hedaoyuan 已提交
98 99 100 101 102
    // 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.
    Tensor col_matrix = col;
    col_matrix.Resize(col_matrix_shape);
103 104 105

    framework::DDim input_shape = {input->dims()[1], input->dims()[2],
                                   input->dims()[3]};
H
hedaoyuan 已提交
106 107
    framework::DDim filter_matrix_shape = {filter.dims()[0],
                                           filter.numel() / filter.dims()[0]};
H
hedaoyuan 已提交
108 109 110 111
    filter.Resize(filter_matrix_shape);

    framework::DDim output_matrix_shape = {output_channels,
                                           output_height * output_width};
H
hedaoyuan 已提交
112
    // convolution operator: im2col + gemm
H
hedaoyuan 已提交
113 114
    int in_step = input_channels / groups;
    int out_step = output_channels / groups;
115
    for (int i = 0; i < batch_size; i++) {
116 117
      Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
      Tensor out_batch = output->Slice(i, i + 1).Resize(output_matrix_shape);
H
hedaoyuan 已提交
118 119
      for (int g = 0; g < groups; g++) {
        // im2col
120
        Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);
H
hedaoyuan 已提交
121
        im2col(context.device_context(), in_slice, col, strides[0], strides[1],
C
chengduoZH 已提交
122
               paddings[0], paddings[0], paddings[1], paddings[1]);
H
hedaoyuan 已提交
123 124

        // gemm
125 126
        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);
H
hedaoyuan 已提交
127 128
        math::matmul<Place, T>(context.device_context(), filter_slice, false,
                               col_matrix, false, T(1.0), &out_slice, T(0.0));
H
hedaoyuan 已提交
129
      }
130 131 132 133 134
    }
  }
};

template <typename Place, typename T>
Y
Yu Yang 已提交
135
class GemmConvGrad2DKernel : public framework::OpKernel<T> {
136 137
 public:
  void Compute(const framework::ExecutionContext& context) const override {
H
hedaoyuan 已提交
138 139 140 141 142
    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 已提交
143
    Tensor* filter_grad =
H
hedaoyuan 已提交
144
        context.Output<Tensor>(framework::GradVarName("Filter"));
H
hedaoyuan 已提交
145 146 147 148 149

    // 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 已提交
150 151 152

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
153
    int groups = context.Attr<int>("groups");
H
hedaoyuan 已提交
154 155 156

    int batch_size = input->dims()[0];
    int input_channels = input->dims()[1];
H
hedaoyuan 已提交
157 158
    int filter_height = filter.dims()[filter.dims().size() - 2];
    int filter_width = filter.dims()[filter.dims().size() - 1];
159
    int output_channels = output_grad->dims()[1];
H
hedaoyuan 已提交
160 161 162
    int output_height = output_grad->dims()[2];
    int output_width = output_grad->dims()[3];

C
chengduoZH 已提交
163 164
    math::Col2ImFunctor<math::ColFormat::kCFO, Place, T> col2im;
    math::Im2ColFunctor<math::ColFormat::kCFO, Place, T> im2col;
H
hedaoyuan 已提交
165
    // use col_shape in the im2col and col2im calculation
166 167
    framework::DDim col_shape = {input_channels / groups, filter_height,
                                 filter_width, output_height, output_width};
H
hedaoyuan 已提交
168 169
    // use col_matrix_shape in the gemm calculation
    framework::DDim col_matrix_shape = {
170
        input_channels / groups * filter_height * filter_width,
H
hedaoyuan 已提交
171 172
        output_height * output_width};
    Tensor col;
H
hedaoyuan 已提交
173
    col.mutable_data<T>(col_shape, context.GetPlace());
H
hedaoyuan 已提交
174 175 176 177 178
    // 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.
    Tensor col_matrix = col;
    col_matrix.Resize(col_matrix_shape);
H
hedaoyuan 已提交
179 180 181 182 183 184 185

    framework::DDim input_shape = {input->dims()[1], input->dims()[2],
                                   input->dims()[3]};
    framework::DDim output_matrix_shape = {
        output_grad->dims()[1],
        output_grad->dims()[2] * output_grad->dims()[3]};

H
hedaoyuan 已提交
186 187
    framework::DDim filter_matrix_shape = {filter.dims()[0],
                                           filter.numel() / filter.dims()[0]};
H
hedaoyuan 已提交
188 189
    filter.Resize(filter_matrix_shape);

H
hedaoyuan 已提交
190 191
    // convolution backward input operator:  gemm + col2im
    // convolution backward weight operator: im2col + gemm
192 193
    int in_step = input_channels / groups;
    int out_step = output_channels / groups;
C
chengduoZH 已提交
194
    math::SetConstant<Place, T> set_zero;
H
hedaoyuan 已提交
195 196 197

    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
198
      set_zero(context.device_context(), input_grad, static_cast<T>(0));
H
hedaoyuan 已提交
199 200 201

      for (int i = 0; i < batch_size; i++) {
        Tensor out_grad_batch =
202 203
            output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
        Tensor in_grad_batch = input_grad->Slice(i, i + 1).Resize(input_shape);
H
hedaoyuan 已提交
204
        for (int g = 0; g < groups; g++) {
205
          // gemm
H
hedaoyuan 已提交
206
          Tensor out_grad_slice =
207 208
              out_grad_batch.Slice(g * out_step, (g + 1) * out_step);
          Tensor filter_slice = filter.Slice(g * out_step, (g + 1) * out_step);
H
hedaoyuan 已提交
209
          math::matmul<Place, T>(context.device_context(), filter_slice, true,
H
hedaoyuan 已提交
210 211
                                 out_grad_slice, false, T(1.0), &col_matrix,
                                 T(0.0));
212 213 214

          // col2im
          Tensor in_grad_slice =
215
              in_grad_batch.Slice(g * in_step, (g + 1) * in_step);
H
hedaoyuan 已提交
216
          col2im(context.device_context(), in_grad_slice, col, strides[0],
C
chengduoZH 已提交
217 218
                 strides[1], paddings[0], paddings[0], paddings[1],
                 paddings[1]);
219
        }
H
hedaoyuan 已提交
220 221
      }
    }
222

H
hedaoyuan 已提交
223 224 225 226
    if (filter_grad) {
      filter_grad->mutable_data<T>(context.GetPlace());
      Tensor filter_grad_ = *filter_grad;
      filter_grad_.Resize(filter_matrix_shape);
C
chengduoZH 已提交
227
      set_zero(context.device_context(), filter_grad, static_cast<T>(0));
H
hedaoyuan 已提交
228 229 230

      for (int i = 0; i < batch_size; i++) {
        Tensor out_grad_batch =
231 232
            output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
H
hedaoyuan 已提交
233
        for (int g = 0; g < groups; g++) {
234
          // im2col
H
hedaoyuan 已提交
235
          Tensor out_grad_slice =
236 237
              out_grad_batch.Slice(g * out_step, (g + 1) * out_step);
          Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);
H
hedaoyuan 已提交
238
          im2col(context.device_context(), in_slice, col, strides[0],
C
chengduoZH 已提交
239 240
                 strides[1], paddings[0], paddings[0], paddings[1],
                 paddings[1]);
241 242 243

          // gemm
          Tensor filter_grad_slice =
244
              filter_grad_.Slice(g * out_step, (g + 1) * out_step);
H
hedaoyuan 已提交
245 246 247
          math::matmul<Place, T>(context.device_context(), out_grad_slice,
                                 false, col_matrix, true, T(1.0),
                                 &filter_grad_slice, T(1.0));
248
        }
249
      }
H
hedaoyuan 已提交
250
    }
251 252 253
  }
};

C
chengduoZH 已提交
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
template <typename Place, typename T>
class GemmConv3DKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const Tensor* input = context.Input<Tensor>("Input");
    // 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");
    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");
    int groups = context.Attr<int>("groups");

    int batch_size = input->dims()[0];
    int input_channels = input->dims()[1];
    int filter_depth = filter.dims()[filter.dims().size() - 3];
    int filter_height = filter.dims()[filter.dims().size() - 2];
    int filter_width = filter.dims()[filter.dims().size() - 1];
    int output_channels = output->dims()[1];
    int output_depth = output->dims()[2];
    int output_height = output->dims()[3];
    int output_width = output->dims()[4];

C
chengduoZH 已提交
280
    math::Vol2ColFunctor<Place, T> vol2col;
C
chengduoZH 已提交
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
    // use col_shape in the vol2col calculation
    framework::DDim col_shape = {input_channels / groups,
                                 filter_depth,
                                 filter_height,
                                 filter_width,
                                 output_depth,
                                 output_height,
                                 output_width};
    // use col_matrix_shape in the gemm calculation
    framework::DDim col_matrix_shape = {
        input_channels / groups * filter_depth * filter_height * filter_width,
        output_depth * output_height * output_width};
    Tensor col;
    col.mutable_data<T>(col_shape, context.GetPlace());
    // 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.
    Tensor col_matrix = col;
    col_matrix.Resize(col_matrix_shape);

    framework::DDim input_shape = {
        input->dims()[1], input->dims()[2], input->dims()[3],
        input->dims()[4]};  // channel, depth, height, width
    framework::DDim filter_matrix_shape = {
        filter.dims()[0],
        filter.numel() / filter.dims()[0]};  // filter_out_channel,
    // filter_in_channel*filter_depth*filter_height*filter_width
    filter.Resize(filter_matrix_shape);

    framework::DDim output_matrix_shape = {
        output_channels, output_depth * output_height * output_width};

    // convolution operator: vol2col + gemm
    int in_step = input_channels / groups;
    int out_step = output_channels / groups;
    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++) {
        // vol2col
        Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);
        vol2col(context.device_context(), in_slice, col, strides[0], strides[1],
                strides[2], paddings[0], paddings[1], paddings[2]);

        // 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));
      }
    }
  }
};

template <typename Place, typename T>
class GemmConvGrad3DKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    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"));
    Tensor* filter_grad =
        context.Output<Tensor>(framework::GradVarName("Filter"));

    // 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");

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
    int groups = context.Attr<int>("groups");

    int batch_size = input->dims()[0];
    int input_channels = input->dims()[1];
    int filter_depth = filter.dims()[filter.dims().size() - 3];
    int filter_height = filter.dims()[filter.dims().size() - 2];
    int filter_width = filter.dims()[filter.dims().size() - 1];
    int output_channels = output_grad->dims()[1];
    int output_depth = output_grad->dims()[2];
    int output_height = output_grad->dims()[3];
    int output_width = output_grad->dims()[4];

C
chengduoZH 已提交
366 367
    math::Col2VolFunctor<Place, T> col2vol;
    math::Vol2ColFunctor<Place, T> vol2col;
C
chengduoZH 已提交
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
    // use col_shape in the vol2col and col2vol calculation
    framework::DDim col_shape = {input_channels / groups,
                                 filter_depth,
                                 filter_height,
                                 filter_width,
                                 output_depth,
                                 output_height,
                                 output_width};
    // use col_matrix_shape in the gemm calculation
    framework::DDim col_matrix_shape = {
        input_channels / groups * filter_depth * filter_height * filter_width,
        output_depth * output_height * output_width};
    Tensor col;
    col.mutable_data<T>(col_shape, context.GetPlace());
    // 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.
    Tensor col_matrix = col;
    col_matrix.Resize(col_matrix_shape);

    framework::DDim input_shape = {
        input->dims()[1], input->dims()[2], input->dims()[3],
        input->dims()[4]};  // channel, depth, height, width
    framework::DDim output_matrix_shape = {output_grad->dims()[1],
                                           output_grad->dims()[2] *
                                               output_grad->dims()[3] *
                                               output_grad->dims()[4]};

    framework::DDim filter_matrix_shape = {
        filter.dims()[0],
        filter.numel() / filter.dims()[0]};  // filter_out_channel,
    // filter_in_channel*filter_depth*filter_height*filter_width
    filter.Resize(filter_matrix_shape);

    // convolution backward input operator:  gemm + col2vol
    // convolution backward weight operator: vol2col + gemm
    int in_step = input_channels / groups;
    int out_step = output_channels / groups;
C
chengduoZH 已提交
406
    math::SetConstant<Place, T> set_zero;
C
chengduoZH 已提交
407 408 409

    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
410
      set_zero(context.device_context(), input_grad, static_cast<T>(0));
C
chengduoZH 已提交
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

      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));

          // col2vol
          Tensor in_grad_slice =
              in_grad_batch.Slice(g * in_step, (g + 1) * in_step);
          col2vol(context.device_context(), in_grad_slice, col, strides[0],
                  strides[1], strides[2], paddings[0], paddings[1],
                  paddings[2]);
        }
      }
    }

    if (filter_grad) {
      filter_grad->mutable_data<T>(context.GetPlace());
      Tensor filter_grad_ = *filter_grad;
      filter_grad_.Resize(filter_matrix_shape);
C
chengduoZH 已提交
439
      set_zero(context.device_context(), filter_grad, static_cast<T>(0));
C
chengduoZH 已提交
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

      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++) {
          // vol2col
          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);
          vol2col(context.device_context(), in_slice, col, strides[0],
                  strides[1], strides[2], paddings[0], paddings[1],
                  paddings[2]);

          // 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));
        }
      }
    }
  }
};

466 467
}  // namespace operators
}  // namespace paddle