test_trt_engine.cc 15.0 KB
Newer Older
W
Wilber 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 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 <math.h>

#include <NvInfer.h>
#include <NvInferRuntime.h>
#include <NvInferRuntimeCommon.h>
W
Wilber 已提交
20 21
#include <glog/logging.h>
#include <gtest/gtest.h>
W
Wilber 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include "paddle/fluid/inference/tensorrt/plugin/split_op_plugin.h"
#include "paddle/fluid/inference/tensorrt/plugin/trt_plugin.h"
#include "paddle/fluid/memory/allocation/allocator_facade.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/infrt/backends/tensorrt/trt_engine.h"
#include "paddle/infrt/backends/tensorrt/trt_options.h"
#include "paddle/phi/backends/gpu/gpu_context.h"
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/common/place.h"
#include "paddle/phi/core/allocator.h"
#include "paddle/phi/core/ddim.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/meta_tensor.h"

namespace infrt {
namespace backends {
namespace tensorrt {

W
Wilber 已提交
40 41 42
const char* model_input = "input_0";
const char* model_output = "output_0";
const char* model_output2 = "output_1";
W
Wilber 已提交
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

TrtUniquePtr<nvinfer1::INetworkDefinition> ConstructNetwork(
    nvinfer1::IBuilder* builder, nvinfer1::Dims dims, bool is_static_shape) {
  TrtUniquePtr<nvinfer1::INetworkDefinition> network;
  if (is_static_shape) {
    network.reset(builder->createNetworkV2(0U));
  } else {
    auto networkFlags =
        1U << static_cast<uint32_t>(
            nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
    network.reset(builder->createNetworkV2(networkFlags));
  }

  ITensor* data =
      network->addInput(model_input, nvinfer1::DataType::kFLOAT, dims);
  CHECK_NOTNULL(data);
  IActivationLayer* act =
      network->addActivation(*data, ActivationType::kSIGMOID);
  CHECK_NOTNULL(act);
  auto* act_out = act->getOutput(0);
  std::vector<int> output_length{1, 2};
  int axis;
  nvinfer1::IPluginV2Layer* split_layer;
  if (is_static_shape) {
    axis = 0;
    paddle::inference::tensorrt::plugin::SplitPlugin plugin(
        axis, output_length, false);
    split_layer = network->addPluginV2(&act_out, 1, plugin);
  } else {
    axis = 1;
    paddle::inference::tensorrt::plugin::SplitPluginDynamic plugin(
        axis, output_length, false);
    split_layer = network->addPluginV2(&act_out, 1, plugin);
  }

  split_layer->getOutput(0)->setName(model_output);
  split_layer->getOutput(1)->setName(model_output2);
  network->markOutput(*split_layer->getOutput(0));
  network->markOutput(*split_layer->getOutput(1));
  return network;
}

W
Wilber 已提交
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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 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
TrtUniquePtr<nvinfer1::INetworkDefinition> ConstructFCNetwork(
    nvinfer1::IBuilder* builder, nvinfer1::Dims dims, bool is_static_shape) {
  TrtUniquePtr<nvinfer1::INetworkDefinition> network;
  if (is_static_shape) {
    network.reset(builder->createNetworkV2(0U));
  } else {
    auto networkFlags =
        1U << static_cast<uint32_t>(
            nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
    network.reset(builder->createNetworkV2(networkFlags));
  }

  ITensor* data =
      network->addInput(model_input, nvinfer1::DataType::kFLOAT, dims);
  CHECK_NOTNULL(data);
  nvinfer1::Weights kernel_weights;
  kernel_weights.type = nvinfer1::DataType::kFLOAT;
  kernel_weights.count = 7840;
  std::vector<float> weight_data(kernel_weights.count);
  for (size_t i = 0; i < weight_data.size(); ++i) {
    weight_data[i] = i % 255 * 0.02f;
  }
  kernel_weights.values = weight_data.data();
  auto* layer = network->addFullyConnected(
      *data, 10, kernel_weights, nvinfer1::Weights{});
  CHECK_NOTNULL(layer);
  auto* out = layer->getOutput(0);
  out->setName(model_output);
  network->markOutput(*out);
  return network;
}

TrtUniquePtr<nvinfer1::INetworkDefinition> ConstructConvNetwork(
    nvinfer1::IBuilder* builder, nvinfer1::Dims dims, bool is_static_shape) {
  TrtUniquePtr<nvinfer1::INetworkDefinition> network;
  if (is_static_shape) {
    network.reset(builder->createNetworkV2(0U));
  } else {
    auto networkFlags =
        1U << static_cast<uint32_t>(
            nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
    network.reset(builder->createNetworkV2(networkFlags));
  }

  ITensor* data =
      network->addInput(model_input, nvinfer1::DataType::kFLOAT, dims);
  CHECK_NOTNULL(data);
  nvinfer1::Weights kernel_weights, bias_weights;
  kernel_weights.type = nvinfer1::DataType::kFLOAT;
  bias_weights.type = nvinfer1::DataType::kFLOAT;
  kernel_weights.count = 81;
  bias_weights.count = 3;
  std::vector<float> weight_data(kernel_weights.count);
  for (size_t i = 0; i < weight_data.size(); ++i) {
    weight_data[i] = i * 0.02f;
  }
  std::vector<float> bias_data(bias_weights.count);
  for (size_t i = 0; i < bias_data.size(); ++i) {
    bias_data[i] = i * 0.5f;
  }
  kernel_weights.values = weight_data.data();
  bias_weights.values = bias_data.data();
  nvinfer1::Dims ksize;
  ksize.nbDims = 2;
  ksize.d[0] = 3;
  ksize.d[1] = 3;
  auto* layer =
      network->addConvolutionNd(*data, 3, ksize, kernel_weights, bias_weights);
  CHECK_NOTNULL(layer);
  auto* out = layer->getOutput(0);
  out->setName(model_output);
  network->markOutput(*out);
  return network;
}

W
Wilber 已提交
160 161 162
// sigmoid(x) = 1 / (1 + exp(-x))
inline float sigmoid(float x) { return 1.f / (1.f + exp(-1 * x)); }

W
Wilber 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
TEST(trt, run_fc_static) {
  TrtEngine engine(0);
  auto net = ConstructFCNetwork(
      engine.GetTrtBuilder(), nvinfer1::Dims3{1, 28, 28}, true);
  BuildOptions build_options;
  build_options.max_batch = 4;
  build_options.workspace = 1024;
  engine.Build(std::move(net), build_options);

  InferenceOptions inference_options;
  inference_options.batch = 1;

  phi::GPUPlace place;
  phi::GPUContext context;
  context.PartialInitWithoutAllocator();
  context.SetAllocator(paddle::memory::allocation::AllocatorFacade::Instance()
                           .GetAllocator(place, context.stream())
                           .get());
  context.PartialInitWithAllocator();

  phi::DenseTensorMeta meta(
      phi::DataType::FLOAT32,
      phi::make_ddim({inference_options.batch, 1, 28, 28}));
  phi::DenseTensor input;
  input.set_meta(meta);
  context.Alloc<float>(&input, input.numel() * sizeof(float));
  std::vector<float> host_data(inference_options.batch * 1 * 28 * 28, 0);
  for (size_t i = 0; i < host_data.size(); ++i) {
    host_data[i] = i % 100 * 0.016f;
  }
  paddle::memory::Copy(place,
                       input.data<float>(),
                       phi::CPUPlace(),
                       host_data.data(),
                       sizeof(float) * host_data.size(),
                       context.stream());

  std::unordered_map<std::string, phi::DenseTensor*> inputs;
  inputs.emplace(std::make_pair(model_input, &input));
  engine.PrepareOutputHandle("output_0");
  engine.SetUpInference(inference_options, inputs);
  engine.GetEngineInfo();
  engine.Run(context);
  cudaStreamSynchronize(context.stream());
}

TEST(trt, run_conv_static) {
  TrtEngine engine(0);
  auto net = ConstructConvNetwork(
      engine.GetTrtBuilder(), nvinfer1::Dims3{3, 28, 28}, true);
  BuildOptions build_options;
  build_options.max_batch = 4;
  build_options.workspace = 1024;
  engine.Build(std::move(net), build_options);

  InferenceOptions inference_options;
  inference_options.batch = 1;

  phi::GPUPlace place;
  phi::GPUContext context;
  context.PartialInitWithoutAllocator();
  context.SetAllocator(paddle::memory::allocation::AllocatorFacade::Instance()
                           .GetAllocator(place, context.stream())
                           .get());
  context.PartialInitWithAllocator();

  phi::DenseTensorMeta meta(
      phi::DataType::FLOAT32,
      phi::make_ddim({inference_options.batch, 3, 28, 28}));
  phi::DenseTensor input;
  input.set_meta(meta);
  context.Alloc<float>(&input, input.numel() * sizeof(float));
  std::vector<float> host_data(inference_options.batch * 3 * 28 * 28, 0);
  for (size_t i = 0; i < host_data.size(); ++i) {
    host_data[i] = i % 100 * 0.016f;
  }
  paddle::memory::Copy(place,
                       input.data<float>(),
                       phi::CPUPlace(),
                       host_data.data(),
                       sizeof(float) * host_data.size(),
                       context.stream());

  std::unordered_map<std::string, phi::DenseTensor*> inputs;
  inputs.emplace(std::make_pair(model_input, &input));
  engine.PrepareOutputHandle("output_0");
  engine.SetUpInference(inference_options, inputs);
  engine.GetEngineInfo();
  engine.Run(context);
  cudaStreamSynchronize(context.stream());
}

W
Wilber 已提交
255
TEST(trt, run_static) {
W
Wilber 已提交
256
  TrtEngine static_trt_engine(0);
W
Wilber 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  auto net = ConstructNetwork(
      static_trt_engine.GetTrtBuilder(), nvinfer1::Dims3{3, 28, 28}, true);
  BuildOptions static_build_options;
  static_build_options.max_batch = 4;
  static_trt_engine.Build(std::move(net), static_build_options);
  InferenceOptions inference_options;
  inference_options.batch = 2;

  phi::GPUPlace place;
  phi::GPUContext context;
  context.PartialInitWithoutAllocator();
  context.SetAllocator(paddle::memory::allocation::AllocatorFacade::Instance()
                           .GetAllocator(place, context.stream())
                           .get());
  context.PartialInitWithAllocator();

  phi::DenseTensorMeta meta(
      phi::DataType::FLOAT32,
      phi::make_ddim({inference_options.batch, 3, 28, 28}));
  phi::DenseTensor input;
  input.set_meta(meta);
  context.Alloc<float>(&input, input.numel() * sizeof(float));
  std::vector<float> host_data(inference_options.batch * 3 * 28 * 28, 0);
  for (size_t i = 0; i < host_data.size(); ++i) {
    host_data[i] = i % 100 * 0.016f;
  }
  paddle::memory::Copy(place,
                       input.data<float>(),
                       phi::CPUPlace(),
                       host_data.data(),
                       sizeof(float) * host_data.size(),
                       context.stream());

  std::unordered_map<std::string, phi::DenseTensor*> inputs;
  inputs.emplace(std::make_pair(model_input, &input));
W
Wilber 已提交
292 293 294
  static_trt_engine.PrepareOutputHandle("output_0");
  static_trt_engine.PrepareOutputHandle("output_1");
  static_trt_engine.SetUpInference(inference_options, inputs);
W
Wilber 已提交
295 296 297
  static_trt_engine.GetEngineInfo();
  static_trt_engine.Run(context);

W
Wilber 已提交
298 299
  phi::DenseTensor* output0 = static_trt_engine.GetOutput("output_0");
  phi::DenseTensor* output1 = static_trt_engine.GetOutput("output_1");
W
Wilber 已提交
300 301 302 303 304
  std::vector<float> output_data1(inference_options.batch * 1 * 28 * 28, 0);
  std::vector<float> output_data2(inference_options.batch * 2 * 28 * 28, 0);
  paddle::memory::Copy(phi::CPUPlace(),
                       output_data1.data(),
                       place,
W
Wilber 已提交
305
                       output0->data<float>(),
W
Wilber 已提交
306 307 308 309 310
                       sizeof(float) * output_data1.size(),
                       context.stream());
  paddle::memory::Copy(phi::CPUPlace(),
                       output_data2.data(),
                       place,
W
Wilber 已提交
311
                       output1->data<float>(),
W
Wilber 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
                       sizeof(float) * output_data2.size(),
                       context.stream());
  cudaStreamSynchronize(context.stream());

  for (size_t i = 0; i < host_data.size(); ++i) {
    int w = i % 28;
    int h = (i / 28) % 28;
    int c = i / (28 * 28) % 3;
    int n = i / (28 * 28 * 3);
    if (c == 0) {
      CHECK_NEAR(
          sigmoid(host_data[i]), output_data1[n * 28 * 28 + h * 28 + w], 1e-5);
    } else {
      CHECK_NEAR(sigmoid(host_data[i]),
                 output_data2[n * 28 * 28 * 2 + (c - 1) * 28 * 28 + h * 28 + w],
                 1e-5);
    }
  }
}

TEST(trt, run_dynamic) {
W
Wilber 已提交
333
  TrtEngine engine(0);
W
Wilber 已提交
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 376 377
  auto net = ConstructNetwork(
      engine.GetTrtBuilder(), nvinfer1::Dims4{-1, 3, -1, -1}, false);
  BuildOptions build_options;
  build_options.max_batch = 4;
  build_options.workspace = 32;
  // build_options.fp16 = true;
  std::vector<int32_t> min_shape{1, 3, 16, 16};
  std::vector<int32_t> opt_shape{2, 3, 28, 28};
  std::vector<int32_t> max_shape{4, 3, 28, 28};
  build_options.shapes[model_input][0] = min_shape;
  build_options.shapes[model_input][1] = opt_shape;
  build_options.shapes[model_input][2] = max_shape;
  engine.Build(std::move(net), build_options);

  InferenceOptions inference_options;
  inference_options.batch = 2;

  phi::GPUPlace place;
  phi::GPUContext context;
  context.PartialInitWithoutAllocator();
  context.SetAllocator(paddle::memory::allocation::AllocatorFacade::Instance()
                           .GetAllocator(place, context.stream())
                           .get());
  context.PartialInitWithAllocator();

  phi::DenseTensorMeta meta(
      phi::DataType::FLOAT32,
      phi::make_ddim({inference_options.batch, 3, 16, 16}));
  phi::DenseTensor input, output, output2;
  input.set_meta(meta);
  context.Alloc<float>(&input, input.numel() * sizeof(float));
  std::vector<float> host_data(inference_options.batch * 3 * 16 * 16, 0);
  for (size_t i = 0; i < host_data.size(); ++i) {
    host_data[i] = i % 100 * 0.016f;
  }
  paddle::memory::Copy(place,
                       input.data<float>(),
                       phi::CPUPlace(),
                       host_data.data(),
                       sizeof(float) * host_data.size(),
                       context.stream());

  std::unordered_map<std::string, phi::DenseTensor*> inputs;
  inputs.emplace(std::make_pair(model_input, &input));
W
Wilber 已提交
378 379 380
  engine.PrepareOutputHandle("output_0");
  engine.PrepareOutputHandle("output_1");
  engine.SetUpInference(inference_options, inputs);
W
Wilber 已提交
381 382
  engine.GetEngineInfo();
  engine.Run(context);
W
Wilber 已提交
383 384
  phi::DenseTensor* output0 = engine.GetOutput("output_0");
  phi::DenseTensor* output1 = engine.GetOutput("output_1");
W
Wilber 已提交
385 386 387 388 389 390

  std::vector<float> output_data1(inference_options.batch * 1 * 16 * 16, 0);
  std::vector<float> output_data2(inference_options.batch * 2 * 16 * 16, 0);
  paddle::memory::Copy(phi::CPUPlace(),
                       output_data1.data(),
                       place,
W
Wilber 已提交
391
                       output0->data<float>(),
W
Wilber 已提交
392 393 394 395 396
                       sizeof(float) * output_data1.size(),
                       context.stream());
  paddle::memory::Copy(phi::CPUPlace(),
                       output_data2.data(),
                       place,
W
Wilber 已提交
397
                       output1->data<float>(),
W
Wilber 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
                       sizeof(float) * output_data2.size(),
                       context.stream());
  cudaStreamSynchronize(context.stream());

  for (size_t i = 0; i < host_data.size(); ++i) {
    int w = i % 16;
    int h = (i / 16) % 16;
    int c = i / (16 * 16) % 3;
    int n = i / (16 * 16 * 3);
    if (c == 0) {
      CHECK_NEAR(
          sigmoid(host_data[i]), output_data1[n * 16 * 16 + h * 16 + w], 1e-5);
    } else {
      CHECK_NEAR(sigmoid(host_data[i]),
                 output_data2[n * 16 * 16 * 2 + (c - 1) * 16 * 16 + h * 16 + w],
                 1e-5);
    }
  }
}

}  // namespace tensorrt
}  // namespace backends
}  // namespace infrt