attribute.h 13.0 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 17 18 19
#pragma once

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

Y
Yi Wang 已提交
23 24 25
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/type_defs.h"
#include "paddle/fluid/platform/enforce.h"
26 27 28

namespace paddle {
namespace framework {
T
tangwei12 已提交
29 30 31 32 33 34 35 36 37 38 39

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 {
      attr_value = &boost::get<T>(attr);
    } catch (boost::bad_get& bad_get) {
40 41 42 43
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type %s, its type is %s.", attr_name_,
          paddle::platform::demangle(typeid(T).name()),
          paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    }
    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
64
      int val = BOOST_GET_CONST(int, attr);
T
tangwei12 已提交
65 66
      attr = static_cast<bool>(val);
    } else if (attr.type() == typeid(float)) {  // NOLINT
67
      float val = BOOST_GET_CONST(float, attr);
T
tangwei12 已提交
68 69 70 71 72 73
      attr = static_cast<bool>(val);
    }
    bool* attr_value = nullptr;
    try {
      attr_value = &boost::get<bool>(attr);
    } catch (boost::bad_get& bad_get) {
74 75 76
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type bool, its type is %s.", attr_name_,
          paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90
    }
    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
91
      int val = BOOST_GET_CONST(int, attr);
T
tangwei12 已提交
92 93
      attr = static_cast<int64_t>(val);
    } else if (attr.type() == typeid(float)) {  // NOLINT
94
      int val = BOOST_GET_CONST(float, attr);
T
tangwei12 已提交
95 96 97 98 99 100
      attr = static_cast<int64_t>(val);
    }
    int64_t* attr_value = nullptr;
    try {
      attr_value = &boost::get<int64_t>(attr);
    } catch (boost::bad_get& bad_get) {
101 102 103
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type int64_t, its type is %s.",
          attr_name_, paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117
    }
    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
118
      std::vector<int> val = BOOST_GET_CONST(std::vector<int>, attr);
T
tangwei12 已提交
119 120 121
      std::vector<int64_t> vec(val.begin(), val.end());
      attr = vec;
    } else if (attr.type() == typeid(std::vector<float>)) {  // NOLINT
122
      std::vector<float> val = BOOST_GET_CONST(std::vector<float>, attr);
T
tangwei12 已提交
123 124 125 126 127 128 129
      std::vector<int64_t> vec(val.begin(), val.end());
      attr = vec;
    }
    std::vector<int64_t>* attr_value = nullptr;
    try {
      attr_value = &boost::get<std::vector<int64_t>>(attr);
    } catch (boost::bad_get& bad_get) {
130 131 132 133
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type std::vector<int64_t>, its type is "
          "%s.",
          attr_name_, paddle::platform::demangle(attr.type().name())));
T
tangwei12 已提交
134 135 136 137 138 139
    }
    return attr_value;
  }

  const std::string& attr_name_;
};
140 141 142 143 144 145 146 147

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
148
      int val = BOOST_GET_CONST(int, attr);
149 150
      attr = static_cast<float>(val);
    } else if (attr.type() == typeid(int64_t)) {  // NOLINT
151
      int64_t val = BOOST_GET_CONST(int64_t, attr);
152 153 154 155 156 157
      attr = static_cast<float>(val);
    }
    float* attr_value = nullptr;
    try {
      attr_value = &boost::get<float>(attr);
    } catch (boost::bad_get& bad_get) {
158 159 160
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type float, its type is %s.",
          attr_name_, paddle::platform::demangle(attr.type().name())));
161 162 163 164 165 166
    }
    return attr_value;
  }

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

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
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 {
      attr_value = &boost::get<std::vector<double>>(attr);
    } catch (boost::bad_get& bad_get) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Cannot get attribute (%s) by type std::vector<double>, its type is "
          "%s.",
          attr_name_, paddle::platform::demangle(attr.type().name())));
    }
    return attr_value;
  }

  const std::string& attr_name_;
};
Y
Yi Wang 已提交
197
template <typename T>
198
inline proto::AttrType AttrTypeID() {
Y
Yu Yang 已提交
199
  Attribute tmp = T();
200
  return static_cast<proto::AttrType>(tmp.which() - 1);
Y
Yu Yang 已提交
201
}
Y
Yi Wang 已提交
202

203
Attribute GetAttrValue(const proto::OpDesc::Attr& attr_desc);
Y
Yi Wang 已提交
204

Q
Qiao Longfei 已提交
205 206 207 208 209 210
class AttrReader {
 public:
  explicit AttrReader(const AttributeMap& attrs) : attrs_(attrs) {}

  template <typename T>
  inline const T& Get(const std::string& name) const {
211 212 213
    PADDLE_ENFORCE_NE(attrs_.count(name), 0,
                      platform::errors::NotFound(
                          "Attribute (%s) should be in AttributeMap.", name));
T
tangwei12 已提交
214 215 216 217 218

    Attribute& attr = const_cast<Attribute&>(attrs_.at(name));
    ExtractAttribute<T> extract_attr(name);
    T* attr_value = extract_attr(attr);
    return *attr_value;
Q
Qiao Longfei 已提交
219 220 221 222 223 224
  }

 private:
  const AttributeMap& attrs_;
};

225 226
// check whether a value(attribute) fit a certain limit
template <typename T>
F
fengjiayi 已提交
227
class GreaterThanChecker {
228
 public:
F
fengjiayi 已提交
229
  explicit GreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
T
tangwei12 已提交
230
  void operator()(const T& value) const {
231 232 233 234
    PADDLE_ENFORCE_GT(
        value, lower_bound_,
        platform::errors::OutOfRange(
            "Check for attribute value greater than a certain value failed."));
235 236 237 238 239 240
  }

 private:
  T lower_bound_;
};

F
WIP  
fengjiayi 已提交
241
template <typename T>
F
fengjiayi 已提交
242
class EqualGreaterThanChecker {
F
WIP  
fengjiayi 已提交
243
 public:
F
fengjiayi 已提交
244
  explicit EqualGreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
T
tangwei12 已提交
245
  void operator()(const T& value) const {
246 247 248 249
    PADDLE_ENFORCE_GE(
        value, lower_bound_,
        platform::errors::OutOfRange("Check for attribute valur equal or "
                                     "greater than a certain value failed."));
F
WIP  
fengjiayi 已提交
250 251 252 253 254 255
  }

 private:
  T lower_bound_;
};

256 257 258 259 260 261
// we can provide users more common Checker, like 'LessThanChecker',
// 'BetweenChecker'...

template <typename T>
class DefaultValueSetter {
 public:
Y
Yi Wang 已提交
262 263
  explicit DefaultValueSetter(T default_value)
      : default_value_(default_value) {}
H
hong 已提交
264
  const T& operator()() const { return default_value_; }
265 266 267 268 269

 private:
  T default_value_;
};

Y
Yu Yang 已提交
270 271 272 273
template <typename T>
class EnumInContainer {
 public:
  explicit EnumInContainer(const std::unordered_set<T>& c) : container_(c) {}
T
tangwei12 已提交
274
  void operator()(const T& val) const {
275 276 277 278
    PADDLE_ENFORCE_NE(
        container_.find(val), container_.end(),
        platform::errors::NotFound("Value %s is not in enum container %s.", val,
                                   ContainerDebugString()));
Y
Yu Yang 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  }

 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_;
};

300 301 302 303
// check whether a certain attribute fit its limits
// an attribute can have more than one limits
template <typename T>
class TypedAttrChecker {
H
hong 已提交
304
  typedef std::function<const T&()> DefaultValueChecker;
T
tangwei12 已提交
305
  typedef std::function<void(const T&)> ValueChecker;
306 307

 public:
Y
Yi Wang 已提交
308 309
  explicit TypedAttrChecker(const std::string& attr_name)
      : attr_name_(attr_name) {}
310

Y
Yu Yang 已提交
311 312 313 314 315
  TypedAttrChecker& InEnum(const std::unordered_set<T>& range) {
    value_checkers_.push_back(EnumInContainer<T>(range));
    return *this;
  }

F
fengjiayi 已提交
316 317
  TypedAttrChecker& GreaterThan(const T& lower_bound) {
    value_checkers_.push_back(GreaterThanChecker<T>(lower_bound));
318 319 320
    return *this;
  }

F
fengjiayi 已提交
321 322
  TypedAttrChecker& EqualGreaterThan(const T& lower_bound) {
    value_checkers_.push_back(EqualGreaterThanChecker<T>(lower_bound));
F
WIP  
fengjiayi 已提交
323 324 325
    return *this;
  }

326 327 328
  // we can add more common limits, like LessThan(), Between()...

  TypedAttrChecker& SetDefault(const T& default_value) {
329 330 331 332 333
    PADDLE_ENFORCE_EQ(
        default_value_setter_.empty(), true,
        platform::errors::AlreadyExists(
            "Attribute (%s) has a default value and cannot be set repeatedly.",
            attr_name_));
334 335 336 337 338 339 340 341 342 343
    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;
  }

344 345 346 347 348 349 350 351 352
  void operator()(AttributeMap* attr_map,
                  bool get_default_value_only = false) const {
    if (get_default_value_only) {
      if (!default_value_setter_.empty()) {
        attr_map->emplace(attr_name_, default_value_setter_[0]());
      }
      return;
    }

H
hong 已提交
353 354
    auto it = attr_map->find(attr_name_);
    if (it == attr_map->end()) {
355
      // user do not set this attr
356 357 358 359
      PADDLE_ENFORCE_EQ(
          default_value_setter_.empty(), false,
          platform::errors::InvalidArgument(
              "Attribute (%s) is not set correctly.", attr_name_));
360
      // default_value_setter_ has no more than one element
H
hong 已提交
361
      attr_map->emplace(attr_name_, default_value_setter_[0]());
362
    }
H
hong 已提交
363
    it = attr_map->find(attr_name_);
364
    ExtractAttribute<T> extract_attr(attr_name_);
H
hong 已提交
365
    T* attr_value = extract_attr(it->second);
366
    for (const auto& checker : value_checkers_) {
367
      checker(*attr_value);
368 369 370 371 372 373
    }
  }

 private:
  std::string attr_name_;
  std::vector<ValueChecker> value_checkers_;
T
tangwei12 已提交
374
  std::vector<DefaultValueChecker> default_value_setter_;
375 376 377 378
};

// check whether op's all attributes fit their own limits
class OpAttrChecker {
379
  typedef std::function<void(AttributeMap*, bool)> AttrChecker;
380 381 382 383 384 385 386 387 388

 public:
  template <typename T>
  TypedAttrChecker<T>& AddAttrChecker(const std::string& attr_name) {
    attr_checkers_.push_back(TypedAttrChecker<T>(attr_name));
    AttrChecker& checker = attr_checkers_.back();
    return *(checker.target<TypedAttrChecker<T>>());
  }

389 390 391 392 393
  void Check(AttributeMap* attr_map, bool explicit_only = false) const {
    auto checker_num = attr_checkers_.size();
    if (explicit_only) checker_num = explicit_checker_num_;
    for (size_t i = 0; i < checker_num; ++i) {
      attr_checkers_[i](attr_map, false);
394 395 396 397 398 399 400
    }
  }

  AttributeMap GetAttrsDefaultValuesMap() const {
    AttributeMap default_values_map;
    for (const auto& checker : attr_checkers_) {
      checker(&default_values_map, true);
401
    }
402
    return default_values_map;
403 404
  }

405 406 407 408
  void RecordExplicitCheckerNum() {
    explicit_checker_num_ = attr_checkers_.size();
  }

409 410
 private:
  std::vector<AttrChecker> attr_checkers_;
411 412 413 414 415 416 417 418 419

  // 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
  // method like "op_role", "op_role_var", and they are useless in dynamic graph
  // mode
  size_t explicit_checker_num_;
420 421 422 423
};

}  // namespace framework
}  // namespace paddle