scope.md 1.5 KB
Newer Older
Q
qiaolongfei 已提交
1 2 3 4 5 6 7
# Scope

### Define

Scope is a context to manage Variables. It mainly contains a map from Variable name to Variable. Net will get and update variable throw scope.

```cpp
Y
Yu Yang 已提交
8 9 10 11
class Variable;
using VariablePtr = std::shared_ptr<Variable>;

class Scope final {
Q
qiaolongfei 已提交
12
 public:
Y
Yu Yang 已提交
13 14 15 16 17
  Scope();
  Scope(const std::shared_ptr<Scope>& parent);

  //! Get Variable in this scope.
  //! @return nullptr if no such variable.
Q
qiaolongfei 已提交
18
  const VariablePtr& GetVar(const std::string& name) const;
Y
Yu Yang 已提交
19 20

  //! Create or get a variable in this scope.
Q
qiaolongfei 已提交
21
  VariablePtr& GetOrCreateVar(const std::string& name);
Q
qiaolongfei 已提交
22 23

private:
Y
Yu Yang 已提交
24 25 26 27
  /// variable name -> variable
  std::unordered_map<std::string, VariablePtr> vars_;
  std::shared_ptr<Scope> parent_{nullptr};
};
Q
qiaolongfei 已提交
28 29 30
```

You need to specify a scope to run a Net. One net can run in different scopes and update different variable in the scope. If you did not specify one, It will run in a default scope.
Y
Yu Yang 已提交
31 32 33

```cpp
Scope global;
Q
qiaolongfei 已提交
34 35
auto x = NewVar("X");  // x is created in scope global, implicitly.
auto y = NewVar("Y");
Y
Yu Yang 已提交
36
Net net1;
Q
qiaolongfei 已提交
37 38
net1.AddOp("add", {x, y}, {x});  // x = x + y;
net1.Run();
Y
Yu Yang 已提交
39 40 41

for (size_t i=0; i<10; ++i) {
  Scope local;
Q
qiaolongfei 已提交
42
  auto tmp = NewVar("tmp");  // tmp is created in scope local.
Y
Yu Yang 已提交
43
  Net net2;
Q
qiaolongfei 已提交
44 45
  net2.AddOp("add", {x, y}, {tmp});
  net2.Run();  // tmp = x + y;
Y
Yu Yang 已提交
46 47 48
}

Net net3;
Q
qiaolongfei 已提交
49
net3.AddOp("add", {x, y}, {"tmp"});  // error! cannot found "tmp" in global scope.
Y
Yu Yang 已提交
50

Q
qiaolongfei 已提交
51 52 53 54 55 56 57
```

### Chain structure

Scope has a pointer point to it's parent scope, this is mainly used in RNN when it need to create many stepNet.


Y
Yu Yang 已提交
58
### Scope Guard