pass.h 12.0 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
#include <functional>
#include <map>
19
#include <memory>
X
Xin Pan 已提交
20
#include <string>
21 22
#include <unordered_map>
#include <unordered_set>
C
chengduo 已提交
23
#include <vector>
W
wanghuancoder 已提交
24

X
Xin Pan 已提交
25 26 27
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/ir/node.h"
#include "paddle/fluid/framework/program_desc.h"
X
Xin Pan 已提交
28
#include "paddle/fluid/platform/variant.h"
29
#include "paddle/utils/any.h"
X
Xin Pan 已提交
30

X
start  
Xin Pan 已提交
31
namespace paddle {
X
Xin Pan 已提交
32
namespace framework {
33 34 35 36 37 38
namespace details {
using ProgramDescs = std::vector<ProgramDesc>;
constexpr char kProgramDescs[] = "program_descs";
constexpr char kStartupProgramDescs[] = "startup_program_descs";
}  // namespace details

39
namespace ir {
W
wanghuancoder 已提交
40
class Graph;
41

X
Xin Pan 已提交
42 43
template <typename PassType>
struct PassRegistrar;
X
Xin Pan 已提交
44

C
chengduo 已提交
45 46
typedef std::unordered_set<std::string> PassRecorder;
constexpr char kPassRecorder[] = "pass_recorder";
47 48 49
constexpr char kEmbEltwiseLayernormPass[] =
    "embedding_eltwise_layernorm_fuse_pass_flag";
constexpr char kMultiheadMatmulPass[] = "multihead_matmul_fuse_pass_flag";
C
chengduo 已提交
50

X
Xin Pan 已提交
51 52 53
class Pass {
 public:
  Pass() = default;
X
Xin Pan 已提交
54 55 56 57 58 59 60 61 62
  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 已提交
63

64 65
  std::string Type() const { return type_; }

66
  Graph *Apply(Graph *graph) const;
X
Xin Pan 已提交
67

X
Xin Pan 已提交
68
  // Get a reference to the attributed previously set.
X
Xin Pan 已提交
69 70
  template <typename AttrType>
  AttrType &Get(const std::string &attr_name) const {
71 72 73
    PADDLE_ENFORCE_NE(attrs_.find(attr_name), attrs_.end(),
                      platform::errors::InvalidArgument(
                          "Attribute %s not registered for pass.", attr_name));
S
sneaxiy 已提交
74
    try {
75 76
      return *paddle::any_cast<AttrType *>(attrs_.at(attr_name));
    } catch (paddle::bad_any_cast &) {
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
      auto TypeToString = [](const std::type_info &info) -> std::string {
        if (std::type_index(info) == std::type_index(typeid(bool *))) {
          return "bool";
        } else if (std::type_index(info) == std::type_index(typeid(int *))) {
          return "int";
        } else if (std::type_index(info) ==
                   std::type_index(typeid(const int *))) {
          return "const int";
        } else if (std::type_index(info) ==
                   std::type_index(typeid(std::string *))) {
          return "std::string";
        }
        return info.name();
      };

      PADDLE_THROW(platform::errors::InvalidArgument(
93
          "Invalid type for attritube %s, expected: %s, actual: %s.", attr_name,
94 95
          TypeToString(typeid(AttrType *)),
          TypeToString(attrs_.at(attr_name).type())));
S
sneaxiy 已提交
96
    }
X
Xin Pan 已提交
97 98
  }

X
fix  
Xin Pan 已提交
99
  bool Has(const std::string &attr_name) const {
S
sneaxiy 已提交
100
    return attrs_.count(attr_name) > 0;
X
fix  
Xin Pan 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113
  }

  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 已提交
114
  // Set a pointer to the attribute. Pass takes ownership of the attribute.
X
Xin Pan 已提交
115 116
  template <typename AttrType>
  void Set(const std::string &attr_name, AttrType *attr) {
117
    if (default_pass_attrs_.count(attr_name) == 0) {
118 119 120 121
      PADDLE_ENFORCE_EQ(
          attrs_.count(attr_name), 0,
          platform::errors::AlreadyExists(
              "Attribute %s already set in the pass.", attr_name));
122 123 124 125
    } else {
      VLOG(3) << "Setting the attribute " << attr_name << " for the pass "
              << type_;
    }
X
Xin Pan 已提交
126 127
    attrs_[attr_name] = attr;
    attr_dels_[attr_name] = [attr, attr_name]() {
M
minqiyang 已提交
128
      VLOG(3) << "deleting " << attr_name;
X
Xin Pan 已提交
129 130 131 132
      delete attr;
    };
  }

X
Xin Pan 已提交
133 134
  // Set a pointer to the attribute. Pass doesn't take ownership. Caller
  // should delete the attribute.
X
Xin Pan 已提交
135 136
  template <typename AttrType>
  void SetNotOwned(const std::string &attr_name, AttrType *attr) {
137 138 139
    PADDLE_ENFORCE_EQ(attrs_.count(attr_name), 0,
                      platform::errors::AlreadyExists(
                          "Attribute %s already set in the pass.", attr_name));
X
Xin Pan 已提交
140 141 142
    attrs_[attr_name] = attr;
  }

143 144 145 146 147 148
  static void ApplyPassesToProgram(const std::vector<const Pass *> &passes,
                                   ProgramDesc *main_program,
                                   ProgramDesc *startup_program);

  virtual bool SupportApplyProgramViaGraph() const { return true; }

X
Xin Pan 已提交
149
 protected:
150
  virtual void ApplyImpl(Graph *graph) const {
151
    PADDLE_THROW(platform::errors::Unimplemented(
152
        "The virtual pass called is not implemented."));
153
  }
X
Xin Pan 已提交
154

155 156 157
  virtual void ApplyImpl(ProgramDesc *main_program,
                         ProgramDesc *startup_program) const;

158 159
  static void ConvertToPrograms(ir::Graph *graph, ProgramDesc *main_program,
                                ProgramDesc *startup_program);
160

C
chengduo 已提交
161 162 163 164
  // Some Pass must be placed before this Pass, and some
  // Pass must be placed after this Pass.
  virtual void CheckPrevPass() const {}

X
Xin Pan 已提交
165
 private:
X
Xin Pan 已提交
166 167 168 169 170 171 172 173 174 175 176 177
  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());
  }

178 179
  // Pass doesn't take ownership. PassRegistrar should delete default_attrs
  void RegisterDefaultPassAttrs(
180
      std::map<std::string, paddle::any> default_attr_values) {
181 182 183 184 185 186
    for (auto const &attr_name : default_attr_values) {
      default_pass_attrs_.insert(attr_name.first);
    }
    attrs_.insert(default_attr_values.begin(), default_attr_values.end());
  }

187 188
  void RegisterType(const std::string &type) { type_ = type; }

X
Xin Pan 已提交
189
  mutable bool applied_{false};
190
  std::string type_;
X
Xin Pan 已提交
191
  std::unordered_set<std::string> required_pass_attrs_;
192
  std::unordered_set<std::string> default_pass_attrs_;
X
Xin Pan 已提交
193
  std::unordered_set<std::string> required_graph_attrs_;
194
  std::map<std::string, paddle::any> attrs_;
X
Xin Pan 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  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() {}
211
};
X
Xin Pan 已提交
212 213 214 215 216 217 218 219 220

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

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

X
Xin Pan 已提交
221
  void Insert(const std::string &pass_type, const PassCreator &pass_creator) {
222 223 224
    PADDLE_ENFORCE_NE(Has(pass_type), true,
                      platform::errors::AlreadyExists(
                          "Pass %s has been registered.", pass_type));
X
Xin Pan 已提交
225
    map_.insert({pass_type, pass_creator});
X
Xin Pan 已提交
226 227
  }

X
Xin Pan 已提交
228
  std::unique_ptr<Pass> Get(const std::string &pass_type) const {
229 230 231 232 233 234 235 236 237 238 239 240 241
    if (pass_type == "tensorrt_subgraph_pass") {
      PADDLE_ENFORCE_EQ(Has(pass_type), true,
                        platform::errors::InvalidArgument(
                            "Pass %s has not been registered. Please "
                            "use the paddle inference library "
                            "compiled with tensorrt or disable "
                            "the tensorrt engine in inference configuration! ",
                            pass_type));
    } else {
      PADDLE_ENFORCE_EQ(Has(pass_type), true,
                        platform::errors::InvalidArgument(
                            "Pass %s has not been registered.", pass_type));
    }
X
Xin Pan 已提交
242
    return map_.at(pass_type)();
X
Xin Pan 已提交
243 244 245 246 247 248 249 250 251 252 253 254
  }

 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) {
255 256 257 258
    PADDLE_ENFORCE_EQ(
        PassRegistry::Instance().Has(pass_type), false,
        platform::errors::AlreadyExists(
            "Pass '%s' is registered more than once.", pass_type));
X
Xin Pan 已提交
259
    PassRegistry::Instance().Insert(
260
        pass_type, [this, pass_type]() -> std::unique_ptr<Pass> {
X
Xin Pan 已提交
261 262 263
          std::unique_ptr<Pass> pass(new PassType());
          pass->RegisterRequiredPassAttrs(this->required_pass_attrs_);
          pass->RegisterRequiredGraphAttrs(this->required_graph_attrs_);
264
          pass->RegisterDefaultPassAttrs(this->default_attr_values_);
265
          pass->RegisterType(pass_type);
X
Xin Pan 已提交
266 267
          return pass;
        });
X
Xin Pan 已提交
268
  }
X
Xin Pan 已提交
269

270 271 272 273 274 275 276 277 278 279
  ~PassRegistrar() {
    for (auto &attr : default_attr_values_) {
      if (default_attr_dels_.find(attr.first) != default_attr_dels_.end()) {
        default_attr_dels_[attr.first]();
      }
    }
    default_attr_values_.clear();
    default_attr_dels_.clear();
  }

X
Xin Pan 已提交
280 281 282 283 284
  PassRegistrar<PassType> &RequirePassAttr(const std::string &attr) {
    required_pass_attrs_.insert(attr);
    return *this;
  }

285 286 287 288 289 290 291 292 293 294 295
  // PassRegistrar takes ownership of default_attr_value
  template <typename AttrType>
  PassRegistrar<PassType> &DefaultPassAttr(const std::string &attr,
                                           AttrType &&default_attr_value) {
    default_attr_values_[attr] = default_attr_value;
    default_attr_dels_[attr] = [default_attr_value, attr]() {
      delete default_attr_value;
    };
    return *this;
  }

X
Xin Pan 已提交
296 297 298 299 300 301 302 303
  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_;
304
  std::map<std::string, paddle::any> default_attr_values_;
305
  std::map<std::string, std::function<void(void)>> default_attr_dels_;
X
Xin Pan 已提交
306 307 308 309 310 311 312 313
};

#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)

X
Xin Pan 已提交
314
// Register a new pass that can be applied on the IR.
P
peizhilin 已提交
315 316 317 318 319 320 321 322 323 324 325 326
#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##__ UNUSED =        \
X
Xin Pan 已提交
327
          __pass_registrar_##pass_type##__
X
Xin Pan 已提交
328

P
peizhilin 已提交
329 330 331 332 333 334
#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##_ UNUSED =  \
X
Xin Pan 已提交
335 336
      TouchPassRegistrar_##pass_type()

337
}  // namespace ir
X
Xin Pan 已提交
338
}  // namespace framework
X
start  
Xin Pan 已提交
339
}  // namespace paddle