tensorrt_subgraph_pass.cc 14.4 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 <algorithm>
16
#include <map>
N
nhzlx 已提交
17
#include <set>
18

19
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
20
#include "paddle/fluid/framework/ir/subgraph_detector.h"
21
#include "paddle/fluid/inference/analysis/helper.h"
22
#include "paddle/fluid/inference/analysis/ir_passes/tensorrt_subgraph_pass.h"
N
nhzlx 已提交
23 24
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/engine.h"
25
#include "paddle/fluid/inference/tensorrt/op_teller.h"
Y
Yan Chunwei 已提交
26
#include "paddle/fluid/string/pretty_log.h"
27 28 29 30 31 32 33

namespace paddle {
namespace inference {
namespace analysis {

using framework::ir::Node;

34 35 36
void analysis::TensorRtSubgraphPass::ApplyImpl(
    framework::ir::Graph *graph) const {
  framework::ir::FusePassBase::Init("tensorrt_subgraph_pass", graph);
37 38 39 40
  auto enable_int8 = Get<bool>("enable_int8");
  auto use_calib_mode = Get<bool>("use_calib_mode");
  bool no_calib_int8 = enable_int8 && !(use_calib_mode);
  auto teller = [&](const framework::ir::Node *node) {
41
    if (!node->IsOp() || !node->Op()) return false;
42 43
    return tensorrt::OpTeller::Global().Tell(node->Op()->Type(), *node->Op(),
                                             no_calib_int8);
44
  };
45

46 47 48
  framework::ir::SubGraphFuser fuser(
      graph, teller, Get<int>("min_subgraph_size") /*min subgraph size*/,
      "tensorrt_engine");
49 50
  fuser();

51 52 53 54 55 56
  std::vector<std::string> graph_param_names =
      ExtractParameters(graph->Nodes());
  // those parameter already exist in trt, and should not have another copy in
  // fluid.
  std::vector<std::string> repetitive_params;

57
  for (auto *node : graph->Nodes()) {
58
    if (node->IsOp() && !framework::ir::Agent(node).subgraph()->empty()) {
59
      CreateTensorRTOp(node, graph, graph_param_names, &repetitive_params);
60 61

      std::unordered_set<const Node *> nodes2remove(
62 63
          framework::ir::Agent(node).subgraph()->begin(),
          framework::ir::Agent(node).subgraph()->end());
64
      framework::ir::GraphSafeRemoveNodes(graph, nodes2remove);
65 66 67 68 69
    }
  }

  std::unordered_set<const Node *> nodes2remove;
  for (auto *node : graph->Nodes()) {
70
    if (node->IsOp() && framework::ir::Agent(node).deleted()) {
71 72 73
      nodes2remove.insert(node);
    }
  }
74
  framework::ir::GraphSafeRemoveNodes(graph, nodes2remove);
75 76
  graph->Set(framework::ir::kRepetitiveParamAttr,
             new std::vector<std::string>(repetitive_params));
77 78
}

N
nhzlx 已提交
79
std::string GenerateEngineKey(const std::set<std::string> &engine_inputs,
N
nhzlx 已提交
80 81
                              const std::set<std::string> &engine_outputs,
                              const std::string &predictor_id) {
N
nhzlx 已提交
82 83 84 85 86 87 88
  std::string engine_hash_key = "";
  for (auto name : engine_inputs) {
    engine_hash_key += name;
  }
  for (auto name : engine_outputs) {
    engine_hash_key += name;
  }
N
nhzlx 已提交
89
  engine_hash_key += predictor_id;
N
nhzlx 已提交
90 91 92 93
  auto engine_key = std::to_string(std::hash<std::string>()(engine_hash_key));
  return engine_key;
}

94
void TensorRtSubgraphPass::CreateTensorRTOp(
95
    framework::ir::Node *node, framework::ir::Graph *graph,
96 97
    const std::vector<std::string> &graph_params,
    std::vector<std::string> *repetitive_params) const {
98
  auto *op_desc = node->Op();
99
  auto &subgraph = *framework::ir::Agent(node).subgraph();
100 101
  PADDLE_ENFORCE(!subgraph.empty());

N
nhzlx 已提交
102 103 104 105 106 107 108 109
  framework::ProgramDesc *program_desc =
      Get<framework::ProgramDesc *>("program");
  // Add new block for TensorRTEngineOP
  const framework::BlockDesc &main_block =
      program_desc->Block(framework::kRootBlockIndex);
  // const framework::BlockDesc& main_block = program_desc->Block(0);
  framework::BlockDesc *new_block = program_desc->AppendBlock(main_block);

110
  // A fake block desc.
111 112 113 114
  framework::proto::BlockDesc block_proto;
  framework::BlockDesc block_desc(nullptr, &block_proto);
  block_desc.Proto()->set_parent_idx(-1);
  block_desc.Proto()->set_idx(0);
115
  LOG(INFO) << "---  detect a sub-graph with " << subgraph.size() << " nodes";
Y
Yan Chunwei 已提交
116

117
  for (auto *node : subgraph) {
N
nhzlx 已提交
118
    auto *new_block_op = new_block->AppendOp();
119
    auto *op = block_desc.AppendOp();
N
nhzlx 已提交
120
    *new_block_op->Proto() = *node->Op()->Proto();
121 122 123
    *op->Proto() = *node->Op()->Proto();
  }

N
nhzlx 已提交
124
  // Then, we will use the input_names_with_id and output_names_with_id to
125
  // generate the engine key.
N
nhzlx 已提交
126 127
  // So, We use set instead of unordered_set here to ensure that the engine key
  // is unique.
N
nhzlx 已提交
128 129
  std::set<std::string> input_names;
  std::set<std::string> input_names_with_id;
130
  std::vector<std::string> params;
131 132 133
  // if we delete fluid copy of params shared by more than 1 ops, there will be
  // problem, so we filter them out.
  std::vector<std::string> params_not_shared;
134

135
  // The node->inputs contains input tensors and parameters.
136 137 138
  for (auto *x : node->inputs) {
    input_names.insert(x->Name());
    input_names_with_id.insert(x->Name() + std::to_string(x->id()));
139 140 141
    if (std::count(graph_params.begin(), graph_params.end(), x->Name()) > 0) {
      params.push_back(x->Name());
    }
142 143 144 145
    if (std::count(graph_params.begin(), graph_params.end(), x->Name()) > 0 &&
        x->outputs.size() <= 1) {
      params_not_shared.push_back(x->Name());
    }
146
  }
147

N
nhzlx 已提交
148 149
  std::set<std::string> output_names;
  std::set<std::string> output_names_with_id;
150 151 152 153 154 155
  for (auto *x : node->outputs) {
    output_names.insert(x->Name());
    output_names_with_id.insert(x->Name() + std::to_string(x->id()));
  }

  std::unordered_map<std::string, std::string> output_name_map;
156 157 158 159 160 161 162
  std::unordered_map<std::string, framework::ir::Node *> graph_var_map;

  for (framework::ir::Node *node : graph->Nodes()) {
    if (node->IsVar() && node->Var()) {
      graph_var_map[node->Name()] = node;
    }
  }
Z
Zhaolong Xing 已提交
163 164 165
  auto precision_mode = Get<AnalysisConfig::Precision>("precision_mode");
  bool enable_fp16 = false;
  if (precision_mode == AnalysisConfig::Precision::kHalf) enable_fp16 = true;
166 167
  auto enable_int8 = Get<bool>("enable_int8");
  auto use_calib_mode = Get<bool>("use_calib_mode");
168
  auto &subgraph_nodes = *framework::ir::Agent(node).subgraph();
169 170 171 172 173 174
  auto min_input_shape =
      Get<std::map<std::string, std::vector<int>>>("min_input_shape");
  auto max_input_shape =
      Get<std::map<std::string, std::vector<int>>>("max_input_shape");
  auto opt_input_shape =
      Get<std::map<std::string, std::vector<int>>>("optim_input_shape");
175 176 177 178 179 180 181 182 183 184 185 186 187

  // The following procedure is used to rename all the intermediate
  // variables and the output variables of the subgraph.
  // Why we do this?
  // During the transition from fluid OP to tensorrt OP, we map
  // the input and output Tensor(fluid data structure) of fluid OP
  // to the corresponding ITensor (trt data structure) through the
  // Tensor name. When we set up ITensor for an variable, we must
  // ensure that it has not been set before.
  // If there is variable in the fluid graph, which is not only the
  // input of a OP, but also the output of a Op, there will be problems.
  // So we have to rename the variable in the subgraph to make sure
  // it is either an OP's input or an OP's output.
N
nhzlx 已提交
188
  RenameAndGetOutputs(subgraph_nodes, &block_desc, input_names_with_id,
189
                      &output_names_with_id, &output_names, &output_name_map,
190
                      graph_var_map, !enable_int8);
191 192 193 194 195 196 197 198 199

  // When tensorrt engine runs at the end of the operation,
  // output_mapping help us copy the data from the renamed ITensor
  // to Tensor.
  std::vector<std::string> output_mapping;
  for (auto name : output_names) {
    PADDLE_ENFORCE(output_name_map.count(name) != 0);
    output_mapping.push_back(output_name_map[name]);
  }
200
  PADDLE_ENFORCE(!output_mapping.empty());
201 202
  PADDLE_ENFORCE(!block_desc.Proto()->vars().empty(),
                 "the block has no var-desc");
N
nhzlx 已提交
203

204 205
  // Set attrs
  op_desc->SetType("tensorrt_engine");
N
nhzlx 已提交
206 207 208 209 210 211
  op_desc->SetInput(
      "Xs", std::vector<std::string>(input_names.begin(), input_names.end()));

  op_desc->SetOutput(
      "Ys", std::vector<std::string>(output_names.begin(), output_names.end()));

N
nhzlx 已提交
212
  op_desc->SetBlockAttr("sub_block", new_block);
213 214 215 216 217 218
  op_desc->SetAttr("subgraph", block_desc.Proto()->SerializeAsString());
  op_desc->SetAttr("max_batch_size", Get<int>("max_batch_size"));
  op_desc->SetAttr("workspace_size", Get<int>("workspace_size"));
  op_desc->SetAttr("gpu_id", Get<int>("gpu_device_id"));
  op_desc->SetAttr("output_name_mapping", output_mapping);
  op_desc->SetAttr("parameters", params);
N
nhzlx 已提交
219

220 221 222 223 224
  // we record all inputs' shapes in attr to check if they are consistent
  // with the real inputs' shapes retrieved from scope when trt runs.
  for (auto *x : node->inputs) {
    if (x->IsVar() && x->Var()) {
      framework::VarDesc *var = x->Var();
225
      op_desc->SetAttr(var->Name() + "_shape", var->GetShape());
226 227 228
    }
  }

229
  auto use_static_engine = Get<bool>("use_static_engine");
230 231
  // TODO(NHZlX)
  // There are models with the same structure but the different parameters,
T
tianshuo78520a 已提交
232
  // when running in the 'use_serialize' mode, there is a bug.
N
nhzlx 已提交
233
  auto engine_key = GenerateEngineKey(input_names_with_id, output_names_with_id,
N
nhzlx 已提交
234
                                      std::to_string(0));
235
  auto predictor_id = Get<int>("predictor_id");
N
nhzlx 已提交
236

N
nhzlx 已提交
237
  // Get "" when there is no cached calibration table data.
238 239
  bool load_from_memory = Get<bool>("model_from_memory");
  std::string calibration_data = "";
240
  if (enable_int8 && use_calib_mode) {
241 242 243
    calibration_data = GetTrtCalibTableData(
        Get<std::string>("model_opt_cache_dir"), engine_key, enable_int8);
  }
244 245 246 247 248 249
  op_desc->SetAttr("calibration_data", calibration_data);
  op_desc->SetAttr("enable_int8", enable_int8);
  op_desc->SetAttr("enable_fp16", enable_fp16);
  op_desc->SetAttr("use_calib_mode", use_calib_mode);
  op_desc->SetAttr("engine_key", engine_key);
  op_desc->SetAttr("predictor_id", predictor_id);
N
nhzlx 已提交
250

251
  std::string trt_engine_serialized_data = "";
252 253
  op_desc->SetAttr("engine_serialized_data", trt_engine_serialized_data);
  op_desc->Flush();
N
nhzlx 已提交
254 255 256 257

  std::unique_ptr<tensorrt::TRTInt8Calibrator> calibrator;
  if (enable_int8 && calibration_data.size() != 0) {
    calibrator.reset(new tensorrt::TRTInt8Calibrator(calibration_data));
258
    LOG(INFO) << "RUN Paddle TRT int8 calibration mode...";
N
nhzlx 已提交
259 260 261
  }
  // When in int8 mode and calibration_mode, the program just produce the
  // calibration table data.
262 263
  bool calibration_mode =
      (enable_int8 && calibration_data.size() == 0 && use_calib_mode);
N
nhzlx 已提交
264 265 266 267
  if (calibration_mode) {
    // calibraion mode means generate int8 calibration table data process.
    return;
  }
N
nhzlx 已提交
268

269
  std::copy(params_not_shared.begin(), params_not_shared.end(),
N
nhzlx 已提交
270 271
            std::back_inserter(*repetitive_params));

272 273 274 275 276 277 278 279 280 281 282 283 284 285
  // Check trt version for dynamic shape input.

  if (min_input_shape.size() > 0 && TRT_VERSION < 6000) {
    LOG_FIRST_N(WARNING, 1) << "You are using the dynamic size input mode of "
                               "Paddle-TRT, but we found that the version of "
                               "the TensorRT is less than 6.0, so we use the "
                               "static shape mode instead.";
    min_input_shape = {};
    max_input_shape = {};
    opt_input_shape = {};
  }

  if (min_input_shape.size() > 0 && TRT_VERSION > 6000) {
    LOG_FIRST_N(WARNING, 1)
286
        << "The Paddle lib links the " << TRT_VERSION << " version TensorRT, "
287 288 289 290
        << "make sure the runtime TensorRT you are using is no less than this "
           "version, otherwise, there might be Segfault!";
  }

291 292 293 294 295
  // Setting the disable_trt_plugin_fp16 to true means that TRT plugin will not
  // run fp16.
  // When running fp16, the output accuracy of the model will be affected,
  // closing the plugin fp16 may bring some improvement on accuracy.
  bool disable_trt_plugin_fp16 = Get<bool>("disable_trt_plugin_fp16");
296 297 298 299
  tensorrt::TensorRTEngine *trt_engine =
      inference::Singleton<inference::tensorrt::TRTEngineManager>::Global()
          .Create(engine_key + std::to_string(predictor_id),
                  Get<int>("max_batch_size"), Get<int>("workspace_size"),
300
                  precision_mode, calibrator.get(), Get<int>("gpu_device_id"),
301 302
                  min_input_shape, max_input_shape, opt_input_shape,
                  disable_trt_plugin_fp16);
303 304

  bool need_serialize = (use_static_engine && !load_from_memory);
N
nhzlx 已提交
305 306 307 308 309
  if (need_serialize) {
    trt_engine_serialized_data = GetTrtEngineSerializedData(
        Get<std::string>("model_opt_cache_dir"), engine_key);
    // we can load the engine info serialized before from the disk.
    if (!trt_engine_serialized_data.empty()) {
310
      trt_engine->Deserialize(trt_engine_serialized_data);
N
nhzlx 已提交
311
      LOG(INFO) << "Load TRT Optimized Info from "
N
nhzlx 已提交
312 313
                << GetTrtEngineSerializedPath(
                       Get<std::string>("model_opt_cache_dir"), engine_key);
N
nhzlx 已提交
314
      return;
315 316 317
    }
  }

N
nhzlx 已提交
318 319 320 321 322
  // the following code will NOT run in following situation:
  // 1. calibraion mode (generate trt int8 calibraiton table data)
  // 2. already load serialized trt engine info.
  LOG(INFO) << "Prepare TRT engine (Optimize model structure, Select OP "
               "kernel etc). This process may cost a lot of time.";
323

N
nhzlx 已提交
324 325 326 327 328 329 330
  auto *scope = param_scope();
  framework::BlockDesc block_desc_temp(nullptr, block_desc.Proto());
  std::unordered_set<std::string> param_set(params.begin(), params.end());
  inference::Singleton<inference::tensorrt::OpConverter>::Global()
      .ConvertBlockToTRTEngine(
          &block_desc_temp, *scope,
          std::vector<std::string>(input_names.begin(), input_names.end()),
331
          param_set, output_mapping, trt_engine);
N
nhzlx 已提交
332 333

  if (need_serialize) {
334 335 336 337
    nvinfer1::IHostMemory *serialized_engine_data = trt_engine->Serialize();
    trt_engine_serialized_data =
        std::string((const char *)serialized_engine_data->data(),
                    serialized_engine_data->size());
N
nhzlx 已提交
338 339 340 341
    SaveTrtEngineSerializedDataToFile(
        GetTrtEngineSerializedPath(Get<std::string>("model_opt_cache_dir"),
                                   engine_key),
        trt_engine_serialized_data);
N
nhzlx 已提交
342 343 344
  }
}

345 346 347 348 349 350 351
}  // namespace analysis
}  // namespace inference
}  // namespace paddle

REGISTER_PASS(tensorrt_subgraph_pass,
              paddle::inference::analysis::TensorRtSubgraphPass)
    .RequirePassAttr("max_batch_size")
352 353
    .RequirePassAttr("workspace_size")
    .RequirePassAttr("min_subgraph_size");