profiler_cache.cpp 5.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/**
 * \file src/gopt/impl/profiler_cache.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * 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.
 */

#include "./opr_safe_dump.h"
#include "megbrain/comp_node_env.h"
15
#include "megbrain/gopt/profiler.h"
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

using namespace mgb;
using namespace gopt;
using ReformatKey = ReformatManager::ReformatKey;

// =================== ProfilerCache ======================
void ProfilerCache::Key::build_blob_from_opr() {
    auto&& opr = m_key_impl.opr_key.opr;

    // process  opr param
    auto data = intl::opr_safe_dump(opr);
    size_t param_size = data.size();

    size_t nr_inputs = opr->input().size();
    size_t nr_outputs = opr->usable_output().size();
    size_t nr_layouts = nr_inputs + nr_outputs;
32
    m_blob_storage.reserve(sizeof(TensorLayout) * 3 * nr_layouts + param_size);
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

    // serialize param
    const char* data_ptr = reinterpret_cast<const char*>(data.data());
    m_blob_storage.append(data_ptr, param_size);

    // serialize layouts
    auto append_layout = [this](const VarNode* v) {
        TensorLayout ly{v->shape(), v->dtype(), v->format()};
        for (size_t i = 0; i < ly.ndim; ++i) {
            if (i)
                m_blob_storage.push_back(',');
            m_blob_storage.append(std::to_string(ly.shape[i]));
        }
        if (!ly.is_contiguous()) {
            m_blob_storage.push_back(';');
            for (size_t i = 0; i < ly.ndim; ++i) {
                if (i)
                    m_blob_storage.push_back(',');
                m_blob_storage.append(std::to_string(ly.stride[i]));
            }
        }
        m_blob_storage.push_back(';');
        m_blob_storage.append(ly.dtype.name());
        m_blob_storage.push_back('|');
    };
    for (size_t i = 0; i < nr_inputs; ++i) {
        append_layout(opr->input(i));
    }
    for (size_t i = 0; i < nr_outputs; ++i) {
        append_layout(opr->output(i));
    }

    // serialize opr_format
66 67
    m_blob_storage.append(
            std::to_string(static_cast<uint32_t>(m_key_impl.opr_key.opr_format)));
68 69

    // serialize extra_attribute
70 71
    m_blob_storage.append(
            std::to_string(static_cast<uint32_t>(m_key_impl.opr_key.extra_attribute)));
72 73 74 75 76 77 78 79 80
}

void ProfilerCache::Key::build_category(CompNode cn) {
    m_category = "layout_transform_profile:";
    auto&& env = CompNodeEnv::from_comp_node(cn);
    switch (env.property().type) {
#if MGB_CUDA
        case CompNode::DeviceType::CUDA: {
            auto&& prop = env.cuda_env().device_prop;
81 82
            m_category += ssprintf(
                    "plat=cuda;dev=%s;cap=%d.%d", prop.name, prop.major, prop.minor);
83 84 85 86 87 88 89
            break;
        }
#endif
        case CompNode::DeviceType::CPU:
            m_category += "plat=cpu";
            break;
        default:
90 91 92 93
            mgb_throw(
                    MegBrainError,
                    "unsupported comp node for global layout transform "
                    "profiler cache category");
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 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
    }
}

void ProfilerCache::Key::build_blob_from_var() {
    auto v = m_key_impl.var_key.var;

    // serialize layouts
    auto append_layout = [this](const VarNode* v) {
        TensorLayout ly{v->shape(), v->dtype(), v->format()};
        for (size_t i = 0; i < ly.ndim; ++i) {
            if (i)
                m_blob_storage.push_back(',');
            m_blob_storage.append(std::to_string(ly.shape[i]));
        }
        if (!ly.is_contiguous()) {
            m_blob_storage.push_back(';');
            for (size_t i = 0; i < ly.ndim; ++i) {
                if (i)
                    m_blob_storage.push_back(',');
                m_blob_storage.append(std::to_string(ly.stride[i]));
            }
        }
        m_blob_storage.push_back(';');
        m_blob_storage.append(ly.dtype.name());
        m_blob_storage.push_back('|');
    };
    append_layout(v);

    // serialze reformat key
    m_blob_storage.append(m_key_impl.var_key.key.to_string());
}

const std::string& ProfilerCache::Key::category() const {
    mgb_assert(!m_category.empty());
    return m_category;
}

PersistentCache::Blob ProfilerCache::Key::blob() const {
    mgb_assert(!m_blob_storage.empty());
    return {m_blob_storage.data(), m_blob_storage.size()};
}

ProfilerCache& ProfilerCache::inst() {
    static ProfilerCache inst;
    return inst;
}

ProfilerCache& ProfilerCache::set_impl(std::unique_ptr<PersistentCache> impl) {
    mgb_assert(impl != nullptr);
    m_impl.swap(impl);
    return *this;
}

void ProfilerCache::dump_cache(const char* path) {
148 149 150 151
    mgb_assert(
            m_impl->support_dump_cache(),
            "current impl of ProfilerCache does not support dump cache to "
            "file.");
152 153 154 155 156 157 158 159 160 161 162
    auto cache = static_cast<InFilePersistentCache*>(m_impl.get());
    cache->dump_cache(path);
}

Maybe<ProfilerCache::Result> ProfilerCache::get(const Key& key) {
    auto raw_buf = m_impl->get(key.category(), key.blob());
    if (!raw_buf.valid())
        return None;
    // data type of cost is float
    auto buf = static_cast<const uint8_t*>(raw_buf->ptr);
    auto size = raw_buf->size;
163 164 165
    mgb_assert(
            buf && size == sizeof(float),
            "ProfileCache invalid value: ptr=%p, size=%zu", buf, size);
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    auto read_f32 = [&]() {
        auto ret = *reinterpret_cast<const float*>(buf);
        return ret;
    };
    auto cost = read_f32();
    return cost;
}

void ProfilerCache::put(const Key& key, Result& result) {
    std::string val;
    megdnn::Algorithm::serialize_write_pod(result, val);
    m_impl->put(key.category(), key.blob(), {val.data(), val.size()});
}

// vim: syntax=cpp.doxygen