conv_transpose_op.h 17.1 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 69 70
 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 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 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 213 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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    // TODO(Zhuoyuan): Paddings can be added in future.
    // groups will alway be disabled in conv2dtranspose.

    const int batch_size = input->dims()[0];
    const int m = input->dims()[1];
    const int h = input->dims()[2];
    const int w = input->dims()[3];

    const int k_h = filter.dims()[2];
    const int k_w = filter.dims()[3];

    const int c = output->dims()[1];  // output channels
    const int o_h = output->dims()[2];
    const int o_w = output->dims()[3];

    paddle::operators::math::Col2ImFunctor<
        paddle::operators::math::ColFormat::kCFO, Place, T>
        col2im;

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

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

    // convolution transpose: gemm + col2im (similar to conv-backward on input)

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

    for (int i = 0; i < batch_size; i++) {
      // batch with size (M, h * w)
      Tensor input_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);
      // filter size: (M, c * k_h * k_w)

      // 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,
                             input_batch, false, T(1.0), &col_matrix, T(0.0));
      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");

    const int batch_size = input->dims()[0];
    const int m = input->dims()[1];
    const int h = input->dims()[2];
    const int w = input->dims()[3];

    const int k_h = filter.dims()[2];
    const int k_w = filter.dims()[3];

    const int c = output_grad->dims()[1];  // output channels
    const int o_h = output_grad->dims()[2];
    const int o_w = output_grad->dims()[3];

    // Only im2col functor required for bp to get to the right shape
    paddle::operators::math::Im2ColFunctor<
        paddle::operators::math::ColFormat::kCFO, Place, T>
        im2col;

    // 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_f = {c * h * w, k_h * k_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.

    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
    if (input_grad) {
      Tensor col_matrix;
      col_matrix.ShareDataWith(col);
      DDim col_matrix_shape = {c * k_h * k_w, h * w};
      col_matrix.Resize(col_matrix_shape);

      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++) {
        // batch with size (c, o_h * o_w)
        Tensor output_grad_batch =
            output_grad->Slice(i, i + 1).Resize(output_shape);
        // filter of size (m, c * k_h * k_w)

        // batch with size (m, h, w)
        Tensor input_grad_batch =
            input_grad->Slice(i, i + 1).Resize(input_matrix_shape);

        // im2col: dy from (c, o_h, o_w) -> (c * k_h * k_w, h * w)
        im2col(context.device_context(), output_grad_batch, col, strides[0],
               strides[1], paddings[0], paddings[0], paddings[1], paddings[1]);

        // gemm: dx = filter * dy
        // (m, c * k_h * k_w) * (c * k_h * k_w, h * w) -> (m, c, h)
        math::matmul<Place, T>(context.device_context(), filter, false,
                               col_matrix, false, T(1.0), &input_grad_batch,
                               T(0.0));
      }
    }

    // filter gradient required
    if (filter_grad) {
      Tensor col_matrix_f;
      col_matrix_f.ShareDataWith(col);
      DDim col_matrix_shape_f = {c * h * w, k_h * k_w};
      col_matrix_f.Resize(col_matrix_shape_f);

      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) {
        // batch with size (c, o_h, o_w)
        Tensor output_grad_batch =
            output_grad->Slice(i, i + 1).Resize(output_shape);
        // input batch
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);

        // im2col: (c * h * w, k_h * k_w)
        im2col(context.device_context(), output_grad_batch, col, strides[0],
               strides[1], paddings[0], paddings[0], paddings[1], paddings[1]);

        // gemm: d_filter = x * y_grad^T
        // (m, c * h * w) * (k_h * k_w, c * h * w) -> (m, c, h)
        math::matmul<Place, T>(context.device_context(), in_batch, false,
                               col_matrix_f, true, T(1.0), &filter_grad_,
                               T(1.0));
      }
    }
  }
};

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 已提交
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
    // TODO(chengduo): Paddings can be added in future.
    // groups will alway be disabled in conv3dtranspose.

    const int batch_size = input->dims()[0];
    const int m = input->dims()[1];
    const int d = input->dims()[2];
    const int h = input->dims()[3];
    const int w = input->dims()[4];

    const int k_d = filter.dims()[2];
    const int k_h = filter.dims()[3];
    const int k_w = filter.dims()[4];

    const int c = output->dims()[1];  // output channels
    const int o_d = output->dims()[2];
    const int o_h = output->dims()[3];
    const int o_w = output->dims()[4];

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

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

    // convolution transpose: gemm + col2vol (similar to conv-backward on input)

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

    for (int i = 0; i < batch_size; i++) {
      // batch with size (M, d * h * w)
      Tensor input_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);
      // filter size: (M, c * k_d * k_h * k_w)

      // 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,
                             input_batch, false, T(1.0), &col_matrix, T(0.0));
      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");

    const int batch_size = input->dims()[0];
    const int m = input->dims()[1];
    const int d = input->dims()[2];
    const int h = input->dims()[3];
    const int w = input->dims()[4];

    const int k_d = filter.dims()[2];
    const int k_h = filter.dims()[3];
    const int k_w = filter.dims()[4];

    const int c = output_grad->dims()[1];  // output channels
    const int o_d = output_grad->dims()[2];
    const int o_h = output_grad->dims()[3];
    const int o_w = output_grad->dims()[4];

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

    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.

    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
    if (input_grad) {
      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);

      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++) {
        // batch with size (c, o_d * o_h * o_w)
        Tensor output_grad_batch =
            output_grad->Slice(i, i + 1).Resize(output_shape);
        // filter of size (m, c * k_d * k_h * k_w)

        // batch with size (m, d, h, w)
        Tensor input_grad_batch =
            input_grad->Slice(i, i + 1).Resize(input_matrix_shape);

        // vol2col: dy from (c, o_d, o_h, o_w) -> (c * k_d * k_h * k_w, d * h *
        // w)
        vol2col(context.device_context(), output_grad_batch, col, strides[0],
                strides[1], strides[2], paddings[0], paddings[1], paddings[2]);

        // gemm: dx = filter * dy
        // (m, c *k_d *  k_h * k_w) * (c * k_d * k_h * k_w, d* h * w) -> (m, c,
        // d, h, w)
        math::matmul<Place, T>(context.device_context(), filter, false,
                               col_matrix, false, T(1.0), &input_grad_batch,
                               T(0.0));
      }
    }

    // filter gradient required
    if (filter_grad) {
      Tensor col_matrix_f;
      col_matrix_f.ShareDataWith(col);
      DDim col_matrix_shape_f = {c * d * h * w, k_d * k_h * k_w};
      col_matrix_f.Resize(col_matrix_shape_f);

      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) {
        // batch with size (c, o_d, o_h, o_w)
        Tensor output_grad_batch =
            output_grad->Slice(i, i + 1).Resize(output_shape);
        // input batch
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);

        // vol2col: (c * d * h * w, k_d * k_h * k_w)
        vol2col(context.device_context(), output_grad_batch, col, strides[0],
                strides[1], strides[2], paddings[0], paddings[1], paddings[2]);

        // gemm: d_filter = x * y_grad^T
        // (m, c * d * h * w) * (k_d * k_h * k_w, c * d * h * w) -> (m, c, d, h,
        // w)
        math::matmul<Place, T>(context.device_context(), in_batch, false,
                               col_matrix_f, true, T(1.0), &filter_grad_,
                               T(1.0));
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle