ut_helper.h 8.9 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

N
nhzlx 已提交
22
#include <memory>
23
#include <string>
N
nhzlx 已提交
24
#include <unordered_set>
25 26
#include <vector>

Y
Yan Chunwei 已提交
27 28
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
N
nhzlx 已提交
29
#include "paddle/fluid/framework/tensor_util.h"
Y
Yan Chunwei 已提交
30 31 32
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/engine.h"
33
#include "paddle/fluid/inference/utils/singleton.h"
Y
Yan Chunwei 已提交
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) {
43
  static std::mt19937 mt(100);
44
  std::uniform_real_distribution<double> dist(low, high);
Y
Yan Chunwei 已提交
45 46 47
  return dist(mt);
}

48
void RandomizeTensor(phi::DenseTensor* tensor,
49
                     const platform::Place& place,
Y
Yan Chunwei 已提交
50 51 52
                     const platform::DeviceContext& ctx) {
  auto dims = tensor->dims();
  size_t num_elements = analysis::AccuDims(dims, dims.size());
S
Shang Zhizhou 已提交
53
  PADDLE_ENFORCE_GT(
54 55
      num_elements,
      0UL,
S
Shang Zhizhou 已提交
56 57
      platform::errors::PermissionDenied("RandomizeTensor only can be used for "
                                         "tensor which dims is not zero."));
N
nhzlx 已提交
58 59

  platform::CPUPlace cpu_place;
60
  phi::DenseTensor temp_tensor;
N
nhzlx 已提交
61 62
  temp_tensor.Resize(dims);
  auto* temp_data = temp_tensor.mutable_data<float>(cpu_place);
63

Y
Yan Chunwei 已提交
64
  for (size_t i = 0; i < num_elements; i++) {
N
nhzlx 已提交
65
    *(temp_data + i) = random(0., 1.);
Y
Yan Chunwei 已提交
66
  }
N
nhzlx 已提交
67

68
  paddle::framework::TensorCopySync(temp_tensor, place, tensor);
Y
Yan Chunwei 已提交
69 70 71 72 73 74 75 76 77 78
}

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

79
  TRTConvertValidation(int max_batch_size,
80
                       const std::unordered_set<std::string>& parameters,
G
gongweibao 已提交
81
                       framework::Scope& scope,  // NOLINT
82
                       int64_t workspace_size = 1 << 30,
83
                       bool if_add_batch = true)
84 85
      : parameters_(parameters),
        scope_(scope),
N
nhzlx 已提交
86 87
        if_add_batch_(if_add_batch),
        max_batch_size_(max_batch_size) {
88 89
    PADDLE_ENFORCE_EQ(cudaStreamCreate(&stream_),
                      0,
S
Shang Zhizhou 已提交
90
                      platform::errors::External("cudaStreamCreate error."));
91 92 93 94
    TensorRTEngine::ConstructionParams params;
    params.max_batch_size = max_batch_size;
    params.max_workspace_size = workspace_size;
    engine_ = std::make_unique<TensorRTEngine>(params);
N
nhzlx 已提交
95
    engine_->InitNetwork();
Y
Yan Chunwei 已提交
96 97 98
  }

  // Declare a Variable as input with random initialization.
99 100
  void DeclInputVar(const std::string& name,
                    const std::vector<int> tensor_dims,
N
nhzlx 已提交
101 102 103 104 105
                    const nvinfer1::Dims& trt_dims) {
    DeclVar(name, tensor_dims);
    engine_->DeclareInput(name, nvinfer1::DataType::kFLOAT, trt_dims);
  }

Y
Yan Chunwei 已提交
106 107 108 109 110 111
  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 已提交
112 113 114 115
  void DeclParamVar(const std::string& name, const std::vector<int> dim_vec) {
    DeclVar(name, dim_vec);
  }

T
tianshuo78520a 已提交
116
  // Declare a parameter variable in the scope.
117
  void DeclParamVar(const std::string& name, const nvinfer1::Dims& dims) {
118
    DeclVar(name, dims, true);
119 120
  }

N
nhzlx 已提交
121 122 123 124
  void DeclOutputVar(const std::string& name, const std::vector<int> dim_vec) {
    DeclVar(name, dim_vec);
  }

Y
Yan Chunwei 已提交
125 126 127 128
  void DeclOutputVar(const std::string& name, const nvinfer1::Dims& dims) {
    DeclVar(name, dims);
  }

N
nhzlx 已提交
129
  void DeclVar(const std::string& name, const std::vector<int> dim_vec) {
L
Leo Chen 已提交
130
    phi::GPUContext ctx(place_);
Y
Yan Chunwei 已提交
131

N
nhzlx 已提交
132
    auto* x = scope_.Var(name);
133
    auto* x_tensor = x->GetMutable<phi::DenseTensor>();
134
    x_tensor->Resize(phi::make_ddim(dim_vec));
N
nhzlx 已提交
135
    RandomizeTensor(x_tensor, place_, ctx);
N
nhzlx 已提交
136 137
  }
  // Declare a variable in a fluid Scope.
138 139
  void DeclVar(const std::string& name,
               const nvinfer1::Dims& dims,
N
nhzlx 已提交
140
               bool is_param = false) {
Y
Yan Chunwei 已提交
141
    // Init Fluid tensor.
142
    std::vector<int> dim_vec(dims.d, dims.d + dims.nbDims);
143
    // There is no batchsize in ITensor's shape, but We should add it to
N
nhzlx 已提交
144 145 146 147
    // 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 已提交
148 149

    DeclVar(name, dim_vec);
Y
Yan Chunwei 已提交
150 151 152 153 154
  }

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

155 156
    Singleton<OpConverter>::Global().ConvertOp(
        desc, parameters_, scope_, engine_.get(), true /*test_mode*/);
Y
Yan Chunwei 已提交
157 158 159 160

    engine_->FreezeNetwork();

    // Declare outputs.
161
    op_desc_ = std::make_unique<framework::OpDesc>(desc, nullptr);
Y
Yan Chunwei 已提交
162 163
  }

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
170 171
    PADDLE_ENFORCE_LE(batch_size,
                      max_batch_size_,
S
Shang Zhizhou 已提交
172 173 174 175
                      platform::errors::InvalidArgument(
                          "Runtime batch_size should be less than or equal to "
                          "max_batch_size_. "
                          "But received batch_size:%d, max_batch_size_:%d",
176 177
                          batch_size,
                          max_batch_size_));
L
Leo Chen 已提交
178
    phi::GPUContext ctx(place_);
N
nhzlx 已提交
179
    op_->Run(scope_, place_);
180
    cudaStreamSynchronize(stream_);
N
nhzlx 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    std::vector<std::string> input_output_names;

    // Note: we need filter the parameter
    for (const auto& input : op_desc_->InputArgumentNames()) {
      if (parameters_.count(input)) continue;
      input_output_names.push_back(input);
    }

    // Collect the fluid outputs.
    std::vector<std::vector<float>> fluid_outs;
    for (const auto& output : op_desc_->OutputArgumentNames()) {
      if (neglected_output.count(output)) continue;
      input_output_names.push_back(output);
      std::vector<float> fluid_out;
      auto* var = scope_.FindVar(output);
196
      auto* tensor = var->GetMutable<phi::DenseTensor>();
N
nhzlx 已提交
197 198 199 200 201 202 203 204 205 206
      framework::TensorToVector(*tensor, ctx, &fluid_out);
      fluid_outs.push_back(fluid_out);
    }

    // Bind input and output for TRT.
    const int num_bindings = input_output_names.size();
    std::vector<void*> buffers(num_bindings);

    for (const std::string& name : input_output_names) {
      auto* var = scope_.FindVar(name);
207
      auto* tensor = var->GetMutable<phi::DenseTensor>();
N
nhzlx 已提交
208 209
      const int bind_index = engine_->engine()->getBindingIndex(name.c_str());
      buffers[bind_index] =
N
nhzlx 已提交
210
          static_cast<void*>(tensor->mutable_data<float>(place_));
N
nhzlx 已提交
211 212
    }

213
    // Execute TRT.
214
    engine_->Execute(batch_size, &buffers, stream_);
215
    cudaStreamSynchronize(stream_);
Y
Yan Chunwei 已提交
216 217

    ASSERT_FALSE(op_desc_->OutputArgumentNames().empty());
N
nhzlx 已提交
218
    int index = 0;
Y
Yan Chunwei 已提交
219
    for (const auto& output : op_desc_->OutputArgumentNames()) {
N
nhzlx 已提交
220
      if (neglected_output.count(output)) continue;
N
nhzlx 已提交
221
      std::vector<float> trt_out;
Y
Yan Chunwei 已提交
222
      auto* var = scope_.FindVar(output);
223
      auto* tensor = var->GetMutable<phi::DenseTensor>();
N
nhzlx 已提交
224
      framework::TensorToVector(*tensor, ctx, &trt_out);
N
nhzlx 已提交
225

N
nhzlx 已提交
226
      size_t fluid_out_size = fluid_outs[index].size();
N
nhzlx 已提交
227
      if (if_add_batch_ == true) {
N
nhzlx 已提交
228
        fluid_out_size =
229
            batch_size * (phi::product(tensor->dims()) / max_batch_size_);
N
nhzlx 已提交
230
      }
N
nhzlx 已提交
231

N
nhzlx 已提交
232
      for (size_t i = 0; i < fluid_out_size; i++) {
233
        // Loose the threshold for CI in different machine model.
N
nhzlx 已提交
234
        EXPECT_LT(std::abs(fluid_outs[index][i] - trt_out[i]), 2e-5);
Y
Yan Chunwei 已提交
235
      }
N
nhzlx 已提交
236
      index += 1;
Y
Yan Chunwei 已提交
237 238 239 240 241 242
    }
  }

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

 private:
N
nhzlx 已提交
243
  platform::CUDAPlace place_;
Y
Yan Chunwei 已提交
244 245 246 247
  std::unique_ptr<TensorRTEngine> engine_;
  cudaStream_t stream_;
  std::unique_ptr<framework::OperatorBase> op_;
  std::unique_ptr<framework::OpDesc> op_desc_;
248 249
  const std::unordered_set<std::string>& parameters_;
  framework::Scope& scope_;
N
nhzlx 已提交
250 251 252 253 254 255
  // 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 已提交
256 257 258 259 260
};

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