io.cpp 11.0 KB
Newer Older
朔-望's avatar
朔-望 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================*/

#include <fstream>

朔-望's avatar
朔-望 已提交
21
#include "../src/io.h"
L
liuruilong 已提交
22
#include "common/log.h"
朔-望's avatar
朔-望 已提交
23 24 25 26 27 28 29 30
#include "framework/framework.pb.h"
#include "framework/lod_tensor.h"
#include "framework/program_desc.h"
#include "framework/scope.h"
#include "framework/tensor.h"

namespace paddle_mobile {

朔-望's avatar
朔-望 已提交
31
void ReadBinaryFile(const std::string &filename, std::string *contents) {
32 33 34 35 36 37 38
  std::ifstream fin(filename, std::ios::in | std::ios::binary);
  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
朔-望 已提交
39 40 41 42 43
}

template <typename Dtype, Precision P>
void Loader<Dtype, P>::LoadVar(framework::LoDTensor *tensor,
                               const std::string &file_path) {
44 45
  std::ifstream is(file_path);

朔-望's avatar
朔-望 已提交
46 47
  std::fpos<mbstate_t> pos;
  pos = is.tellg();  // save   current   position
48
  is.seekg(0, std::ios::end);
朔-望's avatar
朔-望 已提交
49
  is.seekg(pos);  // restore   saved   position
50 51 52 53 54 55 56 57 58 59 60 61

  // 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
朔-望 已提交
62
    is.read(reinterpret_cast<char *>(&size), sizeof(size));
63 64 65
    std::vector<size_t> tmp(size / sizeof(size_t));
    is.read(reinterpret_cast<char *>(tmp.data()),
            static_cast<std::streamsize>(size));
朔-望's avatar
朔-望 已提交
66 67
    for (auto j : tmp) {
      LOG(kLOG_DEBUG1) << "    lod - " << j;
朔-望's avatar
朔-望 已提交
68
    }
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    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
朔-望 已提交
86 87
  for (auto l : desc.dims()) {
    memory_size *= l;
88 89 90 91 92 93 94
  }

  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
朔-望 已提交
95
  void *memory = tensor;
96 97
  int type_size = 0;
  switch (desc.data_type()) {
朔-望's avatar
朔-望 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    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;
119 120 121 122
  }

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

template <typename Dtype, Precision P>
朔-望's avatar
朔-望 已提交
126 127
const framework::Program<Dtype, P> Loader<Dtype, P>::Load(
    const std::string &dirname) {
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  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;
  program.originProgram = originProgramDesc;

  std::shared_ptr<framework::Scope> scope =
      std::make_shared<framework::Scope>();
  program.scope = scope;

朔-望's avatar
朔-望 已提交
144
  originProgramDesc->Block(0);
145

朔-望's avatar
朔-望 已提交
146
  for (const auto &block : originProgramDesc->Blocks()) {
147 148 149 150 151 152 153
    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) {
朔-望's avatar
朔-望 已提交
154
          auto tensor = var->GetMutable<framework::LoDTensor>();
155 156
          // to load
          LoadVar(tensor, dirname + "/" + var_desc->Name());
157
        }
158
      } else {
朔-望's avatar
朔-望 已提交
159
        //  TODO by someone
160
      }
朔-望's avatar
朔-望 已提交
161
    }
162
  }
163 164

#ifdef PADDLE_MOBILE_DEBUG
朔-望's avatar
朔-望 已提交
165
  for (const auto &block : program_desc_proto.blocks()) {
166 167 168 169 170 171 172 173 174 175
    LOG(kLOG_DEBUG) << "block: " << block.idx();
    for (int j = 0; j < block.ops().size(); ++j) {
      if (j == 2) {
        break;
      }
      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
朔-望 已提交
176 177
        for (const auto &n : var.arguments()) {
          LOG(kLOG_DEBUG3) << "argument - " << n;
178 179 180 181 182 183
        }
      }

      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
朔-望 已提交
184 185
        for (const auto &z : var.arguments()) {
          LOG(kLOG_DEBUG3) << "argument - " << z;
186 187 188
        }
      }

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

        switch (attr.type()) {
朔-望's avatar
朔-望 已提交
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
          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;
223 224 225 226
        }
      }
    }

朔-望's avatar
朔-望 已提交
227
    for (const auto &var : block.vars()) {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
      if (var.type().type() == framework::proto::VarType::LOD_TENSOR) {
        LOG(kLOG_DEBUG1) << "var name: " << var.name();
        const framework::proto::VarType::TensorDesc &tensor_desc =
            var.type().lod_tensor().tensor();
        LOG(kLOG_DEBUG2) << "in var tensor desc dims size: "
                         << tensor_desc.dims().size();
        for (int l = 0; l < tensor_desc.dims().size(); ++l) {
          LOG(kLOG_DEBUG3) << "var tensor desc dim " << l
                           << " value: " << tensor_desc.dims()[l];
        }
      }

      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);
朔-望's avatar
朔-望 已提交
245 246
        std::fpos<mbstate_t> pos;
        pos = is.tellg();  // save   current   position
247
        is.seekg(0, std::ios::end);
朔-望's avatar
朔-望 已提交
248
        is.seekg(pos);  // restore   saved   position
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

        // 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
朔-望 已提交
265
        }
266

267 268 269 270 271 272 273 274 275 276 277
        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
朔-望 已提交
278 279
        for (long long l : desc.dims()) {
          memory_size *= l;
280
        }
281 282 283

        int type_size = 0;
        switch (desc.data_type()) {
朔-望's avatar
朔-望 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
          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;
304 305 306 307 308 309
        }

        void *memory = malloc(memory_size * type_size);
        is.read(static_cast<char *>(memory), memory_size * type_size);
        is.close();
      } else {
朔-望's avatar
朔-望 已提交
310
        //  TODO
311
      }
朔-望's avatar
朔-望 已提交
312
    }
313
  }
朔-望's avatar
朔-望 已提交
314 315

#endif
316
  return program;
朔-望's avatar
朔-望 已提交
317
}
朔-望's avatar
朔-望 已提交
318

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

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