conv_op.h 19.9 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 88 89 90
    int output_height = output->dims()[2];
    int output_width = output->dims()[3];

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

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

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

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

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

    // 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 已提交
152 153 154

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

    int batch_size = input->dims()[0];
    int input_channels = input->dims()[1];
H
hedaoyuan 已提交
159 160
    int filter_height = filter.dims()[filter.dims().size() - 2];
    int filter_width = filter.dims()[filter.dims().size() - 1];
161
    int output_channels = output_grad->dims()[1];
H
hedaoyuan 已提交
162 163 164 165 166 167 168 169 170
    int output_height = output_grad->dims()[2];
    int output_width = output_grad->dims()[3];

    paddle::operators::math::Col2ImFunctor<
        paddle::operators::math::ColFormat::kCFO, Place, T>
        col2im;
    paddle::operators::math::Im2ColFunctor<
        paddle::operators::math::ColFormat::kCFO, Place, T>
        im2col;
H
hedaoyuan 已提交
171
    // use col_shape in the im2col and col2im calculation
172 173
    framework::DDim col_shape = {input_channels / groups, filter_height,
                                 filter_width, output_height, output_width};
H
hedaoyuan 已提交
174 175
    // use col_matrix_shape in the gemm calculation
    framework::DDim col_matrix_shape = {
176
        input_channels / groups * filter_height * filter_width,
H
hedaoyuan 已提交
177 178
        output_height * output_width};
    Tensor col;
H
hedaoyuan 已提交
179
    col.mutable_data<T>(col_shape, context.GetPlace());
H
hedaoyuan 已提交
180 181 182 183 184
    // 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 已提交
185 186 187 188 189 190 191

    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 已提交
192 193
    framework::DDim filter_matrix_shape = {filter.dims()[0],
                                           filter.numel() / filter.dims()[0]};
H
hedaoyuan 已提交
194 195
    filter.Resize(filter_matrix_shape);

H
hedaoyuan 已提交
196 197
    // convolution backward input operator:  gemm + col2im
    // convolution backward weight operator: im2col + gemm
198 199
    int in_step = input_channels / groups;
    int out_step = output_channels / groups;
H
hedaoyuan 已提交
200 201 202 203 204 205 206 207

    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
      auto t = framework::EigenVector<T>::Flatten(*input_grad);
      t.device(context.GetEigenDevice<Place>()) = t.constant(static_cast<T>(0));

      for (int i = 0; i < batch_size; i++) {
        Tensor out_grad_batch =
208 209
            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 已提交
210
        for (int g = 0; g < groups; g++) {
211
          // gemm
H
hedaoyuan 已提交
212
          Tensor out_grad_slice =
213 214
              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 已提交
215
          math::matmul<Place, T>(context.device_context(), filter_slice, true,
H
hedaoyuan 已提交
216 217
                                 out_grad_slice, false, T(1.0), &col_matrix,
                                 T(0.0));
218 219 220

          // col2im
          Tensor in_grad_slice =
221
              in_grad_batch.Slice(g * in_step, (g + 1) * in_step);
H
hedaoyuan 已提交
222
          col2im(context.device_context(), in_grad_slice, col, strides[0],
C
chengduoZH 已提交
223 224
                 strides[1], paddings[0], paddings[0], paddings[1],
                 paddings[1]);
225
        }
H
hedaoyuan 已提交
226 227
      }
    }
228

H
hedaoyuan 已提交
229 230 231 232 233 234 235 236 237
    if (filter_grad) {
      filter_grad->mutable_data<T>(context.GetPlace());
      Tensor filter_grad_ = *filter_grad;
      filter_grad_.Resize(filter_matrix_shape);
      auto t = framework::EigenVector<T>::Flatten(filter_grad_);
      t.device(context.GetEigenDevice<Place>()) = t.constant(static_cast<T>(0));

      for (int i = 0; i < batch_size; i++) {
        Tensor out_grad_batch =
238 239
            output_grad->Slice(i, i + 1).Resize(output_matrix_shape);
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_shape);
H
hedaoyuan 已提交
240
        for (int g = 0; g < groups; g++) {
241
          // im2col
H
hedaoyuan 已提交
242
          Tensor out_grad_slice =
243 244
              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 已提交
245
          im2col(context.device_context(), in_slice, col, strides[0],
C
chengduoZH 已提交
246 247
                 strides[1], paddings[0], paddings[0], paddings[1],
                 paddings[1]);
248 249 250

          // gemm
          Tensor filter_grad_slice =
251
              filter_grad_.Slice(g * out_step, (g + 1) * out_step);
H
hedaoyuan 已提交
252 253 254
          math::matmul<Place, T>(context.device_context(), out_grad_slice,
                                 false, col_matrix, true, T(1.0),
                                 &filter_grad_slice, T(1.0));
255
        }
256
      }
H
hedaoyuan 已提交
257
    }
258 259 260
  }
};

C
chengduoZH 已提交
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
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];

    paddle::operators::math::Vol2ColFunctor<Place, T> vol2col;
    // 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];

    paddle::operators::math::Col2VolFunctor<Place, T> col2vol;
    paddle::operators::math::Vol2ColFunctor<Place, T> vol2col;
    // 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;

    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
      auto t = framework::EigenVector<T>::Flatten(*input_grad);
      t.device(context.GetEigenDevice<Place>()) = t.constant(static_cast<T>(0));

      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);
      auto t = framework::EigenVector<T>::Flatten(filter_grad_);
      t.device(context.GetEigenDevice<Place>()) = t.constant(static_cast<T>(0));

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

474 475
}  // namespace operators
}  // namespace paddle