ut_helper.h 5.5 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 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. */

/*
 * This file implements a UT framework to make the validation of transforming
 * Fluid Op to TRT Layer.
 */

#pragma once

22 23 24
#include <string>
#include <vector>

Y
Yan Chunwei 已提交
25 26 27 28 29
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/engine.h"
30
#include "paddle/fluid/inference/utils/singleton.h"
Y
Yan Chunwei 已提交
31 32 33 34 35 36 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 64

namespace paddle {
namespace inference {
namespace tensorrt {

/*
 * Get a random float value between [low, high]
 */
float random(float low, float high) {
  static std::random_device rd;
  static std::mt19937 mt(rd());
  std::uniform_real_distribution<double> dist(1.0, 10.0);
  return dist(mt);
}

void RandomizeTensor(framework::LoDTensor* tensor, const platform::Place& place,
                     const platform::DeviceContext& ctx) {
  auto dims = tensor->dims();
  size_t num_elements = analysis::AccuDims(dims, dims.size());
  PADDLE_ENFORCE_GT(num_elements, 0);
  auto* data = tensor->mutable_data<float>(place);
  for (size_t i = 0; i < num_elements; i++) {
    *(data + i) = random(0., 1.);
  }
}

/*
 * Help to validate the correctness between Fluid Op and the corresponding TRT
 * layer.
 */
class TRTConvertValidation {
 public:
  TRTConvertValidation() = delete;

65 66
  TRTConvertValidation(int batch_size,
                       const std::unordered_set<std::string>& parameters,
G
gongweibao 已提交
67 68
                       framework::Scope& scope,  // NOLINT
                       int workspace_size = 1 << 10)
69
      : parameters_(parameters), scope_(scope) {
Y
Yan Chunwei 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83
    // create engine.
    engine_.reset(new TensorRTEngine(10, 1 << 10, &stream_));
    engine_->InitNetwork();

    PADDLE_ENFORCE_EQ(cudaStreamCreate(&stream_), 0);
  }

  // Declare a Variable as input with random initialization.
  void DeclInputVar(const std::string& name, const nvinfer1::Dims& dims) {
    DeclVar(name, dims);
    // Declare TRT inputs.
    engine_->DeclareInput(name, nvinfer1::DataType::kFLOAT, dims);
  }

84 85 86 87 88
  // Declare a parameter varaible in the scope.
  void DeclParamVar(const std::string& name, const nvinfer1::Dims& dims) {
    DeclVar(name, dims);
  }

Y
Yan Chunwei 已提交
89 90 91 92
  void DeclOutputVar(const std::string& name, const nvinfer1::Dims& dims) {
    DeclVar(name, dims);
  }

93
  // Declare a variable in a fluid Scope.
Y
Yan Chunwei 已提交
94 95 96 97 98
  void DeclVar(const std::string& name, const nvinfer1::Dims& dims) {
    platform::CPUPlace place;
    platform::CPUDeviceContext ctx(place);

    // Init Fluid tensor.
99
    std::vector<int> dim_vec(dims.d, dims.d + dims.nbDims);
Y
Yan Chunwei 已提交
100 101 102 103 104 105 106 107 108
    auto* x = scope_.Var(name);
    auto* x_tensor = x->GetMutable<framework::LoDTensor>();
    x_tensor->Resize(framework::make_ddim(dim_vec));
    RandomizeTensor(x_tensor, place, ctx);
  }

  void SetOp(const framework::proto::OpDesc& desc) {
    op_ = framework::OpRegistry::CreateOp(desc);

109 110
    Singleton<OpConverter>::Global().ConvertOp(
        desc, parameters_, scope_, engine_.get(), true /*test_mode*/);
Y
Yan Chunwei 已提交
111 112 113 114

    engine_->FreezeNetwork();

    // Declare outputs.
F
fengjiayi 已提交
115
    op_desc_.reset(new framework::OpDesc(desc, nullptr));
Y
Yan Chunwei 已提交
116 117 118

    // Set Inputs.
    for (const auto& input : op_desc_->InputArgumentNames()) {
119
      if (parameters_.count(input)) continue;
Y
Yan Chunwei 已提交
120 121 122
      auto* var = scope_.FindVar(input);
      PADDLE_ENFORCE(var);
      auto tensor = var->GetMutable<framework::LoDTensor>();
123

Y
Yan Chunwei 已提交
124
      engine_->SetInputFromCPU(
125
          input, static_cast<void*>(tensor->data<void>()),
Y
Yan Chunwei 已提交
126 127 128 129 130 131 132 133 134 135
          sizeof(float) *
              analysis::AccuDims(tensor->dims(), tensor->dims().size()));
    }
  }

  void Execute(int batch_size) {
    // Execute Fluid Op
    platform::CPUPlace place;
    platform::CPUDeviceContext ctx(place);
    op_->Run(scope_, place);
136 137 138
    // Execute TRT.
    engine_->Execute(batch_size);
    cudaStreamSynchronize(*engine_->stream());
Y
Yan Chunwei 已提交
139 140

    ASSERT_FALSE(op_desc_->OutputArgumentNames().empty());
141
    const size_t output_space_size = 200;
Y
Yan Chunwei 已提交
142 143
    for (const auto& output : op_desc_->OutputArgumentNames()) {
      std::vector<float> fluid_out;
144 145 146 147
      std::vector<float> trt_out(output_space_size);
      engine_->GetOutputInCPU(output, &trt_out[0],
                              output_space_size * sizeof(float));
      cudaStreamSynchronize(*engine_->stream());
Y
Yan Chunwei 已提交
148 149 150 151 152 153 154

      auto* var = scope_.FindVar(output);
      auto tensor = var->GetMutable<framework::LoDTensor>();
      framework::TensorToVector(*tensor, ctx, &fluid_out);
      // Compare two output
      ASSERT_FALSE(fluid_out.empty());
      for (size_t i = 0; i < fluid_out.size(); i++) {
155 156
        // Loose the threshold for CI in different machine model.
        EXPECT_LT(std::abs(fluid_out[i] - trt_out[i]), 2e-5);
Y
Yan Chunwei 已提交
157 158 159 160 161 162 163 164 165 166 167
      }
    }
  }

  framework::Scope& scope() { return scope_; }

 private:
  std::unique_ptr<TensorRTEngine> engine_;
  cudaStream_t stream_;
  std::unique_ptr<framework::OperatorBase> op_;
  std::unique_ptr<framework::OpDesc> op_desc_;
168 169
  const std::unordered_set<std::string>& parameters_;
  framework::Scope& scope_;
Y
Yan Chunwei 已提交
170 171 172 173 174
};

}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle