conv_transpose_op_mlu.cc 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.

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. */

#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/conv_transpose_op.h"
#include "paddle/fluid/operators/mlu/mlu_baseop.h"
#include "paddle/phi/kernels/cpu/conv_util.h"

namespace paddle {
namespace operators {

23
using DataLayout = phi::DataLayout;
24 25 26 27 28

template <typename T>
class Conv2DTransposeMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
29 30 31
    const phi::DenseTensor* input = ctx.Input<phi::DenseTensor>("Input");
    const phi::DenseTensor* filter = ctx.Input<phi::DenseTensor>("Filter");
    phi::DenseTensor* output = ctx.Output<phi::DenseTensor>("Output");
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    output->mutable_data<T>(ctx.GetPlace());
    std::vector<int> output_padding =
        ctx.Attr<std::vector<int>>("output_padding");
    const std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
    std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");
    const std::string data_format = ctx.Attr<std::string>("data_format");
    int groups = ctx.Attr<int>("groups");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");

    // check dimension
    const bool channel_last = data_format == "NHWC";

    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    auto in_dims_size = in_dims.size();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    if (channel_last) {
      in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
    } else {
      in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
    }
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());

    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
60 61
    phi::UpdatePaddingAndDilation(
        &paddings, &dilations, padding_algorithm, in_data_dims, strides, ksize);
62

63 64
    phi::DenseTensor input_tensor(input->type());
    phi::DenseTensor output_tensor(output->type());
65 66 67 68 69 70 71 72 73
    input_tensor.set_layout(DataLayout::kNHWC);
    output_tensor.set_layout(DataLayout::kNHWC);
    const std::vector<int> perm_to_nhwc = {0, 2, 3, 1};

    if (channel_last) {
      input_tensor.ShareDataWith(*input);
      output_tensor.ShareDataWith(*output);
    } else {
      // transpose input from NCHW to NHWC
74 75 76 77
      TransposeFromMLUTensor<T>(ctx,
                                perm_to_nhwc,
                                input,
                                &input_tensor,
78 79 80 81 82 83 84 85
                                true /*need_reshape_or_alloc*/);
      auto output_dims = output->dims();
      output_tensor.mutable_data<T>(
          {output_dims[0], output_dims[2], output_dims[3], output_dims[1]},
          ctx.GetPlace());
    }

    // transpose filter from MCHW to MHWC
86
    phi::DenseTensor trans_filter(filter->type());
87 88 89 90
    TransposeFromMLUTensor<T>(ctx,
                              perm_to_nhwc,
                              filter,
                              &trans_filter,
91 92 93 94
                              true /*need_reshape_or_alloc*/);

    // construct MLU attr
    cnnlTensorLayout_t data_layout = CNNL_LAYOUT_NHWC;
95 96 97 98 99 100 101 102 103 104 105
    MLUCnnlTensorDesc input_desc(
        input_tensor, data_layout, ToCnnlDataType(input_tensor.dtype()));
    MLUCnnlTensorDesc filter_desc(
        trans_filter, data_layout, ToCnnlDataType(trans_filter.type()));
    MLUCnnlTensorDesc output_desc(
        output_tensor, data_layout, ToCnnlDataType(output_tensor.dtype()));
    MLUCnnlConvolutionDesc conv_desc(in_dims_size,
                                     paddings.data(),
                                     strides.data(),
                                     dilations.data(),
                                     groups,
106 107
                                     ToCnnlDataType<T>());

108 109 110 111 112 113 114
    MLUCnnl::ConvBackpropInput(ctx,
                               conv_desc.get(),
                               filter_desc.get(),
                               GetBasePtr(&trans_filter),
                               input_desc.get(),
                               GetBasePtr(&input_tensor),
                               output_desc.get(),
115 116 117 118 119
                               GetBasePtr(&output_tensor));

    if (!channel_last) {
      // transpose output from NHWC to NCHW
      const std::vector<int> perm_to_nchw = {0, 3, 1, 2};
120 121 122 123
      TransposeFromMLUTensor<T>(ctx,
                                perm_to_nchw,
                                &output_tensor,
                                output,
124 125 126 127 128 129 130 131 132
                                false /*need_reshape_or_alloc*/);
    }
  }
};

template <typename T>
class Conv2DTransposeGradMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
133 134 135 136 137 138 139 140
    const phi::DenseTensor* input = ctx.Input<phi::DenseTensor>("Input");
    const phi::DenseTensor* filter = ctx.Input<phi::DenseTensor>("Filter");
    const phi::DenseTensor* output_grad =
        ctx.Input<phi::DenseTensor>(framework::GradVarName("Output"));
    phi::DenseTensor* input_grad =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Input"));
    phi::DenseTensor* filter_grad =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Filter"));
141 142 143 144 145 146 147 148 149

    if ((!input_grad) && (!filter_grad)) return;

    std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
    std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");
    const int groups = ctx.Attr<int>("groups");
    std::string padding_algorithm = ctx.Attr<std::string>("padding_algorithm");
    const std::string data_format = ctx.Attr<std::string>("data_format");
150
    const phi::DataLayout data_layout = phi::StringToDataLayout(data_format);
151 152 153 154 155

    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    auto in_dims_size = in_dims.size();

156
    const bool channel_last = (data_layout == phi::DataLayout::kNHWC);
157 158 159 160 161 162 163 164 165 166

    framework::DDim in_data_dims;
    if (channel_last) {
      in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
    } else {
      in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
    }
    framework::DDim filter_data_dims =
        phi::slice_ddim(filter_dims, 2, filter_dims.size());
    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
167 168
    phi::UpdatePaddingAndDilation(
        &paddings, &dilations, padding_algorithm, in_data_dims, strides, ksize);
169

170 171
    phi::DenseTensor input_tensor(input->type());
    phi::DenseTensor output_grad_tensor(output_grad->type());
172 173 174 175 176 177 178 179
    output_grad_tensor.set_layout(DataLayout::kNHWC);

    const std::vector<int> perm_to_nhwc = {0, 2, 3, 1};
    if (channel_last) {
      input_tensor.ShareDataWith(*input);
      output_grad_tensor.ShareDataWith(*output_grad);
    } else {
      // transpose input from NCHW to NHWC
180 181 182 183
      TransposeFromMLUTensor<T>(ctx,
                                perm_to_nhwc,
                                input,
                                &input_tensor,
184
                                true /*need_reshape_or_alloc*/);
185 186 187
      TransposeFromMLUTensor<T>(ctx,
                                perm_to_nhwc,
                                output_grad,
188 189 190 191 192
                                &output_grad_tensor,
                                true /*need_reshape_or_alloc*/);
    }

    // transpose filter from MCHW to MHWC
193
    phi::DenseTensor trans_filter(filter->type());
194 195 196 197
    TransposeFromMLUTensor<T>(ctx,
                              perm_to_nhwc,
                              filter,
                              &trans_filter,
198 199 200 201
                              true /*need_reshape_or_alloc*/);

    // MLU descs
    cnnlTensorLayout_t data_layout_mlu = CNNL_LAYOUT_NHWC;
202 203 204 205
    MLUCnnlTensorDesc input_desc(
        input_tensor, data_layout_mlu, ToCnnlDataType(input_tensor.dtype()));
    MLUCnnlTensorDesc trans_filter_desc(
        trans_filter, data_layout_mlu, ToCnnlDataType(trans_filter.type()));
206
    MLUCnnlTensorDesc output_grad_desc(
207 208
        output_grad_tensor,
        data_layout_mlu,
209
        ToCnnlDataType(output_grad_tensor.dtype()));
210 211 212 213 214
    MLUCnnlConvolutionDesc conv_desc(in_dims_size,
                                     paddings.data(),
                                     strides.data(),
                                     dilations.data(),
                                     groups,
215 216 217 218
                                     ToCnnlDataType<T>());

    if (filter_grad) {
      filter_grad->mutable_data<T>(ctx.GetPlace());
219
      phi::DenseTensor filter_grad_tensor(filter_grad->type());
220 221 222
      // filter_grad always MCHW
      // filter_grad_tensor always MHWC
      auto filter_grad_dims = filter_grad->dims();
223 224 225 226 227
      filter_grad_tensor.mutable_data<T>({filter_grad_dims[0],
                                          filter_grad_dims[2],
                                          filter_grad_dims[3],
                                          filter_grad_dims[1]},
                                         ctx.GetPlace());
228 229 230 231
      //}
      filter_grad_tensor.set_layout(DataLayout::kNHWC);

      MLUCnnlTensorDesc filter_grad_desc(
232 233
          filter_grad_tensor,
          data_layout_mlu,
234 235
          ToCnnlDataType(filter_grad_tensor.dtype()));

236 237 238 239 240 241 242 243
      MLUCnnl::ConvBackpropFilter(ctx,
                                  conv_desc.get(),
                                  output_grad_desc.get(),
                                  GetBasePtr(output_grad),
                                  input_desc.get(),
                                  GetBasePtr(&input_tensor),
                                  filter_grad_desc.get(),
                                  GetBasePtr(&filter_grad_tensor));
244 245
      // transpose output from MHWC to MCHW
      const std::vector<int> perm_to_mchw = {0, 3, 1, 2};
246 247 248 249 250
      TransposeFromMLUTensor<T>(ctx,
                                perm_to_mchw,
                                &filter_grad_tensor,
                                filter_grad,
                                false /*need_reshape_or_alloc*/);
251 252 253 254
    }

    if (input_grad) {
      input_grad->mutable_data<T>(ctx.GetPlace());
255
      phi::DenseTensor input_grad_tensor(input_grad->type());
256 257 258 259 260 261
      input_tensor.set_layout(DataLayout::kNHWC);

      if (channel_last) {
        input_grad_tensor.ShareDataWith(*input_grad);
      } else {
        auto input_grad_dims = input_grad->dims();
262 263 264 265 266
        input_grad_tensor.mutable_data<T>({input_grad_dims[0],
                                           input_grad_dims[2],
                                           input_grad_dims[3],
                                           input_grad_dims[1]},
                                          ctx.GetPlace());
267 268 269
      }

      MLUCnnlTensorDesc input_grad_desc(
270 271
          input_grad_tensor,
          data_layout_mlu,
272 273
          ToCnnlDataType(input_grad_tensor.dtype()));

274 275 276 277 278 279 280 281 282 283 284 285
      MLUCnnl::ConvolutionForward(ctx,
                                  conv_desc.get(),
                                  nullptr /*alpha*/,
                                  nullptr /*beta*/,
                                  nullptr /*bias_desc*/,
                                  nullptr /*bias_ptr*/,
                                  output_grad_desc.get(),
                                  GetBasePtr(&output_grad_tensor),
                                  trans_filter_desc.get(),
                                  GetBasePtr(&trans_filter),
                                  input_grad_desc.get(),
                                  GetBasePtr(&input_grad_tensor));
286 287 288
      if (!channel_last) {
        // transpose output from NHWC to NCHW
        const std::vector<int> perm_to_nchw = {0, 3, 1, 2};
289 290 291 292 293
        TransposeFromMLUTensor<T>(ctx,
                                  perm_to_nchw,
                                  &input_grad_tensor,
                                  input_grad,
                                  false /*need_reshape_or_alloc*/);
294 295 296 297 298 299 300 301 302 303 304
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

305 306
REGISTER_OP_MLU_KERNEL(conv2d_transpose,
                       ops::Conv2DTransposeMLUKernel<float>,
307 308 309 310 311
                       ops::Conv2DTransposeMLUKernel<plat::float16>);

REGISTER_OP_MLU_KERNEL(conv2d_transpose_grad,
                       ops::Conv2DTransposeGradMLUKernel<float>,
                       ops::Conv2DTransposeGradMLUKernel<plat::float16>);