analysis_predictor.h 11.8 KB
Newer Older
Y
Yan Chunwei 已提交
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
#pragma once
16 17
#include <algorithm>
#include <map>
N
nhzlx 已提交
18
#include <memory>
19 20
#include <string>
#include <vector>
21
#include "paddle/fluid/framework/naive_executor.h"
22
#include "paddle/fluid/framework/op_compatible_info.h"
Y
Yan Chunwei 已提交
23 24
#include "paddle/fluid/inference/analysis/analyzer.h"
#include "paddle/fluid/inference/api/api_impl.h"
Y
Yan Chunwei 已提交
25
#include "paddle/fluid/inference/api/details/reset_tensor_array.h"
N
nhzlx 已提交
26
#include "paddle/fluid/inference/api/helper.h"
Y
Yan Chunwei 已提交
27
#include "paddle/fluid/inference/api/paddle_inference_api.h"
28
#include "paddle/fluid/string/printf.h"
29 30 31 32
#ifdef PADDLE_WITH_TESTING
#include <gtest/gtest.h>
#include <gtest/gtest_prod.h>
#endif
33 34 35 36 37 38 39 40 41 42 43 44

///
/// \file analysis_predictor.h
///
/// \brief Compared to NativePredictor, AnalysisPredictor is a high-performance
/// predictor that includes many optimizations
///
/// \author paddle-infer@baidu.com
/// \date 2020-01-01
/// \since 1.7.0
///

Y
Yan Chunwei 已提交
45 46 47 48 49
namespace paddle {

using inference::analysis::Argument;
using inference::analysis::Analyzer;
using framework::proto::ProgramDesc;
50
using framework::NaiveExecutor;
Y
Yan Chunwei 已提交
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
///
/// \class AnalysisPredictor
///
/// \brief The analysis predictor is based on the original native predictor with
/// IR and Analysis support. It will optimize IR and Parameters in the runtime.
///
/// The predictor has the following typical uses:
///
/// Get predictor
/// \code{cpp}
///   auto predictor = CreatePaddlePredictor(config);
/// \endcode
///
/// Get input or output names
/// \code{cpp}
///   auto input_names = predictor->GetInputNames();
///   auto output_names = predictor->GetOutputNames();
/// \endcode
///
/// Get input or output tensors
/// \code{cpp}
///   auto input_t = predictor->GetInputTensor(input_names[0]);
///   auto output_t = predictor->GetOutputTensor(output_names[0]);
/// \endcode
///
/// Run predictor
/// \code{cpp}
///   predictor->ZeroCopyRun();
/// \endcode
///
82
class AnalysisPredictor : public PaddlePredictor {
Y
Yan Chunwei 已提交
83
 public:
84 85 86 87 88
  ///
  /// \brief Construct a new Analysis Predictor object
  ///
  /// \param[in] AnalysisConfig config
  ///
89 90 91
  explicit AnalysisPredictor(const AnalysisConfig &config) : config_(config) {
    predictor_id_ = inference::GetUniqueId();
  }
92 93 94
  ///
  /// \brief Destroy the Analysis Predictor object
  ///
F
flame 已提交
95
  ~AnalysisPredictor();
Y
Yan Chunwei 已提交
96

97 98 99 100 101 102 103 104 105 106 107 108
  ///
  /// \brief Initialize predictor
  ///
  /// Initializing predictor mainly includes the following tasks:
  /// preparing scope, creating executor, preparing program, initializing the
  /// variables required by the executor, getting the feed_target_names and
  /// fetch_target_names, etc.
  ///
  /// \param[in] parent_scope parent scope
  /// \param[in] program program
  /// \return Whether the init function executed successfully
  ///
109 110
  bool Init(const std::shared_ptr<framework::Scope> &parent_scope,
            const std::shared_ptr<framework::ProgramDesc> &program = nullptr);
Y
Yan Chunwei 已提交
111

112 113 114 115 116 117 118 119
  ///
  /// \brief Run the prediction engine. Deprecated. Please refer to ZeroCopyRun
  ///
  /// \param[in] inputs input tensors
  /// \param[out] output_data output tensors
  /// \param[in] batch_size data's batch size
  /// \return Whether the function executed successfully
  ///
120 121 122 123
  bool Run(const std::vector<PaddleTensor> &inputs,
           std::vector<PaddleTensor> *output_data,
           int batch_size = -1) override;

124 125 126 127 128
  ///
  /// \brief Get the input names
  ///
  /// \return input names
  ///
N
nhzlx 已提交
129
  std::vector<std::string> GetInputNames();
130 131 132 133 134
  ///
  /// \brief Get the output names
  ///
  /// \return output names
  ///
N
nhzlx 已提交
135 136
  std::vector<std::string> GetOutputNames();

137 138 139 140 141 142
  ///
  /// \brief Get the Input Tensor object
  ///
  /// \param[in] name input name
  /// \return input tensor
  ///
143 144
  std::unique_ptr<ZeroCopyTensor> GetInputTensor(
      const std::string &name) override;
145 146 147 148 149 150
  ///
  /// \brief Get the Output Tensor object
  ///
  /// \param[in] name otuput name
  /// \return output tensor
  ///
151 152
  std::unique_ptr<ZeroCopyTensor> GetOutputTensor(
      const std::string &name) override;
153 154 155 156 157
  ///
  /// \brief Get all input names and their corresponding shapes
  ///
  /// \return the map of input names and shapes
  ///
158 159
  std::map<std::string, std::vector<int64_t>> GetInputTensorShape() override;

160 161 162 163 164
  ///
  /// \brief Run the prediction engine
  ///
  /// \return Whether the function executed successfully
  ///
165 166
  bool ZeroCopyRun() override;

167 168 169 170 171
  ///
  /// \brief Create feed fetch variables
  ///
  /// \param[in] scope Scope needed to create variables
  ///
172
  void CreateFeedFetchVar(framework::Scope *scope);
173 174 175 176
  ///
  /// \brief Determine the model's inputs and outputs based on the program's
  /// feed fetch op
  ///
177
  void PrepareFeedFetch();
Y
Yan Chunwei 已提交
178

179 180 181 182
  ///
  /// \brief Set predictor's argument according to config, which mainly includes
  /// execution information and graph optimization related pass information
  ///
183
  void PrepareArgument();
184 185 186 187
  ///
  /// \brief According to argument information, execute the relevant pass
  /// to get the optimized model program
  ///
Y
Yan Chunwei 已提交
188 189
  void OptimizeInferenceProgram();

190 191 192 193 194
  ///
  /// \brief Get the argument used by predictor
  ///
  /// \return the argument obtained by config
  ///
195
  Argument &analysis_argument() { return argument_; }
196 197 198 199 200
  ///
  /// \brief Clone to get the new predictor. thread safe.
  ///
  /// \return get a new predictor
  ///
201
  std::unique_ptr<PaddlePredictor> Clone() override;
202 203 204 205 206
  ///
  /// \brief Get the scope used by predictor
  ///
  /// \return scope
  ///
207
  framework::Scope *scope() { return scope_.get(); }
208 209 210 211 212
  ///
  /// \brief Get the inference program
  ///
  /// \return the inference program
  ///
213 214
  framework::ProgramDesc &program() { return *inference_program_; }

215 216 217 218 219
  ///
  /// \brief Get the serialized program
  ///
  /// \return the serialized program
  ///
220
  std::string GetSerializedProgram() const override;
Y
Yan Chunwei 已提交
221

222 223 224 225 226
  ///
  /// \brief Initialize mkldnn quantizer and execute mkldnn quantization pass
  ///
  /// \return Whether the function executed successfully
  ///
227 228
  bool MkldnnQuantize();

229 230 231 232 233
  ///
  /// \brief save program to model and save parameters to params
  ///
  /// \param[in] dir path to save the model
  ///
234 235
  void SaveOptimModel(const std::string &dir);

236
 protected:
237 238 239 240 241 242 243
  ///
  /// \brief Prepare predictor's required programs, including loading model
  /// information, graph optimization, and executor creation variables, etc.
  ///
  /// \param[in] program paddle program
  /// \return Whether the function executed successfully
  ///
244
  bool PrepareProgram(const std::shared_ptr<framework::ProgramDesc> &program);
245 246 247 248 249 250
  ///
  /// \brief Prepare scope environment, each predictor has its own scope
  ///
  /// \param[in] parent_scope The scope of the predictor to be cloned, or null
  /// \return Whether the function executed successfully
  ///
251
  bool PrepareScope(const std::shared_ptr<framework::Scope> &parent_scope);
252 253 254 255 256
  ///
  /// \brief Create an Executor object
  ///
  /// \return Whether the function executed successfully
  ///
257
  bool CreateExecutor();
258 259 260 261 262
  ///
  /// \brief According to the model's program, the executor creates ops
  ///
  /// \return Whether the function executed successfully
  ///
263 264
  bool PrepareExecutor();

265 266 267 268 269
  ///
  /// \brief Load model program.
  ///
  /// \return Whether the function executed successfully
  ///
270
  bool LoadProgramDesc();
271 272 273 274 275
  ///
  /// \brief Load model parameters.
  ///
  /// \return Whether the function executed successfully
  ///
276
  bool LoadParameters();
277

278 279 280 281 282 283 284
  ///
  /// \brief Prepare input data, only used in Run()
  ///
  /// \param[in] input_datas inpute tensors
  /// \param[in] scope the scope used by predictor
  /// \return Whether the function executed successfully
  ///
285 286
  bool SetFeed(const std::vector<PaddleTensor> &input_datas,
               framework::Scope *scope);
287 288 289 290 291 292 293
  ///
  /// \brief Get the output data, only used in Run()
  ///
  /// \param[out] output_data output tensors
  /// \param[in] scope the scope used by predictor
  /// \return Whether the function executed successfully
  ///
294 295
  bool GetFetch(std::vector<PaddleTensor> *output_data,
                framework::Scope *scope);
296 297 298 299 300 301
  ///
  /// \brief Get the output data, only used in GetFetch()
  ///
  /// \param[in] tensor for fetch op
  /// \param[out] output_data output tensor
  ///
302 303 304
  template <typename T>
  void GetFetchOne(const framework::LoDTensor &fetchs,
                   PaddleTensor *output_data);
305 306 307 308 309 310 311 312
  ///
  /// \brief PreSet for Mkldnn multi-thread and dynamic shape input.
  ///
  /// Used in AnalysisPredictor::Run(), do not support
  /// AnalysisPredictor::ZeroCopyRun() now.
  ///
  /// \param[in] inputs tensors
  ///
313
  void MkldnnPreSet(const std::vector<PaddleTensor> &inputs);
314 315 316 317 318 319
  ///
  /// \brief PostReset for Mkldnn multi-thread and dynamic shape input.
  ///
  /// Used in AnalysisPredictor::Run(), do not support
  /// AnalysisPredictor::ZeroCopyRun() now.
  ///
320
  void MkldnnPostReset();
321 322 323 324 325 326
  ///
  /// \brief Compute compatibility based on model version information and
  /// operator version information
  ///
  /// \return Compatible information
  ///
327
  bool CheckOperatorCompatible();
Y
Yan Chunwei 已提交
328

N
nhzlx 已提交
329
#if PADDLE_WITH_TENSORRT
330 331 332 333 334 335 336 337 338 339 340 341 342 343
  ///
  /// \brief save calibration table
  ///
  /// When we use Paddle-TRT INT8 engine, we need to generate calibration table
  /// data first,
  /// the calibration table contains the range for each op's input and output,
  /// this whole process can be divided into several steps:
  /// 1. Builds a 32-bit engine, runs it on the calibration set, and records a
  ///  histogram for each tensor of the distribution of activation values.
  /// 2. Builds a calibration table from the histograms.
  /// After step 2, we need to store the calibration table on disk.
  ///
  /// \return Whether the function executed successfully
  ///
N
nhzlx 已提交
344
  bool SaveTrtCalibToDisk();
N
nhzlx 已提交
345
#endif
N
nhzlx 已提交
346

347 348 349 350 351 352 353 354
// Some more detailed tests, they are made the friends of the predictor, so that
// the all the details can be tested.
#if PADDLE_WITH_TESTING
  FRIEND_TEST(AnalysisPredictor, analysis_off);
  FRIEND_TEST(AnalysisPredictor, analysis_on);
  FRIEND_TEST(AnalysisPredictor, with_gpu);
#endif

Y
Yan Chunwei 已提交
355
 private:
356
  AnalysisConfig config_;
Y
Yan Chunwei 已提交
357
  Argument argument_;
358 359 360 361 362
  std::unique_ptr<NaiveExecutor> executor_;
  platform::Place place_;
  std::shared_ptr<framework::Scope> scope_;
  framework::Scope *sub_scope_{nullptr};
  std::shared_ptr<framework::ProgramDesc> inference_program_;
363
  framework::OpCompatibleMap op_compatible_map_;
364 365
  std::vector<framework::OpDesc *> feeds_;
  std::map<std::string, size_t> feed_names_;
N
nhzlx 已提交
366 367
  // Sorted according to the idx.
  std::map<size_t, std::string> idx2feeds_;
Y
Yan Chunwei 已提交
368
  std::vector<framework::OpDesc *> fetches_;
N
nhzlx 已提交
369 370
  std::map<size_t, std::string> idx2fetches_;

371 372 373 374 375 376 377 378 379 380
#if PADDLE_WITH_MKLDNN
  // Helper class to perform quantization
  class MkldnnQuantizer;
  MkldnnQuantizer *mkldnn_quantizer_{nullptr};

#if PADDLE_WITH_TESTING
  friend class MkldnnQuantizerTest;
#endif
#endif

381
  // Memory buffer for feed inputs. The temporary LoDTensor will cause serious
382
  // concurrency problems, wrong results and memory leak, so cache them.
383
  std::vector<framework::LoDTensor> feed_tensors_;
Y
Yan Chunwei 已提交
384
  details::TensorArrayBatchCleaner tensor_array_batch_cleaner_;
Y
Yan Chunwei 已提交
385 386
  // A mutex help to make Clone thread safe.
  std::mutex clone_mutex_;
387

Y
Yan Chunwei 已提交
388 389 390 391
  // For memory optimization.
  const size_t max_shape_collect_count_{1000};
  int need_collect_var_shapes_{-1};  // -1 for default, 0 for false, 1 for true.
  std::vector<std::map<std::string, std::vector<int>>> batch_var_shapes_;
392
  int predictor_id_;
Y
Yan Chunwei 已提交
393

394 395 396 397
 private:
  // Some status here that help to determine the status inside the predictor.
  bool status_is_cloned_{false};
  bool status_use_gpu_{false};
Y
Yan Chunwei 已提交
398 399 400
};

}  // namespace paddle