attribute.h 9.2 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

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) {
      PADDLE_THROW("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()));
    }
    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
      int val = boost::get<int>(attr);
      attr = static_cast<bool>(val);
    } else if (attr.type() == typeid(float)) {  // NOLINT
      float val = boost::get<float>(attr);
      attr = static_cast<bool>(val);
    }
    bool* attr_value = nullptr;
    try {
      attr_value = &boost::get<bool>(attr);
    } catch (boost::bad_get& bad_get) {
      PADDLE_THROW("Cannot get attribute %s by type bool, its type is %s",
                   attr_name_, paddle::platform::demangle(attr.type().name()));
    }
    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
      int val = boost::get<int>(attr);
      attr = static_cast<int64_t>(val);
    } else if (attr.type() == typeid(float)) {  // NOLINT
      int val = boost::get<float>(attr);
      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) {
      PADDLE_THROW("Cannot get attribute %s by type int64_t, its type is %s",
                   attr_name_, paddle::platform::demangle(attr.type().name()));
    }
    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
      std::vector<int> val = boost::get<std::vector<int>>(attr);
      std::vector<int64_t> vec(val.begin(), val.end());
      attr = vec;
    } else if (attr.type() == typeid(std::vector<float>)) {  // NOLINT
      std::vector<float> val = boost::get<std::vector<float>>(attr);
      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) {
      PADDLE_THROW("Cannot get attribute %s by type int64_t, its type is %s",
                   attr_name_, paddle::platform::demangle(attr.type().name()));
    }
    return attr_value;
  }

  const std::string& attr_name_;
};

Y
Yi Wang 已提交
136
template <typename T>
137
inline proto::AttrType AttrTypeID() {
Y
Yu Yang 已提交
138
  Attribute tmp = T();
139
  return static_cast<proto::AttrType>(tmp.which() - 1);
Y
Yu Yang 已提交
140
}
Y
Yi Wang 已提交
141

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

Q
Qiao Longfei 已提交
144 145 146 147 148 149 150 151
class AttrReader {
 public:
  explicit AttrReader(const AttributeMap& attrs) : attrs_(attrs) {}

  template <typename T>
  inline const T& Get(const std::string& name) const {
    PADDLE_ENFORCE(attrs_.count(name) != 0, "%s should be in AttributeMap",
                   name);
T
tangwei12 已提交
152 153 154 155 156

    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 已提交
157 158 159 160 161 162
  }

 private:
  const AttributeMap& attrs_;
};

163 164
// check whether a value(attribute) fit a certain limit
template <typename T>
F
fengjiayi 已提交
165
class GreaterThanChecker {
166
 public:
F
fengjiayi 已提交
167
  explicit GreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
168
  void operator()(T& value) const {
F
fengjiayi 已提交
169
    PADDLE_ENFORCE(value > lower_bound_, "larger_than check fails.");
170 171 172 173 174 175
  }

 private:
  T lower_bound_;
};

F
WIP  
fengjiayi 已提交
176
template <typename T>
F
fengjiayi 已提交
177
class EqualGreaterThanChecker {
F
WIP  
fengjiayi 已提交
178
 public:
F
fengjiayi 已提交
179
  explicit EqualGreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
F
WIP  
fengjiayi 已提交
180
  void operator()(T& value) const {
F
fengjiayi 已提交
181
    PADDLE_ENFORCE_GE(value, lower_bound_, "equal_larger_than check fails.");
F
WIP  
fengjiayi 已提交
182 183 184 185 186 187
  }

 private:
  T lower_bound_;
};

188 189 190 191 192 193
// we can provide users more common Checker, like 'LessThanChecker',
// 'BetweenChecker'...

template <typename T>
class DefaultValueSetter {
 public:
Y
Yi Wang 已提交
194 195
  explicit DefaultValueSetter(T default_value)
      : default_value_(default_value) {}
T
tangwei12 已提交
196
  void operator()(const T& value) const { value = default_value_; }
197 198 199 200 201

 private:
  T default_value_;
};

Y
Yu Yang 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
template <typename T>
class EnumInContainer {
 public:
  explicit EnumInContainer(const std::unordered_set<T>& c) : container_(c) {}
  void operator()(T& val) const {
    PADDLE_ENFORCE(container_.find(val) != container_.end(),
                   "Value %s is not in enum container %s", val,
                   ContainerDebugString());
  }

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

231 232 233 234 235 236 237
// check whether a certain attribute fit its limits
// an attribute can have more than one limits
template <typename T>
class TypedAttrChecker {
  typedef std::function<void(T&)> ValueChecker;

 public:
Y
Yi Wang 已提交
238 239
  explicit TypedAttrChecker(const std::string& attr_name)
      : attr_name_(attr_name) {}
240

Y
Yu Yang 已提交
241 242 243 244 245
  TypedAttrChecker& InEnum(const std::unordered_set<T>& range) {
    value_checkers_.push_back(EnumInContainer<T>(range));
    return *this;
  }

F
fengjiayi 已提交
246 247
  TypedAttrChecker& GreaterThan(const T& lower_bound) {
    value_checkers_.push_back(GreaterThanChecker<T>(lower_bound));
248 249 250
    return *this;
  }

F
fengjiayi 已提交
251 252
  TypedAttrChecker& EqualGreaterThan(const T& lower_bound) {
    value_checkers_.push_back(EqualGreaterThanChecker<T>(lower_bound));
F
WIP  
fengjiayi 已提交
253 254 255
    return *this;
  }

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
  // we can add more common limits, like LessThan(), Between()...

  TypedAttrChecker& SetDefault(const T& default_value) {
    PADDLE_ENFORCE(default_value_setter_.empty(),
                   "%s can't have more than one default value!", attr_name_);
    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;
  }

T
tangwei12 已提交
271
  void operator()(const AttributeMap& attr_map) const {
272 273 274 275 276 277 278 279 280 281
    if (!attr_map.count(attr_name_)) {
      // user do not set this attr
      PADDLE_ENFORCE(!default_value_setter_.empty(),
                     "Attribute '%s' is required!", attr_name_);
      // default_value_setter_ has no more than one element
      T val;
      (default_value_setter_[0])(val);
      attr_map[attr_name_] = val;
    }
    Attribute& attr = attr_map.at(attr_name_);
282 283
    ExtractAttribute<T> extract_attr(attr_name_);
    T* attr_value = extract_attr(attr);
284
    for (const auto& checker : value_checkers_) {
285
      checker(*attr_value);
286 287 288 289 290 291 292 293 294 295 296
    }
  }

 private:
  std::string attr_name_;
  std::vector<ValueChecker> value_checkers_;
  std::vector<ValueChecker> default_value_setter_;
};

// check whether op's all attributes fit their own limits
class OpAttrChecker {
T
tangwei12 已提交
297
  typedef std::function<void(const AttributeMap&)> AttrChecker;
298 299 300 301 302 303 304 305 306

 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>>());
  }

T
tangwei12 已提交
307
  void Check(const AttributeMap& attr_map) const {
308 309 310 311 312 313 314 315 316 317 318
    for (const auto& checker : attr_checkers_) {
      checker(attr_map);
    }
  }

 private:
  std::vector<AttrChecker> attr_checkers_;
};

}  // namespace framework
}  // namespace paddle