inference_icnet.cc 6.7 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 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. */

/*
 * This file contains a simple demo for how to take a model for inference.
 */
#include <cassert>
#include <cctype>

#include <algorithm>
D
dzhwinter 已提交
22
#include <fstream>
D
dzhwinter 已提交
23 24 25 26 27 28 29 30
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <thread>  //NOLINT
#include "paddle/fluid/inference/paddle_inference_api.h"

D
dzhwinter 已提交
31 32 33 34 35 36 37 38
std::string MODELDIR = ""; /* "Directory of the inference model." */ // NOLINT
std::string REFER = ""; /*"path to reference result for comparison."*/ //NOTLINT
/*path of data; each line is a record, format:
<space splitted floats as data>\t<space splitted ints as shape>

Please check the demo data of data.txt for details.
 */
std::string DATA = "";  
D
dzhwinter 已提交
39 40
bool USE_GPU = false;     /*"Whether use gpu."*/

D
dzhwinter 已提交
41

D
dzhwinter 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
auto message_err = []() {
  std::cout << "Copyright (c) 2018 PaddlePaddle Authors." << std::endl;
  std::cout << "Demo Case for windows inference. "
            << "\n"
            << "Usage: Input your model path and use_gpu as the guide requires,"
            << "then run the demo inference, and will get a result."
            << std::endl;
  std::cout << std::endl;
};


namespace paddle {
namespace demo {
D
dzhwinter 已提交
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

void split(const std::string& str, char sep,
                  std::vector<std::string>* pieces) {
  pieces->clear();
  if (str.empty()) {
    return;
  }
  size_t pos = 0;
  size_t next = str.find(sep, pos);
  while (next != std::string::npos) {
    pieces->push_back(str.substr(pos, next - pos));
    pos = next + 1;
    next = str.find(sep, pos);
  }
  if (!str.substr(pos).empty()) {
    pieces->push_back(str.substr(pos));
  }
}

/*
 * Get a summary of a PaddleTensor content.
 */
std::string SummaryTensor(const PaddleTensor& tensor) {
  std::stringstream ss;
  int num_elems = tensor.data.length() / PaddleDtypeSize(tensor.dtype);

  ss << "data[:10]\t";
  switch (tensor.dtype) {
    case PaddleDType::INT64: {
      for (int i = 0; i < std::min(num_elems, 10); i++) {
        ss << static_cast<int64_t*>(tensor.data.data())[i] << " ";
      }
      break;
    }
    case PaddleDType::FLOAT32:
      for (int i = 0; i < std::min(num_elems, 10); i++) {
        ss << static_cast<float*>(tensor.data.data())[i] << " ";
      }
      break;
  }
  return ss.str();
}

D
dzhwinter 已提交
98 99 100 101 102 103 104 105 106 107 108 109
std::string ToString(const NativeConfig& config) {
  std::stringstream ss;
  ss << "Use GPU : " << (config.use_gpu ? "True" : "False") << "\n"
     << "Device : " << config.device << "\n"
     << "fraction_of_gpu_memory : " << config.fraction_of_gpu_memory << "\n"
     << "specify_input_name : "
     << (config.specify_input_name ? "True" : "False") << "\n"
     << "Program File : " << config.prog_file << "\n"
     << "Param File : " << config.param_file;
  return ss.str();
}

D
dzhwinter 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
struct Record {
  std::vector<float> data;
  std::vector<int32_t> shape;
};


Record ProcessALine(const std::string& line) {
  std::cout << "process a line" << std::endl;;
  std::vector<std::string> columns;
  split(line, '\t', &columns);
  assert(columns.size() == 2UL,
        "data format error, should be <data>\t<shape>");

  Record record;
  std::vector<std::string> data_strs;
  split(columns[0], ' ', &data_strs);
  for (auto& d : data_strs) {
    record.data.push_back(std::stof(d));
  }

  std::vector<std::string> shape_strs;
  split(columns[1], ' ', &shape_strs);
  for (auto& s : shape_strs) {
    record.shape.push_back(std::stoi(s));
  }
  std::cout << "data size " << record.data.size() << std::endl;
  std::cout << "data shape size " << record.shape.size() << std::endl;
  return record;
}
D
dzhwinter 已提交
139

D
dzhwinter 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
void CheckOutput(const std::string& referfile, const PaddleTensor& output) {
  std::string line;
  std::ifstream file(referfile);
  std::getline(file, line);
  auto refer = ProcessALine(line);
  file.close();

  size_t numel = output.data.length() / PaddleDtypeSize(output.dtype);
  std::cout << "predictor output numel " << numel << std::endl;
  std::cout << "reference output numel " << refer.data.size() << std::endl;
  assert(numel == refer.data.size());
  switch (output.dtype) {
    case PaddleDType::INT64: {
      for (size_t i = 0; i < numel; ++i) {
        assert(static_cast<int64_t*>(output.data.data())[i] == 
                          refer.data[i]);
      }
      break;
D
dzhwinter 已提交
158
    }
D
dzhwinter 已提交
159 160 161 162 163 164 165
    case PaddleDType::FLOAT32:
      for (size_t i = 0; i < numel; ++i) {
        assert(
            fabs(static_cast<float*>(output.data.data())[i] - refer.data[i]) <=
            1e-5);
      }
      break;
D
dzhwinter 已提交
166 167 168
  }
}

D
dzhwinter 已提交
169 170 171 172
/*
 * Use the native fluid engine to inference the demo.
 */
void Main(bool use_gpu) {
D
dzhwinter 已提交
173
  NativeConfig config;
D
dzhwinter 已提交
174 175
  config.param_file = MODELDIR + "/__params__";
  config.prog_file = MODELDIR + "/__model__";
D
dzhwinter 已提交
176 177
  config.use_gpu = USE_GPU;
  config.device = 0;
D
dzhwinter 已提交
178 179 180
  if (USE_GPU) {
    config.fraction_of_gpu_memory = 0.1f;  // set by yourself
  }
D
dzhwinter 已提交
181
  std::cout << ToString(config) << std::endl;
D
dzhwinter 已提交
182 183
  std::cout << "init predictor" << std::endl;
  auto predictor =
D
dzhwinter 已提交
184 185
      CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(config);

D
dzhwinter 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  std::cout << "begin to process data" << std::endl;
  // Just a single batch of data.
  std::string line;
  std::ifstream file(DATA);
  std::getline(file, line);
  auto record = ProcessALine(line);
  file.close();

  // Inference.
  PaddleTensor input;
  input.shape = record.shape;
  input.data =
      PaddleBuf(record.data.data(), record.data.size() * sizeof(float));
  input.dtype = PaddleDType::FLOAT32;

  std::cout << "run executor" << std::endl;
  std::vector<PaddleTensor> output;
  predictor->Run({input}, &output);

  std::cout << "output.size " << output.size() << std::endl;
  auto& tensor = output.front();
  std::cout << "output: " << SummaryTensor(tensor) << std::endl;

  // compare with reference result
  CheckOutput(REFER, tensor);
D
dzhwinter 已提交
211 212
}

D
dzhwinter 已提交
213

D
dzhwinter 已提交
214 215 216 217 218
}  // namespace demo
}  // namespace paddle

int main(int argc, char** argv) {
  // ParseArgs();
D
dzhwinter 已提交
219 220 221
  MODELDIR = "./mobilenet/model";
  DATA = "./mobilenet/data.txt";
  REFER = "./mobilenet/result.txt";
D
dzhwinter 已提交
222 223 224 225 226 227 228 229
  USE_GPU = true;
  paddle::demo::Main(false /* USE_GPU*/);
  if (USE_GPU) {
    paddle::demo::Main(true /*USE_GPU*/);
  }
  system("pause");
  return 0;
}