optimize_options.cpp 28.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "megbrain/gopt/inference.h"
#if MGB_ENABLE_TENSOR_RT
#include "megbrain/tensorrt/tensorrt_engine_cache.h"
#endif
#include "lite/global.h"
#include "misc.h"
#include "models/model_lite.h"
#include "models/model_mdl.h"
#include "optimize_options.h"

///////////////////////// fuse and preprocess optimize options ///////////////
namespace lar {
template <>
void FusePreprocessOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (enable_fuse_preprocess) {
18
            LITE_LOG("enable fuse-preprocess optimization");
19 20 21 22 23 24 25 26 27 28 29
            model->get_config().options.fuse_preprocess = true;
        }
    }
}

template <>
void FusePreprocessOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (enable_fuse_preprocess) {
30
            mgb_log("enable fuse-preprocess optimization");
31 32 33 34 35 36
            graph_option.graph_opt.enable_fuse_preprocess();
        }
    }
}
}  // namespace lar
using namespace lar;
37
bool FusePreprocessOption::m_valid;
38
void FusePreprocessOption::update() {
39 40
    m_option_name = "fuse_preprocess";
    enable_fuse_preprocess = FLAGS_enable_fuse_preprocess;
41 42 43
    m_option = {{"enable_fuse_preprocess", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["enable_fuse_preprocess"])
            ->set_value(FLAGS_enable_fuse_preprocess);
44 45 46 47
}

bool FusePreprocessOption::is_valid() {
    bool ret = FLAGS_enable_fuse_preprocess;
48
    return ret || m_valid;
49 50 51 52 53
}

std::shared_ptr<OptionBase> FusePreprocessOption::create_option() {
    static std::shared_ptr<FusePreprocessOption> option(new FusePreprocessOption);
    if (FusePreprocessOption::is_valid()) {
54
        option->update();
55 56 57 58 59 60 61 62
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void FusePreprocessOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
63 64 65
    enable_fuse_preprocess =
            std::static_pointer_cast<lar::Bool>(m_option["enable_fuse_preprocess"])
                    ->get_value();
66 67 68 69
    CONFIG_MODEL_FUN;
}

///////////////////////// weight preprocess optimize options ///////////////
70
bool WeightPreprocessOption::m_valid;
71 72 73 74 75 76
namespace lar {
template <>
void WeightPreprocessOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (weight_preprocess) {
77
            LITE_LOG("enable weight-preprocess optimization");
78 79 80 81 82 83 84 85 86 87 88
            model->get_config().options.weight_preprocess = true;
        }
    }
}

template <>
void WeightPreprocessOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (weight_preprocess) {
89
            mgb_log("enable weight-preprocess optimization");
90 91 92 93 94 95
            graph_option.graph_opt.enable_weight_preprocess();
        }
    }
}
}  // namespace lar

96
void WeightPreprocessOption::update() {
97 98
    m_option_name = "weight_preprocess";
    weight_preprocess = FLAGS_weight_preprocess;
99 100 101
    m_option = {{"weight_preprocess", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["weight_preprocess"])
            ->set_value(FLAGS_weight_preprocess);
102 103 104 105
}

bool WeightPreprocessOption::is_valid() {
    bool ret = FLAGS_weight_preprocess;
106
    return ret || m_valid;
107 108 109 110 111
}

std::shared_ptr<OptionBase> WeightPreprocessOption::create_option() {
    static std::shared_ptr<WeightPreprocessOption> option(new WeightPreprocessOption);
    if (WeightPreprocessOption::is_valid()) {
112
        option->update();
113 114 115 116 117 118 119 120
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void WeightPreprocessOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
121 122 123
    weight_preprocess =
            std::static_pointer_cast<lar::Bool>(m_option["weight_preprocess"])
                    ->get_value();
124 125 126
    CONFIG_MODEL_FUN;
}

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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
///////////////////////// fuse grain optimize options ///////////////
bool FuseGrainOption::m_valid;
namespace lar {
template <>
void FuseGrainOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite>) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (m_fuse_grain) {
            LITE_THROW("enable fuse-grain optimization not support in lite model");
        }
    }
}

template <>
void FuseGrainOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (m_fuse_grain) {
            mgb_log_warn("enable fuse-grain optimization");
            graph_option.graph_opt.enable_fuse_grain();
        }
    }
}
}  // namespace lar

FuseGrainOption::FuseGrainOption() {
    m_option_name = "fuse_grain";
    m_fuse_grain = FLAGS_fuse_grain;
    m_option = {{"fuse_grain", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["fuse_grain"])
            ->set_value(FLAGS_fuse_grain);
}

bool FuseGrainOption::is_valid() {
    return true;
}

std::shared_ptr<OptionBase> FuseGrainOption::create_option() {
    static std::shared_ptr<FuseGrainOption> option(new FuseGrainOption);
    if (FuseGrainOption::is_valid()) {
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void FuseGrainOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
    m_fuse_grain =
            std::static_pointer_cast<lar::Bool>(m_option["fuse_grain"])->get_value();
    CONFIG_MODEL_FUN;
}

181
///// fuse conv bias and nonlinear activation opr optimize options ////////
182
bool FuseConvBiasNonlinearOption::m_valid;
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
namespace lar {
template <>
void FuseConvBiasNonlinearOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    LITE_MARK_USED_VAR(model);
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (enable_fuse_conv_bias_nonlinearity) {
            LITE_THROW("fuse conv+bias+nonlinearity not supported in lite model");
        }
    }
}

template <>
void FuseConvBiasNonlinearOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (enable_fuse_conv_bias_nonlinearity) {
201
            mgb_log("enable fuse conv+bias+nonlinearity optimization");
202 203 204 205 206 207
            graph_option.graph_opt.enable_fuse_conv_bias_nonlinearity();
        }
    }
}
}  // namespace lar

208
void FuseConvBiasNonlinearOption::update() {
209
    m_option_name = "fuse_conv_bias_nonlinearity";
210
    enable_fuse_conv_bias_nonlinearity = FLAGS_enable_fuse_conv_bias_nonlinearity;
211 212 213
    m_option = {{"enable_fuse_conv_bias_nonlinearity", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["enable_fuse_conv_bias_nonlinearity"])
            ->set_value(FLAGS_enable_fuse_conv_bias_nonlinearity);
214 215 216 217
}

bool FuseConvBiasNonlinearOption::is_valid() {
    bool ret = FLAGS_enable_fuse_conv_bias_nonlinearity;
218
    return ret || m_valid;
219 220 221 222 223 224
}

std::shared_ptr<OptionBase> FuseConvBiasNonlinearOption::create_option() {
    static std::shared_ptr<FuseConvBiasNonlinearOption> option(
            new FuseConvBiasNonlinearOption);
    if (FuseConvBiasNonlinearOption::is_valid()) {
225
        option->update();
226 227 228 229 230 231 232 233
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void FuseConvBiasNonlinearOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
234 235 236 237
    enable_fuse_conv_bias_nonlinearity =
            std::static_pointer_cast<lar::Bool>(
                    m_option["enable_fuse_conv_bias_nonlinearity"])
                    ->get_value();
238 239 240 241
    CONFIG_MODEL_FUN;
}

///////////////////////// fuse and preprocess optimize options ///////////////
242
bool FuseConvBiasElemwiseAddOption::m_valid;
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
namespace lar {
template <>
void FuseConvBiasElemwiseAddOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    LITE_MARK_USED_VAR(model);
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (enable_fuse_conv_bias_with_z) {
            LITE_THROW(
                    "fuse conv+bias+z optimization not supported in lite "
                    "model");
        }
    }
}

template <>
void FuseConvBiasElemwiseAddOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (enable_fuse_conv_bias_with_z) {
263
            mgb_log("enable fuse conv+bias+z optimization");
264 265 266 267 268 269
            graph_option.graph_opt.enable_fuse_conv_bias_with_z();
        }
    }
}
}  // namespace lar

270
void FuseConvBiasElemwiseAddOption::update() {
271
    m_option_name = "fuse_conv_bias_with_z";
272
    enable_fuse_conv_bias_with_z = FLAGS_enable_fuse_conv_bias_with_z;
273 274 275
    m_option = {{"enable_fuse_conv_bias_with_z", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["enable_fuse_conv_bias_with_z"])
            ->set_value(FLAGS_enable_fuse_conv_bias_with_z);
276 277 278 279
}

bool FuseConvBiasElemwiseAddOption::is_valid() {
    bool ret = FLAGS_enable_fuse_conv_bias_with_z;
280
    return ret || m_valid;
281 282 283 284 285 286
}

std::shared_ptr<OptionBase> FuseConvBiasElemwiseAddOption::create_option() {
    static std::shared_ptr<FuseConvBiasElemwiseAddOption> option(
            new FuseConvBiasElemwiseAddOption);
    if (FuseConvBiasElemwiseAddOption::is_valid()) {
287
        option->update();
288 289 290 291 292 293 294 295
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void FuseConvBiasElemwiseAddOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
296 297 298
    enable_fuse_conv_bias_with_z = std::static_pointer_cast<lar::Bool>(
                                           m_option["enable_fuse_conv_bias_with_z"])
                                           ->get_value();
299 300 301
    CONFIG_MODEL_FUN;
}

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
///////////////////////// optimize for inference options ///////////////
bool OptimizeForInferenceOption::m_valid;
namespace lar {
template <>
void OptimizeForInferenceOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    LITE_MARK_USED_VAR(model);
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto optimize_for_infer =
                std::static_pointer_cast<lar::Bool>(m_option["optimize_for_inference"])
                        ->get_value();
        if (optimize_for_infer) {
            LITE_THROW(
                    "optimize for inference not supported in lite "
                    "model");
        }
    }
}

template <>
void OptimizeForInferenceOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::AFTER_MODEL_LOAD) {
        auto optimize_for_infer =
                std::static_pointer_cast<lar::Bool>(m_option["optimize_for_inference"])
                        ->get_value();
        if (optimize_for_infer) {
            mgb_log("enable optimize for inference optimization");
            auto&& load_result = model->get_mdl_load_result();
            mgb::cg::GraphCommonOptimizeOptions opt =
                    model->get_mdl_load_result().graph->options().graph_opt;
            auto inference_opt2 = mgb::gopt::OptimizeForInferenceOptions(opt);
            auto output_var_list = mgb::gopt::optimize_for_inference(
                    load_result.output_var_list, inference_opt2);
            model->get_mdl_load_result().update_output_var_list(output_var_list);
            model->get_mdl_load_result().graph->options().graph_opt.clear();
        }
    }
}
}  // namespace lar

void OptimizeForInferenceOption::update() {
    m_option_name = "optimize_for_inference";
    m_option = {{"optimize_for_inference", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["optimize_for_inference"])
            ->set_value(FLAGS_optimize_for_inference);
}

bool OptimizeForInferenceOption::is_valid() {
    bool ret = FLAGS_optimize_for_inference;
    return ret || m_valid;
}

std::shared_ptr<OptionBase> OptimizeForInferenceOption::create_option() {
    static std::shared_ptr<OptimizeForInferenceOption> option(
            new OptimizeForInferenceOption);
    if (OptimizeForInferenceOption::is_valid()) {
        option->update();
        return option;
    } else {
        return nullptr;
    }
}

void OptimizeForInferenceOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
    CONFIG_MODEL_FUN;
}

371
///////////////////////// graph retrict options /////////////////////////
372
bool GraphRecordOption::m_valid;
373 374 375 376 377 378 379
namespace lar {
template <>
void GraphRecordOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& config_option = model->get_config().options;
        if (const_shape) {
380
            LITE_LOG("enable const var shape");
381 382 383
            config_option.const_shape = true;
        }
        if (fake_first) {
384
            LITE_LOG("enable fake-first optimization");
385 386 387
            config_option.fake_next_exec = true;
        }
        if (no_sanity_check) {
388
            LITE_LOG("disable var sanity check optimization");
389 390 391
            config_option.var_sanity_check_first_run = false;
        }
        if (m_record_comp_seq == 1) {
392
            LITE_LOG("set record_comp_seq_level to 1");
393 394 395 396 397 398
        }
        if (m_record_comp_seq == 2) {
            mgb_assert(
                    no_sanity_check,
                    "--no-sanity-check should be set before "
                    "--record-comp-seq2");
399
            LITE_LOG("set record_comp_seq_level to 2");
400 401 402 403 404 405 406 407 408 409 410
        }
        config_option.comp_node_seq_record_level = m_record_comp_seq;
    }
}

template <>
void GraphRecordOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (const_shape) {
411
            mgb_log("enable const var shape");
412 413 414
            model->get_mdl_config().const_var_shape = true;
        }
        if (fake_first) {
415
            mgb_log("enable fake-first optimization");
416 417 418
            graph_option.fake_next_exec = true;
        }
        if (no_sanity_check) {
419
            mgb_log("disable var sanity check optimization");
420 421 422
            graph_option.var_sanity_check_first_run = false;
        }
        if (m_record_comp_seq == 1) {
423
            mgb_log("set record_comp_seq_level to 1");
424 425 426 427 428 429
        }
        if (m_record_comp_seq == 2) {
            mgb_assert(
                    no_sanity_check && !fake_first,
                    "--no-sanity-check should be set before "
                    "--record-comp-seq2 and --fake-first should not be set");
430
            mgb_log("set record_comp_seq_level to 2");
431 432 433 434 435 436
        }
        graph_option.comp_node_seq_record_level = m_record_comp_seq;
    }
}
}  // namespace lar

437
void GraphRecordOption::update() {
438 439 440 441 442 443 444 445 446 447 448
    m_option_name = "graph_record";
    m_record_comp_seq = 0;
    const_shape = FLAGS_const_shape;
    fake_first = FLAGS_fake_first;
    no_sanity_check = FLAGS_no_sanity_check;
    if (FLAGS_record_comp_seq) {
        m_record_comp_seq = 1;
    }
    if (FLAGS_record_comp_seq2) {
        m_record_comp_seq = 2;
    }
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

    m_option = {
            {"record_comp_seq", lar::Bool::make(false)},
            {"record_comp_seq2", lar::Bool::make(false)},
            {"const_shape", lar::Bool::make(false)},
            {"fake_first", lar::Bool::make(false)},
            {"no_sanity_check", lar::Bool::make(false)}};
    std::static_pointer_cast<lar::Bool>(m_option["const_shape"])
            ->set_value(FLAGS_const_shape);
    std::static_pointer_cast<lar::Bool>(m_option["fake_first"])
            ->set_value(FLAGS_fake_first);
    std::static_pointer_cast<lar::Bool>(m_option["no_sanity_check"])
            ->set_value(FLAGS_no_sanity_check);
    std::static_pointer_cast<lar::Bool>(m_option["record_comp_seq"])
            ->set_value(FLAGS_record_comp_seq);
    std::static_pointer_cast<lar::Bool>(m_option["record_comp_seq2"])
            ->set_value(FLAGS_record_comp_seq2);
466 467 468 469 470 471 472 473
}

bool GraphRecordOption::is_valid() {
    bool ret = FLAGS_const_shape;
    ret = ret || FLAGS_fake_first;
    ret = ret || FLAGS_no_sanity_check;
    ret = ret || FLAGS_record_comp_seq;
    ret = ret || FLAGS_record_comp_seq2;
474
    return ret || m_valid;
475 476 477 478 479
}

std::shared_ptr<OptionBase> GraphRecordOption::create_option() {
    static std::shared_ptr<GraphRecordOption> option(new GraphRecordOption);
    if (GraphRecordOption::is_valid()) {
480
        option->update();
481 482 483 484 485 486 487 488
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void GraphRecordOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
489 490 491 492 493 494
    const_shape =
            std::static_pointer_cast<lar::Bool>(m_option["const_shape"])->get_value();
    fake_first =
            std::static_pointer_cast<lar::Bool>(m_option["fake_first"])->get_value();
    no_sanity_check = std::static_pointer_cast<lar::Bool>(m_option["no_sanity_check"])
                              ->get_value();
495 496 497 498 499 500 501 502
    if (std::static_pointer_cast<lar::Bool>(m_option["record_comp_seq"])->get_value()) {
        m_record_comp_seq = 1;
    } else if (std::static_pointer_cast<lar::Bool>(m_option["record_comp_seq2"])
                       ->get_value()) {
        m_record_comp_seq = 2;
    } else {
        m_record_comp_seq = 0;
    }
503

504 505 506 507 508 509 510 511 512 513 514 515 516 517
    CONFIG_MODEL_FUN;
}
///////////////////////// graph retrict options /////////////////////////
namespace lar {
template <>
void MemoryOptimizeOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    LITE_MARK_USED_VAR(model);
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (disable_mem_opt) {
            LITE_THROW("lite model don't support disable memory optimization");
        }
    } else if (runtime_param.stage == RunStage::AFTER_MODEL_LOAD) {
        if (workspace_limit != SIZE_MAX) {
518
            LITE_LOG("set workspace limit to %ld", workspace_limit);
519 520 521 522 523 524 525 526 527 528 529 530
            lite::Runtime::set_network_algo_workspace_limit(
                    model->get_lite_network(), workspace_limit);
        }
    }
}

template <>
void MemoryOptimizeOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (disable_mem_opt) {
531
            mgb_log("disable memory optimization");
532 533 534 535
            graph_option.seq_opt.enable_mem_plan_opt = false;
            graph_option.seq_opt.enable_mem_reuse_alloc = false;
        }
        if (workspace_limit < SIZE_MAX) {
536
            mgb_log("set workspace limit to %ld", workspace_limit);
537
            auto&& output_spec = model->get_output_spec();
538 539 540 541 542 543 544 545 546 547
            mgb::SymbolVarArray vars;
            for (auto i : output_spec) {
                vars.push_back(i.first);
            }
            mgb::gopt::set_opr_algo_workspace_limit_inplace(vars, workspace_limit);
        }
    }
}
}  // namespace lar

548
void MemoryOptimizeOption::update() {
549 550 551 552 553 554 555 556 557 558 559 560 561 562
    m_option_name = "memory_optimize";
    disable_mem_opt = FLAGS_disable_mem_opt;
    workspace_limit = FLAGS_workspace_limit;
}

bool MemoryOptimizeOption::is_valid() {
    bool ret = FLAGS_disable_mem_opt;
    ret = ret || FLAGS_workspace_limit < SIZE_MAX;
    return ret;
}

std::shared_ptr<OptionBase> MemoryOptimizeOption::create_option() {
    static std::shared_ptr<MemoryOptimizeOption> option(new MemoryOptimizeOption);
    if (MemoryOptimizeOption::is_valid()) {
563
        option->update();
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void MemoryOptimizeOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
    CONFIG_MODEL_FUN;
}

///////////////////////// other options for optimization /////////////////
namespace lar {
template <>
void JITOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& config_option = model->get_config().options;
        if (enable_jit) {
583
            LITE_LOG("enable JIT (level 1)");
584 585 586 587 588 589 590 591 592 593 594
            config_option.jit_level = 1;
        }
    }
}

template <>
void JITOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (enable_jit) {
595
            mgb_log("enable JIT (level 1)");
596 597 598 599 600
            graph_option.graph_opt.jit = 1;
        }
    }
}
}  // namespace lar
601
void JITOption::update() {
602 603 604 605 606 607 608 609 610 611 612 613
    m_option_name = "JIT";
    enable_jit = FLAGS_enable_jit;
}

bool JITOption::is_valid() {
    bool ret = FLAGS_enable_jit;
    return ret;
}

std::shared_ptr<OptionBase> JITOption::create_option() {
    static std::shared_ptr<JITOption> option(new JITOption);
    if (JITOption::is_valid()) {
614
        option->update();
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void JITOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
    CONFIG_MODEL_FUN;
}
///////////////////////// other options for optimization /////////////////
#if MGB_ENABLE_TENSOR_RT
namespace lar {
template <>
void TensorRTOption::config_model_internel<ModelLite>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelLite> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        if (!tensorrt_cache.empty()) {
633
            LITE_LOG("set tensorrt cache as %s", tensorrt_cache.c_str());
634 635 636 637
            lite::set_tensor_rt_cache(tensorrt_cache);
        }
    } else if (runtime_param.stage == RunStage::AFTER_MODEL_LOAD) {
        if (enable_tensorrt) {
638
            LITE_LOG("enable TensorRT");
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
            lite::Runtime::use_tensorrt(model->get_lite_network());
        }
    } else if (runtime_param.stage == RunStage::AFTER_MODEL_RUNNING) {
        if (!tensorrt_cache.empty()) {
            lite::dump_tensor_rt_cache();
        }
    }
}

template <>
void TensorRTOption::config_model_internel<ModelMdl>(
        RuntimeParam& runtime_param, std::shared_ptr<ModelMdl> model) {
    if (runtime_param.stage == RunStage::BEFORE_MODEL_LOAD) {
        auto&& graph_option = model->get_mdl_config().comp_graph->options();
        if (enable_tensorrt) {
654
            mgb_log("using tensorRT");
655 656 657
            graph_option.graph_opt.tensorrt = true;
        }
        if (!tensorrt_cache.empty()) {
658
            mgb_log("use tensorrt cache: %s", tensorrt_cache.c_str());
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
            mgb::TensorRTEngineCache::enable_engine_cache(true);
            mgb::TensorRTEngineCache::set_impl(
                    std::make_shared<mgb::TensorRTEngineCacheIO>(
                            tensorrt_cache.c_str()));
        }
    } else if (runtime_param.stage == RunStage::AFTER_MODEL_RUNNING) {
        if (!tensorrt_cache.empty()) {
            if (mgb::TensorRTEngineCache::enable_engine_cache()) {
                mgb::TensorRTEngineCache::inst().dump_cache();
            }
        }
    }
}
}  // namespace lar

674
void TensorRTOption::update() {
675 676 677 678 679 680 681 682 683 684 685 686 687 688
    m_option_name = "tensorRT";
    enable_tensorrt = FLAGS_tensorrt;
    tensorrt_cache = FLAGS_tensorrt_cache;
}

bool TensorRTOption::is_valid() {
    bool ret = FLAGS_tensorrt;
    ret = ret || !FLAGS_tensorrt_cache.empty();
    return ret;
}

std::shared_ptr<OptionBase> TensorRTOption::create_option() {
    static std::shared_ptr<TensorRTOption> option(new TensorRTOption);
    if (TensorRTOption::is_valid()) {
689
        option->update();
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
        return std::static_pointer_cast<OptionBase>(option);
    } else {
        return nullptr;
    }
}

void TensorRTOption::config_model(
        RuntimeParam& runtime_param, std::shared_ptr<ModelBase> model) {
    CONFIG_MODEL_FUN;
}
#endif
///////////////////////// fuse and preprocess optimize options ///////////////
DEFINE_bool(
        enable_fuse_preprocess, false,
        "Fusion astype | pad_channel | dimshuffle and etc opr from h2d opr");
705
DEFINE_bool(fuse_grain, false, "Enable fusion grain opr to huge opr");
706 707 708 709 710 711 712 713 714 715
DEFINE_bool(
        weight_preprocess, false,
        "Execute operators with weight preprocess, which can optimize the "
        "operator execution time with algo of winograd, im2col ,etc., but "
        "it may consume more memory.");
DEFINE_bool(
        enable_fuse_conv_bias_nonlinearity, false,
        "whether to fuse conv+bias+nonlinearity");
DEFINE_bool(
        enable_fuse_conv_bias_with_z, false,
716
        "fuse conv, bias (elemwise add), z(elemwise add) into one opr "
717
        "(only support on GPU)");
718 719 720
DEFINE_bool(
        optimize_for_inference, false,
        "whether to optimize_for_inference, fuse bn and many base optimize");
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

///////////////////////// graph retrict options /////////////////////////
DEFINE_bool(
        const_shape, false,
        "set const_var_shape to reduce memory usage, since some static "
        "inference data structures can be omitted");
DEFINE_bool(
        fake_first, false,
        "Enable fake exec for the first run. In fake exec mode, some "
        "initialization job would be done, but no actual computing is "
        "performed.");
DEFINE_bool(no_sanity_check, false, "Disable var sanity check on the first run");
DEFINE_bool(
        record_comp_seq, false,
        "Record the computing sequence, in level 1 . It reduces overhead of API"
        "calls of some asynchronous computing devices");
DEFINE_bool(
        record_comp_seq2, false,
        "Record the computing sequence, in level 2, the computing graph can be"
        "destructed to reduce memory usage");
DEFINE_bool(disable_mem_opt, false, "disable memory optimization!!");
DEFINE_uint64(workspace_limit, SIZE_MAX, "set workspace upbound limit");

///////////////////////// other options for optimization /////////////////
DEFINE_bool(
        enable_jit, false,
        " Execute supported operators with JIT(now only support NVRTC). "
        "Can only be used on Nvidia GPUs");
#if MGB_ENABLE_TENSOR_RT
DEFINE_bool(
        tensorrt, false,
        " Execute supported operators with TensorRT. Can only be used on "
        "Nvidia GPUs,i.e. comp node is xpu or gpu.");
DEFINE_string(
        tensorrt_cache, "",
        "Set the TensorRT engine cache path for serialized prebuilt "
        "ICudaEngine");
#endif
759

760
REGIST_OPTION_CREATOR(fuse_preprocess, lar::FusePreprocessOption::create_option);
761 762
REGIST_OPTION_VALIDATER(fuse_preprocess, lar::FusePreprocessOption::set_valid);

763
REGIST_OPTION_CREATOR(weight_preprocess, lar::WeightPreprocessOption::create_option);
764 765
REGIST_OPTION_VALIDATER(weight_preprocess, lar::WeightPreprocessOption::set_valid);

766 767 768
REGIST_OPTION_CREATOR(disable_fuse_grain, lar::FuseGrainOption::create_option);
REGIST_OPTION_VALIDATER(disable_fuse_grain, lar::FuseGrainOption::set_valid);

769
REGIST_OPTION_CREATOR(
770 771 772 773
        fuse_conv_bias_nonlinearity, lar::FuseConvBiasNonlinearOption::create_option);
REGIST_OPTION_VALIDATER(
        fuse_conv_bias_nonlinearity, lar::FuseConvBiasNonlinearOption::set_valid);

774 775 776 777 778
REGIST_OPTION_CREATOR(
        optimize_for_inference, lar::OptimizeForInferenceOption::create_option);
REGIST_OPTION_VALIDATER(
        optimize_for_inference, lar::OptimizeForInferenceOption::set_valid);

779
REGIST_OPTION_CREATOR(
780 781 782 783
        fuse_conv_bias_with_z, lar::FuseConvBiasElemwiseAddOption::create_option);
REGIST_OPTION_VALIDATER(
        fuse_conv_bias_with_z, lar::FuseConvBiasElemwiseAddOption::set_valid);

784
REGIST_OPTION_CREATOR(graph_record, lar::GraphRecordOption::create_option);
785 786
REGIST_OPTION_VALIDATER(graph_record, lar::GraphRecordOption::set_valid);

787 788 789 790 791
REGIST_OPTION_CREATOR(memory_optimize, lar::MemoryOptimizeOption::create_option);
REGIST_OPTION_CREATOR(JIT, lar::JITOption::create_option);
#if MGB_ENABLE_TENSOR_RT
REGIST_OPTION_CREATOR(tensorRT, lar::TensorRTOption::create_option);
#endif