scope.h 6.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Q
qiaolongfei 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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

Q
qiaolongfei 已提交
15 16
#pragma once

M
minqiyang 已提交
17 18 19 20
extern "C" {
#include <xxhash.h>
}

Y
Yi Wang 已提交
21
#include <list>
M
minqiyang 已提交
22
#include <memory>
Q
qiaolongfei 已提交
23
#include <string>
M
minqiyang 已提交
24
#include <unordered_map>
25
#include <unordered_set>
M
minqiyang 已提交
26
#include <utility>
27
#include <vector>
Q
qiaolongfei 已提交
28

Y
Yi Wang 已提交
29 30
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/platform/macros.h"
31
#include "paddle/phi/core/utils/rw_lock.h"
Q
qiaolongfei 已提交
32

W
wanghuancoder 已提交
33 34 35 36 37 38
namespace paddle {
namespace framework {
class Variable;
}  // namespace framework
}  // namespace paddle

Q
qiaolongfei 已提交
39 40 41
namespace paddle {
namespace framework {

42 43 44 45 46 47 48 49 50 51
// TODO(zhiqiu): add more function in base class
class ScopeBase {
 public:
  /// Find a variable in the scope or any of its ancestors.  Returns
  /// nullptr if cannot find.
  /// Caller doesn't own the returned Variable.
  virtual Variable* FindVar(const std::string& name) const = 0;
  virtual ~ScopeBase() {}
};

Q
Qiao Longfei 已提交
52 53
class Scope;

54 55 56 57 58 59 60
class ScopeListener {
  // NOTE(xiongkun03) Abstract Class, doesn't have any attributes.
  // Used by VariableScope. If we modify the original scope, we
  // need synchronize changes to VariableScope. So we add listerer
  // in original Scope.
 public:
  virtual ~ScopeListener() {}
61
  virtual void onCreateVariable(const std::string& name, Variable* v) {}
62 63 64 65 66 67 68 69
  virtual void onDeleteVariable(const std::string& name) {}
  virtual void onRenameVariable(const std::string& old_name,
                                const std::string& new_name) {}
  virtual void onCreateScope(Scope* Scope) {}
  virtual void onDeleteScope(Scope* Scope) {}
  virtual void onClear() {}
};

Q
qiaolongfei 已提交
70
/**
71 72
 * @brief Scope that manage all variables.
 *
73
 * Scope is an association of a name to Variable. All variables belong to
74
 * Scope. You need to specify a scope to run a Net, i.e., `net.Run(&scope)`.
75 76
 * One net can run in different scopes and update different variable in the
 * scope.
Q
qiaolongfei 已提交
77
 */
78
class Scope : public ScopeBase {
Q
qiaolongfei 已提交
79
 public:
80
  Scope() {}
Y
Yi Wang 已提交
81
  ~Scope();
82

Y
Yu Yang 已提交
83 84 85 86 87
  /// Create a sub-scope. Returns a reference other than a pointer so
  /// to prevent from manual deletion.
  /// Mark it to const because that new kid scope cannot change parent scope.
  Scope& NewScope() const;

88 89
  /// Create a sub-scope for current scope but do not record it in the kids to
  /// avoid performance problems.
90
  std::unique_ptr<Scope> NewTmpScope() const;
Q
Qiao Longfei 已提交
91

Y
Yu Yang 已提交
92
  /// Create a variable with given name if it doesn't exist.
93
  /// Caller doesn't own the returned Variable.
D
dongzhihong 已提交
94
  Variable* Var(const std::string& name);
Y
Yi Wang 已提交
95

Y
Yu Yang 已提交
96
  /// Create a variable with a scope-unique name.
97
  /// Caller doesn't own the returned Variable.
Y
Yu Yang 已提交
98
  Variable* Var(std::string* name = nullptr);
Y
Yi Wang 已提交
99

Y
Yancey1989 已提交
100
  void EraseVars(const std::vector<std::string>& var_names);
101

102 103 104
  // Erase all variables except the given `vars`
  void EraseVarsExcept(const std::unordered_set<Variable*>& vars);

Y
Yu Yang 已提交
105 106
  /// Find a variable in the scope or any of its ancestors.  Returns
  /// nullptr if cannot find.
107
  /// Caller doesn't own the returned Variable.
Y
Yi Wang 已提交
108 109
  Variable* FindVar(const std::string& name) const;

110 111 112 113
  // Get a variable in the scope or any of its ancestors. Enforce
  /// the returned Variable is not nullptr
  Variable* GetVar(const std::string& name) const;

S
sneaxiy 已提交
114 115 116 117 118
  /// Find a variable in the current scope.
  /// Return nullptr if cannot find.
  /// Caller doesn't own the returned Variable.
  Variable* FindLocalVar(const std::string& name) const;

119
  const Scope* parent() const { return parent_; }
Y
Yan Chunwei 已提交
120

Y
Yu Yang 已提交
121 122 123
  /// Find the scope or an ancestor scope that contains the given variable.
  const Scope* FindScope(const Variable* var) const;

124 125 126
  /// Find the scope or an ancestor scope that contains the given variable name.
  const Scope* FindScope(const std::string& name) const;

127
  void DeleteScope(Scope* scope) const;
Y
Yu Yang 已提交
128

Y
Yu Yang 已提交
129 130
  /// Drop all kids scopes belonged to this scope.
  void DropKids();
131

M
minqiyang 已提交
132 133 134
  /// Find if a scope exists in the kid scopes
  bool HasKid(const Scope* scope) const;

135 136
  const std::list<Scope*>& kids() const { return kids_; }

137
  // enumerate all the variable names current contains.
Y
Yang Yu 已提交
138
  std::vector<std::string> LocalVarNames() const;
139

140 141 142
  // enumerate all the variables current contains.
  std::vector<Variable*> LocalVars();

Y
Yu Yang 已提交
143 144 145 146
  // Rename variable to a new name
  void Rename(const std::string& origin_name,
              const std::string& new_name) const;

147 148 149
  // Return the number of variables in scope
  size_t Size() { return vars_.size(); }

Y
Yu Yang 已提交
150 151 152
  // Rename variable to a new name and return the new name
  std::string Rename(const std::string& origin_name) const;

L
Leo Chen 已提交
153
  void AddListener(const std::shared_ptr<ScopeListener>& listener);
154

L
Leo Chen 已提交
155
  void DelListener(const std::shared_ptr<ScopeListener>& listener);
156

157 158
  bool HasListener(const std::shared_ptr<ScopeListener>& listener);

159
 protected:
M
minqiyang 已提交
160 161 162 163 164 165 166
  struct KeyHasher {
    std::size_t operator()(const std::string& key) const {
      return XXH32(key.c_str(), key.size(), 1);
    }
  };

  mutable std::unordered_map<std::string, std::unique_ptr<Variable>, KeyHasher>
M
minqiyang 已提交
167
      vars_;
168

169
 private:
Y
Yi Wang 已提交
170
  // Call Scope::NewScope for a sub-scope.
Y
Yu Yang 已提交
171
  explicit Scope(Scope const* parent) : parent_(parent) {}
Y
Yi Wang 已提交
172

T
tensor-tang 已提交
173 174 175 176 177 178
  // Called by Var.
  Variable* VarInternal(const std::string& name);

  // Called by FindScope.
  const Scope* FindScopeInternal(const Variable* var) const;

179 180 181
  // Called by FindScope.
  const Scope* FindScopeInternal(const std::string& name) const;

T
tensor-tang 已提交
182 183 184 185
  // Called by Rename.
  void RenameInternal(const std::string& origin_name,
                      const std::string& new_name) const;

T
tensor-tang 已提交
186
  // Called by FindVar recursively.
T
tensor-tang 已提交
187 188
  Variable* FindVarInternal(const std::string& name) const;

T
tensor-tang 已提交
189
  // Called by FindVarInternal and Var.
T
tensor-tang 已提交
190 191
  Variable* FindVarLocally(const std::string& name) const;

192
  // Scope in `kids_` are owned by this class.
Y
Yu Yang 已提交
193
  mutable std::list<Scope*> kids_;
194
  const Scope* parent_{nullptr};
L
Leo Chen 已提交
195
  std::list<std::shared_ptr<ScopeListener>> listeners_;
D
format  
dongzhihong 已提交
196 197

  DISABLE_COPY_AND_ASSIGN(Scope);
Y
Yancey1989 已提交
198

199 200
#ifndef PADDLE_ON_INFERENCE

Y
Yancey1989 已提交
201
 private:
202 203
  mutable phi::RWLock kids_lock_;
  mutable phi::RWLock vars_lock_;
204
#endif
Q
qiaolongfei 已提交
205
};
206 207 208 209 210

// Generate some debug string about the inherience structure of scope, quite
// naive.
std::string GenScopeTreeDebugInfo(Scope*);

Q
qiaolongfei 已提交
211 212
}  // namespace framework
}  // namespace paddle