while_kernel.cpp 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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

H
update  
hjchen2 已提交
15 16
#ifdef WHILE_OP

17
#include "operators/kernel/while_kernel.h"
H
update  
hjchen2 已提交
18 19
#include "framework/op_registry.h"
#include "framework/operator.h"
20 21 22 23

namespace paddle_mobile {
namespace operators {

H
update  
hjchen2 已提交
24 25 26 27 28
class StepExecutor {
  typedef std::shared_ptr<framework::OperatorBase<CPU>> OperatorPtr;

 public:
  StepExecutor(const framework::BlockDesc *block, framework::Scope *scope)
29
      : scope_(scope) {
H
update  
hjchen2 已提交
30 31 32 33
    std::vector<std::shared_ptr<framework::OpDesc>> ops = block->Ops();
    ops_of_block_.resize(ops.size());
    for (int i = 0; i < ops.size(); ++i) {
      std::shared_ptr<framework::OpDesc> op_desc = ops[i];
34
      DLOG << "create op: " << op_desc->Type();
H
update  
hjchen2 已提交
35 36 37
      auto op_handler = framework::OpRegistry<CPU>::CreateOp(
          op_desc->Type(), op_desc->GetInputs(), op_desc->GetOutputs(),
          op_desc->GetAttrMap(), scope_);
38
      op_handler->Init();
H
update  
hjchen2 已提交
39 40 41 42 43 44 45 46 47 48 49 50
      ops_of_block_[i] = op_handler;
    }
  }

  void Run() {
    for (auto &op_handler : ops_of_block_) {
      op_handler->InferShape();
      op_handler->Run();
    }
  }

 private:
51
  framework::Scope *scope_;
H
update  
hjchen2 已提交
52 53 54
  std::vector<OperatorPtr> ops_of_block_;
};

55 56 57 58 59 60 61
template <>
bool WhileKernel<CPU, float>::Init(WhileParam<CPU> *param) {
  return true;
}

template <>
void WhileKernel<CPU, float>::Compute(const WhileParam<CPU> &param) {
H
update  
hjchen2 已提交
62 63 64 65 66 67
  auto &current_scope = param.scope_->NewScope();
  StepExecutor executor(param.sub_block_, &current_scope);
  while (param.cond_->data<bool>()[0]) {
    executor.Run();
  }
  param.scope_->DeleteScope(&current_scope);
68 69 70 71
}

}  // namespace operators
}  // namespace paddle_mobile
H
update  
hjchen2 已提交
72 73

#endif  // WHILE_OP