strategy_fitting.cpp 21.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include "strategy_fitting.h"
#if defined(_WIN32)
#include <io.h>
#define F_OK         0
#define access(a, b) _access(a, b)
#elif __linux__ || __unix__ || __APPLE__
#include <unistd.h>
#endif
#include <fstream>
#include <iostream>
#include <list>
#include <regex>
#include <thread>
#include "lite/pack_model.h"
#include "megbrain/common.h"
#include "megbrain/comp_node_env.h"
#include "megbrain/exception.h"
#include "megbrain/utils/timer.h"
#include "megbrain/version.h"
#include "megdnn/version.h"
#include "misc.h"
DECLARE_bool(cpu);
23 24
using namespace lar;

25 26 27 28 29 30 31
// /////////////////// OptionsFastManager ///////////////////
void OptionsFastManager::init(std::shared_ptr<OptionMap>& options) {
    m_option_group_cnt = 0;
    m_fixed_option_cnt = 0;
    m_internal_options_name = {
            {"enable_fuse_conv_bias_with_z"},
            {"enable_fuse_preprocess"},
32 33
            {"record_comp_seq"},
            {"const_shape"}};
34 35 36 37 38 39 40 41 42
    //! record the independent option value
    for (auto& option : *options) {
        auto option_vals = option.second->get_option();
        if (option_vals) {
            for (auto& item : *option_vals) {
                m_valid_option_vals.insert(item);
            }
        }
    }
43 44
};

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 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 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
std::string OptionsFastManager::set_next_fixed_options() {
    reset_option();
    auto& fixed_options_name = m_fixed_options_name[m_fixed_option_cnt];
    for (auto& item : fixed_options_name) {
        if (m_valid_option_vals.find(item) != m_valid_option_vals.end()) {
            auto& option_val = m_valid_option_vals[item];
            auto type = option_val->get_type();
            if (type == JsonValueType::Bool) {
                auto option_val_ptr = std::static_pointer_cast<lar::Bool>(option_val);
                option_val_ptr->set_value(true);
            } else if (type == JsonValueType::String && item == "layout_transform") {
                auto option_val_ptr = std::static_pointer_cast<lar::String>(option_val);
                //! device type
                option_val_ptr->set_value(fixed_options_name[0]);
            } else {
                mgb_log_error(
                        "invalid JsonValueType:%s to set next value for fitting mode",
                        option_val->type_string().c_str());
            }
        }
    }
    ++m_fixed_option_cnt;
    std::string code = m_gflags_coder.encode(m_valid_option_vals);
    return code;
}

std::string OptionsFastManager::set_next_options() {
    reset_option();
    auto& constraint = m_internal_options_name[m_option_group_cnt];
    for (auto& item : constraint) {
        if (m_valid_option_vals.find(item) != m_valid_option_vals.end()) {
            auto& option_val = m_valid_option_vals[item];
            auto type = option_val->get_type();
            if (type == JsonValueType::Bool) {
                auto option_val_ptr = std::static_pointer_cast<lar::Bool>(option_val);
                option_val_ptr->set_value(true);
            } else {
                mgb_log_error(
                        "invalid JsonValueType: %s to set next value for fitting mode",
                        option_val->type_string().c_str());
            }
        }
    }
    ++m_option_group_cnt;
    std::string code = m_gflags_coder.encode(m_valid_option_vals);
    return code;
}

bool OptionsFastManager::is_end_options() {
    return m_option_group_cnt == m_internal_options_name.size();
}

bool OptionsFastManager::is_fixed_end() {
    return m_fixed_option_cnt == m_fixed_options_name.size();
}

void OptionsFastManager::set_options(const std::string& code) {
    reset_option();
#if MGB_ENABLE_JSON
    const std::regex json_regex(".\\{");
#endif
    const std::regex gflags_regex("--.*=.*");
    if (std::regex_search(code, gflags_regex)) {
        m_gflags_coder.decode(code, m_valid_option_vals);
    }
#if MGB_ENABLE_JSON
    else if (std::regex_search(code, json_regex)) {
        m_json_coder.decode(code, m_valid_option_vals);
    }
#endif
    else {
        mgb_log_error("invalid options code format \"%s\" to decode", code.c_str());
    }
}

void OptionsFastManager::registe_fixed_options(
        const std::vector<std::string>& option_name) {
    m_fixed_options_name.push_back(option_name);
}

std::string OptionsFastManager::get_curr_options_code(CoderType type, bool encode_all) {
    if (type == CoderType::GFLAGS) {
        return m_gflags_coder.encode(m_valid_option_vals, encode_all);
    }
#if MGB_ENABLE_JSON
    else if (type == CoderType::JSON) {
        return m_json_coder.encode(m_valid_option_vals, encode_all);
    }
#endif
    else {
        mgb_log_error("coder should be implemented in furture");
        return "";
    }
}
#if MGB_ENABLE_JSON
std::vector<std::shared_ptr<mgb::json::Object>> OptionsFastManager::get_json() {
    std::vector<std::shared_ptr<mgb::json::Object>> ret =
            m_json_coder.encode(m_valid_option_vals);
    return ret;
}
#endif

void OptionsFastManager::reset_option() {
    for (auto& option : m_valid_option_vals) {
        option.second->reset_value();
    }
}

////////////////// OptionsTimeProfiler //////////////////

void OptionsTimeProfiler::profile_with_given_options(
        const std::string& model_path, std::shared_ptr<OptionMap>& given_options,
        const std::string& option_code) {
    RuntimeParam runtime_param;
    auto model = ModelBase::create_model(model_path);
    mgb::RealTimer timer;
    auto stage_config_model = [&]() {
        for (auto& option : *given_options) {
163
            mgb_assert(option.second, "invalid option %s\n", option.first.c_str());
164 165 166 167 168 169 170 171 172
            option.second->config_model(runtime_param, model);
        }
    };

    auto warm_up = [&]() {
        for (size_t i = 0; i < runtime_param.warmup_iter; i++) {
            auto start = timer.get_msecs();
            model->run_model();
            model->wait();
173
            mgb_log("warm up %ld time %f ms", i, timer.get_msecs() - start);
174 175 176 177 178 179 180 181 182
        }
    };
    double inference_time = 0.0;
    auto run_iter = [&]() {
        for (size_t i = 0; i < runtime_param.run_iter; i++) {
            auto start = timer.get_msecs();
            model->run_model();
            model->wait();
            auto end = timer.get_msecs();
183
            mgb_log("run iter %ld time %f ms", i, end - start);
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
            inference_time += end - start;
            mgb_throw_if(
                    inference_time > TIME_OUT, mgb::TimeoutError,
                    "time out while using fitting");
        }
    };

    //! model with testcase
    size_t case_num = runtime_param.testcase_num;

    bool exception_state = false;
    MGB_TRY {
        timer.reset();
        runtime_param.stage = RunStage::BEFORE_MODEL_LOAD;
        stage_config_model();

        model->load_model();
        //! after load configure
        auto config_model_before_runing = [&]() {
            for (auto stage :
                 {RunStage::AFTER_MODEL_LOAD, RunStage::GLOBAL_OPTIMIZATION,
                  RunStage::BEFORE_OUTSPEC_SET, RunStage::AFTER_OUTSPEC_SET,
                  RunStage::MODEL_RUNNING}) {
                runtime_param.stage = stage;
                stage_config_model();
            }
        };
        timer.reset();
        for (size_t idx = 0; idx < case_num; idx++) {
            auto start = timer.get_msecs();
            config_model_before_runing();
            auto end = timer.get_msecs();
216
            mgb_log("config model time %f ms", end - start);
217 218 219 220 221 222 223 224 225 226 227 228 229 230
            warm_up();
            run_iter();
        }
        runtime_param.stage = RunStage::AFTER_MODEL_RUNNING;
        stage_config_model();
    }
    MGB_CATCH(std::exception & exc, {
        mgb_log_error("catch exception: %s", exc.what());
        exception_state = true;
    });

    auto average = inference_time / runtime_param.run_iter;
    if (exception_state) {
        average = TIME_OUT;
231 232 233 234
        mgb_log_error(
                "out of time (this may be caused by some exception, please checkout "
                "the log) when profile option:\n%s\n",
                option_code.c_str());
235
    } else {
236 237
        mgb_log("profile option:\n%s\naverage time = %.2f\n", option_code.c_str(),
                average);
238 239
        //! record profile result
        m_options_profile_result.insert({option_code, average});
240

241
        //! record the best result
242

243 244 245 246
        if (average < m_best_setting.second) {
            m_best_setting.first = option_code;
            m_best_setting.second = average;
        }
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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    }
}
/////////////////////////// UserInfoParser /////////////////////////////
void UserInfoParser::get_user_info() {
    //! register user information tips
    std::vector<std::pair<std::string, std::string>> info_tips;
    m_user_info["fitting_preference"] = "Inferspeed";
}
void UserInfoParser::parse_info(std::shared_ptr<OptionsFastManager>& manager) {
    std::vector<std::string> fixed_options;
    fixed_options.push_back("enable_fuse_conv_bias_nonlinearity");
    std::vector<std::string> tmp_options;

    auto insert_common_cpu_options = [&]() {
        tmp_options = {"cpu"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "weight_preprocess", "fast_run"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "layout_transform"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "layout_transform", "weight_preprocess"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);
    };

#if (MEGDNN_AARCH64 || MEGDNN_ARMV7)
    //! arm cpu device
        insert_common_cpu_options();
        tmp_options = {"cpu", "enable_nchw44"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "enable_nchw44", "weight_preprocess", "fast_run"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "enable_nchw44_dot"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "enable_nchw44_dot", "weight_preprocess", "fast_run"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

#else
#if LITE_WITH_CUDA
    //! build with cuda and not force to use cpu device
    if (!FLAGS_cpu) {
        tmp_options = {"cuda"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cuda", "enable_nchw4"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cuda", "enable_chwn4"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cuda", "enable_nchw64"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cuda", "enable_nchw32"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cuda", "layout_transform"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cuda", "layout_transform", "weight_preprocess"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);
    }

#endif
#if LITE_WITH_CUDA
    //! build with cuda force to use cpu
    if (FLAGS_cpu) {
#endif
        //!x86 cpu options
        insert_common_cpu_options();
        tmp_options = {"cpu", "enable_nchw88"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);

        tmp_options = {"cpu", "enable_nchw88", "weight_preprocess", "fast_run"};
        tmp_options.insert(
                tmp_options.end(), fixed_options.begin(), fixed_options.end());
        manager->registe_fixed_options(tmp_options);
#if LITE_WITH_CUDA
    }
#endif
#endif

    m_proifler_type = ProiflerType::TIME_PROFILER;
}

// /////////////////// FittingStrategy //////////////////////////////////
FittingStrategy::FittingStrategy(std::string model_path) {
    m_manager = std::make_shared<OptionsFastManager>();
    m_dumped_model = FLAGS_dump_fitting_model;
    m_options = std::make_shared<OptionMap>();
    m_model_path = model_path;
    auto option_creator_map = OptionFactory::get_Instance().get_option_creator_map();
    auto option_validater_map =
            OptionFactory::get_Instance().get_option_validater_map();
    //! validate option used in fitting
    auto validate_option = [&](std::string name) -> void {
        if (option_validater_map->find(name) != option_validater_map->end()) {
            auto& validater = (*option_validater_map).at(name);
            if (validater) {
                validater(true);
            }
        }
    };

    //! construct option which is valid
    auto construct_option = [&](std::string name) -> void {
        auto& creator = (*option_creator_map)[name];
        auto option = creator();
        if (option) {
            m_options->insert({name, option});
        }
    };

    //! get all options which is valid
    for (auto& creator : *option_creator_map) {
        auto name = creator.first;
        if (m_options->count(name) == 0) {
            validate_option(name);
            construct_option(name);
        }
    }

    m_manager->init(m_options);
}

void FittingStrategy::dump_best_options_with_model() {
    std::vector<uint8_t> info_algo_policy_data;
    std::vector<uint8_t> info_binary_cache_data;
    auto model = ModelBase::create_model(m_model_path);
    RuntimeParam runtime_param;
    auto stage_config_model = [&]() {
        for (auto& option : *m_options) {
            option.second->config_model(runtime_param, model);
        }
    };
    runtime_param.stage = RunStage::BEFORE_MODEL_LOAD;
    stage_config_model();

    model->load_model();

    //! get json info vector
    std::string json_info_str;
#if MGB_ENABLE_JSON
    std::shared_ptr<mgb::json::Object> code_json = model->get_io_info();
    m_packed_info.push_back({mgb::json::String("IO"), (*code_json)["IO"]});
    auto info_json = m_manager->get_json();
    m_packed_info.push_back({mgb::json::String("options"), (*info_json[0])["options"]});
    m_packed_info.push_back({mgb::json::String("device"), (*info_json[1])["device"]});
    m_packed_info.push_back(
            {mgb::json::String("backend"), mgb::json::String::make("MGE")});
    int lite_major, lite_minor, lite_patch;
    lite::get_version(lite_major, lite_minor, lite_patch);
    std::string version = std::to_string(lite_major);
    version += ".";
    version += std::to_string(lite_minor) + ".";
    version += std::to_string(lite_patch);
    m_packed_info.push_back(
            {mgb::json::String("version"), mgb::json::String::make(version)});
    m_packed_info.push_back({mgb::json::String("valid"), mgb::json::Bool::make(true)});
    m_packed_info.push_back(
            {mgb::json::String("name"), mgb::json::String::make("packed_model")});
    auto obj = mgb::json::Object::make(m_packed_info);
    json_info_str = obj->to_string();
#endif
    std::vector<uint8_t> json_info(json_info_str.begin(), json_info_str.end());

    //! get model binary data after optimized
    for (auto stage :
         {RunStage::AFTER_MODEL_LOAD, RunStage::GLOBAL_OPTIMIZATION,
          RunStage::BEFORE_OUTSPEC_SET, RunStage::AFTER_OUTSPEC_SET,
          RunStage::MODEL_RUNNING}) {
        runtime_param.stage = stage;
        stage_config_model();
    }
    model->run_model();
    model->wait();
    std::vector<uint8_t> model_data = model->get_model_data();
461 462 463 464
    mgb_log("model_data size=%zu", model_data.size());
    mgb_log("json_info size=%zu", json_info.size());
    mgb_log("info_algo_policy_data size=%zu", info_algo_policy_data.size());
    mgb_log("info_binary_cache_data size=%zu", info_binary_cache_data.size());
465 466 467
    lite::ModelPacker packer(
            model_data, m_dumped_model, json_info, info_algo_policy_data,
            info_binary_cache_data);
468
    packer.set_header("NONE", "NONE", info_binary_cache_data.empty());
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    packer.pack_model();
}
///////////////////////// AutoCleanFile///////////////////////////
FittingStrategy::AutoCleanFile::AutoCleanFile(
        const std::string& model_path, std::shared_ptr<OptionMap>& options)
        : m_model_path(model_path), m_options(options) {
    m_filename = "fitting_tmp_model";
    if (!access(m_filename.c_str(), F_OK)) {
        remove(m_filename.c_str());
    }
}

FittingStrategy::AutoCleanFile::~AutoCleanFile() {
    if (!access(m_filename.c_str(), F_OK)) {
        remove(m_filename.c_str());
    }
}

void FittingStrategy::AutoCleanFile::dump_model() {
    auto model = ModelBase::create_model(m_model_path);
    RuntimeParam runtime_param;
    auto stage_config_model = [&]() {
        for (auto& option : *m_options) {
            option.second->config_model(runtime_param, model);
        }
    };
    runtime_param.stage = RunStage::BEFORE_MODEL_LOAD;
    stage_config_model();

    model->load_model();
    //! get model binary data after optimized
    for (auto stage :
         {RunStage::AFTER_MODEL_LOAD, RunStage::GLOBAL_OPTIMIZATION,
          RunStage::BEFORE_OUTSPEC_SET, RunStage::AFTER_OUTSPEC_SET,
          RunStage::MODEL_RUNNING}) {
        runtime_param.stage = stage;
        stage_config_model();
    }
    model->run_model();
    model->wait();

    std::vector<uint8_t> model_data = model->get_model_data();
511
    mgb_log("dumped model_data size=%zu\n", model_data.size());
512 513 514 515 516
    auto fp = fopen(m_filename.c_str(), "wb");
    fwrite(model_data.data(), 1, model_data.size(), fp);
    fclose(fp);
}

517
void FittingStrategy::run() {
518 519
    auto mgb_version = mgb::get_version();
    auto dnn_version = megdnn::get_version();
520 521 522 523
    mgb_log("megbrain/lite/load_and_run:\nusing MegBrain "
            "%d.%d.%d(%d) and MegDNN %d.%d.%d\n",
            mgb_version.major, mgb_version.minor, mgb_version.patch, mgb_version.is_dev,
            dnn_version.major, dnn_version.minor, dnn_version.patch);
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    // ! create profiler with given user info
    m_info_parser.get_user_info();
    m_info_parser.parse_info(m_manager);
    auto profiler = m_info_parser.create_profiler();
    mgb_throw_if(
            profiler == nullptr, mgb::AssertionError,
            "get empty profiler for fittting\n");
    //! profile model with fixed options
    while (!m_manager->is_fixed_end()) {
        std::string option_str = m_manager->set_next_fixed_options();
        profiler->profile_with_given_options(m_model_path, m_options, option_str);
#if (MEGDNN_AARCH64 || MEGDNN_ARMV7)
        //! sleep to keep machine with stable cpu frequence
        usleep(500000);
#endif
    }
    std::string m_tmp_model = m_model_path;
    const std::regex layout_regex("layout_transform");
    auto best_fixed_options = profiler->get_best_setting();
    m_manager->set_options(best_fixed_options);
    //! dump model for global layout transform
    auto m_tmp_file = AutoCleanFile(m_model_path, m_options);
    if (std::regex_search(best_fixed_options, layout_regex)) {
        m_tmp_file.dump_model();
        m_model_path = m_tmp_file.filename();
    }
    //! profile model with given profiler
    while (!m_manager->is_end_options()) {
        std::string curr_option_str = m_manager->set_next_options();
        //! set option with current option and fixed options
        if (m_model_path == m_tmp_model) {
            auto total_option_str = curr_option_str + best_fixed_options;
            m_manager->set_options(total_option_str);
        }

        curr_option_str += best_fixed_options;
        profiler->profile_with_given_options(m_model_path, m_options, curr_option_str);
#if (MEGDNN_AARCH64 || MEGDNN_ARMV7)
        usleep(500000);
#endif
    }
    //! set with best options and inference
    m_model_path = m_tmp_model;
    auto best_options = profiler->get_best_setting();

    m_manager->set_options(best_options);
    profiler->profile_with_given_options(m_model_path, m_options, best_options);

    //! save best options into given dir
    std::cout << "the best options:\n" << best_options << std::endl;
574

575 576 577 578
    if (!m_dumped_model.empty()) {
        dump_best_options_with_model();
    }
}
579
DEFINE_bool(
580 581
        fitting, false, "use the fitting mode profile and get the best option set.");
DEFINE_string(dump_fitting_model, "", "dump the best option and algo cache into model");