tensorrt_engine_op.cc 5.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 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. */

#ifdef PADDLE_WITH_CUDA

G
gongweibao 已提交
17 18 19
#include <string>
#include <vector>

20 21
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
22
#include "paddle/fluid/inference/tensorrt/engine.h"
23
#include "paddle/fluid/inference/utils/singleton.h"
G
gongweibao 已提交
24
#include "paddle/fluid/operators/tensorrt_engine_op.h"
25 26

namespace paddle {
27 28 29

DEFINE_int32(tensorrt_engine_batch_size, 1, "the batch_size of TensorRT");

30 31
namespace operators {

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
using inference::Singleton;
using inference::tensorrt::TRT_EngineManager;

using FluidDT = framework::proto::VarType_Type;
using TRT_DT = nvinfer1::DataType;

namespace {

TRT_DT FluidDataType2TRT(FluidDT type) {
  switch (type) {
    case FluidDT::VarType_Type_FP32:
      return TRT_DT::kFLOAT;
    case FluidDT::VarType_Type_INT32:
      return TRT_DT::kINT32;
    default:
      return TRT_DT::kINT32;
  }
  PADDLE_THROW("unkown type");
  return TRT_DT::kINT32;
}

nvinfer1::Dims Vec2TRT_Dims(const std::vector<int64_t> &shape) {
  PADDLE_ENFORCE_GT(shape.size(), 1UL,
                    "TensorRT' tensor input requires at least 2 dimensions");
  PADDLE_ENFORCE_LE(shape.size(), 4UL,
                    "TensorRT' tensor input requires at most 4 dimensions");
58 59
  PADDLE_ENFORCE_EQ(shape.size(), 4UL);
  return nvinfer1::DimsCHW(shape[1], shape[2], shape[3]);
60 61 62 63
}

}  // namespace

64
template <typename DeviceContext, typename T>
Y
Yan Chunwei 已提交
65
void TensorRTEngineKernel<DeviceContext, T>::Prepare(
66
    const framework::ExecutionContext &context) const {
67
  VLOG(4) << "Prepare engine";
68
  // Get the ProgramDesc and pass to convert.
69 70
  framework::proto::BlockDesc block_desc;
  block_desc.ParseFromString(context.Attr<std::string>("subgraph"));
Y
Yan Chunwei 已提交
71
  int max_batch = context.Attr<int>("max_batch");
72
  auto max_workspace = context.Attr<int>("max_workspace");
Y
Yan Chunwei 已提交
73 74 75 76 77 78
  auto params = context.Attr<std::vector<std::string>>("parameters");
  std::unordered_set<std::string> parameters;
  for (const auto &param : params) {
    parameters.insert(param);
  }

79 80 81
  std::vector<std::string> output_maps =
      context.Attr<std::vector<std::string>>("output_name_mapping");

Y
Yan Chunwei 已提交
82 83 84 85 86
  // TODO(Superjomn) replace this with a different stream
  auto *engine = Singleton<TRT_EngineManager>::Global().Create(
      max_batch, max_workspace, nullptr /*engine hold its own stream*/,
      context.Attr<std::string>("engine_uniq_key"));
  engine->InitNetwork();
87 88

  framework::BlockDesc block(nullptr /*programdesc*/, &block_desc);
89
  VLOG(4) << "parsed var size " << block.AllVars().size();
90 91 92
  // Add inputs
  VLOG(4) << "declare inputs";
  for (auto &input : context.Inputs("Xs")) {
93
    if (parameters.count(input)) continue;
94 95
    VLOG(4) << "declare input " << input;
    auto *var = block.FindVar(input);
96 97 98
    // TensorRT engine need to create parameters. The parameter's description
    // should be set in
    PADDLE_ENFORCE(var, "no variable called %s", input);
99 100 101
    PADDLE_ENFORCE_EQ(var->GetType(), FluidDT::VarType_Type_LOD_TENSOR,
                      "TensorRT engine only takes LoDTensor as input");
    auto shape = var->GetShape();
102 103 104 105 106 107 108
    // For the special batch_size placeholder -1, drop it and pass the real
    // shape of data.
    // TODO(Superjomn) fix this with batch broadcast, or it can't handle
    // variational batch size.
    if (shape[0] == -1) {
      shape[0] = FLAGS_tensorrt_engine_batch_size;
    }
Y
Yan Chunwei 已提交
109
    engine->DeclareInput(
110 111
        input, FluidDataType2TRT(
                   var->Proto()->type().lod_tensor().tensor().data_type()),
112
        Vec2TRT_Dims(shape));
113 114
  }

115
  inference::Singleton<inference::tensorrt::OpConverter>::Global().ConvertBlock(
Y
Yan Chunwei 已提交
116
      block_desc, parameters, context.scope(), engine);
117 118

  // Add outputs
119
  for (auto &output : output_maps) {
Y
Yan Chunwei 已提交
120
    engine->DeclareOutput(output);
121 122
  }

Y
Yan Chunwei 已提交
123
  engine->FreezeNetwork();
124 125 126 127 128 129 130
}

class TensorRTEngineOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Xs", "A list of inputs.").AsDuplicable();
    AddOutput("Ys", "A list of outputs").AsDuplicable();
131
    AddAttr<std::string>("subgraph", "the subgraph.");
Y
Yan Chunwei 已提交
132
    AddAttr<std::string>("engine_uniq_key", "unique key for the TRT engine.");
133 134
    AddAttr<int>("max_batch", "the maximum batch size.");
    AddAttr<int>("max_workspace", "the maximum batch size.");
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    AddComment("TensorRT engine operator.");
  }
};

class TensorRTEngineInferVarType : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc &op_desc,
                  framework::BlockDesc *block) const override {}
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(tensorrt_engine, ops::TensorRTEngineOp,
                  ops::TensorRTEngineOpMaker, ops::TensorRTEngineOpMaker);

REGISTER_OP_CPU_KERNEL(
    tensorrt_engine,
    ops::TensorRTEngineKernel<paddle::platform::CPUDeviceContext, float>,
    ops::TensorRTEngineKernel<paddle::platform::CPUDeviceContext, double>,
    ops::TensorRTEngineKernel<paddle::platform::CPUDeviceContext, int>,
    ops::TensorRTEngineKernel<paddle::platform::CPUDeviceContext, int64_t>);

#endif  // PADDLE_WITH_CUDA