io.cpp 19.1 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>

L
liuruilong 已提交
21
#include "common/log.h"
朔-望's avatar
朔-望 已提交
22 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"
#include "io.h"

namespace paddle_mobile {

31 32 33 34 35 36 37 38
    void ReadBinaryFile(const std::string &filename, std::string *contents) {
        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) {
L
liuruilong 已提交
44
        //        LOG(kLOG_DEBUG) << "  to load " << file_path;
L
liuruilong 已提交
45
        //  Log(kLOG_DEBUG) << "123";
朔-望's avatar
朔-望 已提交
46 47

        std::ifstream is(file_path);
48

L
liuruilong 已提交
49
        std::streampos pos = is.tellg(); //   save   current   position
朔-望's avatar
朔-望 已提交
50
        is.seekg(0, std::ios::end);
L
liuruilong 已提交
51
        //        LOG(kLOG_DEBUG) << "  file length = " << is.tellg();
L
liuruilong 已提交
52
        is.seekg(pos); //   restore   saved   position
朔-望's avatar
朔-望 已提交
53 54 55 56

        // 1. version
        uint32_t version;
        is.read(reinterpret_cast<char *>(&version), sizeof(version));
L
liuruilong 已提交
57
        //        LOG(kLOG_INFO) << "   version: " << version;
朔-望's avatar
朔-望 已提交
58 59 60 61

        // 2 Lod information
        uint64_t lod_level;
        is.read(reinterpret_cast<char *>(&lod_level), sizeof(lod_level));
L
liuruilong 已提交
62 63
        //        LOG(kLOG_DEBUG) << "   load level: " << lod_level;
        //        LOG(kLOG_DEBUG) << "   lod info: ";
64 65
        auto &lod = *tensor->mutable_lod();
        lod.resize(lod_level);
朔-望's avatar
朔-望 已提交
66
        for (uint64_t i = 0; i < lod_level; ++i) {
67 68 69 70 71 72
            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) {
L
liuruilong 已提交
73
                LOG(kLOG_DEBUG1) << "    lod - " << tmp[j];
74 75
            }
            lod[i] = tmp;
朔-望's avatar
朔-望 已提交
76 77
        }

78
        // 3. tensor version
朔-望's avatar
朔-望 已提交
79
        uint32_t tensor_version;
80 81 82
        is.read(reinterpret_cast<char *>(&tensor_version),
                sizeof(tensor_version));
        //  std::cout << "   tensor_version: " << tensor_version << std::endl;
朔-望's avatar
朔-望 已提交
83

84
        // 4. tensor desc
朔-望's avatar
朔-望 已提交
85 86
        int32_t size;
        is.read(reinterpret_cast<char *>(&size), sizeof(size));
87
        //  std::cout << "   tensor desc size: " << size << std::endl;
朔-望's avatar
朔-望 已提交
88 89 90 91 92 93
        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);

94 95
        //  std::cout << "   desc dims size " << desc.dims().size() <<
        //  std::endl;
朔-望's avatar
朔-望 已提交
96 97
        int memory_size = 1;
        for (int l = 0; l < desc.dims().size(); ++l) {
98 99 100 101
            //    std::cout << "    dim " << l << " value: " << desc.dims()[l]
            //    <<
            //    std::endl;
            memory_size *= desc.dims()[l];
朔-望's avatar
朔-望 已提交
102 103
        }

104 105 106 107 108 109 110
        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;
朔-望's avatar
朔-望 已提交
111
        int type_size = 0;
112
        //  std::cout << "    desc pre type: ";
朔-望's avatar
朔-望 已提交
113
        switch (desc.data_type()) {
L
liuruilong 已提交
114
        case framework::proto::VarType::FP16:
115 116 117
            //      std::cout << "FP16" << std::endl;
            type_size = 2;
            break;
L
liuruilong 已提交
118
        case framework::proto::VarType::FP32:
119 120 121 122
            type_size = 4;
            memory = tensor->mutable_data<float>();
            //      std::cout << "FP32" << std::endl;
            break;
L
liuruilong 已提交
123
        case framework::proto::VarType::FP64:
124 125 126
            type_size = 8;
            //      std::cout << "FP64" << std::endl;
            break;
L
liuruilong 已提交
127
        case framework::proto::VarType::INT32:
128 129 130
            type_size = 4;
            //      std::cout << "INT32" << std::endl;
            break;
L
liuruilong 已提交
131
        case framework::proto::VarType::INT64:
132 133 134
            type_size = 8;
            //      std::cout << "INT64" << std::endl;
            break;
L
liuruilong 已提交
135
        case framework::proto::VarType::BOOL:
136 137 138
            type_size = 1;
            //      std::cout << "BOOL" << std::endl;
            break;
L
liuruilong 已提交
139
        default:
140 141
            break;
            //      std::cout << "    not support" << std::endl;
朔-望's avatar
朔-望 已提交
142 143
        }

144 145
        //  std::cout << "    malloc size: " << memory_size * type_size <<
        //  std::endl;
朔-望's avatar
朔-望 已提交
146
        is.read(static_cast<char *>(memory), memory_size * type_size);
147
        //  std::cout << "    memory: " << memory << std::endl;
朔-望's avatar
朔-望 已提交
148
        is.close();
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    };

    template <typename Dtype, Precision P>
    const framework::Program<Dtype, P>
    Loader<Dtype, P>::Load(const std::string &dirname) {
        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;

        auto block = originProgramDesc->Block(0);

        for (auto block : originProgramDesc->Blocks()) {
            //    std::cout << "for block" << std::endl;
            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) {
                        framework::LoDTensor *tensor =
                            var->GetMutable<framework::LoDTensor>();
                        // to load
                        LoadVar(tensor, dirname + "/" + var_desc->Name());
                    }
                } else {
                    //        std::cout << "非 lod" << std::endl;
                }
            }
        }

#ifdef PADDLE_MOBILE_DEBUG
        for (int i = 0; i < program_desc_proto.blocks().size(); ++i) {
            framework::proto::BlockDesc block = program_desc_proto.blocks()[i];
L
liuruilong 已提交
198
            LOG(kLOG_DEBUG) << "block: " << block.idx();
199 200
            for (int j = 0; j < block.ops().size(); ++j) {
                framework::proto::OpDesc op = block.ops()[j];
L
liuruilong 已提交
201
                LOG(kLOG_DEBUG1) << " op: " << op.type();
202 203
                for (int m = 0; m < op.inputs_size(); ++m) {
                    const framework::proto::OpDesc::Var &var = op.inputs(m);
L
liuruilong 已提交
204 205
                    LOG(kLOG_DEBUG2) << "  input parameter: "
                                     << var.parameter();
206
                    for (int n = 0; n < var.arguments().size(); ++n) {
L
liuruilong 已提交
207 208
                        LOG(kLOG_DEBUG3) << "   argument - "
                                         << var.arguments()[n];
209 210 211 212 213
                    }
                }

                for (int y = 0; y < op.outputs_size(); ++y) {
                    const framework::proto::OpDesc::Var &var = op.outputs(y);
L
liuruilong 已提交
214
                    LOG(kLOG_DEBUG2) << "  out parameter: " << var.parameter();
215
                    for (int z = 0; z < var.arguments().size(); ++z) {
L
liuruilong 已提交
216 217
                        LOG(kLOG_DEBUG3) << "   argument - "
                                         << var.arguments()[z];
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 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
                    }
                }

                for (int x = 0; x < op.attrs().size(); ++x) {
                    const framework::proto::OpDesc_Attr attr = op.attrs()[x];
                    //        std::cout << "  attr name: " << attr.name() <<
                    //        std::endl;
                    //        std::cout << "  attr type: " << attr.type() <<
                    //        std::endl;

                    switch (attr.type()) {
                    case framework::proto::AttrType::BOOLEAN:
                        //            std::cout << "   boolen: " << attr.b() <<
                        //            std::endl;
                        break;
                    case framework::proto::AttrType::INT:
                        //            std::cout << "   int: " << attr.i() <<
                        //            std::endl;
                        break;
                    case framework::proto::AttrType::FLOAT:
                    //            std::cout << "   float: " << attr.f() <<
                    //            std::endl;
                    case framework::proto::AttrType::STRING:
                    //            std::cout << "   string: " << attr.s() <<
                    //            std::endl;
                    case framework::proto::AttrType::BOOLEANS:
                        //                            std::vector<bool>
                        //                            bools(attr.bools_size());
                        for (int y = 0; y < attr.bools_size(); ++y) {
                            //              std::cout << "   bool - " <<
                            //              attr.bools(y) <<
                            //              std::endl;
                        }
                    case framework::proto::AttrType::LONG:
                    //            std::cout << "   long: " << attr.l() <<
                    //            std::endl;
                    case framework::proto::AttrType::FLOATS:
                        for (int y = 0; y < attr.floats_size(); ++y) {
                            //              std::cout << "   float - " << y <<
                            //              ": " <<
                            //              attr.floats(y)
                            //                        << std::endl;
                        }
                    case framework::proto::AttrType::INTS:
                        for (int y = 0; y < attr.ints_size(); ++y) {
                            //              std::cout << "   int - " << y << ":
                            //              " <<
                            //              attr.ints(y)
                            //                        << std::endl;
                        }
                    case framework::proto::AttrType::STRINGS:
                        for (int y = 0; y < attr.strings_size(); ++y) {
                            //              std::cout << "   string - " << y <<
                            //              ": " <<
                            //              attr.strings(y)
                            //                        << std::endl;
                        }
                    }
                }
            }

            for (int k = 0; k < block.vars().size(); ++k) {
                framework::proto::VarDesc var = block.vars()[k];
                if (var.type().type() ==
                    framework::proto::VarType::LOD_TENSOR) {
                    //        std::cout << " var name: " << var.name() <<
                    //        std::endl;
                    const framework::proto::VarType::TensorDesc &tensor_desc =
                        var.type().lod_tensor().tensor();
                    //        std::cout << "  in var tensor desc dims size "
                    //                  << tensor_desc.dims().size() <<
                    //                  std::endl;
                    int memory_size = 1;
                    for (int l = 0; l < tensor_desc.dims().size(); ++l) {
                        //          std::cout << " var tensor desc dim " << l
                        //                    << " value: " <<
                        //                    tensor_desc.dims()[l] <<
                        //                    std::endl;
                    }
                }

                if (var.persistable() &&
                    var.type().type() !=
                        framework::proto::VarType::FEED_MINIBATCH &&
                    var.type().type() !=
                        framework::proto::VarType::FETCH_LIST) {
                    //        std::cout << "  to load " << var.name() <<
                    //        std::endl;
                    std::string file_path = dirname + "/" + var.name();
                    std::ifstream is(file_path);
                    std::streampos pos =
                        is.tellg(); //   save   current   position
                    is.seekg(0, std::ios::end);
                    //        std::cout << "  file length = " << is.tellg() <<
                    //        std::endl;
                    is.seekg(pos); //   restore   saved   position

                    // 1. version
                    uint32_t version;
                    is.read(reinterpret_cast<char *>(&version),
                            sizeof(version));
                    //        std::cout << "   version: " << version <<
                    //        std::endl;

                    // 2 Lod information
                    uint64_t lod_level;
                    is.read(reinterpret_cast<char *>(&lod_level),
                            sizeof(lod_level));
                    //        std::cout << "   load level: " << lod_level <<
                    //        std::endl;
                    //        std::cout << "   lod info: " << std::endl;
                    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) {
                            //            std::cout << "    lod - " << tmp[j] <<
                            //            std::endl;
                        }
                    }

                    uint32_t tensor_version;
                    is.read(reinterpret_cast<char *>(&version),
                            sizeof(version));
                    //        std::cout << "   tensor_version: " <<
                    //        tensor_version <<
                    //        std::endl;

                    int32_t size;
                    is.read(reinterpret_cast<char *>(&size), sizeof(size));
                    //        std::cout << "   tensor desc size: " << size <<
                    //        std::endl;
                    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);

                    //        std::cout << "   desc dims size " <<
                    //        desc.dims().size() <<
                    //        std::endl;
                    int memory_size = 1;
                    for (int l = 0; l < desc.dims().size(); ++l) {
                        //          std::cout << "    dim " << l << " value: "
                        //          <<
                        //          desc.dims()[l]
                        //                    << std::endl;
                        memory_size *= desc.dims()[l];
                    }

                    int type_size = 0;
                    //        std::cout << "    desc pre type: ";
                    switch (desc.data_type()) {
                    case framework::proto::VarType::FP16:
                        //            std::cout << "FP16" << std::endl;
                        type_size = 2;
                        break;
                    case framework::proto::VarType::FP32:
                        type_size = 4;
                        //            std::cout << "FP32" << std::endl;
                        break;
                    case framework::proto::VarType::FP64:
                        type_size = 8;
                        //            std::cout << "FP64" << std::endl;
                        break;
                    case framework::proto::VarType::INT32:
                        type_size = 4;
                        //            std::cout << "INT32" << std::endl;
                        break;
                    case framework::proto::VarType::INT64:
                        type_size = 8;
                        //            std::cout << "INT64" << std::endl;
                        break;
                    case framework::proto::VarType::BOOL:
                        type_size = 1;
                        //            std::cout << "BOOL" << std::endl;
                        break;
                    default:
                        break;
                        //            std::cout << "    not support" <<
                        //            std::endl;
                    }

                    //        std::cout << "    malloc size: " << memory_size *
                    //        type_size
                    //                  << std::endl;
                    void *memory = malloc(memory_size * type_size);
                    is.read(static_cast<char *>(memory),
                            memory_size * type_size);
                    //        std::cout << "    memory: " << memory <<
                    //        std::endl;
                    is.close();
                } else {
                    //        std::cout << "  *not load "
                    //                  << " var : " << var.name() << std::endl;
                }
            }
        }
朔-望's avatar
朔-望 已提交
418 419

#endif
420 421
        return program;
    }
朔-望's avatar
朔-望 已提交
422

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

L
liuruilong 已提交
425
} // namespace paddle_mobile