conv2dtranspose_op.h 9.1 KB
Newer Older
Z
deconv  
zchen0211 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* 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"
#include "paddle/operators/math/im2col.h"
#include "paddle/operators/math/math_function.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
Z
zchen0211 已提交
26
using DDim = framework::DDim;
Z
deconv  
zchen0211 已提交
27

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

Z
deconv  
zchen0211 已提交
36
class Conv2DTransposeOp : public framework::OperatorWithKernel {
Z
deconv  
zchen0211 已提交
37 38 39 40 41 42 43
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

Z
deconv  
zchen0211 已提交
44
class Conv2DTransposeOpGrad : public framework::OperatorWithKernel {
Z
deconv  
zchen0211 已提交
45 46 47 48 49 50 51
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

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

Z
zchen0211 已提交
52
template <typename Place, typename T>
Z
deconv  
zchen0211 已提交
53
class GemmConv2DTransposeKernel : public framework::OpKernel<T> {
Z
zchen0211 已提交
54 55 56
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const Tensor* input = context.Input<Tensor>("Input");
Z
zchen0211 已提交
57
    // The filter will be reshaped, so it should not be constant pointer
Z
zchen0211 已提交
58 59 60 61 62 63
    Tensor filter = *context.Input<Tensor>("Filter");

    Tensor* output = context.Output<Tensor>("Output");

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

Z
zchen0211 已提交
64 65
    // TODO(Zhuoyuan): Paddings can be added in future.
    // groups will alway be disabled in conv2dtranspose.
Z
zchen0211 已提交
66

Z
deconv  
zchen0211 已提交
67 68 69 70
    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];
Z
zchen0211 已提交
71

Z
deconv  
zchen0211 已提交
72 73
    const int k_h = filter.dims()[2];
    const int k_w = filter.dims()[3];
Z
zchen0211 已提交
74

Z
deconv  
zchen0211 已提交
75 76 77
    const int c = output->dims()[1];  // output channels
    const int o_h = output->dims()[2];
    const int o_w = output->dims()[3];
Z
zchen0211 已提交
78 79 80 81 82 83

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

    // use col_shape in the im2col and col2im calculation
Z
deconv  
zchen0211 已提交
84
    DDim col_shape = {c, k_h, k_w, h, w};
Z
zchen0211 已提交
85 86

    // use col_matrix_shape in the gemm calculation
Z
deconv  
zchen0211 已提交
87
    DDim col_matrix_shape = {c * k_h * k_w, h * w};
Z
zchen0211 已提交
88 89 90 91 92 93

    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.
Z
zchen0211 已提交
94 95
    Tensor col_matrix;
    col_matrix.ShareDataWith(col);
Z
zchen0211 已提交
96 97
    col_matrix.Resize(col_matrix_shape);

Z
deconv  
zchen0211 已提交
98 99
    DDim output_shape = {c, o_h, o_w};
    DDim input_matrix_shape = {m, h * w};
Z
zchen0211 已提交
100

Z
deconv  
zchen0211 已提交
101
    DDim filter_matrix_shape = {m, c * k_h * k_w};
Z
zchen0211 已提交
102 103
    filter.Resize(filter_matrix_shape);

Z
zchen0211 已提交
104
    // convolution transpose: gemm + col2im (similar to conv-backward on input)
Z
zchen0211 已提交
105 106 107 108 109

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

Z
deconv  
zchen0211 已提交
110 111 112 113
    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)
Z
deconv  
zchen0211 已提交
114

Z
deconv  
zchen0211 已提交
115 116
      // output size: (c, o_h, o_w)
      Tensor output_batch = output->Slice(i, i + 1).Resize(output_shape);
Z
zchen0211 已提交
117 118

      // col_matrix = filter * input_batch
Z
deconv  
zchen0211 已提交
119
      // of shape (c * k_h * k_w, h * w)
Z
zchen0211 已提交
120 121
      math::matmul<Place, T>(context.device_context(), filter, true,
                             input_batch, false, T(1.0), &col_matrix, T(0.0));
Z
deconv  
zchen0211 已提交
122
      col2im(context.device_context(), output_batch, col, strides[0],
C
chengduoZH 已提交
123
             strides[1], 0, 0, 0, 0);
Z
zchen0211 已提交
124 125 126 127 128
    }
  }
};

template <typename Place, typename T>
Z
deconv  
zchen0211 已提交
129
class GemmConv2DTransposeGradKernel : public framework::OpKernel<T> {
Z
zchen0211 已提交
130 131 132 133 134 135
 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"));

Z
zchen0211 已提交
136 137
    // For filter, we do not use const pointer b/c we will do reshape,
    // but we should avoid modifying its value.
Z
zchen0211 已提交
138 139 140 141 142 143 144 145
    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");
Z
zchen0211 已提交
146
    // Actually, no paddings and groups allowed in conv transpose.
Z
deconv  
zchen0211 已提交
147
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
Z
zchen0211 已提交
148

Z
deconv  
zchen0211 已提交
149 150 151 152
    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];
Z
zchen0211 已提交
153

Z
deconv  
zchen0211 已提交
154 155
    const int k_h = filter.dims()[2];
    const int k_w = filter.dims()[3];
Z
zchen0211 已提交
156

Z
deconv  
zchen0211 已提交
157 158 159
    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];
Z
zchen0211 已提交
160

Z
deconv  
zchen0211 已提交
161
    // Only im2col functor required for bp to get to the right shape
Z
deconv  
zchen0211 已提交
162 163 164
    paddle::operators::math::Im2ColFunctor<
        paddle::operators::math::ColFormat::kCFO, Place, T>
        im2col;
Z
zchen0211 已提交
165 166

    // use col_shape in the im2col and col2im calculation
Z
deconv  
zchen0211 已提交
167
    DDim col_shape = {c, k_h, k_w, h, w};
Z
zchen0211 已提交
168 169

    // use col_matrix_shape in the gemm calculation
Z
deconv  
zchen0211 已提交
170
    DDim col_matrix_shape_f = {c * h * w, k_h * k_w};
Z
zchen0211 已提交
171 172 173 174 175 176 177

    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.

Z
deconv  
zchen0211 已提交
178 179
    DDim output_shape = {c, o_h, o_w};
    DDim input_matrix_shape = {m, h * w};
Z
zchen0211 已提交
180

Z
deconv  
zchen0211 已提交
181
    DDim filter_matrix_shape = {m, c * k_h * k_w};
Z
zchen0211 已提交
182 183
    filter.Resize(filter_matrix_shape);

Z
zchen0211 已提交
184
    // convolution transpose grad on input:
Z
deconv  
zchen0211 已提交
185 186 187
    // im2col + gemm (similar to conv-forward)
    // input need to compute gradient
    if (input_grad) {
Z
zchen0211 已提交
188 189
      Tensor col_matrix;
      col_matrix.ShareDataWith(col);
Z
deconv  
zchen0211 已提交
190
      DDim col_matrix_shape = {c * k_h * k_w, h * w};
Z
deconv  
zchen0211 已提交
191 192
      col_matrix.Resize(col_matrix_shape);

Z
deconv  
zchen0211 已提交
193 194 195 196
      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));

Z
deconv  
zchen0211 已提交
197 198
      for (int i = 0; i < batch_size; i++) {
        // batch with size (c, o_h * o_w)
Z
deconv  
zchen0211 已提交
199
        Tensor output_grad_batch =
Z
deconv  
zchen0211 已提交
200 201
            output_grad->Slice(i, i + 1).Resize(output_shape);
        // filter of size (m, c * k_h * k_w)
Z
deconv  
zchen0211 已提交
202

Z
deconv  
zchen0211 已提交
203
        // batch with size (m, h, w)
Z
deconv  
zchen0211 已提交
204
        Tensor input_grad_batch =
Z
deconv  
zchen0211 已提交
205
            input_grad->Slice(i, i + 1).Resize(input_matrix_shape);
Z
deconv  
zchen0211 已提交
206

Z
deconv  
zchen0211 已提交
207
        // im2col: dy from (c, o_h, o_w) -> (c * k_h * k_w, h * w)
Z
deconv  
zchen0211 已提交
208
        im2col(context.device_context(), output_grad_batch, col, strides[0],
C
chengduoZH 已提交
209
               strides[1], paddings[0], paddings[0], paddings[1], paddings[1]);
Z
deconv  
zchen0211 已提交
210

Z
deconv  
zchen0211 已提交
211
        // gemm: dx = filter * dy
Z
deconv  
zchen0211 已提交
212
        // (m, c * k_h * k_w) * (c * k_h * k_w, h * w) -> (m, c, h)
Z
deconv  
zchen0211 已提交
213 214 215 216 217
        math::matmul<Place, T>(context.device_context(), filter, false,
                               col_matrix, false, T(1.0), &input_grad_batch,
                               T(0.0));
      }
    }
Z
zchen0211 已提交
218

Z
deconv  
zchen0211 已提交
219 220
    // filter gradient required
    if (filter_grad) {
Z
zchen0211 已提交
221 222
      Tensor col_matrix_f;
      col_matrix_f.ShareDataWith(col);
Z
deconv  
zchen0211 已提交
223
      DDim col_matrix_shape_f = {c * h * w, k_h * k_w};
Z
deconv  
zchen0211 已提交
224 225
      col_matrix_f.Resize(col_matrix_shape_f);

Z
deconv  
zchen0211 已提交
226 227 228 229 230 231
      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));

Z
deconv  
zchen0211 已提交
232 233
      for (int i = 0; i < batch_size; ++i) {
        // batch with size (c, o_h, o_w)
Z
deconv  
zchen0211 已提交
234
        Tensor output_grad_batch =
Z
deconv  
zchen0211 已提交
235
            output_grad->Slice(i, i + 1).Resize(output_shape);
Z
deconv  
zchen0211 已提交
236
        // input batch
Z
deconv  
zchen0211 已提交
237
        Tensor in_batch = input->Slice(i, i + 1).Resize(input_matrix_shape);
Z
deconv  
zchen0211 已提交
238

Z
deconv  
zchen0211 已提交
239
        // im2col: (c * h * w, k_h * k_w)
Z
deconv  
zchen0211 已提交
240
        im2col(context.device_context(), output_grad_batch, col, strides[0],
C
chengduoZH 已提交
241
               strides[1], paddings[0], paddings[0], paddings[1], paddings[1]);
Z
deconv  
zchen0211 已提交
242

Z
deconv  
zchen0211 已提交
243
        // gemm: d_filter = x * y_grad^T
Z
deconv  
zchen0211 已提交
244
        // (m, c * h * w) * (k_h * k_w, c * h * w) -> (m, c, h)
Z
deconv  
zchen0211 已提交
245
        math::matmul<Place, T>(context.device_context(), in_batch, false,
Z
deconv  
zchen0211 已提交
246 247
                               col_matrix_f, true, T(1.0), &filter_grad_,
                               T(1.0));
Z
deconv  
zchen0211 已提交
248
      }
Z
zchen0211 已提交
249 250 251 252
    }
  }
};

Z
deconv  
zchen0211 已提交
253 254
}  // namespace operators
}  // namespace paddle