helper.h 4.7 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
#include <cstdio>
Y
Yan Chunwei 已提交
19
#include <fstream>
20
#include <string>
S
sneaxiy 已提交
21
#include <typeindex>
22 23 24
#include <unordered_map>
#include <vector>

25
#include "paddle/fluid/framework/framework.pb.h"
26 27
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/variable.h"
28 29 30 31 32 33
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace inference {
namespace analysis {

34 35 36 37
template <typename T>
void SetAttr(framework::proto::OpDesc *op, const std::string &name,
             const T &data);

Y
Yan Chunwei 已提交
38 39 40 41 42 43 44 45 46
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 已提交
47
#define SET_TYPE(type__) dic_[std::type_index(typeid(type__))] = #type__;
48 49 50 51 52 53 54 55 56 57 58
/*
 * 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 已提交
59
    auto x = std::type_index(typeid(T));
60 61 62 63
    PADDLE_ENFORCE(dic_.count(x), "unknown type for representation");
    return dic_.at(x);
  }

S
sneaxiy 已提交
64 65 66
  const std::string &repr(const std::type_index &type) const {  // NOLINT
    PADDLE_ENFORCE(dic_.count(type), "unknown type for representation");
    return dic_.at(type);
67 68 69 70 71 72 73
  }

 private:
  DataTypeNamer() {
    SET_TYPE(int);
    SET_TYPE(bool);
    SET_TYPE(float);
Y
Yan Chunwei 已提交
74
    SET_TYPE(void *);
75 76
  }

S
sneaxiy 已提交
77
  std::unordered_map<std::type_index, std::string> dic_;
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
};
#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) {
103
    PADDLE_ENFORCE(!dic_.count(name), "duplicate key [%s]", name);
104 105 106
    dic_[name] = elements_.size();
    elements_.emplace_back(std::unique_ptr<T>(x));
    return elements_.back().get();
107 108 109 110 111
  }

  T *Lookup(const std::string &name) {
    auto it = dic_.find(name);
    if (it == dic_.end()) return nullptr;
112
    return elements_[it->second].get();
113 114 115 116
  }

 protected:
  std::unordered_map<std::string, int> dic_;
117
  std::vector<std::unique_ptr<T>> elements_;
118 119
};

120 121 122 123 124 125 126
template <typename T>
T &GetFromScope(const framework::Scope &scope, const std::string &name) {
  framework::Variable *var = scope.FindVar(name);
  PADDLE_ENFORCE(var != nullptr);
  return *var->GetMutable<T>();
}

127 128 129 130 131 132 133 134 135 136 137 138 139 140
static void ExecShellCommand(const std::string &cmd, std::string *message) {
  char buffer[128];
  std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose);
  if (!pipe) {
    LOG(ERROR) << "error running command: " << cmd;
    return;
  }
  while (!feof(pipe.get())) {
    if (fgets(buffer, 128, pipe.get()) != nullptr) {
      *message += buffer;
    }
  }
}

Y
Yan Chunwei 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154
static framework::proto::ProgramDesc LoadProgramDesc(
    const std::string &model_path) {
  std::ifstream fin(model_path, std::ios::in | std::ios::binary);
  PADDLE_ENFORCE(fin.is_open(), "Cannot open file %s", model_path);
  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;
}

155 156 157 158 159 160 161
static bool FileExists(const std::string &filepath) {
  std::ifstream file(filepath);
  bool exists = file.is_open();
  file.close();
  return exists;
}

162 163 164 165 166 167 168 169 170 171
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;
}

172 173 174 175 176 177 178
}  // namespace analysis
}  // namespace inference
}  // namespace paddle

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