helper.h 8.1 KB
Newer Older
1 2
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Y
Yan Chunwei 已提交
3 4 5
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
6

Y
Yan Chunwei 已提交
7
http://www.apache.org/licenses/LICENSE-2.0
8

Y
Yan Chunwei 已提交
9 10 11 12 13
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. */
14 15 16

#pragma once

17
#include <sys/stat.h>
18

19
#include <cstdio>
Y
Yan Chunwei 已提交
20
#include <fstream>
N
nhzlx 已提交
21
#include <memory>
N
nhzlx 已提交
22
#include <set>
23
#include <string>
S
sneaxiy 已提交
24
#include <typeindex>
25
#include <unordered_map>
N
nhzlx 已提交
26
#include <utility>
27 28
#include <vector>

29 30
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/variable.h"
31
#include "paddle/fluid/platform/enforce.h"
32
#include "paddle/phi/backends/dynload/port.h"
33

Y
Yan Chunwei 已提交
34
#ifdef _WIN32
N
nhzlx 已提交
35 36
#include <direct.h>
#include <io.h>
37
#define GCC_ATTRIBUTE(attr__)
N
nhzlx 已提交
38
#define MKDIR(path) _mkdir(path)
Y
Yan Chunwei 已提交
39
#else
N
nhzlx 已提交
40
#include <unistd.h>
Y
Yan Chunwei 已提交
41
#define GCC_ATTRIBUTE(attr__) __attribute__((attr__));
N
nhzlx 已提交
42
#define MKDIR(path) mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
Y
Yan Chunwei 已提交
43 44 45
#endif
#define __SHOULD_USE_RESULT__ GCC_ATTRIBUTE(warn_unused_result)

46 47 48 49
namespace paddle {
namespace inference {
namespace analysis {

50 51 52 53
template <typename T>
void SetAttr(framework::proto::OpDesc *op, const std::string &name,
             const T &data);

Y
Yan Chunwei 已提交
54 55 56 57 58 59 60 61 62
template <typename Vec>
int AccuDims(Vec &&vec, int size) {
  int res = 1;
  for (int i = 0; i < size; i++) {
    res *= std::forward<Vec>(vec)[i];
  }
  return res;
}

S
sneaxiy 已提交
63
#define SET_TYPE(type__) dic_[std::type_index(typeid(type__))] = #type__;
64 65 66 67 68 69 70 71 72 73 74
/*
 * Map typeid to representation.
 */
struct DataTypeNamer {
  static const DataTypeNamer &Global() {
    static auto *x = new DataTypeNamer();
    return *x;
  }

  template <typename T>
  const std::string &repr() const {
S
sneaxiy 已提交
75
    auto x = std::type_index(typeid(T));
76 77 78
    PADDLE_ENFORCE_GT(dic_.count(x), 0,
                      platform::errors::PreconditionNotMet(
                          "unknown type for representation"));
79 80 81
    return dic_.at(x);
  }

S
sneaxiy 已提交
82
  const std::string &repr(const std::type_index &type) const {  // NOLINT
83 84 85
    PADDLE_ENFORCE_GT(dic_.count(type), 0,
                      platform::errors::PreconditionNotMet(
                          "unknown type for representation"));
S
sneaxiy 已提交
86
    return dic_.at(type);
87 88 89 90 91 92 93
  }

 private:
  DataTypeNamer() {
    SET_TYPE(int);
    SET_TYPE(bool);
    SET_TYPE(float);
Y
Yan Chunwei 已提交
94
    SET_TYPE(void *);
95 96
  }

S
sneaxiy 已提交
97
  std::unordered_map<std::type_index, std::string> dic_;
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
};
#undef SET_TYPE

template <typename IteratorT>
class iterator_range {
  IteratorT begin_, end_;

 public:
  template <typename Container>
  explicit iterator_range(Container &&c) : begin_(c.begin()), end_(c.end()) {}

  iterator_range(const IteratorT &begin, const IteratorT &end)
      : begin_(begin), end_(end) {}

  const IteratorT &begin() const { return begin_; }
  const IteratorT &end() const { return end_; }
};

/*
 * An registry helper class, with its records keeps the order they registers.
 */
template <typename T>
class OrderedRegistry {
 public:
  T *Register(const std::string &name, T *x) {
123 124 125
    PADDLE_ENFORCE_EQ(dic_.count(name), 0,
                      platform::errors::PreconditionNotMet(
                          "There exists duplicate key [%s]", name));
126 127 128
    dic_[name] = elements_.size();
    elements_.emplace_back(std::unique_ptr<T>(x));
    return elements_.back().get();
129 130 131 132 133
  }

  T *Lookup(const std::string &name) {
    auto it = dic_.find(name);
    if (it == dic_.end()) return nullptr;
134
    return elements_[it->second].get();
135 136 137 138
  }

 protected:
  std::unordered_map<std::string, int> dic_;
139
  std::vector<std::unique_ptr<T>> elements_;
140 141
};

142 143 144
template <typename T>
T &GetFromScope(const framework::Scope &scope, const std::string &name) {
  framework::Variable *var = scope.FindVar(name);
145 146 147
  PADDLE_ENFORCE_NOT_NULL(
      var, platform::errors::PreconditionNotMet(
               "The var which name is %s should not be nullptr.", name));
148 149 150
  return *var->GetMutable<T>();
}

Y
Yan Chunwei 已提交
151 152 153
static framework::proto::ProgramDesc LoadProgramDesc(
    const std::string &model_path) {
  std::ifstream fin(model_path, std::ios::in | std::ios::binary);
154 155 156 157 158
  PADDLE_ENFORCE_EQ(
      fin.is_open(), true,
      platform::errors::NotFound(
          "Cannot open file %s, please confirm whether the file exists",
          model_path));
Y
Yan Chunwei 已提交
159 160 161 162 163 164 165 166 167 168
  fin.seekg(0, std::ios::end);
  std::string buffer(fin.tellg(), ' ');
  fin.seekg(0, std::ios::beg);
  fin.read(&buffer[0], buffer.size());
  fin.close();
  framework::proto::ProgramDesc program_desc;
  program_desc.ParseFromString(buffer);
  return program_desc;
}

169 170 171 172 173 174 175
static bool FileExists(const std::string &filepath) {
  std::ifstream file(filepath);
  bool exists = file.is_open();
  file.close();
  return exists;
}

176 177 178 179 180 181 182 183 184 185
static bool PathExists(const std::string &path) {
  struct stat statbuf;
  if (stat(path.c_str(), &statbuf) != -1) {
    if (S_ISDIR(statbuf.st_mode)) {
      return true;
    }
  }
  return false;
}

N
nhzlx 已提交
186
static std::string GetDirRoot(const std::string &path) {
187 188 189 190 191 192 193 194 195 196
  char sep_1 = '/', sep_2 = '\\';

  size_t i_1 = path.rfind(sep_1, path.length());
  size_t i_2 = path.rfind(sep_2, path.length());
  if (i_1 != std::string::npos && i_2 != std::string::npos) {
    return path.substr(0, std::max(i_1, i_2));
  } else if (i_1 != std::string::npos) {
    return path.substr(0, i_1);
  } else if (i_2 != std::string::npos) {
    return path.substr(0, i_2);
N
nhzlx 已提交
197 198 199 200
  }
  return path;
}

201 202
static void MakeDirIfNotExists(const std::string &path) {
  if (!PathExists(path)) {
203
    PADDLE_ENFORCE_NE(
204
        MKDIR(path.c_str()), -1,
205 206 207
        platform::errors::PreconditionNotMet(
            "Can not create optimize cache directory: %s, Make sure you "
            "have permission to write",
208
            path));
N
nhzlx 已提交
209
  }
210 211 212 213 214
}

static std::string GetOrCreateModelOptCacheDir(const std::string &model_root) {
  std::string opt_cache_dir = model_root + "/_opt_cache/";
  MakeDirIfNotExists(opt_cache_dir);
N
nhzlx 已提交
215 216 217
  return opt_cache_dir;
}

N
nhzlx 已提交
218 219 220 221 222
static std::string GetTrtCalibPath(const std::string &model_root,
                                   const std::string &engine_key) {
  return model_root + "/trt_calib_" + engine_key;
}

N
nhzlx 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
// If there is no calib table data file in model_opt_cache_dir, return "".
static std::string GetTrtCalibTableData(const std::string &model_opt_cache_dir,
                                        const std::string &engine_key,
                                        bool enable_int8) {
  std::string trt_calib_table_path =
      GetTrtCalibPath(model_opt_cache_dir, engine_key);
  if (enable_int8 && FileExists(trt_calib_table_path)) {
    VLOG(3) << "Calibration table file: " << trt_calib_table_path
            << "is found here";
    std::ifstream infile(trt_calib_table_path, std::ios::in);
    std::stringstream buffer;
    buffer << infile.rdbuf();
    std::string calibration_data(buffer.str());
    return calibration_data;
  }
  return "";
}

N
nhzlx 已提交
241 242 243 244 245 246 247 248 249 250 251 252
static std::string GetTrtEngineSerializedPath(const std::string &model_root,
                                              const std::string &engine_key) {
  return model_root + "/trt_serialized_" + engine_key;
}

static std::string GetTrtEngineSerializedData(
    const std::string &model_opt_cache_dir, const std::string &engine_key) {
  std::string trt_serialized_path =
      GetTrtEngineSerializedPath(model_opt_cache_dir, engine_key);
  if (FileExists(trt_serialized_path)) {
    VLOG(3) << "Trt serialized file: " << trt_serialized_path
            << "is found here";
253
    std::ifstream infile(trt_serialized_path, std::ios::binary);
N
nhzlx 已提交
254 255 256 257 258 259 260 261 262 263 264
    std::stringstream buffer;
    buffer << infile.rdbuf();
    std::string trt_engine_serialized_data(buffer.str());
    return trt_engine_serialized_data;
  }
  return "";
}

static void SaveTrtEngineSerializedDataToFile(
    const std::string &trt_serialized_path,
    const std::string &engine_serialized_data) {
265
  std::ofstream outfile(trt_serialized_path, std::ios::binary);
N
nhzlx 已提交
266 267 268 269
  outfile << engine_serialized_data;
  outfile.close();
}

270 271 272 273 274 275 276
}  // namespace analysis
}  // namespace inference
}  // namespace paddle

#define PADDLE_DISALLOW_COPY_AND_ASSIGN(type__) \
  type__(const type__ &) = delete;              \
  void operator=(const type__ &) = delete;