op_compat_sensible_pass.cc 9.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.

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

#include "paddle/fluid/framework/ir/op_compat_sensible_pass.h"
16 17 18 19
#include <memory>
#include <mutex>
#include <unordered_map>
#include "paddle/fluid/framework/op_def_api.h"
20
#include "paddle/fluid/framework/op_info.h"
21

22 23 24 25 26 27 28 29 30
namespace {
std::unordered_set<std::string> global_extra_attrs = {
    "op_role",       "op_role_var",      "op_namescope",
    "op_callstack",  "op_device",        "@ENABLE_CACHE_RUNTIME_CONTEXT@",
    "is_test",       "use_mkldnn",       "mkldnn_data_type",
    "use_quantizer", "mkldnn_data_type", "use_cudnn",
    "name"};
}

31 32 33 34
namespace paddle {
namespace framework {
namespace ir {

35 36 37 38 39 40 41
AttrCompat& AttrCompat::IsStringEQ(const std::string& value) {
  conditions_.emplace_back([value](const Attribute& attr) -> bool {
    return value == BOOST_GET_CONST(std::string, attr);
  });
  return *this;
}

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
AttrCompat& AttrCompat::IsStringIn(const std::set<std::string>& candidates) {
  conditions_.emplace_back([candidates](const Attribute& attr) -> bool {
    std::string value = BOOST_GET_CONST(std::string, attr);
    for (auto& str : candidates) {
      if (str == value) {
        return true;
      }
    }
    return false;
  });
  return *this;
}

AttrCompat& AttrCompat::IsStringMatch(
    const std::function<bool(const std::string&)>& func) {
  conditions_.emplace_back([func](const Attribute& attr) -> bool {
    std::string value = BOOST_GET_CONST(std::string, attr);
    return func(value);
  });
  return *this;
}

AttrCompat& AttrCompat::IsIntIn(const std::set<int>& candidates) {
  conditions_.emplace_back([candidates](const Attribute& attr) -> bool {
    int value = BOOST_GET_CONST(int, attr);
    return candidates.find(value) != candidates.end();
  });
  return *this;
}

72 73 74
AttrCompat& AttrCompat::IsLeftDefault() {
  const std::string& op_name = op_compat_->Name();
  if (!OpInfoMap::Instance().Has(op_name)) {
75
    LOG(WARNING) << "Op (" << op_name << ") is not registered!";
76 77 78 79
    conditions_.emplace_back([](const Attribute& attr) { return false; });
    return *this;
  }
  const OpInfo& op_info = OpInfoMap::Instance().Get(op_name);
80
  const AttributeMap attrs = op_info.Checker()->GetDefaultAttrsMap();
81
  if (attrs.find(attr_name_) == attrs.end()) {
82
    LOG(WARNING) << "Op (" << op_name << ") has no default attr:" << attr_name_;
83 84 85 86 87 88 89 90 91
    conditions_.emplace_back([](const Attribute& attr) { return false; });
  } else {
    Attribute default_attr = attrs.at(attr_name_);
    conditions_.emplace_back([default_attr](const Attribute& attr) -> bool {
      return attr == default_attr;
    });
  }
  return *this;
}
92 93 94

bool AttrCompat::operator()(const OpDesc& op_desc) {
  if (!op_desc.HasAttr(attr_name_)) {
95 96 97 98
    if (!optional_) {
      LOG(WARNING) << "The non-optional Attr(" << attr_name_ << ") of Op ("
                   << op_compat_->Name() << ") not find ! ";
    }
99
    return optional_;
100 101 102 103 104 105 106 107 108
  }
  const Attribute attr = op_desc.GetAttr(attr_name_);
  for (auto& func : conditions_) {
    if (!func(attr)) {
      return false;
    }
  }
  return true;
}
109 110 111 112
AttrCompat& AttrCompat::IsOptional() {
  optional_ = true;
  return *this;
}
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

AttrCompat& AttrCompat::IsBoolEQ(bool v) {
  conditions_.emplace_back([v](const Attribute& attr) -> bool {
    bool value = BOOST_GET_CONST(bool, attr);
    return value == v;
  });
  return *this;
}

InputOrOutputCompat& InputOrOutputCompat::IsTensor() {
  conditions_.emplace_back([](const std::vector<std::string>& input) -> bool {
    return input.size() == 1u;
  });
  return *this;
}

InputOrOutputCompat& InputOrOutputCompat::IsOptional() {
  optional_ = true;
  return *this;
}

bool InputOrOutputCompat::operator()(
    const std::vector<std::string>& input) const {
136
  if (input.empty()) return optional_;
137 138 139 140 141 142 143 144 145
  for (auto& func : conditions_) {
    if (!func(input)) {
      return false;
    }
  }
  return true;
}

AttrCompat& OpCompat::AddAttr(const std::string& attr_name) {
146 147 148 149 150 151
  PADDLE_ENFORCE_EQ(
      attr_compats_.find(attr_name), attr_compats_.end(),
      platform::errors::InvalidArgument(
          "The attrubute compat with the same name has been added"));
  attr_compats_.emplace(attr_name, AttrCompat(attr_name, this));
  return attr_compats_.at(attr_name);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
}

InputOrOutputCompat& OpCompat::AddInput(const std::string& name) {
  PADDLE_ENFORCE_EQ(input_compats_.find(name), input_compats_.end(),
                    platform::errors::InvalidArgument(
                        "The input with the same name has been added"));
  input_compats_.emplace(name, InputOrOutputCompat(name, this));
  return input_compats_.at(name);
}

InputOrOutputCompat& OpCompat::AddOutput(const std::string& name) {
  PADDLE_ENFORCE_EQ(output_compats_.find(name), output_compats_.end(),
                    platform::errors::InvalidArgument(
                        "The output with the same name has been added"));
  output_compats_.emplace(name, InputOrOutputCompat(name, this));
  return output_compats_.at(name);
}

bool OpCompat::Judge(const OpDesc& op_desc) {
171 172 173 174 175 176 177 178 179 180
  if (is_first_judge_) {
    is_first_judge_ = false;
    const proto::OpDef& op_def = GetOpDef(op_name_);
    if (op_def.has_extra()) {
      for (const proto::OpDef_AttrDef& attr : op_def.extra().attrs()) {
        extra_attrs_.emplace(attr.name());
      }
    }
  }

181
  for (auto& attr_map : op_desc.GetAttrMap()) {
182 183 184 185 186 187
    const std::string& name = attr_map.first;
    if (name.size() >= 10u &&
        0 == name.compare(name.size() - 10u, 10u, "_threshold")) {
      continue;  // skip the attribute ends with "_threshold", it used for
                 // quantization.
    }
188
    if (attr_compats_.find(attr_map.first) == attr_compats_.end()) {
189 190
      if (global_extra_attrs.find(attr_map.first) != global_extra_attrs.end() ||
          extra_attrs_.find(attr_map.first) != extra_attrs_.end()) {
191 192
        continue;
      }
193
      if (!AttrCompat(attr_map.first, this).IsLeftDefault()(op_desc)) {
194 195 196 197
        LOG(WARNING)
            << "The Attr(" << attr_map.first << ") of Op (" << op_name_
            << ") not reigistered in OpCompat, not in extra attribute, not "
               "equal to default value!";
198 199 200 201
        return false;
      }
    }
  }
202

203
  for (auto& attr_compat : attr_compats_) {
204
    if (!attr_compat.second(op_desc)) {
205 206
      LOG(WARNING) << " Check the Attr(" << attr_compat.first << ") of Op("
                   << op_name_ << ") failed!";
207 208 209 210 211 212 213 214
      return false;
    }
  }

  const VariableNameMap& inputs_map = op_desc.Inputs();
  for (auto& input_desc : inputs_map) {
    if (input_compats_.find(input_desc.first) == input_compats_.end()) {
      if (!input_desc.second.empty()) {
215 216
        LOG(WARNING) << "The Input (" << input_desc.first << ") of Operator ("
                     << op_name_ << ") not reigistered in OpCompat!";
217 218 219 220 221 222 223
        return false;
      }
    }
  }
  for (auto& input_val : input_compats_) {
    if (inputs_map.find(input_val.first) == inputs_map.end()) {
      if (!input_val.second.Optional()) {
224 225 226
        LOG(WARNING) << "The No optional Input (" << input_val.first
                     << ") of Operator (" << op_name_
                     << ") not find in op_desc!";
227 228 229 230
        return false;
      }
    } else {
      if (!input_val.second(inputs_map.at(input_val.first))) {
231 232
        LOG(WARNING) << "The Input (" << input_val.first << ") of Operator ("
                     << op_name_ << ") compat check failed!";
233 234 235 236 237 238 239 240 241
        return false;
      }
    }
  }

  const VariableNameMap& outputs_map = op_desc.Outputs();
  for (auto& output_desc : outputs_map) {
    if (output_compats_.find(output_desc.first) == output_compats_.end()) {
      if (!output_desc.second.empty()) {
242 243
        LOG(WARNING) << "The Output (" << output_desc.first << ") of Operator ("
                     << op_name_ << ") not reigistered in OpCompat!";
244 245 246 247 248 249 250
        return false;
      }
    }
  }
  for (auto& output_val : output_compats_) {
    if (outputs_map.find(output_val.first) == outputs_map.end()) {
      if (!output_val.second.Optional()) {
251 252 253
        LOG(WARNING) << "The No optional Output (" << output_val.first
                     << ") of Operator (" << op_name_
                     << ") not find in op_desc!";
254 255 256 257
        return false;
      }
    } else {
      if (!output_val.second(outputs_map.at(output_val.first))) {
258 259
        LOG(WARNING) << "The Output (" << output_val.first << ") of Operator ("
                     << op_name_ << ") compat check failed!";
260 261 262 263 264 265 266 267 268 269 270 271 272
        return false;
      }
    }
  }
  return true;
}

OpCompat& OpCompatSensiblePass::AddOpCompat(OpCompat&& op_compat) {
  std::string name = op_compat.Name();
  op_compat_judgers_[name].reset(new OpCompat(std::move(op_compat)));
  return *(op_compat_judgers_[name]);
}

273 274 275 276 277 278 279 280 281 282 283 284 285
//! Tell the Op compability of a subgraph.
bool OpCompatSensiblePass::IsCompat(
    const GraphPatternDetector::subgraph_t& subgraph, Graph*) const {
  PADDLE_ENFORCE_EQ(op_compat_judgers_.empty(), false,
                    platform::errors::InvalidArgument(
                        "At least one OpCompat instance should be added"));
  // Check the all the ops in the subgraph are contained in the
  // op_compat.
  for (auto& node_pair : subgraph) {
    if (!node_pair.second->IsOp()) continue;
    auto op_type = node_pair.second->Op()->Type();
    if (!op_compat_judgers_.count(op_type)) {
      if (HasOpDef(op_type)) {
286
        LOG(WARNING) << op_type << " compat not registered!";
287 288 289 290 291 292 293 294 295 296 297 298
        return false;
      }
      continue;
    }
    auto& judger = *op_compat_judgers_.at(op_type);
    if (!judger.Judge(*(node_pair.second->Op()))) {
      return false;
    }
  }
  return true;
}

299 300 301
}  // namespace ir
}  // namespace framework
}  // namespace paddle