unsqueeze_op.cc 15.0 KB
Newer Older
1
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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

15 16
#include "paddle/fluid/operators/unsqueeze_op.h"
#include <memory>
17 18
#include <string>
#include <vector>
19
#include "paddle/fluid/framework/op_registry.h"
20 21 22 23

namespace paddle {
namespace operators {

24
class UnsqueezeOp : public framework::OperatorWithKernel {
25
 public:
26 27 28 29
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
30 31 32
                      platform::errors::InvalidArgument(
                          "Input(X) of "
                          "Unsqueeze operator should not be null."));
33
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
34 35 36
                      platform::errors::InvalidArgument(
                          "Output(Out) of "
                          "Unsqueeze operator should not be null."));
37

38 39
    const auto &axes = ctx->Attrs().Get<std::vector<int>>("axes");
    const auto &x_dims = ctx->GetInputDim("X");
40
    // Validity Check: input tensor dims (<6).
41
    PADDLE_ENFORCE_LE(x_dims.size(), 6,
42 43 44 45
                      platform::errors::InvalidArgument(
                          "Invalid "
                          "dimensions, the rank of Input(X) "
                          "should be in the range of [1, 6] (Eigen limit)"));
46 47 48 49 50 51 52 53 54 55 56 57
    if (!axes.empty()) {
      auto out_dims = GetOutputShape(axes, x_dims);
      ctx->SetOutputDim("Out", out_dims);
      if (x_dims[0] == out_dims[0]) {
        // Only pass LoD when the first dimension of output and Input(X)
        // are the same.
        ctx->ShareLoD("X", "Out");
      }
    } else if (ctx->HasInputs("AxesTensorList")) {
      auto AxesTensorList = ctx->Inputs("AxesTensorList");
      int output_size = x_dims.size() + static_cast<int>(AxesTensorList.size());
      PADDLE_ENFORCE_LE(output_size, 6,
58 59
                        platform::errors::InvalidArgument(
                            "The output tensor's rank should be less than 6."));
60 61 62 63
      std::vector<int> vec_out_dims(output_size, -1);
      ctx->SetOutputDim("Out", framework::make_ddim(vec_out_dims));
    } else if (ctx->HasInput("AxesTensor")) {
      auto axes_dims = ctx->GetInputDim("AxesTensor");
64 65 66 67 68 69 70 71 72 73 74 75 76
      PADDLE_ENFORCE_EQ(axes_dims.size(), 1,
                        platform::errors::InvalidArgument(
                            "Input(AxesTensor)'s dimension of "
                            "Op(unsqueeze) must be 1. "
                            "But received AxesTensor's shape = [%s], "
                            "AxesTensor's dimension = %d.",
                            axes_dims, axes_dims.size()));
      PADDLE_ENFORCE_GE(
          axes_dims[0], 0,
          platform::errors::InvalidArgument(
              "Input(AxesTensor)'s shape must be known. But received "
              "AxesTensor's shape = [%s]",
              axes_dims));
77 78
      int output_size = x_dims.size() + static_cast<int>(axes_dims[0]);
      PADDLE_ENFORCE_LE(output_size, 6,
79 80
                        platform::errors::InvalidArgument(
                            "The output tensor's rank should be less than 6."));
81 82
      std::vector<int> vec_out_dims(output_size, -1);
      ctx->SetOutputDim("Out", framework::make_ddim(vec_out_dims));
83
    }
84 85
  }

86
  static framework::DDim GetOutputShape(const std::vector<int> unsqz_dims,
87
                                        const framework::DDim &in_dims) {
88 89
    int output_size = in_dims.size() + static_cast<int>(unsqz_dims.size());
    int cur_output_size = in_dims.size();
90 91 92
    std::vector<int64_t> output_shape(output_size, 0);

    // Validity Check: rank range.
93
    PADDLE_ENFORCE_LE(output_size, 6,
94 95
                      platform::errors::InvalidArgument(
                          "The output tensor's rank should be less than 6."));
96 97

    for (int axis : unsqz_dims) {
98
      int cur = axis < 0 ? axis + cur_output_size + 1 : axis;
99
      // Vaildity Check: the axis bound
100 101 102 103 104 105 106
      PADDLE_ENFORCE_GE(cur, 0, platform::errors::InvalidArgument(
                                    "The insert dimension value should "
                                    "not be less than 0"));
      PADDLE_ENFORCE_LE(cur, cur_output_size,
                        platform::errors::InvalidArgument(
                            "The insert dimension value shoud not be larger "
                            "than the dimension size of input tensor"));
107 108 109 110 111 112 113 114 115
      // Move old axis, and insert new axis
      for (int i = cur_output_size; i >= cur; --i) {
        if (output_shape[i] == 1) {
          // Move axis
          output_shape[i + 1] = 1;
          output_shape[i] = 0;
        }
      }
      output_shape[cur] = 1;
116
      // Add the output size.
117
      cur_output_size++;
118 119
    }

120
    // Make output shape
121 122
    for (int in_idx = 0, out_idx = 0; out_idx < output_size; ++out_idx) {
      if (output_shape[out_idx] == 0) {
123 124 125 126 127 128
        output_shape[out_idx] = in_dims[in_idx++];
      }
    }

    return framework::make_ddim(output_shape);
  }
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    return framework::OpKernelType(ctx.Input<framework::LoDTensor>("X")->type(),
                                   ctx.device_context());
  }

  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const framework::Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "AxesTensor" || var_name == "AxesTensorList") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
146 147 148 149 150 151
};

class UnsqueezeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor). The input tensor of unsqueeze operator.");
152 153 154 155 156 157 158 159 160 161 162
    AddInput("AxesTensor",
             "(Tensor<int32>, optional). The dimensions to be inserted. "
             "If it exists, it will replace Attr(axes).")
        .AsDispensable();
    AddInput(
        "AxesTensorList",
        "(vector<Tensor<int32>>, optional). The dimensions to be inserted. "
        "If it exists, it will replace Attr(axes)."
        "The shape of the element in vector must be [1].")
        .AsDuplicable()
        .AsDispensable();
163 164
    AddOutput("Out", "(Tensor). The output tensor of unsqueeze operator.");
    AddAttr<std::vector<int>>("axes",
165
                              "(std::vector<int>). List of integers,"
166
                              " indicating the dimensions to be inserted")
167
        .SetDefault({})
168 169
        .AddCustomChecker([](const std::vector<int> &axes) {
          // Validity Check: axes dims (<6).
170
          PADDLE_ENFORCE_LT(static_cast<int>(axes.size()), 6,
171 172 173 174
                            platform::errors::InvalidArgument(
                                "Invalid "
                                "dimensions, dynamic dimensions should be "
                                "within [1, 6] dimensions (Eigen limit)."));
T
tianshuo78520a 已提交
175
          // Validity Check: the range of unsqueeze axis.
176
          for (int axis : axes) {
177
            PADDLE_ENFORCE_LT(axis, 6,
178 179 180 181
                              platform::errors::InvalidArgument(
                                  "Invalid "
                                  "dimensions, input axis should be"
                                  "within [1, 6] dimensions (Eigen limit)."));
182 183
          }
        });
184
    AddComment(R"DOC(
185 186
    Unsqueeze Operator.

187 188 189 190 191 192
    Insert single-dimensional entries to the shape of a tensor.
    Takes one required argument axes, a list of dimensions that will be inserted.
    Dimension indices in axes are as seen in the output tensor.

    For example:
      Given a tensor such that tensor with shape [3, 4, 5],
193
      then Unsqueeze(tensor, axes=[0, 4]) has shape [1, 3, 4, 5, 1]
194 195 196 197
    )DOC");
  }
};

198
class UnsqueezeGradOp : public framework::OperatorWithKernel {
199
 public:
200 201 202
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
203
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
204
    ctx->ShareLoD("X", framework::GradVarName("X"));
205
  }
206 207 208 209 210 211 212 213 214 215 216 217 218 219

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
  }
};

template <typename T>
class UnsqueezeGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

220
  void Apply(GradOpPtr<T> grad_op) const override {
221 222 223 224 225 226
    grad_op->SetType("unsqueeze_grad");
    grad_op->SetInput("X", this->Input("X"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
  }
227
};
228

229 230 231 232 233
// FIXME(zcd): unsqueeze2 adds an intermediate output(XShape) based on
// unsqueeze, the XShape is used to carry the shape and lod of X which
// will be used in unsqueeze_grad, in this way, the framework can reuse
// the memory of X immediately the unsqueeze2_op is finished.
// Considering compatibility issues, we could not fix unsqueeze2_op
234
class Unsqueeze2Op : public UnsqueezeOp {
235
 public:
236
  using UnsqueezeOp::UnsqueezeOp;
237
  void InferShape(framework::InferShapeContext *ctx) const override {
238
    UnsqueezeOp::InferShape(ctx);
239
    const auto &x_dims = ctx->GetInputDim("X");
240 241 242

    PADDLE_ENFORCE_EQ(
        ctx->HasOutput("XShape"), true,
243 244
        platform::errors::InvalidArgument("Output(XShape) of Unsqueeze "
                                          "operator should not be null."));
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    std::vector<int64_t> xshape_dims(x_dims.size() + 1);
    xshape_dims[0] = 0;
    for (int i = 0; i < x_dims.size(); ++i) {
      xshape_dims[i + 1] = x_dims[i];
    }
    ctx->SetOutputDim("XShape", framework::make_ddim(xshape_dims));
    ctx->ShareLoD("X", /*->*/ "XShape");
  }
};

class Unsqueeze2OpMaker : public UnsqueezeOpMaker {
 public:
  void Make() override {
    UnsqueezeOpMaker::Make();
    AddOutput("XShape",
              "XShape is just used to store the shape and lod of X, which will "
              "be used in UnsqueezeGradOp.")
        .AsIntermediate();
  }
};

H
hong 已提交
266 267
template <typename T>
class Unsqueeze2GradOpMaker : public framework::SingleGradOpMaker<T> {
268
 public:
H
hong 已提交
269
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
270

271
  void Apply(GradOpPtr<T> grad_op) const override {
272
    grad_op->SetType("unsqueeze2_grad");
H
hong 已提交
273 274 275 276
    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());
277 278 279
  }
};

280
class Unsqueeze2GradOp : public framework::OperatorWithKernel {
281
 public:
282 283
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext *context) const override {
284 285 286
    PADDLE_ENFORCE_EQ(
        context->HasInput("XShape"), true,
        platform::errors::InvalidArgument("Input(XShape) shouldn't be null."));
287
    PADDLE_ENFORCE_EQ(context->HasInput(framework::GradVarName("Out")), true,
288 289
                      platform::errors::InvalidArgument(
                          "Input(Out@GRAD) shouldn't be null."));
290 291 292 293 294 295
    auto xshape_dims = context->GetInputDim("XShape");
    auto x_dims = framework::slice_ddim(xshape_dims, 1, xshape_dims.size());
    context->SetOutputDim(framework::GradVarName("X"), x_dims);
    context->ShareLoD("XShape", framework::GradVarName("X"));
  }

296 297 298
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
299 300 301
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
302 303
  }
};
304 305 306 307 308

DECLARE_INPLACE_OP_INFERER(UnsqueezeInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(UnsqueezeGradInplaceInferer,
                           {framework::GradVarName("Out"),
                            framework::GradVarName("X")});
Z
Zeng Jinle 已提交
309 310
DECLARE_NO_NEED_BUFFER_VARS_INFERER(UnsqueezeGradOpNoNeedBufferVarInference,
                                    "X");
311 312 313 314
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
315 316 317 318 319
REGISTER_OPERATOR(unsqueeze, ops::UnsqueezeOp, ops::UnsqueezeOpMaker,
                  ops::UnsqueezeGradOpMaker<paddle::framework::OpDesc>,
                  ops::UnsqueezeGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(unsqueeze_grad, ops::UnsqueezeGradOp,
                  ops::UnsqueezeGradOpNoNeedBufferVarInference);
320 321

REGISTER_OPERATOR(unsqueeze2, ops::Unsqueeze2Op, ops::Unsqueeze2OpMaker,
H
hong 已提交
322 323 324
                  ops::Unsqueeze2GradOpMaker<paddle::framework::OpDesc>,
                  ops::Unsqueeze2GradOpMaker<paddle::imperative::OpBase>,
                  ops::UnsqueezeInplaceInferer);
325
REGISTER_OPERATOR(unsqueeze2_grad, ops::Unsqueeze2GradOp,
326
                  ops::UnsqueezeGradInplaceInferer);
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

REGISTER_OP_CPU_KERNEL(
    unsqueeze, ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, float>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, double>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, int>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, int8_t>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, int64_t>);
REGISTER_OP_CPU_KERNEL(
    unsqueeze_grad,
    ops::UnsqueezeGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::UnsqueezeGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::UnsqueezeGradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::UnsqueezeGradKernel<paddle::platform::CPUDeviceContext, int8_t>,
    ops::UnsqueezeGradKernel<paddle::platform::CPUDeviceContext, int64_t>);
REGISTER_OP_CPU_KERNEL(
342 343 344 345 346
    unsqueeze2, ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, float>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, double>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, int>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, int8_t>,
    ops::UnsqueezeKernel<paddle::platform::CPUDeviceContext, int64_t>);
347 348 349 350 351 352 353
REGISTER_OP_CPU_KERNEL(
    unsqueeze2_grad,
    ops::Unsqueeze2GradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::Unsqueeze2GradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::Unsqueeze2GradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::Unsqueeze2GradKernel<paddle::platform::CPUDeviceContext, int8_t>,
    ops::Unsqueeze2GradKernel<paddle::platform::CPUDeviceContext, int64_t>);