pass.h 9.1 KB
Newer Older
X
Xin Pan 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
X
start  
Xin Pan 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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

#pragma once

X
Xin Pan 已提交
17 18 19 20
#include <functional>
#include <map>
#include <string>

X
Xin Pan 已提交
21 22 23
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/ir/node.h"
#include "paddle/fluid/framework/program_desc.h"
D
dzhwinter 已提交
24
#include "paddle/fluid/platform/port.h"
X
Xin Pan 已提交
25
#include "paddle/fluid/platform/variant.h"
X
Xin Pan 已提交
26

X
start  
Xin Pan 已提交
27
namespace paddle {
X
Xin Pan 已提交
28
namespace framework {
29
namespace ir {
X
Xin Pan 已提交
30 31
template <typename PassType>
struct PassRegistrar;
X
Xin Pan 已提交
32 33 34 35

class Pass {
 public:
  Pass() = default;
X
Xin Pan 已提交
36 37 38 39 40 41 42 43 44
  virtual ~Pass() {
    for (auto &attr : attrs_) {
      if (attr_dels_.find(attr.first) != attr_dels_.end()) {
        attr_dels_[attr.first]();
      }
    }
    attrs_.clear();
    attr_dels_.clear();
  }
X
Xin Pan 已提交
45

46 47
  std::string Type() const { return type_; }

X
Xin Pan 已提交
48
  std::unique_ptr<Graph> Apply(std::unique_ptr<Graph> graph) const;
X
Xin Pan 已提交
49

X
Xin Pan 已提交
50
  // Get a reference to the attributed previously set.
X
Xin Pan 已提交
51 52
  template <typename AttrType>
  AttrType &Get(const std::string &attr_name) const {
X
Xin Pan 已提交
53 54
    PADDLE_ENFORCE(attrs_.find(attr_name) != attrs_.end(),
                   "%s attr not registered for pass.", attr_name);
X
Xin Pan 已提交
55 56 57
    return *boost::any_cast<AttrType *>(attrs_.at(attr_name));
  }

X
fix  
Xin Pan 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
  bool Has(const std::string &attr_name) const {
    return attrs_.find(attr_name) != attrs_.end();
  }

  void Erase(const std::string &attr_name) {
    if (!Has(attr_name)) {
      return;
    }
    if (attr_dels_.find(attr_name) != attr_dels_.end()) {
      attr_dels_[attr_name]();
      attr_dels_.erase(attr_name);
    }
    attrs_.erase(attr_name);
  }

X
Xin Pan 已提交
73
  // Set a pointer to the attribute. Pass takes ownership of the attribute.
X
Xin Pan 已提交
74 75
  template <typename AttrType>
  void Set(const std::string &attr_name, AttrType *attr) {
X
Xin Pan 已提交
76 77
    PADDLE_ENFORCE(attrs_.count(attr_name) == 0, "%s already set in the pass",
                   attr_name);
X
Xin Pan 已提交
78 79
    attrs_[attr_name] = attr;
    attr_dels_[attr_name] = [attr, attr_name]() {
80
      VLOG(30) << "deleting " << attr_name;
X
Xin Pan 已提交
81 82 83 84
      delete attr;
    };
  }

X
Xin Pan 已提交
85 86
  // Set a pointer to the attribute. Pass doesn't take ownership. Caller
  // should delete the attribute.
X
Xin Pan 已提交
87 88
  template <typename AttrType>
  void SetNotOwned(const std::string &attr_name, AttrType *attr) {
X
fix  
Xin Pan 已提交
89 90
    PADDLE_ENFORCE(attrs_.count(attr_name) == 0, "%s already set in the pass",
                   attr_name);
X
Xin Pan 已提交
91 92 93
    attrs_[attr_name] = attr;
  }

X
Xin Pan 已提交
94
 protected:
95 96 97
  virtual std::unique_ptr<Graph> ApplyImpl(std::unique_ptr<Graph> graph) const {
    LOG(FATAL) << "Calling virtual Pass not implemented.";
  }
X
Xin Pan 已提交
98

X
Xin Pan 已提交
99
 private:
X
Xin Pan 已提交
100 101 102 103 104 105 106 107 108 109 110 111
  template <typename PassType>
  friend struct PassRegistrar;

  void RegisterRequiredPassAttrs(const std::unordered_set<std::string> &attrs) {
    required_pass_attrs_.insert(attrs.begin(), attrs.end());
  }

  void RegisterRequiredGraphAttrs(
      const std::unordered_set<std::string> &attrs) {
    required_graph_attrs_.insert(attrs.begin(), attrs.end());
  }

112 113
  void RegisterType(const std::string &type) { type_ = type; }

X
Xin Pan 已提交
114
  mutable bool applied_{false};
115
  std::string type_;
X
Xin Pan 已提交
116 117
  std::unordered_set<std::string> required_pass_attrs_;
  std::unordered_set<std::string> required_graph_attrs_;
X
Xin Pan 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  std::map<std::string, boost::any> attrs_;
  std::map<std::string, std::function<void(void)>> attr_dels_;
};

using PassCreator = std::function<std::unique_ptr<Pass>()>;

class Registrar {
 public:
  // In our design, various kinds of passes,
  // have their corresponding registry and registrar. The action of
  // registration is in the constructor of a global registrar variable, which
  // are not used in the code that calls package framework, and would
  // be removed from the generated binary file by the linker. To avoid such
  // removal, we add Touch to all registrar classes and make USE_PASS macros to
  // call this method. So, as long as the callee code calls USE_PASS, the global
  // registrar variable won't be removed by the linker.
  void Touch() {}
135
};
X
Xin Pan 已提交
136 137 138 139 140 141 142 143 144

class PassRegistry {
 public:
  static PassRegistry &Instance();

  bool Has(const std::string &pass_type) const {
    return map_.find(pass_type) != map_.end();
  }

X
Xin Pan 已提交
145 146 147
  void Insert(const std::string &pass_type, const PassCreator &pass_creator) {
    PADDLE_ENFORCE(!Has(pass_type), "Pass %s has been registered", pass_type);
    map_.insert({pass_type, pass_creator});
X
Xin Pan 已提交
148 149
  }

X
Xin Pan 已提交
150 151 152 153
  std::unique_ptr<Pass> Get(const std::string &pass_type) const {
    PADDLE_ENFORCE(Has(pass_type), "Pass %s has not been registered",
                   pass_type);
    return map_.at(pass_type)();
X
Xin Pan 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167
  }

 private:
  PassRegistry() = default;
  std::unordered_map<std::string, PassCreator> map_;

  DISABLE_COPY_AND_ASSIGN(PassRegistry);
};

template <typename PassType>
struct PassRegistrar : public Registrar {
  explicit PassRegistrar(const char *pass_type) {
    PADDLE_ENFORCE(!PassRegistry::Instance().Has(pass_type),
                   "'%s' is registered more than once.", pass_type);
X
Xin Pan 已提交
168
    PassRegistry::Instance().Insert(
169
        pass_type, [this, pass_type]() -> std::unique_ptr<Pass> {
X
Xin Pan 已提交
170 171 172
          std::unique_ptr<Pass> pass(new PassType());
          pass->RegisterRequiredPassAttrs(this->required_pass_attrs_);
          pass->RegisterRequiredGraphAttrs(this->required_graph_attrs_);
173
          pass->RegisterType(pass_type);
X
Xin Pan 已提交
174 175
          return pass;
        });
X
Xin Pan 已提交
176
  }
X
Xin Pan 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190

  PassRegistrar<PassType> &RequirePassAttr(const std::string &attr) {
    required_pass_attrs_.insert(attr);
    return *this;
  }

  PassRegistrar<PassType> &RequireGraphAttr(const std::string &attr) {
    required_graph_attrs_.insert(attr);
    return *this;
  }

 private:
  std::unordered_set<std::string> required_pass_attrs_;
  std::unordered_set<std::string> required_graph_attrs_;
X
Xin Pan 已提交
191 192 193 194 195 196 197 198
};

#define STATIC_ASSERT_PASS_GLOBAL_NAMESPACE(uniq_name, msg)                   \
  struct __test_global_namespace_##uniq_name##__ {};                          \
  static_assert(std::is_same<::__test_global_namespace_##uniq_name##__,       \
                             __test_global_namespace_##uniq_name##__>::value, \
                msg)

D
dzhwinter 已提交
199
#if !defined(_WIN32)
X
Xin Pan 已提交
200
// Register a new pass that can be applied on the IR.
X
Xin Pan 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213
#define REGISTER_PASS(pass_type, pass_class)                          \
  STATIC_ASSERT_PASS_GLOBAL_NAMESPACE(                                \
      __reg_pass__##pass_type,                                        \
      "REGISTER_PASS must be called in global namespace");            \
  static ::paddle::framework::ir::PassRegistrar<pass_class>           \
      __pass_registrar_##pass_type##__(#pass_type);                   \
  int TouchPassRegistrar_##pass_type() {                              \
    __pass_registrar_##pass_type##__.Touch();                         \
    return 0;                                                         \
  }                                                                   \
  static ::paddle::framework::ir::PassRegistrar<pass_class>           \
      &__pass_tmp_registrar_##pass_type##__ __attribute__((unused)) = \
          __pass_registrar_##pass_type##__
X
Xin Pan 已提交
214 215 216 217 218 219 220 221

#define USE_PASS(pass_type)                                           \
  STATIC_ASSERT_PASS_GLOBAL_NAMESPACE(                                \
      __use_pass_itself_##pass_type,                                  \
      "USE_PASS must be called in global namespace");                 \
  extern int TouchPassRegistrar_##pass_type();                        \
  static int use_pass_itself_##pass_type##_ __attribute__((unused)) = \
      TouchPassRegistrar_##pass_type()
D
dzhwinter 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
#else
// windows version of __attribute__((unused))
#define UNUSED(x) __pragma(warning(suppress : 4100)) x
#define REGISTER_PASS(pass_type, pass_class)                        \
  STATIC_ASSERT_PASS_GLOBAL_NAMESPACE(                              \
      __reg_pass__##pass_type,                                      \
      "REGISTER_PASS must be called in global namespace");          \
  static ::paddle::framework::ir::PassRegistrar<pass_class>         \
      __pass_registrar_##pass_type##__(#pass_type);                 \
  int TouchPassRegistrar_##pass_type() {                            \
    __pass_registrar_##pass_type##__.Touch();                       \
    return 0;                                                       \
  }                                                                 \
  static ::paddle::framework::ir::PassRegistrar<pass_class> UNUSED( \
      &__pass_tmp_registrar_##pass_type##__) =                      \
      __pass_registrar_##pass_type##__

#define USE_PASS(pass_type)                           \
  STATIC_ASSERT_PASS_GLOBAL_NAMESPACE(                \
      __use_pass_itself_##pass_type,                  \
      "USE_PASS must be called in global namespace"); \
  extern int TouchPassRegistrar_##pass_type();        \
  static int UNUSED(use_pass_itself_##pass_type##_) = \
      TouchPassRegistrar_##pass_type()
X
Xin Pan 已提交
246

D
dzhwinter 已提交
247
#endif  // !_WIN32
248
}  // namespace ir
X
Xin Pan 已提交
249
}  // namespace framework
X
start  
Xin Pan 已提交
250
}  // namespace paddle