io.cpp 16.3 KB
Newer Older
W
wangliu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/* 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. */
朔-望's avatar
朔-望 已提交
14

L
liuruilong 已提交
15
#include "io.h"
朔-望's avatar
朔-望 已提交
16
#include <fstream>
L
liuruilong 已提交
17
#include <vector>
朔-望's avatar
朔-望 已提交
18

L
liuruilong 已提交
19
#include "common/enforce.h"
L
liuruilong 已提交
20
#include "common/log.h"
L
liuruilong 已提交
21
#include "framework/framework.pb.h"
L
liuruilong 已提交
22
#include "framework/lod_tensor.h"
L
liuruilong 已提交
23
#include "framework/operator.h"
L
liuruilong 已提交
24
#include "framework/program/program_desc.h"
L
liuruilong 已提交
25 26
#include "framework/scope.h"
#include "framework/tensor.h"
L
liuruilong 已提交
27

朔-望's avatar
朔-望 已提交
28 29
namespace paddle_mobile {

朔-望's avatar
朔-望 已提交
30
void ReadBinaryFile(const std::string &filename, std::string *contents) {
31
  std::ifstream fin(filename, std::ios::in | std::ios::binary);
L
liuruilong 已提交
32 33
  PADDLE_MOBILE_ENFORCE(fin.is_open(), "open file: %s failed",
                        filename.c_str());
34 35 36 37 38 39
  fin.seekg(0, std::ios::end);
  contents->clear();
  contents->resize(fin.tellg());
  fin.seekg(0, std::ios::beg);
  fin.read(&(contents->at(0)), contents->size());
  fin.close();
朔-望's avatar
朔-望 已提交
40 41 42 43 44
}

template <typename Dtype, Precision P>
void Loader<Dtype, P>::LoadVar(framework::LoDTensor *tensor,
                               const std::string &file_path) {
45
  std::ifstream is(file_path);
L
liuruilong 已提交
46 47
  PADDLE_MOBILE_ENFORCE(is.is_open(), "open file: %s failed",
                        file_path.c_str());
朔-望's avatar
朔-望 已提交
48 49
  std::fpos<mbstate_t> pos;
  pos = is.tellg();  // save   current   position
50
  is.seekg(0, std::ios::end);
朔-望's avatar
朔-望 已提交
51
  is.seekg(pos);  // restore   saved   position
52 53 54 55 56 57 58 59 60 61 62 63

  // 1. version
  uint32_t version;
  is.read(reinterpret_cast<char *>(&version), sizeof(version));

  // 2 Lod information
  uint64_t lod_level;
  is.read(reinterpret_cast<char *>(&lod_level), sizeof(lod_level));
  auto &lod = *tensor->mutable_lod();
  lod.resize(lod_level);
  for (uint64_t i = 0; i < lod_level; ++i) {
    uint64_t size;
朔-望's avatar
朔-望 已提交
64
    is.read(reinterpret_cast<char *>(&size), sizeof(size));
65 66 67
    std::vector<size_t> tmp(size / sizeof(size_t));
    is.read(reinterpret_cast<char *>(tmp.data()),
            static_cast<std::streamsize>(size));
朔-望's avatar
朔-望 已提交
68 69
    for (auto j : tmp) {
      LOG(kLOG_DEBUG1) << "    lod - " << j;
朔-望's avatar
朔-望 已提交
70
    }
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    lod[i] = tmp;
  }

  // 3. tensor version
  uint32_t tensor_version;
  is.read(reinterpret_cast<char *>(&tensor_version), sizeof(tensor_version));

  // 4. tensor desc
  int32_t size;
  is.read(reinterpret_cast<char *>(&size), sizeof(size));
  std::unique_ptr<char[]> buf(new char[size]);
  is.read(reinterpret_cast<char *>(buf.get()), size);

  framework::proto::VarType::TensorDesc desc;
  desc.ParseFromArray(buf.get(), size);

  int memory_size = 1;
朔-望's avatar
朔-望 已提交
88 89
  for (auto l : desc.dims()) {
    memory_size *= l;
90 91 92 93 94 95 96
  }

  std::vector<int64_t> dims;
  dims.reserve(static_cast<size_t>(desc.dims().size()));
  std::copy(desc.dims().begin(), desc.dims().end(), std::back_inserter(dims));
  tensor->Resize(framework::make_ddim(dims));

朔-望's avatar
朔-望 已提交
97
  void *memory = tensor;
98 99
  int type_size = 0;
  switch (desc.data_type()) {
朔-望's avatar
朔-望 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    case framework::proto::VarType::FP16:
      type_size = 2;
      break;
    case framework::proto::VarType::FP32:
      type_size = 4;
      memory = tensor->mutable_data<float>();
      break;
    case framework::proto::VarType::FP64:
      type_size = 8;
      break;
    case framework::proto::VarType::INT32:
      type_size = 4;
      break;
    case framework::proto::VarType::INT64:
      type_size = 8;
      break;
    case framework::proto::VarType::BOOL:
      type_size = 1;
      break;
    default:
      break;
121 122 123 124
  }

  is.read(static_cast<char *>(memory), memory_size * type_size);
  is.close();
朔-望's avatar
朔-望 已提交
125
}
朔-望's avatar
朔-望 已提交
126 127

template <typename Dtype, Precision P>
朔-望's avatar
朔-望 已提交
128 129
const framework::Program<Dtype, P> Loader<Dtype, P>::Load(
    const std::string &dirname) {
130 131 132 133 134 135 136 137 138 139
  std::string model_filename = dirname + "/__model__";
  std::string program_desc_str;
  ReadBinaryFile(model_filename, &program_desc_str);
  framework::proto::ProgramDesc program_desc_proto;
  program_desc_proto.ParseFromString(program_desc_str);

  std::shared_ptr<framework::ProgramDesc> originProgramDesc =
      std::make_shared<framework::ProgramDesc>(program_desc_proto);

  framework::Program<Dtype, P> program;
L
liuruilong 已提交
140
  program.model_path = dirname;
141 142 143 144 145
  program.originProgram = originProgramDesc;

  std::shared_ptr<framework::Scope> scope =
      std::make_shared<framework::Scope>();
  program.scope = scope;
E
eclipsess 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  originProgramDesc->Block(0);

  for (const auto &block : originProgramDesc->Blocks()) {
    for (int i = 0; i < block->Vars().size(); ++i) {
      std::shared_ptr<framework::VarDesc> var_desc = block->Vars()[i];
      auto var = scope->Var(var_desc->Name());
      if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
        if (var_desc->Persistable() &&
            var_desc->GetType() != framework::proto::VarType::FEED_MINIBATCH &&
            var_desc->GetType() != framework::proto::VarType::FETCH_LIST) {
          auto tensor = var->GetMutable<framework::LoDTensor>();
          // to load
          LoadVar(tensor, dirname + "/" + var_desc->Name());
        }
      } else {
        // TODO(codeWorm): some.
      }
    }
  }
165 166

#ifdef PADDLE_MOBILE_DEBUG
朔-望's avatar
朔-望 已提交
167
  for (const auto &block : program_desc_proto.blocks()) {
168 169 170 171 172 173 174
    LOG(kLOG_DEBUG) << "block: " << block.idx();
    for (int j = 0; j < block.ops().size(); ++j) {
      framework::proto::OpDesc op = block.ops()[j];
      LOG(kLOG_DEBUG1) << "op: " << op.type();
      for (int m = 0; m < op.inputs_size(); ++m) {
        const framework::proto::OpDesc::Var &var = op.inputs(m);
        LOG(kLOG_DEBUG2) << "input parameter: " << var.parameter();
朔-望's avatar
朔-望 已提交
175 176
        for (const auto &n : var.arguments()) {
          LOG(kLOG_DEBUG3) << "argument - " << n;
177 178 179 180 181 182
        }
      }

      for (int y = 0; y < op.outputs_size(); ++y) {
        const framework::proto::OpDesc::Var &var = op.outputs(y);
        LOG(kLOG_DEBUG2) << "out parameter: " << var.parameter();
朔-望's avatar
朔-望 已提交
183 184
        for (const auto &z : var.arguments()) {
          LOG(kLOG_DEBUG3) << "argument - " << z;
185 186 187
        }
      }

朔-望's avatar
朔-望 已提交
188
      for (const auto &attr : op.attrs()) {
189 190 191
        LOG(kLOG_DEBUG2) << "attr name: " << attr.name();

        switch (attr.type()) {
朔-望's avatar
朔-望 已提交
192 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
          case framework::proto::AttrType::BOOLEAN:
            LOG(kLOG_DEBUG3) << "boolen: " << attr.b();
            break;
          case framework::proto::AttrType::INT:
            LOG(kLOG_DEBUG3) << "int: " << attr.i();
            break;
          case framework::proto::AttrType::FLOAT:
            LOG(kLOG_DEBUG3) << "float: " << attr.f();
          case framework::proto::AttrType::STRING:
            LOG(kLOG_DEBUG3) << "string: " << attr.s();
          case framework::proto::AttrType::BOOLEANS:
            for (int y = 0; y < attr.bools_size(); ++y) {
              LOG(kLOG_DEBUG3) << "bools: " << attr.bools(y);
            }
          case framework::proto::AttrType::LONG:
            LOG(kLOG_DEBUG3) << "long: " << attr.l();
          case framework::proto::AttrType::FLOATS:
            for (int y = 0; y < attr.floats_size(); ++y) {
              LOG(kLOG_DEBUG3) << "floats: " << attr.floats(y);
            }
          case framework::proto::AttrType::INTS:
            for (int y = 0; y < attr.ints_size(); ++y) {
              LOG(kLOG_DEBUG3) << "ints: " << attr.ints(y);
            }
          case framework::proto::AttrType::STRINGS:
            for (int y = 0; y < attr.strings_size(); ++y) {
              LOG(kLOG_DEBUG3) << "strings: " << attr.strings(y);
            }
          case framework::proto::BLOCK:
            break;
222 223 224 225
        }
      }
    }

朔-望's avatar
朔-望 已提交
226
    for (const auto &var : block.vars()) {
227 228 229 230 231
      if (var.persistable() &&
          var.type().type() != framework::proto::VarType::FEED_MINIBATCH &&
          var.type().type() != framework::proto::VarType::FETCH_LIST) {
        std::string file_path = dirname + "/" + var.name();
        std::ifstream is(file_path);
L
liuruilong 已提交
232 233
        PADDLE_MOBILE_ENFORCE(is.is_open(), "open file: %s failed",
                              file_path.c_str());
朔-望's avatar
朔-望 已提交
234 235
        std::fpos<mbstate_t> pos;
        pos = is.tellg();  // save   current   position
236
        is.seekg(0, std::ios::end);
朔-望's avatar
朔-望 已提交
237
        is.seekg(pos);  // restore   saved   position
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

        // 1. version
        uint32_t version;
        is.read(reinterpret_cast<char *>(&version), sizeof(version));

        // 2 Lod information
        uint64_t lod_level;
        is.read(reinterpret_cast<char *>(&lod_level), sizeof(lod_level));
        for (uint64_t i = 0; i < lod_level; ++i) {
          uint64_t size;
          is.read(reinterpret_cast<char *>(&size), sizeof(size));
          std::vector<size_t> tmp(size / sizeof(size_t));
          is.read(reinterpret_cast<char *>(tmp.data()),
                  static_cast<std::streamsize>(size));
          for (int j = 0; j < tmp.size(); ++j) {
          }
朔-望's avatar
朔-望 已提交
254
        }
255

256 257 258 259 260 261 262 263 264 265 266
        is.read(reinterpret_cast<char *>(&version), sizeof(version));

        int32_t size;
        is.read(reinterpret_cast<char *>(&size), sizeof(size));
        std::unique_ptr<char[]> buf(new char[size]);
        is.read(reinterpret_cast<char *>(buf.get()), size);

        framework::proto::VarType::TensorDesc desc;
        desc.ParseFromArray(buf.get(), size);

        int memory_size = 1;
朔-望's avatar
朔-望 已提交
267 268
        for (long long l : desc.dims()) {
          memory_size *= l;
269
        }
270 271 272

        int type_size = 0;
        switch (desc.data_type()) {
朔-望's avatar
朔-望 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
          case framework::proto::VarType::FP16:
            type_size = 2;
            break;
          case framework::proto::VarType::FP32:
            type_size = 4;
            break;
          case framework::proto::VarType::FP64:
            type_size = 8;
            break;
          case framework::proto::VarType::INT32:
            type_size = 4;
            break;
          case framework::proto::VarType::INT64:
            type_size = 8;
            break;
          case framework::proto::VarType::BOOL:
            type_size = 1;
            break;
          default:
            break;
293 294 295 296 297 298
        }

        void *memory = malloc(memory_size * type_size);
        is.read(static_cast<char *>(memory), memory_size * type_size);
        is.close();
      } else {
L
liuruilong 已提交
299
        // TODO
300
      }
朔-望's avatar
朔-望 已提交
301
    }
302
  }
朔-望's avatar
朔-望 已提交
303 304

#endif
305
  return program;
朔-望's avatar
朔-望 已提交
306
}
朔-望's avatar
朔-望 已提交
307

朔-望's avatar
朔-望 已提交
308
template class Loader<CPU, Precision::FP32>;
朔-望's avatar
朔-望 已提交
309

L
liuruilong 已提交
310 311 312 313 314 315 316 317 318 319
#pragma mark - executor

template <typename Dtype, Precision P>
Executor<Dtype, P>::Executor(const framework::Program<Dtype> p) : program_(p) {
  if (use_optimize_) {
    to_predict_program_ = program_.optimizeProgram;
  } else {
    to_predict_program_ = program_.originProgram;
  }

L
liuruilong 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  const std::vector<std::shared_ptr<framework::BlockDesc>> blocks =
      to_predict_program_->Blocks();
  for (int i = 0; i < blocks.size(); ++i) {
    std::shared_ptr<framework::BlockDesc> block_desc = blocks[i];
    std::vector<std::shared_ptr<framework::OpDesc>> ops = block_desc->Ops();
    for (int j = 0; j < ops.size(); ++j) {
      std::shared_ptr<framework::OpDesc> op = ops[j];
      //              auto op_base =
      //              framework::OpRegistry<Dtype>::CreateOp(op->Type(),
      //                      op->GetInputs(), op->GetOutputs(),
      //                      op->GetAttrMap(), program_.scope);
      //              op_base->InferShape();
    }
  }
  InitMemory();
L
liuruilong 已提交
335 336 337
}

template <typename Dtype, Precision P>
L
liuruilong 已提交
338 339
void Executor<Dtype, P>::LoadMemory(framework::LoDTensor *tensor,
                                    const std::string &file_path) {
L
liuruilong 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
  std::ifstream is(file_path);
  PADDLE_MOBILE_ENFORCE(is.is_open(), "open file: %s failed",
                        file_path.c_str());
  std::fpos<mbstate_t> pos;
  pos = is.tellg();  // save   current   position
  is.seekg(0, std::ios::end);
  is.seekg(pos);  // restore   saved   position

  // 1. version
  uint32_t version;
  is.read(reinterpret_cast<char *>(&version), sizeof(version));

  // 2 Lod information
  uint64_t lod_level;
  is.read(reinterpret_cast<char *>(&lod_level), sizeof(lod_level));
  auto &lod = *tensor->mutable_lod();
  lod.resize(lod_level);
  for (uint64_t i = 0; i < lod_level; ++i) {
    uint64_t size;
    is.read(reinterpret_cast<char *>(&size), sizeof(size));
    std::vector<size_t> tmp(size / sizeof(size_t));
    is.read(reinterpret_cast<char *>(tmp.data()),
            static_cast<std::streamsize>(size));
    for (auto j : tmp) {
      LOG(kLOG_DEBUG1) << "    lod - " << j;
    }
    lod[i] = tmp;
  }

  // 3. tensor version
  uint32_t tensor_version;
  is.read(reinterpret_cast<char *>(&tensor_version), sizeof(tensor_version));

  // 4. tensor desc
  int32_t size;
  is.read(reinterpret_cast<char *>(&size), sizeof(size));
  std::unique_ptr<char[]> buf(new char[size]);
  is.read(reinterpret_cast<char *>(buf.get()), size);

  framework::proto::VarType::TensorDesc desc;
  desc.ParseFromArray(buf.get(), size);

  int memory_size = 1;
  for (auto l : desc.dims()) {
    memory_size *= l;
  }

  std::vector<int64_t> dims;
  dims.reserve(static_cast<size_t>(desc.dims().size()));
  std::copy(desc.dims().begin(), desc.dims().end(), std::back_inserter(dims));
  tensor->Resize(framework::make_ddim(dims));

  void *memory = tensor;
  int type_size = 0;
  switch (desc.data_type()) {
    case framework::proto::VarType::FP16:
      type_size = 2;
      break;
    case framework::proto::VarType::FP32:
      type_size = 4;
      memory = tensor->mutable_data<float>();
      break;
    case framework::proto::VarType::FP64:
      type_size = 8;
      break;
    case framework::proto::VarType::INT32:
      type_size = 4;
      break;
    case framework::proto::VarType::INT64:
      type_size = 8;
      break;
    case framework::proto::VarType::BOOL:
      type_size = 1;
      break;
    default:
      break;
  }

  is.read(static_cast<char *>(memory), memory_size * type_size);
  is.close();
};

template <typename Dtype, Precision P>
void Executor<Dtype, P>::InitMemory() {
  for (const auto &block : to_predict_program_->Blocks()) {
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());
L
liuruilong 已提交
427 428 429 430 431 432 433 434 435
      if (var_desc->Persistable()) {
        auto tensor = var->template GetMutable<framework::LoDTensor>();
        LoadMemory(tensor, program_.model_path + "/" + var_desc->Name());
      } else {
        if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
          auto tensor = var->template GetMutable<framework::Tensor>();
          tensor->template mutable_data<Ptype>();
        }
      }
L
liuruilong 已提交
436 437 438 439 440
    }
  }
}

template <typename Dtype, Precision P>
L
liuruilong 已提交
441 442
std::shared_ptr<framework::Tensor> Executor<Dtype, P>::predict(
    framework::Tensor &t) {
L
liuruilong 已提交
443 444 445 446 447 448 449
  // feed
  auto scope = program_.scope;
  framework::Variable *g_feed_value = scope->Var("pixel");
  auto tensor = g_feed_value->GetMutable<framework::Tensor>();
  tensor->ShareDataWith(t);

  framework::Variable *con_output = scope->Var("conv2d_0.tmp_0");
L
liuruilong 已提交
450 451
  framework::Tensor *output_tensor =
      con_output->GetMutable<framework::Tensor>();
L
liuruilong 已提交
452 453 454 455 456
  output_tensor->mutable_data<float>({1, 16, 32, 32});
  //  std::cout << typeid(output_tensor).name() << std::endl;
  //  std::cout << "output_tensor dims: " << output_tensor->dims() <<
  //  std::endl;

L
liuruilong 已提交
457 458
  std::shared_ptr<framework::Tensor> out_tensor =
      std::make_shared<framework::LoDTensor>();
L
liuruilong 已提交
459 460 461 462 463 464 465 466
  out_tensor.reset(output_tensor);

  predict(t, 0);
  return out_tensor;
}

template <typename Dtype, Precision P>
void Executor<Dtype, P>::predict(const framework::Tensor &t, int block_id) {
L
liuruilong 已提交
467 468 469
  //  framework::Variable *g_feed_value = program_.scope->Var("feed");
  //  auto feed_tensor = g_feed_value->GetMutable<framework::Tensor>();
  //  feed_tensor->ShareDataWith(t);
L
liuruilong 已提交
470 471

  std::shared_ptr<framework::BlockDesc> to_predict_block =
L
liuruilong 已提交
472
      to_predict_program_->Block(block_id);
L
liuruilong 已提交
473 474 475 476 477 478 479
  for (int j = 0; j < ops_of_block_[*to_predict_block.get()].size(); ++j) {
    auto op = ops_of_block_[*to_predict_block.get()][j];
    op->Run();
  }
}

template <typename Dtype, Precision P>
L
liuruilong 已提交
480 481
std::vector<typename Executor<Dtype, P>::Ptype> Executor<Dtype, P>::predict(
    const std::vector<Ptype> &input, const std::vector<int64_t> &dims) {
L
liuruilong 已提交
482 483 484 485 486
  DLOG << "start predict: ";

  framework::Tensor tensor;
  auto ddim = framework::make_ddim(dims);

L
liuruilong 已提交
487
  auto input_ptr = tensor.mutable_data<Ptype>(ddim);
L
liuruilong 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501
  for (int i = 0; i < input.size(); ++i) {
    input_ptr[i] = input[i];
  }

  predict(tensor, 0);

  framework::Variable *g_feed_value = program_.scope->Var("col");
  auto feed_tensor = g_feed_value->GetMutable<framework::Tensor>();

  return {};
}

template class Executor<CPU, Precision::FP32>;

朔-望's avatar
朔-望 已提交
502
}  // namespace paddle_mobile