executor.md 2.1 KB
Newer Older
Y
Yang Yang(Tony) 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Executor Desgin Doc

## Overview

`Executor` evaluates a `ProgramDesc`. Essentially, it instantializes Variables and Operators, then run all the operators

```c++
void Executor::Run(const ProgramDesc& pdesc, Scope* scope) {
  auto& block = pdesc.blocks(0);
  auto& device = device_contexts_[0];

  // Instantiate all the vars in the global scope
  for (auto& var : block.vars()) {
    scope->NewVar(var.name());
  }

  // Decide which operator should be run
Y
Yang Yang 已提交
18
  std::vector<bool> should_run = Prune(pdesc);
Y
Yang Yang(Tony) 已提交
19 20 21 22 23 24 25

  // Run the block
  Scope& local_scope = scope->NewScope();
  for (size_t i = 0; i < should_run.size(); ++i) {
    if (should_run[i]) {
      for (auto var : block.ops(i).outputs()) {
        for (auto argu : var.arguments()) {
Y
Yang Yang 已提交
26
          // Create temp variable in the local_scope
Y
Yang Yang(Tony) 已提交
27 28 29 30 31 32 33 34 35 36 37 38
          if (local_scope.FindVar(argu) == nullptr) {
            local_scope.NewVar(argu);
          }
        }
      }
      auto op = paddle::framework::OpRegistry::CreateOp(block.ops(i));
      op->Run(local_scope, *device);
    }
  }
}
```

Y
Yang Yang 已提交
39
## Challenge
Y
Yang Yang(Tony) 已提交
40

Y
Yang Yang 已提交
41
It is not hard to simply evaluate a graph. However, it is hard to determine which op should be run. Consider the following different situations.
Y
Yang Yang(Tony) 已提交
42

Y
Yang Yang 已提交
43 44 45 46 47 48 49 50
```python
# Case 1: run foward pass.
cost_np = executor.run(target=cost)
# Case 2: run backward passing.
opts_np, _ = executor.run(target=[cost, opt])
# Case 3: run checkpointing
_ = executor.run(target=checkpoint)
```
Y
Yang Yang(Tony) 已提交
51

Y
Yang Yang 已提交
52
We want to support the evaluation of both variables and operators.
Y
Yang Yang(Tony) 已提交
53

Y
Yang Yang 已提交
54
## Solution
Y
Yang Yang(Tony) 已提交
55

Y
Yang Yang 已提交
56
To support evaluation of operators, we add `is_target` field in the `OpDesc`.
Y
Yang Yang(Tony) 已提交
57

Y
Yang Yang 已提交
58 59 60 61 62 63 64 65 66
```c++
message OpDesc {
  required string type = 3;
  repeated Var inputs = 1;
  repeated Var outputs = 2;
  repeated Attr attrs = 4;
  required bool is_target = 5 [ default = false ]; // true if the op is target
};
```
Y
Yang Yang(Tony) 已提交
67

Y
Yang Yang 已提交
68
To support evaluation of variables, we add [fetch_op](https://github.com/PaddlePaddle/Paddle/pull/4599). For each variable in the `target`, we insert a `fetch_op` into the `ProgramDesc`. (Also, a user may want to overwrite a variable, so we also added [feed_op](https://github.com/PaddlePaddle/Paddle/pull/4599). )