ut_helper.h 7.6 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6
/* 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

7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yan Chunwei 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21

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
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
N
nhzlx 已提交
27
#include "paddle/fluid/framework/tensor_util.h"
Y
Yan Chunwei 已提交
28 29 30
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/engine.h"
31
#include "paddle/fluid/inference/utils/singleton.h"
Y
Yan Chunwei 已提交
32 33 34 35 36 37 38 39 40 41 42

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());
43
  std::uniform_real_distribution<double> dist(low, high);
Y
Yan Chunwei 已提交
44 45 46 47 48 49 50 51
  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);
N
nhzlx 已提交
52 53 54 55 56

  platform::CPUPlace cpu_place;
  framework::LoDTensor temp_tensor;
  temp_tensor.Resize(dims);
  auto* temp_data = temp_tensor.mutable_data<float>(cpu_place);
57

Y
Yan Chunwei 已提交
58
  for (size_t i = 0; i < num_elements; i++) {
N
nhzlx 已提交
59
    *(temp_data + i) = random(0., 1.);
Y
Yan Chunwei 已提交
60
  }
N
nhzlx 已提交
61 62

  TensorCopySync(temp_tensor, place, tensor);
Y
Yan Chunwei 已提交
63 64 65 66 67 68 69 70 71 72
}

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

73
  TRTConvertValidation(int max_batch_size,
74
                       const std::unordered_set<std::string>& parameters,
G
gongweibao 已提交
75
                       framework::Scope& scope,  // NOLINT
N
nhzlx 已提交
76
                       int workspace_size = 1 << 10, bool if_add_batch = true)
77 78
      : parameters_(parameters),
        scope_(scope),
N
nhzlx 已提交
79 80
        if_add_batch_(if_add_batch),
        max_batch_size_(max_batch_size) {
Y
Yan Chunwei 已提交
81
    PADDLE_ENFORCE_EQ(cudaStreamCreate(&stream_), 0);
N
nhzlx 已提交
82 83
    engine_.reset(new TensorRTEngine(max_batch_size, workspace_size, stream_));
    engine_->InitNetwork();
Y
Yan Chunwei 已提交
84 85 86
  }

  // Declare a Variable as input with random initialization.
N
nhzlx 已提交
87 88 89 90 91 92
  void DeclInputVar(const std::string& name, const std::vector<int> tensor_dims,
                    const nvinfer1::Dims& trt_dims) {
    DeclVar(name, tensor_dims);
    engine_->DeclareInput(name, nvinfer1::DataType::kFLOAT, trt_dims);
  }

Y
Yan Chunwei 已提交
93 94 95 96 97 98
  void DeclInputVar(const std::string& name, const nvinfer1::Dims& dims) {
    DeclVar(name, dims);
    // Declare TRT inputs.
    engine_->DeclareInput(name, nvinfer1::DataType::kFLOAT, dims);
  }

N
nhzlx 已提交
99 100 101 102
  void DeclParamVar(const std::string& name, const std::vector<int> dim_vec) {
    DeclVar(name, dim_vec);
  }

103 104
  // Declare a parameter varaible in the scope.
  void DeclParamVar(const std::string& name, const nvinfer1::Dims& dims) {
105
    DeclVar(name, dims, true);
106 107
  }

N
nhzlx 已提交
108 109 110 111
  void DeclOutputVar(const std::string& name, const std::vector<int> dim_vec) {
    DeclVar(name, dim_vec);
  }

Y
Yan Chunwei 已提交
112 113 114 115
  void DeclOutputVar(const std::string& name, const nvinfer1::Dims& dims) {
    DeclVar(name, dims);
  }

N
nhzlx 已提交
116
  void DeclVar(const std::string& name, const std::vector<int> dim_vec) {
N
nhzlx 已提交
117 118
    platform::CUDAPlace place;
    platform::CUDADeviceContext ctx(place);
Y
Yan Chunwei 已提交
119

N
nhzlx 已提交
120 121 122 123 124 125 126 127
    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);
  }
  // Declare a variable in a fluid Scope.
  void DeclVar(const std::string& name, const nvinfer1::Dims& dims,
               bool is_param = false) {
Y
Yan Chunwei 已提交
128
    // Init Fluid tensor.
129
    std::vector<int> dim_vec(dims.d, dims.d + dims.nbDims);
130
    // There is no batchsize in ITensor's shape, but We should add it to
N
nhzlx 已提交
131 132 133 134
    // tensor's shape of fluid. If the variable is not parameter and the
    // if_add_batch_ flag is true, add the max batchsize to dim_vec.
    if (is_param != true && if_add_batch_ == true)
      dim_vec.insert(dim_vec.begin(), max_batch_size_);
N
nhzlx 已提交
135 136

    DeclVar(name, dim_vec);
Y
Yan Chunwei 已提交
137 138 139 140 141
  }

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

142 143
    Singleton<OpConverter>::Global().ConvertOp(
        desc, parameters_, scope_, engine_.get(), true /*test_mode*/);
Y
Yan Chunwei 已提交
144 145 146 147

    engine_->FreezeNetwork();

    // Declare outputs.
F
fengjiayi 已提交
148
    op_desc_.reset(new framework::OpDesc(desc, nullptr));
Y
Yan Chunwei 已提交
149 150 151

    // Set Inputs.
    for (const auto& input : op_desc_->InputArgumentNames()) {
152
      if (parameters_.count(input)) continue;
Y
Yan Chunwei 已提交
153 154 155
      auto* var = scope_.FindVar(input);
      PADDLE_ENFORCE(var);
      auto tensor = var->GetMutable<framework::LoDTensor>();
156

N
nhzlx 已提交
157
      engine_->SetInputFromGPU(
158
          input, static_cast<void*>(tensor->data<void>()),
Y
Yan Chunwei 已提交
159 160 161 162 163
          sizeof(float) *
              analysis::AccuDims(tensor->dims(), tensor->dims().size()));
    }
  }

N
nhzlx 已提交
164 165 166
  // We use the set 'neglected_output' here, because some Ops like batch norm,
  // the outputs specified in the op des are only used during training,
  // so we should neglect those output during inference.
N
nhzlx 已提交
167 168
  void Execute(int batch_size,
               std::unordered_set<std::string> neglected_output = {}) {
Y
Yan Chunwei 已提交
169
    // Execute Fluid Op
N
nhzlx 已提交
170
    PADDLE_ENFORCE_LE(batch_size, max_batch_size_);
N
nhzlx 已提交
171 172
    platform::CUDAPlace place;
    platform::CUDADeviceContext ctx(place);
Y
Yan Chunwei 已提交
173
    op_->Run(scope_, place);
174 175
    // Execute TRT.
    engine_->Execute(batch_size);
N
nhzlx 已提交
176
    cudaStreamSynchronize(engine_->stream());
Y
Yan Chunwei 已提交
177 178

    ASSERT_FALSE(op_desc_->OutputArgumentNames().empty());
N
nhzlx 已提交
179
    const size_t output_space_size = 3000;
Y
Yan Chunwei 已提交
180
    for (const auto& output : op_desc_->OutputArgumentNames()) {
N
nhzlx 已提交
181
      if (neglected_output.count(output)) continue;
Y
Yan Chunwei 已提交
182
      std::vector<float> fluid_out;
183
      std::vector<float> trt_out(output_space_size);
N
nhzlx 已提交
184
      engine_->GetOutputInCPU(output, &trt_out[0], output_space_size);
N
nhzlx 已提交
185
      cudaStreamSynchronize(engine_->stream());
Y
Yan Chunwei 已提交
186 187 188 189

      auto* var = scope_.FindVar(output);
      auto tensor = var->GetMutable<framework::LoDTensor>();
      framework::TensorToVector(*tensor, ctx, &fluid_out);
N
nhzlx 已提交
190 191 192

      size_t fluid_out_size = fluid_out.size();
      if (if_add_batch_ == true) {
N
nhzlx 已提交
193 194
        fluid_out_size =
            batch_size * (framework::product(tensor->dims()) / max_batch_size_);
N
nhzlx 已提交
195
      }
Y
Yan Chunwei 已提交
196 197
      // Compare two output
      ASSERT_FALSE(fluid_out.empty());
N
nhzlx 已提交
198
      for (size_t i = 0; i < fluid_out_size; i++) {
199 200
        // Loose the threshold for CI in different machine model.
        EXPECT_LT(std::abs(fluid_out[i] - trt_out[i]), 2e-5);
Y
Yan Chunwei 已提交
201 202 203 204 205 206 207 208 209 210 211
      }
    }
  }

  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_;
212 213
  const std::unordered_set<std::string>& parameters_;
  framework::Scope& scope_;
N
nhzlx 已提交
214 215 216 217 218 219
  // The ITensor of trt does not cotain the batch size,
  // bug, in most cases, we need to set batch size for
  // fluid's tensor shape. This variable indicates
  // whether to add batch size to tensor shape of fluid.
  bool if_add_batch_;
  int max_batch_size_;
Y
Yan Chunwei 已提交
220 221 222 223 224
};

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