scope.md 2.4 KB
Newer Older
Y
Yu Yang 已提交
1
# What is a scope.
Q
qiaolongfei 已提交
2

Y
Yu Yang 已提交
3
## Overview
Q
qiaolongfei 已提交
4

Y
Yu Yang 已提交
5
预期使用场景。
Q
qiaolongfei 已提交
6

Y
Yu Yang 已提交
7 8 9
引出Scope的两个属性。
    1. Scope是Variable的Container
    2. Scope可以共享
Y
Yu Yang 已提交
10

Y
Yu Yang 已提交
11
## Scope 是一个Variable的Container
Y
Yu Yang 已提交
12

Y
Yu Yang 已提交
13
解释下为啥Scope是Variable的container。解释下面几个小点的原因。
Y
Yu Yang 已提交
14

Y
Yu Yang 已提交
15 16 17 18 19
    * 他只包含variable
    * 每一个variable也只属于一个Scope
    * 每一个Scope析构的时候,会同时析构variable
    * 只能通过Scope创建Vairable。
    * 只能通过Scope获取Variable。
Q
qiaolongfei 已提交
20

Y
Yu Yang 已提交
21 22
## Parent scope and local scope

Y
Yu Yang 已提交
23
Just like [scope](https://en.wikipedia.org/wiki/Scope_(computer_science)) in programming languages, `Scope` in the neural network can also be a local scope. There are two attributes about local scope.
Y
Yu Yang 已提交
24

Y
Yu Yang 已提交
25
1.  We can create local variables in a local scope. When that local scope are destroyed, all local variables should also be destroyed.
Y
Yu Yang 已提交
26
2.  Variables in a parent scope can be retrieved from local scopes of that parent scope, i.e., when user get a variable from a scope, it will try to search this variable in current scope. If there is no such variable in the local scope, `scope` will keep searching from its parent, until the variable is found or there is no parent.
Y
Yu Yang 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

```cpp
class Scope {
public:
  Scope(const std::shared_ptr<Scope>& scope): parent_(scope) {}

  Variable* Get(const std::string& name) const {
    Variable* var = GetVarLocally(name);
    if (var != nullptr) {
      return var;
    } else if (parent_ != nullptr) {
      return parent_->Get(name);
    } else {
      return nullptr;
    }
  }

private:
  std::shared_ptr<Scope> parent_ {nullptr};
};
```
Y
Yu Yang 已提交
48

Y
Yu Yang 已提交
49
In `Scope` class, there is a private data member called `parent_`. `parent_` is a smart pointer to its parent scope. When user `Get` a variable by its `name`, the `name` will be searched inside the current scope. If the variable cannot be found locally and parent scope is not a `nullptr`, the variable will be searched inside that parent scope. `parent_` pointer's default value is `nullptr`. It means that the scope is a global scope when `parent_` is nullptr.
Y
Yu Yang 已提交
50

Y
Yu Yang 已提交
51
A local scope is very useful when we implement Recurrent Neural Network. Each timestep of an RNN should be a `Net`. Each `Net` of timestep (`StepNet` for short) should use an independent local scope. Just like variables in a while loop is inside a local scope in programming languages. By using a single `StepNet` and changing local scope, we can implement an RNN easily.
Y
Yu Yang 已提交
52

Y
Yu Yang 已提交
53
# 接口实现
Y
Yu Yang 已提交
54

55
# 各个接口是啥意思,为啥这么设计