scope.h 1.8 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

Q
qiaolongfei 已提交
17
#include <string>
Q
qiaolongfei 已提交
18
#include <unordered_map>
19
#include <vector>
Q
qiaolongfei 已提交
20

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

namespace paddle {
namespace framework {

/**
27 28 29 30
 * Scope is an association of a name to Variable. All variables belong to
 * `Scope`. You need to specify a scope to run a Net, i.e., `net.Run(&scope)`.
 * One net can run in different scopes and update different variable in the
 * scope.
Q
qiaolongfei 已提交
31 32 33 34 35
 */
class Scope {
 public:
  Scope() {}

36
  explicit Scope(const std::shared_ptr<Scope>& scope) : parent_(scope) {}
Q
qiaolongfei 已提交
37 38 39 40 41

  ~Scope() {}

  // Create Variable in this Scope. Return error if Variable already been
  // created.
Q
qiaolongfei 已提交
42
  Variable* CreateVariable(const std::string& name);
Q
qiaolongfei 已提交
43 44

  // Get Variable from this Scope, this function will recursive find Variable
45
  // from it's parent scope. Return nullptr if not found.
Q
qiaolongfei 已提交
46 47
  Variable* GetVariable(const std::string& name) const;

Q
qiaolongfei 已提交
48
  // Find and return Variables in the scope it self.
Q
qiaolongfei 已提交
49 50
  Variable* GetVarLocally(const std::string& name) const;

Q
qiaolongfei 已提交
51
  // Find if there is a Variable in this scope and it's parent scope
Q
qiaolongfei 已提交
52
  bool HasVariable(const std::string& name);
Q
qiaolongfei 已提交
53 54 55

 private:
  std::unordered_map<std::string, std::unique_ptr<Variable>> vars_;
56
  std::shared_ptr<Scope> parent_{nullptr};
Q
qiaolongfei 已提交
57 58 59 60
};

}  // namespace framework
}  // namespace paddle