tensorrt_engine_op.h 12.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* 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. */

#pragma once

#ifdef PADDLE_WITH_CUDA

G
gongweibao 已提交
19
#include <string>
N
nhzlx 已提交
20
#include <unordered_map>
G
gongweibao 已提交
21 22
#include <vector>

N
nhzlx 已提交
23
#include "paddle/fluid/framework/executor.h"
N
nhzlx 已提交
24
#include "paddle/fluid/framework/op_registry.h"
25 26
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/inference/analysis/helper.h"
N
nhzlx 已提交
27
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
28 29 30
#include "paddle/fluid/inference/tensorrt/engine.h"

namespace paddle {
31

32 33
namespace operators {

N
nhzlx 已提交
34 35 36
using FluidDT = framework::proto::VarType_Type;
using TRT_DT = nvinfer1::DataType;

D
dzhwinter 已提交
37
namespace {  // NOLINT
N
nhzlx 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51

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

N
nhzlx 已提交
52
nvinfer1::Dims Vec2TRT_Dims(const std::vector<int64_t> &shape) {
N
nhzlx 已提交
53 54 55 56
  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");
57 58 59 60
  PADDLE_ENFORCE(shape.size() == 4UL || shape.size() == 2UL);
  if (shape.size() == 4UL)
    return nvinfer1::DimsCHW(shape[1], shape[2], shape[3]);
  return nvinfer1::DimsCHW(shape[1], 1, 1);
N
nhzlx 已提交
61 62
}

63
}  // namespace // NOLINT
N
nhzlx 已提交
64

Y
Yan Chunwei 已提交
65
using inference::Singleton;
N
nhzlx 已提交
66
using inference::tensorrt::TensorRTEngine;
N
nhzlx 已提交
67
using inference::tensorrt::TRTInt8Calibrator;
N
nhzlx 已提交
68 69
using inference::tensorrt::TRTCalibratorEngine;
using inference::tensorrt::TRTCalibratorEngineManager;
N
nhzlx 已提交
70 71 72 73 74 75 76 77

class TensorRTEngineOp : public framework::OperatorBase {
 private:
  std::vector<std::string> input_names_;
  std::unordered_set<std::string> param_names_;
  mutable std::unique_ptr<TensorRTEngine> trt_engine_;
  int max_batch_size_;
  int workspace_size_;
N
nhzlx 已提交
78
  std::unique_ptr<TRTInt8Calibrator> calibrator_;
N
nhzlx 已提交
79
  bool enable_int8_;
N
nhzlx 已提交
80 81 82
  std::string calibration_data_;
  std::string engine_key_;
  bool calibration_mode_;
Y
Yan Chunwei 已提交
83

84
 public:
N
nhzlx 已提交
85 86 87 88 89 90 91 92
  TensorRTEngineOp(const std::string &type,
                   const framework::VariableNameMap &inputs,
                   const framework::VariableNameMap &outputs,
                   const framework::AttributeMap &attrs)
      : framework::OperatorBase(type, inputs, outputs, attrs) {
    input_names_ = Inputs("Xs");
    max_batch_size_ = Attr<int>("max_batch_size");
    workspace_size_ = Attr<int>("workspace_size");
N
nhzlx 已提交
93
    enable_int8_ = Attr<bool>("enable_int8");
N
nhzlx 已提交
94 95
    calibration_data_ = Attr<std::string>("calibration_data");
    engine_key_ = Attr<std::string>("engine_key");
N
nhzlx 已提交
96 97 98 99 100

    auto params = Attr<std::vector<std::string>>("parameters");
    for (const auto &param : params) {
      param_names_.insert(param);
    }
N
nhzlx 已提交
101 102 103
    // calibration_mode is ture represents we need to
    // generate the calibration table data.
    calibration_mode_ = (enable_int8_ && calibration_data_.size() == 0);
N
nhzlx 已提交
104

N
nhzlx 已提交
105 106
    VLOG(4) << "calibration_mode: " << calibration_mode_;
    if (enable_int8_ && calibration_data_.size()) {
N
nhzlx 已提交
107 108
      calibrator_.reset(new TRTInt8Calibrator(calibration_data_));
    }
N
nhzlx 已提交
109 110 111 112 113

    // we will create an engine here.
    if (!calibration_mode_) {
      // trt_engine_.reset();
    }
N
nhzlx 已提交
114
  }
115 116

 protected:
N
nhzlx 已提交
117 118
  void RunNativeImpl(const framework::Scope &scope,
                     const platform::Place &dev_place) const {
N
nhzlx 已提交
119 120 121
    framework::Executor executor(dev_place);
    auto *block = Attr<framework::BlockDesc *>("sub_block");
    auto *program = block->Program();
N
nhzlx 已提交
122
    auto &current_scope = scope.NewScope();
N
nhzlx 已提交
123
    auto ctx = executor.Prepare(*program, block->ID());
N
nhzlx 已提交
124
    executor.RunPreparedContext(ctx.get(), &current_scope, false, true, true);
N
nhzlx 已提交
125 126
  }

N
nhzlx 已提交
127 128
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
N
nhzlx 已提交
129 130 131 132
    if (calibration_mode_ == true) {
      RunCalibration(scope, dev_place);
      return;
    }
N
nhzlx 已提交
133 134
    auto trt_engine = GetEngine(scope, dev_place);
    RunTrt(scope, dev_place, trt_engine);
135 136
  }

N
nhzlx 已提交
137 138
  void RunCalibration(const framework::Scope &scope,
                      const platform::Place &dev_place) const {
N
nhzlx 已提交
139 140 141
    // This process will builds a 32-bit trt engine, runs it on the calibration
    // set, and records a histogram for each
    // tensor of the distribution of activation values.
N
nhzlx 已提交
142 143
    LOG_FIRST_N(INFO, 1) << "The TRT engine: " << engine_key_
                         << " is running calibration trt int8... ";
N
nhzlx 已提交
144
    int runtime_batch = 1;
145 146 147 148
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(dev_place);
    auto stream =
        reinterpret_cast<const platform::CUDADeviceContext &>(dev_ctx).stream();
N
nhzlx 已提交
149 150 151
    if (!Singleton<TRTCalibratorEngineManager>::Global().Has(engine_key_)) {
      TRTCalibratorEngine *calib_res =
          Singleton<TRTCalibratorEngineManager>::Global().Create(engine_key_);
N
nhzlx 已提交
152 153 154 155 156 157 158 159 160 161 162 163
      std::unordered_map<std::string, size_t> calib_buffers;
      for (auto &x : input_names_) {
        if (param_names_.count(x)) continue;
        auto &t =
            inference::analysis::GetFromScope<framework::LoDTensor>(scope, x);
        calib_buffers[x] = t.memory_size();
        auto t_shape = framework::vectorize(t.dims());
        runtime_batch = t_shape[0];
      }
      calib_res->calib_.reset(new TRTInt8Calibrator(
          calib_buffers, runtime_batch, engine_key_, dev_place));
      calib_res->thr_.reset(new std::thread([&]() {
N
nhzlx 已提交
164 165 166
        calib_res->engine_.reset(
            new TensorRTEngine(max_batch_size_, workspace_size_, stream,
                               enable_int8_, calib_res->calib_.get()));
N
nhzlx 已提交
167 168 169 170 171 172
        VLOG(3) << "start the calib trt engine thread";
        Prepare(scope, dev_place, calib_res->engine_.get());
      }));
    }

    TRTInt8Calibrator *temp_calibrator =
N
nhzlx 已提交
173
        Singleton<TRTCalibratorEngineManager>::Global()
N
nhzlx 已提交
174 175 176 177 178 179 180 181 182 183 184
            .Get(engine_key_)
            ->calib_.get();
    std::unordered_map<std::string, void *> calib_data;

    for (auto &x : Inputs("Xs")) {
      if (param_names_.count(x)) continue;
      auto &t =
          inference::analysis::GetFromScope<framework::LoDTensor>(scope, x);
      calib_data.emplace(x, t.data<void>());
    }
    temp_calibrator->setBatch(calib_data);
N
nhzlx 已提交
185
    RunNativeImpl(scope, dev_place);
N
nhzlx 已提交
186 187
  }

N
nhzlx 已提交
188 189
  void RunTrt(const framework::Scope &scope, const platform::Place &dev_place,
              TensorRTEngine *engine) const {
N
nhzlx 已提交
190
    int runtime_batch = 1;
N
nhzlx 已提交
191 192 193 194
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(dev_place);
    auto stream =
        reinterpret_cast<const platform::CUDADeviceContext &>(dev_ctx).stream();
N
nhzlx 已提交
195

N
nhzlx 已提交
196
    // auto *engine = trt_engine_.get();
N
nhzlx 已提交
197
    PADDLE_ENFORCE(!input_names_.empty(), "should pass more than one inputs");
198

199
    std::vector<std::string> output_maps =
N
nhzlx 已提交
200
        Attr<std::vector<std::string>>("output_name_mapping");
201

N
nhzlx 已提交
202 203 204 205 206 207 208 209 210 211
    int num_inputs = 0;

    for (const auto &x : Inputs("Xs")) {
      if (param_names_.count(x)) continue;
      num_inputs += 1;
    }
    const int num_bindings = num_inputs + Outputs("Ys").size();
    std::vector<void *> buffers(num_bindings);

    // Bind input tensor to TRT.
N
nhzlx 已提交
212 213
    for (const auto &x : Inputs("Xs")) {
      if (param_names_.count(x)) continue;
214
      // convert input and copy to TRT engine's buffer
N
nhzlx 已提交
215 216 217 218 219
      auto &t =
          inference::analysis::GetFromScope<framework::LoDTensor>(scope, x);
      auto t_shape = framework::vectorize(t.dims());
      runtime_batch = t_shape[0];

N
nhzlx 已提交
220 221 222 223 224
      const int bind_index = engine->engine()->getBindingIndex(x.c_str());
      PADDLE_ENFORCE(bind_index < num_bindings,
                     "The bind index should be less than num_bindings");
      buffers[bind_index] = static_cast<void *>(t.data<float>());
    }
225

N
nhzlx 已提交
226
    // Bind output tensor to TRT.
227
    int output_index = 0;
M
minqiyang 已提交
228
    VLOG(4) << "TensorRT Engine Op Outputs:";
N
nhzlx 已提交
229 230
    for (const auto &y : Outputs("Ys")) {
      nvinfer1::ITensor *trt_t = engine->GetITensor(output_maps[output_index]);
231 232
      auto dims = trt_t->getDimensions();
      // Use the output ITensor's dims to reshape the Fluid Tensor.
233 234
      // The ITensor doesn't contain the batch size dim.
      std::vector<int> ddim;
N
nhzlx 已提交
235
      ddim.push_back(runtime_batch);
236 237 238
      for (int i = 0; i < dims.nbDims; i++) {
        ddim.push_back(dims.d[i]);
      }
N
nhzlx 已提交
239
      auto *fluid_v = scope.FindVar(y);
240
      PADDLE_ENFORCE_NOT_NULL(fluid_v, "no output variable called %s", y);
N
nhzlx 已提交
241
      auto *fluid_t = fluid_v->GetMutable<framework::LoDTensor>();
242
      fluid_t->Resize(framework::make_ddim(ddim));
243

N
nhzlx 已提交
244 245 246 247 248 249 250
      const int bind_index =
          engine->engine()->getBindingIndex(output_maps[output_index].c_str());
      PADDLE_ENFORCE(bind_index < num_bindings,
                     "The bind index should be less than num_bindings");
      buffers[bind_index] = static_cast<void *>(fluid_t->mutable_data<float>(
          boost::get<platform::CUDAPlace>(dev_place)));

251
      output_index += 1;
252
    }
253

N
nhzlx 已提交
254 255 256
    PADDLE_ENFORCE_LE(runtime_batch, max_batch_size_);
    // Execute the engine.
    engine->Execute(runtime_batch, buffers);
N
nhzlx 已提交
257
    cudaStreamSynchronize(stream);
258 259
  }

N
nhzlx 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  TensorRTEngine *GetEngine(const framework::Scope &scope,
                            const platform::Place &dev_place) const {
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(dev_place);
    auto stream =
        reinterpret_cast<const platform::CUDADeviceContext &>(dev_ctx).stream();
    if (trt_engine_.get() == nullptr) {
      trt_engine_.reset(new TensorRTEngine(max_batch_size_, workspace_size_,
                                           stream, enable_int8_,
                                           calibrator_.get()));
      if (true) {
        Prepare(scope, dev_place, trt_engine_.get());
      } else {
        // create static engine
      }
    }
    return trt_engine_.get();
  }

N
nhzlx 已提交
279 280
  void Prepare(const framework::Scope &scope, const platform::Place &dev_place,
               TensorRTEngine *engine) const {
N
nhzlx 已提交
281 282
    LOG(INFO) << "Prepare TRT engine (Optimize model structure, Select OP "
                 "kernel etc). This process may cost a lot of time.";
N
nhzlx 已提交
283
    framework::proto::BlockDesc block_desc;
N
nhzlx 已提交
284
    block_desc.ParseFromString(Attr<std::string>("subgraph"));
N
nhzlx 已提交
285 286

    std::vector<std::string> output_maps =
N
nhzlx 已提交
287
        Attr<std::vector<std::string>>("output_name_mapping");
N
nhzlx 已提交
288 289 290 291

    engine->InitNetwork();

    framework::BlockDesc block(nullptr /*programdesc*/, &block_desc);
M
minqiyang 已提交
292
    VLOG(4) << "parsed var size " << block.AllVars().size();
N
nhzlx 已提交
293
    // Add inputs
M
minqiyang 已提交
294
    VLOG(4) << "declare inputs";
N
nhzlx 已提交
295 296
    for (auto &input : Inputs("Xs")) {
      if (param_names_.count(input)) continue;
M
minqiyang 已提交
297
      VLOG(4) << "declare input " << input;
N
nhzlx 已提交
298 299 300 301 302 303

      auto &t =
          inference::analysis::GetFromScope<framework::LoDTensor>(scope, input);
      auto t_shape = framework::vectorize(t.dims());

      auto *var = block.FindVar(input);
N
nhzlx 已提交
304 305 306 307 308
      // TensorRT engine need to create parameters. The parameter's description
      // should be set in
      PADDLE_ENFORCE(var, "no variable called %s", input);
      PADDLE_ENFORCE_EQ(var->GetType(), FluidDT::VarType_Type_LOD_TENSOR,
                        "TensorRT engine only takes LoDTensor as input");
N
nhzlx 已提交
309

N
nhzlx 已提交
310 311 312
      engine->DeclareInput(
          input, FluidDataType2TRT(
                     var->Proto()->type().lod_tensor().tensor().data_type()),
N
nhzlx 已提交
313
          Vec2TRT_Dims(t_shape));
N
nhzlx 已提交
314 315
    }
    inference::Singleton<inference::tensorrt::OpConverter>::Global()
N
nhzlx 已提交
316
        .ConvertBlock(block_desc, param_names_, scope, engine);
N
nhzlx 已提交
317 318

    // Add outputs
N
nhzlx 已提交
319 320
    for (auto &output : output_maps) {
      engine->DeclareOutput(output);
N
nhzlx 已提交
321 322 323
    }
    engine->FreezeNetwork();
  }
324 325 326 327 328 329
};

}  // namespace operators
}  // namespace paddle

#endif  // PADDLE_WITH_CUDA