file_cache.cpp 7.6 KB
Newer Older
1 2
/**
 * \file lite/src/mge/algo_cache/file_cache.cpp
3
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
4
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6
 *
7 8 9
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 */

#include "lite_build_config.h"

#if LITE_BUILD_WITH_MGE
#include "../common.h"
#include "file_cache.h"

using namespace lite;

//////////////////////// InFilePersistentCache::InputMemory ///////////////
class InFilePersistentCache::InputMemory {
    const uint8_t* m_ptr;
    size_t m_offset = 0;
    size_t m_size;

public:
    InputMemory(const uint8_t* bin, size_t size) : m_ptr{bin}, m_size{size} {}

    template <typename T>
    void read(T& val) {
M
Megvii Engine Team 已提交
31 32 33
        static_assert(
                std::is_trivially_copyable<T>::value,
                "only support trivially copyable type");
34 35 36 37 38 39 40 41
        LITE_ASSERT(m_offset + sizeof(T) <= m_size);
        memcpy(&val, m_ptr, sizeof(T));
        m_offset += sizeof(T);
        m_ptr += sizeof(T);
    }

    template <typename T>
    void read(T* buf, size_t size) {
M
Megvii Engine Team 已提交
42 43 44
        static_assert(
                std::is_trivially_copyable<T>::value && sizeof(T) == 1,
                "only support read bytes");
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        LITE_ASSERT(m_offset + size <= m_size);
        memcpy(buf, m_ptr, size);
        m_offset += size;
        m_ptr += size;
    }
};

//////////////////////// InFilePersistentCache::InputFile ///////////////
class InFilePersistentCache::InputFile {
    FILE* m_fp;

public:
    InputFile(const char* path) : m_fp{fopen(path, "rb")} {
        LITE_ASSERT(m_fp, "failed to open %s: %s", path, strerror(errno));
    }
    ~InputFile() {
        if (m_fp) {
            fclose(m_fp);
        }
    }

    template <typename T>
    void read(T& val) {
M
Megvii Engine Team 已提交
68 69 70
        static_assert(
                std::is_trivially_copyable<T>::value,
                "only support trivially copyable type");
71 72 73 74 75 76
        auto ret = fread(&val, sizeof(T), 1, m_fp);
        LITE_ASSERT(ret == 1);
    }

    template <typename T>
    void read(T* buf, size_t size) {
M
Megvii Engine Team 已提交
77 78 79
        static_assert(
                std::is_trivially_copyable<T>::value && sizeof(T) == 1,
                "only support read bytes");
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        auto ret = fread(buf, size, 1, m_fp);
        LITE_ASSERT(ret == 1);
    }
};

//////////////////////// InFilePersistentCache::OutputFile ///////////////
class InFilePersistentCache::OutputFile {
    FILE* m_fp;

public:
    OutputFile(const char* path) : m_fp{fopen(path, "wb")} {
        LITE_ASSERT(m_fp, "failed to open %s: %s", path, strerror(errno));
    }
    ~OutputFile() {
        if (m_fp) {
            fclose(m_fp);
        }
    }

    template <typename T>
    void write(T val) {
        auto ret = fwrite(&val, sizeof(T), 1, m_fp);
        LITE_ASSERT(ret == 1);
    }

    template <typename T>
    void write(const T* buf, size_t size) {
        static_assert(sizeof(T) == 1, "only support write bytes");
        auto ret = fwrite(buf, size, 1, m_fp);
        LITE_ASSERT(ret == 1);
    }

    void flush() { fflush(m_fp); }

    void set_head() { fseek(m_fp, 0, SEEK_SET); }
};

//////////////////////// InFilePersistentCache::BlobStorage ///////////////

template <typename Input>
M
Megvii Engine Team 已提交
120 121
InFilePersistentCache::BlobStorage& InFilePersistentCache::BlobStorage::init_from_input(
        Input& inp) {
122 123 124 125 126 127 128 129 130
    uint32_t data_size;
    inp.read(data_size);
    size = data_size;
    data_refhold = std::make_unique<uint8_t[]>(size);
    inp.read(data_refhold.get(), size);
    ptr = data_refhold.get();
    return *this;
}

M
Megvii Engine Team 已提交
131
void InFilePersistentCache::BlobStorage::write_to_file(OutputFile& out_file) const {
132 133 134 135 136
    uint32_t u_size = size;
    out_file.write(u_size);
    out_file.write(data_refhold.get(), u_size);
}

M
Megvii Engine Team 已提交
137 138
InFilePersistentCache::BlobStorage& InFilePersistentCache::BlobStorage::init_data_ref(
        const Blob& b) {
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 170 171 172 173 174
    data_refhold = std::make_unique<uint8_t[]>(b.size + 1);
    memcpy(data_refhold.get(), b.ptr, b.size);
    data_refhold.get()[b.size] = 0;  // for C-string safety
    ptr = data_refhold.get();
    size = b.size;
    return *this;
}

//////////////////////// InFilePersistentCache //////////////////////

template <typename Input>
void InFilePersistentCache::read_cache(Input& inp) {
    uint32_t nr_category;
    inp.read(nr_category);
    char category_buf[256];
    for (uint32_t i = 0; i < nr_category; i++) {
        uint32_t category_size;
        inp.read(category_size);
        inp.read(category_buf, category_size);
        category_buf[category_size] = '\0';

        std::string category(category_buf);
        mgb_log_debug("load new category: %s", category_buf);

        // read bobs
        uint32_t nr_bobs;
        inp.read(nr_bobs);
        for (uint32_t j = 0; j < nr_bobs; j++) {
            BlobStorage key_storage;
            key_storage.init_from_input(inp).init_hash();
            mgb_log_debug("read key: %zu", key_storage.hash);
            m_cache[category][std::move(key_storage)].init_from_input(inp);
        }
    }
}

M
Megvii Engine Team 已提交
175
InFilePersistentCache::InFilePersistentCache(const char* path, bool always_open) {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    if (!access(path, F_OK)) {
        mgb_log_debug("use fastrun cache: %s", path);
        InputFile inp(path);
        read_cache<InputFile>(inp);
    }
    if (always_open) {
        m_always_open_file = std::make_shared<OutputFile>(path);
    }
}

InFilePersistentCache::InFilePersistentCache(const uint8_t* bin, size_t size) {
    LITE_ASSERT(bin);
    InputMemory inp(bin, size);
    read_cache<InputMemory>(inp);
}

void InFilePersistentCache::dump_cache(const char* path) {
    OutputFile out_file(path);
    dump_cache(&out_file);
}

void InFilePersistentCache::dump_cache(OutputFile* out_file) {
    uint32_t nr_category = m_cache.size();
    out_file->write(nr_category);

    for (const auto& cached_category : m_cache) {
        uint32_t category_size = cached_category.first.size();
        out_file->write(category_size);
        out_file->write(cached_category.first.data(), category_size);
        mgb_log_debug("write new category: %s", cached_category.first.c_str());

        uint32_t nr_bobs = cached_category.second.size();
        out_file->write(nr_bobs);
        for (const auto& item : cached_category.second) {
            mgb_log_debug("dump key: %zu", item.first.hash);
            item.first.write_to_file(*out_file);
            item.second.write_to_file(*out_file);
        }
    }
}

mgb::Maybe<InFilePersistentCache::Blob> InFilePersistentCache::get(
        const std::string& category, const Blob& key) {
    decltype(m_cache.begin()) iter0;
    {
        MGB_LOCK_GUARD(m_mtx);
        iter0 = m_cache.find(category);
        if (iter0 == m_cache.end())
            return mgb::None;
    }

    BlobStorage key_storage;
    key_storage.Blob::operator=(key);
    key_storage.init_hash();

    MGB_LOCK_GUARD(m_mtx);

    auto iter1 = iter0->second.find(key_storage);
    if (iter1 == iter0->second.end())
        return mgb::None;
    return iter1->second;
}

M
Megvii Engine Team 已提交
239 240
void InFilePersistentCache::put(
        const std::string& category, const Blob& key, const Blob& value) {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    BlobStorage key_storage;
    key_storage.init_data_ref(key).init_hash();

    MGB_LOCK_GUARD(m_mtx);
    auto size0 = m_cache.size();
    m_cache[category][std::move(key_storage)].init_data_ref(value);
    if (m_cache.size() > size0) {
        mgb_log_debug("new cache category: %s", category.c_str());
    }
    if (m_always_open_file) {
        m_always_open_file->set_head();
        dump_cache(m_always_open_file.get());
        m_always_open_file->flush();
    }
}
#endif

// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}