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

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

Y
Yi Wang 已提交
17 18
#include <list>
#include <map>
Q
qiaolongfei 已提交
19
#include <string>
Q
qiaolongfei 已提交
20

Q
qiaolongfei 已提交
21 22 23 24 25
#include "paddle/framework/variable.h"

namespace paddle {
namespace framework {

Q
Qiao Longfei 已提交
26 27
class Scope;

Q
qiaolongfei 已提交
28
/**
29 30
 * @brief Scope that manage all variables.
 *
31
 * Scope is an association of a name to Variable. All variables belong to
32
 * Scope. You need to specify a scope to run a Net, i.e., `net.Run(&scope)`.
33 34
 * One net can run in different scopes and update different variable in the
 * scope.
Q
qiaolongfei 已提交
35 36
 */
class Scope {
Q
qiaolongfei 已提交
37
 public:
38
  Scope() {}
Y
Yi Wang 已提交
39
  ~Scope();
40

Y
Yi Wang 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  // Create a sub-scope. Returns a reference other than a pointer so
  // to prevent from manual deletion.
  Scope& NewScope();

  // Create a variable with given name if it doesn't exist.
  Variable* NewVar(const std::string& name);

  // Create a variable with a scope-unique name.
  Variable* NewVar();

  // Find a variable in the scope or any of its ancestors.  Returns
  // nullptr if cannot find.
  Variable* FindVar(const std::string& name) const;

  // Find the scope or an ancestor scope that contains the given variable.
  Scope* FindScope(const Variable* var) const;

  // Returns the name of a variable in this scope.
  std::string VarName(const Variable* var) const { return var->name_; }
60

Q
qiaolongfei 已提交
61
 private:
Y
Yi Wang 已提交
62 63 64 65 66 67
  // Call Scope::NewScope for a sub-scope.
  explicit Scope(Scope* parent) : parent_(parent) {}

  std::map<std::string, Variable*> vars_;
  std::list<Scope*> kids_;
  Scope* parent_{nullptr};
Q
qiaolongfei 已提交
68 69 70 71
};

}  // namespace framework
}  // namespace paddle