attribute.h 15.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yi Wang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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

15 16
#pragma once

17
#include <stdint.h>
18

19
#include <functional>
20
#include <iosfwd>
21 22
#include <string>
#include <unordered_map>
Y
Yu Yang 已提交
23
#include <unordered_set>
24
#include <vector>
Y
Yi Wang 已提交
25

Y
Yi Wang 已提交
26 27 28
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/type_defs.h"
#include "paddle/fluid/platform/enforce.h"
29
#include "paddle/fluid/platform/errors.h"
30
#include "paddle/utils/any.h"
R
Ruibiao Chen 已提交
31
#include "paddle/utils/variant.h"
32 33 34

namespace paddle {
namespace framework {
T
tangwei12 已提交
35

36 37 38 39
paddle::any GetAttrValue(const Attribute& attr);

Attribute GetAttrValue(const proto::OpDesc::Attr& attr_desc);

T
tangwei12 已提交
40 41 42 43 44 45 46 47
template <typename T>
struct ExtractAttribute {
  explicit ExtractAttribute(const std::string& attr_name)
      : attr_name_(attr_name) {}

  T* operator()(Attribute& attr) const {
    T* attr_value = nullptr;
    try {
R
Ruibiao Chen 已提交
48 49
      attr_value = &paddle::get<T>(attr);
    } catch (paddle::bad_variant_access const& bad_get) {
50
      PADDLE_THROW(platform::errors::InvalidArgument(
51 52
          "Cannot get attribute (%s) by type %s, its type is %s.",
          attr_name_,
53 54
          paddle::platform::demangle(typeid(T).name()),
          paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    }
    return attr_value;
  }

  const std::string& attr_name_;
};

// special handle bool
// FIXME(yuyang18): Currently we cast bool into int in python binding. It is
// hard to change the logic there. In another way, we should correct handle
// if the user set `some_flag=1`.
//
// FIX ME anytime if there is a better solution.
template <>
struct ExtractAttribute<bool> {
  explicit ExtractAttribute(const std::string& attr_name)
      : attr_name_(attr_name) {}

  bool* operator()(Attribute& attr) const {
    if (attr.type() == typeid(int)) {  // NOLINT
75
      int val = BOOST_GET_CONST(int, attr);
T
tangwei12 已提交
76 77
      attr = static_cast<bool>(val);
    } else if (attr.type() == typeid(float)) {  // NOLINT
78
      float val = BOOST_GET_CONST(float, attr);
T
tangwei12 已提交
79 80 81 82
      attr = static_cast<bool>(val);
    }
    bool* attr_value = nullptr;
    try {
R
Ruibiao Chen 已提交
83 84
      attr_value = &paddle::get<bool>(attr);
    } catch (paddle::bad_variant_access const& bad_get) {
85
      PADDLE_THROW(platform::errors::InvalidArgument(
86 87
          "Cannot get attribute (%s) by type bool, its type is %s.",
          attr_name_,
88
          paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102
    }
    return attr_value;
  }

  const std::string& attr_name_;
};

template <>
struct ExtractAttribute<int64_t> {
  explicit ExtractAttribute(const std::string& attr_name)
      : attr_name_(attr_name) {}

  int64_t* operator()(Attribute& attr) const {
    if (attr.type() == typeid(int)) {  // NOLINT
103
      int val = BOOST_GET_CONST(int, attr);
T
tangwei12 已提交
104 105
      attr = static_cast<int64_t>(val);
    } else if (attr.type() == typeid(float)) {  // NOLINT
106
      int val = BOOST_GET_CONST(float, attr);
T
tangwei12 已提交
107 108 109 110
      attr = static_cast<int64_t>(val);
    }
    int64_t* attr_value = nullptr;
    try {
R
Ruibiao Chen 已提交
111 112
      attr_value = &paddle::get<int64_t>(attr);
    } catch (paddle::bad_variant_access const& bad_get) {
113 114
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type int64_t, its type is %s.",
115 116
          attr_name_,
          paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130
    }
    return attr_value;
  }

  const std::string& attr_name_;
};

template <>
struct ExtractAttribute<std::vector<int64_t>> {
  explicit ExtractAttribute(const std::string& attr_name)
      : attr_name_(attr_name) {}

  std::vector<int64_t>* operator()(Attribute& attr) const {
    if (attr.type() == typeid(std::vector<int>)) {  // NOLINT
131
      std::vector<int> val = BOOST_GET_CONST(std::vector<int>, attr);
T
tangwei12 已提交
132 133 134
      std::vector<int64_t> vec(val.begin(), val.end());
      attr = vec;
    } else if (attr.type() == typeid(std::vector<float>)) {  // NOLINT
135
      std::vector<float> val = BOOST_GET_CONST(std::vector<float>, attr);
T
tangwei12 已提交
136 137 138 139 140
      std::vector<int64_t> vec(val.begin(), val.end());
      attr = vec;
    }
    std::vector<int64_t>* attr_value = nullptr;
    try {
R
Ruibiao Chen 已提交
141 142
      attr_value = &paddle::get<std::vector<int64_t>>(attr);
    } catch (paddle::bad_variant_access const& bad_get) {
143 144 145
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type std::vector<int64_t>, its type is "
          "%s.",
146 147
          attr_name_,
          paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
148 149 150 151 152 153
    }
    return attr_value;
  }

  const std::string& attr_name_;
};
154 155 156 157 158 159 160 161

template <>
struct ExtractAttribute<float> {
  explicit ExtractAttribute(const std::string& attr_name)
      : attr_name_(attr_name) {}

  float* operator()(Attribute& attr) const {
    if (attr.type() == typeid(int)) {  // NOLINT
162
      int val = BOOST_GET_CONST(int, attr);
163 164
      attr = static_cast<float>(val);
    } else if (attr.type() == typeid(int64_t)) {  // NOLINT
165
      int64_t val = BOOST_GET_CONST(int64_t, attr);
166 167 168 169
      attr = static_cast<float>(val);
    }
    float* attr_value = nullptr;
    try {
R
Ruibiao Chen 已提交
170 171
      attr_value = &paddle::get<float>(attr);
    } catch (paddle::bad_variant_access const& bad_get) {
172 173
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type float, its type is %s.",
174 175
          attr_name_,
          paddle::platform::demangle(attr.type().name())));
176 177 178 179 180 181
    }
    return attr_value;
  }

  const std::string& attr_name_;
};
T
tangwei12 已提交
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
template <>
struct ExtractAttribute<std::vector<double>> {
  explicit ExtractAttribute(const std::string& attr_name)
      : attr_name_(attr_name) {}

  std::vector<double>* operator()(Attribute& attr) const {
    if (attr.type() == typeid(std::vector<int>)) {  // NOLINT
      std::vector<int> val = BOOST_GET_CONST(std::vector<int>, attr);
      std::vector<double> vec(val.begin(), val.end());
      attr = vec;
    } else if (attr.type() == typeid(std::vector<float>)) {  // NOLINT
      std::vector<float> val = BOOST_GET_CONST(std::vector<float>, attr);
      std::vector<double> vec(val.begin(), val.end());
      attr = vec;
    }
    std::vector<double>* attr_value = nullptr;
    try {
R
Ruibiao Chen 已提交
200 201
      attr_value = &paddle::get<std::vector<double>>(attr);
    } catch (paddle::bad_variant_access const& bad_get) {
202 203 204
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type std::vector<double>, its type is "
          "%s.",
205 206
          attr_name_,
          paddle::platform::demangle(attr.type().name())));
207 208 209 210 211 212
    }
    return attr_value;
  }

  const std::string& attr_name_;
};
C
Chen Weihang 已提交
213

Y
Yi Wang 已提交
214
template <typename T>
215
inline proto::AttrType AttrTypeID() {
Y
Yu Yang 已提交
216
  Attribute tmp = T();
R
Ruibiao Chen 已提交
217
  return static_cast<proto::AttrType>(tmp.index() - 1);
Y
Yu Yang 已提交
218
}
Y
Yi Wang 已提交
219

C
Chen Weihang 已提交
220
inline proto::AttrType AttrTypeID(const Attribute& attr) {
R
Ruibiao Chen 已提交
221
  return static_cast<proto::AttrType>(attr.index() - 1);
C
Chen Weihang 已提交
222 223
}

Q
Qiao Longfei 已提交
224 225
class AttrReader {
 public:
226 227 228 229 230
  explicit AttrReader(const AttributeMap& attrs)
      : attrs_(attrs), default_attrs_(nullptr) {}

  AttrReader(const AttributeMap& attrs, const AttributeMap& default_attrs)
      : attrs_(attrs), default_attrs_(&default_attrs) {}
Q
Qiao Longfei 已提交
231 232 233

  template <typename T>
  inline const T& Get(const std::string& name) const {
234 235 236 237 238 239 240 241
    auto it = attrs_.find(name);
    bool found = it != attrs_.end();
    if (!found) {
      if (default_attrs_ != nullptr) {
        it = default_attrs_->find(name);
        found = it != default_attrs_->end();
      }
    }
242 243
    PADDLE_ENFORCE_EQ(found,
                      true,
244 245
                      platform::errors::NotFound(
                          "Attribute (%s) should be in AttributeMap.", name));
T
tangwei12 已提交
246

247
    Attribute& attr = const_cast<Attribute&>(it->second);
T
tangwei12 已提交
248 249 250
    ExtractAttribute<T> extract_attr(name);
    T* attr_value = extract_attr(attr);
    return *attr_value;
Q
Qiao Longfei 已提交
251 252
  }

253
  const Attribute* GetAttr(const std::string& name) const {
254 255 256 257 258 259 260 261
    auto it = attrs_.find(name);
    bool found = it != attrs_.end();
    if (!found) {
      if (default_attrs_ != nullptr) {
        it = default_attrs_->find(name);
        found = it != default_attrs_->end();
      }
    }
262 263 264 265
    if (found) {
      return &it->second;
    }
    return nullptr;
266 267
  }

Q
Qiao Longfei 已提交
268 269
 private:
  const AttributeMap& attrs_;
270
  const AttributeMap* default_attrs_;
Q
Qiao Longfei 已提交
271 272
};

273 274
// check whether a value(attribute) fit a certain limit
template <typename T>
F
fengjiayi 已提交
275
class GreaterThanChecker {
276
 public:
F
fengjiayi 已提交
277
  explicit GreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
T
tangwei12 已提交
278
  void operator()(const T& value) const {
279
    PADDLE_ENFORCE_GT(
280 281
        value,
        lower_bound_,
282 283
        platform::errors::OutOfRange("Check for attribute value greater than "
                                     "a certain value failed."));
284 285 286 287 288 289
  }

 private:
  T lower_bound_;
};

F
WIP  
fengjiayi 已提交
290
template <typename T>
F
fengjiayi 已提交
291
class EqualGreaterThanChecker {
F
WIP  
fengjiayi 已提交
292
 public:
F
fengjiayi 已提交
293
  explicit EqualGreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
T
tangwei12 已提交
294
  void operator()(const T& value) const {
295
    PADDLE_ENFORCE_GE(
296 297
        value,
        lower_bound_,
298 299
        platform::errors::OutOfRange("Check for attribute valur equal or "
                                     "greater than a certain value failed."));
F
WIP  
fengjiayi 已提交
300 301 302 303 304 305
  }

 private:
  T lower_bound_;
};

306 307 308 309 310 311
// we can provide users more common Checker, like 'LessThanChecker',
// 'BetweenChecker'...

template <typename T>
class DefaultValueSetter {
 public:
Y
Yi Wang 已提交
312 313
  explicit DefaultValueSetter(T default_value)
      : default_value_(default_value) {}
H
hong 已提交
314
  const T& operator()() const { return default_value_; }
315 316 317 318 319

 private:
  T default_value_;
};

Y
Yu Yang 已提交
320 321 322 323
template <typename T>
class EnumInContainer {
 public:
  explicit EnumInContainer(const std::unordered_set<T>& c) : container_(c) {}
T
tangwei12 已提交
324
  void operator()(const T& val) const {
325
    PADDLE_ENFORCE_NE(
326 327 328 329
        container_.find(val),
        container_.end(),
        platform::errors::NotFound("Value %s is not in enum container %s.",
                                   val,
330
                                   ContainerDebugString()));
Y
Yu Yang 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
  }

 private:
  std::string ContainerDebugString() const {
    std::ostringstream sout;
    sout << "[";
    size_t cnt = 0;
    for (auto& v : container_) {
      sout << v;
      ++cnt;
      if (cnt != container_.size()) {
        sout << " ,";
      }
    }
    sout << "]";
    return sout.str();
  }

  std::unordered_set<T> container_;
};

352 353 354 355
// check whether a certain attribute fit its limits
// an attribute can have more than one limits
template <typename T>
class TypedAttrChecker {
H
hong 已提交
356
  typedef std::function<const T&()> DefaultValueChecker;
T
tangwei12 已提交
357
  typedef std::function<void(const T&)> ValueChecker;
358 359

 public:
360 361 362 363 364 365 366 367 368 369 370 371 372
  explicit TypedAttrChecker(const std::string& attr_name,
                            proto::OpProto_Attr* attr)
      : attr_name_(attr_name), attr_(attr) {}

  TypedAttrChecker& AsExtra() {
    attr_->set_extra(true);
    return *this;
  }

  TypedAttrChecker& AsQuant() {
    attr_->set_quant(true);
    return *this;
  }
373

Y
Yu Yang 已提交
374 375 376 377 378
  TypedAttrChecker& InEnum(const std::unordered_set<T>& range) {
    value_checkers_.push_back(EnumInContainer<T>(range));
    return *this;
  }

F
fengjiayi 已提交
379 380
  TypedAttrChecker& GreaterThan(const T& lower_bound) {
    value_checkers_.push_back(GreaterThanChecker<T>(lower_bound));
381 382 383
    return *this;
  }

F
fengjiayi 已提交
384 385
  TypedAttrChecker& EqualGreaterThan(const T& lower_bound) {
    value_checkers_.push_back(EqualGreaterThanChecker<T>(lower_bound));
F
WIP  
fengjiayi 已提交
386 387 388
    return *this;
  }

389 390 391
  // we can add more common limits, like LessThan(), Between()...

  TypedAttrChecker& SetDefault(const T& default_value) {
392
    PADDLE_ENFORCE_EQ(
393 394
        default_value_setter_.empty(),
        true,
395 396 397
        platform::errors::AlreadyExists("Attribute (%s) has a default value "
                                        "and cannot be set repeatedly.",
                                        attr_name_));
398 399 400 401 402 403 404 405 406 407
    default_value_setter_.push_back(DefaultValueSetter<T>(default_value));
    return *this;
  }

  // allow users provide their own checker
  TypedAttrChecker& AddCustomChecker(const ValueChecker& checker) {
    value_checkers_.push_back(checker);
    return *this;
  }

408 409
  void operator()(AttributeMap* attr_map,
                  bool get_default_value_only = false,
410
                  bool only_check_exist_value = false) const {
411 412 413 414 415 416 417
    if (get_default_value_only) {
      if (!default_value_setter_.empty()) {
        attr_map->emplace(attr_name_, default_value_setter_[0]());
      }
      return;
    }

418 419 420 421 422 423 424 425 426 427 428 429 430 431
    if (only_check_exist_value) {
      auto it = attr_map->find(attr_name_);
      if (it != attr_map->end()) {
        ExtractAttribute<T> extract_attr(attr_name_);
        T* attr_value = extract_attr(it->second);
        for (const auto& checker : value_checkers_) {
          checker(*attr_value);
        }
      }
    } else {
      auto it = attr_map->find(attr_name_);
      if (it == attr_map->end()) {
        // user do not set this attr
        PADDLE_ENFORCE_EQ(
432 433
            default_value_setter_.empty(),
            false,
434 435 436 437 438 439 440 441 442 443 444
            platform::errors::InvalidArgument(
                "Attribute (%s) is not set correctly.", attr_name_));
        // default_value_setter_ has no more than one element
        auto tmp = attr_map->emplace(attr_name_, default_value_setter_[0]());
        it = tmp.first;
      }
      ExtractAttribute<T> extract_attr(attr_name_);
      T* attr_value = extract_attr(it->second);
      for (const auto& checker : value_checkers_) {
        checker(*attr_value);
      }
445 446 447 448 449
    }
  }

 private:
  std::string attr_name_;
450
  proto::OpProto_Attr* attr_;
451
  std::vector<ValueChecker> value_checkers_;
T
tangwei12 已提交
452
  std::vector<DefaultValueChecker> default_value_setter_;
453 454 455 456
};

// check whether op's all attributes fit their own limits
class OpAttrChecker {
457
  typedef std::function<void(AttributeMap*, bool, bool)> AttrChecker;
458 459 460

 public:
  template <typename T>
461 462 463
  TypedAttrChecker<T>& AddAttrChecker(const std::string& attr_name,
                                      proto::OpProto_Attr* attr) {
    attr_checkers_.push_back(TypedAttrChecker<T>(attr_name, attr));
464 465 466 467
    AttrChecker& checker = attr_checkers_.back();
    return *(checker.target<TypedAttrChecker<T>>());
  }

468 469
  void Check(AttributeMap* attr_map,
             bool explicit_only = false,
470
             bool only_check_exist_value = false) const {
471 472 473
    auto checker_num = attr_checkers_.size();
    if (explicit_only) checker_num = explicit_checker_num_;
    for (size_t i = 0; i < checker_num; ++i) {
474
      attr_checkers_[i](attr_map, false, only_check_exist_value);
475 476 477
    }
  }

478
  AttributeMap GetDefaultAttrsMap() const {
479 480
    AttributeMap default_values_map;
    for (const auto& checker : attr_checkers_) {
481
      checker(&default_values_map, true, false);
482
    }
483
    return default_values_map;
484 485
  }

486 487 488 489
  void RecordExplicitCheckerNum() {
    explicit_checker_num_ = attr_checkers_.size();
  }

490 491 492 493 494 495 496 497
  void InitDefaultAttributeMap() {
    for (const auto& checker : attr_checkers_) {
      checker(&default_attrs_, true, false);
    }
  }

  const AttributeMap& GetDefaultAttrMap() const { return default_attrs_; }

498 499
 private:
  std::vector<AttrChecker> attr_checkers_;
500

501 502
  AttributeMap default_attrs_;

503 504 505 506 507
  // in order to improve the efficiency of dynamic graph mode,
  // we divede the attribute into explicit type and implicit type.
  // for explicit attribute, we mean the attribute added in the customized
  // op makers, usually it's defined in the overloaded Make method.
  // for implicit attribute, we mean the attribute added outside of the Make
508 509
  // method like "op_role", "op_role_var", and they are useless in dynamic
  // graph
510 511
  // mode
  size_t explicit_checker_num_;
512 513 514 515
};

}  // namespace framework
}  // namespace paddle