pd_predictor.cc 11.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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.

#include <algorithm>
F
flame 已提交
16 17
#include <cstdlib>
#include <cstring>
18
#include <map>
19
#include <memory>
20 21
#include <numeric>
#include <vector>
F
flame 已提交
22
#include "paddle/fluid/inference/api/paddle_api.h"
23
#include "paddle/fluid/inference/capi/c_api_internal.h"
F
flame 已提交
24
#include "paddle/fluid/inference/capi/paddle_c_api.h"
25
#include "paddle/fluid/platform/enforce.h"
26

F
flame 已提交
27
using paddle::ConvertToACPrecision;
28 29 30
using paddle::ConvertToPaddleDType;
using paddle::ConvertToPDDataType;

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
namespace {
#define _DataTypeHelper_(CALLBACK, CPP_TYPE, PD_TYPE) \
  CALLBACK(CPP_TYPE, PD_DataType::PD_TYPE);

#define _DataType_(CALLBACK)                     \
  _DataTypeHelper_(CALLBACK, float, PD_FLOAT32); \
  _DataTypeHelper_(CALLBACK, int32_t, PD_INT32); \
  _DataTypeHelper_(CALLBACK, int64_t, PD_INT64); \
  _DataTypeHelper_(CALLBACK, uint8_t, PD_UINT8);

template <typename Visitor>
inline void VisitDataType(PD_DataType type, Visitor visitor) {
#define VisitDataTypeCallback(CPP_TYPE, PD_TYPE) \
  do {                                           \
    if (type == PD_TYPE) {                       \
      visitor.template apply<CPP_TYPE>();        \
      return;                                    \
    }                                            \
  } while (0)

  _DataType_(VisitDataTypeCallback);
#undef VisitDataTypeCallback
53 54
  PADDLE_THROW(
      paddle::platform::errors::InvalidArgument("Unsupported data type."));
55 56 57 58 59
}

struct PD_ZeroCopyFunctor {
  PD_ZeroCopyData* output_i;
  paddle::ZeroCopyTensor* output_t;
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  PD_ZeroCopyFunctor(PD_ZeroCopyData* output_i_,
                     paddle::ZeroCopyTensor* output_t_)
      : output_i(output_i_), output_t(output_t_) {}

  template <typename OutT>
  void apply() {
    std::vector<OutT> out_data;
    int out_num =
        std::accumulate(output_i->shape, output_i->shape + output_i->shape_size,
                        1, std::multiplies<int>());
    out_data.resize(out_num);
    output_t->copy_to_cpu(out_data.data());
    output_i->data = reinterpret_cast<void*>(malloc(out_num * sizeof(OutT)));
    memmove(static_cast<OutT*>(output_i->data), out_data.data(),
            out_num * sizeof(OutT));
  }
};

}  // namespace

extern "C" {
82
bool PD_PredictorRun(const PD_AnalysisConfig* config, PD_Tensor* inputs,
83
                     int in_size, PD_Tensor** output_data, int* out_size,
84
                     int batch_size) {
85 86 87 88
  PADDLE_ENFORCE_NOT_NULL(
      config,
      paddle::platform::errors::InvalidArgument(
          "The pointer of analysis configuration shouldn't be nullptr"));
89
  VLOG(3) << "Predoctor: PD_PredictorRun. ";
90 91 92 93 94 95 96
  static std::map<std::string, std::unique_ptr<paddle::PaddlePredictor>>
      predictors;
  if (!predictors.count(config->config.model_dir())) {
    predictors[config->config.model_dir()] =
        paddle::CreatePaddlePredictor(config->config);
  }
  auto& predictor = predictors[config->config.model_dir()];
97 98 99 100 101
  std::vector<paddle::PaddleTensor> in;
  for (int i = 0; i < in_size; ++i) {
    in.emplace_back(inputs->tensor);
  }
  std::vector<paddle::PaddleTensor> out;
102
  VLOG(3) << "Run predictor in CAPI encapsulation. ";
103 104
  if (predictor->Run(in, &out, batch_size)) {
    int osize = out.size();
105
    *output_data = new PD_Tensor[osize];
106
    for (int i = 0; i < osize; ++i) {
107
      output_data[i]->tensor = out[i];
108
    }
109
    *out_size = osize;
110 111 112 113 114 115 116
    return true;
  }
  return false;
}

bool PD_PredictorZeroCopyRun(const PD_AnalysisConfig* config,
                             PD_ZeroCopyData* inputs, int in_size,
117
                             PD_ZeroCopyData** output, int* out_size) {
118 119 120 121
  PADDLE_ENFORCE_NOT_NULL(
      config,
      paddle::platform::errors::InvalidArgument(
          "The pointer of analysis configuration shouldn't be nullptr"));
122 123 124 125 126 127 128
  static std::map<std::string, std::unique_ptr<paddle::PaddlePredictor>>
      predictors;
  if (!predictors.count(config->config.model_dir())) {
    predictors[config->config.model_dir()] =
        paddle::CreatePaddlePredictor(config->config);
  }
  auto& predictor = predictors[config->config.model_dir()];
129
  auto input_names = predictor->GetInputNames();
130
  VLOG(3) << "The inputs' size is " << input_names.size();
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  PADDLE_ENFORCE_EQ(
      input_names.size(), in_size,
      "The number of input and the number of model's input must match. ");
  for (int i = 0; i < in_size; ++i) {
    auto input_t = predictor->GetInputTensor(inputs[i].name);
    std::vector<int> tensor_shape;
    tensor_shape.assign(inputs[i].shape,
                        inputs[i].shape + inputs[i].shape_size);
    input_t->Reshape(tensor_shape);
    switch (inputs[i].dtype) {
      case PD_FLOAT32:
        input_t->copy_from_cpu(static_cast<float*>(inputs[i].data));
        break;
      case PD_INT32:
        input_t->copy_from_cpu(static_cast<int32_t*>(inputs[i].data));
        break;
      case PD_INT64:
        input_t->copy_from_cpu(static_cast<int64_t*>(inputs[i].data));
        break;
      case PD_UINT8:
        input_t->copy_from_cpu(static_cast<uint8_t*>(inputs[i].data));
        break;
      default:
154 155
        PADDLE_THROW(paddle::platform::errors::InvalidArgument(
            "Unsupported data type."));
156 157 158
        break;
    }
  }
159
  VLOG(3) << "Run ZeroCopyRun() in CAPI encapsulation. ";
160 161 162
  CHECK(predictor->ZeroCopyRun());
  auto output_names = predictor->GetOutputNames();
  int osize = output_names.size();
163
  *out_size = osize;
164 165
  *output = new PD_ZeroCopyData[osize];
  VLOG(3) << "The output size is " << osize;
166
  for (int i = 0; i < *out_size; ++i) {
167 168 169
    auto& output_i = (*output)[i];
    output_i.name = new char[output_names[i].length() + 1];
    snprintf(output_i.name, output_names[i].length() + 1, "%s",
170 171
             output_names[i].c_str());
    auto output_t = predictor->GetOutputTensor(output_names[i]);
172
    output_i.dtype = ConvertToPDDataType(output_t->type());
173
    std::vector<int> output_shape = output_t->shape();
174
    output_i.shape = new int[output_shape.size()];
175 176
    memmove(output_i.shape, output_shape.data(),
            output_shape.size() * sizeof(int));
177
    output_i.shape_size = output_shape.size();
178 179
    VisitDataType(output_i.dtype,
                  PD_ZeroCopyFunctor(&output_i, std::move(output_t.get())));
180 181 182
  }
  return true;
}
F
flame 已提交
183 184 185 186 187 188 189 190

PD_Predictor* PD_NewPredictor(const PD_AnalysisConfig* config) {
  PD_Predictor* predictor = new PD_Predictor;
  predictor->predictor = paddle::CreatePaddlePredictor(config->config);
  return predictor;
}

void PD_DeletePredictor(PD_Predictor* predictor) {
191 192
  if (predictor) {
    predictor->predictor = nullptr;
F
flame 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    delete predictor;
    predictor = nullptr;
  }
}

int PD_GetInputNum(const PD_Predictor* predictor) {
  return static_cast<int>(predictor->predictor->GetInputNames().size());
}

int PD_GetOutputNum(const PD_Predictor* predictor) {
  return static_cast<int>(predictor->predictor->GetOutputNames().size());
}

const char* PD_GetInputName(const PD_Predictor* predictor, int n) {
  static std::vector<std::string> names = predictor->predictor->GetInputNames();
  return names[n].c_str();
}

const char* PD_GetOutputName(const PD_Predictor* predictor, int n) {
  static std::vector<std::string> names =
      predictor->predictor->GetOutputNames();
  return names[n].c_str();
}

void PD_SetZeroCopyInput(PD_Predictor* predictor,
                         const PD_ZeroCopyTensor* tensor) {
  auto input = predictor->predictor->GetInputTensor(tensor->name);
  auto* shape_ptr = static_cast<int*>(tensor->shape.data);
  std::vector<int> shape(shape_ptr,
                         shape_ptr + tensor->shape.length / sizeof(int));
  input->Reshape(std::move(shape));
  switch (tensor->dtype) {
    case PD_FLOAT32:
      input->copy_from_cpu(static_cast<float*>(tensor->data.data));
      break;
    case PD_INT32:
      input->copy_from_cpu(static_cast<int32_t*>(tensor->data.data));
      break;
    case PD_INT64:
      input->copy_from_cpu(static_cast<int64_t*>(tensor->data.data));
      break;
    case PD_UINT8:
      input->copy_from_cpu(static_cast<uint8_t*>(tensor->data.data));
      break;
    default:
238 239
      PADDLE_THROW(
          paddle::platform::errors::InvalidArgument("Unsupported data type."));
F
flame 已提交
240 241 242 243 244
      break;
  }

  if (tensor->lod.length) {
    auto* lod_ptr = reinterpret_cast<size_t*>(tensor->lod.data);
245 246
    std::vector<size_t> lod;
    lod.assign(lod_ptr, lod_ptr + tensor->lod.length / sizeof(size_t));
F
flame 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    input->SetLoD({std::move(lod)});
  }
}

void PD_GetZeroCopyOutput(PD_Predictor* predictor, PD_ZeroCopyTensor* tensor) {
  auto output = predictor->predictor->GetOutputTensor(tensor->name);
  tensor->dtype = ConvertToPDDataType(output->type());
  auto shape = output->shape();
  size_t shape_size = shape.size();
  if (tensor->shape.capacity < shape_size * sizeof(int)) {
    if (tensor->shape.data || tensor->shape.capacity) {
      std::free(tensor->shape.data);
    }
    tensor->shape.data = std::malloc(shape_size * sizeof(int));
    tensor->shape.capacity = shape_size * sizeof(int);
  }
  tensor->shape.length = shape_size * sizeof(int);
  std::copy(shape.begin(), shape.end(), static_cast<int*>(tensor->shape.data));

  int n =
      std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>());
  size_t length = n * paddle::PaddleDtypeSize(output->type());
  if (tensor->data.capacity < length) {
    if (tensor->data.data) {
      std::free(tensor->data.data);
    }
    tensor->data.data = std::malloc(length);
    tensor->data.capacity = std::move(length);
  }
  tensor->data.length = length;

  auto lod = output->lod();
279 280 281 282 283 284
  if (!lod.empty()) {
    tensor->lod.length = lod.front().size() * sizeof(size_t);
    if (tensor->lod.capacity < lod.front().size()) {
      if (tensor->lod.data) {
        std::free(tensor->lod.data);
      }
F
flame 已提交
285

286 287 288 289 290
      tensor->lod.data = std::malloc(lod.front().size() * sizeof(size_t));
      tensor->lod.capacity = lod.front().size() * sizeof(size_t);
    }
    std::copy(lod.front().begin(), lod.front().end(),
              reinterpret_cast<size_t*>(tensor->lod.data));
F
flame 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
  }
  switch (tensor->dtype) {
    case PD_FLOAT32:
      output->copy_to_cpu(reinterpret_cast<float*>(tensor->data.data));
      break;
    case PD_INT32:
      output->copy_to_cpu(reinterpret_cast<int32_t*>(tensor->data.data));
      break;
    case PD_INT64:
      output->copy_to_cpu(reinterpret_cast<int64_t*>(tensor->data.data));
      break;
    case PD_UINT8:
      output->copy_to_cpu(reinterpret_cast<uint8_t*>(tensor->data.data));
      break;
    default:
306 307
      PADDLE_THROW(
          paddle::platform::errors::InvalidArgument("Unsupported data type."));
F
flame 已提交
308 309 310 311 312 313 314
      break;
  }
}

void PD_ZeroCopyRun(PD_Predictor* predictor) {
  predictor->predictor->ZeroCopyRun();
}
315
}  // extern "C"