transpose_op.cc 12.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
X
xzl 已提交
2

L
Luo Tao 已提交
3 4 5
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
X
xzl 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
X
xzl 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
X
xzl 已提交
14

15
#include <memory>
16
#include <string>
17
#include <vector>
X
xzl 已提交
18

19 20 21 22
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/unary.h"

23 24 25
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
26
#include "paddle/fluid/framework/op_registry.h"
27

X
xzl 已提交
28 29 30 31 32 33 34
namespace paddle {
namespace operators {

class TransposeOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

35
  void InferShape(framework::InferShapeContext *ctx) const override {
36 37
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Transpose");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Transpose");
Q
Qiao Longfei 已提交
38 39
    auto x_dims = ctx->GetInputDim("X");
    std::vector<int> axis = ctx->Attrs().Get<std::vector<int>>("axis");
40

X
xzl 已提交
41
    size_t x_rank = x_dims.size();
X
xzl 已提交
42
    size_t axis_size = axis.size();
X
xzl 已提交
43

44 45 46
    // Note: x_rank > axis_size when fuse squeeze2 + transpose2, else x_rank ==
    // axis_size
    PADDLE_ENFORCE_GE(x_rank,
47
                      axis_size,
48 49
                      platform::errors::InvalidArgument(
                          "The input tensor's dimension "
50
                          "should be equal to or greater than the axis's size. "
51 52
                          "But received input tensor's dimension is %d, "
                          "axis's size is %d",
53 54
                          x_rank,
                          axis_size));
55 56 57

    std::vector<int> count(axis_size, 0);
    for (size_t i = 0; i < axis_size; i++) {
58 59
      PADDLE_ENFORCE_GE(axis[i],
                        0,
60 61 62
                        platform::errors::InvalidArgument(
                            "The axis should be greater than or equal to 0."
                            "But received %d of axis[%d]",
63 64
                            axis[i],
                            i));
65

66
      PADDLE_ENFORCE_EQ(
67 68
          axis[i] < static_cast<int>(axis_size) && ++count[axis[i]] == 1,
          true,
69 70 71 72 73 74 75
          platform::errors::InvalidArgument(
              "Each element of Attribute axis should "
              "be a unique value range from 0 to (dims - 1), "
              "where the dims is the axis's size, "
              "unique value means this axis value can appear only once. "
              "But received axis[%d] is %d, axis_size is %d, "
              "count[axis[%d]] is %d",
76 77 78 79 80
              i,
              axis[i],
              axis_size,
              i,
              count[axis[i]]));
X
xzl 已提交
81
    }
X
xzl 已提交
82

X
xzl 已提交
83
    framework::DDim out_dims(x_dims);
J
Jacek Czaja 已提交
84 85 86
#ifdef PADDLE_WITH_MKLDNN
    // Here we need to match dims to paddle layout
    // as we are producing non-oneDNN result
87
    if (ctx->IsRunMKLDNNKernel() && (x_dims.size() >= 3) &&
88 89
        (phi::OneDNNContext::tls().get_cur_paddle_data_layout() ==
         phi::DataLayout::kNHWC)) {
90
      auto dims = phi::vectorize<int>(x_dims);
J
Jacek Czaja 已提交
91 92 93 94 95 96
      std::rotate(dims.begin() + 1, dims.begin() + 2, dims.end());
      x_dims = x_dims.reshape(dims);
      VLOG(3)
          << "Rotating Shape in Transpose from: kMKLDNN to: kNHWC output_shape";
    }
#endif
97
    for (size_t i = 0; i < axis_size; i++) {
X
xzl 已提交
98
      out_dims[i] = x_dims[axis[i]];
X
xzl 已提交
99
    }
Q
Qiao Longfei 已提交
100
    ctx->SetOutputDim("Out", out_dims);
X
xzl 已提交
101
  }
102 103

 protected:
104
  phi::KernelKey GetExpectedKernelType(
105
      const framework::ExecutionContext &ctx) const override {
106
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
J
jiahongyu 已提交
107
    auto &data_format = ctx.Attr<std::string>("data_format");
108
    phi::DataLayout layout_ = phi::StringToDataLayout(data_format);
109 110
    return phi::KernelKey(
        ctx.GetPlace(), layout_, phi::TransToPhiDataType(data_type));
111
  }
X
xzl 已提交
112 113 114 115
};

class TransposeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
116
  void Make() override {
117
    AddInput(
X
xzl 已提交
118
        "X",
119 120
        "(Tensor) The input tensor, tensors with rank up to 6 are supported.");
    AddOutput("Out", "(Tensor)The output tensor.");
X
xzl 已提交
121 122
    AddAttr<std::vector<int>>(
        "axis",
123 124 125
        "(vector<int>) A list of values, and the size of the list should be "
        "the same with the input tensor rank. This operator permutes the input "
        "tensor's axes according to the values given.");
126 127
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
128 129
        .SetDefault(false)
        .AsExtra();
130 131 132 133 134 135
    AddAttr<std::string>(
        "data_format",
        "(string, default NCHW) Only used in "
        "An optional string from: \"NHWC\", \"NCHW\". "
        "Defaults to \"NHWC\". Specify the data format of the output data, "
        "the input will be transformed automatically. ")
136 137
        .SetDefault("AnyLayout")
        .AsExtra();
138 139 140 141
    AddAttr<bool>(
        "use_quantizer",
        "(bool, default false) "
        "This parameter is no longer used. Use 'mkldnn_data_type' instead.")
142 143
        .SetDefault(false)
        .AsExtra();
144 145 146 147
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
148 149
        .InEnum({"float32", "int8", "bfloat16"})
        .AsExtra();
150
    /* int8 parameters */
X
xzl 已提交
151
    AddComment(R"DOC(
152 153
Transpose Operator.

154 155
The input tensor will be permuted according to the axes given.
The behavior of this operator is similar to how `numpy.transpose` works.
Y
ying 已提交
156

157 158 159 160 161 162
- suppose the input `X` is a 2-D tensor:
    $$
    X = \begin{pmatrix}
    0 &1 &2 \\
    3 &4 &5
    \end{pmatrix}$$
W
wanghaoshuang 已提交
163

164
    the given `axes` is: $[1, 0]$, and $Y$ = transpose($X$, axis)
W
wanghaoshuang 已提交
165

166
    then the output $Y$ is:
W
wanghaoshuang 已提交
167

168 169 170 171 172 173
    $$
    Y = \begin{pmatrix}
         0 &3 \\
         1 &4  \\
         2 &5
    \end{pmatrix}$$
W
wanghaoshuang 已提交
174

175
- Given a input tensor with shape $(N, C, H, W)$ and the `axes` is
176
$[0, 2, 3, 1]$, then shape of the output tensor will be: $(N, H, W, C)$.
177

X
xzl 已提交
178 179 180 181 182 183 184 185
)DOC");
  }
};

class TransposeOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

186
 protected:
187
  phi::KernelKey GetExpectedKernelType(
188
      const framework::ExecutionContext &ctx) const override {
189 190
    auto data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
J
jiahongyu 已提交
191
    std::string data_format = ctx.Attr<std::string>("data_format");
192
    phi::DataLayout layout_ = phi::StringToDataLayout(data_format);
193 194
    return phi::KernelKey(
        ctx.GetPlace(), layout_, phi::TransToPhiDataType(data_type));
195
  }
X
xzl 已提交
196 197
};

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
// FIXME(zcd): transpose2 adds an intermediate output(XShape) based on
// transpose, the XShape is used to carry the shape and lod of X which
// will be used in transpose_grad, in this way, the framework can reuse
// the memory of X immediately the transpose2_op is finished.
// Considering compatibility issues, we could not fix transpose2_op
class Transpose2Op : public TransposeOp {
 public:
  Transpose2Op(const std::string &type,
               const framework::VariableNameMap &inputs,
               const framework::VariableNameMap &outputs,
               const framework::AttributeMap &attrs)
      : TransposeOp(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
    TransposeOp::InferShape(ctx);
213
    if (!ctx->HasOutput("XShape")) return;
214 215 216 217 218 219
    const auto &in_dims = ctx->GetInputDim("X");
    std::vector<int64_t> x_shape_dim(in_dims.size() + 1);
    x_shape_dim[0] = 0;
    for (int i = 0; i < in_dims.size(); ++i) {
      x_shape_dim[i + 1] = in_dims[i];
    }
220
    ctx->SetOutputDim("XShape", phi::make_ddim(x_shape_dim));
221 222 223 224
    ctx->ShareLoD("X", /*->*/ "XShape");
  }

 protected:
225
  phi::KernelKey GetExpectedKernelType(
226
      const framework::ExecutionContext &ctx) const override {
227 228
    framework::proto::VarType::Type data_type =
        OperatorWithKernel::IndicateVarDataType(ctx, "X");
J
jiahongyu 已提交
229
    std::string data_format = ctx.Attr<std::string>("data_format");
230
    phi::DataLayout layout_ = phi::StringToDataLayout(data_format);
231 232
    return phi::KernelKey(
        ctx.GetPlace(), layout_, phi::TransToPhiDataType(data_type));
233 234 235
  }
};

236
class Transpose2OpMaker : public framework::OpProtoAndCheckerMaker {
237 238
 public:
  void Make() override {
239 240 241 242 243 244 245 246 247
    AddInput(
        "X",
        "(Tensor) The input tensor, tensors with rank up to 6 are supported.");
    AddOutput("Out", "(Tensor)The output tensor.");
    AddAttr<std::vector<int>>(
        "axis",
        "(vector<int>) A list of values, and the size of the list should be "
        "the same with the input tensor rank. This operator permutes the input "
        "tensor's axes according to the values given.");
248 249 250
    AddOutput("XShape", "(Tensor)The output tensor.")
        .AsIntermediate()
        .AsExtra();
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    AddComment(R"DOC(
Transpose Operator.

The input tensor will be permuted according to the axes given.
The behavior of this operator is similar to how `numpy.transpose` works.

- suppose the input `X` is a 2-D tensor:
    $$
    X = \begin{pmatrix}
    0 &1 &2 \\
    3 &4 &5
    \end{pmatrix}$$

    the given `axes` is: $[1, 0]$, and $Y$ = transpose($X$, axis)

    then the output $Y$ is:

    $$
    Y = \begin{pmatrix}
         0 &3 \\
         1 &4  \\
         2 &5
    \end{pmatrix}$$

- Given a input tensor with shape $(N, C, H, W)$ and the `axes` is
$[0, 2, 3, 1]$, then shape of the output tensor will be: $(N, H, W, C)$.

)DOC");
279 280 281
  }
};

H
hong 已提交
282 283
template <typename T>
class Transpose2GradMaker : public framework::SingleGradOpMaker<T> {
284
 public:
H
hong 已提交
285
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
286

287
  void Apply(GradOpPtr<T> grad_op) const override {
288
    grad_op->SetType("transpose2_grad");
H
hong 已提交
289 290 291 292
    grad_op->SetInput("XShape", this->Output("XShape"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
293 294 295
  }
};

296 297 298 299 300 301 302 303 304 305 306 307 308 309
template <typename T>
class Transpose2DoubleGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

  void Apply(GradOpPtr<T> grad_op) const override {
    grad_op->SetType("transpose2");
    grad_op->SetInput("X", this->OutputGrad(framework::GradVarName("X")));
    grad_op->SetOutput("Out", this->InputGrad(framework::GradVarName("Out")));
    grad_op->SetOutput("XShape", this->Input("XShape"));
    grad_op->SetAttrMap(this->Attrs());
  }
};

310 311 312 313 314
class Transpose2OpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
315
  phi::KernelKey GetExpectedKernelType(
316
      const framework::ExecutionContext &ctx) const override {
317 318 319
    framework::proto::VarType::Type data_type =
        OperatorWithKernel::IndicateVarDataType(ctx,
                                                framework::GradVarName("Out"));
J
jiahongyu 已提交
320
    std::string data_format = ctx.Attr<std::string>("data_format");
321
    phi::DataLayout layout_ = phi::StringToDataLayout(data_format);
322 323
    return phi::KernelKey(
        ctx.GetPlace(), layout_, phi::TransToPhiDataType(data_type));
324 325 326
  }
};

H
hong 已提交
327 328 329 330 331 332 333 334
class TransposeGradInferVarType : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext *ctx) const override {
    ctx->SyncTypeAndDataType(framework::GradVarName("Out"),
                             framework::GradVarName("X"));
  }
};

X
xzl 已提交
335 336 337
}  // namespace operators
}  // namespace paddle

338 339 340 341 342 343 344
DECLARE_INFER_SHAPE_FUNCTOR(transpose_grad,
                            TransposeGradInferShapeFunctor,
                            PD_INFER_META(phi::TransposeGradInferMeta));

DECLARE_INFER_SHAPE_FUNCTOR(transpose2_grad,
                            Transpose2GradInferShapeFunctor,
                            PD_INFER_META(phi::TransposeGradInferMeta));
X
xzl 已提交
345
namespace ops = paddle::operators;
H
hong 已提交
346
REGISTER_OPERATOR(
347 348 349
    transpose,
    ops::TransposeOp,
    ops::TransposeOpMaker,
H
hong 已提交
350 351
    paddle::framework::DefaultGradOpMaker<paddle::framework::OpDesc, true>,
    paddle::framework::DefaultGradOpMaker<paddle::imperative::OpBase, true>);
352 353
REGISTER_OPERATOR(transpose_grad,
                  ops::TransposeOpGrad,
354 355
                  ops::TransposeGradInferVarType,
                  TransposeGradInferShapeFunctor);
356

357 358 359
REGISTER_OPERATOR(transpose2,
                  ops::Transpose2Op,
                  ops::Transpose2OpMaker,
H
hong 已提交
360 361
                  ops::Transpose2GradMaker<paddle::framework::OpDesc>,
                  ops::Transpose2GradMaker<paddle::imperative::OpBase>);
362 363
REGISTER_OPERATOR(transpose2_grad,
                  ops::Transpose2OpGrad,
H
hong 已提交
364
                  ops::TransposeGradInferVarType,
365
                  ops::Transpose2DoubleGradMaker<paddle::framework::OpDesc>,
366 367
                  ops::Transpose2DoubleGradMaker<paddle::imperative::OpBase>,
                  Transpose2GradInferShapeFunctor);