conditional_block_op.cc 17.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"
16

17
#include "paddle/fluid/operators/assign_op.h"
18
#include "paddle/phi/kernels/funcs/math_function.h"
Y
Yu Yang 已提交
19

20 21 22 23
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif

24 25
DECLARE_bool(use_mkldnn);

Y
Yu Yang 已提交
26 27 28
namespace paddle {
namespace operators {

Z
Zeng Jinle 已提交
29 30 31 32 33 34
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";

35 36 37
using Executor = framework::Executor;
using ExecutorPrepareContext = framework::ExecutorPrepareContext;

Y
Yu Yang 已提交
38 39 40 41 42 43 44
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) {}
45 46 47 48

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
49 50
    bool need_run;
    if (Attr<bool>("is_scalar_condition")) {
51 52 53
      // 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 已提交
54
      auto xs = InputTensors(scope, ConditionalOp::kCondition);
55 56
      need_run = ScalarCondition(xs);
    } else {
57 58 59
      // 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 已提交
60
      auto xs = InputTensors(scope, ConditionalOp::kInputs);
61 62 63 64
      need_run =
          std::all_of(xs.begin(), xs.end(), [](const framework::LoDTensor *t) {
            return t->numel() != 0;
          });
65
    }
Y
Yu Yang 已提交
66 67

    if (need_run) {
Z
Zeng Jinle 已提交
68
      auto *scope_var = scope.FindVar(Output(ConditionalOp::kScope));
69
      PADDLE_ENFORCE_NOT_NULL(
70 71 72 73
          scope_var,
          platform::errors::PreconditionNotMet(
              "Expect Scope variable to be set in conditional_block_op, but "
              "got a null Scope variable. Please set the Scope variable."));
Y
Yu Yang 已提交
74 75 76 77
      auto *scopes = scope_var->GetMutable<std::vector<framework::Scope *>>();
      scopes->resize(1);
      scopes->front() = &scope.NewScope();
      auto &cur_scope = *scopes->front();
78 79 80 81 82 83
#ifdef PADDLE_WITH_MKLDNN
      // (jczaja) Executor on being destroyed clears oneDNN cache and
      // reset registered model data layout. This is unwanted for nested
      // Executors (executors declared inside control ops)
      platform::DontClearMKLDNNCache(dev_place);
#endif
Y
Yu Yang 已提交
84
      auto *block = Attr<framework::BlockDesc *>("sub_block");
85 86
      VLOG(3) << "Conditional block.idx = " << block->ID()
              << ", scope = " << &cur_scope;
Z
Zeng Jinle 已提交
87 88
      auto &skip_vars =
          Attr<std::vector<std::string>>(ConditionalOp::kSkipEagerDeletionVars);
89 90 91 92 93 94 95 96 97 98 99
      if (!exec || !platform::is_same_place(exec->GetPlace(), dev_place)) {
        auto &pdesc = *block->Program();
        exec.reset(new Executor(dev_place));
        if (FLAGS_use_mkldnn) exec->EnableMKLDNN(pdesc);
        ctx = exec->Prepare(pdesc, block->ID(), skip_vars, false);
#ifdef PADDLE_WITH_MKLDNN
        platform::AttachPointerHashToMKLDNNKey(exec.get(), dev_place);
        platform::RegisterModelLayout(ctx->ops_, dev_place);
#endif
      }
      exec->RunPreparedContext(ctx.get(), &cur_scope, false, true, true);
Y
Yu Yang 已提交
100 101
    }
  }
102 103 104 105

 private:
  mutable std::shared_ptr<Executor> exec{nullptr};
  mutable std::unique_ptr<ExecutorPrepareContext> ctx{nullptr};
Y
Yu Yang 已提交
106 107
};

108 109 110
class ConditionalBlockInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
111 112
    PADDLE_ENFORCE_EQ(context->HasInputs(ConditionalOp::kCondition),
                      true,
113
                      platform::errors::InvalidArgument(
114
                          "conditional_block_op must have condition input."));
115 116 117
  }
};

Y
Yu Yang 已提交
118 119 120 121 122 123 124
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) {}
125 126 127 128

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
129 130
    bool need_run;
    if (Attr<bool>("is_scalar_condition")) {
Z
Zeng Jinle 已提交
131
      auto xs = this->InputTensors(scope, ConditionalOp::kCondition);
132 133
      need_run = ScalarCondition(xs);
    } else {
Z
Zeng Jinle 已提交
134
      auto xs = this->InputTensors(scope, ConditionalOp::kInputs);
135 136 137 138
      need_run =
          std::all_of(xs.begin(), xs.end(), [](const framework::LoDTensor *t) {
            return t->numel() != 0;
          });
139
    }
Y
Yu Yang 已提交
140

141 142 143
    const auto &inputs = Inputs(ConditionalOp::kInputs);
    const auto &outside_grads =
        Outputs(framework::GradVarName(ConditionalOp::kInputs));
Y
Yu Yang 已提交
144
    if (need_run) {
145 146 147 148 149 150
      std::vector<std::string> inside_grads;
      inside_grads.reserve(inputs.size());
      for (auto &in : inputs) {
        inside_grads.emplace_back(framework::GradVarName(in));
      }

Z
Zeng Jinle 已提交
151
      auto *scope_var = scope.FindVar(Input(ConditionalOp::kScope));
152
      PADDLE_ENFORCE_NOT_NULL(
153 154 155 156
          scope_var,
          platform::errors::PreconditionNotMet(
              "Expect Scope variable to be set in conditional_block_op, but "
              "got a null Scope variable. Please set the Scope variable."));
Y
Yu Yang 已提交
157
      auto &scopes = scope_var->Get<std::vector<framework::Scope *>>();
158
      PADDLE_ENFORCE_GT(
159 160
          scopes.size(),
          0,
161 162 163
          platform::errors::InvalidArgument(
              "Expect Scope variable contains at least 1 scope, but got: %d",
              scopes.size()));
Y
Yu Yang 已提交
164 165
      framework::Scope &cur_scope = *scopes[0];

Y
Yu Yang 已提交
166
      auto *block = Attr<framework::BlockDesc *>("sub_block");
Y
Yu Yang 已提交
167

168 169
      VLOG(3) << "Conditional Grad block.idx = " << block->ID()
              << ", scope = " << &cur_scope;
170 171 172 173 174 175 176 177 178 179 180
      if (!exec || !platform::is_same_place(exec->GetPlace(), dev_place)) {
        auto &pdesc = *block->Program();
        exec.reset(new Executor(dev_place));
        if (FLAGS_use_mkldnn) exec->EnableMKLDNN(pdesc);
        ctx = exec->Prepare(pdesc, block->ID(), inside_grads, false);
#ifdef PADDLE_WITH_MKLDNN
        platform::AttachPointerHashToMKLDNNKey(exec.get(), dev_place);
        platform::RegisterModelLayout(ctx->ops_, dev_place);
#endif
      }
      exec->RunPreparedContext(ctx.get(), &cur_scope, false, true, false);
Y
Yu Yang 已提交
181

182 183
      AssignLocalGradientToParentScope(
          dev_place, cur_scope, scope, inside_grads, outside_grads, inputs);
184
      return;
Y
Yu Yang 已提交
185
    }
186 187

    AssignZeroToParentScope(dev_place, scope, inputs, outside_grads);
Y
Yu Yang 已提交
188 189
  }

190 191 192 193
 private:
  mutable std::shared_ptr<Executor> exec{nullptr};
  mutable std::unique_ptr<ExecutorPrepareContext> ctx{nullptr};

Y
Yu Yang 已提交
194
 private:
195
  void AssignLocalGradientToParentScope(
196 197
      const platform::Place &place,
      const framework::Scope &cur_scope,
198 199
      const framework::Scope &parent_scope,
      const std::vector<std::string> &inside_grads,
200 201 202 203
      const std::vector<std::string> &outside_grads,
      const std::vector<std::string> &inputs) const {
    std::vector<std::string> assign_zero_outside_grads;
    std::vector<std::string> assign_zero_inputs;
204 205 206 207 208 209 210 211 212 213
    for (size_t i = 0; i < outside_grads.size(); ++i) {
      const std::string &outside_grad_name = outside_grads[i];
      const std::string &inside_grad_name = inside_grads[i];
      VLOG(4) << "inside_grad_name = " << inside_grad_name
              << ", outside_grad_name = " << outside_grad_name;
      framework::Variable *outside_var =
          parent_scope.FindVar(outside_grad_name);
      if (outside_var == nullptr) {
        continue;
      }
214 215 216 217 218 219 220
      framework::Variable *inside_var =
          cur_scope.FindLocalVar(inside_grad_name);
      if (inside_var == nullptr) {
        assign_zero_outside_grads.emplace_back(outside_grad_name);
        assign_zero_inputs.emplace_back(inputs[i]);
        continue;
      }
221 222 223 224
      platform::DeviceContext *dev_ctx =
          platform::DeviceContextPool::Instance().Get(place);
      framework::VisitVarType(*inside_var,
                              AssignFunctor(outside_var, *dev_ctx));
Y
Yu Yang 已提交
225
    }
226 227
    // Assign zero to the grad_vars that are in outside_grads but not in
    // inside_grads
228 229
    AssignZeroToParentScope(
        place, parent_scope, assign_zero_inputs, assign_zero_outside_grads);
Y
Yu Yang 已提交
230
  }
231 232

  void AssignZeroToParentScope(
233 234
      const platform::Place &place,
      const framework::Scope &scope,
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
      const std::vector<std::string> &inputs,
      const std::vector<std::string> &outside_grads) const {
    for (size_t i = 0; i < outside_grads.size(); ++i) {
      const std::string &outside_grad_name = outside_grads[i];
      const std::string &input_name = inputs[i];
      VLOG(4) << "input_name = " << input_name
              << ", outside_grad_name = " << outside_grad_name;
      framework::Variable *input_var = scope.FindVar(input_name);
      if (input_var == nullptr) {
        continue;
      }
      framework::Variable *outside_var = scope.FindVar(outside_grad_name);
      if (outside_var == nullptr) {
        continue;
      }

      if (input_var->IsType<framework::LoDTensor>()) {
252 253
        PADDLE_ENFORCE_EQ(outside_var->IsType<framework::LoDTensor>(),
                          true,
254 255
                          platform::errors::InvalidArgument(
                              "Type of outside_var %s is NOT LoDTensor, which "
256
                              "doesn't match input_var %s.",
257 258
                              outside_grad_name,
                              input_name));
259
        AssignZeroToOutsideTensor(
260 261 262
            place,
            scope,
            input_var->Get<framework::LoDTensor>(),
263 264 265 266 267 268
            outside_var->GetMutable<framework::LoDTensor>());
      } else if (input_var->IsType<framework::LoDTensorArray>()) {
        PADDLE_ENFORCE_EQ(outside_var->IsType<framework::LoDTensorArray>(),
                          true,
                          platform::errors::InvalidArgument(
                              "Type of outside_var %s is NOT LoDTensorArray, "
269
                              "which doesn't match input_var %s.",
270 271
                              outside_grad_name,
                              input_name));
272 273 274
        const auto &input_tensors = input_var->Get<framework::LoDTensorArray>();
        auto *outside_tensors =
            outside_var->GetMutable<framework::LoDTensorArray>();
275 276 277
        if (outside_tensors->size() == 0U) {
          outside_tensors->resize(input_tensors.size());
        }
278 279
        PADDLE_ENFORCE_EQ(input_tensors.size(),
                          outside_tensors->size(),
280 281
                          platform::errors::InvalidArgument(
                              "LoDTensorArray outside_var %s doen't have same "
282
                              "size as input_var %s.",
283 284
                              outside_grad_name,
                              input_name));
285
        for (size_t j = 0; j < input_tensors.size(); ++j) {
286 287
          AssignZeroToOutsideTensor(
              place, scope, input_tensors[j], &((*outside_tensors)[j]));
288 289 290 291 292
        }
      } else {
        // TODO(huihuangzheng): add support for SelectedRows
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Conditional block grad op doesn't support non-LoDTensor output "
293
            "now."));
294 295 296 297 298 299 300 301 302 303 304 305 306
      }
    }
  }

  void AssignZeroToOutsideTensor(const platform::Place &place,
                                 const framework::Scope &cur_scope,
                                 const framework::LoDTensor &input_tensor,
                                 framework::LoDTensor *outside_tensor) const {
    if (!input_tensor.IsInitialized() || input_tensor.numel() == 0) {
      return;
    }
    VLOG(4) << "Assigning zero to " << outside_tensor;
    outside_tensor->Resize(input_tensor.dims());
307
    outside_tensor->mutable_data(place, input_tensor.dtype());
308 309
    const platform::DeviceContext *dev_ctx =
        platform::DeviceContextPool::Instance().Get(place);
310
    phi::funcs::set_constant(*dev_ctx, outside_tensor, 0.0f);
311 312
    outside_tensor->set_lod(input_tensor.lod());
  }
Y
Yu Yang 已提交
313 314
};

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
template <class T>
struct FilterNoGradInput {};

template <>
struct FilterNoGradInput<framework::OpDesc> {
  static void filter(const framework::BlockDesc *desc,
                     std::vector<std::string> *vec) {
    auto f = [desc](const std::string &name) -> std::string {
      if (name == framework::kEmptyVarName) {
        // don't drop empty var name, you can use Input(name, true) to drop it.
        return framework::kEmptyVarName;
      }
      auto var_desc =
          desc->FindVarRecursive(framework::GradOriginalVarName(name));
      std::set<framework::proto::VarType::Type> not_support_backward_dtype = {
          framework::proto::VarType::BOOL,
          framework::proto::VarType::INT8,
          framework::proto::VarType::UINT8,
          framework::proto::VarType::INT16,
          framework::proto::VarType::INT32,
          framework::proto::VarType::INT64,
      };
      if (!var_desc ||
          not_support_backward_dtype.count(var_desc->GetDataType()))
        return framework::kEmptyVarName;
      return name;
    };
    std::transform(vec->begin(), vec->end(), vec->begin(), f);
  }
};

Y
Yu Yang 已提交
346 347 348
class ConditionalBlockGradInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
349
    PADDLE_ENFORCE_EQ(
350 351
        context->HasInputs(ConditionalOp::kCondition),
        true,
352 353
        platform::errors::InvalidArgument(
            "Condition must be set in conditional_block_grad_op."));
354 355
    if (context->HasInputs(ConditionalOp::kInputs) &&
        context->HasOutputs(framework::GradVarName(ConditionalOp::kInputs))) {
Z
Zeng Jinle 已提交
356 357
      context->SetOutputsDim(framework::GradVarName(ConditionalOp::kInputs),
                             context->GetInputsDim(ConditionalOp::kInputs));
Y
Yu Yang 已提交
358 359 360 361
    }
  }
};

362 363 364 365 366 367 368
class ConditionalBlockGradInferVarType : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext *ctx) const override {
    // NOTE(Aurelius84): VarType of Output is LoDTensor by default. In case of
    // Input is {Tensor, LoDTensorArray}, we need synchronous the Input's
    // VarType into Input@GRAD to avoid generating {Tensor, Tensor} as
    // Input@GRAD.
369 370 371
    auto input_size = ctx->InputSize(ConditionalOp::kInputs);
    auto output_size =
        ctx->OutputSize(framework::GradVarName(ConditionalOp::kInputs));
372 373
    PADDLE_ENFORCE_EQ(input_size,
                      output_size,
374 375 376 377 378 379 380 381
                      platform::errors::InvalidArgument(
                          "input_size and output_size should be equal for "
                          "conditional_block_grad_op."));
    for (size_t i = 0; i < output_size; ++i) {
      ctx->SyncTypeAndDataType(ConditionalOp::kInputs,
                               framework::GradVarName(ConditionalOp::kInputs),
                               i);
    }
382 383 384
  }
};

H
hong 已提交
385 386
template <typename T>
class ConditionalBlockGradMaker : public framework::SingleGradOpMaker<T> {
Y
Yu Yang 已提交
387
 public:
H
hong 已提交
388
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Y
Yu Yang 已提交
389 390

 protected:
391
  void Apply(GradOpPtr<T> grad_op) const override {
Y
Yu Yang 已提交
392
    grad_op->SetType("conditional_block_grad");
Z
Zeng Jinle 已提交
393
    grad_op->SetInput(ConditionalOp::kCondition,
H
hong 已提交
394 395 396 397 398
                      this->Input(ConditionalOp::kCondition));
    grad_op->SetInput(ConditionalOp::kInputs,
                      this->Input(ConditionalOp::kInputs));
    grad_op->SetInput(ConditionalOp::kOutputs,
                      this->Output(ConditionalOp::kOutputs));
Z
Zeng Jinle 已提交
399
    grad_op->SetInput(framework::GradVarName(ConditionalOp::kOutputs),
H
hong 已提交
400 401 402
                      this->OutputGrad(ConditionalOp::kOutputs));
    grad_op->SetInput(ConditionalOp::kScope,
                      this->Output(ConditionalOp::kScope));
403 404 405

    auto fwd_inputs = this->InputGrad(ConditionalOp::kInputs, false);
    FilterNoGradInput<T>::filter(this->GetForwardOpBlock(), &fwd_inputs);
Z
Zeng Jinle 已提交
406
    grad_op->SetOutput(framework::GradVarName(ConditionalOp::kInputs),
407
                       fwd_inputs);
A
Abhinav Arora 已提交
408
    grad_op->SetBlockAttr("sub_block", this->grad_block_[0]);
H
hong 已提交
409 410
    grad_op->SetAttr("is_scalar_condition",
                     this->GetAttr("is_scalar_condition"));
Y
Yu Yang 已提交
411 412 413 414 415 416 417
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
418 419
REGISTER_OPERATOR(conditional_block,
                  ops::ConditionalBlockOp,
420
                  ops::ConditionalBlockInferShape,
Y
Yu Yang 已提交
421
                  ops::ConditionalBlockOpProtoMaker,
H
hong 已提交
422
                  ops::ConditionalBlockGradMaker<paddle::framework::OpDesc>);
423 424
REGISTER_OPERATOR(conditional_block_grad,
                  ops::ConditionalBlockGradOp,
425 426
                  ops::ConditionalBlockGradInferShape,
                  ops::ConditionalBlockGradInferVarType);