convert.cpp 8.5 KB
Newer Older
1 2


3 4 5
#include "src/enforce.h"
#include "src/var_desc.h"
#include "src/program_desc.h"
6
#include <cstring>
7
#include <cstdlib>
8 9 10 11 12 13 14 15
#include <cmath>
#include <iostream>
#include <utility>
#include <vector>
#include "src/framework.pb-c.h"
#include "src/protobuf-c.h"
#include <fstream>
#include <iostream>
X
xiebaiyuan 已提交
16
#include <limits>
17
#include <limits>
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54


const size_t kSize64 = sizeof(uint64_t);
const size_t kSize32 = sizeof(uint32_t);

char *Get_binary_data(const std::string &filename) {

    FILE *file = fopen(filename.c_str(), "rb");

    PADDLE_MOBILE_ENFORCE(file != nullptr, "can't open file: %s ",
                          filename.c_str());
    fseek(file, 0, SEEK_END);
    int64_t size = ftell(file);

    PADDLE_MOBILE_ENFORCE(size > 0, "size is too small");
    rewind(file);
    auto *data = new char[size];
    size_t bytes_read = fread(data, 1, static_cast<size_t>(size), file);
    PADDLE_MOBILE_ENFORCE(bytes_read == size,
                          "read binary file bytes do not match with fseek");
    fclose(file);
    return data;
}


static size_t ReadBuffer(const char *file_name, uint8_t **out) {
    FILE *fp;
    fp = fopen(file_name, "rb");
    PADDLE_MOBILE_ENFORCE(fp != nullptr, " %s open failed !", file_name);
    fseek(fp, 0, SEEK_END);
    auto size = static_cast<size_t>(ftell(fp));
    rewind(fp);
    *out = reinterpret_cast<uint8_t *>(malloc(size));
    size_t cur_len = 0;
    size_t nread;
    while ((nread = fread(*out + cur_len, 1, size - cur_len, fp)) != 0) {
        cur_len += nread;
55
    }
56 57 58
    fclose(fp);
    return cur_len;
}
59

60 61 62 63 64 65 66 67 68 69
std::shared_ptr<ProgramDesc> loadParams(const std::string &model_path) {
    PaddleMobile__Framework__Proto__ProgramDesc *c_program;
    uint8_t *buf = nullptr;
    size_t read_size = ReadBuffer(model_path.c_str(), &buf);
    PADDLE_MOBILE_ENFORCE(buf != nullptr, "read from __model__ is null");
    c_program = paddle_mobile__framework__proto__program_desc__unpack(
            nullptr, read_size, buf);
    PADDLE_MOBILE_ENFORCE(c_program != nullptr, "program is null");
    auto originProgramDesc = std::make_shared<ProgramDesc>(c_program);
    return originProgramDesc;
70

71
}
72

73 74 75
void LoadWithDump(const paddle_mobile::framework::VarDesc &var_desc, char *dataP, FILE *out_file) {
    // 1. version
    uint32_t version = *reinterpret_cast<uint32_t *>(dataP);
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    // write version
    fwrite(&version, kSize32, 1, out_file);

    dataP += kSize32;

    // 2 Lod information
    auto *lod_level_ptr = new uint64_t();
    memcpy(lod_level_ptr, dataP, kSize64);

    uint64_t lod_level = 0;
    // write lod Information
    fwrite(&lod_level, kSize64, 1, out_file);
    delete lod_level_ptr;

    dataP += kSize64;

    for (uint64_t i = 0; i < lod_level; ++i) {
        uint64_t size = *reinterpret_cast<uint64_t *>(dataP);
        // write lod size
        fwrite(&size, kSize64, 1, out_file);
        (dataP) += kSize64;

        std::vector<size_t> tmp(size / sizeof(size_t));
        for (unsigned long &k : tmp) {
            k = *reinterpret_cast<size_t *>(dataP);
            (dataP) += sizeof(size_t);
103
        }
104 105 106 107 108 109 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        // write lod size vector
        fwrite(&tmp, sizeof(size_t), tmp.size(), out_file);
    }

    // 3. tensor version
    uint32_t tensor_version = *reinterpret_cast<uint32_t *>(dataP);
    // write tensor version
    fwrite(&tensor_version, kSize32, 1, out_file);
    (dataP) += kSize32;

    // 4. tensor desc
    int32_t size = *reinterpret_cast<int32_t *>(dataP);
    // write tensor desc
    fwrite(&size, sizeof(int32_t), 1, out_file);
    (dataP) += sizeof(int32_t);

    std::unique_ptr<char[]> buf(new char[size]);
    for (int m = 0; m < size; ++m) {
        buf.get()[m] = (dataP)[m];
    }

    fwrite(buf.get(), sizeof(char), static_cast<size_t>(size), out_file);
    (dataP) += (sizeof(char) * size);

    const paddle_mobile::framework::TensorDesc &desc = var_desc.Tensor_desc();
    int memory_size = 1;
    for (auto l : desc.Dims()) {
        memory_size *= l;
    }

    void *memory = nullptr;
    int type_size = 0;
    switch (desc.DataType()) {
        case paddle_mobile::framework::VARTYPE_TYPE_FP16:
            type_size = 2;
            break;
        case paddle_mobile::framework::VARTYPE_TYPE_FP32:
            type_size = 4;
            break;
        case paddle_mobile::framework::VARTYPE_TYPE_FP64:
            type_size = 8;
            break;
        case paddle_mobile::framework::VARTYPE_TYPE_INT32:
            type_size = 4;
            break;
        case paddle_mobile::framework::VARTYPE_TYPE_INT64:
            type_size = 8;
            break;
        case paddle_mobile::framework::VARTYPE_TYPE_BOOL:
            type_size = 1;
            break;
        default:
            break;
    }
    size_t tensorSize = sizeof(char) * memory_size * type_size;

    memory = new char[tensorSize];

    for (int n = 0; n < tensorSize; ++n) {
        static_cast<char *>(memory)[n] = (dataP)[n];
    }
    dataP += tensorSize;

    // for float 32
    float min_value = std::numeric_limits<float>::max();
    float max_value = std::numeric_limits<float>::min();
170

171 172 173 174 175 176 177
    for (int k = 0; k < memory_size; ++k) {
        min_value = std::min(min_value, static_cast<float *> (memory)[k]);
        max_value = std::max(max_value, static_cast<float *> (memory)[k]);
    }

    fwrite(&min_value, sizeof(float), 1, out_file);
    fwrite(&max_value, sizeof(float), 1, out_file);
178

179 180 181 182
    for (int g = 0; g < memory_size; ++g) {
        float value = static_cast<float *> (memory)[g];
        auto factor = (uint8_t) round((value - min_value) / (max_value - min_value) * 255);
        fwrite(&factor, sizeof(uint8_t), 1, out_file);
183
    }
184
}
185

186 187 188 189 190 191 192 193 194 195 196 197
void
quantificate_combined(const std::string &model_path, const std::string &param_path, const std::string &param_min_path) {

    auto program = loadParams(model_path);
    char *origin_data = Get_binary_data(param_path);
    char *data = origin_data;
    FILE *out_file = fopen(param_min_path.c_str(), "wb");
    for (const auto &block : program->Blocks()) {
        for (const auto &var_desc : block->Vars()) {
            if (var_desc->Persistable()) {
                if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
                    continue;
198
                }
199
                LoadWithDump(*var_desc, data, out_file);
200 201 202
            }
        }
    }
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    fclose(out_file);
    delete origin_data;

}

void quantificate_seperated(const std::string model_dir, const std::string param_min_path) {

    auto program = loadParams(model_dir + "/__model__");

    std::string shell_command = "mkdir " + param_min_path;
    system(shell_command.c_str());

    for (const auto &block : program->Blocks()) {
        for (const auto &var_desc : block->Vars()) {
            if (var_desc->Persistable()) {
                if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
                    continue;
220
                }
221 222 223 224 225 226 227
                std::string file_name = param_min_path + "/" + var_desc->Name();
                FILE *out_file = fopen(file_name.c_str(), "wb");
                char *origin_data = Get_binary_data(model_dir + "/" + var_desc->Name());
                char *data = origin_data;
                LoadWithDump(*var_desc, data, out_file);
                delete origin_data;
                fclose(out_file);
228 229
            }
        }
230 231 232 233 234 235 236 237
    }

}


int main(int argc, char **argv) {

    const std::string kNoteEg = "( eg:  ./quantify 1 your_combined_model_path output_path  or  ./quantify 0 your_seperated_model_path output_path)";
238

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    PADDLE_MOBILE_ENFORCE(argc > 1, "wee need params.%s ", kNoteEg.c_str());

    std::string action_type = argv[1];
    PADDLE_MOBILE_ENFORCE(argc > 1 && (action_type) == "1" || action_type == "0",
                          "only 1 or 2 supported, current is %s %s ",
                          action_type.c_str(),
                          kNoteEg.c_str());

    PADDLE_MOBILE_ENFORCE(argc > 2, "we need your model path. %s ", kNoteEg.c_str());
    std::string base_path = argv[2];

    PADDLE_MOBILE_ENFORCE(argc > 3, "we need your output path. %s ", kNoteEg.c_str());
    std::string output_path = argv[3];

    if (action_type == "0") {
        // for seperated
        const std::string &seperated_min_dir = output_path;
        quantificate_seperated(base_path, seperated_min_dir);
        return 0;
258
    }
259 260 261 262 263 264 265

    if (action_type == "1") {
        // for combined
        const std::string &combined_min_dir = output_path;
        std::string model_path = base_path + "/model";
        std::string param_path = base_path + "/params";
        quantificate_combined(model_path, param_path, combined_min_dir);
266 267 268 269

        return 0;
    }

270 271 272
    return -1;
}

273 274 275 276 277