conditional_block_op.cc 8.8 KB
Newer Older
L
Luo Tao 已提交
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Y
Yu Yang 已提交
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
Y
Yu Yang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yu Yang 已提交
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. */
Y
Yu Yang 已提交
14
#include <algorithm>
Y
Yi Wang 已提交
15 16
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/op_registry.h"
Y
Yu Yang 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

namespace paddle {
namespace operators {

class ConditionalOp : public framework::OperatorBase {
 public:
  ConditionalOp(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 protected:
  std::vector<const framework::LoDTensor *> InputTensors(
      const framework::Scope &scope) const {
    std::vector<const framework::LoDTensor *> retv;
    auto xs = Inputs("X");
    retv.resize(xs.size(), nullptr);
    std::transform(
        xs.begin(), xs.end(), retv.begin(),
        [&scope](const std::string &var_name) -> const framework::LoDTensor * {
          auto *var = scope.FindVar(var_name);
          PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s", var_name);
          return &var->Get<framework::LoDTensor>();
        });
    return retv;
  }
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

  bool ScalarCondition(
      const std::vector<const framework::LoDTensor *> &ips) const {
    if (!(ips.size() == 1UL && ips[0]->IsInitialized())) {
      PADDLE_THROW("should have one initialized input as condition");
    }
    if (!(ips[0]->type().hash_code() == typeid(bool).hash_code() &&
          ips[0]->numel() == 1)) {
      PADDLE_THROW(
          "condition input's data type should be bool, "
          "numel should be 1, actual numel is %d",
          ips[0]->numel());
    }
    return ips[0]->data<bool>()[0];
  }
Y
Yu Yang 已提交
59 60 61 62 63 64 65 66 67 68
};

class ConditionalBlockOp : public ConditionalOp {
 public:
  ConditionalBlockOp(const std::string &type,
                     const framework::VariableNameMap &inputs,
                     const framework::VariableNameMap &outputs,
                     const framework::AttributeMap &attrs)
      : ConditionalOp(type, inputs, outputs, attrs) {}
  void Run(const framework::Scope &scope,
D
dzhwinter 已提交
69
           const platform::Place &dev_place) const override {
Y
Yu Yang 已提交
70
    auto xs = InputTensors(scope);
71 72 73 74 75 76 77 78 79

    bool need_run;
    if (Attr<bool>("is_scalar_condition")) {
      need_run = ScalarCondition(xs);
    } else {
      need_run = std::all_of(
          xs.begin(), xs.end(),
          [](const framework::LoDTensor *t) { return t->numel() != 0; });
    }
Y
Yu Yang 已提交
80 81 82 83 84 85 86 87 88

    if (need_run) {
      auto *scope_var = scope.FindVar(Output("Scope"));
      PADDLE_ENFORCE(scope_var != nullptr, "Must set scope");
      auto *scopes = scope_var->GetMutable<std::vector<framework::Scope *>>();
      scopes->resize(1);
      scopes->front() = &scope.NewScope();
      auto &cur_scope = *scopes->front();

D
dzhwinter 已提交
89
      framework::Executor exec(dev_place);
Y
Yu Yang 已提交
90
      auto *block = Attr<framework::BlockDesc *>("sub_block");
Y
Yu Yang 已提交
91 92 93 94 95 96 97
      exec.Run(*block->Program(), &cur_scope, block->ID(), false);
    }
  }
};

class ConditionalBlockOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
98
  ConditionalBlockOpProtoMaker(OpProto *proto, OpAttrChecker *op_checker)
Y
Yu Yang 已提交
99 100 101 102 103 104 105 106 107 108 109
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X",
             "The conditional variable of this operator. If X is empty, the "
             "whole sub-block will not be executed.")
        .AsDuplicable();
    AddInput("Params", "The input variables of the sub-block.").AsDuplicable();
    AddOutput("Out", "The output variables of the sub-block.").AsDuplicable();
    AddOutput("Scope",
              "(std::vector<Scope*>) The step scope of conditional block. To "
              "unify the conditional block, rnn and while op, the type of "
              "scope is std::vector<Scope*>");
Y
Yu Yang 已提交
110
    AddAttr<framework::BlockDesc *>(
111
        "sub_block", "The step block of conditional block operator");
112 113 114 115
    AddAttr<bool>("is_scalar_condition",
                  "the input X is used as scalar "
                  "condition")
        .SetDefault(false);
Y
Yu Yang 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    AddComment(R"DOC(Conditional block operator

Run the sub-block if X is not empty. Params is the other inputs and Out is the
outputs of the sub-block.
)DOC");
  }
};

class ConditionalBlockGradOp : public ConditionalOp {
 public:
  ConditionalBlockGradOp(const std::string &type,
                         const framework::VariableNameMap &inputs,
                         const framework::VariableNameMap &outputs,
                         const framework::AttributeMap &attrs)
      : ConditionalOp(type, inputs, outputs, attrs) {}
  void Run(const framework::Scope &scope,
D
dzhwinter 已提交
132
           const platform::Place &dev_place) const override {
Y
Yu Yang 已提交
133
    auto xs = this->InputTensors(scope);
134 135 136 137 138 139 140 141 142

    bool need_run;
    if (Attr<bool>("is_scalar_condition")) {
      need_run = ScalarCondition(xs);
    } else {
      need_run = std::all_of(
          xs.begin(), xs.end(),
          [](const framework::LoDTensor *t) { return t->numel() != 0; });
    }
Y
Yu Yang 已提交
143 144 145 146 147 148 149

    if (need_run) {
      auto *scope_var = scope.FindVar(Input("Scope"));
      PADDLE_ENFORCE(scope_var != nullptr, "Must set scope");
      auto &scopes = scope_var->Get<std::vector<framework::Scope *>>();
      framework::Scope &cur_scope = *scopes[0];

D
dzhwinter 已提交
150
      framework::Executor exec(dev_place);
Y
Yu Yang 已提交
151
      auto *block = Attr<framework::BlockDesc *>("sub_block");
Y
Yu Yang 已提交
152 153
      exec.Run(*block->Program(), &cur_scope, block->ID(), false);

D
dzhwinter 已提交
154
      AssignLocalGradientToGlobal(dev_place, cur_scope, Inputs("Params"),
Y
Yu Yang 已提交
155 156
                                  Outputs(framework::GradVarName("Params")));

D
dzhwinter 已提交
157
      AssignLocalGradientToGlobal(dev_place, cur_scope, Inputs("X"),
Y
Yu Yang 已提交
158 159 160 161 162 163
                                  Outputs(framework::GradVarName("X")));
    }
  }

 private:
  void AssignLocalGradientToGlobal(
D
dzhwinter 已提交
164
      const platform::Place &place, const framework::Scope &cur_scope,
Y
Yu Yang 已提交
165 166 167 168 169 170 171 172 173 174
      const std::vector<std::string> &p_names,
      const std::vector<std::string> &pg_names) const {
    for (size_t i = 0; i < p_names.size(); ++i) {
      auto out_grad_name = pg_names[i];
      auto in_grad_name = framework::GradVarName(p_names[i]);
      auto *in_var = cur_scope.FindVar(in_grad_name);
      if (in_var == nullptr) {
        continue;
      }
      auto new_in_grad_name = cur_scope.Rename(in_grad_name);
Y
Yiqun Liu 已提交
175 176 177
      auto assign = framework::OpRegistry::CreateOp(
          "assign", {{"X", {new_in_grad_name}}}, {{"Out", {out_grad_name}}},
          framework::AttributeMap{});
D
dzhwinter 已提交
178
      assign->Run(cur_scope, place);
Y
Yu Yang 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
      cur_scope.Rename(new_in_grad_name, in_grad_name);
    }
  }
};

class ConditionalBlockGradInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInputs("X"));
    if (context->HasInputs("Params")) {
      PADDLE_ENFORCE(context->HasOutputs(framework::GradVarName("Params")));
      context->SetOutputsDim(framework::GradVarName("Params"),
                             context->GetInputsDim("Params"));
    }
    PADDLE_ENFORCE(context->HasOutputs(framework::GradVarName("X")));
    context->SetOutputsDim(framework::GradVarName("X"),
                           context->GetInputsDim("X"));
  }
};

class ConditionalBlockGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
Y
Yu Yang 已提交
204 205
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto grad_op = new framework::OpDesc();
Y
Yu Yang 已提交
206 207 208 209 210 211
    grad_op->SetType("conditional_block_grad");
    grad_op->SetInput("X", Input("X"));
    grad_op->SetInput("Params", Input("Params"));
    grad_op->SetInput("Out", Output("Out"));
    grad_op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    grad_op->SetInput("Scope", Output("Scope"));
212 213 214
    grad_op->SetOutput(framework::GradVarName("X"), InputGrad("X", false));
    grad_op->SetOutput(framework::GradVarName("Params"),
                       InputGrad("Params", false));
215
    grad_op->SetBlockAttr("sub_block", *this->grad_block_[0]);
216
    grad_op->SetAttr("is_scalar_condition", GetAttr("is_scalar_condition"));
Y
Yu Yang 已提交
217
    return std::unique_ptr<framework::OpDesc>(grad_op);
Y
Yu Yang 已提交
218 219 220 221 222 223 224 225 226 227 228 229
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(conditional_block, ops::ConditionalBlockOp,
                  ops::ConditionalBlockOpProtoMaker,
                  ops::ConditionalBlockGradMaker);
REGISTER_OPERATOR(conditional_block_grad, ops::ConditionalBlockGradOp,
                  ops::ConditionalBlockGradInferShape);