convert.cpp 14.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 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

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;
53
    }
54 55 56
    fclose(fp);
    return cur_len;
}
57

58 59 60 61 62 63 64 65 66 67
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;
68

69
}
70

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

75 76 77
    // write version
    fwrite(&version, kSize32, 1, out_file);

78
    *dataP += kSize32;
79 80 81

    // 2 Lod information
    auto *lod_level_ptr = new uint64_t();
82
    memcpy(lod_level_ptr, *dataP, kSize64);
83 84 85 86 87 88

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

89
    *dataP += kSize64;
90 91

    for (uint64_t i = 0; i < lod_level; ++i) {
92
        uint64_t size = *reinterpret_cast<uint64_t *>(*dataP);
93 94
        // write lod size
        fwrite(&size, kSize64, 1, out_file);
95
        (*dataP) += kSize64;
96 97 98

        std::vector<size_t> tmp(size / sizeof(size_t));
        for (unsigned long &k : tmp) {
99 100
            k = *reinterpret_cast<size_t *>(*dataP);
            (*dataP) += sizeof(size_t);
101
        }
102 103 104 105 106
        // write lod size vector
        fwrite(&tmp, sizeof(size_t), tmp.size(), out_file);
    }

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

    // 4. tensor desc
113
    int32_t size = *reinterpret_cast<int32_t *>(*dataP);
114 115
    // write tensor desc
    fwrite(&size, sizeof(int32_t), 1, out_file);
116
    (*dataP) += sizeof(int32_t);
117 118 119

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

    fwrite(buf.get(), sizeof(char), static_cast<size_t>(size), out_file);
124
    (*dataP) += (sizeof(char) * size);
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

    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) {
161
        static_cast<char *>(memory)[n] = (*dataP)[n];
162
    }
163
    *dataP += tensorSize;
164 165 166 167

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

169 170 171 172 173 174 175
    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);
176

177 178 179 180
    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);
181
    }
182
}
183

184
void
185
quantificate_combined_int8(const std::string &model_path, const std::string &param_path, const std::string &param_min_path) {
186 187 188 189 190 191 192 193 194
    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;
195
                }
196
                LoadWithDumpForInt8(*var_desc, &data, out_file);
197 198 199
            }
        }
    }
200 201 202 203
    fclose(out_file);
    delete origin_data;
}

204
void quantificate_seperated_int8(const std::string model_dir, const std::string param_min_path) {
205 206 207 208 209 210 211 212 213 214
    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;
215
                }
216 217 218 219
                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;
220
                LoadWithDumpForInt8(*var_desc, &data, out_file);
221 222
                delete origin_data;
                fclose(out_file);
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
}

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

    // 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);
        }
        // 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();

    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]);
    }
330

331 332 333 334 335 336 337 338 339
    float diff = 0.0;
    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);
        float value_quantized = min_value + (factor / 255.0) * (max_value - min_value);
        diff += abs(value - value_quantized);
        fwrite(&value_quantized, sizeof(float), 1, out_file);
    }
    std::cout << "avg diff caused by quantization for var " << var_desc.Name() << " is: " << diff << std::endl;
340 341
}

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
void
quantificate_combined_float32(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;
                }
                LoadWithDumpForFloat32(*var_desc, &data, out_file);
            }
        }
    }
    fclose(out_file);
    delete origin_data;
}
361

362 363
void quantificate_seperated_float32(const std::string model_dir, const std::string param_min_path) {
    auto program = loadParams(model_dir + "/__model__");
364

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    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;
                }
                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;
                LoadWithDumpForFloat32(*var_desc, &data, out_file);
                delete origin_data;
                fclose(out_file);
            }
        }
    }
}

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  or  ./quantify 3 your_seperated_model_path output_path  or  ./quantify 2 your_seperated_model_path output_path)";
388

389 390 391
    PADDLE_MOBILE_ENFORCE(argc > 1, "wee need params.%s ", kNoteEg.c_str());

    std::string action_type = argv[1];
392 393
    PADDLE_MOBILE_ENFORCE(argc > 1 && (action_type) == "0" || action_type == "1" || action_type == "2" || action_type == "3",
                          "only 0, 1, 2 or 3 supported, current is %s %s ",
394 395 396 397 398 399 400 401 402 403 404 405
                          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;
406
        quantificate_seperated_int8(base_path, seperated_min_dir);
407
        return 0;
408
    }
409 410 411 412 413 414

    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";
415 416 417 418 419 420 421 422 423 424
        quantificate_combined_int8(model_path, param_path, combined_min_dir);
        return 0;
    }

    if (action_type == "2") {
        // for seperated
        const std::string &seperated_min_dir = output_path;
        quantificate_seperated_float32(base_path, seperated_min_dir);
        return 0;
    }
425

426 427 428 429 430 431
    if (action_type == "3") {
        // 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_float32(model_path, param_path, combined_min_dir);
432 433 434
        return 0;
    }

435 436 437
    return -1;
}