You need to sign in or sign up before continuing.
algo_chooser.cpp 49.8 KB
Newer Older
1 2 3 4
/**
 * \file src/opr/impl/search_policy/algo_chooser.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11 12 13
 *
 * 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 "megbrain/opr/search_policy/algo_chooser.h"
14
#include <limits>
15 16
#include <unordered_set>
#include "megbrain/opr/dnn/convolution.h"
17
#include "megbrain/opr/internal/megdnn_opr_wrapper.h"
18
#include "megbrain/opr/search_policy/algo_chooser_helper.h"
19 20 21 22 23 24 25 26
#include "megbrain/opr/search_policy/profiler.h"

#include "../internal/invoke.h"
#include "../internal/megdnn_opr_wrapper.inl"
#include "./workspace_need_limit_getter.inl"

//! TODO: here has to be know some megdnn::opr when there is produced midout.h
//! fix it if there is another graceful way.
27
#include "megdnn/opr_param_defs.h"
28
#include "megdnn/oprs.h"
29
#include "megdnn/oprs/base.h"
30 31 32 33 34 35 36 37
#include "midout.h"
MIDOUT_DECL(megbrain_opr_algo_chooser)
#define MIDOUT_B(...) MIDOUT_BEGIN(megbrain_opr_algo_chooser, __VA_ARGS__) {
#define MIDOUT_E \
    }            \
    MIDOUT_END();

using mgb::opr::intl::WorkspaceLimitGetter;
38 39
using namespace megdnn;
using namespace mgb;
40 41 42 43 44 45 46 47

#define APPLY(statement, ...)                                  \
    mgb::apply([&](const auto&... args) { return statement; }, \
               std::tuple_cat(__VA_ARGS__))

// timeout delta to be added with fastest known algorithm for new algos
constexpr double TIMEOUT_TOLERANCE = 2;

48
#define CACHE_KEY_VERSION "v5"
49 50 51 52 53 54 55 56 57 58

namespace {
template <typename Opr>
std::string profile_name(Opr* opr) {
    std::string ret =
            std::string(MegDNNOpr2MGBOpr<Opr>::MGBOpr::typeinfo()->name) +
            CACHE_KEY_VERSION;
    ret.append(opr->get_algorithm_set_name());
    return ret;
}
59 60 61 62

template <typename Opr>
std::string format_fixlayouts(
        const typename opr::AlgoChooser<Opr>::FixedTensorLayouts& layouts,
63 64
        size_t arity_in, size_t arity_out,
        const std::string& delimiter = " -> ") {
65
    std::string ret;
66 67 68 69 70 71 72
    if (arity_in) {
        ret.append("(");
        for (size_t i = 0; i < arity_in; ++i) {
            if (i) {
                ret.append(", ");
            }
            ret.append(layouts[i].to_string() + " ");
73
        }
74 75 76 77
        ret.append(")");
    }
    if (arity_in && arity_out) {
        ret.append(delimiter);
78
    }
79 80 81 82 83 84 85
    if (arity_out) {
        ret.append("(");
        for (size_t i = 0; i < arity_out; ++i) {
            if (i) {
                ret.append(", ");
            }
            ret.append(layouts[i + arity_in].to_string() + " ");
86
        }
87
        ret.append(")");
88 89 90 91
    }
    return ret;
}

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
/**
 * \brief Check if the sub opr list has circular dependence.
 */
class CircularDepsChecker {
    struct SearchItemStorage {
        std::string data_hold;
        size_t hash = 0;

        SearchItemStorage(const Algorithm::SearchItem& item) {
            Algorithm::serialize_write_pod(item.opr_type, data_hold);
            for (auto&& layout : item.layouts) {
                data_hold += layout.serialize();
            }
            data_hold += item.param;
        }

        SearchItemStorage& init_hash() {
            hash = XXHash64CT::hash(data_hold.data(), data_hold.size(),
                                    20201225);
            return *this;
        }

        bool operator==(const SearchItemStorage& rhs) const {
            return data_hold == rhs.data_hold;
        }

        struct Hash {
            size_t operator()(const SearchItemStorage& s) const {
                return s.hash;
            }
        };
    };
    std::unordered_set<SearchItemStorage, SearchItemStorage::Hash> m_set;

public:
    void put(const megdnn::Algorithm::SearchItem& key) {
        SearchItemStorage key_storage(key);
        key_storage.init_hash();
        mgb_assert(m_set.find(key_storage) == m_set.end(),
                   "Circular dependency during flatten search space");
        auto ret = m_set.insert(std::move(key_storage));
        mgb_assert(ret.second);
    }
    void remove(const megdnn::Algorithm::SearchItem& key) {
        SearchItemStorage key_storage(key);
        key_storage.init_hash();
        auto&& iter = m_set.find(key_storage);
        mgb_assert(iter != m_set.end());
        m_set.erase(iter);
    }
};

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
///////////////// OprTypeTrait /////////////////////////////
template <megdnn::Algorithm::OprType>
struct OprFromOprTypeTrait;

template <typename Opr>
struct OprTypeFromOprTrait;

#define cb(_opr_type, _opr)                                             \
    template <>                                                         \
    struct OprFromOprTypeTrait<megdnn::Algorithm::OprType::_opr_type> { \
        using Opr = megdnn::_opr;                                       \
    };                                                                  \
    template <>                                                         \
    struct OprTypeFromOprTrait<megdnn::_opr> {                          \
        constexpr static megdnn::Algorithm::OprType opr_type =          \
                megdnn::Algorithm::OprType::_opr_type;                  \
    }

cb(MATRIX_MUL_FORWARD, MatrixMulForward);
cb(BATCHED_MATRIX_MUL_FORWARD, BatchedMatrixMulForward);
cb(CONVOLUTION_FORWARD, ConvolutionForward);
cb(CONVOLUTION_BACKWARD_DATA, ConvolutionBackwardData);
cb(CONVOLUTION_BACKWARD_FILTER, ConvolutionBackwardFilter);
cb(CONVOLUTION3D_FORWARD, Convolution3DForward);
cb(CONVOLUTION3D_BACKWARD_DATA, Convolution3DBackwardData);
cb(CONVOLUTION3D_BACKWARD_FILTER, Convolution3DBackwardFilter);
cb(LOCAL_SHARE_FORWARD, LocalShareForward);
cb(LOCAL_SHARE_BACKWARD_DATA, LocalShareBackwardData);
cb(LOCAL_SHARE_BACKWARD_FILTER, LocalShareBackwardFilter);
cb(DEFORMABLE_CONV_FORWARD, DeformableConvForward);
cb(DEFORMABLE_CONV_BACKWARD_DATA, DeformableConvBackwardData);
cb(DEFORMABLE_CONV_BACKWARD_FILTER, DeformableConvBackwardFilter);
cb(BATCH_CONV_FORWARD, BatchConvBiasForward);
cb(CONVBIAS_FORWARD, ConvBiasForward);
178 179
cb(POOLING_FORWARD, PoolingForward);
cb(POOLING_BACKWARD, PoolingBackward);
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

#undef cb

// clang-format off
#define FOREACH_OPR_TYPE_WITH_STMT(cb, stmt)  \
    cb(MATRIX_MUL_FORWARD, stmt)              \
    cb(BATCHED_MATRIX_MUL_FORWARD, stmt)      \
    cb(CONVOLUTION_FORWARD, stmt)             \
    cb(CONVOLUTION_BACKWARD_DATA, stmt)       \
    cb(CONVOLUTION_BACKWARD_FILTER, stmt)     \
    cb(CONVOLUTION3D_FORWARD, stmt)           \
    cb(CONVOLUTION3D_BACKWARD_DATA, stmt)     \
    cb(CONVOLUTION3D_BACKWARD_FILTER, stmt)   \
    cb(LOCAL_SHARE_FORWARD, stmt)             \
    cb(LOCAL_SHARE_BACKWARD_DATA, stmt)       \
    cb(LOCAL_SHARE_BACKWARD_FILTER, stmt)     \
    cb(DEFORMABLE_CONV_FORWARD, stmt)         \
    cb(DEFORMABLE_CONV_BACKWARD_DATA, stmt)   \
    cb(DEFORMABLE_CONV_BACKWARD_FILTER, stmt) \
    cb(BATCH_CONV_FORWARD, stmt)              \
200 201 202
    cb(CONVBIAS_FORWARD, stmt)                \
    cb(POOLING_FORWARD, stmt)                 \
    cb(POOLING_BACKWARD, stmt)
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
// clang-format on

#define _OPR_TYPE_CASE(_opr_type, _stmt)             \
    case Algorithm::OprType::_opr_type: {            \
        using _Opr = typename OprFromOprTypeTrait<   \
                Algorithm::OprType::_opr_type>::Opr; \
        _stmt;                                       \
        break;                                       \
    }

#define FOREACH_OPR_TYPE_DISPATCH(_search_items, _stmt)          \
    for (size_t _item_idx = 0; _item_idx < _search_items.size(); \
         _item_idx++) {                                          \
        auto&& _item = _search_items[_item_idx];                 \
        switch (_item.opr_type) {                                \
            FOREACH_OPR_TYPE_WITH_STMT(_OPR_TYPE_CASE, _stmt)    \
            default:                                             \
                mgb_throw(MegBrainError, "unknown opr_type");    \
        }                                                        \
    }

template <typename Opr>
TensorLayoutArray to_layout_array(
        const typename opr::AlgoChooser<Opr>::FixedTensorLayouts& layouts) {
    TensorLayoutArray ret;
    for (auto&& layout : layouts) {
        ret.push_back(layout);
    }
    return ret;
232 233
}

234 235 236 237 238 239 240 241 242 243 244 245
template <typename Opr>
typename opr::AlgoChooser<Opr>::FixedTensorLayouts to_fixed_layouts(
        const TensorLayoutArray& layouts) {
    typename opr::AlgoChooser<Opr>::FixedTensorLayouts ret;
    mgb_assert(ret.size() == layouts.size());
    size_t idx = 0;
    for (auto&& layout : layouts) {
        ret[idx++] = layout;
    }
    return ret;
}

246 247 248 249 250 251 252 253 254 255 256 257
/**
 * flatten search space in postorder traversal
 * The subopr search construct a search tree
 *
 *           A
 *        /    \
 *       B1B2   C
 *      /     \
 *     D1D2D3   E
 * We use postorder traverse the search tree.
 * D1 -> D2 -> D3 -> E -> B1 -> B2 -> C -> A
 */
258
template <typename Opr>
259
std::vector<megdnn::Algorithm::SearchItem> flatten_search_space(
260
        const typename opr::AlgoChooser<Opr>::AlgoChooserHelper& helper,
261 262
        CircularDepsChecker& checker) {
    auto&& search_item = megdnn::Algorithm::SearchItem{
263
            OprTypeFromOprTrait<Opr>::opr_type, helper.param(),
264
            to_layout_array<Opr>(helper.fastrun_layouts())};
265
    checker.put(search_item);
266
    std::vector<megdnn::Algorithm::SearchItem> ret;
267 268 269
    for (auto algo_info : helper.get_all_candidates()) {
        megdnn::Algorithm* algo =
                helper.get_algorithm_from_desc(algo_info.desc);
270 271
        mgb_assert(algo, "Unknown algo description");
        std::vector<megdnn::Algorithm::SearchItem>&& sub_items =
272 273 274
                algo->get_subopr_list(
                        to_layout_array<Opr>(helper.fastrun_layouts()),
                        helper.megdnn_opr());
275 276

        FOREACH_OPR_TYPE_DISPATCH(sub_items, {
277
            auto&& megdnn_opr =
278
                    opr::intl::create_megdnn_opr<_Opr>(helper.comp_node());
279 280 281
            megdnn_opr->param() =
                    Algorithm::deserialize_read_pod<typename _Opr::Param>(
                            _item.param);
282
            typename opr::AlgoChooser<_Opr>::AlgoChooserHelper sub_helper(
283
                    to_fixed_layouts<_Opr>(_item.layouts), megdnn_opr.get(),
284 285 286 287
                    _item.param, helper.mgb_opr(), helper.comp_node(),
                    helper.execution_policy(),
                    helper.allow_weight_preprocess());
            auto space = flatten_search_space<_Opr>(sub_helper, checker);
288 289
            ret.insert(ret.end(), space.begin(), space.end());
        });
290
    }
291 292
    ret.push_back(search_item);
    checker.remove(search_item);
293 294
    return ret;
}
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
//! serialize a algo's desc to string. format is
//! handle_type|algo_type|size_of_param|size_of_name|string_of_param|string_of_name
static void serialize_write_pod(const Algorithm::Info::Desc& val,
                                std::string& result) {
    megdnn::Algorithm::serialize_write_pod(val.handle_type, result);
    megdnn::Algorithm::serialize_write_pod(val.type, result);
    uint32_t param_size = val.param.size();
    uint32_t name_size = val.name.size();
    megdnn::Algorithm::serialize_write_pod<uint32_t>(param_size, result);
    megdnn::Algorithm::serialize_write_pod<uint32_t>(name_size, result);
    result += val.param;
    result += val.name;
}

static Algorithm::Info::Desc deserialize_read_pod(const std::string& data,
                                                  size_t offset = 0) {
    Algorithm::Info::Desc ret;
#define cb(_val, _type)                                                \
    _val = megdnn::Algorithm::deserialize_read_pod<_type>(data.data(), \
                                                          offset);     \
    offset += sizeof(_val)

    cb(ret.handle_type, megdnn::Handle::HandleType);
    cb(ret.type, uint32_t);

    uint32_t param_size = 0;
    uint32_t name_size = 0;
    cb(param_size, uint32_t);
    cb(name_size, uint32_t);

    if (param_size > 0) {
        ret.param = std::string(data.data() + offset, param_size);
        offset += param_size;
    }
    if (name_size > 0) {
        ret.name = std::string(data.data() + offset, name_size);
        offset += name_size;
    }
    return ret;
}

337 338 339 340
}  // namespace

namespace mgb {
namespace opr {
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 461 462 463 464 465 466 467 468 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
template <class Opr>
class LayoutsModifier {
    using FixedTensorLayouts = typename AlgoChooser<Opr>::FixedTensorLayouts;

public:
    static void on(FixedTensorLayouts&, const typename Opr::Param&, size_t) {}

private:
    //! index of batch in tensor, 3 for CHWN4 e.g.
    static size_t index_of_batch(const typename Opr::Param&) { return 0; }

    //! indices contain batch in inputs and outputs, src(0) dst(2) for conv e.g.
    static std::vector<size_t> sm_indices_contain_batch;
};
template <class Opr>
std::vector<size_t> LayoutsModifier<Opr>::sm_indices_contain_batch = {};

#define DEFAULT_OPR_WITHOUT_INPUT_BROADCAST(opr, idxs)                       \
    template <>                                                              \
    class LayoutsModifier<opr> {                                             \
    public:                                                                  \
        using FixedTensorLayouts =                                           \
                typename AlgoChooser<opr>::FixedTensorLayouts;               \
        static void on(FixedTensorLayouts& layouts, const opr::Param& param, \
                       size_t new_batch_size) {                              \
            size_t batch_index = index_of_batch(param);                      \
            for (size_t index : sm_indices_contain_batch) {                  \
                layouts.at(index)[batch_index] = new_batch_size;             \
            }                                                                \
        }                                                                    \
                                                                             \
    private:                                                                 \
        static size_t index_of_batch(const opr::Param&) { return 0; }        \
        static std::vector<size_t> sm_indices_contain_batch;                 \
    };                                                                       \
    std::vector<size_t> LayoutsModifier<opr>::sm_indices_contain_batch = idxs;

DEFAULT_OPR_WITHOUT_INPUT_BROADCAST(megdnn::Convolution3DForward,
                                    (std::initializer_list<size_t>{0, 2}))
DEFAULT_OPR_WITHOUT_INPUT_BROADCAST(megdnn::Convolution3DBackwardData,
                                    (std::initializer_list<size_t>{1, 2}))
DEFAULT_OPR_WITHOUT_INPUT_BROADCAST(megdnn::Convolution3DBackwardFilter,
                                    (std::initializer_list<size_t>{0, 1}))
DEFAULT_OPR_WITHOUT_INPUT_BROADCAST(megdnn::BatchedMatrixMul,
                                    (std::initializer_list<size_t>{0, 1, 2}))
#undef DEFAULT_OPR_WITHOUT_INPUT_BROADCAST

#define CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(opr, idxs)                     \
    template <>                                                              \
    class LayoutsModifier<opr> {                                             \
    public:                                                                  \
        using FixedTensorLayouts =                                           \
                typename AlgoChooser<opr>::FixedTensorLayouts;               \
        static void on(FixedTensorLayouts& layouts, const opr::Param& param, \
                       size_t new_batch_size) {                              \
            size_t batch_index = index_of_batch(param);                      \
            for (size_t index : sm_indices_contain_batch) {                  \
                layouts.at(index)[batch_index] = new_batch_size;             \
            }                                                                \
        }                                                                    \
                                                                             \
    private:                                                                 \
        static size_t index_of_batch(const opr::Param& param) {              \
            if (param.format == opr::Param::Format::CHWN4) {                 \
                return 3;                                                    \
            }                                                                \
            return 0;                                                        \
        }                                                                    \
        static std::vector<size_t> sm_indices_contain_batch;                 \
    };                                                                       \
    std::vector<size_t> LayoutsModifier<opr>::sm_indices_contain_batch = idxs;

CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::ConvolutionForward,
                                      (std::initializer_list<size_t>{0, 2}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::ConvolutionBackwardData,
                                      (std::initializer_list<size_t>{1, 2}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::ConvolutionBackwardFilter,
                                      (std::initializer_list<size_t>{0, 1}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::LocalShareForward,
                                      (std::initializer_list<size_t>{0, 2}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::LocalShareBackwardData,
                                      (std::initializer_list<size_t>{1, 2}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::LocalShareBackwardFilter,
                                      (std::initializer_list<size_t>{0, 1}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::DeformableConvForward,
                                      (std::initializer_list<size_t>{0, 2, 3,
                                                                     4}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::DeformableConvBackwardData,
                                      (std::initializer_list<size_t>{0, 2, 3, 4,
                                                                     5, 6, 7}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::DeformableConvBackwardFilter,
                                      (std::initializer_list<size_t>{0, 1, 2,
                                                                     3}))
CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST(megdnn::BatchConvBiasForward,
                                      (std::initializer_list<size_t>{0, 1, 2, 3,
                                                                     4}))
#undef CONV_LIKE_OPR_WITHOUT_INPUT_BROADCAST

template <>
class LayoutsModifier<megdnn::ConvBiasForward> {
public:
    using FixedTensorLayouts =
            typename AlgoChooser<megdnn::ConvBiasForward>::FixedTensorLayouts;
    static void on(FixedTensorLayouts& layouts,
                   const megdnn::ConvBiasForward::Param& param,
                   size_t new_batch_size) {
        size_t batch_index = index_of_batch(param);
        for (size_t index : sm_indices_contain_batch) {
            layouts.at(index)[batch_index] = new_batch_size;
        }
        for (size_t index : sm_indices_contain_batch_broadcast) {
            if (!check_bias_share_in_channel(layouts.at(index), param.format)) {
                layouts.at(index)[batch_index] = new_batch_size;
            }
        }
    }

private:
    static std::vector<size_t> sm_indices_contain_batch;
    static std::vector<size_t> sm_indices_contain_batch_broadcast;
    static size_t index_of_batch(const megdnn::ConvBiasForward::Param& param) {
        if (param.format == megdnn::ConvBiasForward::Param::Format::CHWN4) {
            return 3;
        }
        return 0;
    }
};
std::vector<size_t>
        LayoutsModifier<megdnn::ConvBiasForward>::sm_indices_contain_batch = {
                0, 3, 4};
std::vector<size_t> LayoutsModifier<
        megdnn::ConvBiasForward>::sm_indices_contain_batch_broadcast = {2};

template <>
class LayoutsModifier<megdnn::MatrixMul> {
public:
    using FixedTensorLayouts=
            typename AlgoChooser<megdnn::MatrixMul>::FixedTensorLayouts;
    static void on(FixedTensorLayouts& layouts,
                   const megdnn::MatrixMul::Param& param,
                   size_t new_batch_size) {
        //! Because we do not know whether the batch size is in the dimension m
        //! or the dimension n, we just ignore both m and n here.
        // FIXME Find a way to make mgb obtain batch size information from R or
        // automatically
        layouts.at(2)[0] = new_batch_size;
        layouts.at(2)[1] = new_batch_size;
        if (param.transposeA) {
            layouts.at(0)[1] = new_batch_size;
        } else {
            layouts.at(0)[0] = new_batch_size;
        }
        if (param.transposeB) {
            layouts.at(1)[0] = new_batch_size;
        } else {
            layouts.at(1)[1] = new_batch_size;
        }
    }
};

501
///////////////////////////// AlgoChooserHelper //////////////////////////
502
template <typename Opr>
503 504 505 506 507 508
AlgoChooser<Opr>::AlgoChooserHelper::AlgoChooserHelper(
        const FixedTensorLayouts& layouts, Opr* megdnn_opr,
        const std::string& param_str, const cg::OperatorNodeBase* mgb_opr,
        const CompNode& cn,
        const megdnn::param::ExecutionPolicy& execution_policy,
        bool allow_weight_preprocess)
509 510
        : m_fastrun_layouts{layouts},
          m_incache_layouts{layouts},
511
          m_dnn_opr{megdnn_opr},
512 513 514 515 516
          m_param{param_str},
          m_base_mgb_opr{mgb_opr},
          m_cn{cn},
          m_execution_policy{execution_policy},
          m_allow_weight_preprocess{allow_weight_preprocess} {
517 518 519 520 521 522 523 524 525 526 527
    auto fastrun_batch_size =
            owner_graph()->options().fast_run_config.shared_batch_size;

    if (fastrun_batch_size) {
        LayoutsModifier<Opr>::on(m_incache_layouts, m_dnn_opr->param(), 0);
        LayoutsModifier<Opr>::on(m_fastrun_layouts, m_dnn_opr->param(),
                                 fastrun_batch_size);
    }

    mgb_assert(m_fastrun_layouts.size() == layouts.size());

528 529 530 531 532 533 534 535
    static_assert(
            std::tuple_size<FixedTensorLayouts>::value == 2 ||
                    std::tuple_size<FixedTensorLayouts>::value == 3 ||
                    std::tuple_size<FixedTensorLayouts>::value == 4 ||
                    std::tuple_size<FixedTensorLayouts>::value == 5 ||
                    std::tuple_size<FixedTensorLayouts>::value == 8,
            "Pooling assumes arity = 2 or 4,Convolution AlgoChooser assumes "
            "arity = 3 , 5 or 8 (for deformable conv)");
536
}
537

538 539 540 541 542 543
template <typename Opr>
typename AlgoChooser<Opr>::ImplExecutionPolicy
AlgoChooser<Opr>::AlgoChooserHelper::choose_by_heuristic(
        const ExecutionStrategy& selected_strategy) const {
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("choose_by_heuristic")))
    ImplExecutionPolicy policy;
544
    auto workspace_limit = WorkspaceLimitGetter::get_workspace_limit(
545 546 547
            owner_graph(), m_cn, m_execution_policy.workspace_limit);
    auto attr = extract_algo_attribute(selected_strategy);
    policy.algo =
548
            APPLY(m_dnn_opr->get_algorithm_info_heuristic(
549
                          args..., workspace_limit, attr.first, attr.second),
550
                  m_fastrun_layouts)
551
                    .desc;
552

553
    Algorithm* algo = m_dnn_opr->get_algorithm_from_desc(policy.algo);
554 555
    mgb_assert(algo, "Unknown algo description");
    std::vector<Algorithm::SearchItem>&& sub_items = algo->get_subopr_list(
556
            to_layout_array<Opr>(m_fastrun_layouts), m_dnn_opr);
557

558 559 560 561 562 563 564 565 566 567 568 569
    FOREACH_OPR_TYPE_DISPATCH(sub_items, {
        auto&& megdnn_opr = intl::create_megdnn_opr<_Opr>(m_cn);
        megdnn_opr->param() =
                Algorithm::deserialize_read_pod<typename _Opr::Param>(
                        _item.param);
        typename AlgoChooser<_Opr>::AlgoChooserHelper sub_helper(
                to_fixed_layouts<_Opr>(_item.layouts), megdnn_opr.get(),
                _item.param, m_base_mgb_opr, m_cn, m_execution_policy,
                m_allow_weight_preprocess);
        policy.sub_policy.push_back(
                sub_helper.choose_by_heuristic(selected_strategy));
    });
570

571 572
    return policy;
    MIDOUT_E
573 574 575
}

template <typename Opr>
576
typename AlgoChooser<Opr>::ImplExecutionPolicy
577 578 579 580
AlgoChooser<Opr>::AlgoChooserHelper::choose_by_profile(
        const ExecutionStrategy& selected_strategy, bool enable_update) const {
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("choose_by_profile")))
    if (owner_graph()->options().no_profiling_on_shape_change) {
581
        auto policy = m_dnn_opr->execution_policy();
582
        if (policy.algo.valid()) {
583
            return policy;
584
        }
585
        if (is_matmul<Opr>()) {
586 587 588
            mgb_log_warn(
                    "choose algo by heuristic, which may cause performance "
                    "regression.");
589
            return choose_by_heuristic(selected_strategy);
590
        }
591 592
    }

593 594 595 596 597 598 599 600 601 602
    typename AlgoChooser<Opr>::ImplExecutionPolicy tmp_policy;
    bool retrive_from_cache = true;
    bool allow_log = false;
    construct_execution_policy(selected_strategy, tmp_policy,
                               retrive_from_cache, allow_log);
    if (tmp_policy.algo.valid()) {
        // return policy when contruct successed
        return tmp_policy;
    }

603
    if (enable_update) {
604 605
        CircularDepsChecker circular_deps_checker;
        auto&& search_items =
606
                flatten_search_space<Opr>(*this, circular_deps_checker);
607
        FOREACH_OPR_TYPE_DISPATCH(search_items, {
608
            auto&& megdnn_opr = intl::create_megdnn_opr<_Opr>(m_cn);
609 610 611
            megdnn_opr->param() =
                    Algorithm::deserialize_read_pod<typename _Opr::Param>(
                            _item.param);
612
            typename AlgoChooser<_Opr>::AlgoChooserHelper sub_helper(
613
                    to_fixed_layouts<_Opr>(_item.layouts), megdnn_opr.get(),
614 615 616
                    _item.param, m_base_mgb_opr, m_cn, m_execution_policy,
                    m_allow_weight_preprocess);
            sub_helper.profile(selected_strategy);
617
        });
618
    }
619

620
    typename AlgoChooser<Opr>::ImplExecutionPolicy policy;
621
    construct_execution_policy(selected_strategy, policy);
622
    return policy;
623 624 625 626
    MIDOUT_E
}

template <typename Opr>
627
typename AlgoChooser<Opr>::ImplAlgoDesc
628 629 630
AlgoChooser<Opr>::AlgoChooserHelper::get_profile_result_from_cache(
        const ExecutionStrategy& selected_strategy) const {
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("get_profile_result_from_cache")))
631
    AlgoChooserProfileCache cache(m_cn, profile_name(m_dnn_opr).c_str());
632

633
    typename Opr::Param origin_param = m_dnn_opr->param();
634 635
    AlgoChooserProfileCache::Key cache_key{m_incache_layouts.data(),
                                           m_incache_layouts.size(),
636 637 638 639 640 641
                                           &origin_param, sizeof(origin_param)};
    auto&& rst = cache.get(cache_key);
    if (!rst.valid())
        return {};

    auto&& prof = rst.val();
642 643 644
    if (prof.empty())
        return {};

645
    auto target_attr = extract_algo_attribute(selected_strategy);
646
    bool skip_by_negative = false;
647
    for (auto&& i : prof) {
648 649 650
        auto attr_of_algo =
                static_cast<megdnn::Algorithm::Attribute>(i.attribute);
        bool contain_attr_all_positive =
651
                (target_attr.first == (attr_of_algo & target_attr.first));
652
        bool contain_attr_any_negative =
653
                static_cast<bool>(attr_of_algo & target_attr.second);
654 655
        if (contain_attr_all_positive) {
            if (!contain_attr_any_negative) {
656 657
                Algorithm::Info::Desc algo_desc = deserialize_read_pod(i.algo);
                return algo_desc;
658 659 660
            } else {
                skip_by_negative = true;
            }
661 662 663
        }
    }

664
    std::string layouts_str =
665
            format_fixlayouts<Opr>(m_fastrun_layouts, arity_in, arity_out);
666 667
    if (skip_by_negative) {
        mgb_log_error(
668 669
                "opr: %s, layouts: %s, No usable algo. There are available "
                "algos match "
670
                "positive strategy(%s), but filtered by negative stategy(%s).",
671
                m_base_mgb_opr->dyn_typeinfo()->name, layouts_str.c_str(),
672
                Algorithm::attribute_str(target_attr.first).c_str(),
673 674 675
                Algorithm::attribute_str(target_attr.second).c_str());
    } else {
        mgb_log_error(
676 677
                "opr: %s, layouts: %s, No usable algo. algos read from cache "
                "could not "
678
                "satisfy positive strategy(%s)",
679
                m_base_mgb_opr->dyn_typeinfo()->name, layouts_str.c_str(),
680 681
                Algorithm::attribute_str(target_attr.first).c_str());
    }
682

683 684 685 686 687
    mgb_trap();
    MIDOUT_E
}

template <typename Opr>
688
void AlgoChooser<Opr>::AlgoChooserHelper::construct_execution_policy(
689 690 691
        const ExecutionStrategy& selected_strategy,
        typename AlgoChooser<Opr>::ImplExecutionPolicy& policy,
        bool retrive_from_cache, bool allow_log) const {
692
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("construct_execution_policy")))
693
    if (!policy.algo.valid()) {
694
        if (retrive_from_cache) {
695
            policy.algo = get_profile_result_from_cache(selected_strategy);
696
            if (!policy.algo.valid()) {
697 698 699 700
                if (allow_log) {
                    auto target_attr =
                            extract_algo_attribute(selected_strategy);
                    std::string layouts_str = format_fixlayouts<Opr>(
701
                            m_fastrun_layouts, arity_in, arity_out);
702
                    std::string msg = ssprintf(
703
                            "(opr : %s, layouts %s, with attribute(%s) and "
704 705 706 707 708 709 710 711 712 713 714 715 716 717
                            "without attribute(%s)",
                            m_base_mgb_opr->dyn_typeinfo()->name,
                            layouts_str.c_str(),
                            Algorithm::attribute_str(target_attr.first).c_str(),
                            Algorithm::attribute_str(target_attr.second)
                                    .c_str());
                    mgb_log_warn(
                            "No algo get from cache for %s. This may caused by "
                            "mismatch with model and cache file or imcomplete "
                            "cache file. ex. profiling with version1, but "
                            "inferencing on version2 or profiling modelA but "
                            "inferencing modelB",
                            msg.c_str());
                }
718 719
                return;
            }
720 721 722
        } else {
            auto workspace_limit = WorkspaceLimitGetter::get_workspace_limit(
                    owner_graph(), m_cn, m_execution_policy.workspace_limit);
723

724
            auto attr = extract_algo_attribute(selected_strategy);
725
            policy.algo = APPLY(m_dnn_opr->get_algorithm_info_heuristic(
726 727
                                        args..., workspace_limit, attr.first,
                                        attr.second),
728
                                m_fastrun_layouts)
729
                                  .desc;
730 731 732 733 734
            mgb_assert(policy.algo.valid(),
                       "No algo found from heuristic with strategy %u and "
                       "workspace limit %zu",
                       static_cast<uint32_t>(selected_strategy),
                       workspace_limit);
735
        }
736
    }
737

738
    Algorithm* algo = m_dnn_opr->get_algorithm_from_desc(policy.algo);
739 740
    mgb_assert(algo, "Unknown algo description");
    std::vector<Algorithm::SearchItem>&& sub_items = algo->get_subopr_list(
741
            to_layout_array<Opr>(m_fastrun_layouts), m_dnn_opr);
742 743 744 745 746 747

    FOREACH_OPR_TYPE_DISPATCH(sub_items, {
        auto&& megdnn_opr = intl::create_megdnn_opr<_Opr>(m_cn);
        megdnn_opr->param() =
                Algorithm::deserialize_read_pod<typename _Opr::Param>(
                        _item.param);
748
        typename AlgoChooser<_Opr>::AlgoChooserHelper sub_helper(
749 750 751 752
                to_fixed_layouts<_Opr>(_item.layouts), megdnn_opr.get(),
                _item.param, m_base_mgb_opr, m_cn, m_execution_policy,
                m_allow_weight_preprocess);
        policy.sub_policy.push_back({});
753
        sub_helper.construct_execution_policy(selected_strategy,
754 755
                                              policy.sub_policy.back(),
                                              retrive_from_cache, allow_log);
756
        if (!policy.sub_policy.back().algo.valid()) {
757
            // means sub_helper.construct_execution_policy fails. clean up
758 759 760 761
            // policy.algo and return
            policy = {};
            return;
        }
762
    });
763
    MIDOUT_E
764 765 766
}

template <typename Opr>
767
size_t AlgoChooser<Opr>::AlgoChooserHelper::get_workspace_size_bytes(
768 769
        const ImplExecutionPolicy& policy,
        const FixedTensorLayouts& layouts) const {
770
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("get_workspace_size_bytes")))
771
    m_dnn_opr->execution_policy() = policy;
772
    size_t result;
773 774 775 776
    const FixedTensorLayouts* layouts_ptr = &m_fastrun_layouts;
    if (layouts.at(0).ndim) {
        layouts_ptr = &layouts;
    }
777 778
    if_constexpr<opr_supports_preprocess<Opr>()>(
            [&](auto _) {
779
                auto&& opr = _(m_dnn_opr);
780 781
                auto prep =
                        this->construct_fake_preprocess_filter(*layouts_ptr);
782 783 784 785
                PreprocessFilter<Opr>* prep_ptr =
                        prep.valid() ? &prep.val() : nullptr;
                result = std::max(
                        APPLY(opr->get_preprocess_workspace_in_bytes(args...),
786
                              *layouts_ptr),
787
                        APPLY(opr->get_workspace_in_bytes(args..., prep_ptr),
788
                              *layouts_ptr));
789 790 791
            },
            /* else */
            [&](auto _) {
792
                result = APPLY(_(m_dnn_opr)->get_workspace_in_bytes(args...),
793
                               *layouts_ptr);
794 795
            });
    return result;
796 797 798 799 800 801 802 803
    MIDOUT_E
}

template <typename Opr>
std::vector<typename AlgoChooser<Opr>::ImplAlgo>
AlgoChooser<Opr>::AlgoChooserHelper::get_all_candidates() const {
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("get_all_candidates")))
    auto heu = choose_by_heuristic(m_execution_policy.strategy);
804 805
    auto&& ret = APPLY(m_dnn_opr->get_all_algorithms_info(args...),
                       m_fastrun_layouts);
806 807 808 809 810 811 812 813 814
    bool found = false;
    for (size_t i = 0; i < ret.size(); ++i) {
        if (ret[i].desc == heu.algo) {
            found = true;
            std::swap(ret[i], ret[0]);
            break;
        }
    }

815
    Algorithm* palgo = m_dnn_opr->get_algorithm_from_desc(heu.algo);
816 817 818 819 820 821 822
    mgb_assert(palgo, "Unknown algo description");
    mgb_assert(found,
               "algo %s got by heuristic not found in "
               "candidate list",
               palgo->name());
    return std::move(ret);
    MIDOUT_E
823 824 825 826
}

template <typename Opr>
Maybe<AlgoChooserProfileCache::ResultEntry>
827
AlgoChooser<Opr>::AlgoChooserHelper::profile_single_algo(
828
        const ImplExecutionPolicy& policy, double& timeout) const {
829
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("profile_single_algo")))
830 831
    typename TimedProfiler<Opr>::Param param;
    // force check copy size <= dest len-1 from gcc8 for safe
832 833 834
    param.execution_policy =
            TimedProfiler<Opr>::Param::ExecutionPolicyBlob::serialize(policy);
    param.workspace = get_workspace_size_bytes(policy);
835
    for (int i = 0; i < arity; ++i) {
836
        auto&& src = m_fastrun_layouts[i];
837
        bool cond_normal = src.format.is_default() &&
838 839
                           (src.dtype.category() == DTypeCategory::FLOAT ||
                            src.dtype.category() == DTypeCategory::INT ||
840 841 842 843 844 845 846 847 848
                            src.dtype.category() == DTypeCategory::QUANTIZED);

        bool cond_low_bit = src.dtype.is_low_bit() &&
                            src.format.is_lowbit_aligned() &&
                            (src.dtype.category() == DTypeCategory::QUANTIZED ||
                             src.dtype.category() == DTypeCategory::LOWBIT);
        MGB_MARK_USED_VAR(cond_normal);
        MGB_MARK_USED_VAR(cond_low_bit);
        mgb_assert(cond_normal || cond_low_bit,
849 850 851 852
                   "unsupported layout in profiling: %s",
                   src.to_string().c_str());
        param.dtypes[i] = src.dtype.enumv();
    }
853
    param.comp_node_loc = m_cn.locator();
854
    mgb_assert(param.shapes.size() == m_fastrun_layouts.size());
855
    for (size_t i = 0; i < param.shapes.size(); ++i)
856
        param.shapes[i] = m_fastrun_layouts[i];
857
    param.opr_param = m_dnn_opr->param();
858 859
    param.allow_weight_preprocess = m_allow_weight_preprocess;

860
    Algorithm* palgo = m_dnn_opr->get_algorithm_from_desc(policy.algo);
861 862
    mgb_assert(palgo, "can not find algo when profile single algo");

863 864 865 866
    auto rst = TimedProfiler<Opr>::profile(param, timeout);
    // MIOpen conv profiles all available algos when a specfic shape is
    // provided for the first time, which probably adds to the result time.
    // Therefore, a second profile execution is needed.
867
    if (strncmp(palgo->name(), "MIOpen", 6) == 0) {
868
        rst = TimedProfiler<Opr>::profile(param, timeout);
869
    }
870 871
    if (!rst.valid())
        return None;
872 873 874

    std::string algo_desc;
    serialize_write_pod(policy.algo, algo_desc);
875
    return AlgoChooserProfileCache::ResultEntry{
876
            algo_desc, static_cast<uint32_t>(palgo->attribute()),
877
            rst.val().time, param.workspace};
878 879 880 881 882 883 884 885 886 887 888 889 890
    MIDOUT_E
}

template <typename Opr>
void AlgoChooser<Opr>::AlgoChooserHelper::profile(
        const ExecutionStrategy& selected_strategy) const {
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("profile")))
    if (get_profile_result_from_cache(selected_strategy).valid())
        return;
    AlgoChooserProfileCache::Result prof_rst;

    auto target_attr = extract_algo_attribute(selected_strategy);
    std::string layouts_str =
891
            format_fixlayouts<Opr>(m_fastrun_layouts, arity_in, arity_out);
892 893 894 895 896 897 898 899 900 901 902 903
    double cur_timeout = 0;

    auto workspace_limit = WorkspaceLimitGetter::get_workspace_limit(
            owner_graph(), m_cn, m_execution_policy.workspace_limit);
    RealTimer timer;
    for (auto algo : get_all_candidates()) {
        Maybe<AlgoChooserProfileCache::ResultEntry> cur_rst;

        ImplExecutionPolicy policy;
        policy.algo = algo.desc;

        //! check negative attribute : skip negative attribute
904
        auto palgo = m_dnn_opr->get_algorithm_from_desc(policy.algo);
905 906 907 908 909 910 911 912 913 914
        if (palgo->contain_attribute_any(target_attr.second)) {
            mgb_log_debug(
                    "skip algo %s, which matches the profile strategy required "
                    "'not contain attribute(%s).'",
                    algo.desc.name.c_str(),
                    Algorithm::attribute_str(target_attr.second).c_str());
            continue;
        }

        //! check workspace limit
915 916 917
        construct_execution_policy(selected_strategy, policy);
        mgb_assert(policy.algo.valid(),
                   "construct execution policy must success when profiling");
918
        if (get_workspace_size_bytes(policy) > workspace_limit) {
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
            continue;
        }

        std::string msg = ssprintf("profiling %s algorithm %s %s",
                                   m_base_mgb_opr->dyn_typeinfo()->name,
                                   algo.desc.name.c_str(), layouts_str.c_str());
        timer.reset();
        MGB_TRY { cur_rst = profile_single_algo(policy, cur_timeout); }
        MGB_CATCH(std::exception & exc, {
            mgb_log_warn("caught exception during %s: %s", msg.c_str(),
                         exc.what());
            continue;
        })
        MGB_CATCH(..., {
            mgb_log_warn("caught exception during %s", msg.c_str());
            continue;
        })
        if (!cur_rst.valid()) {
            mgb_log_warn("timeout when %s; timeout setting: %.3fsec",
                         msg.c_str(), cur_timeout);
            continue;
        }
        if (!cur_timeout) {
            cur_timeout = timer.get_secs() + TIMEOUT_TOLERANCE;
        } else {
            cur_timeout =
                    std::min(cur_timeout, timer.get_secs() + TIMEOUT_TOLERANCE);
        }
        auto&& rst = cur_rst.val();
        mgb_log_debug("%s: workspace: %zu; time: %.3gsec", msg.c_str(),
                      rst.workspace, rst.time);
        prof_rst.push_back(rst);
    }
    std::string msg = ssprintf(
            "no usable %s algorithm %s without attribute(%s) or could not meet "
            "workspace limite requirement(%zu)",
            m_base_mgb_opr->dyn_typeinfo()->name, layouts_str.c_str(),
            Algorithm::attribute_str(target_attr.second).c_str(),
            workspace_limit);
    mgb_assert(!prof_rst.empty(), "%s", msg.c_str());

960
    FixedTensorLayouts incache_layouts = m_incache_layouts;
961
    typename Opr::Param origin_param = m_dnn_opr->param();
962 963
    AlgoChooserProfileCache::Key cache_key{incache_layouts.data(),
                                           incache_layouts.size(), &origin_param,
964 965
                                           sizeof(origin_param)};

966
    AlgoChooserProfileCache cache(m_cn, profile_name(m_dnn_opr).c_str());
967 968
    cache.put(cache_key, prof_rst);
    MIDOUT_E
969 970 971 972
}

template <typename Opr>
Maybe<PreprocessFilter<Opr>>
973 974
AlgoChooser<Opr>::AlgoChooserHelper::construct_fake_preprocess_filter(
        const FixedTensorLayouts& layouts) const {
975
    MIDOUT_B(Opr, midout_iv(MGB_HASH_STR("construct_fake_preprocess_filter")))
976
    Maybe<PreprocessFilter<Opr>> result = None;
977 978 979 980
    const FixedTensorLayouts* layouts_ptr = &m_fastrun_layouts;
    if (layouts.at(0).ndim) {
        layouts_ptr = &layouts;
    }
981 982 983
    if_constexpr<opr_supports_preprocess<Opr>()>([&](auto _) {
        if (!m_allow_weight_preprocess)
            return;
984
        auto opr = _(m_dnn_opr);
985
        auto layouts = APPLY(opr->deduce_preprocessed_filter_layout(args...),
986
                             *layouts_ptr);
987 988
        //! No preprocess layout means no need weight preprocess
        if (layouts.empty()) {
989
            return;
990 991 992 993 994 995 996 997 998 999 1000 1001
        }
        //! all layouts arm empty means no need weight preprocess
        bool layout_valid = false;
        for (auto&& layout : layouts) {
            if (!layout.is_empty()) {
                layout_valid = true;
            }
        }
        if (!layout_valid) {
            return;
        }

1002 1003 1004
        result = PreprocessFilter<Opr>{};
        auto& res = result.val();
        res.algorithm_id = nullptr;
1005 1006 1007
        res.tensors.resize(layouts.size());
        for (size_t i = 0; i < layouts.size(); i++) {
            res.tensors[i] = megdnn::TensorND(nullptr, layouts[i]);
1008 1009 1010
        }
    });
    return result;
1011
    MIDOUT_E
1012 1013
}

1014 1015
template <typename Opr>
std::pair<AlgoAttribute, AlgoAttribute>
1016
AlgoChooser<Opr>::AlgoChooserHelper::extract_algo_attribute(
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
        const ExecutionStrategy& strategy) const {
    std::pair<AlgoAttribute, AlgoAttribute> ret =
            std::make_pair(AlgoAttribute::DEFAULT, AlgoAttribute::DEFAULT);

    //! from strategy
    if (strategy & ExecutionStrategy::REPRODUCIBLE) {
        ret.first |= AlgoAttribute::REPRODUCIBLE;
    }
    if (strategy & ExecutionStrategy::OPTMIZED) {
        ret.second |= AlgoAttribute::NAIVE;
    }

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    //! from graph option
    if (owner_graph()->options().fast_run_config.shared_batch_size) {
        ret.second |= AlgoAttribute::USABLE_DEPEND_ON_SHAPE;
    }

    if (owner_graph()->options().fast_run_config.binary_equal_between_batch) {
        ret.first |= AlgoAttribute::REPRODUCIBLE;
        ret.second |= AlgoAttribute::ACCURACY_DEPEND_ON_BATCH;
    }

1039 1040 1041
    return ret;
}

1042
#define INST(Opr)                                                              \
1043
    template AlgoChooser<megdnn::Opr>::AlgoChooserHelper::AlgoChooserHelper(   \
1044 1045 1046 1047 1048 1049
            const FixedTensorLayouts& layouts, megdnn::Opr* megdnn_opr,        \
            const std::string& param_str, const cg::OperatorNodeBase* mgb_opr, \
            const CompNode& cn,                                                \
            const megdnn::param::ExecutionPolicy& execution_policy,            \
            bool allow_weight_preprocess);                                     \
    template typename AlgoChooser<megdnn::Opr>::ImplExecutionPolicy            \
1050 1051 1052 1053 1054 1055
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::choose_by_heuristic(          \
            const ExecutionStrategy& select_strategy) const;                   \
    template typename AlgoChooser<megdnn::Opr>::ImplExecutionPolicy            \
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::choose_by_profile(            \
            const ExecutionStrategy& select_strategy, bool enable_update)      \
            const;                                                             \
1056
    template typename AlgoChooser<megdnn::Opr>::ImplAlgoDesc                   \
1057 1058 1059 1060 1061
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::                              \
            get_profile_result_from_cache(                                     \
                    const ExecutionStrategy& select_strategy) const;           \
    template void                                                              \
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::construct_execution_policy(   \
1062 1063 1064
            const ExecutionStrategy& select_strategy,                          \
            typename AlgoChooser<megdnn::Opr>::ImplExecutionPolicy& policy,    \
            bool retrive_from_cache, bool allow_log) const;                    \
1065
    template size_t                                                            \
1066
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::get_workspace_size_bytes(     \
1067
            const typename AlgoChooser<megdnn::Opr>::ImplExecutionPolicy&      \
1068 1069
                    policy,                                                    \
            const FixedTensorLayouts& layouts) const;                          \
1070 1071
    template std::vector<typename AlgoChooser<megdnn::Opr>::ImplAlgo>          \
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::get_all_candidates() const;   \
1072
    template Maybe<AlgoChooserProfileCache::ResultEntry>                       \
1073
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::profile_single_algo(          \
1074 1075
            const typename AlgoChooser<megdnn::Opr>::ImplExecutionPolicy&      \
                    policy,                                                    \
1076 1077
            double& timeout) const;                                            \
    template std::pair<AlgoAttribute, AlgoAttribute>                           \
1078 1079 1080 1081
    AlgoChooser<megdnn::Opr>::AlgoChooserHelper::extract_algo_attribute(       \
            const ExecutionStrategy& strategy) const;                          \
    template void AlgoChooser<megdnn::Opr>::AlgoChooserHelper::profile(        \
            const ExecutionStrategy& selected_strategy) const;
1082 1083

MGB_FOREACH_FASTRUN_OPR(INST)
1084
#undef INST
1085

1086 1087 1088 1089 1090
//////////////////////////////// AlgoChoose /////////////////////////////
template <typename Opr>
typename AlgoChooser<Opr>::ImplExecutionPolicy AlgoChooser<Opr>::get_policy(
        const AlgoChooserHelper& helper) {
    auto opr_strategy = helper.execution_policy().strategy;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    auto strategy2str = [](auto strategy) {
        std::string ret;
        if (strategy & ExecutionStrategy::HEURISTIC) {
            ret += "HEURISTIC ";
        }
        if (strategy & ExecutionStrategy::PROFILE) {
            ret += "PROFILE ";
        }
        if (strategy & ExecutionStrategy::REPRODUCIBLE) {
            ret += "REPRODUCIBLE ";
        }
        if (strategy & ExecutionStrategy::OPTIMIZED) {
            ret += "OPTIMIZED ";
        }
        return ret;
    };
    mgb_log_debug("Use Stragegy :%s", strategy2str(opr_strategy).c_str());
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    if (opr_strategy & ExecutionStrategy::HEURISTIC) {
        if (opr_strategy & ExecutionStrategy::PROFILE) {
            //! this strategy will choose from cache first, then choost by
            //! heuristic if fail.
            ImplExecutionPolicy policy =
                    helper.choose_by_profile(opr_strategy, false);
            if (!policy.algo.valid()) {
                policy = helper.choose_by_heuristic(opr_strategy);
            }
            return policy;
        } else {
            return helper.choose_by_heuristic(opr_strategy);
        }
    }
#if MGB_ENABLE_FASTRUN
    else if (opr_strategy & ExecutionStrategy::PROFILE) {
        return helper.choose_by_profile(opr_strategy, true);
    }
#endif
    else {
        mgb_throw(GraphError, "bad ExecutionPolicy strategy");
    }
}

template <typename Opr>
size_t AlgoChooser<Opr>::setup_algo(const FixedTensorLayouts& layouts,
                                    Opr* megdnn_opr, const MGBOpr* mgb_opr,
                                    bool allow_weight_preprocess) {
    if (WorkspaceLimitGetter::is_prealloc_run(mgb_opr->owner_graph())) {
        return 0;
    }

    std::string param_str;
    Algorithm::serialize_write_pod(megdnn_opr->param(), param_str);
    AlgoChooserHelper helper(layouts, megdnn_opr, param_str, mgb_opr,
                             mgb_opr->comp_node(), mgb_opr->execution_policy(),
                             allow_weight_preprocess);

    ImplExecutionPolicy policy;
    if (auto algo_choose_hook = mgb_opr->algo_chooser()) {
        policy = algo_choose_hook(mgb_opr);
        auto strategy =
                ExecutionStrategy::HEURISTIC | ExecutionStrategy::REPRODUCIBLE;
1151 1152
        bool retrive_from_cache = false;
        helper.construct_execution_policy(strategy, policy, retrive_from_cache);
1153 1154 1155 1156
    }
    if (!policy.algo.valid()) {
        policy = get_policy(helper);
    }
1157
    size_t workspace = helper.get_workspace_size_bytes(policy, layouts);
1158 1159 1160

    std::string ret;
    ret.append(mgb_opr->dyn_typeinfo()->name);
1161
    ret.append(": tensor layouts");
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    ret += format_fixlayouts<Opr>(layouts, arity_in, arity_out);
    Algorithm* palgo = megdnn_opr->get_algorithm_from_desc(policy.algo);
    mgb_assert(palgo, "Unknown algo description");
    ret.append("): algo=" + std::string(palgo->name()));
    ret.append(ssprintf(" workspace=%.2fMiB attirbute=%d",
                        workspace / (1024 * 1024.0),
                        static_cast<uint32_t>(palgo->attribute())));
    mgb_log_debug("%s", ret.c_str());

    megdnn_opr->execution_policy() = policy;
    return workspace;
}

#define INST(Opr)                                                         \
    template AlgoChooser<megdnn::Opr>::ImplExecutionPolicy                \
    AlgoChooser<megdnn::Opr>::get_policy(const AlgoChooserHelper& proxy); \
    template size_t AlgoChooser<megdnn::Opr>::setup_algo(                 \
            const FixedTensorLayouts& layouts, megdnn::Opr* megdnn_opr,   \
            const MGBOpr* mgb_opr, bool allow_weight_preprocess);

MGB_FOREACH_FASTRUN_OPR(INST)
1183
#undef INST
1184

1185 1186 1187 1188
}  // namespace opr
}  // namespace mgb

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