lod_reset_op.cc 9.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
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. */
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/lod_reset_op.h"
S
sneaxiy 已提交
16
#include <memory>
17
#include <string>
18 19 20 21 22 23 24 25 26

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext *ctx) const override {
27 28
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "LoDReset");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "LoDReset");
29 30

    if (!ctx->HasInput("Y")) {
31
      auto level0 = ctx->Attrs().Get<std::vector<int>>("target_lod");
32 33 34
      PADDLE_ENFORCE_GT(
          static_cast<int64_t>(level0.size()), 0,
          platform::errors::InvalidArgument(
35 36 37
              "If Input(Y) is not provided, the output's LoD should be "
              "specified by attribute 'target_lod'. But the size of "
              "'target_lod' is 0."));
38
    } else if (ctx->IsRuntime()) {
H
Hongyu Liu 已提交
39
      ctx->ShareLoD("Y", "Out");
P
phlrain 已提交
40
    }
41 42 43 44
    auto append = ctx->Attrs().Get<bool>("append");
    if (append) {
      ctx->ShareLoD("X", /*->*/ "Out");
    }
45 46 47 48 49 50 51 52 53 54 55 56 57 58

    if (ctx->HasInput("Y")) {
      if (!ctx->IsRuntime()) {
        ctx->SetLoDLevel("Out", std::max(ctx->GetLoDLevel("Y"), 1));
      }
    } else if (append) {
      if (!ctx->IsRuntime()) {
        ctx->SetLoDLevel("Out", std::max(ctx->GetLoDLevel("X") + 1, 1));
      }
    } else {
      if (!ctx->IsRuntime()) {
        ctx->SetLoDLevel("Out", 1);
      }
    }
59 60 61 62
    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
  }

 protected:
63
  framework::OpKernelType GetExpectedKernelType(
64
      const framework::ExecutionContext &ctx) const override {
65 66 67
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
68
  }
69 70 71 72 73 74 75 76

  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const framework::Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   expected_kernel_type.place_,
                                   tensor.layout());
  }
77 78
};

79 80
class LoDResetOpVarTypeInference
    : public framework::StaticGraphVarTypeInference {
81 82
 public:
  void operator()(framework::InferVarTypeContext *ctx) const override {
83 84
    auto x_var_name = Input(ctx, "X").front();
    auto out_var_name = Output(ctx, "Out").front();
85
    bool append = boost::get<bool>(ctx->GetAttr("append"));
86
    if (ctx->HasInput("Y")) {
87 88 89
      auto y_var_name = Input(ctx, "Y").front();
      auto y_lod_level = std::max(GetLoDLevel(ctx, y_var_name), 1);
      SetLoDLevel(ctx, out_var_name, y_lod_level);
90
    } else if (append) {
91 92
      auto x_lod_level = std::max(GetLoDLevel(ctx, x_var_name), 1);
      SetLoDLevel(ctx, out_var_name, x_lod_level);
93
    } else {
94
      SetLoDLevel(ctx, out_var_name, 1);
95
    }
96 97
    SetDataType(ctx, out_var_name, GetDataType(ctx, x_var_name));
    SetType(ctx, out_var_name, paddle::framework::proto::VarType::LOD_TENSOR);
98 99 100
  }
};

101 102
class LoDResetOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
103
  void Make() override {
104 105 106 107 108
    AddInput("X",
             "(Tensor, LoDTensor) Input variable of LoDResetOp which "
             "could be a Tensor or LoDTensor, where the data of output "
             "variable inherits from.");
    AddInput("Y",
Y
yangyaming 已提交
109 110 111 112
             "(Tensor, LoDTensor, optional) If provided and Y is LoDTensor, "
             "lod of Input(Y) would be considered as the target lod first, "
             "otherwise data of Input(Y) would be considered as the "
             "target lod.")
113
        .AsDispensable();
114 115 116
    AddOutput("Out",
              "(LoDTensor) Output variable of LoDResetOp which should be a "
              "LoDTensor.");
117 118 119
    AddAttr<std::vector<int>>("target_lod",
                              "The target level 0 LoD from Attr().")
        .SetDefault(std::vector<int>{});
120
    AddAttr<bool>("append", "Append data to lod vector.").SetDefault(false);
121 122
    AddComment(R"DOC(LoDReset operator

123
Set LoD of `X` to a new one specified by `Y` or attribute `target_lod`. When `Y`
Y
yangyaming 已提交
124 125 126 127 128
provided and `Y` is a LoDTensor, `Y.lod` would be considered as target LoD
first, otherwise `Y.data` would be considered as target LoD. If `Y` is not
provided, target LoD should be specified by attribute `target_lod`.
If target LoD is specified by `Y.data` or `target_lod`, only one level LoD
is supported.
129

Y
yangyaming 已提交
130
Example 1:
131

Y
yangyaming 已提交
132 133
Given a 1-level LoDTensor input(X):
    X.lod =  [[ 0,     2,                   5      6 ]]
134 135
    X.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    X.dims = [6, 1]
136

Y
yangyaming 已提交
137
attr(target_lod): [0, 4, 6]
138

Y
yangyaming 已提交
139
then we get a 1-level LoDTensor:
140 141 142
    Out.lod =  [[ 0,                   4,            6 ]]
    Out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    Out.dims = [6, 1]
143

Y
yangyaming 已提交
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
Example 2:

Given a 1-level LoDTensor input(X):
    X.lod =  [[ 0,     2,                   5      6 ]]
    X.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    X.dims = [6, 1]

input(Y) is a Tensor:
    Y.data = [[0, 2, 6]]
    Y.dims = [1, 3]

then we get a 1-level LoDTensor:
    Out.lod =  [[ 0,     2,                          6 ]]
    Out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    Out.dims = [6, 1]

Example 3:

Given a 1-level LoDTensor input(X):
    X.lod =  [[ 0,      2,                   5     6 ]]
    X.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    X.dims = [6, 1]

input(Y) is a 2-level LoDTensor:
    Y.lod =  [[0, 2, 4], [0, 2, 5, 6]]
    Y.data = [[1.1], [2.1], [3.1], [4.1], [5.1], [6.1]]
    Y.dims = [6, 1]

then we get a 2-level LoDTensor:
    Out.lod =  [[0, 2, 4], [0, 2, 5, 6]]
    Out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    Out.dims = [6, 1]

177 178 179 180 181 182 183 184 185
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext *ctx) const override {
186 187 188
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "LoDResetGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Output",
                   framework::GradVarName("Out"), "LoDResetGrad");
189 190 191 192 193 194

    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, ctx->GetInputDim("X"));
      ctx->ShareLoD("X", /*->*/ x_grad_name);
    }
195 196 197
  }

 protected:
198
  framework::OpKernelType GetExpectedKernelType(
199
      const framework::ExecutionContext &ctx) const override {
200 201 202
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
203 204 205
  }
};

H
hong 已提交
206 207
template <typename T>
class LoDResetGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
208
 public:
H
hong 已提交
209
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
210 211

 protected:
212
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
213
    op->SetType("lod_reset_grad");
H
hong 已提交
214 215 216 217
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetInput("X", this->Input("X"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
218 219 220
  }
};

221 222
DECLARE_INPLACE_OP_INFERER(LoDResetInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(LoDResetGradInplaceInferer,
223 224 225
                           {framework::GradVarName("Out"),
                            framework::GradVarName("X")});

226
DECLARE_NO_NEED_BUFFER_VARS_INFERER(LoDResetGradNoNeedBufferVarInference, "X");
S
sneaxiy 已提交
227

228 229 230 231
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
232
REGISTER_OPERATOR(lod_reset, ops::LoDResetOp, ops::LoDResetOpMaker,
H
hong 已提交
233 234
                  ops::LoDResetGradMaker<paddle::framework::OpDesc>,
                  ops::LoDResetGradMaker<paddle::imperative::OpBase>,
235
                  ops::LoDResetOpVarTypeInference, ops::LoDResetInplaceInferer);
S
sneaxiy 已提交
236
REGISTER_OPERATOR(lod_reset_grad, ops::LoDResetGradOp,
237
                  ops::LoDResetGradNoNeedBufferVarInference,
238
                  ops::LoDResetGradInplaceInferer);
239

240 241 242 243 244
REGISTER_OP_CPU_KERNEL(
    lod_reset, ops::LoDResetKernel<paddle::platform::CPUPlace, float>,
    ops::LoDResetKernel<paddle::platform::CPUPlace, double>,
    ops::LoDResetKernel<paddle::platform::CPUPlace, int>,
    ops::LoDResetKernel<paddle::platform::CPUPlace, int64_t>);
245 246
REGISTER_OP_CPU_KERNEL(
    lod_reset_grad, ops::LoDResetGradKernel<paddle::platform::CPUPlace, float>,
247 248 249
    ops::LoDResetGradKernel<paddle::platform::CPUPlace, double>,
    ops::LoDResetGradKernel<paddle::platform::CPUPlace, int>,
    ops::LoDResetGradKernel<paddle::platform::CPUPlace, int64_t>);