engine.cc 33.7 KB
Newer Older
Y
Yan Chunwei 已提交
1 2
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

N
nhzlx 已提交
3 4
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License.
Y
Yan Chunwei 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18
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/inference/tensorrt/engine.h"

#include <NvInfer.h>
#include <glog/logging.h>
19

A
Abhinav Arora 已提交
20
#include <string>
W
wanghuancoder 已提交
21

22
#include "NvInferRuntimeCommon.h"
23
#include "cuda_runtime_api.h"  // NOLINT
24

Y
Yan Chunwei 已提交
25
#include "paddle/fluid/inference/tensorrt/helper.h"
26
#include "paddle/fluid/inference/tensorrt/trt_int8_calibrator.h"
27
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
Y
Yan Chunwei 已提交
28 29 30 31 32

namespace paddle {
namespace inference {
namespace tensorrt {

33 34
thread_local int TensorRTEngine::predictor_id_per_thread = -1;

35
void TensorRTEngine::Weight::SetDataType(phi::DataType type) {
36
  nvinfer1::DataType nv_type = nvinfer1::DataType::kFLOAT;
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
  switch (type) {
    case phi::DataType::FLOAT32:
      nv_type = nvinfer1::DataType::kFLOAT;
      break;
    case phi::DataType::FLOAT16:
      nv_type = nvinfer1::DataType::kHALF;
      break;
    case phi::DataType::INT32:
      nv_type = nvinfer1::DataType::kINT32;
      break;
    case phi::DataType::INT8:
      nv_type = nvinfer1::DataType::kINT8;
      break;
#if IS_TRT_VERSION_GE(7000)
    case phi::DataType::BOOL:
      nv_type = nvinfer1::DataType::kBOOL;
      break;
#endif
    default:
      paddle::platform::errors::InvalidArgument(
          "Paddle-TRT loads weighths failed, found not supported data type %s.",
          type);
      break;
  }
  w_.type = nv_type;
}

64
void TensorRTEngine::InitNetwork() {
65
  FreshDeviceId();
66 67
  infer_builder_.reset(createInferBuilder(&logger_));

68
  if (with_dynamic_shape()) {
69
    infer_network_.reset(infer_builder_->createNetworkV2(
70 71 72
        1U << static_cast<int>(
            nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));
  } else {
73
    infer_network_.reset(infer_builder_->createNetworkV2(0U));
74
  }
75 76

  infer_builder_config_.reset(infer_builder_->createBuilderConfig());
W
wenbin 已提交
77 78 79
  optim_profiles_.resize(max_profile_num_);
  for (int i = 0; i < max_profile_num_; i++)
    optim_profiles_[i] = infer_builder_->createOptimizationProfile();
Y
Yan Chunwei 已提交
80 81
}

82 83 84 85 86 87 88 89 90 91 92
nvinfer1::IExecutionContext *TensorRTEngine::context() {
  std::unique_lock<std::mutex> lock(mutex_);
  if (infer_context_.find(predictor_id_per_thread) == infer_context_.end()) {
    PADDLE_ENFORCE_NOT_NULL(
        infer_engine_,
        platform::errors::InvalidArgument(
            "You should build engine first and then set the context."));
    // We may see trt warning: Profile 0 has been chosen by another
    // IExecutionContext...
    // It's ok. We will set it later.
    nvinfer1::IExecutionContext *infer_context{nullptr};
93
    if (params_.context_memory_sharing) {
94 95 96 97 98 99 100 101 102
      infer_context =
          infer_engine_->createExecutionContextWithoutDeviceMemory();
    } else {
      infer_context = infer_engine_->createExecutionContext();
    }
    PADDLE_ENFORCE_NOT_NULL(
        infer_context,
        platform::errors::InvalidArgument(
            "TensorRT engine can not build execution context."));
103
    if (with_dynamic_shape()) {
104 105 106 107 108 109 110 111 112 113 114 115
      // need new profile if it's not the first
      if (cur_profile_num_ > 0) {
        infer_context->setOptimizationProfile(cur_profile_num_);
      }
      profile_index_[predictor_id_per_thread] = cur_profile_num_;
      ++cur_profile_num_;
    }
    infer_context_[predictor_id_per_thread].reset(infer_context);
  }
  return infer_context_[predictor_id_per_thread].get();
}

116 117
void TensorRTEngine::Execute(int batch_size,
                             std::vector<void *> *buffers,
118
                             cudaStream_t stream) {
119
  FreshDeviceId();
120
  auto infer_context = context();
121
  if (params_.context_memory_sharing) {
122 123 124
    void *context_memory{nullptr};
    context_memory =
        inference::Singleton<inference::tensorrt::TRTEngineManager>::Global()
125
            .GetContextMemory(
126
                predictor_id_per_thread,
127
                phi::GPUPlace(device_id()),
128 129 130
                phi::Stream(reinterpret_cast<phi::StreamId>(stream)));
    infer_context->setDeviceMemory(context_memory);
  }
W
Wilber 已提交
131 132 133 134 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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

  // TODO(wilber): Is cudaGraph has conflict with memory sharing?
  if (startup_with_cudagraph_ && !cudagraph_inited_) {
    // Avoid capturing initialization calls by executing the enqueue function at
    // least once before starting CUDA graph capture.
    const auto ret = Enqueue(infer_context, buffers, batch_size, stream);
    PADDLE_ENFORCE_EQ(
        ret,
        true,
        phi::errors::PreconditionNotMet("Trt CudaGraph test run failed."));
    cudaStreamSynchronize(stream);

    cuda_graph_.BeginCapture(stream);
    // The built TRT engine may contain operations that are not permitted under
    // CUDA graph capture mode. When the stream is capturing, the call may
    // return false if the current CUDA graph capture fails.
    if (Enqueue(infer_context, buffers, batch_size, stream)) {
      cuda_graph_.EndCapture(stream);
      cudagraph_inited_ = true;
    } else {
      cuda_graph_.EndCaptureOnError(stream);
      // Ensure any CUDA error has been cleaned up.
      PADDLE_ENFORCE_GPU_SUCCESS(cudaGetLastError());
      LOG(WARNING) << "The built TensorRT engine contains operations that are "
                      "not permitted under "
                      "CUDA graph capture mode. The specified UseCudaGraph "
                      "flag has been ignored. The inference will be "
                      "launched without using CUDA graph launch.";
      cudagraph_inited_ = false;
    }
    startup_with_cudagraph_ = false;
  }

  Enqueue(infer_context, buffers, batch_size, stream);
}

bool TensorRTEngine::Enqueue(nvinfer1::IExecutionContext *context,
                             std::vector<void *> *buffers,
                             int batch_size,
                             cudaStream_t stream) {
  if (cudagraph_inited_) {
    VLOG(1) << "cuda_graph init success, so we will use cuda graph launch the "
               "entire graph.";
    return cuda_graph_.Launch(stream);
  }

  bool ret;
178
  if (!with_dynamic_shape()) {
W
Wilber 已提交
179
    ret = context->enqueue(batch_size, buffers->data(), stream, nullptr);
180
  } else {
W
Wilber 已提交
181
    ret = context->enqueueV2(buffers->data(), stream, nullptr);
182
  }
W
Wilber 已提交
183
  return ret;
N
nhzlx 已提交
184 185
}

Y
Yan Chunwei 已提交
186
void TensorRTEngine::FreezeNetwork() {
187
  FreshDeviceId();
188
  VLOG(3) << "TRT to freeze network";
189 190 191 192 193 194 195
  PADDLE_ENFORCE_NOT_NULL(infer_builder_,
                          platform::errors::InvalidArgument(
                              "Inference builder of TRT is null. Please make "
                              "sure you call InitNetwork first."));
  PADDLE_ENFORCE_NOT_NULL(network(),
                          platform::errors::InvalidArgument(
                              "Call InitNetwork first to initialize network."));
Y
Yan Chunwei 已提交
196
  // build engine.
197 198
  if (!with_dynamic_shape()) {
    infer_builder_->setMaxBatchSize(params_.max_batch_size);
199
  }
200 201
#if IS_TRT_VERSION_GE(8300)
  infer_builder_config_->setMemoryPoolLimit(
202
      nvinfer1::MemoryPoolType::kWORKSPACE, params_.max_workspace_size);
203
#else
204
  infer_builder_config_->setMaxWorkspaceSize(params_.max_workspace_size);
205
#endif
206

207
  bool enable_fp16 = (precision() == phi::DataType::FLOAT16);
Z
Zhaolong Xing 已提交
208 209
  if (enable_fp16) {
    bool support_fp16 = infer_builder_->platformHasFastFp16();
210
    infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);
Z
Zhaolong Xing 已提交
211 212 213
    if (!support_fp16) {
      LOG(INFO) << "You specify FP16 mode, but the hardware do not support "
                   "FP16 speed up, use FP32 instead.";
214 215
    } else {
      LOG(INFO) << "Run Paddle-TRT FP16 mode";
Z
Zhaolong Xing 已提交
216 217 218
    }
  }

219
  bool enable_int8 = (precision() == phi::DataType::INT8);
Z
Zhaolong Xing 已提交
220
  if (enable_int8) {
221
    if (!use_dla()) {
C
csy0225 已提交
222 223
      infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);
    }
224 225
    infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kINT8);

226 227
    if (params_.calibrator) {
      infer_builder_config_->setInt8Calibrator(params_.calibrator);
228
    } else {
229
      infer_builder_config_->setInt8Calibrator(nullptr);
230 231 232 233 234 235 236 237

      for (auto &quant_range : quant_dynamic_range_) {
        auto tensor = quant_range.first;
        float range = quant_range.second;
        tensor->setDynamicRange(-range, range);
      }

      std::unordered_set<nvinfer1::ITensor *> all_t;
238 239
      for (int i = 0; i < network()->getNbLayers(); i++) {
        auto layer = network()->getLayer(i);
240 241 242 243
        for (int j = 0; j < layer->getNbOutputs(); j++) {
          all_t.insert(layer->getOutput(j));
        }
      }
244

245 246
      for (int i = 0; i < network()->getNbInputs(); i++) {
        all_t.insert(network()->getInput(i));
247 248 249 250
      }

      for (auto &t : all_t) {
        if (!quant_dynamic_range_.count(t)) {
T
tianshuo78520a 已提交
251 252 253
          VLOG(3) << "We are in trt int8 mode(not calibration), scale not set"
                  << " for tensor " << t->getName()
                  << ", this might be ok when trt does not need this range";
254 255 256
        }
      }
    }
N
nhzlx 已提交
257
  }
Y
Yan Chunwei 已提交
258

259
  if (use_dla()) {
260 261 262 263 264 265 266 267
    if (!enable_int8 && !enable_fp16) {
      LOG(WARNING) << "TensorRT DLA must be used with int8 or fp16, but you "
                      "set float32, so DLA is not used.";
    } else if (infer_builder_->getNbDLACores() == 0) {
      LOG(WARNING)
          << "TensorRT DLA is set by config, but your device does not have "
             "DLA, so DLA is not used.";
    } else {
268 269 270
      if (params_.dla_core < 0 ||
          params_.dla_core >= infer_builder_->getNbDLACores()) {
        params_.dla_core = 0;
271 272
        LOG(WARNING) << "Invalid DLACore, must be 0 < DLACore < "
                     << infer_builder_->getNbDLACores() << ", but got "
273
                     << params_.dla_core << ", so use use 0 as default.";
274
      }
275
      infer_builder_config_->setDefaultDeviceType(nvinfer1::DeviceType::kDLA);
276
      infer_builder_config_->setDLACore(params_.dla_core);
277
      infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kGPU_FALLBACK);
278
      LOG(INFO) << "TensorRT DLA enabled in FreezeNetwork(), DLACore "
279
                << params_.dla_core;
280 281 282
    }
  }

283
  if (with_dynamic_shape()) {
284
    LOG(INFO) << "Run Paddle-TRT Dynamic Shape mode.";
W
wenbin 已提交
285
    for (int i = 0; i < max_profile_num_; i++) {
286
      for (auto &input : min_input_shape()) {
287 288
#if IS_TRT_VERSION_LT(7100)
        // trt6/trt7011 will check all_of input > 0
289 290
        if (!(std::all_of(input.second.begin(),
                          input.second.end(),
W
wenbin 已提交
291
                          [](int x) { return x > 0; }) &&
292 293
              std::all_of(max_input_shape()[input.first].begin(),
                          max_input_shape()[input.first].end(),
W
wenbin 已提交
294
                          [](int x) { return x > 0; }) &&
295 296
              std::all_of(optim_input_shape()[input.first].begin(),
                          optim_input_shape()[input.first].end(),
W
wenbin 已提交
297 298 299
                          [](int x) { return x > 0; }))) {
          continue;
        }
300
#endif
W
wenbin 已提交
301 302
        VLOG(4) << "TRT dynamic_shape set " << input.first
                << " min: " << Vec2Str(input.second)
303 304
                << ", max: " << Vec2Str(max_input_shape()[input.first])
                << ", opt: " << Vec2Str(optim_input_shape()[input.first]);
W
wenbin 已提交
305 306

        optim_profiles_[i]->setDimensions(
307 308
            input.first.c_str(),
            nvinfer1::OptProfileSelector::kMIN,
W
wenbin 已提交
309 310
            Vec2TRT_Dims(input.second, input.first, true));
        optim_profiles_[i]->setDimensions(
311 312
            input.first.c_str(),
            nvinfer1::OptProfileSelector::kMAX,
313
            Vec2TRT_Dims(max_input_shape()[input.first], input.first, true));
W
wenbin 已提交
314
        optim_profiles_[i]->setDimensions(
315 316
            input.first.c_str(),
            nvinfer1::OptProfileSelector::kOPT,
317
            Vec2TRT_Dims(optim_input_shape()[input.first], input.first, true));
W
wenbin 已提交
318
      }
319 320 321 322 323

      for (int input_id = 0; input_id < network()->getNbInputs(); input_id++) {
        auto input_name = network()->getInput(input_id)->getName();
        if (!itensor_map_.count(input_name)) continue;
        if (!GetITensor(input_name)->isShapeTensor()) continue;
324 325 326
        PADDLE_ENFORCE_EQ(min_shape_tensor().count(input_name) > 0 &&
                              max_shape_tensor().count(input_name) > 0 &&
                              optim_shape_tensor().count(input_name) > 0,
327 328 329 330 331
                          true,
                          platform::errors::InvalidArgument(
                              "Fail to find min/max/optim shape value for TRT "
                              "network's shape tensor input named %s.",
                              input_name));
332
        auto min_vec = min_shape_tensor().at(input_name);
333 334 335 336
        optim_profiles_[i]->setShapeValues(input_name,
                                           nvinfer1::OptProfileSelector::kMIN,
                                           min_vec.data(),
                                           min_vec.size());
337 338 339 340 341
        optim_profiles_[i]->setShapeValues(
            input_name,
            nvinfer1::OptProfileSelector::kMAX,
            max_shape_tensor()[input_name].data(),
            min_vec.size());
342 343 344
        optim_profiles_[i]->setShapeValues(
            input_name,
            nvinfer1::OptProfileSelector::kOPT,
345
            optim_shape_tensor()[input_name].data(),
346 347 348
            min_vec.size());
      }

W
wenbin 已提交
349
      infer_builder_config_->addOptimizationProfile(optim_profiles_[i]);
350
    }
351 352 353 354 355 356
    if (WithFp16() && disable_trt_plugin_fp16()) {
      LOG(INFO) << "NOTE: In order to achieve higher accuracy, you have "
                   "disabled the fp16 mode of TRT Plugin,\n"
                << "you can reopen it with "
                   "'config.SetDynamicShapeInfo(min_shape, max_shape, "
                   "opt_shape, false /*disable_trt_plugin_fp16*/)'";
357
    }
358
  }
359
#if IS_TRT_VERSION_GE(8200)
360
  if (params_.use_inspector) {
361 362 363
    infer_builder_config_->setProfilingVerbosity(
        nvinfer1::ProfilingVerbosity::kDETAILED);
  }
364 365
#endif

366
#if IS_TRT_VERSION_LT(8000)
367 368
  infer_engine_.reset(infer_builder_->buildEngineWithConfig(
      *network(), *infer_builder_config_));
369
#else
Z
zlsh80826 已提交
370
  ihost_memory_.reset(infer_builder_->buildSerializedNetwork(
371
      *network(), *infer_builder_config_));
372 373 374
  infer_runtime_.reset(createInferRuntime(&logger_));
  infer_engine_.reset(infer_runtime_->deserializeCudaEngine(
      ihost_memory_->data(), ihost_memory_->size()));
375
#endif
376

377
  PADDLE_ENFORCE_NOT_NULL(
378 379 380 381
      infer_engine_,
      platform::errors::Fatal(
          "Build TensorRT cuda engine failed! Please recheck "
          "you configurations related to paddle-TensorRT."));
382

W
wenbin 已提交
383 384 385 386 387 388
  binding_num_ = infer_engine_->getNbBindings();
  // reset status for dynamic shape clone
  if (max_profile_num_ > 1) {
    infer_context_.clear();
    cur_profile_num_ = 0;
  }
389
  // for engine context memory sharing
390
  if (params_.context_memory_sharing) {
391
    inference::Singleton<inference::tensorrt::TRTEngineManager>::Global()
392
        .UpdateContextMemorySize(infer_engine_->getDeviceMemorySize(),
393 394
                                 predictor_id_per_thread);
  }
395
  if (params_.use_inspector) {
396 397
    GetEngineInfo();
  }
Y
Yan Chunwei 已提交
398 399
}

400
nvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,
Y
Yan Chunwei 已提交
401
                                                nvinfer1::DataType dtype,
402
                                                const nvinfer1::Dims &dims) {
403 404
  PADDLE_ENFORCE_EQ(network() != nullptr,
                    true,
405 406 407
                    platform::errors::InvalidArgument(
                        "The TRT network should be initialized first."));
  auto *input = network()->addInput(name.c_str(), dtype, dims);
408
  PADDLE_ENFORCE_NOT_NULL(
409 410 411 412 413 414 415
      input,
      platform::errors::InvalidArgument("Adding input %s failed in "
                                        "TensorRT inference network. "
                                        "Please recheck your input.",
                                        name));
  PADDLE_ENFORCE_EQ(input->isNetworkInput(),
                    true,
416 417 418 419
                    platform::errors::InvalidArgument(
                        "Input %s is not the input of TRT inference network. "
                        "Please recheck your input.",
                        name));
L
Luo Tao 已提交
420
  TensorRTEngine::SetITensor(name, input);
Y
Yan Chunwei 已提交
421 422 423
  return input;
}

424 425
void TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer,
                                   int offset,
426 427
                                   const std::string &name) {
  auto *output = layer->getOutput(offset);
428
  SetITensor(name, output);
429
  PADDLE_ENFORCE_NOT_NULL(
430 431 432
      output,
      platform::errors::InvalidArgument(
          "The output %s of TRT engine should not be null.", name));
Y
Yan Chunwei 已提交
433
  output->setName(name.c_str());
434 435
  PADDLE_ENFORCE_EQ(output->isNetworkInput(),
                    false,
436 437 438 439
                    platform::errors::InvalidArgument(
                        "The output %s of TRT engine should not be the input "
                        "of the network at the same time.",
                        name));
440
  network()->markOutput(*output);
441
  PADDLE_ENFORCE_EQ(
442 443
      output->isNetworkOutput(),
      true,
444 445 446
      platform::errors::InvalidArgument(
          "The output %s of TRT engine should be the output of the network.",
          name));
N
nhzlx 已提交
447 448
}

449 450
void TensorRTEngine::DeclareOutput(const std::string &name) {
  auto *output = TensorRTEngine::GetITensor(name);
451
  PADDLE_ENFORCE_NOT_NULL(
452 453 454
      output,
      platform::errors::InvalidArgument(
          "The output %s of TRT engine should not be null.", name));
L
Luo Tao 已提交
455
  output->setName(name.c_str());
456 457
  PADDLE_ENFORCE_EQ(output->isNetworkInput(),
                    false,
458 459 460 461
                    platform::errors::InvalidArgument(
                        "The output %s of TRT engine should not be the input "
                        "of the network at the same time.",
                        name));
462
  network()->markOutput(*output);
L
Luo Tao 已提交
463
}
464 465 466 467 468 469 470 471

void TensorRTEngine::DeclareOutput(const std::string &name,
                                   nvinfer1::DataType dtype) {
  auto *output = TensorRTEngine::GetITensor(name);
  DeclareOutput(name);
  output->setType(dtype);
}

472 473 474 475 476 477 478 479 480 481 482 483 484
void TensorRTEngine::DeleteITensor(const std::string &name,
                                   nvinfer1::ITensor *tensor) {
  PADDLE_ENFORCE_NOT_NULL(
      tensor,
      platform::errors::InvalidArgument(
          "Tensor named %s of TRT engine should not be null.", name));
  PADDLE_ENFORCE_EQ(
      true,
      itensor_map_.count(name),
      platform::errors::InvalidArgument(
          "Tensor named %s of TRT engine should not be null", name));
  itensor_map_.erase(name);
}
L
Luo Tao 已提交
485

486 487
void TensorRTEngine::SetITensor(const std::string &name,
                                nvinfer1::ITensor *tensor) {
488
  PADDLE_ENFORCE_NOT_NULL(
489 490 491
      tensor,
      platform::errors::InvalidArgument(
          "Tensor named %s of TRT engine should not be null.", name));
492
  PADDLE_ENFORCE_EQ(
493 494
      0,
      itensor_map_.count(name),
495 496
      platform::errors::InvalidArgument(
          "Tensor named %s of TRT engine should not be duplicated", name));
L
Luo Tao 已提交
497 498 499
  itensor_map_[name] = tensor;
}

500 501 502 503 504
nvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name,
                                              bool scalar) {
  if (scalar) {
    return ConvertWeight2ITensor(name, true);
  }
505 506 507 508 509 510 511 512 513 514 515
  if (itensor_map_.count(name)) {
    return itensor_map_[name];
  } else {
    ConvertWeight2ITensor(name);
    return itensor_map_[name];
  }
}

// For cases when input is not middle-tensor , but persistable tensor
// you should call this.
nvinfer1::ITensor *TensorRTEngine::ConvertWeight2ITensor(
516
    const std::string &name, bool scalar) {
517 518 519 520 521 522 523
  auto *var_v = scope_->FindVar(name);
  PADDLE_ENFORCE_NOT_NULL(
      var_v,
      platform::errors::NotFound("You are converting a persistable weight to a "
                                 "tensor, but there is no "
                                 "persistable variable called %s in scope.",
                                 name));
524
  auto *var_t = var_v->GetMutable<phi::DenseTensor>();
525 526 527 528 529 530 531 532 533
  auto weight = this->GetTrtWeight(name, *var_t);

  // Now we have create weights, then we need create a itensor
  auto var_dims = var_t->dims();
  nvinfer1::Dims trt_in_shape;
  trt_in_shape.nbDims = var_t->dims().size();
  for (int64_t i = 0; i < trt_in_shape.nbDims; i++) {
    trt_in_shape.d[i] = var_dims[i];
  }
534 535 536 537 538
  // Make 0-D tensor to 1-D tensor.
  if (trt_in_shape.nbDims == 0) {
    trt_in_shape.nbDims = 1;
    trt_in_shape.d[0] = 1;
  }
539 540
  // In fact , this is not always right, because we can't determine if the 0th
  // dimension is batch. Just for run chenqu's model
541
  if (!with_dynamic_shape()) {
542 543 544 545 546
    trt_in_shape.nbDims--;
    for (int i = 0; i < trt_in_shape.nbDims; i++) {
      trt_in_shape.d[i] = trt_in_shape.d[i + 1];
    }
  }
547 548 549 550
  if (scalar) {
    trt_in_shape.nbDims = 0;
    trt_in_shape.d[0] = var_dims[0];
  }
551 552
  nvinfer1::ILayer *layer =
      TRT_ENGINE_ADD_LAYER(this, Constant, trt_in_shape, weight.get());
553 554 555
  if (!scalar) {
    this->SetITensor(name, layer->getOutput(0));
  }
556
  return layer->getOutput(0);
L
Luo Tao 已提交
557 558
}

559 560 561 562 563
std::unordered_map<std::string, nvinfer1::ITensor *>
    *TensorRTEngine::GetITensorMap() {
  return &itensor_map_;
}

564
void TensorRTEngine::Deserialize(const std::string &engine_serialized_data) {
565
  FreshDeviceId();
566
  infer_runtime_.reset(createInferRuntime(&logger_));
567

568 569 570
  if (use_dla()) {
    if (precision() != phi::DataType::INT8 &&
        precision() != phi::DataType::FLOAT16) {
571 572
      LOG(WARNING) << "TensorRT DLA must be used with int8 or fp16, but you "
                      "set float32, so DLA is not used.";
573
    } else if (infer_runtime_->getNbDLACores() == 0) {
574 575 576 577
      LOG(WARNING)
          << "TensorRT DLA is set by config, but your device does not have "
             "DLA, so DLA is not used.";
    } else {
578 579 580
      if (params_.dla_core < 0 ||
          params_.dla_core >= infer_runtime_->getNbDLACores()) {
        params_.dla_core = 0;
581
        LOG(WARNING) << "Invalid DLACore, must be 0 < DLACore < "
582
                     << infer_runtime_->getNbDLACores() << ", but got "
583
                     << params_.dla_core << ", so use use 0 as default.";
584
      }
585
      infer_runtime_->setDLACore(params_.dla_core);
586
      LOG(INFO) << "TensorRT DLA enabled in Deserialize(), DLACore "
587
                << params_.dla_core;
588 589 590
    }
  }

591
  infer_engine_.reset(infer_runtime_->deserializeCudaEngine(
592 593 594 595 596 597 598 599 600 601 602 603 604
      engine_serialized_data.c_str(), engine_serialized_data.size()));

  PADDLE_ENFORCE_NOT_NULL(
      infer_engine_,
      platform::errors::Fatal(
          "Building TRT cuda engine failed when deserializing engine info. "
          "Please check:\n1. Your TRT serialization is generated and loaded "
          "on the same GPU architecture;\n2. The Paddle Inference version of "
          "generating serialization file and doing inference are "
          "consistent."));

  binding_num_ = infer_engine_->getNbBindings();
  // for engine context memory sharing
605
  if (params_.context_memory_sharing) {
606
    inference::Singleton<inference::tensorrt::TRTEngineManager>::Global()
607
        .UpdateContextMemorySize(infer_engine_->getDeviceMemorySize(),
608 609
                                 predictor_id_per_thread);
  }
610
  if (params_.use_inspector) {
611 612
    GetEngineInfo();
  }
613 614
}

615 616
// Note: Only for support plugin.
TensorRTEngine::Weight TensorRTEngine::GetFp16TrtWeight(
617
    const std::string &name, const phi::DenseTensor &weight_tensor) {
618 619 620 621 622 623 624 625 626 627 628
  static int name_suffix_counter = 0;
  std::string name_suffix = std::to_string(name_suffix_counter);
  std::string splitter = "__";
  std::string name_with_suffix = name + splitter + name_suffix;
  platform::CPUPlace cpu_place;
  PADDLE_ENFORCE_EQ(weight_map.count(name_with_suffix),
                    0,
                    platform::errors::AlreadyExists(
                        "The weight named %s is set into the weight map "
                        "twice in TRT OP converter.",
                        name_with_suffix));
629
  weight_map[name_with_suffix].reset(new phi::DenseTensor());
630 631 632 633 634
  weight_map[name_with_suffix]->Resize(weight_tensor.dims());

  TensorRTEngine::Weight weight;
  weight.SetCount(weight_tensor.numel());

Y
Yuanle Liu 已提交
635
  // if trt not support dtype, we need to cast to fp16.
636
  if (weight_tensor.dtype() == phi::DataType::BFLOAT16) {
637
    phi::DenseTensor bf16_tensor;
638 639 640
    bf16_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &bf16_tensor);
641
    weight_map[name_with_suffix]->set_type(phi::DataType::FLOAT16);
642 643 644 645 646 647
    auto *fp16_data = weight_map[name_with_suffix]->mutable_data<float16>(
        platform::CPUPlace());
    auto *bf16_data = bf16_tensor.mutable_data<bfloat16>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      fp16_data[i] = static_cast<float16>(bf16_data[i]);
    }
Y
Yuanle Liu 已提交
648 649
    weight.SetDataType(phi::DataType::FLOAT16);
    weight.SetValues(fp16_data);
650
  } else if (weight_tensor.dtype() == phi::DataType::FLOAT32) {
651
    phi::DenseTensor fp32_tensor;
652 653 654
    fp32_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &fp32_tensor);
655
    weight_map[name_with_suffix]->set_type(phi::DataType::FLOAT16);
656 657 658 659 660 661
    auto *fp16_data = weight_map[name_with_suffix]->mutable_data<float16>(
        platform::CPUPlace());
    auto *fp32_data = fp32_tensor.mutable_data<float>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      fp16_data[i] = static_cast<float16>(fp32_data[i]);
    }
Y
Yuanle Liu 已提交
662 663 664 665 666 667 668
    weight.SetDataType(phi::DataType::FLOAT16);
    weight.SetValues(fp16_data);
  } else if (weight_tensor.dtype() == phi::DataType::INT64) {
    phi::DenseTensor int64_tensor;
    int64_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &int64_tensor);
669
    weight_map[name_with_suffix]->set_type(phi::DataType::INT32);
Y
Yuanle Liu 已提交
670 671 672 673 674 675 676 677
    auto *int32_data = weight_map[name_with_suffix]->mutable_data<int32_t>(
        platform::CPUPlace());
    auto *int64_data = int64_tensor.mutable_data<int64_t>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      int32_data[i] = int64_data[i];
    }
    weight.SetDataType(phi::DataType::INT32);
    weight.SetValues(int32_data);
678 679 680
  } else {
    paddle::framework::TensorCopySync(
        weight_tensor, cpu_place, weight_map[name_with_suffix].get());
Y
Yuanle Liu 已提交
681 682
    weight.SetDataType(weight_tensor.dtype());
    weight.SetValues(weight_map[name_with_suffix]->data());
683 684 685 686 687 688
  }
  name_suffix_counter += 1;
  return weight;
}

// Note: Only for support plugin.
689
TensorRTEngine::Weight TensorRTEngine::GetFp32TrtWeight(
690
    const std::string &name, const phi::DenseTensor &weight_tensor) {
691 692 693 694
  static int name_suffix_counter = 0;
  std::string name_suffix = std::to_string(name_suffix_counter);
  std::string splitter = "__";
  std::string name_with_suffix = name + splitter + name_suffix;
695
  platform::CPUPlace cpu_place;
696 697 698 699 700 701
  PADDLE_ENFORCE_EQ(weight_map.count(name_with_suffix),
                    0,
                    platform::errors::AlreadyExists(
                        "The weight named %s is set into the weight map "
                        "twice in TRT OP converter.",
                        name_with_suffix));
702
  weight_map[name_with_suffix].reset(new phi::DenseTensor());
703 704 705 706 707
  weight_map[name_with_suffix]->Resize(weight_tensor.dims());

  TensorRTEngine::Weight weight;
  weight.SetCount(weight_tensor.numel());

Y
Yuanle Liu 已提交
708
  // if trt not support dtype, we need to cast to fp32.
709
  if (weight_tensor.dtype() == phi::DataType::BFLOAT16) {
710
    phi::DenseTensor bf16_tensor;
711 712 713
    bf16_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &bf16_tensor);
714
    weight_map[name_with_suffix]->set_type(phi::DataType::FLOAT32);
715 716 717 718 719 720
    auto *fp32_data =
        weight_map[name_with_suffix]->mutable_data<float>(platform::CPUPlace());
    auto *bf16_data = bf16_tensor.mutable_data<bfloat16>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      fp32_data[i] = static_cast<float>(bf16_data[i]);
    }
Y
Yuanle Liu 已提交
721 722
    weight.SetDataType(phi::DataType::FLOAT32);
    weight.SetValues(fp32_data);
723
  } else if (weight_tensor.dtype() == phi::DataType::FLOAT16) {
724
    phi::DenseTensor fp16_tensor;
725 726 727
    fp16_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &fp16_tensor);
728
    weight_map[name_with_suffix]->set_type(phi::DataType::FLOAT32);
729 730 731 732 733 734
    auto *fp32_data =
        weight_map[name_with_suffix]->mutable_data<float>(platform::CPUPlace());
    auto *fp16_data = fp16_tensor.mutable_data<float16>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      fp32_data[i] = static_cast<float>(fp16_data[i]);
    }
Y
Yuanle Liu 已提交
735 736 737 738 739 740 741
    weight.SetDataType(phi::DataType::FLOAT32);
    weight.SetValues(fp32_data);
  } else if (weight_tensor.dtype() == phi::DataType::INT64) {
    phi::DenseTensor int64_tensor;
    int64_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &int64_tensor);
742
    weight_map[name_with_suffix]->set_type(phi::DataType::INT32);
Y
Yuanle Liu 已提交
743 744 745 746 747 748 749 750
    auto *int32_data = weight_map[name_with_suffix]->mutable_data<int32_t>(
        platform::CPUPlace());
    auto *int64_data = int64_tensor.mutable_data<int64_t>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      int32_data[i] = int64_data[i];
    }
    weight.SetDataType(phi::DataType::INT32);
    weight.SetValues(int32_data);
751 752 753
  } else {
    paddle::framework::TensorCopySync(
        weight_tensor, cpu_place, weight_map[name_with_suffix].get());
Y
Yuanle Liu 已提交
754 755
    weight.SetDataType(weight_tensor.dtype());
    weight.SetValues(weight_map[name_with_suffix]->data());
756 757 758
  }
  name_suffix_counter += 1;
  return weight;
759 760
}

761
TensorRTEngine::Weight TensorRTEngine::GetTrtWeight(
762
    const std::string &name, const phi::DenseTensor &weight_tensor) {
763 764 765 766 767 768 769 770 771 772 773 774
  static int name_suffix_counter = 0;
  std::string name_suffix = std::to_string(name_suffix_counter);
  std::string splitter = "__";
  std::string name_with_suffix = name + splitter + name_suffix;
  platform::CPUPlace cpu_place;
  PADDLE_ENFORCE_EQ(weight_map.count(name_with_suffix),
                    0,
                    platform::errors::AlreadyExists(
                        "The weight named %s is set into the weight map "
                        "twice in TRT OP converter.",
                        name_with_suffix));

775 776 777 778 779
  if (weight_tensor.place() == PlaceType::kGPU ||
      weight_tensor.dtype() != phi::DataType::FLOAT32) {
    weight_map[name_with_suffix].reset(new phi::DenseTensor());
    weight_map[name_with_suffix]->Resize(weight_tensor.dims());
  }
780 781 782 783 784 785

  TensorRTEngine::Weight weight;
  weight.SetCount(weight_tensor.numel());

  // if trt not support dtype, we need to cast to fp32.
  if (weight_tensor.dtype() == phi::DataType::BFLOAT16) {
786
    phi::DenseTensor bf16_tensor;
787 788 789
    bf16_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &bf16_tensor);
790
    weight_map[name_with_suffix]->set_type(phi::DataType::FLOAT32);
791 792 793 794 795 796 797 798 799
    auto *fp32_data =
        weight_map[name_with_suffix]->mutable_data<float>(platform::CPUPlace());
    auto *bf16_data = bf16_tensor.mutable_data<bfloat16>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      fp32_data[i] = static_cast<float>(bf16_data[i]);
    }
    weight.SetDataType(phi::DataType::FLOAT32);
    weight.SetValues(fp32_data);
  } else if (weight_tensor.dtype() == phi::DataType::INT64) {
800
    phi::DenseTensor int64_tensor;
801 802 803
    int64_tensor.clear();
    paddle::framework::TensorCopySync(
        weight_tensor, platform::CPUPlace(), &int64_tensor);
804
    weight_map[name_with_suffix]->set_type(phi::DataType::INT32);
Y
Yuanle Liu 已提交
805 806
    auto *int32_data = weight_map[name_with_suffix]->mutable_data<int32_t>(
        platform::CPUPlace());
807 808 809 810
    auto *int64_data = int64_tensor.mutable_data<int64_t>(platform::CPUPlace());
    for (int i = 0; i < weight_tensor.numel(); i++) {
      int32_data[i] = int64_data[i];
    }
Z
zhoutianzi666 已提交
811
    weight.SetDataType(phi::DataType::INT32);
812 813
    weight.SetValues(int32_data);
  } else {
814 815 816 817 818 819 820 821 822
    if (weight_tensor.place() == PlaceType::kGPU) {
      paddle::framework::TensorCopySync(
          weight_tensor, cpu_place, weight_map[name_with_suffix].get());
      weight.SetDataType(weight_tensor.dtype());
      weight.SetValues(weight_map[name_with_suffix]->data());
    } else {
      weight.SetDataType(weight_tensor.dtype());
      weight.SetValues(weight_tensor.data());
    }
823
  }
824

825 826 827
  name_suffix_counter += 1;
  return weight;
}
828

829
nvinfer1::IPluginV2Layer *TensorRTEngine::AddPlugin(
830 831
    nvinfer1::ITensor *const *inputs,
    int num_inputs,
832
    plugin::PluginTensorRT *plugin) {
833
  owned_plugin_.emplace_back(plugin);
834
  return network()->addPluginV2(inputs, num_inputs, *plugin);
835 836
}

837
nvinfer1::IPluginV2Layer *TensorRTEngine::AddPluginV2Ext(
838 839
    nvinfer1::ITensor *const *inputs,
    int num_inputs,
840 841 842 843 844
    plugin::PluginTensorRTV2Ext *plugin) {
  owned_plugin_v2ext_.emplace_back(plugin);
  return network()->addPluginV2(inputs, num_inputs, *plugin);
}

845
nvinfer1::IPluginV2Layer *TensorRTEngine::AddPluginV2IOExt(
846 847
    nvinfer1::ITensor *const *inputs,
    int num_inputs,
848 849 850 851 852
    nvinfer1::IPluginV2IOExt *plugin) {
  owned_plugin_v2ioext_.emplace_back(plugin);
  return network()->addPluginV2(inputs, num_inputs, *plugin);
}

853
void TensorRTEngine::FreshDeviceId() {
N
nhzlx 已提交
854 855
  int count;
  cudaGetDeviceCount(&count);
856
  PADDLE_ENFORCE_LT(device_id(),
857
                    count,
858 859
                    platform::errors::OutOfRange(
                        "Device id %d exceeds the current device count: %d.",
860
                        device_id(),
861
                        count));
862
  platform::SetDeviceId(device_id());
N
nhzlx 已提交
863 864
}

865 866 867 868 869
void TensorRTEngine::GetEngineInfo() {
#if IS_TRT_VERSION_GE(8200)
  LOG(INFO) << "====== engine info ======";
  std::unique_ptr<nvinfer1::IEngineInspector> infer_inspector(
      infer_engine_->createEngineInspector());
870 871
  auto *infer_context = context();
  infer_inspector->setExecutionContext(infer_context);
872 873 874 875
  for (int i = 0; i < infer_engine_->getNbLayers(); ++i) {
    LOG(INFO) << infer_inspector->getLayerInformation(
        i, nvinfer1::LayerInformationFormat::kJSON);
  }
876 877 878 879 880 881
  LOG(INFO) << "====== engine info end ======";
#else
  LOG(INFO) << "Inspector needs TensorRT version 8.2 and after.";
#endif
}

Y
Yan Chunwei 已提交
882 883 884
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle