op_version_registry.h 13.9 KB
Newer Older
1
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

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

#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

23
#include "paddle/fluid/framework/op_version_proto.h"
24
#include "paddle/fluid/platform/enforce.h"
25
#include "paddle/phi/core/macros.h"
26
#include "paddle/utils/none.h"
27 28 29 30 31

namespace paddle {
namespace framework {
namespace compatible {

32 33 34 35
namespace pb {
class OpVersionMap;
}  // namespace pb

36
using OpAttrVariantT =
R
Ruibiao Chen 已提交
37 38 39 40 41 42 43 44 45 46 47 48
    paddle::variant<bool,                     /* AttrType::BOOL */
                    float,                    /* AttrType::FLOAT */
                    int32_t,                  /* AttrType::INT */
                    int64_t,                  /* AttrType::LONG*/
                    std::string,              /* AttrType::STRING */
                    std::vector<bool>,        /* AttrType::BOOLS */
                    std::vector<float>,       /* AttrType::FLOATS */
                    std::vector<int32_t>,     /* AttrType::INTS */
                    std::vector<int64_t>,     /* AttrType::LONGS */
                    std::vector<std::string>, /* AttrType::STRINGS */
                    paddle::none_t            /* None */
                    >;
49 50 51

struct OpUpdateInfo {
  virtual ~OpUpdateInfo() = default;
52 53
};

54
struct OpAttrInfo : OpUpdateInfo {
55 56
  OpAttrInfo(const std::string& name,
             const std::string& remark,
57
             const OpAttrVariantT& default_value = paddle::none)
58 59 60 61 62
      : name_{name}, default_value_{default_value}, remark_{remark} {}

  const std::string& name() const { return name_; }
  const OpAttrVariantT& default_value() const { return default_value_; }
  const std::string& remark() const { return remark_; }
63 64 65

 private:
  std::string name_;
66 67
  OpAttrVariantT default_value_;
  std::string remark_;
68
};
69

70 71 72 73 74 75
struct OpInputOutputInfo : OpUpdateInfo {
  OpInputOutputInfo(const std::string& name, const std::string& remark)
      : name_{name}, remark_{remark} {}

  const std::string& name() const { return name_; }
  const std::string& remark() const { return remark_; }
76 77 78

 private:
  std::string name_;
79
  std::string remark_;
80 81
};

82 83 84
struct OpBugfixInfo : OpUpdateInfo {
  explicit OpBugfixInfo(const std::string& remark) : remark_{remark} {}
  const std::string& remark() const { return remark_; }
85 86

 private:
87
  std::string remark_;
88 89
};

90 91
enum class OpUpdateType {
  kInvalid = 0,
92
  /* Compatibility upgrade */
93 94 95 96 97
  kModifyAttr,
  kNewAttr,
  kNewInput,
  kNewOutput,
  kBugfixWithBehaviorChanged,
98 99 100 101 102 103
  /* Incompatible upgrade, only for existing registration. */
  kDeleteAttr = 100,
  kModifyInput,
  kModifyOutput,
  kDeleteInput,
  kDeleteOutput,
104
};
105

106 107
class OpUpdateBase {
 public:
108
  virtual const OpUpdateInfo& info() const = 0;
109 110
  virtual OpUpdateType type() const = 0;
  virtual ~OpUpdateBase() = default;
111 112
};

113 114 115 116
template <typename InfoType, OpUpdateType type__>
class OpUpdate : public OpUpdateBase {
 public:
  explicit OpUpdate(const InfoType& info) : info_{info}, type_{type__} {}
117
  const InfoType& info() const override { return info_; }
118 119 120 121 122
  OpUpdateType type() const override { return type_; }

 private:
  InfoType info_;
  OpUpdateType type_;
W
Wilber 已提交
123 124
};

125 126 127 128 129 130 131 132 133 134 135 136 137
template <OpUpdateType type__, typename InfoType>
OpUpdate<InfoType, type__>* new_update(InfoType&& info) {
  return new OpUpdate<InfoType, type__>(info);
}

template <typename T>
OpAttrVariantT op_attr_wrapper(const T& val) {
  return OpAttrVariantT{val};
}

template <int N>
OpAttrVariantT op_attr_wrapper(const char (&val)[N]) {
  PADDLE_ENFORCE_EQ(
138 139
      val[N - 1],
      0,
140 141 142 143 144
      platform::errors::InvalidArgument(
          "The argument of operator register %c is illegal.", val[N - 1]));
  return OpAttrVariantT{std::string{val}};
}

145 146
class OpVersionDesc {
 public:
147
  /* Compatibility upgrade */
148
  template <typename T>
149 150
  OpVersionDesc&& ModifyAttr(const std::string& name,
                             const std::string& remark,
151 152 153 154 155 156 157
                             const T& default_value) {
    infos_.emplace_back(new_update<OpUpdateType::kModifyAttr>(
        OpAttrInfo(name, remark, op_attr_wrapper(default_value))));
    return std::move(*this);
  }

  template <typename T>
158 159
  OpVersionDesc&& NewAttr(const std::string& name,
                          const std::string& remark,
160 161 162 163 164 165
                          const T& default_value) {
    infos_.emplace_back(new_update<OpUpdateType::kNewAttr>(
        OpAttrInfo(name, remark, op_attr_wrapper(default_value))));
    return std::move(*this);
  }

166 167 168
  OpVersionDesc&& NewInput(const std::string& name, const std::string& remark);
  OpVersionDesc&& NewOutput(const std::string& name, const std::string& remark);
  OpVersionDesc&& BugfixWithBehaviorChanged(const std::string& remark);
169 170 171 172 173 174 175 176 177 178 179 180 181 182

  /* Incompatible upgrade, only for existing registration. */
  OpVersionDesc&& DeleteAttr(const std::string& name,
                             const std::string& remark);
  OpVersionDesc&& ModifyInput(const std::string& name,
                              const std::string& remark);
  OpVersionDesc&& ModifyOutput(const std::string& name,
                               const std::string& remark);
  OpVersionDesc&& DeleteInput(const std::string& name,
                              const std::string& remark);
  OpVersionDesc&& DeleteOutput(const std::string& name,
                               const std::string& remark);

 public:
183 184
  const std::vector<std::unique_ptr<OpUpdateBase>>& infos() const {
    return infos_;
185
  }
186 187 188
  OpVersionDesc() = default;
  OpVersionDesc(OpVersionDesc&&) = default;
  OpVersionDesc& operator=(OpVersionDesc&&) = default;
189

190 191 192
 private:
  std::vector<std::unique_ptr<OpUpdateBase>> infos_;
};
193

194 195 196 197 198 199 200
class OpCheckpoint {
 public:
  OpCheckpoint(const std::string& note, OpVersionDesc&& op_version_desc)
      : note_{note},
        op_version_desc_{std::forward<OpVersionDesc>(op_version_desc)} {}
  const std::string& note() const { return note_; }
  const OpVersionDesc& version_desc() { return op_version_desc_; }
201

202 203 204
  OpCheckpoint() = default;
  OpCheckpoint(OpCheckpoint&&) = default;
  OpCheckpoint& operator=(OpCheckpoint&&) = default;
W
Wilber 已提交
205

206
 private:
207 208
  std::string note_;
  OpVersionDesc op_version_desc_;
209 210 211 212 213
};

class OpVersion {
 public:
  OpVersion& AddCheckpoint(const std::string& note,
214 215
                           OpVersionDesc&& op_version_desc) {
    checkpoints_.emplace_back(OpCheckpoint{note, std::move(op_version_desc)});
216 217
    return *this;
  }
218
  uint32_t version_id() const {
S
Shang Zhizhou 已提交
219 220
    return static_cast<uint32_t>(checkpoints_.size());
  }
221 222 223 224 225
  const std::vector<OpCheckpoint>& checkpoints() const { return checkpoints_; }

  OpVersion() = default;
  OpVersion(OpVersion&&) = default;
  OpVersion& operator=(OpVersion&&) = default;
226 227

 private:
228
  std::vector<OpCheckpoint> checkpoints_;
229 230 231 232 233 234 235 236
};

class OpVersionRegistrar {
 public:
  static OpVersionRegistrar& GetInstance() {
    static OpVersionRegistrar instance;
    return instance;
  }
237
  OpVersion& Register(const std::string& op_type);
238 239 240
  const std::unordered_map<std::string, OpVersion>& GetVersionMap() {
    return op_version_map_;
  }
241 242
  bool Has(const std::string& op_type) const {
    return op_version_map_.count(op_type);
S
Shang Zhizhou 已提交
243
  }
244
  uint32_t version_id(const std::string& op_type) const;
245 246 247

 private:
  std::unordered_map<std::string, OpVersion> op_version_map_;
248 249
  OpVersionRegistrar() = default;
  OpVersionRegistrar& operator=(const OpVersionRegistrar&) = delete;
250 251
};

252 253 254 255
inline const std::unordered_map<std::string, OpVersion>& get_op_version_map() {
  return OpVersionRegistrar::GetInstance().GetVersionMap();
}

256 257 258 259
inline void SaveOpVersions(
    const std::unordered_map<std::string, OpVersion>& src,
    pb::OpVersionMap* dst) {
  for (const auto& pair : src) {
260
    (*dst)[pair.first].SetVersionID(pair.second.version_id());
261 262 263
  }
}

S
Shang Zhizhou 已提交
264 265 266 267 268 269
class OpVersionComparator {
 public:
  virtual bool operator()() = 0;
  virtual ~OpVersionComparator() = default;
};

270 271 272 273 274 275 276 277 278 279 280
#define ADD_OP_VERSION_COMPARATOR(cmp_name, cmp_math)                        \
  class OpVersion##cmp_name##Comparator : public OpVersionComparator {       \
   public:                                                                   \
    explicit OpVersion##cmp_name##Comparator(const std::string op_name,      \
                                             uint32_t target_version)        \
        : op_name_(op_name), target_version_(target_version) {}              \
    virtual bool operator()() {                                              \
      uint32_t version_id = 0;                                               \
      if (OpVersionRegistrar::GetInstance().Has(op_name_)) {                 \
        version_id = OpVersionRegistrar::GetInstance().version_id(op_name_); \
      }                                                                      \
281 282 283 284 285 286 287
      bool check_ok = version_id cmp_math target_version_;                   \
      if (!check_ok) {                                                       \
        LOG(WARNING) << "Check op version in pass failed. op name:"          \
                     << op_name_.c_str() << " op_version:" << version_id     \
                     << "  target_version:" << target_version_;              \
      }                                                                      \
      return check_ok;                                                       \
288 289 290 291 292 293
    }                                                                        \
    virtual ~OpVersion##cmp_name##Comparator() {}                            \
                                                                             \
   private:                                                                  \
    std::string op_name_;                                                    \
    uint32_t target_version_;                                                \
S
Shang Zhizhou 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  };

ADD_OP_VERSION_COMPARATOR(LE, <=);
ADD_OP_VERSION_COMPARATOR(EQ, ==);
ADD_OP_VERSION_COMPARATOR(GE, >=);
ADD_OP_VERSION_COMPARATOR(NE, !=);

class OpVersionComparatorCombination {
 public:
  OpVersionComparatorCombination() {}

  OpVersionComparatorCombination& LE(const std::string& op_name,
                                     int target_version) {
    op_version_comparators_.push_back(std::shared_ptr<OpVersionComparator>(
        new OpVersionLEComparator(op_name, target_version)));
    return *this;
  }
  OpVersionComparatorCombination& EQ(const std::string& op_name,
                                     int target_version) {
    op_version_comparators_.push_back(std::shared_ptr<OpVersionComparator>(
        new OpVersionEQComparator(op_name, target_version)));
    return *this;
  }
  OpVersionComparatorCombination& GE(const std::string& op_name,
                                     int target_version) {
    op_version_comparators_.push_back(std::shared_ptr<OpVersionComparator>(
        new OpVersionGEComparator(op_name, target_version)));
    return *this;
  }
  OpVersionComparatorCombination& NE(const std::string& op_name,
                                     int target_version) {
    op_version_comparators_.push_back(std::shared_ptr<OpVersionComparator>(
        new OpVersionNEComparator(op_name, target_version)));
    return *this;
  }

  bool IsMatched() const {
    for (const auto& cmp : op_version_comparators_) {
      if (!(*cmp)()) {
        return false;
      }
    }
    return true;
  }

 private:
  std::vector<std::shared_ptr<OpVersionComparator>> op_version_comparators_;
};

class PassVersionCheckers {
 public:
  PassVersionCheckers& AddCombination(
      const OpVersionComparatorCombination& combinations) {
    pass_version_checkers_.push_back(combinations);
    return *this;
  }
  bool IsPassCompatible() const {
    if (pass_version_checkers_.empty()) {
      return true;
    }
    for (const auto& checker : pass_version_checkers_) {
      if (checker.IsMatched()) {
        return true;
      }
    }
    return false;
  }

 private:
  std::vector<OpVersionComparatorCombination> pass_version_checkers_;
};

class PassVersionCheckerRegistrar {
 public:
  static PassVersionCheckerRegistrar& GetInstance() {
    static PassVersionCheckerRegistrar instance;
    return instance;
  }
  PassVersionCheckers& Register(const std::string& pass_name) {
373 374 375 376 377
    PADDLE_ENFORCE_EQ(pass_version_checkers_map_.find(pass_name),
                      pass_version_checkers_map_.end(),
                      platform::errors::AlreadyExists(
                          "PassVersionCheckers(%s) has alredy been registered.",
                          pass_name.c_str()));
S
Shang Zhizhou 已提交
378 379 380 381 382
    return pass_version_checkers_map_[pass_name];
  }
  bool IsPassCompatible(const std::string& fuse_pass_name) const {
    auto iter = pass_version_checkers_map_.find(fuse_pass_name);
    if (iter == pass_version_checkers_map_.end()) {
383
      return false;
S
Shang Zhizhou 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396
    }
    return iter->second.IsPassCompatible();
  }

 private:
  std::unordered_map<std::string, PassVersionCheckers>
      pass_version_checkers_map_;

  PassVersionCheckerRegistrar() = default;
  PassVersionCheckerRegistrar& operator=(const PassVersionCheckerRegistrar&) =
      delete;
};

397 398 399 400 401
}  // namespace compatible
}  // namespace framework
}  // namespace paddle

#define REGISTER_OP_VERSION(op_type)                                       \
402
  UNUSED static paddle::framework::compatible::OpVersion&                  \
403 404 405
      RegisterOpVersion__##op_type =                                       \
          paddle::framework::compatible::OpVersionRegistrar::GetInstance() \
              .Register(#op_type)
S
Shang Zhizhou 已提交
406 407 408 409 410 411

#define REGISTER_PASS_CAPABILITY(pass_name)                        \
  static auto RegisterOpPassVersionChecker__##pass_name =          \
      paddle::framework::compatible::PassVersionCheckerRegistrar:: \
          GetInstance()                                            \
              .Register(#pass_name)