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

#include <glog/logging.h>
#include <gtest/gtest.h>

N
nhzlx 已提交
18
#include "paddle/fluid/framework/tensor.h"
19
#include "paddle/fluid/inference/tensorrt/engine.h"
Y
Yan Chunwei 已提交
20 21 22 23 24 25 26 27 28
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace inference {
namespace tensorrt {

class TensorRTEngineTest : public ::testing::Test {
 protected:
  void SetUp() override {
L
Leo Chen 已提交
29
    ctx_ = new phi::GPUContext(platform::CUDAPlace(0));
W
Wilber 已提交
30 31 32 33 34 35 36 37 38 39 40
    ctx_->SetAllocator(paddle::memory::allocation::AllocatorFacade::Instance()
                           .GetAllocator(platform::CUDAPlace(0), ctx_->stream())
                           .get());
    ctx_->SetHostAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
            .GetAllocator(paddle::platform::CPUPlace())
            .get());
    ctx_->SetZeroAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
            .GetZeroAllocator(platform::CUDAPlace(0))
            .get());
41 42 43 44
    ctx_->SetHostZeroAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
            .GetZeroAllocator(paddle::platform::CPUPlace())
            .get());
W
wanghuancoder 已提交
45 46 47 48
    ctx_->SetPinnedAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
            .GetAllocator(paddle::platform::CUDAPinnedPlace())
            .get());
W
Wilber 已提交
49
    ctx_->PartialInitWithAllocator();
N
nhzlx 已提交
50

51
    engine_ = new TensorRTEngine(10, 1 << 10);
Y
Yan Chunwei 已提交
52 53 54
    engine_->InitNetwork();
  }

N
nhzlx 已提交
55 56 57 58 59 60
  void TearDown() override {
    if (engine_) {
      delete engine_;
      engine_ = nullptr;
    }
  }
N
nhzlx 已提交
61 62 63

  void PrepareInputOutput(const std::vector<float> &input,
                          std::vector<int> output_shape) {
64
    paddle::framework::TensorFromVector(input, *ctx_, &input_);
65
    output_.Resize(phi::make_ddim(output_shape));
N
nhzlx 已提交
66 67 68
  }

  void GetOutput(std::vector<float> *output) {
69
    paddle::framework::TensorToVector(output_, *ctx_, output);
Y
Yan Chunwei 已提交
70 71 72
  }

 protected:
73 74
  phi::DenseTensor input_;
  phi::DenseTensor output_;
N
nhzlx 已提交
75
  TensorRTEngine *engine_;
L
Leo Chen 已提交
76
  phi::GPUContext *ctx_;
Y
Yan Chunwei 已提交
77 78 79 80 81 82 83 84
};

TEST_F(TensorRTEngineTest, add_layer) {
  const int size = 1;

  float raw_weight[size] = {2.};  // Weight in CPU memory.
  float raw_bias[size] = {3.};

N
nhzlx 已提交
85 86
  std::vector<void *> buffers(2);  // TRT binded inputs

Y
Yan Chunwei 已提交
87 88 89
  LOG(INFO) << "create weights";
  TensorRTEngine::Weight weight(nvinfer1::DataType::kFLOAT, raw_weight, size);
  TensorRTEngine::Weight bias(nvinfer1::DataType::kFLOAT, raw_bias, size);
90 91 92 93
  auto *x = engine_->DeclareInput(
      "x", nvinfer1::DataType::kFLOAT, nvinfer1::Dims3{1, 1, 1});
  auto *fc_layer = TRT_ENGINE_ADD_LAYER(
      engine_, FullyConnected, *x, size, weight.get(), bias.get());
94 95 96
  PADDLE_ENFORCE_NOT_NULL(fc_layer,
                          platform::errors::InvalidArgument(
                              "TRT fully connected layer building failed."));
Y
Yan Chunwei 已提交
97 98 99 100 101 102 103

  engine_->DeclareOutput(fc_layer, 0, "y");
  LOG(INFO) << "freeze network";
  engine_->FreezeNetwork();
  ASSERT_EQ(engine_->engine()->getNbBindings(), 2);

  // fill in real data
N
nhzlx 已提交
104 105 106 107 108 109 110 111 112 113
  std::vector<float> x_v = {1234};
  std::vector<float> y_cpu;
  PrepareInputOutput(x_v, {1});

  auto *x_v_gpu_data = input_.mutable_data<float>(ctx_->GetPlace());
  auto *y_gpu_data = output_.mutable_data<float>(ctx_->GetPlace());

  buffers[0] = reinterpret_cast<void *>(x_v_gpu_data);
  buffers[1] = reinterpret_cast<void *>(y_gpu_data);

114 115 116 117 118 119 120 121 122
  LOG(INFO) << "Set attr";
  engine_->Set("test_attr", new std::string("test_attr"));
  if (engine_->Has("test_attr")) {
    auto attr_val = engine_->Get<std::string>("test_attr");
    engine_->Erase("test_attr");
  }
  std::string *attr_key = new std::string("attr_key");
  engine_->SetNotOwned("attr1", attr_key);

Y
Yan Chunwei 已提交
123
  LOG(INFO) << "to execute";
124
  engine_->Execute(1, &buffers, ctx_->stream());
Y
Yan Chunwei 已提交
125 126

  LOG(INFO) << "to get output";
N
nhzlx 已提交
127
  GetOutput(&y_cpu);
Y
Yan Chunwei 已提交
128 129

  LOG(INFO) << "to checkout output";
N
nhzlx 已提交
130
  ASSERT_EQ(y_cpu[0], x_v[0] * 2 + 3);
131 132

  delete attr_key;
Y
Yan Chunwei 已提交
133 134
}

X
Xin Pan 已提交
135 136 137 138 139 140
TEST_F(TensorRTEngineTest, add_layer_multi_dim) {
  // Weight in CPU memory.
  // It seems tensorrt FC use col-major: [[1.0, 3.3], [1.1, 4.4]]
  // instead of row-major, which is [[1.0, 1.1], [3.3, 4.4]]
  float raw_weight[4] = {1.0, 1.1, 3.3, 4.4};
  float raw_bias[2] = {1.3, 2.4};
N
nhzlx 已提交
141
  std::vector<void *> buffers(2);  // TRT binded inputs
X
Xin Pan 已提交
142 143 144

  TensorRTEngine::Weight weight(nvinfer1::DataType::kFLOAT, raw_weight, 4);
  TensorRTEngine::Weight bias(nvinfer1::DataType::kFLOAT, raw_bias, 2);
145 146 147 148
  auto *x = engine_->DeclareInput(
      "x", nvinfer1::DataType::kFLOAT, nvinfer1::Dims3{1, 2, 1});
  auto *fc_layer = TRT_ENGINE_ADD_LAYER(
      engine_, FullyConnected, *x, 2, weight.get(), bias.get());
149 150 151
  PADDLE_ENFORCE_NOT_NULL(fc_layer,
                          platform::errors::InvalidArgument(
                              "TRT fully connected layer building failed."));
X
Xin Pan 已提交
152 153 154 155 156

  engine_->DeclareOutput(fc_layer, 0, "y");
  engine_->FreezeNetwork();
  ASSERT_EQ(engine_->engine()->getNbBindings(), 2);

N
nhzlx 已提交
157 158 159 160 161 162 163 164 165 166 167
  // fill in real data
  std::vector<float> x_v = {1.0, 2.0};
  std::vector<float> y_cpu;
  PrepareInputOutput(x_v, {2});

  auto *x_v_gpu_data = input_.mutable_data<float>(ctx_->GetPlace());
  auto *y_gpu_data = output_.mutable_data<float>(ctx_->GetPlace());

  buffers[0] = reinterpret_cast<void *>(x_v_gpu_data);
  buffers[1] = reinterpret_cast<void *>(y_gpu_data);

168
  engine_->Execute(1, &buffers, ctx_->stream());
X
Xin Pan 已提交
169 170

  LOG(INFO) << "to get output";
N
nhzlx 已提交
171
  GetOutput(&y_cpu);
N
nhzlx 已提交
172

173 174 175 176
  auto dims = engine_->GetITensor("y")->getDimensions();
  ASSERT_EQ(dims.nbDims, 3);
  ASSERT_EQ(dims.d[0], 2);
  ASSERT_EQ(dims.d[1], 1);
N
nhzlx 已提交
177

X
Xin Pan 已提交
178 179 180 181
  ASSERT_EQ(y_cpu[0], 4.5);
  ASSERT_EQ(y_cpu[1], 14.5);
}

182
TEST_F(TensorRTEngineTest, test_conv2d) {
183 184 185
  // Weight in CPU memory.
  float raw_weight[9] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
  float raw_bias[1] = {0};
N
nhzlx 已提交
186
  std::vector<void *> buffers(2);  // TRT binded inputs
187 188 189

  TensorRTEngine::Weight weight(nvinfer1::DataType::kFLOAT, raw_weight, 9);
  TensorRTEngine::Weight bias(nvinfer1::DataType::kFLOAT, raw_bias, 1);
190 191 192 193 194 195 196 197 198
  auto *x = engine_->DeclareInput(
      "x", nvinfer1::DataType::kFLOAT, nvinfer1::Dims3{1, 3, 3});
  auto *conv_layer = TRT_ENGINE_ADD_LAYER(engine_,
                                          Convolution,
                                          *x,
                                          1,
                                          nvinfer1::DimsHW{3, 3},
                                          weight.get(),
                                          bias.get());
199 200 201
  PADDLE_ENFORCE_NOT_NULL(conv_layer,
                          platform::errors::InvalidArgument(
                              "TRT convolution layer building failed."));
202 203 204 205 206 207 208
  conv_layer->setStride(nvinfer1::DimsHW{1, 1});
  conv_layer->setPadding(nvinfer1::DimsHW{1, 1});

  engine_->DeclareOutput(conv_layer, 0, "y");
  engine_->FreezeNetwork();
  ASSERT_EQ(engine_->engine()->getNbBindings(), 2);

N
nhzlx 已提交
209
  // fill in real data
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  std::vector<float> x_v = {1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0,
                            1.0};
N
nhzlx 已提交
228 229 230 231 232 233 234 235 236
  std::vector<float> y_cpu;
  PrepareInputOutput(x_v, {18});

  auto *x_v_gpu_data = input_.mutable_data<float>(ctx_->GetPlace());
  auto *y_gpu_data = output_.mutable_data<float>(ctx_->GetPlace());

  buffers[0] = reinterpret_cast<void *>(x_v_gpu_data);
  buffers[1] = reinterpret_cast<void *>(y_gpu_data);

237
  engine_->Execute(2, &buffers, ctx_->stream());
238 239

  LOG(INFO) << "to get output";
N
nhzlx 已提交
240 241
  GetOutput(&y_cpu);

242 243 244 245
  ASSERT_EQ(y_cpu[0], 4.0);
  ASSERT_EQ(y_cpu[1], 6.0);
}

246 247
TEST_F(TensorRTEngineTest, test_pool2d) {
  // Weight in CPU memory.
248 249
  auto *x = engine_->DeclareInput(
      "x", nvinfer1::DataType::kFLOAT, nvinfer1::Dims3{1, 2, 2});
250

N
nhzlx 已提交
251
  std::vector<void *> buffers(2);  // TRT binded inputs
252
  nvinfer1::PoolingType pool_t = nvinfer1::PoolingType::kAVERAGE;
253 254
  auto *pool_layer = TRT_ENGINE_ADD_LAYER(
      engine_, Pooling, *x, pool_t, nvinfer1::DimsHW{2, 2});
255

256 257 258
  PADDLE_ENFORCE_NOT_NULL(
      pool_layer,
      platform::errors::InvalidArgument("TRT pooling layer building failed."));
259 260 261 262 263 264 265
  pool_layer->setStride(nvinfer1::DimsHW{1, 1});
  pool_layer->setPadding(nvinfer1::DimsHW{0, 0});

  engine_->DeclareOutput(pool_layer, 0, "y");
  engine_->FreezeNetwork();
  ASSERT_EQ(engine_->engine()->getNbBindings(), 2);

N
nhzlx 已提交
266 267 268 269 270 271 272 273 274 275 276
  // fill in real data
  std::vector<float> x_v = {1.0, 2.0, 5.0, 0.0, 2.0, 3.0, 5.0, 10.0};
  std::vector<float> y_cpu;
  PrepareInputOutput(x_v, {2});

  auto *x_v_gpu_data = input_.mutable_data<float>(ctx_->GetPlace());
  auto *y_gpu_data = output_.mutable_data<float>(ctx_->GetPlace());

  buffers[0] = reinterpret_cast<void *>(x_v_gpu_data);
  buffers[1] = reinterpret_cast<void *>(y_gpu_data);

277
  engine_->Execute(2, &buffers, ctx_->stream());
278 279

  LOG(INFO) << "to get output";
N
nhzlx 已提交
280
  GetOutput(&y_cpu);
281 282 283 284 285

  ASSERT_EQ(y_cpu[0], 2.0);
  ASSERT_EQ(y_cpu[1], 5.0);
}

Y
Yan Chunwei 已提交
286 287 288
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle