analysis_predictor_tester.cc 22.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

15
#include "paddle/fluid/inference/api/analysis_predictor.h"
16
#include "paddle/fluid/inference/api/resource_manager.h"
17 18 19
#if defined(PADDLE_WITH_CUDA)
#include <cuda_runtime.h>
#endif
20 21
#include <glog/logging.h>
#include <gtest/gtest.h>
22

23
#include <thread>  // NOLINT
24

Y
Yan Chunwei 已提交
25
#include "paddle/fluid/framework/ir/pass.h"
26
#include "paddle/fluid/framework/tensor.h"
27
#include "paddle/fluid/inference/api/helper.h"
28
#include "paddle/fluid/inference/api/paddle_api.h"
29
#include "paddle/fluid/inference/api/paddle_inference_api.h"
30
#include "paddle/fluid/inference/utils/io_utils.h"
31
#include "paddle/phi/backends/cpu/cpu_info.h"
T
tianshuo78520a 已提交
32
#include "test/cpp/inference/api/tester_helper.h"
33 34 35 36 37

DEFINE_string(dirname, "", "dirname to tests.");

namespace paddle {

38
TEST(AnalysisPredictor, analysis_off) {
39 40 41
  AnalysisConfig config;
  config.SetModel(FLAGS_dirname);
  config.SwitchIrOptim(false);
42
  LOG(INFO) << config.Summary();
43 44
  LOG(INFO) << "Shape Info collected: " << config.shape_range_info_collected()
            << ", path: " << config.shape_range_info_path();
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

  auto _predictor = CreatePaddlePredictor<AnalysisConfig>(config);
  auto* predictor = static_cast<AnalysisPredictor*>(_predictor.get());

  // Without analysis, the scope_ and sub_scope_ are created by predictor
  // itself.
  ASSERT_TRUE(predictor->scope_);
  ASSERT_TRUE(predictor->sub_scope_);
  ASSERT_EQ(predictor->scope_->parent(), nullptr);
  ASSERT_EQ(predictor->sub_scope_->parent(), predictor->scope_.get());
  // ir is turned off, so program shouldn't be optimized.
  LOG(INFO) << "scope parameters " << predictor->scope_->LocalVarNames().size();

  // 2. Dummy Input Data
  int64_t data[4] = {1, 2, 3, 4};
  PaddleTensor tensor;
  tensor.shape = std::vector<int>({4, 1});
  tensor.data.Reset(data, sizeof(data));
  tensor.dtype = PaddleDType::INT64;

  std::vector<PaddleTensor> inputs(4, tensor);
  std::vector<PaddleTensor> outputs;
  ASSERT_TRUE(predictor->Run(inputs, &outputs));
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#ifndef WIN32
TEST(AnalysisPredictor, lite_nn_adapter_npu) {
  AnalysisConfig config;
  config.SetModel(FLAGS_dirname);
  config.EnableLiteEngine();
  config.NNAdapter()
      .Disable()
      .Enable()
      .SetDeviceNames({"huawei_ascend_npu"})
      .SetContextProperties("HUAWEI_ASCEND_NPU_SELECTED_DEVICE_IDS=0")
      .SetModelCacheDir("cache_dirr")
      .SetSubgraphPartitionConfigPath("")
      .SetModelCacheBuffers("c1", {'c'});
#ifndef LITE_SUBGRAPH_WITH_NNADAPTER
  EXPECT_THROW(CreatePaddlePredictor<AnalysisConfig>(config),
               paddle::platform::EnforceNotMet);
#endif
}
#endif

90
TEST(AnalysisPredictor, analysis_on) {
91 92 93
  AnalysisConfig config;
  config.SetModel(FLAGS_dirname);
  config.SwitchIrOptim(true);
94
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
95
  config.EnableUseGpu(100, 0);
96
#else
97
  config.DisableGpu();
98
#endif
99
  LOG(INFO) << config.Summary();
100 101 102 103 104 105 106 107

  auto _predictor = CreatePaddlePredictor<AnalysisConfig>(config);
  auto* predictor = static_cast<AnalysisPredictor*>(_predictor.get());

  ASSERT_TRUE(predictor->scope_);
  ASSERT_TRUE(predictor->sub_scope_);
  ASSERT_EQ(predictor->scope_->parent(), nullptr);
  ASSERT_EQ(predictor->sub_scope_->parent(), predictor->scope_.get());
108
  ASSERT_EQ(predictor->GetInputTypes().size(), 4UL);
109 110
  ASSERT_EQ(predictor->GetOutputTypes().size(), 1UL);
  ASSERT_EQ(predictor->GetOutputTensorShape().size(), 1UL);
111 112 113 114 115 116 117 118 119 120 121 122
  // 2. Dummy Input Data
  int64_t data[4] = {1, 2, 3, 4};
  PaddleTensor tensor;
  tensor.shape = std::vector<int>({4, 1});
  tensor.data.Reset(data, sizeof(data));
  tensor.dtype = PaddleDType::INT64;

  std::vector<PaddleTensor> inputs(4, tensor);
  std::vector<PaddleTensor> outputs;
  ASSERT_TRUE(predictor->Run(inputs, &outputs));

  // compare with NativePredictor
123 124
  auto naive_predictor =
      CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
125 126 127 128 129 130
  std::vector<PaddleTensor> naive_outputs;
  ASSERT_TRUE(naive_predictor->Run(inputs, &naive_outputs));
  ASSERT_EQ(naive_outputs.size(), 1UL);
  inference::CompareTensor(outputs.front(), naive_outputs.front());
}

131 132 133 134 135 136 137 138 139 140 141 142 143
#ifdef PADDLE_WITH_XPU
TEST(AnalysisPredictor, save_optimized_model_on) {
  AnalysisConfig config;
  config.SetModel(FLAGS_dirname);
  config.SwitchIrOptim(true);
  config.EnableSaveOptimModel(true);
  config.EnableXpu();
  config.SetXpuDeviceId(0);
  LOG(INFO) << config.Summary();
  CreatePaddlePredictor<AnalysisConfig>(config);
}
#endif

144 145
TEST(AnalysisPredictor, ZeroCopy) {
  AnalysisConfig config;
146 147
  config.SetModel(FLAGS_dirname);
  config.SwitchUseFeedFetchOps(false);
148
  LOG(INFO) << config.Summary();
S
superjomn 已提交
149
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
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 178 179 180

  auto w0 = predictor->GetInputTensor("firstw");
  auto w1 = predictor->GetInputTensor("secondw");
  auto w2 = predictor->GetInputTensor("thirdw");
  auto w3 = predictor->GetInputTensor("forthw");

  w0->Reshape({4, 1});
  w1->Reshape({4, 1});
  w2->Reshape({4, 1});
  w3->Reshape({4, 1});

  auto* w0_data = w0->mutable_data<int64_t>(PaddlePlace::kCPU);
  auto* w1_data = w1->mutable_data<int64_t>(PaddlePlace::kCPU);
  auto* w2_data = w2->mutable_data<int64_t>(PaddlePlace::kCPU);
  auto* w3_data = w3->mutable_data<int64_t>(PaddlePlace::kCPU);

  for (int i = 0; i < 4; i++) {
    w0_data[i] = i;
    w1_data[i] = i;
    w2_data[i] = i;
    w3_data[i] = i;
  }

  predictor->ZeroCopyRun();

  auto out = predictor->GetOutputTensor("fc_1.tmp_2");
  PaddlePlace place;
  int size = 0;
  auto* out_data = out->data<float>(&place, &size);
  LOG(INFO) << "output size: " << size / sizeof(float);
  LOG(INFO) << "output_data: " << out_data;
181
  predictor->TryShrinkMemory();
182 183
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
TEST(AnalysisPredictor, CollectShapeRangeInfo) {
  AnalysisConfig config;
  config.SetModel(FLAGS_dirname);
  config.SwitchUseFeedFetchOps(false);
  config.EnableUseGpu(100, 0);
  config.CollectShapeRangeInfo(FLAGS_dirname + "/shape_range.pbtxt");
  LOG(INFO) << config.Summary();
  AnalysisConfig config2(config);
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(config2);

  auto w0 = predictor->GetInputTensor("firstw");
  auto w1 = predictor->GetInputTensor("secondw");
  auto w2 = predictor->GetInputTensor("thirdw");
  auto w3 = predictor->GetInputTensor("forthw");

  w0->Reshape({4, 1});
  w1->Reshape({4, 1});
  w2->Reshape({4, 1});
  w3->Reshape({4, 1});
203 204 205 206 207
  std::vector<int64_t> input_data{0, 1, 2, 3};
  w0->copy_from_cpu(input_data.data());
  w1->copy_from_cpu(input_data.data());
  w2->copy_from_cpu(input_data.data());
  w3->copy_from_cpu(input_data.data());
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

  predictor->ZeroCopyRun();

  auto out = predictor->GetOutputTensor("fc_1.tmp_2");
  PaddlePlace place;
  int size = 0;
  out->data<float>(&place, &size);
  LOG(INFO) << "output size: " << size / sizeof(float);
  // TODO(wilber): check for windows
  // std::map<std::string, std::vector<int32_t>> min_shape;
  // std::map<std::string, std::vector<int32_t>> max_shape;
  // std::map<std::string, std::vector<int32_t>> opt_shape;
  // inference::DeserializeShapeRangeInfo(FLAGS_dirname + "/shape_range.pbtxt",
  //                                     &min_shape, &max_shape, &opt_shape);
  // ASSERT_EQ(min_shape.size(), 14u);
}

225 226
TEST(AnalysisPredictor, Clone) {
  AnalysisConfig config;
227 228 229
  config.SetModel(FLAGS_dirname);
  config.SwitchUseFeedFetchOps(true);
  config.SwitchIrOptim(true);
230
  LOG(INFO) << config.Summary();
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

  std::vector<std::unique_ptr<PaddlePredictor>> predictors;
  predictors.emplace_back(CreatePaddlePredictor(config));

  LOG(INFO) << "************** to clone ************************";
  const int num_threads = 3;
  for (int i = 1; i < num_threads; i++) {
    predictors.emplace_back(predictors.front()->Clone());
  }

  auto* root_scope =
      static_cast<AnalysisPredictor*>(predictors[0].get())->scope();
  ASSERT_FALSE(root_scope->kids().empty());
  LOG(INFO) << "***** scope ******\n"
            << framework::GenScopeTreeDebugInfo(root_scope);

  // 2. Dummy Input Data
  int64_t data[4] = {1, 2, 3, 4};
  PaddleTensor tensor;
  tensor.shape = std::vector<int>({4, 1});
  tensor.data.Reset(data, sizeof(data));
  tensor.dtype = PaddleDType::INT64;

  std::vector<PaddleTensor> inputs(4, tensor);
  std::vector<PaddleTensor> outputs;
  predictors[0]->Run(inputs, &outputs);

  LOG(INFO) << "Run with single thread";
  for (int i = 0; i < num_threads; i++) {
    LOG(INFO) << "run predictor " << i;
    ASSERT_TRUE(predictors[i]->Run(inputs, &outputs));
  }

  LOG(INFO) << "Run with multiple threads";
  std::vector<std::thread> threads;
  for (int i = 0; i < num_threads; i++) {
    threads.emplace_back([&predictors, &inputs, i] {
      LOG(INFO) << "thread #" << i << " running";
      std::vector<PaddleTensor> outputs;
Y
Yan Chunwei 已提交
270
      auto predictor = predictors.front()->Clone();
271
      for (int j = 0; j < 10; j++) {
Y
Yan Chunwei 已提交
272
        ASSERT_TRUE(predictor->Run(inputs, &outputs));
273 274 275 276 277 278 279 280 281
      }
    });
  }

  for (auto& t : threads) {
    t.join();
  }
}

S
superjomn 已提交
282 283 284
// This function is not released yet, will fail on some machine.
// TODO(Superjomn) Turn on it latter.
/*
Y
Yan Chunwei 已提交
285 286 287 288
TEST(AnalysisPredictor, memory_optim) {
  AnalysisConfig config(FLAGS_dirname);
  config.DisableGpu();
  config.EnableMemoryOptim(true);
Y
Yan Chunwei 已提交
289
  config.SwitchIrDebug();
Y
Yan Chunwei 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

  auto native_predictor =
      CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());

  // 2. Dummy Input Data
  int64_t data[4] = {1, 2, 3, 4};
  PaddleTensor tensor;
  tensor.shape = std::vector<int>({4, 1});
  tensor.data.Reset(data, sizeof(data));
  tensor.dtype = PaddleDType::INT64;

  std::vector<PaddleTensor> inputs(4, tensor);
  std::vector<PaddleTensor> output, output1;

  {
    // The first predictor help to cache the memory optimize strategy.
    auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
307 308
    LOG(INFO) << "serialized program: " << predictor->GetSerializedProgram();
    ASSERT_FALSE(predictor->GetSerializedProgram().empty());
Y
Yan Chunwei 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

    // Run several times to check the parameters are not reused by mistake.
    for (int i = 0; i < 5; i++) {
      ASSERT_TRUE(predictor->Run(inputs, &output));
    }
  }

  {
    output.clear();
    // The second predictor to perform memory optimization.
    config.EnableMemoryOptim(false);
    auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);

    // Run with memory optimization
    ASSERT_TRUE(predictor->Run(inputs, &output));
  }

  // Run native
  ASSERT_TRUE(native_predictor->Run(inputs, &output1));

  LOG(INFO) << "the output " << inference::DescribeTensor(output.front());
  LOG(INFO) << "the native output "
            << inference::DescribeTensor(output1.front());

  inference::CompareResult(output, output1);
}
S
superjomn 已提交
335
*/
Y
Yan Chunwei 已提交
336

337
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
338 339 340 341 342 343 344
TEST(AnalysisPredictor, bf16_gpu_pass_strategy) {
  AnalysisConfig config;
  config.SetModel(FLAGS_dirname);
  config.SwitchIrOptim(true);
  config.EnableUseGpu(100, 0);
  config.EnableMkldnnBfloat16();
#ifdef PADDLE_WITH_MKLDNN
345
  if (phi::backends::cpu::MayIUse(phi::backends::cpu::cpu_isa_t::avx512_core))
346 347 348
    ASSERT_EQ(config.mkldnn_bfloat16_enabled(), true);
  else
    ASSERT_EQ(config.mkldnn_bfloat16_enabled(), false);
349 350 351 352 353 354 355 356 357 358 359 360
#else
  ASSERT_EQ(config.mkldnn_bfloat16_enabled(), false);
#endif
}
#endif

TEST(AnalysisPredictor, bf16_pass_strategy) {
  std::vector<std::string> passes;
  PassStrategy passStrategy(passes);
  passStrategy.EnableMkldnnBfloat16();
}

P
Paulina Gacek 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
TEST(AnalysisPredictor, mkldnn_fc_pass_strategy) {
  std::vector<std::string> passes;
  PassStrategy passStrategy(passes);
  passStrategy.DisableMkldnnFcPasses();
  ASSERT_EQ(passes.size(), (size_t)0);
}

#ifdef PADDLE_WITH_MKLDNN
TEST(AnalysisPredictor, mkldnn_fc_passes_cpu_pass_strategy) {
  CpuPassStrategy cpuPassStrategy;
  cpuPassStrategy.EnableMKLDNN();
  const std::vector<std::string> fc_passes_to_erase(
      {"fc_mkldnn_pass",
       "fc_act_mkldnn_fuse_pass",
       "fc_elementwise_add_mkldnn_fuse_pass"});
  for (const auto& pass : fc_passes_to_erase) {
    ASSERT_NE(cpuPassStrategy.GetPassIndex(pass), (size_t)-1);
  }
  cpuPassStrategy.DisableMkldnnFcPasses();
  for (const auto& pass : fc_passes_to_erase) {
    ASSERT_EQ(cpuPassStrategy.GetPassIndex(pass), (size_t)-1);
  }
}
#endif

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
TEST(AnalysisPredictor, mkldnn_fc_passes_gpu_pass_strategy) {
  AnalysisConfig config;
  config.EnableUseGpu(100, 0);
  config.EnableMKLDNN();
  config.DisableMkldnnFcPasses();
#ifdef PADDLE_WITH_MKLDNN
  ASSERT_TRUE(config.mkldnn_fc_passes_disabled());
#else
  ASSERT_FALSE(config.mkldnn_fc_passes_disabled());
#endif
}
#endif

400 401 402 403 404 405 406 407 408 409 410
#ifdef PADDLE_WITH_XPU
TEST(AnalysisPredictor, set_xpu_device_id) {
  AnalysisConfig config;
  config.EnableXpu();
  config.SetXpuDeviceId(0);
  ASSERT_EQ(config.xpu_device_id(), 0);
  config.SetXpuDeviceId(1);
  ASSERT_EQ(config.xpu_device_id(), 1);
}
#endif

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
TEST(AnalysisPredictor, enable_onnxruntime) {
  AnalysisConfig config;
  config.EnableONNXRuntime();
#ifdef PADDLE_WITH_ONNXRUNTIME
  ASSERT_TRUE(config.use_onnxruntime());
#else
  ASSERT_TRUE(!config.use_onnxruntime());
#endif
  config.EnableORTOptimization();
#ifdef PADDLE_WITH_ONNXRUNTIME
  ASSERT_TRUE(config.ort_optimization_enabled());
#else
  ASSERT_TRUE(!config.ort_optimization_enabled());
#endif
  config.DisableONNXRuntime();
  ASSERT_TRUE(!config.use_onnxruntime());
}

429
}  // namespace paddle
430 431 432 433

namespace paddle_infer {

TEST(Predictor, Run) {
434 435 436 437 438 439 440 441 442
  auto trt_compile_ver = GetTrtCompileVersion();
  auto trt_runtime_ver = GetTrtRuntimeVersion();
  LOG(INFO) << "trt compile version: " << std::get<0>(trt_compile_ver) << "."
            << std::get<1>(trt_compile_ver) << "."
            << std::get<2>(trt_compile_ver);
  LOG(INFO) << "trt runtime version: " << std::get<0>(trt_runtime_ver) << "."
            << std::get<1>(trt_runtime_ver) << "."
            << std::get<2>(trt_runtime_ver);

443 444 445 446
  Config config;
  config.SetModel(FLAGS_dirname);

  auto predictor = CreatePredictor(config);
447
  ASSERT_EQ(predictor->GetInputTypes().size(), 4UL);
448 449
  ASSERT_EQ(predictor->GetOutputTypes().size(), 1UL);
  ASSERT_EQ(predictor->GetOutputTensorShape().size(), 1UL);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

  auto w0 = predictor->GetInputHandle("firstw");
  auto w1 = predictor->GetInputHandle("secondw");
  auto w2 = predictor->GetInputHandle("thirdw");
  auto w3 = predictor->GetInputHandle("forthw");

  w0->Reshape({4, 1});
  w1->Reshape({4, 1});
  w2->Reshape({4, 1});
  w3->Reshape({4, 1});

  auto* w0_data = w0->mutable_data<int64_t>(PlaceType::kCPU);
  auto* w1_data = w1->mutable_data<int64_t>(PlaceType::kCPU);
  auto* w2_data = w2->mutable_data<int64_t>(PlaceType::kCPU);
  auto* w3_data = w3->mutable_data<int64_t>(PlaceType::kCPU);

  for (int i = 0; i < 4; i++) {
    w0_data[i] = i;
    w1_data[i] = i;
    w2_data[i] = i;
    w3_data[i] = i;
  }

  predictor->Run();

  auto out = predictor->GetOutputHandle("fc_1.tmp_2");
  PlaceType place;
  int size = 0;
  out->data<float>(&place, &size);
  LOG(INFO) << "output size: " << size / sizeof(float);
  predictor->TryShrinkMemory();
}

483 484 485 486 487 488 489 490
TEST(Predictor, EnableONNXRuntime) {
  Config config;
  config.SetModel(FLAGS_dirname);
  config.EnableONNXRuntime();
  config.EnableORTOptimization();
  auto predictor = CreatePredictor(config);
}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
TEST(Tensor, CpuShareExternalData) {
  Config config;
  config.SetModel(FLAGS_dirname);

  auto predictor = CreatePredictor(config);

  auto w0 = predictor->GetInputHandle("firstw");
  auto w1 = predictor->GetInputHandle("secondw");
  auto w2 = predictor->GetInputHandle("thirdw");
  auto w3 = predictor->GetInputHandle("forthw");

  std::vector<std::vector<int64_t>> input_data(4, {0, 1, 2, 3});
  w0->ShareExternalData<int64_t>(input_data[0].data(), {4, 1}, PlaceType::kCPU);
  w1->ShareExternalData<int64_t>(input_data[1].data(), {4, 1}, PlaceType::kCPU);
  w2->ShareExternalData<int64_t>(input_data[2].data(), {4, 1}, PlaceType::kCPU);
  w3->ShareExternalData<int64_t>(input_data[3].data(), {4, 1}, PlaceType::kCPU);

  auto out = predictor->GetOutputHandle("fc_1.tmp_2");
  auto out_shape = out->shape();
  std::vector<float> out_data;
W
Wilber 已提交
511 512
  out_data.resize(std::accumulate(
      out_shape.begin(), out_shape.end(), 1, std::multiplies<int>()));
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  out->ShareExternalData<float>(out_data.data(), out_shape, PlaceType::kCPU);

  predictor->Run();

  PlaceType place;
  int size = 0;
  out->data<float>(&place, &size);
  LOG(INFO) << "output size: " << size / sizeof(float);
  predictor->TryShrinkMemory();
}

#if defined(PADDLE_WITH_CUDA)
TEST(Tensor, GpuShareExternalData) {
  Config config;
  config.SetModel(FLAGS_dirname);
  config.EnableUseGpu(100, 0);

  auto predictor = CreatePredictor(config);

  auto w0 = predictor->GetInputHandle("firstw");
  auto w1 = predictor->GetInputHandle("secondw");
  auto w2 = predictor->GetInputHandle("thirdw");
  auto w3 = predictor->GetInputHandle("forthw");

  std::vector<std::vector<int64_t>> input_data(4, {0, 1, 2, 3});
  std::vector<int64_t*> input_gpu(4, nullptr);

  for (size_t i = 0; i < 4; ++i) {
    cudaMalloc(reinterpret_cast<void**>(&input_gpu[i]), 4 * sizeof(int64_t));
W
Wilber 已提交
542 543 544
    cudaMemcpy(input_gpu[i],
               input_data[i].data(),
               4 * sizeof(int64_t),
545 546 547 548 549 550 551 552 553 554
               cudaMemcpyHostToDevice);
  }

  w0->ShareExternalData<int64_t>(input_gpu[0], {4, 1}, PlaceType::kGPU);
  w1->ShareExternalData<int64_t>(input_gpu[1], {4, 1}, PlaceType::kGPU);
  w2->ShareExternalData<int64_t>(input_gpu[2], {4, 1}, PlaceType::kGPU);
  w3->ShareExternalData<int64_t>(input_gpu[3], {4, 1}, PlaceType::kGPU);

  auto out = predictor->GetOutputHandle("fc_1.tmp_2");
  auto out_shape = out->shape();
555
  float* out_data = nullptr;
W
Wilber 已提交
556 557 558 559
  auto out_size =
      std::accumulate(
          out_shape.begin(), out_shape.end(), 1, std::multiplies<int>()) *
      sizeof(float);
560 561 562 563 564 565 566 567 568 569 570
  cudaMalloc(reinterpret_cast<void**>(out_data), out_size * sizeof(float));
  out->ShareExternalData<float>(out_data, out_shape, PlaceType::kGPU);

  predictor->Run();

  PlaceType place;
  int size = 0;
  out->data<float>(&place, &size);
  LOG(INFO) << "output size: " << size / sizeof(float);
  predictor->TryShrinkMemory();
}
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667

TEST(Predictor, Streams) {
  // internal stream.
  {
    Config config;
    config.SetModel(FLAGS_dirname);
    config.EnableUseGpu(100, 0);
    auto predictor = CreatePredictor(config);
    gpuStream_t stream =
        reinterpret_cast<gpuStream_t>(predictor->GetExecStream());
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream), 0);
  }

  // internal stream, create 2 predictor.
  {
    Config config1;
    config1.SetModel(FLAGS_dirname);
    config1.EnableUseGpu(100, 0);
    auto predictor1 = CreatePredictor(config1);
    gpuStream_t stream1 =
        reinterpret_cast<gpuStream_t>(predictor1->GetExecStream());
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream1), 0);

    Config config2;
    config2.SetModel(FLAGS_dirname);
    config2.EnableUseGpu(100, 0);
    auto predictor2 = CreatePredictor(config2);
    gpuStream_t stream2 =
        reinterpret_cast<gpuStream_t>(predictor2->GetExecStream());
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream2), 0);
    CHECK_EQ(stream1, stream2);
  }

  // internal stream, clone
  {
    Config config;
    config.SetModel(FLAGS_dirname);
    config.EnableUseGpu(100, 0);
    auto predictor = CreatePredictor(config);
    gpuStream_t stream =
        reinterpret_cast<gpuStream_t>(predictor->GetExecStream());
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream), 0);

    auto predictor2 = predictor->Clone();
    gpuStream_t stream2 =
        reinterpret_cast<gpuStream_t>(predictor2->GetExecStream());
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream2), 0);
    CHECK_EQ(stream, stream2);
  }

  // external stream
  {
    cudaStream_t external_stream;
    cudaStreamCreate(&external_stream);
    Config config;
    config.SetModel(FLAGS_dirname);
    config.EnableUseGpu(100, 0);
    config.SetExecStream(external_stream);
    CHECK_EQ(config.external_stream_enabled(), true);

    auto predictor = CreatePredictor(config);
    gpuStream_t stream =
        reinterpret_cast<gpuStream_t>(predictor->GetExecStream());
    CHECK_EQ(external_stream, stream);
    CHECK_NOTNULL(paddle::ResourceManager::Instance().GetGPUResource(stream));
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream), 1);
  }

  // 2 predictor on 2 stream
  {
    cudaStream_t external_stream;
    cudaStreamCreate(&external_stream);
    Config config;
    config.SetModel(FLAGS_dirname);
    config.EnableUseGpu(100, 0);
    config.SetExecStream(external_stream);
    auto predictor = CreatePredictor(config);
    gpuStream_t stream =
        reinterpret_cast<gpuStream_t>(predictor->GetExecStream());
    CHECK_NOTNULL(paddle::ResourceManager::Instance().GetGPUResource(stream));
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream), 1);

    cudaStream_t external_stream2;
    cudaStreamCreate(&external_stream2);
    Config config2;
    config2.SetModel(FLAGS_dirname);
    config2.EnableUseGpu(100, 0);
    config2.SetExecStream(external_stream2);
    auto predictor2 = CreatePredictor(config2);
    gpuStream_t stream2 =
        reinterpret_cast<gpuStream_t>(predictor2->GetExecStream());
    CHECK_NOTNULL(paddle::ResourceManager::Instance().GetGPUResource(stream2));
    CHECK_EQ(paddle::ResourceManager::Instance().RefCount(stream2), 1);

    CHECK_NE(stream, stream2);
  }
}
668 669
#endif

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
TEST(AnalysisPredictor, OutputTensorHookFunc) {
  auto hookfunc = [](const std::string& type,
                     const std::string& var_name,
                     const paddle::Tensor& tensor) {
    LOG(INFO) << "in hook function";
  };

  {
    Config config;
    config.SetModel(FLAGS_dirname);
    config.EnableUseGpu(100, 0);

    auto predictor = CreatePredictor(config);

    predictor->RegisterOutputHook(hookfunc);
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    auto w0 = predictor->GetInputHandle("firstw");
    auto w1 = predictor->GetInputHandle("secondw");
    auto w2 = predictor->GetInputHandle("thirdw");
    auto w3 = predictor->GetInputHandle("forthw");
    w0->Reshape({4, 1});
    w1->Reshape({4, 1});
    w2->Reshape({4, 1});
    w3->Reshape({4, 1});
    auto* w0_data = w0->mutable_data<int64_t>(PlaceType::kCPU);
    auto* w1_data = w1->mutable_data<int64_t>(PlaceType::kCPU);
    auto* w2_data = w2->mutable_data<int64_t>(PlaceType::kCPU);
    auto* w3_data = w3->mutable_data<int64_t>(PlaceType::kCPU);
    for (int i = 0; i < 4; i++) {
      w0_data[i] = i;
      w1_data[i] = i;
      w2_data[i] = i;
      w3_data[i] = i;
    }
    predictor->Run();
    predictor->TryShrinkMemory();
  }

  {
    Config config;
    config.SetModel(FLAGS_dirname);
    config.EnableMemoryOptim();
    config.EnableUseGpu(100, 0);

    auto predictor = CreatePredictor(config);

    predictor->RegisterOutputHook(hookfunc);
  }
}

719
}  // namespace paddle_infer