network.cpp 17.7 KB
Newer Older
1 2
/**
 * \file src/network.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 31 32 33 34 35 36 37 38 39
 */

#include "lite/network.h"
#include "function_base.h"
#include "network_impl_base.h"
#include "parse_info/parse_info_base.h"
#include "parse_model/model_parser.h"
#include "type_info.h"
#if LITE_BUILD_WITH_MGE
#include "mge/function_dft.h"
#include "mge/network_impl.h"
#endif

#include <fstream>
#include <memory>

using namespace lite;

/**
 * \brief Construct the new work implement
 * the order must be :
 * 1. creeat the implement
 * 2. config and load
 * 3. set_io
 */
Network::Network(const Config& config, const NetworkIO& network_io) {
    LITE_ERROR_HANDLER_BEGIN
    m_config = config;
    m_network_io = network_io;
    if (config.backend == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
40 41
        m_impl = call_func<
                NetworkImplDft, std::unique_ptr<lite::Network::NetworkImplBase>>(
42 43 44 45 46 47 48 49 50 51 52 53
                "create_network");
    }
    m_impl->set_config(config);
    m_impl->set_io(network_io);
    LITE_ERROR_HANDLER_END
}

Network::Network(const NetworkIO& network_io, const Config& config) {
    LITE_ERROR_HANDLER_BEGIN
    m_config = config;
    m_network_io = network_io;
    if (config.backend == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
54 55
        m_impl = call_func<
                NetworkImplDft, std::unique_ptr<lite::Network::NetworkImplBase>>(
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
                "create_network");
    }
    m_impl->set_config(config);
    m_impl->set_io(network_io);
    LITE_ERROR_HANDLER_END
}

void Network::load_model(void* model_mem, size_t size) {
    LITE_ERROR_HANDLER_BEGIN
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    //! this model_mem is managed by user
    std::shared_ptr<void> model{model_mem, [](void*) {}};
    prase_model(model, size);
    LITE_ERROR_HANDLER_END
}

void Network::load_model(std::string model_path) {
    LITE_ERROR_HANDLER_BEGIN
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    FILE* fin = fopen(model_path.c_str(), "rb");
M
Megvii Engine Team 已提交
76
    LITE_ASSERT(fin, "failed to open %s: %s", model_path.c_str(), strerror(errno));
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    fseek(fin, 0, SEEK_END);
    size_t size = ftell(fin);
    fseek(fin, 0, SEEK_SET);
    void* ptr = malloc(size);
    std::shared_ptr<void> buf{ptr, ::free};
    auto nr = fread(buf.get(), 1, size, fin);
    LITE_ASSERT(nr == size);
    fclose(fin);
    prase_model(buf, size);
    LITE_ERROR_HANDLER_END
}

void Network::prase_model(std::shared_ptr<void> model_data, size_t size) {
    std::unordered_map<std::string, LiteAny> separate_config_map;
    ModelParser model_parser(model_data, size);
    //! parse the model info
M
Megvii Engine Team 已提交
93 94
    if (model_parser.parse_model_info(
                m_config, m_network_io, separate_config_map, m_extra_info)) {
95 96
        if (m_config.backend == LiteBackend::LITE_DEFAULT &&
            m_impl->get_backend_type() != LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
97
            m_impl.reset(try_call_func<NetworkImplDft, lite::Network::NetworkImplBase*>(
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
                    "parse_model"));
        }
        m_impl->set_config(m_config);
        m_impl->set_io(m_network_io);
    }
    //! decryption the model
    size_t model_length;
    auto&& model_shared_ptr = model_parser.parse_model(model_length, m_config);

    m_impl->load_model(model_shared_ptr, model_length, separate_config_map);
    m_loaded = true;
    update_from_implement();
}

Network::~Network() = default;

void Network::update_from_implement() {
    m_config.device_type = m_impl->get_device_type();
}

void Network::compute_only_configured_output() {
    LITE_ERROR_HANDLER_BEGIN
M
Megvii Engine Team 已提交
120 121 122 123
    LITE_ASSERT(
            !m_loaded,
            "compute_only_configured_output should be used before model "
            "loaded.");
124 125 126 127 128
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->compute_only_configured_output();
    LITE_ERROR_HANDLER_END
}

M
Megvii Engine Team 已提交
129 130
std::shared_ptr<Tensor> Network::get_io_tensor(
        std::string name, LiteTensorPhase phase) {
131 132 133 134 135 136 137 138 139
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(m_loaded, "get_io_tensor should be used after model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_io_tensor(name, phase);
    LITE_ERROR_HANDLER_END
}

std::shared_ptr<Tensor> Network::get_input_tensor(size_t index) {
    LITE_ERROR_HANDLER_BEGIN
M
Megvii Engine Team 已提交
140
    LITE_ASSERT(m_loaded, "get_input_tensor should be used after model loaded.");
141 142 143 144 145 146 147
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_input_tensor(index);
    LITE_ERROR_HANDLER_END
}

std::shared_ptr<Tensor> Network::get_output_tensor(size_t index) {
    LITE_ERROR_HANDLER_BEGIN
M
Megvii Engine Team 已提交
148
    LITE_ASSERT(m_loaded, "get_output_tensor should be used after model loaded.");
149 150 151 152 153 154 155
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_output_tensor(index);
    LITE_ERROR_HANDLER_END
}

Network& Network::set_async_callback(const AsyncCallback& callback) {
    LITE_ERROR_HANDLER_BEGIN
156 157 158 159
    LITE_ASSERT(
            !m_config.options.force_output_use_user_specified_memory,
            "Async mode can't run with force_output_use_user_specified_memory which "
            "output data is written to use specific memory.");
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 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
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    m_impl->set_async_callback(std::move(callback));
    return *this;
    LITE_ERROR_HANDLER_END
}

Network& Network::set_start_callback(const StartCallback& callback) {
    LITE_ERROR_HANDLER_BEGIN
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    m_impl->set_start_callback(std::move(callback));
    return *this;
    LITE_ERROR_HANDLER_END
}

Network& Network::set_finish_callback(const FinishCallback& callback) {
    LITE_ERROR_HANDLER_BEGIN
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    m_impl->set_finish_callback(std::move(callback));
    return *this;
    LITE_ERROR_HANDLER_END
}

Network& Network::set_device_id(int device_id) {
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(!m_loaded, "set_device_id should be used before model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    m_impl->set_device_id(device_id);
    return *this;
    LITE_ERROR_HANDLER_END
}

Network& Network::set_stream_id(int stream_id) {
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(!m_loaded, "set_stream_id should be used before model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    m_impl->set_stream_id(stream_id);
    return *this;
    LITE_ERROR_HANDLER_END
}

void Network::forward() {
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(m_loaded, "forward should be used after model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl.get());
    m_impl->forward();
    LITE_ERROR_HANDLER_END
}

void Network::wait() {
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(m_loaded, "wait should be used after model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    m_impl->wait();
    LITE_ERROR_HANDLER_END
}

std::string Network::get_input_name(size_t index) const {
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(m_loaded, "get_input_name should be used after model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_input_name(index);
    LITE_ERROR_HANDLER_END
}

std::string Network::get_output_name(size_t index) const {
    LITE_ERROR_HANDLER_BEGIN
    LITE_ASSERT(m_loaded, "get_output_name should be used after model loaded.");
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_output_name(index);
    LITE_ERROR_HANDLER_END
}

std::vector<std::string> Network::get_all_input_name() const {
    LITE_ERROR_HANDLER_BEGIN
M
Megvii Engine Team 已提交
234
    LITE_ASSERT(m_loaded, "get_all_input_name should be used after model loaded.");
235 236 237 238 239 240 241 242 243 244 245 246
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    auto all_input_name = m_impl->get_all_input_name();
    std::vector<std::string> all_names;
    for (auto& name : all_input_name) {
        all_names.push_back(name);
    }
    return all_names;
    LITE_ERROR_HANDLER_END
}

std::vector<std::string> Network::get_all_output_name() const {
    LITE_ERROR_HANDLER_BEGIN
M
Megvii Engine Team 已提交
247
    LITE_ASSERT(m_loaded, "get_all_output_name should be used after model loaded.");
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
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    auto all_output_name = m_impl->get_all_output_name();
    std::vector<std::string> all_names;
    for (auto& name : all_output_name) {
        all_names.push_back(name);
    }
    return all_names;
    LITE_ERROR_HANDLER_END
}

int Network::get_device_id() const {
    LITE_ERROR_HANDLER_BEGIN
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_device_id();
    LITE_ERROR_HANDLER_END
}

int Network::get_stream_id() const {
    LITE_ERROR_HANDLER_BEGIN
    LITE_CHECK_NON_NULL_POINTER(m_impl);
    return m_impl->get_stream_id();
    LITE_ERROR_HANDLER_END
}

void Network::enable_profile_performance(std::string profile_file_path) {
    LITE_ERROR_HANDLER_BEGIN
    m_impl->enable_profile_performance(profile_file_path);
    LITE_ERROR_HANDLER_END
}

const std::string& Network::get_model_extra_info() {
    LITE_ERROR_HANDLER_BEGIN
    return m_extra_info;
    LITE_ERROR_HANDLER_END
}

LiteDeviceType Network::get_device_type() const {
    LITE_ERROR_HANDLER_BEGIN
    return m_impl->get_device_type();
    LITE_ERROR_HANDLER_END
}

290 291 292 293 294 295 296 297 298 299 300 301 302 303
void Network::get_static_memory_alloc_info(const std::string& log_dir) const {
    LITE_ERROR_HANDLER_BEGIN
#ifndef __IN_TEE_ENV__
#if MGB_ENABLE_JSON
    LITE_ASSERT(m_loaded, "get_all_output_name should be used after model loaded.");
    m_impl->get_static_memory_alloc_info(log_dir);
    return;
#endif
#endif
    LITE_MARK_USED_VAR(log_dir);
    LITE_THROW("Doesn't support get_static_memory_alloc_info().Please check macro.");
    LITE_ERROR_HANDLER_END
}

304 305
/*********************** MGE special network function ***************/

M
Megvii Engine Team 已提交
306 307
void Runtime::set_cpu_threads_number(
        std::shared_ptr<Network> network, size_t nr_threads) {
308 309 310 311 312 313
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
        LITE_ASSERT(
                !NetworkHelper::loaded(network),
                "set_cpu_threads_number should be used before model loaded.");
M
Megvii Engine Team 已提交
314 315
        call_func<NetworkImplDft, void>(
                "set_cpu_threads_number", network_impl, nr_threads);
316 317 318 319 320 321 322 323 324 325
        return;
    }
    LITE_THROW("set_cpu_threads_number is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

void Runtime::use_tensorrt(std::shared_ptr<Network> network) {
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
326 327 328
        LITE_ASSERT(
                !NetworkHelper::loaded(network),
                "use_tensorrt should be used before model loaded.");
329 330 331 332 333 334 335 336 337 338 339
        call_func<NetworkImplDft, void>("use_tensorrt", network_impl);
        return;
    }
    LITE_THROW("use_tensorrt is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

size_t Runtime::get_cpu_threads_number(const std::shared_ptr<Network> network) {
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
340 341
        return call_func<NetworkImplDft, size_t>(
                "get_cpu_threads_number", network_impl);
342 343 344 345 346 347 348 349 350 351 352
    }
    LITE_THROW("get_cpu_threads_number is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

void Runtime::set_runtime_thread_affinity(
        std::shared_ptr<Network> network,
        const ThreadAffinityCallback& thread_affinity_callback) {
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
353 354 355 356 357 358
        LITE_ASSERT(
                NetworkHelper::loaded(network),
                "set_runtime_thread_affinity should be used after model "
                "loaded.");
        call_func<NetworkImplDft, void>(
                "set_runtime_thread_affinity", network_impl, thread_affinity_callback);
359 360 361 362 363 364 365 366 367 368 369

        return;
    }
    LITE_THROW("set_runtime_thread_affinity is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

void Runtime::set_cpu_inplace_mode(std::shared_ptr<Network> network) {
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
370 371 372
        LITE_ASSERT(
                !NetworkHelper::loaded(network),
                "set_cpu_inplace_mode should be used before model loaded.");
373 374 375 376 377 378 379 380 381 382 383
        call_func<NetworkImplDft, void>("set_cpu_inplace_mode", network_impl);
        return;
    }
    LITE_THROW("set_cpu_inplace_mode is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

bool Runtime::is_cpu_inplace_mode(const std::shared_ptr<Network> network) {
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
384
        return call_func<NetworkImplDft, bool>("is_cpu_inplace_mode", network_impl);
385 386 387 388 389 390
    }
    LITE_THROW("is_cpu_inplace_mode is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

//! set opr algorithm selection strategy in the network
M
Megvii Engine Team 已提交
391 392 393
void Runtime::set_network_algo_policy(
        std::shared_ptr<Network> network, LiteAlgoSelectStrategy strategy,
        uint32_t shared_batch_size, bool binary_equal_between_batch) {
394 395 396
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
397 398 399
        call_func<NetworkImplDft, void>(
                "set_network_algo_policy", network_impl, strategy, shared_batch_size,
                binary_equal_between_batch);
400 401 402 403 404 405 406
        return;
    }
    LITE_THROW("set_network_algo_policy is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

//! set opr algorithm selection strategy in the network
M
Megvii Engine Team 已提交
407 408
void Runtime::set_network_algo_workspace_limit(
        std::shared_ptr<Network> network, size_t workspace_limit) {
409 410 411
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
412 413 414 415 416 417
        LITE_ASSERT(
                NetworkHelper::loaded(network),
                "set_network_algo_policy should be used after model "
                "loaded.");
        call_func<NetworkImplDft, void>(
                "set_network_algo_workspace_limit", network_impl, workspace_limit);
418 419 420 421 422 423 424 425 426
        return;
    }
    LITE_THROW(
            "set_network_algo_workspace_limit is not aviliable in the "
            "backend.");
    LITE_ERROR_HANDLER_END
}

//! set the network memroy allocator, the allocator is defined by user
M
Megvii Engine Team 已提交
427 428
void Runtime::set_memory_allocator(
        std::shared_ptr<Network> network, std::shared_ptr<Allocator> user_allocator) {
429 430 431
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
432 433 434 435 436
        LITE_ASSERT(
                !NetworkHelper::loaded(network),
                "set_memory_allocator should be used before model loaded.");
        call_func<NetworkImplDft, void>(
                "set_memory_allocator", network_impl, user_allocator);
437 438 439 440 441 442
        return;
    }
    LITE_THROW("set_memory_allocator is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

M
Megvii Engine Team 已提交
443 444
void Runtime::share_runtime_memory_with(
        std::shared_ptr<Network> dst_network, std::shared_ptr<Network> src_network) {
445 446 447
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl_dst = NetworkHelper::implement(dst_network);
    if (network_impl_dst->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
448 449 450 451 452 453 454
        LITE_ASSERT(
                !NetworkHelper::loaded(dst_network),
                "share_runtime_memory_with should be used before model "
                "loaded.");
        call_func<NetworkImplDft, void>(
                "share_runtime_memory_with", network_impl_dst,
                NetworkHelper::implement(src_network));
455 456 457 458 459 460
        return;
    }
    LITE_THROW("share_runtime_memory_with is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

M
Megvii Engine Team 已提交
461 462
void Runtime::enable_io_txt_dump(
        std::shared_ptr<Network> network, std::string io_txt_out_file) {
463 464 465
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
466 467
        call_func<NetworkImplDft, void>(
                "enable_io_txt_dump", network_impl, io_txt_out_file);
468 469 470 471 472 473
        return;
    }
    LITE_THROW("enable_io_txt_dump is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

M
Megvii Engine Team 已提交
474 475
void Runtime::enable_io_bin_dump(
        std::shared_ptr<Network> network, std::string io_bin_out_dir) {
476 477 478
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl = NetworkHelper::implement(network);
    if (network_impl->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
479 480
        call_func<NetworkImplDft, void>(
                "enable_io_bin_dump", network_impl, io_bin_out_dir);
481 482 483 484 485 486 487 488 489 490 491 492
        return;
    }
    LITE_THROW("enable_io_bin_dump is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

void Runtime::shared_weight_with_network(
        std::shared_ptr<Network> dst_network,
        const std::shared_ptr<Network> src_network) {
    LITE_ERROR_HANDLER_BEGIN
    auto network_impl_dst = NetworkHelper::implement(dst_network);
    if (network_impl_dst->get_backend_type() == LiteBackend::LITE_DEFAULT) {
M
Megvii Engine Team 已提交
493 494 495 496 497
        LITE_ASSERT(
                NetworkHelper::loaded(src_network),
                "shared_weight_with_network should be used after the src "
                "network "
                "loaded.");
498
        auto src_implment = NetworkHelper::implement(src_network);
M
Megvii Engine Team 已提交
499 500
        call_func<NetworkImplDft, void>(
                "shared_weight_with", network_impl_dst, src_implment);
501 502 503 504 505 506 507 508
        NetworkHelper::loaded(dst_network, true);
        return;
    }
    LITE_THROW("shared_weight_with_network is not aviliable in the backend.");
    LITE_ERROR_HANDLER_END
}

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