paddle_mlir.cc 19.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2022 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/infrt/host_context/paddle_mlir.h"
16 17 18

#include <mlir/IR/OpDefinition.h>

H
huzhiqiang 已提交
19 20
#include "paddle/infrt/dialect/infrt/ir/basic_kernels.h"
#include "paddle/infrt/dialect/infrt/ir/infrt_dialect.h"
21
#include "paddle/infrt/dialect/pd/common/pd_ops_info.h"
22
#include "paddle/infrt/dialect/phi/ir/infrt_phi_tensor.h"
23 24 25 26 27 28

MLIRModelGenImpl::MLIRModelGenImpl()
    : context_(infrt::Global::getMLIRContext()), builder_(context_) {
  context_->getOrLoadDialect<mlir::StandardOpsDialect>();
  context_->getOrLoadDialect<infrt::ts::TensorShapeDialect>();
  context_->getOrLoadDialect<infrt::dt::DTDialect>();
29
  context_->getOrLoadDialect<infrt::pd::PaddleDialect>();
H
huzhiqiang 已提交
30
  context_->getOrLoadDialect<::infrt::InfrtDialect>();
31 32
  context_->getOrLoadDialect<::infrt::phi::PHIDialect>();
  context_->getOrLoadDialect<::infrt::phi::PHIDenseTensorDialect>();
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
  module_ = mlir::ModuleOp::create(mlir::UnknownLoc::get(context_));
}

infrt::paddle::framework_proto::ProgramDesc MLIRModelGenImpl::ParsePaddleModel(
    const std::string &model_file) {
  infrt::paddle::framework_proto::ProgramDesc program_proto =
      *infrt::paddle::LoadProgram(model_file);
  return program_proto;
}

mlir::ModuleOp MLIRModelGenImpl::ImportPaddleModel(
    const std::string &model_dir) {
  infrt::paddle::framework_proto::ProgramDesc program_proto =
      ParsePaddleModel(model_dir + "/__model__");
  return ImportPaddleModel(program_proto);
}

mlir::ModuleOp MLIRModelGenImpl::ImportPaddleModel(
    const std::string &model_file, const std::string &param_file) {
  infrt::paddle::framework_proto::ProgramDesc program_proto =
      ParsePaddleModel(model_file);
  return ImportPaddleModel(program_proto);
}

mlir::ModuleOp MLIRModelGenImpl::ImportPaddleModel(
    const infrt::paddle::framework_proto::ProgramDesc &program) {
  main_block_ = program.blocks(0);
  llvm::SmallVector<mlir::Type, 4> operandTypes = GetModelInputsType(program);
  llvm::SmallVector<mlir::Type, 4> resultTypes = GetModelOutputsType(program);
  mlir::FuncOp mainFunc = UpdateModelModule(operandTypes, resultTypes);
  UpdateModelParams(program, &mainFunc);
  UpdateModelOps(program);
  UpdateModelOutputs(program);
  return module_;
}

mlir::FuncOp MLIRModelGenImpl::UpdateModelModule(
    llvm::SmallVector<mlir::Type, 4> operandTypes,
    llvm::SmallVector<mlir::Type, 4> resultTypes) {
  // create main op
  const std::string &name = "main_graph";
  auto mainFunc = mlir::FuncOp::create(
      mlir::UnknownLoc::get(context_),
      name,
      /*type=*/builder_.getFunctionType({operandTypes}, {resultTypes}),
      /*attrs=*/{});
  module_.push_back(mainFunc);
  mainFunc.addEntryBlock();
  builder_.setInsertionPointToStart(&mainFunc.body().back());
  return mainFunc;
}

llvm::SmallVector<mlir::Type, 4> MLIRModelGenImpl::GetModelInputsType(
    const infrt::paddle::framework_proto::ProgramDesc &program) {
  llvm::SmallVector<mlir::Type, 4> operandTypes;
88
  operandTypes.push_back(infrt::phi::DenseTensorMapType::get(context_));
89 90 91 92 93 94 95 96 97 98 99
  for (auto &op_desc : main_block_.ops()) {
    if (op_desc.type() != "feed") continue;
    for (int var_idx = 0; var_idx < op_desc.outputs_size(); ++var_idx) {
      // update input variables
      auto &in = op_desc.outputs()[var_idx];
      std::string input_var_name = in.arguments(0);
      for (int i = 0; i < main_block_.vars_size(); i++) {
        auto var_desc = main_block_.vars(i);
        if (var_desc.name() == input_var_name) {
          std::vector<int64_t> dims = RepeatedToVector<int64_t>(
              var_desc.type().lod_tensor().tensor().dims());
H
huzhiqiang 已提交
100
          infrt::PrecisionType precision_;
101
          ConvertDataTypeToInfrt(
H
huzhiqiang 已提交
102 103 104 105 106
              var_desc.type().lod_tensor().tensor().data_type(), &precision_);
          mlir::Type type_ =
              infrt::DenseTensorType::get(context_,
                                          infrt::TargetType::CPU,
                                          precision_,
107
                                          infrt::LayoutType::NCHW);
H
huzhiqiang 已提交
108

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
          operandTypes.push_back(type_);
        }
      }
    }
  }
  return operandTypes;
}

llvm::SmallVector<mlir::Type, 4> MLIRModelGenImpl::GetModelOutputsType(
    const infrt::paddle::framework_proto::ProgramDesc &program) {
  llvm::SmallVector<mlir::Type, 4> resultTypes;
  for (auto &op_desc : main_block_.ops()) {
    if (op_desc.type() != "fetch") continue;
    for (int var_idx = 0; var_idx < op_desc.inputs_size(); ++var_idx) {
      auto &in = op_desc.inputs()[var_idx];
      std::string input_var_name = in.arguments(0);
      for (int i = 0; i < main_block_.vars_size(); i++) {
        auto var_desc = main_block_.vars(i);
        if (var_desc.name() == input_var_name) {
          std::vector<int64_t> dims = RepeatedToVector<int64_t>(
              var_desc.type().lod_tensor().tensor().dims());
H
huzhiqiang 已提交
130
          infrt::PrecisionType precision_;
131
          ConvertDataTypeToInfrt(
H
huzhiqiang 已提交
132 133 134 135 136
              var_desc.type().lod_tensor().tensor().data_type(), &precision_);
          mlir::Type type_ =
              infrt::DenseTensorType::get(context_,
                                          infrt::TargetType::CPU,
                                          precision_,
137
                                          infrt::LayoutType::NCHW);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
          resultTypes.push_back(type_);
        }
      }
    }
  }
  return resultTypes;
}

void MLIRModelGenImpl::UpdateModelOps(
    const infrt::paddle::framework_proto::ProgramDesc &program) {
  for (auto &op_desc : main_block_.ops()) {
    if (op_desc.type() == "feed" || op_desc.type() == "fetch") {
      continue;
    }
    buildOperation(op_desc);
  }
}

void MLIRModelGenImpl::UpdateModelParams(
    const infrt::paddle::framework_proto::ProgramDesc &program,
    mlir::FuncOp *mainFunc) {
  // update input vars
160
  int input_index = 1;
161 162 163 164 165 166
  for (auto &op_desc : main_block_.ops()) {
    if (op_desc.type() == "feed") {
      for (int var_idx = 0; var_idx < op_desc.outputs_size(); ++var_idx) {
        // update input variables
        auto &in = op_desc.outputs()[var_idx];
        std::string input_var_name = in.arguments(0);
167
        ::mlir::Value input_ = mainFunc->getArgument(input_index++);
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        params_map_.insert(
            std::pair<std::string, mlir::Value>(input_var_name, input_));
      }
    }
  }

  // update persistable tensors
  ::mlir::Value map = mainFunc->getArgument(0);
  for (int i = 0; i < main_block_.vars_size(); i++) {
    auto var_desc = main_block_.vars(i);
    if (params_map_.find(var_desc.name()) != params_map_.end()) continue;
    if (var_desc.name() != "feed" && var_desc.name() != "fetch" &&
        var_desc.persistable()) {
      auto name = builder_.getStringAttr(var_desc.name());
      std::vector<int64_t> dims = RepeatedToVector<int64_t>(
          var_desc.type().lod_tensor().tensor().dims());
H
huzhiqiang 已提交
184
      infrt::PrecisionType precision_;
185 186 187 188 189 190
      ConvertDataTypeToInfrt(var_desc.type().lod_tensor().tensor().data_type(),
                             &precision_);
      mlir::Type type_ = infrt::DenseTensorType::get(context_,
                                                     infrt::TargetType::CPU,
                                                     precision_,
                                                     infrt::LayoutType::NCHW);
191
      auto op = builder_.create<::infrt::phi::TensorMapGetTensorOp>(
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
          mlir::UnknownLoc::get(context_), type_, map, name);
      params_map_.insert(std::pair<std::string, mlir::Value>(
          var_desc.name(), op.getOperation()->getResult(0)));
    }
  }
}

void MLIRModelGenImpl::UpdateModelOutputs(
    const infrt::paddle::framework_proto::ProgramDesc &program) {
  // update outputs
  for (auto &op_desc : main_block_.ops()) {
    if (op_desc.type() == "fetch") {
      for (int var_idx = 0; var_idx < op_desc.inputs_size(); ++var_idx) {
        auto &in = op_desc.inputs()[var_idx];
        // varibale name
        std::string input_var_name = in.arguments(0);
        // update model outpus
        mlir::Location loc = mlir::UnknownLoc::get(context_);
        llvm::SmallVector<mlir::Value, 4> operands;

        operands.push_back((params_map_[input_var_name]));

        llvm::SmallVector<mlir::Type, 4> resultTypes;
        llvm::SmallVector<mlir::NamedAttribute, 4> attrs;
H
huzhiqiang 已提交
216

217
        mlir::OperationState state(loc,
H
huzhiqiang 已提交
218
                                   ::infrt::ReturnOp::getOperationName(),
219 220 221 222 223 224 225 226 227 228 229
                                   operands,
                                   resultTypes,
                                   attrs);
        builder_.createOperation(state);
      }
    }
  }
}

void MLIRModelGenImpl::buildOperation(
    const infrt::paddle::framework_proto::OpDesc &op_) {
230
  const std::string op_name = "pd." + op_.type();
231
  mlir::Location loc = mlir::UnknownLoc::get(context_);
232 233 234 235 236 237 238 239 240 241 242 243 244
  mlir::OperationState result(loc, op_name);

  if (!result.name.isRegistered()) {
    LOG(FATAL) << "Find unregistered operation: " << op_name;
    return;
  }

  if (result.name.hasTrait<mlir::OpTrait::AttrSizedOperandSegments>()) {
    LOG(FATAL) << "Find operation: " << op_name
               << "has trait: AttrSizedOperandSegments. Current not support!";
    return;
  }

245
  llvm::SmallVector<mlir::Value, 4> operands = GetOpInputValue(op_);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  int empty_operand_cnt = 0;
  for (auto it = operands.begin(); it != operands.end();) {
    if (*it) {
      ++it;
    } else {
      operands.erase(it);
      ++empty_operand_cnt;
    }
  }
  if (empty_operand_cnt > 1) {
    LOG(FATAL)
        << "Find operation: " << op_name << ", has " << empty_operand_cnt
        << " empty operands. current not support empty operands more than one!";
    return;
  }
  result.addOperands(operands);
262 263
  llvm::SmallVector<mlir::Type, 4> resultTypes = GetOpOutputType(op_);
  llvm::SmallVector<mlir::NamedAttribute, 4> attrs = GetOpAttributes(op_);
264 265
  result.addTypes(resultTypes);
  result.addAttributes(attrs);
266 267 268 269 270 271 272 273
  mlir::Operation *mlir_op_ = builder_.createOperation(result);
  RegisterOpOutputVars(op_, mlir_op_);
}

llvm::SmallVector<mlir::Value, 4> MLIRModelGenImpl::GetOpInputValue(
    const infrt::paddle::framework_proto::OpDesc &op_) {
  llvm::SmallVector<mlir::Value, 4> operands;

274
  std::unordered_map<std::string, uint8_t> inputs_info = {};
275 276
  if (pd_dialect_inputs_info_map_.count(op_.type()))
    inputs_info = pd_dialect_inputs_info_map_.at(op_.type());
277
  operands.resize(inputs_info.size());
278 279 280
  for (int var_idx = 0; var_idx < op_.inputs_size(); ++var_idx) {
    auto &var = op_.inputs(var_idx);
    if (!var.arguments().empty()) {
281
      if (!inputs_info.count(var.parameter())) continue;
282 283
      operands[inputs_info.at(var.parameter())] =
          params_map_[var.arguments()[0]];
284 285 286 287 288 289 290 291 292
    }
  }
  return operands;
}

llvm::SmallVector<mlir::Type, 4> MLIRModelGenImpl::GetOpOutputType(
    const infrt::paddle::framework_proto::OpDesc &op_) {
  llvm::SmallVector<mlir::Type, 4> resultTypes;

293
  std::unordered_map<std::string, uint8_t> pd_dialect_outputs_info = {};
294 295
  if (pd_dialect_outputs_info_map_.count(op_.type()))
    pd_dialect_outputs_info = pd_dialect_outputs_info_map_.at(op_.type());
296
  resultTypes.resize(pd_dialect_outputs_info.size());
297 298 299
  // update op outputs info
  for (int var_idx = 0; var_idx < op_.outputs_size(); ++var_idx) {
    auto &var_name = op_.outputs(var_idx).arguments()[0];
300
    if (!pd_dialect_outputs_info.count(op_.outputs(var_idx).parameter()))
301 302 303 304 305 306 307
      continue;
    // update persistable tensors
    for (int i = 0; i < main_block_.vars_size(); i++) {
      auto var_desc = main_block_.vars(i);
      if (var_desc.name() == var_name) {
        std::vector<int64_t> dims = RepeatedToVector<int64_t>(
            var_desc.type().lod_tensor().tensor().dims());
H
huzhiqiang 已提交
308
        infrt::PrecisionType precision_;
309 310
        ConvertDataTypeToInfrt(
            var_desc.type().lod_tensor().tensor().data_type(), &precision_);
H
huzhiqiang 已提交
311 312 313
        mlir::Type type_ = infrt::DenseTensorType::get(context_,
                                                       infrt::TargetType::CPU,
                                                       precision_,
314 315 316
                                                       infrt::LayoutType::NCHW);
        resultTypes[pd_dialect_outputs_info.at(
            op_.outputs(var_idx).parameter())] = type_;
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 373 374 375
      }
    }
  }
  return resultTypes;
}

llvm::SmallVector<mlir::NamedAttribute, 4> MLIRModelGenImpl::GetOpAttributes(
    const infrt::paddle::framework_proto::OpDesc &op_) {
  // GetInputVarName
  llvm::SmallVector<mlir::NamedAttribute, 4> attrs;

#define ATTR_IMPL_CASE(PROTO_TYPE, PROTO_TYPE_METHOD, MLIR_TYPE_METHOD) \
  case infrt::paddle::framework_proto::AttrType::PROTO_TYPE: {          \
    auto data = op_.attrs(attrs_num).PROTO_TYPE_METHOD();               \
    auto value_ = builder_.MLIR_TYPE_METHOD(data);                      \
    auto name_ = builder_.getStringAttr(attr_name_);                    \
    auto attr_ = mlir::NamedAttribute(name_, value_);                   \
    attrs.push_back(attr_);                                             \
    break;                                                              \
  }

#define REPEATED_ATTR_IMPLE_CASE(                                       \
    PROTO_TYPE, PROTO_TYPE_METHOD, MLIR_TYPE, MLIR_TYPE_METHOD)         \
  case infrt::paddle::framework_proto::AttrType::PROTO_TYPE: {          \
    std::vector<MLIR_TYPE> data;                                        \
    for (const auto &var : op_.attrs(attrs_num).PROTO_TYPE_METHOD()) {  \
      data.push_back(MLIR_TYPE(var));                                   \
    }                                                                   \
    auto value_ =                                                       \
        builder_.MLIR_TYPE_METHOD(llvm::makeArrayRef<MLIR_TYPE>(data)); \
    auto name_ = builder_.getStringAttr(attr_name_);                    \
    auto attr_ = mlir::NamedAttribute(name_, value_);                   \
    attrs.push_back(attr_);                                             \
    break;                                                              \
  }

#define UNIMPLEMENTED_ATTR_IMPL_CASE(PROTO_TYPE)                        \
  case infrt::paddle::framework_proto::AttrType::PROTO_TYPE: {          \
    std::cout << "Unimplemented attr type: framework_proto::AttrType::" \
              << #PROTO_TYPE << std::endl;                              \
    break;                                                              \
  }

  // get registered attributes
  const std::string &op_name = "pd." + op_.type();
  mlir::RegisteredOperationName registered_op_name_ =
      mlir::RegisteredOperationName::lookup(op_name, context_).getValue();
  llvm::ArrayRef<mlir::StringAttr> attr_names_ =
      registered_op_name_.getAttributeNames();
  std::vector<mlir::StringAttr> attr_names_vec_ = attr_names_.vec();
  // update attrs
  for (int attrs_num = 0; attrs_num < op_.attrs_size(); attrs_num++) {
    auto attr_name_ = op_.attrs(attrs_num).name();
    auto type = op_.attrs(attrs_num).type();
    if (!std::count(attr_names_vec_.begin(), attr_names_vec_.end(), attr_name_))
      continue;
    switch (type) {
      ATTR_IMPL_CASE(FLOAT, f, getF32FloatAttr);
      ATTR_IMPL_CASE(BOOLEAN, b, getBoolAttr);
H
huzhiqiang 已提交
376
      ATTR_IMPL_CASE(INT, i, getSI32IntegerAttr);
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
      ATTR_IMPL_CASE(LONG, l, getI64IntegerAttr);
      ATTR_IMPL_CASE(STRING, s, getStringAttr);

      REPEATED_ATTR_IMPLE_CASE(
          STRINGS, strings, llvm::StringRef, getStrArrayAttr);
      REPEATED_ATTR_IMPLE_CASE(FLOATS, floats, float, getF32ArrayAttr);
      REPEATED_ATTR_IMPLE_CASE(INTS, ints, int32_t, getI32ArrayAttr);
      REPEATED_ATTR_IMPLE_CASE(LONGS, longs, int64_t, getI64ArrayAttr);

      // Unimplemented attr type, will be supported later @DannyIsFunny
      // bools attribute is not supported due to bug of llvm.
      // REPEATED_ATTR_IMPLE_CASE(BOOLEANS, bools, bool, getBoolArrayAttr);
      UNIMPLEMENTED_ATTR_IMPL_CASE(BOOLEANS);
      UNIMPLEMENTED_ATTR_IMPL_CASE(BLOCK);
      UNIMPLEMENTED_ATTR_IMPL_CASE(BLOCKS);
      default:
        std::cout << "error attribute" << attr_name_ << std::endl;
    }
  }
  return attrs;
}

void MLIRModelGenImpl::RegisterOpOutputVars(
    const infrt::paddle::framework_proto::OpDesc &op_,
    mlir::Operation *mlir_op_) {
402 403 404
  std::unordered_map<std::string, uint8_t> pd_dialect_outputs_info =
      pd_dialect_outputs_info_map_.at(op_.type());

405 406
  // op outputs
  for (int var_idx = 0; var_idx < op_.outputs_size(); ++var_idx) {
407 408
    if (!pd_dialect_outputs_info.count(op_.outputs(var_idx).parameter()))
      continue;
409
    auto &var_name = op_.outputs(var_idx).arguments()[0];
410
    int index = pd_dialect_outputs_info[op_.outputs(var_idx).parameter()];
411
    // output name
412
    auto var_ = mlir_op_->getResult(index);
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    params_map_.insert(std::pair<std::string, mlir::Value>(var_name, var_));
  }
}

bool ConvertDataType(infrt::paddle::framework_proto::VarType::Type dtype,
                     mlir::Builder builder,
                     mlir::Type *type) {
  switch (dtype) {
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_FP16:
      *type = builder.getF16Type();
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_FP32:
      *type = builder.getF32Type();
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_FP64:
      *type = builder.getF64Type();
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_BOOL:
      *type = builder.getIntegerType(1);
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT8:
      *type = builder.getIntegerType(8);
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT16:
      *type = builder.getIntegerType(16);
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT32:
      *type = builder.getIntegerType(32);
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT64:
      *type = builder.getIntegerType(64);
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_UINT8:
      *type = builder.getIntegerType(8, /*isSigned=*/false);
      return true;
    default:
      return false;
  }
}
H
huzhiqiang 已提交
452

453 454
bool ConvertDataTypeToInfrt(infrt::paddle::framework_proto::VarType::Type dtype,
                            infrt::PrecisionType *type) {
H
huzhiqiang 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  switch (dtype) {
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_FP16:
      *type = infrt::PrecisionType::FLOAT16;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_FP32:
      *type = infrt::PrecisionType::FLOAT32;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_FP64:
      *type = infrt::PrecisionType::FLOAT64;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_BOOL:
      *type = infrt::PrecisionType::BOOL;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT8:
      *type = infrt::PrecisionType::INT8;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT16:
      *type = infrt::PrecisionType::INT16;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT32:
      *type = infrt::PrecisionType::INT32;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_INT64:
      *type = infrt::PrecisionType::INT64;
      return true;
    case infrt::paddle::framework_proto::VarType::Type::VarType_Type_UINT8:
      *type = infrt::PrecisionType::UINT8;
      return true;
    default:
      return false;
  }
}