checker.h 22.3 KB
Newer Older
1 2 3 4
/**
 * \file dnn/test/common/checker.h
 * 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
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
9 10
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 */

#pragma once

#include "megdnn/basic_types.h"
#include "megdnn/tensor_iter.h"
#include "test/common/opr_algo_proxy.h"
#include "test/common/opr_proxy.h"
#include "test/common/rng.h"

#include <gtest/gtest.h>

#include <memory>
#include <regex>
#include <unordered_map>

27
// clang-format off
28
#if defined(__has_feature)
29 30 31 32 33
    #if __has_feature(address_sanitizer)
        #define MEGDNN_TEST_ASAN 1
    #else
        #define MEGDNN_TEST_ASAN 0
    #endif
34
#elif defined(__SANITIZE_ADDRESS__)
35
    #define MEGDNN_TEST_ASAN 1
36
#else
37 38 39 40
    #define MEGDNN_TEST_ASAN 0
#endif
// clang-format on

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
namespace megdnn {
namespace test {

class CheckerHelper {
    // TensorLayoutArray and TensorValueArray should be protected in theory;
    // but g++-4.9 bugs handle access privilege wrongfully, so we change it
    // to public.
public:
    using TensorValueArray = TensorNDArray;
    using TensorsConstriant = std::function<void(TensorValueArray& tensors)>;
    using ExtraOprImpl = std::function<void(const TensorNDArray&)>;
    using OutputCanonizer = std::function<void(const TensorValueArray&)>;
    static std::shared_ptr<TensorValueArray> alloc_tensors(
            Handle* handle, const TensorLayoutArray& layouts, size_t offset);

    Handle* handle() const { return m_handle_cur; }

58 59 60 61 62 63
    CheckerHelper() {
        auto tmp_handle = create_cpu_handle(2, false);
        m_handle_naive = std::move(tmp_handle);
        m_default_rng = std::unique_ptr<RNG>(new NormalRNG());
    }

64 65 66 67 68 69 70 71 72 73 74 75 76 77
protected:
    //! whether to use physically contiguous (i.e. default layout) for naive
    //! impl
    bool m_enable_contig_naive = false;

    bool m_prev_succ = true;
    const char* m_input_tensors_fpath = nullptr;
    thin_function<void()> m_expect_exec_fail;
    std::unique_ptr<Handle> m_handle_naive;
    Handle* m_handle_cur;
    std::unique_ptr<RNG> m_default_rng;
    std::unordered_map<size_t, RNG*> m_rng;
    std::unordered_map<size_t, DType> m_dtype;
    std::unordered_map<size_t, TensorFormat> m_fmt;
78
    std::set<size_t> m_bypass;
M
Megvii Engine Team 已提交
79
    float_t m_epsilon = 1e-3, m_max_avg_error = 1e-3, m_max_avg_biased_error = 1e-3;
80 81 82 83 84
    float_t m_perf_check_threshold = -1;
    bool m_perf_check = false;
    ExtraOprImpl m_extra_opr_impl;
    OutputCanonizer m_output_canonizer;
    TensorsConstriant m_tensor_constraint;
85 86
    bool m_no_naive_and_check = false;
    bool m_stable_check = false;
87
    bool m_force_deduce_dst = true;
88
    bool m_allow_invalid_check = false;
89 90 91 92 93 94 95 96 97 98
    /**
     * the offset from the start of malloc memory
     *
     * \note alloc \p m_offset more memory when alloc memory for a tensor,
     * the start of tensor just begin at \p m_offset.
     * \warning current only used for opencl
     */
    size_t m_offset = 0;

    CheckerHelper(Handle* handle, bool check_dispatch = true);
99

100 101 102 103
    ~CheckerHelper() noexcept;

    using OprExec = std::function<void(const TensorValueArray&)>;

M
Megvii Engine Team 已提交
104 105 106
    void do_exec_with_testcases(
            const TensorValueArray& testcase_in, const TensorValueArray& testcase_out,
            const OprExec& exec_opr);
107

M
Megvii Engine Team 已提交
108 109 110 111
    void do_exec(
            const TensorLayoutArray& user_layouts,
            const TensorLayoutArray& deduced_layouts, const OprExec& exec_naive,
            const OprExec& exec_opr);
112 113 114

    void enable_contig_naive() { m_enable_contig_naive = true; }

M
Megvii Engine Team 已提交
115 116 117 118
    void copy_tensors_to_device(
            const TensorValueArray& dest, const TensorValueArray& src);
    void copy_tensors_from_device(
            const TensorValueArray& dest, const TensorValueArray& src);
119

120 121 122
    void check_tensors(
            const TensorValueArray& expected, const TensorValueArray& computed);

123 124 125 126
private:
    std::shared_ptr<TensorValueArray> m_tensors_naive;

    void init_naive_values();
127 128 129 130 131 132
};

template <typename Opr, typename Proxy = OprProxy<Opr>>
class Checker : public CheckerHelper {
public:
    using Param = typename Opr::Param;
M
Megvii Engine Team 已提交
133
    using BeforeExecCallback = std::function<void(Opr*, const TensorValueArray&)>;
134 135 136 137 138 139
    Checker(Handle* handle, bool check_dispatch = true)
            : CheckerHelper(handle, check_dispatch), m_param(Param()) {}

    TensorLayoutArray make_layouts(const TensorShapeArray& shapes) {
        TensorLayoutArray layouts(shapes.size());
        for (size_t i = 0; i < shapes.size(); ++i) {
M
Megvii Engine Team 已提交
140 141
            DType dt =
                    (m_dtype.find(i) != m_dtype.end() ? m_dtype[i] : dtype::Float32());
142 143 144 145
            if (m_fmt.find(i) == m_fmt.end()) {
                layouts[i] = TensorLayout(shapes[i], dt);
            } else
                layouts[i] = TensorLayout(shapes[i], dt, m_fmt[i]);
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
        }
        return layouts;
    }

    /*!
     * \brief execute opr on current param/dtype/rng config
     * \param shapes input/output shapes, which would be passed as
     *      arguments to Opr::deduce_layout
     *
     * Checker would construct TensorLayout vectors from shapes and dtypes,
     * and call exec(TensorLayoutArray &).
     */
    Checker& exec(const TensorShapeArray& shapes) {
        exec(make_layouts(shapes));
        return *this;
    }

    void exec(TensorLayoutArray layouts);

    //! explicitly require argument to be TensorShape
    Checker& execs(const TensorShapeArray& shapes) { return exec(shapes); }

    //! explicitly require argument to be TensorLayout
    Checker& execl(const TensorLayoutArray& layouts) {
        exec(layouts);
        return *this;
    }

M
Megvii Engine Team 已提交
174 175
    Checker& exect(
            const TensorValueArray& testcase_in, const TensorValueArray& testcase_out);
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

    Checker& set_param(Param param) {
        m_param = param;
        opr()->param() = param;
        return *this;
    }
    Checker& set_dtype(size_t idx, DType dtype) {
        m_dtype[idx] = dtype;
        return *this;
    }
    Checker& set_fmt(size_t idx, TensorFormat fmt) {
        m_fmt[idx] = fmt;
        return *this;
    }
    Checker& set_rng(size_t idx, RNG* rng) {
        m_rng[idx] = rng;
        return *this;
    }
194 195 196 197
    Checker& set_bypass(size_t idx) {
        m_bypass.insert(idx);
        return *this;
    }
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    //! max error of a single element
    Checker& set_epsilon(dt_float32 epsilon) {
        m_epsilon = epsilon;
        m_max_avg_error = epsilon;
        m_max_avg_biased_error = epsilon;
        return *this;
    }
    //! max average error; defaults to epsilon
    Checker& set_max_avg_error(dt_float32 error) {
        m_max_avg_error = error;
        return *this;
    }
    //! max average biased error; defaults to epsilon
    Checker& set_max_avg_biased_error(dt_float32 error) {
        m_max_avg_biased_error = error;
        return *this;
    }
    Checker& set_offset(size_t offset) {
        m_offset = offset;
        return *this;
    }

    Checker& set_proxy(const Proxy& proxy) {
        m_naive_proxy = proxy;
        m_cur_proxy = proxy;
        return *this;
    }

    //! set_perf_check and set_perf_check_threshold control the
    //! performance checking behavior.
    //!
    //! If perf_check is on (default to off), the running time of the
    //! current operator and the naive operator would be measured and
    //! checked when calling exec.
    //! The accelerating ratio should be larger than perf_check_threshold,
    //! otherwise errors would be reported.
    //! perf_check_threshold must be set in advance since the default value
    //! (which is negative) is invalid.
    Checker& set_perf_check(bool perf_check) {
        m_perf_check = perf_check;
        return *this;
    }

    Checker& set_perf_check_threshold(float perf_check_threshold) {
        m_perf_check_threshold = perf_check_threshold;
        return *this;
    }

246 247 248 249 250 251
    //! stable check will run many iter and compare result with first iter
    Checker& set_stable_check(bool stable_check) {
        m_stable_check = stable_check;
        return *this;
    }

252 253 254 255 256 257
    //! froce deduce dst
    Checker& set_force_deduce_dst(bool force_deduce_dst) {
        m_force_deduce_dst = force_deduce_dst;
        return *this;
    }

258 259 260 261 262
    Checker& set_no_naive_check(bool no_naive_and_check) {
        m_no_naive_and_check = no_naive_and_check;
        return *this;
    }

263 264 265 266 267
    Checker& set_allow_invalid_check(bool allow_invalid_check) {
        m_allow_invalid_check = allow_invalid_check;
        return *this;
    }

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    //! load input tensors from file for next run
    Checker& load_input_tensors(const char* fpath) {
        m_input_tensors_fpath = fpath;
        return *this;
    }

    //! add another checker to ensure naive implementation is correct
    Checker& set_extra_opr_impl(const ExtraOprImpl& chk) {
        m_extra_opr_impl = chk;
        return *this;
    }

    //! set a callback to be invoked before executing the operator
    Checker& set_before_exec_callback(const BeforeExecCallback& cb) {
        m_before_exec_callback = cb;
        return *this;
    }

286 287 288 289 290
    Checker& reset_before_exec_callback() {
        m_before_exec_callback = nullptr;
        return *this;
    }

291 292
    //! set a tensors constraints function, for the purpose of manipulating
    //! tensors when testing.
M
Megvii Engine Team 已提交
293
    Checker& set_tensors_constraint(const TensorsConstriant& tensor_constraint) {
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
        m_tensor_constraint = tensor_constraint;
        return *this;
    }

    /*!
     * \brief set that exec() on opr should fail, so naive is not called and
     * exec() returns directly after opr is called.
     *
     * This is only valid for next exec() call. It is usually used for
     * testing megcore::AsyncErrorInfo.
     *
     * \param cb callback to be invoked after opr exec (so error would not
     *           be passed to destructor)
     */
    Checker& set_expect_exec_fail(const thin_function<void()>& cb) {
        m_expect_exec_fail = cb;
        return *this;
    }

    /*!
     * \brief set a function to canonize the outputs
     *
     * For some oprs maybe multiple outputs can be accepted; we can use a
     * function to transform them into a canonized form before comparing.
     *
     * The arguments are tensors on CPU and should be modified in-place.
     */
    Checker& set_output_canonizer(OutputCanonizer canonizer) {
        m_output_canonizer = std::move(canonizer);
        return *this;
    }

    //! get the opr impl so setting other than param() can be modified
    Opr* opr() {
        if (!m_opr_cur) {
            m_opr_cur = m_handle_cur->create_operator<Opr>();
        }
        return m_opr_cur.get();
    }

    //! whether previous exec succeeds
    bool prev_succ() const { return m_prev_succ; }

private:
    BeforeExecCallback m_before_exec_callback;
    Param m_param;
    Proxy m_naive_proxy, m_cur_proxy;
    std::unique_ptr<Opr> m_opr_cur;
};

::testing::AssertionResult __assert_tensor_eq(
345 346 347 348 349 350
        const char* expr0, const char* expr1, const char* expr_maxerr,
        const char* expr_maxerr_avg, const char* expr_maxerr_avg_biased,
        const TensorND& v0, const TensorND& v1, float maxerr, float maxerr_avg,
        float maxerr_avg_biased, bool allow_invalid = false);

::testing::AssertionResult __assert_tensor_eq_allow_invalid(
351 352 353 354 355
        const char* expr0, const char* expr1, const char* expr_maxerr,
        const char* expr_maxerr_avg, const char* expr_maxerr_avg_biased,
        const TensorND& v0, const TensorND& v1, float maxerr, float maxerr_avg,
        float maxerr_avg_biased);

M
Megvii Engine Team 已提交
356 357 358 359
#define MEGDNN_ASSERT_TENSOR_EQ_EPS_AVG(v0, v1, maxerr, maxerr_avg, maxerr_avg_biased) \
    ASSERT_PRED_FORMAT5(                                                               \
            ::megdnn::test::__assert_tensor_eq, v0, v1, maxerr, maxerr_avg,            \
            maxerr_avg_biased)
360

361 362
#define MEGDNN_ASSERT_TENSOR_EQ_EPS_AVG_ALLOW_INVALID(                        \
        v0, v1, maxerr, maxerr_avg, maxerr_avg_biased)                        \
M
Megvii Engine Team 已提交
363 364 365
    ASSERT_PRED_FORMAT5(                                                      \
            ::megdnn::test::__assert_tensor_eq_allow_invalid, v0, v1, maxerr, \
            maxerr_avg, maxerr_avg_biased)
366

367 368 369
#define MEGDNN_ASSERT_TENSOR_EQ_EPS(v0, v1, maxerr) \
    MEGDNN_ASSERT_TENSOR_EQ_EPS_AVG(v0, v1, maxerr, maxerr, maxerr)

M
Megvii Engine Team 已提交
370
#define MEGDNN_ASSERT_TENSOR_EQ(v0, v1) MEGDNN_ASSERT_TENSOR_EQ_EPS(v0, v1, 1e-3)
371 372 373 374 375 376 377 378 379

template <typename Opr, typename Proxy>
void Checker<Opr, Proxy>::exec(TensorLayoutArray layouts) {
    auto opr_naive = m_handle_naive->create_operator<Opr>();
    auto opr_relayout = m_handle_naive->create_operator<RelayoutForward>();

    auto opr_cur = this->opr();
    opr_naive->param() = m_param;
    opr_cur->param() = m_param;
380 381 382 383
    bool deduce_layout = layouts.back().ndim == 0;
    if (deduce_layout || m_force_deduce_dst) {
        m_naive_proxy.deduce_layout(opr_naive.get(), layouts);
    }
384 385 386 387 388 389 390 391 392 393 394 395
    auto exec_naive = [this, &opr_naive, &layouts,
                       &opr_relayout](const TensorValueArray& values) {
        TensorValueArray contig_values = values;
        TensorValueArray real_values = values;
        std::shared_ptr<TensorValueArray> tensors_naive_contig_storage;
        if (m_enable_contig_naive) {
            TensorLayoutArray contig_layouts;
            for (auto&& layout : layouts) {
                contig_layouts.emplace_back(TensorLayout{
                        static_cast<const TensorShape&>(layout), layout.dtype});
            }
            m_naive_proxy.deduce_layout(opr_naive.get(), contig_layouts);
M
Megvii Engine Team 已提交
396 397
            tensors_naive_contig_storage =
                    alloc_tensors(m_handle_naive.get(), contig_layouts, m_offset);
398 399 400 401 402 403
            contig_values = *tensors_naive_contig_storage;
            //! relayout value to the contig_values
            for (size_t i = 0; i < contig_values.size(); ++i) {
                if (real_values[i].layout.ndim == 0)
                    continue;
                real_values[i].layout.format = {};
M
Megvii Engine Team 已提交
404 405
                opr_relayout->exec(
                        real_values[i], contig_values[i], m_handle_naive.get());
406 407 408 409 410 411 412 413 414 415
            }
        }

        m_naive_proxy.exec(opr_naive.get(), contig_values);

        if (m_enable_contig_naive) {
            //! relayout to the values
            for (size_t i = 0; i < contig_values.size(); ++i) {
                if (real_values[i].layout.ndim == 0)
                    continue;
M
Megvii Engine Team 已提交
416 417
                opr_relayout->exec(
                        contig_values[i], real_values[i], m_handle_naive.get());
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
            }
        }
    };
    auto exec_opr = [this, opr_cur](const TensorValueArray& values) {
        if (m_before_exec_callback) {
            m_before_exec_callback(opr_cur, values);
        }
        m_cur_proxy.exec(opr_cur, values);
    };
    auto user_layouts = layouts;
    do_exec(user_layouts, layouts, exec_naive, exec_opr);
}

template <typename Opr, typename Proxy>
Checker<Opr, Proxy>& Checker<Opr, Proxy>::exect(
M
Megvii Engine Team 已提交
433
        const TensorValueArray& testcase_in, const TensorValueArray& testcase_out) {
434 435 436 437 438 439 440 441 442 443 444 445 446
    auto opr_cur = this->opr();
    opr_cur->param() = m_param;
    auto exec_opr = [this, opr_cur](const TensorValueArray& values) {
        if (m_before_exec_callback) {
            m_before_exec_callback(opr_cur, values);
        }
        m_cur_proxy.exec(opr_cur, values);
    };
    do_exec_with_testcases(testcase_in, testcase_out, exec_opr);
    return *this;
}

template <typename T, typename U>
M
Megvii Engine Team 已提交
447 448
TensorND TensorValue(
        const TensorShape& shape, T dtype, std::initializer_list<U> values) {
449 450 451
    TensorLayout layout{shape, dtype};
    auto buf = static_cast<dt_byte*>(malloc(layout.span().dist_byte()));
    TensorND tensor{buf, layout};
M
Megvii Engine Team 已提交
452 453 454
    megdnn_assert(
            values.size() == tensor.layout.total_nr_elems(), "%zu == %zu",
            values.size(), tensor.layout.total_nr_elems());
455 456 457 458 459 460 461 462
    auto ptr = tensor.ptr<typename DTypeTrait<T>::ctype>();
    for (const auto& v : values) {
        *ptr++ = typename DTypeTrait<T>::ctype(v);
    }
    return tensor;
}

template <typename T, typename U>
M
Megvii Engine Team 已提交
463
TensorND TensorValueLowbit4(const TensorShape& shape, T dtype, std::vector<U> values) {
464 465 466
    TensorLayout layout{shape, dtype};
    auto buf = static_cast<dt_byte*>(malloc(layout.span().dist_byte()));
    TensorND tensor{buf, layout};
467
    megdnn_assert(values.size() == tensor.layout.total_nr_elems());
468
    auto ptr = tensor.ptr<typename DTypeTrait<T>::ctype>();
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    auto dim_in = shape[layout.ndim - 1];
    auto elems = tensor.layout.total_nr_elems();
    auto dim_out = elems / dim_in;
    auto stride_out = div_ceil(dim_in, 2_z);
    size_t in_offset = 0;
    for (size_t i = 0; i < dim_out; ++i) {
        for (size_t j = 0; j < dim_in; j += 2) {
            U a = values[in_offset + j];
            U b = 0;
            if (j + 1 < dim_in)
                b = values[in_offset + j + 1];
            megdnn_assert(a >= DTypeTrait<T>::min());
            megdnn_assert(a <= DTypeTrait<T>::max());
            megdnn_assert(b >= DTypeTrait<T>::min());
            megdnn_assert(b <= DTypeTrait<T>::max());
            ptr[j / 2] = (a & 0xF) | (b << 4);
485
        }
486 487
        in_offset += dim_in;
        ptr += stride_out;
488 489 490 491 492 493 494 495 496 497
    }
    return tensor;
}

class Testcase : public SmallVector<TensorND> {
public:
    using SmallVector<TensorND>::SmallVector;
    ~Testcase() {
        // Suicide
        for (const auto& tensor : *this) {
498 499
            if (tensor.raw_ptr()) {
                free(tensor.raw_ptr());
500 501 502 503 504 505 506 507
            }
        }
    }

    Testcase(const Testcase&) = delete;
    Testcase operator=(const Testcase&) = delete;
};

508 509 510 511 512 513 514
struct ExecutionPolicyAlgoName {
    std::string name;
    std::vector<ExecutionPolicyAlgoName> sub_policy_names;

    ExecutionPolicyAlgoName(const char* name) : name{name} {}

    ExecutionPolicyAlgoName(
M
Megvii Engine Team 已提交
515
            const char* name, const std::vector<ExecutionPolicyAlgoName>& sub_policy)
516 517
            : name{name}, sub_policy_names{sub_policy} {}
};
518 519 520 521
/*!
 * \brief a callable to check that given algorithm is used for heuristic
 * \param require_algo if its value is true, then requires
 *      get_algorithm_heuristic() to return the expected algo; otherwise the
522
 *      expected algo must exist in get_all_algorithms_safe() and it would be set to
523 524 525 526 527
 *      be used
 */
template <class Opr, typename OprAlgoProxy = OprAlgoProxy<Opr>>
class AlgoChecker {
public:
528 529 530 531 532 533 534 535 536 537 538 539 540
    AlgoChecker(ExecutionPolicyAlgoName name, bool* require_algo = nullptr)
            : m_policy_name{name}, m_require_algo{require_algo} {}

    AlgoChecker(ExecutionPolicy policy, bool* require_algo = nullptr)
            : m_policy{policy}, m_require_algo{require_algo} {}

    static ExecutionPolicy construct_execution_policy_from_name(
            const ExecutionPolicyAlgoName& policy_name,
            const TensorLayoutArray& layouts, const std::string& param,
            Handle* handle) {
        ExecutionPolicy ret;
        megdnn_assert(layouts.size() == OprTrait<Opr>::arity);
        auto opr = handle->create_operator<Opr>();
M
Megvii Engine Team 已提交
541
        opr->param() = Algorithm::deserialize_read_pod<typename Opr::Param>(param);
542
        for (auto algo_info :
543
             AlgoProxy<Opr, OprTrait<Opr>::arity>::get_all_algorithms_info_safe(
544 545
                     opr.get(), layouts)) {
            if (std::regex_match(
546
                        algo_info.desc.name,
547 548 549 550 551 552 553 554 555
                        std::regex("(" + policy_name.name + ")(.*)"))) {
                ret.algo = algo_info.desc;
            } else {
                continue;
            }

            Algorithm* algo = opr->get_algorithm_from_desc(algo_info.desc);
            std::vector<Algorithm::SearchItem>&& sub_items =
                    algo->get_subopr_list(layouts, opr.get());
556 557 558
            if (sub_items.size() != policy_name.sub_policy_names.size()) {
                printf("Invalid sub_policy_names in %s, expected %zu but got "
                       "%zu\n",
559
                       algo_info.desc.name.c_str(), sub_items.size(),
560 561 562
                       policy_name.sub_policy_names.size());
                return {};
            }
563 564 565
            FOREACH_OPR_TYPE_DISPATCH(sub_items, {
                ExecutionPolicy policy =
                        AlgoChecker<_Opr>::construct_execution_policy_from_name(
M
Megvii Engine Team 已提交
566 567
                                policy_name.sub_policy_names[_item_idx], _item.layouts,
                                _item.param, handle);
568 569 570 571
                ret.sub_policy.push_back(policy);
            });
            return ret;
        }
572
        megdnn_assert(false, "Expected algo not found: %s\n", policy_name.name.c_str());
573 574
        return ret;
    }
575 576 577 578 579 580

    void operator()(Opr* opr, const CheckerHelper::TensorValueArray& arr) {
        TensorLayoutArray layouts;
        for (auto&& val : arr) {
            layouts.push_back(val.layout);
        }
581 582 583 584 585 586 587 588
        if (!m_policy_name.name.empty()) {
            std::string param_str;
            Algorithm::serialize_write_pod(opr->param(), param_str);
            m_policy = construct_execution_policy_from_name(
                    m_policy_name, layouts, param_str, opr->handle());
            ASSERT_TRUE(m_policy.algo.valid())
                    << "algorithm " << m_policy_name.name << " not found";
        }
589
        if (m_require_algo && *m_require_algo) {
M
Megvii Engine Team 已提交
590 591 592 593
            auto algo = OprAlgoProxy::get_algorithm_info_heuristic(opr, layouts);
            ASSERT_STREQ(
                    opr->get_algorithm_from_desc(m_policy.algo)->name(),
                    algo.desc.name.c_str());
594
        } else {
595
            opr->execution_policy() = m_policy;
596 597
        }
    }
598 599 600 601 602

private:
    ExecutionPolicyAlgoName m_policy_name;
    ExecutionPolicy m_policy;
    bool* m_require_algo;
603 604
};

605
template <typename Opr>
M
Megvii Engine Team 已提交
606 607 608
void construct_sub_execution_policy_heuristic(
        ExecutionPolicy& policy, const TensorLayoutArray& layouts,
        const std::string& param, Handle* handle) {
609 610 611 612
    megdnn_assert(layouts.size() == OprTrait<Opr>::arity);
    auto opr = handle->create_operator<Opr>();
    opr->param() = Algorithm::deserialize_read_pod<typename Opr::Param>(param);
    if (!policy.algo.valid()) {
M
Megvii Engine Team 已提交
613 614 615 616
        policy.algo =
                AlgoProxy<Opr, OprTrait<Opr>::arity>::get_algorithm_info_heuristic(
                        opr.get(), layouts)
                        .desc;
617 618 619 620 621 622 623 624
    }

    Algorithm* algo = opr->get_algorithm_from_desc(policy.algo);
    std::vector<Algorithm::SearchItem>&& sub_items =
            algo->get_subopr_list(layouts, opr.get());
    FOREACH_OPR_TYPE_DISPATCH(sub_items, {
        policy.sub_policy.push_back(ExecutionPolicy{});
        construct_sub_execution_policy_heuristic<_Opr>(
625
                policy.sub_policy.back(), _item.layouts, _item.param, handle);
626 627 628
    });
}

629 630 631 632
}  // namespace test
}  // namespace megdnn

// vim: syntax=cpp.doxygen