conv_transpose_op.h 16.5 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* 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

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

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using DDim = framework::DDim;

// Define Op classes in .h file so that other conv transpose
// operator implementations can reuse the code.
C
chengduoZH 已提交
31 32 33 34 35 36
class Conv2DTransposeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  Conv2DTransposeOpMaker(framework::OpProto* proto,
                         framework::OpAttrChecker* op_checker);
};

C
chengduoZH 已提交
37 38 39 40 41 42
class Conv3DTransposeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  Conv3DTransposeOpMaker(framework::OpProto* proto,
                         framework::OpAttrChecker* op_checker);
};

C
chengduoZH 已提交
43
class ConvTransposeOp : public framework::OperatorWithKernel {
C
chengduoZH 已提交
44 45 46 47 48 49 50
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

C
chengduoZH 已提交
51
class ConvTransposeOpGrad : public framework::OperatorWithKernel {
C
chengduoZH 已提交
52 53 54 55 56 57 58 59
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

template <typename Place, typename T>
C
chengduoZH 已提交
60
class GemmConv2DTransposeKernel : public framework::OpKernel<T> {
C
chengduoZH 已提交
61 62 63 64 65 66 67 68
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const Tensor* input = context.Input<Tensor>("Input");
    // The filter will be reshaped, so it should not be constant pointer
    Tensor filter = *context.Input<Tensor>("Filter");
    Tensor* output = context.Output<Tensor>("Output");

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
C
chengduoZH 已提交
69 70 71
    // TODO(Zhuoyuan): Paddings can be added in future.
    // groups will alway be disabled in conv2dtranspose.

C
chengduoZH 已提交
72 73 74 75
    const int batch_size = static_cast<int>(input->dims()[0]);
    const int64_t m = input->dims()[1];
    const int64_t h = input->dims()[2];
    const int64_t w = input->dims()[3];
C
chengduoZH 已提交
76

C
chengduoZH 已提交
77 78
    const int64_t k_h = filter.dims()[2];
    const int64_t k_w = filter.dims()[3];
C
chengduoZH 已提交
79

C
chengduoZH 已提交
80 81 82
    const int64_t c = output->dims()[1];  // output channels
    const int64_t o_h = output->dims()[2];
    const int64_t o_w = output->dims()[3];
C
chengduoZH 已提交
83

C
chengduoZH 已提交
84
    math::Col2ImFunctor<math::ColFormat::kCFO, Place, T> col2im;
C
chengduoZH 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

    // use col_shape in the im2col and col2im calculation
    DDim col_shape = {c, k_h, k_w, h, w};

    // use col_matrix_shape in the gemm calculation
    DDim col_matrix_shape = {c * k_h * k_w, h * w};

    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_matrix.ShareDataWith(col);
    col_matrix.Resize(col_matrix_shape);

    DDim output_shape = {c, o_h, o_w};
    DDim input_matrix_shape = {m, h * w};

C
chengduoZH 已提交
104
    // filter size: (m, c * k_h * k_w)
C
chengduoZH 已提交
105 106 107 108
    DDim filter_matrix_shape = {m, c * k_h * k_w};
    filter.Resize(filter_matrix_shape);

    output->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
109 110
    math::SetConstant<Place, T> set_zero;
    set_zero(context.device_context(), output, static_cast<T>(0));
C
chengduoZH 已提交
111

C
chengduoZH 已提交
112
    // convolution transpose: gemm + col2im (similar to conv-backward on input)
C
chengduoZH 已提交
113
    for (int i = 0; i < batch_size; i++) {
C
chengduoZH 已提交
114
      // batch with size (m, h * w)
C
chengduoZH 已提交
115 116 117 118 119 120 121 122
      Tensor input_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);

      // output size: (c, o_h, o_w)
      Tensor output_batch = output->Slice(i, i + 1).Resize(output_shape);

      // col_matrix = filter * input_batch
      // of shape (c * k_h * k_w, h * w)
      math::matmul<Place, T>(context.device_context(), filter, true,
C
chengduoZH 已提交
123 124 125 126 127
                             input_batch, false, static_cast<T>(1.0),
                             &col_matrix, static_cast<T>(0.0));

      // col2im: col_matrix -> dy
      // from (c * k_h * k_w, h * w) to (c, o_h, o_w)
C
chengduoZH 已提交
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
      col2im(context.device_context(), output_batch, col, strides[0],
             strides[1], 0, 0, 0, 0);
    }
  }
};

template <typename Place, typename T>
class GemmConv2DTransposeGradKernel : 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"));

    // For filter, we do not use const pointer b/c we will do reshape,
    // but we should avoid modifying its value.
    Tensor filter = *context.Input<Tensor>("Filter");
    Tensor* input_grad =
        context.Output<Tensor>(framework::GradVarName("Input"));
    Tensor* filter_grad =
        context.Output<Tensor>(framework::GradVarName("Filter"));

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    // Actually, no paddings and groups allowed in conv transpose.
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");

C
chengduoZH 已提交
154 155 156 157
    const int batch_size = static_cast<int>(input->dims()[0]);
    const int64_t m = input->dims()[1];
    const int64_t h = input->dims()[2];
    const int64_t w = input->dims()[3];
C
chengduoZH 已提交
158

C
chengduoZH 已提交
159 160
    const int64_t k_h = filter.dims()[2];
    const int64_t k_w = filter.dims()[3];
C
chengduoZH 已提交
161

C
chengduoZH 已提交
162 163 164
    const int64_t c = output_grad->dims()[1];  // output channels
    const int64_t o_h = output_grad->dims()[2];
    const int64_t o_w = output_grad->dims()[3];
C
chengduoZH 已提交
165 166

    // Only im2col functor required for bp to get to the right shape
C
chengduoZH 已提交
167
    math::Im2ColFunctor<math::ColFormat::kCFO, Place, T> im2col;
C
chengduoZH 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180

    // use col_shape in the im2col and col2im calculation
    DDim col_shape = {c, k_h, k_w, h, w};

    DDim output_shape = {c, o_h, o_w};
    DDim input_matrix_shape = {m, h * w};

    DDim filter_matrix_shape = {m, c * k_h * k_w};
    filter.Resize(filter_matrix_shape);

    // convolution transpose grad on input:
    // im2col + gemm (similar to conv-forward)
    // input need to compute gradient
C
chengduoZH 已提交
181 182 183 184 185 186
    if (input_grad || filter_grad) {
      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.
C
chengduoZH 已提交
187 188 189 190 191
      Tensor col_matrix;
      col_matrix.ShareDataWith(col);
      DDim col_matrix_shape = {c * k_h * k_w, h * w};
      col_matrix.Resize(col_matrix_shape);

C
chengduoZH 已提交
192 193
      Tensor filter_grad_;
      math::SetConstant<Place, T> set_zero;
C
chengduoZH 已提交
194

C
chengduoZH 已提交
195 196 197 198 199 200 201 202 203
      if (input_grad) {
        input_grad->mutable_data<T>(context.GetPlace());
        set_zero(context.device_context(), input_grad, static_cast<T>(0));
      }
      if (filter_grad) {  // filter size (m, c, k_h, k_w)
        filter_grad->mutable_data<T>(context.GetPlace());
        set_zero(context.device_context(), filter_grad, static_cast<T>(0));
        filter_grad_ = *filter_grad;
        filter_grad_.Resize(filter_matrix_shape);
C
chengduoZH 已提交
204 205
      }

C
chengduoZH 已提交
206 207
      for (int i = 0; i < batch_size; i++) {
        // batch with size (c, o_h * o_w)
C
chengduoZH 已提交
208 209 210
        Tensor output_grad_batch =
            output_grad->Slice(i, i + 1).Resize(output_shape);

C
chengduoZH 已提交
211 212
        // im2col: dy -> col matrix
        // from (c, o_h, o_w) to (c * k_h * k_w, h * w)
C
chengduoZH 已提交
213 214 215
        im2col(context.device_context(), output_grad_batch, col, strides[0],
               strides[1], paddings[0], paddings[0], paddings[1], paddings[1]);

C
chengduoZH 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        if (input_grad) {
          // batch with size (m, h, w)
          Tensor input_grad_batch =
              input_grad->Slice(i, i + 1).Resize(input_matrix_shape);
          // gemm: dx = filter * dy
          // (m, c * k_h * k_w) * (c * k_h * k_w, h * w) -> (m, h * w)
          math::matmul<Place, T>(context.device_context(), filter, false,
                                 col_matrix, false, static_cast<T>(1.0),
                                 &input_grad_batch, static_cast<T>(0.0));
        }
        if (filter_grad) {
          // input batch
          Tensor in_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);
          // gemm: d_filter = x * dy^T
          // (m, c * h * w) * (k_h * k_w, c * h * w) -> (m, k_h * k_w)
          math::matmul<Place, T>(context.device_context(), in_batch, false,
                                 col_matrix, true, static_cast<T>(1.0),
                                 &filter_grad_, static_cast<T>(1.0));
        }
C
chengduoZH 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
      }
    }
  }
};

template <typename Place, typename T>
class GemmConv3DTransposeKernel : 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, so it should not be constant pointer
    Tensor filter = *context.Input<Tensor>("Filter");
    Tensor* output = context.Output<Tensor>("Output");

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
C
chengduoZH 已提交
250 251 252
    // TODO(chengduo): Paddings can be added in future.
    // groups will alway be disabled in conv3dtranspose.

C
chengduoZH 已提交
253 254 255 256 257
    const int batch_size = static_cast<int>(input->dims()[0]);
    const int64_t m = input->dims()[1];
    const int64_t d = input->dims()[2];
    const int64_t h = input->dims()[3];
    const int64_t w = input->dims()[4];
C
chengduoZH 已提交
258

C
chengduoZH 已提交
259 260 261
    const int64_t k_d = filter.dims()[2];
    const int64_t k_h = filter.dims()[3];
    const int64_t k_w = filter.dims()[4];
C
chengduoZH 已提交
262

C
chengduoZH 已提交
263 264 265 266
    const int64_t c = output->dims()[1];  // output channels
    const int64_t o_d = output->dims()[2];
    const int64_t o_h = output->dims()[3];
    const int64_t o_w = output->dims()[4];
C
chengduoZH 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

    paddle::operators::math::Col2VolFunctor<Place, T> col2vol;

    // use col_shape in the vol2col and col2vol calculation
    DDim col_shape = {c, k_d, k_h, k_w, d, h, w};
    // use col_matrix_shape in the gemm calculation
    DDim col_matrix_shape = {c * k_d * k_h * k_w, d * h * w};

    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_matrix.ShareDataWith(col);
    col_matrix.Resize(col_matrix_shape);

    DDim output_shape = {c, o_d, o_h, o_w};
    DDim input_matrix_shape = {m, d * h * w};

C
chengduoZH 已提交
287
    // filter size: (m, c * k_d * k_h * k_w)
C
chengduoZH 已提交
288 289 290 291
    DDim filter_matrix_shape = {m, c * k_d * k_h * k_w};
    filter.Resize(filter_matrix_shape);

    output->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
292 293
    math::SetConstant<Place, T> set_zero;
    set_zero(context.device_context(), output, static_cast<T>(0));
C
chengduoZH 已提交
294

C
chengduoZH 已提交
295
    // convolution transpose: gemm + col2vol (similar to conv-backward on input)
C
chengduoZH 已提交
296
    for (int i = 0; i < batch_size; i++) {
C
chengduoZH 已提交
297
      // batch with size (m, d * h * w)
C
chengduoZH 已提交
298 299 300 301 302 303 304 305
      Tensor input_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);

      // output size: (c, o_d, o_h, o_w)
      Tensor output_batch = output->Slice(i, i + 1).Resize(output_shape);

      // col_matrix = filter * input_batch
      // of shape (c * k_d * k_h * k_w, d * h * w)
      math::matmul<Place, T>(context.device_context(), filter, true,
C
chengduoZH 已提交
306 307 308 309
                             input_batch, false, static_cast<T>(1.0),
                             &col_matrix, static_cast<T>(0.0));
      // col2vol: col_matrix -> dy
      // from (c * k_d * k_h * k_w, d * h * w) to (c, o_d, o_h, o_w)
C
chengduoZH 已提交
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
      col2vol(context.device_context(), output_batch, col, strides[0],
              strides[1], strides[2], 0, 0, 0);
    }
  }
};

template <typename Place, typename T>
class GemmConv3DTransposeGradKernel : 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"));

    // For filter, we do not use const pointer b/c we will do reshape,
    // but we should avoid modifying its value.
    Tensor filter = *context.Input<Tensor>("Filter");
    Tensor* input_grad =
        context.Output<Tensor>(framework::GradVarName("Input"));
    Tensor* filter_grad =
        context.Output<Tensor>(framework::GradVarName("Filter"));

    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    // Actually, no paddings and groups allowed in conv transpose.
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");

C
chengduoZH 已提交
336 337 338 339 340
    const int batch_size = static_cast<int>(input->dims()[0]);
    const int64_t m = input->dims()[1];
    const int64_t d = input->dims()[2];
    const int64_t h = input->dims()[3];
    const int64_t w = input->dims()[4];
C
chengduoZH 已提交
341

C
chengduoZH 已提交
342 343 344
    const int64_t k_d = filter.dims()[2];
    const int64_t k_h = filter.dims()[3];
    const int64_t k_w = filter.dims()[4];
C
chengduoZH 已提交
345

C
chengduoZH 已提交
346 347 348 349
    const int64_t c = output_grad->dims()[1];  // output channels
    const int64_t o_d = output_grad->dims()[2];
    const int64_t o_h = output_grad->dims()[3];
    const int64_t o_w = output_grad->dims()[4];
C
chengduoZH 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

    // Only vol2col functor required for bp to get to the right shape
    paddle::operators::math::Vol2ColFunctor<Place, T> vol2col;

    // use col_shape in the vol2col and col2vol calculation
    DDim col_shape = {c, k_d, k_h, k_w, d, h, w};

    // use col_matrix_shape in the gemm calculation
    DDim col_matrix_shape_f = {c * d * h * w, k_d * k_h * k_w};

    DDim output_shape = {c, o_d, o_h, o_w};
    DDim input_matrix_shape = {m, d * h * w};

    DDim filter_matrix_shape = {m, c * k_d * k_h * k_w};
    filter.Resize(filter_matrix_shape);

    // convolution transpose grad on input:
    // vol2col + gemm (similar to conv-forward)
    // input need to compute gradient
C
chengduoZH 已提交
369 370 371 372 373 374
    if (input_grad || filter_grad) {
      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.
C
chengduoZH 已提交
375 376 377 378 379
      Tensor col_matrix;
      col_matrix.ShareDataWith(col);
      DDim col_matrix_shape = {c * k_d * k_h * k_w, d * h * w};
      col_matrix.Resize(col_matrix_shape);

C
chengduoZH 已提交
380 381
      Tensor filter_grad_;
      math::SetConstant<Place, T> set_zero;
C
chengduoZH 已提交
382

C
chengduoZH 已提交
383 384 385 386 387 388 389 390 391
      if (input_grad) {
        input_grad->mutable_data<T>(context.GetPlace());
        set_zero(context.device_context(), input_grad, static_cast<T>(0));
      }
      if (filter_grad) {  // filter size (m, c * k_d * k_h * k_w)
        filter_grad->mutable_data<T>(context.GetPlace());
        set_zero(context.device_context(), filter_grad, static_cast<T>(0));
        filter_grad_ = *filter_grad;
        filter_grad_.Resize(filter_matrix_shape);
C
chengduoZH 已提交
392 393
      }

C
chengduoZH 已提交
394 395
      for (int i = 0; i < batch_size; i++) {
        // batch with size (c, o_d * o_h * o_w)
C
chengduoZH 已提交
396 397 398
        Tensor output_grad_batch =
            output_grad->Slice(i, i + 1).Resize(output_shape);

C
chengduoZH 已提交
399 400
        // vol2col: dy -> col_matrix
        // from (c, o_d, o_h, o_w) to (c * k_d * k_h * k_w, d * h * w)
C
chengduoZH 已提交
401 402 403
        vol2col(context.device_context(), output_grad_batch, col, strides[0],
                strides[1], strides[2], paddings[0], paddings[1], paddings[2]);

C
chengduoZH 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        if (input_grad) {
          // batch with size (m, d, h, w)
          Tensor input_grad_batch =
              input_grad->Slice(i, i + 1).Resize(input_matrix_shape);
          // gemm: dx = filter * dy
          // (m, c * k_d * k_h * k_w) * (c * k_d * k_h * k_w, d * h * w) -> (m,
          // d, h, w)
          math::matmul<Place, T>(context.device_context(), filter, false,
                                 col_matrix, false, static_cast<T>(1.0),
                                 &input_grad_batch, static_cast<T>(0.0));
        }
        if (filter_grad) {
          // input batch
          Tensor in_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);
          // gemm: d_filter = x * dy^T
          // (m, d * h * w) * (d * h * w, c * k_d * k_h * k_w) -> (m, c * k_d *
          // k_h * k_w)
          math::matmul<Place, T>(context.device_context(), in_batch, false,
                                 col_matrix, true, static_cast<T>(1.0),
                                 &filter_grad_, static_cast<T>(1.0));
        }
C
chengduoZH 已提交
425 426 427 428 429 430 431
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle