conditional_block_op.cc 8.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */
14 15

#include "paddle/fluid/operators/controlflow/conditional_block_op.h"
Y
Yu Yang 已提交
16 17 18 19

namespace paddle {
namespace operators {

Z
Zeng Jinle 已提交
20 21 22 23 24 25
const char ConditionalOp::kInputs[] = "Input";
const char ConditionalOp::kOutputs[] = "Out";
const char ConditionalOp::kCondition[] = "Cond";
const char ConditionalOp::kScope[] = "Scope";
const char ConditionalOp::kSkipEagerDeletionVars[] = "skip_eager_deletion_vars";

Y
Yu Yang 已提交
26 27 28 29 30 31 32
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) {}
33 34 35 36

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
37 38
    bool need_run;
    if (Attr<bool>("is_scalar_condition")) {
39 40 41
      // When is_scalar_condition is True, the conditional variable is a scalar,
      // whether need to execute the operators in sub-block depends on the
      // conditional variable (Cond).
Z
Zeng Jinle 已提交
42
      auto xs = InputTensors(scope, ConditionalOp::kCondition);
43 44
      need_run = ScalarCondition(xs);
    } else {
45 46 47
      // When is_scalar_condition is False, the conditional variable maybe a
      // vector or tensor, whether need to execute the operators in sub-block
      // depends on the input variables (Input).
Z
Zeng Jinle 已提交
48
      auto xs = InputTensors(scope, ConditionalOp::kInputs);
49 50 51 52
      need_run = std::all_of(
          xs.begin(), xs.end(),
          [](const framework::LoDTensor *t) { return t->numel() != 0; });
    }
Y
Yu Yang 已提交
53 54

    if (need_run) {
Z
Zeng Jinle 已提交
55
      auto *scope_var = scope.FindVar(Output(ConditionalOp::kScope));
Y
Yu Yang 已提交
56 57 58 59 60 61
      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 已提交
62
      framework::Executor exec(dev_place);
Y
Yu Yang 已提交
63
      auto *block = Attr<framework::BlockDesc *>("sub_block");
Z
Zeng Jinle 已提交
64 65 66 67
      auto &skip_vars =
          Attr<std::vector<std::string>>(ConditionalOp::kSkipEagerDeletionVars);
      exec.Run(*block->Program(), &cur_scope, block->ID(), false, true,
               skip_vars);
Y
Yu Yang 已提交
68 69 70 71 72 73 74 75 76 77 78
    }
  }
};

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) {}
79 80 81 82

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
83 84
    bool need_run;
    if (Attr<bool>("is_scalar_condition")) {
Z
Zeng Jinle 已提交
85
      auto xs = this->InputTensors(scope, ConditionalOp::kCondition);
86 87
      need_run = ScalarCondition(xs);
    } else {
Z
Zeng Jinle 已提交
88
      auto xs = this->InputTensors(scope, ConditionalOp::kInputs);
89 90 91 92
      need_run = std::all_of(
          xs.begin(), xs.end(),
          [](const framework::LoDTensor *t) { return t->numel() != 0; });
    }
Y
Yu Yang 已提交
93 94

    if (need_run) {
Z
Zeng Jinle 已提交
95
      auto *scope_var = scope.FindVar(Input(ConditionalOp::kScope));
Y
Yu Yang 已提交
96 97 98 99
      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 已提交
100
      framework::Executor exec(dev_place);
Y
Yu Yang 已提交
101
      auto *block = Attr<framework::BlockDesc *>("sub_block");
Y
Yu Yang 已提交
102

Z
Zeng Jinle 已提交
103 104 105 106 107 108
      const auto &ins = Inputs(ConditionalOp::kInputs);
      const auto &d_ins =
          Outputs(framework::GradVarName(ConditionalOp::kInputs));
      const auto &conds = Inputs(ConditionalOp::kCondition);
      const auto &d_conds =
          Outputs(framework::GradVarName(ConditionalOp::kCondition));
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

      std::vector<std::string> ins_conds_grads;
      ins_conds_grads.reserve(ins.size() + conds.size());
      for (auto &in : ins) {
        ins_conds_grads.emplace_back(framework::GradVarName(in));
      }
      for (auto &cond : conds) {
        ins_conds_grads.emplace_back(framework::GradVarName(cond));
      }

      exec.Run(*block->Program(), &cur_scope, block->ID(), false, true,
               ins_conds_grads);

      AssignLocalGradientToGlobal(dev_place, cur_scope, ins_conds_grads.data(),
                                  ins.size(), d_ins);
Y
Yu Yang 已提交
124

125 126 127
      AssignLocalGradientToGlobal(dev_place, cur_scope,
                                  ins_conds_grads.data() + ins.size(),
                                  conds.size(), d_conds);
Y
Yu Yang 已提交
128 129 130 131 132
    }
  }

 private:
  void AssignLocalGradientToGlobal(
D
dzhwinter 已提交
133
      const platform::Place &place, const framework::Scope &cur_scope,
134
      const std::string *p_grad_names, size_t p_grad_names_num,
Y
Yu Yang 已提交
135
      const std::vector<std::string> &pg_names) const {
136
    for (size_t i = 0; i < p_grad_names_num; ++i) {
Y
Yu Yang 已提交
137
      auto out_grad_name = pg_names[i];
138
      const auto &in_grad_name = p_grad_names[i];
Y
Yu Yang 已提交
139 140 141 142 143
      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 已提交
144 145 146
      auto assign = framework::OpRegistry::CreateOp(
          "assign", {{"X", {new_in_grad_name}}}, {{"Out", {out_grad_name}}},
          framework::AttributeMap{});
D
dzhwinter 已提交
147
      assign->Run(cur_scope, place);
Y
Yu Yang 已提交
148 149 150 151 152 153 154 155
      cur_scope.Rename(new_in_grad_name, in_grad_name);
    }
  }
};

class ConditionalBlockGradInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
Z
Zeng Jinle 已提交
156 157 158 159 160 161
    PADDLE_ENFORCE(context->HasInputs(ConditionalOp::kCondition));
    if (context->HasInputs(ConditionalOp::kInputs)) {
      PADDLE_ENFORCE(
          context->HasOutputs(framework::GradVarName(ConditionalOp::kInputs)));
      context->SetOutputsDim(framework::GradVarName(ConditionalOp::kInputs),
                             context->GetInputsDim(ConditionalOp::kInputs));
Y
Yu Yang 已提交
162
    }
Z
Zeng Jinle 已提交
163 164 165 166
    if (context->HasOutputs(
            framework::GradVarName(ConditionalOp::kCondition))) {
      context->SetOutputsDim(framework::GradVarName(ConditionalOp::kCondition),
                             context->GetInputsDim(ConditionalOp::kCondition));
167
    }
Y
Yu Yang 已提交
168 169 170 171 172 173 174 175
  }
};

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

 protected:
Y
Yu Yang 已提交
176 177
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto grad_op = new framework::OpDesc();
Y
Yu Yang 已提交
178
    grad_op->SetType("conditional_block_grad");
Z
Zeng Jinle 已提交
179 180 181 182 183 184 185 186 187 188 189
    grad_op->SetInput(ConditionalOp::kCondition,
                      Input(ConditionalOp::kCondition));
    grad_op->SetInput(ConditionalOp::kInputs, Input(ConditionalOp::kInputs));
    grad_op->SetInput(ConditionalOp::kOutputs, Output(ConditionalOp::kOutputs));
    grad_op->SetInput(framework::GradVarName(ConditionalOp::kOutputs),
                      OutputGrad(ConditionalOp::kOutputs));
    grad_op->SetInput(ConditionalOp::kScope, Output(ConditionalOp::kScope));
    grad_op->SetOutput(framework::GradVarName(ConditionalOp::kCondition),
                       InputGrad(ConditionalOp::kCondition, false));
    grad_op->SetOutput(framework::GradVarName(ConditionalOp::kInputs),
                       InputGrad(ConditionalOp::kInputs, false));
A
Abhinav Arora 已提交
190
    grad_op->SetBlockAttr("sub_block", this->grad_block_[0]);
191
    grad_op->SetAttr("is_scalar_condition", GetAttr("is_scalar_condition"));
Y
Yu Yang 已提交
192
    return std::unique_ptr<framework::OpDesc>(grad_op);
Y
Yu Yang 已提交
193 194 195 196 197 198 199 200 201 202 203 204
  }
};

}  // 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);