infrt_api.cc 11.9 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

15
// clang-format off
Y
Yan Chunwei 已提交
16 17 18 19 20
#include "paddle/infrt/api/infrt_api.h"

#include <llvm/ADT/SmallVector.h>
#include <llvm/Support/DynamicLibrary.h>
#include <mlir/Dialect/StandardOps/IR/Ops.h>
W
Wilber 已提交
21
#include <mlir/IR/BuiltinOps.h>
Y
Yan Chunwei 已提交
22
#include <mlir/Parser.h>
W
Wilber 已提交
23 24
#include <mlir/Pass/PassManager.h>
#include <mlir/Transforms/Passes.h>
Y
Yan Chunwei 已提交
25 26 27 28

#include <unordered_map>
#include <vector>

29
#include "paddle/infrt/backends/host/phi_allocator.h"
Y
Yan Chunwei 已提交
30 31
#include "paddle/infrt/common/global.h"
#include "paddle/infrt/dialect/dense_tensor.h"
32
#include "paddle/infrt/dialect/infrt/ir/infrt_dialect.h"
33
#include "paddle/infrt/dialect/infrt/pass/infrt_op_fuse_pass.h"
Y
Yan Chunwei 已提交
34
#include "paddle/infrt/dialect/mlir_loader.h"
35 36
#include "paddle/infrt/dialect/phi/ir/phi_base.h"
#include "paddle/infrt/dialect/phi/pass/phi_op_convert_pass.h"
Y
Yan Chunwei 已提交
37 38 39 40 41
#include "paddle/infrt/host_context/core_runtime.h"
#include "paddle/infrt/host_context/kernel_registry.h"
#include "paddle/infrt/host_context/mlir_function_executable.h"
#include "paddle/infrt/host_context/mlir_to_runtime_translate.h"
#include "paddle/infrt/host_context/op_executable.h"
42
#include "paddle/infrt/host_context/paddle_mlir.h"
Y
Yan Chunwei 已提交
43 44 45
#include "paddle/infrt/host_context/value.h"
#include "paddle/infrt/kernel/basic_kernels.h"
#include "paddle/infrt/kernel/control_flow_kernels.h"
46 47 48
#include "paddle/infrt/kernel/phi/dense_tensor_kernels.h"
#include "paddle/infrt/kernel/phi/infershaped/infershaped_kernel_launchers.h"
#include "paddle/infrt/kernel/phi/registry.h"
Y
Yan Chunwei 已提交
49 50 51 52 53
#include "paddle/infrt/kernel/tensor_kernels.h"
#include "paddle/infrt/kernel/tensor_shape_kernels.h"
#include "paddle/infrt/kernel/test_kernels.h"
#include "paddle/infrt/tensor/tensor_map.h"

W
Wilber 已提交
54 55
#include "paddle/infrt/dialect/infrt/pass/infrt_weights_unfold_pass.h"

56 57
#if defined(INFRT_WITH_GPU) && defined(INFRT_WITH_TRT)
#include "paddle/infrt/kernel/tensorrt/registry.h"
W
Wilber 已提交
58 59 60 61 62 63

#include "paddle/infrt/dialect/tensorrt/trt_graph_fuse_pass.h"
#include "paddle/infrt/dialect/tensorrt/trt_graph_split_pass.h"
#include "paddle/infrt/dialect/tensorrt/trt_op_converter_pass.h"
#include "paddle/infrt/dialect/tensorrt/trt_op_teller_pass.h"
#include "paddle/infrt/dialect/tensorrt/trt_type_convert_pass.h"
64
#endif
65
// clang-format on
66

Y
Yan Chunwei 已提交
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
using namespace infrt::host_context;  // NOLINT
using namespace infrt::tensor;        // NOLINT
using namespace infrt::tensor;        // NOLINT

namespace infrt {

template <typename T>
std::string DumpToString(T& op) {  // NOLINT
  std::string buffer;
  llvm::raw_string_ostream os(buffer);
  op.print(os);
  os.flush();
  return buffer;
}

struct MlirToRuntimeTranslator::Impl {
  mlir::ModuleOp module;
  // The runtime for a function call.
  CoreRuntimeBuilder* runtime{};

  // The current working op, the translator process the ops one by one, each
  // time it updates `cur_op` here to current op
  // working on.
  OpExecutableBuilder* cur_op{};

  // record the current function name.
  std::string cur_func_name;

  // Name to function definitions.
  std::unordered_map<std::string, mlir::FuncOp> func_defs;

  // Map from an operation to its results.
  std::unordered_map<const mlir::Operation*, std::vector<ValueRef>> op_results;
  llvm::DenseMap<mlir::Value, ValueRef> value_map;
};

/**
 * Execute the mlir program in predict mode.
 */
class PredictExecutor : public MlirToRuntimeTranslator {
 public:
  CoreRuntimeBuilder core_runtime;

  PredictExecutor(mlir::ModuleOp module,
                  KernelRegistry* registry,
112
                  ::infrt::phi::DenseTensorMap&& map)
Y
Yan Chunwei 已提交
113 114 115 116
      : MlirToRuntimeTranslator(module, &core_runtime),
        core_runtime(registry),
        registry_(registry) {
    CHECK(registry_);
117
    Init(std::move(map));
Y
Yan Chunwei 已提交
118 119 120 121 122 123 124 125 126 127
  }

  void Run() {
    auto arguments = llvm::makeArrayRef(arguments_);
    auto results = llvm::makeMutableArrayRef(results_.begin(), results_.size());
    function_executable_->Execute(arguments, results);
  }

  int GetInputNum() { return inputs_.size(); }

128
  ::phi::DenseTensor* GetInput(int i) { return inputs_[i]; }
Y
Yan Chunwei 已提交
129 130 131

  int GetOutputNum() { return outputs_.size(); }

132
  ::phi::DenseTensor* GetOutput(int i) { return outputs_[i]; }
Y
Yan Chunwei 已提交
133 134

 private:
135
  void Init(::infrt::phi::DenseTensorMap&& map) {
Y
Yan Chunwei 已提交
136 137 138
    EmitFunctions();
    llvm::Optional<mlir::FuncOp> predict_func_ = llvm::None;
    for (auto func_op : impl_->module.getOps<mlir::FuncOp>()) {
139
      if (func_op.getName().str() != "main_graph") continue;
Y
Yan Chunwei 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152
      predict_func_ = func_op;
      break;
    }
    if (!predict_func_) {
      std::cout << "ERROR: init failed, no predict function found in mlir."
                << std::endl;
      return;
    }
    auto& predict_func = predict_func_.getValue();
    function_executable_ =
        new MlirFunctionExecutable(predict_func, registry_, impl_->func_defs);

    // process parammeters
153 154
    VLOG(3) << "Arguments num of predict func: "
            << predict_func.getNumArguments();
Y
Yan Chunwei 已提交
155 156 157 158
    for (size_t i = 0; i < predict_func.getNumArguments(); ++i) {
      auto arg = predict_func.getArgument(i);
      auto type = arg.getType();
      // this param is TensorMap
159 160
      if (type.isa<::infrt::phi::DenseTensorMapType>()) {
        auto* value = new host_context::Value(std::move(map));
Y
Yan Chunwei 已提交
161 162
        arguments_.push_back(value);
        AddValue(predict_func.getArgument(i), value);
163
      } else if (type.isa<::infrt::DenseTensorType>()) {
Y
Yan Chunwei 已提交
164
        // this param is an input Tensor
165
        auto dht = ::phi::DenseTensor();
Y
Yan Chunwei 已提交
166 167
        auto* value = new host_context::Value(std::move(dht));
        arguments_.push_back(value);
168 169 170
        inputs_.push_back(&(value->get<::phi::DenseTensor>()));
      } else {
        llvm_unreachable("The input type has not been supported by predictor.");
Y
Yan Chunwei 已提交
171 172 173 174 175
      }
    }

    // process results
    auto& last_op = predict_func.front().back();
176
    if (last_op.getName().getStringRef() == "infrt.return") {
Y
Yan Chunwei 已提交
177
      for (size_t i = 0; i < last_op.getNumOperands(); ++i) {
178 179 180 181 182 183 184 185 186 187 188 189
        auto operand = last_op.getOperand(i);
        if (operand.getType().isa<::infrt::DenseTensorType>()) {
          auto r = impl_->value_map.try_emplace(
              operand, ValueRef(new host_context::Value(::phi::DenseTensor())));
          CHECK(r.second) << "Duplicate add mlir value ["
                          << DumpToString(operand) << "]";
          auto* value = r.first->second.get();
          results_.push_back(ValueRef(value));
          outputs_.push_back(&(value->get<::phi::DenseTensor>()));
        } else {
          llvm_unreachable("infrt.return only supports DenseTensor now.");
        }
Y
Yan Chunwei 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
      }
    }
  }

 protected:
  std::unordered_map<std::string, mlir::FuncOp> func_def_table;

  void EmitFunction(mlir::FuncOp op) override {
    CHECK(!impl_->func_defs.count(op.getName().str()))
        << "Duplicate function defition found for function ["
        << op.getName().str();
    impl_->func_defs.emplace(op.getName().str(), op);
  }

 private:
  KernelRegistry* registry_{};
  MlirFunctionExecutable* function_executable_;
207
  llvm::SmallVector<::phi::DenseTensor*, 1> inputs_;
Y
Yan Chunwei 已提交
208
  llvm::SmallVector<host_context::Value*, 2> arguments_;
209
  llvm::SmallVector<::phi::DenseTensor*, 1> outputs_;
Y
Yan Chunwei 已提交
210 211 212
  llvm::SmallVector<ValueRef, 1> results_;
};

213
std::unique_ptr<InfRtPredictor> CreateInfRtPredictor(
Y
Yan Chunwei 已提交
214
    const InfRtConfig& config) {
215
  auto x = std::make_unique<InfRtPredictor>();
Y
Yan Chunwei 已提交
216 217 218 219 220 221
  x->Init(config);
  return x;
}

struct InfRtPredictor::Impl {
  std::unique_ptr<PredictExecutor> executor;
222
  MLIRModelGenImpl module_gen_;
Y
Yan Chunwei 已提交
223 224 225 226 227 228 229 230
};

InfRtPredictor::InfRtPredictor() : impl_(new Impl) {}
InfRtPredictor::~InfRtPredictor() {}

void InfRtPredictor::Run() { impl_->executor->Run(); }

int InfRtPredictor::Init(const InfRtConfig& config) {
231
  mlir::MLIRContext* context = ::infrt::Global::getMLIRContext();
Y
Yan Chunwei 已提交
232 233 234 235 236 237 238 239

  KernelRegistry* registry = new KernelRegistry();

  kernel::RegisterBasicKernels(registry);
  kernel::RegisterTestKernels(registry);
  kernel::RegisterTensorShapeKernels(registry);
  kernel::RegisterTensorKernels(registry);
  kernel::RegisterControlFlowKernels(registry);
240 241 242 243 244 245 246 247
#ifdef INFRT_WITH_PHI
  kernel::RegisterPhiKernels(registry);
  kernel::RegisterInferShapeLaunchers(registry);
#if defined(INFRT_WITH_GPU) && defined(INFRT_WITH_TRT)
  kernel::RegisterTrtKernels(registry);
#endif  // INFRT_WITH_GPU && INFRT_WITH_TRT
#endif

W
Wilber 已提交
248 249 250 251 252 253 254 255
  mlir::ModuleOp module_op;
  if (config.tensorrt_enabled()) {
    module_op = impl_->module_gen_.ImportPaddleModel(
        config.model_dir(), config.param_dir(), false);
  } else {
    module_op = impl_->module_gen_.ImportPaddleModel(config.model_dir(),
                                                     config.param_dir());
  }
256 257 258

  context->loadAllAvailableDialects();
  ::mlir::PassManager pm(context);
W
Wilber 已提交
259 260 261
  ::mlir::OpPassManager& pass_manager = pm.nest<::mlir::FuncOp>();
  if (config.tensorrt_enabled()) {
    pass_manager.addPass(::infrt::CreateInfrtWeightsUnfoldPass());
262
#if defined(INFRT_WITH_GPU) && defined(INFRT_WITH_TRT)
W
Wilber 已提交
263 264 265 266 267
    pass_manager.addPass(::infrt::trt::CreateTrtOpTellerPass());
    pass_manager.addPass(::infrt::trt::CreateTrtGraphFusePass());
    pass_manager.addPass(::infrt::trt::CreateTrtGraphSplitPass(1));
    pass_manager.addPass(::infrt::trt::CreateTrtOpConverterPass());
    pass_manager.addPass(::infrt::trt::CreateTrtTypeConvertPass());
268
#endif
W
Wilber 已提交
269 270 271 272 273 274
    pass_manager.addPass(::mlir::createCanonicalizerPass());
  } else {
    std::vector<::infrt::Place> valid_places = {
        {::infrt::TargetType::CPU,
         ::infrt::PrecisionType::FLOAT32,
         ::infrt::LayoutType::NCHW}};
275 276 277 278 279 280
    if (config.gpu_enabled()) {
      valid_places.insert(valid_places.begin(),
                          ::infrt::Place(::infrt::TargetType::GPU,
                                         ::infrt::PrecisionType::FLOAT32,
                                         ::infrt::LayoutType::NCHW));
    }
W
Wilber 已提交
281 282 283
    pass_manager.addPass(CreatePhiOpCvtPass(valid_places));
    pass_manager.addPass(CreateInfrtOpFusePass());
  }
284 285 286 287 288 289 290
  if (mlir::failed(pm.run(module_op))) {
    std::cout << "\npass failed!\n" << std::endl;
    return 4;
  }
#ifndef NDEBUG
  module_op.dump();
#endif  // NDEBUG
Y
Yan Chunwei 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

  // load extra shared library
  for (const std::string& lib_path : config.shared_libs()) {
    std::string err;
    llvm::sys::DynamicLibrary dynLib =
        llvm::sys::DynamicLibrary::getPermanentLibrary(lib_path.c_str(), &err);
    if (!dynLib.isValid()) {
      llvm::errs() << "Load shared library failed. Error: " << err << "\n";
      return 1;
    }
    if (auto reg_sym = dynLib.SearchForAddressOfSymbol("RegisterKernels")) {
      auto reg_func = reinterpret_cast<void (*)(KernelRegistry*)>(reg_sym);
      reg_func(registry);
    } else {
      llvm::outs() << "Symbol \"RegisterKernels\" not found in \"" << lib_path
                   << "\". Skip.\n";
    }
  }

  // Load params
311 312 313 314 315 316 317 318 319 320 321 322
  if (config.gpu_enabled() && !config.tensorrt_enabled()) {
    auto tensor_map = ::infrt::kernel::phi::LoadCombinedParamsToGpu(
        config.model_dir(), config.param_dir());
    impl_->executor.reset(
        new PredictExecutor(module_op, registry, std::move(tensor_map)));

  } else {
    auto tensor_map = ::infrt::kernel::phi::LoadCombinedParameters(
        config.model_dir(), config.param_dir());
    impl_->executor.reset(
        new PredictExecutor(module_op, registry, std::move(tensor_map)));
  }
Y
Yan Chunwei 已提交
323 324 325 326 327 328

  return 0;
}

int InfRtPredictor::GetInputNum() { return impl_->executor->GetInputNum(); }

329
::phi::DenseTensor* InfRtPredictor::GetInput(int i) {
Y
Yan Chunwei 已提交
330 331 332 333 334
  return impl_->executor->GetInput(i);
}

int InfRtPredictor::GetOutputNum() { return impl_->executor->GetOutputNum(); }

335
::phi::DenseTensor* InfRtPredictor::GetOutput(int i) {
Y
Yan Chunwei 已提交
336 337 338 339
  return impl_->executor->GetOutput(i);
}

}  // namespace infrt