You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

checker.h 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. /**
  2. * \file dnn/test/common/checker.h
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10. * implied.
  11. */
  12. #pragma once
  13. #include "megdnn/basic_types.h"
  14. #include "megdnn/tensor_iter.h"
  15. #include "test/common/opr_algo_proxy.h"
  16. #include "test/common/opr_proxy.h"
  17. #include "test/common/rng.h"
  18. #include <gtest/gtest.h>
  19. #include <memory>
  20. #include <regex>
  21. #include <unordered_map>
  22. // clang-format off
  23. #if defined(__has_feature)
  24. #if __has_feature(address_sanitizer)
  25. #define MEGDNN_TEST_ASAN 1
  26. #else
  27. #define MEGDNN_TEST_ASAN 0
  28. #endif
  29. #elif defined(__SANITIZE_ADDRESS__)
  30. #define MEGDNN_TEST_ASAN 1
  31. #else
  32. #define MEGDNN_TEST_ASAN 0
  33. #endif
  34. // clang-format on
  35. namespace megdnn {
  36. namespace test {
  37. class CheckerHelper {
  38. // TensorLayoutArray and TensorValueArray should be protected in theory;
  39. // but g++-4.9 bugs handle access privilege wrongfully, so we change it
  40. // to public.
  41. public:
  42. using TensorValueArray = TensorNDArray;
  43. using TensorsConstriant = std::function<void(TensorValueArray& tensors)>;
  44. using ExtraOprImpl = std::function<void(const TensorNDArray&)>;
  45. using OutputCanonizer = std::function<void(const TensorValueArray&)>;
  46. static std::shared_ptr<TensorValueArray> alloc_tensors(
  47. Handle* handle, const TensorLayoutArray& layouts, size_t offset);
  48. Handle* handle() const { return m_handle_cur; }
  49. CheckerHelper() {
  50. auto tmp_handle = create_cpu_handle(2, false);
  51. m_handle_naive = std::move(tmp_handle);
  52. m_default_rng = std::unique_ptr<RNG>(new NormalRNG());
  53. }
  54. protected:
  55. //! whether to use physically contiguous (i.e. default layout) for naive
  56. //! impl
  57. bool m_enable_contig_naive = false;
  58. bool m_prev_succ = true;
  59. const char* m_input_tensors_fpath = nullptr;
  60. thin_function<void()> m_expect_exec_fail;
  61. std::unique_ptr<Handle> m_handle_naive;
  62. Handle* m_handle_cur;
  63. std::unique_ptr<RNG> m_default_rng;
  64. std::unordered_map<size_t, RNG*> m_rng;
  65. std::unordered_map<size_t, DType> m_dtype;
  66. std::unordered_map<size_t, TensorFormat> m_fmt;
  67. std::set<size_t> m_bypass;
  68. float_t m_epsilon = 1e-3, m_max_avg_error = 1e-3, m_max_avg_biased_error = 1e-3;
  69. float_t m_perf_check_threshold = -1;
  70. bool m_perf_check = false;
  71. ExtraOprImpl m_extra_opr_impl;
  72. OutputCanonizer m_output_canonizer;
  73. TensorsConstriant m_tensor_constraint;
  74. bool m_no_naive_and_check = false;
  75. bool m_stable_check = false;
  76. bool m_force_deduce_dst = true;
  77. bool m_allow_invalid_check = false;
  78. /**
  79. * the offset from the start of malloc memory
  80. *
  81. * \note alloc \p m_offset more memory when alloc memory for a tensor,
  82. * the start of tensor just begin at \p m_offset.
  83. * \warning current only used for opencl
  84. */
  85. size_t m_offset = 0;
  86. CheckerHelper(Handle* handle, bool check_dispatch = true);
  87. ~CheckerHelper() noexcept;
  88. using OprExec = std::function<void(const TensorValueArray&)>;
  89. void do_exec_with_testcases(
  90. const TensorValueArray& testcase_in, const TensorValueArray& testcase_out,
  91. const OprExec& exec_opr);
  92. void do_exec(
  93. const TensorLayoutArray& user_layouts,
  94. const TensorLayoutArray& deduced_layouts, const OprExec& exec_naive,
  95. const OprExec& exec_opr);
  96. void enable_contig_naive() { m_enable_contig_naive = true; }
  97. void copy_tensors_to_device(
  98. const TensorValueArray& dest, const TensorValueArray& src);
  99. void copy_tensors_from_device(
  100. const TensorValueArray& dest, const TensorValueArray& src);
  101. void check_tensors(
  102. const TensorValueArray& expected, const TensorValueArray& computed);
  103. private:
  104. std::shared_ptr<TensorValueArray> m_tensors_naive;
  105. void init_naive_values();
  106. };
  107. template <typename Opr, typename Proxy = OprProxy<Opr>>
  108. class Checker : public CheckerHelper {
  109. public:
  110. using Param = typename Opr::Param;
  111. using BeforeExecCallback = std::function<void(Opr*, const TensorValueArray&)>;
  112. Checker(Handle* handle, bool check_dispatch = true)
  113. : CheckerHelper(handle, check_dispatch), m_param(Param()) {}
  114. TensorLayoutArray make_layouts(const TensorShapeArray& shapes) {
  115. TensorLayoutArray layouts(shapes.size());
  116. for (size_t i = 0; i < shapes.size(); ++i) {
  117. DType dt =
  118. (m_dtype.find(i) != m_dtype.end() ? m_dtype[i] : dtype::Float32());
  119. if (m_fmt.find(i) == m_fmt.end()) {
  120. layouts[i] = TensorLayout(shapes[i], dt);
  121. } else
  122. layouts[i] = TensorLayout(shapes[i], dt, m_fmt[i]);
  123. }
  124. return layouts;
  125. }
  126. /*!
  127. * \brief execute opr on current param/dtype/rng config
  128. * \param shapes input/output shapes, which would be passed as
  129. * arguments to Opr::deduce_layout
  130. *
  131. * Checker would construct TensorLayout vectors from shapes and dtypes,
  132. * and call exec(TensorLayoutArray &).
  133. */
  134. Checker& exec(const TensorShapeArray& shapes) {
  135. exec(make_layouts(shapes));
  136. return *this;
  137. }
  138. void exec(TensorLayoutArray layouts);
  139. //! explicitly require argument to be TensorShape
  140. Checker& execs(const TensorShapeArray& shapes) { return exec(shapes); }
  141. //! explicitly require argument to be TensorLayout
  142. Checker& execl(const TensorLayoutArray& layouts) {
  143. exec(layouts);
  144. return *this;
  145. }
  146. Checker& exect(
  147. const TensorValueArray& testcase_in, const TensorValueArray& testcase_out);
  148. Checker& set_param(Param param) {
  149. m_param = param;
  150. opr()->param() = param;
  151. return *this;
  152. }
  153. Checker& set_dtype(size_t idx, DType dtype) {
  154. m_dtype[idx] = dtype;
  155. return *this;
  156. }
  157. Checker& set_fmt(size_t idx, TensorFormat fmt) {
  158. m_fmt[idx] = fmt;
  159. return *this;
  160. }
  161. Checker& set_rng(size_t idx, RNG* rng) {
  162. m_rng[idx] = rng;
  163. return *this;
  164. }
  165. Checker& set_bypass(size_t idx) {
  166. m_bypass.insert(idx);
  167. return *this;
  168. }
  169. //! max error of a single element
  170. Checker& set_epsilon(dt_float32 epsilon) {
  171. m_epsilon = epsilon;
  172. m_max_avg_error = epsilon;
  173. m_max_avg_biased_error = epsilon;
  174. return *this;
  175. }
  176. //! max average error; defaults to epsilon
  177. Checker& set_max_avg_error(dt_float32 error) {
  178. m_max_avg_error = error;
  179. return *this;
  180. }
  181. //! max average biased error; defaults to epsilon
  182. Checker& set_max_avg_biased_error(dt_float32 error) {
  183. m_max_avg_biased_error = error;
  184. return *this;
  185. }
  186. Checker& set_offset(size_t offset) {
  187. m_offset = offset;
  188. return *this;
  189. }
  190. Checker& set_proxy(const Proxy& proxy) {
  191. m_naive_proxy = proxy;
  192. m_cur_proxy = proxy;
  193. return *this;
  194. }
  195. //! set_perf_check and set_perf_check_threshold control the
  196. //! performance checking behavior.
  197. //!
  198. //! If perf_check is on (default to off), the running time of the
  199. //! current operator and the naive operator would be measured and
  200. //! checked when calling exec.
  201. //! The accelerating ratio should be larger than perf_check_threshold,
  202. //! otherwise errors would be reported.
  203. //! perf_check_threshold must be set in advance since the default value
  204. //! (which is negative) is invalid.
  205. Checker& set_perf_check(bool perf_check) {
  206. m_perf_check = perf_check;
  207. return *this;
  208. }
  209. Checker& set_perf_check_threshold(float perf_check_threshold) {
  210. m_perf_check_threshold = perf_check_threshold;
  211. return *this;
  212. }
  213. //! stable check will run many iter and compare result with first iter
  214. Checker& set_stable_check(bool stable_check) {
  215. m_stable_check = stable_check;
  216. return *this;
  217. }
  218. //! froce deduce dst
  219. Checker& set_force_deduce_dst(bool force_deduce_dst) {
  220. m_force_deduce_dst = force_deduce_dst;
  221. return *this;
  222. }
  223. Checker& set_no_naive_check(bool no_naive_and_check) {
  224. m_no_naive_and_check = no_naive_and_check;
  225. return *this;
  226. }
  227. Checker& set_allow_invalid_check(bool allow_invalid_check) {
  228. m_allow_invalid_check = allow_invalid_check;
  229. return *this;
  230. }
  231. //! load input tensors from file for next run
  232. Checker& load_input_tensors(const char* fpath) {
  233. m_input_tensors_fpath = fpath;
  234. return *this;
  235. }
  236. //! add another checker to ensure naive implementation is correct
  237. Checker& set_extra_opr_impl(const ExtraOprImpl& chk) {
  238. m_extra_opr_impl = chk;
  239. return *this;
  240. }
  241. //! set a callback to be invoked before executing the operator
  242. Checker& set_before_exec_callback(const BeforeExecCallback& cb) {
  243. m_before_exec_callback = cb;
  244. return *this;
  245. }
  246. Checker& reset_before_exec_callback() {
  247. m_before_exec_callback = nullptr;
  248. return *this;
  249. }
  250. //! set a tensors constraints function, for the purpose of manipulating
  251. //! tensors when testing.
  252. Checker& set_tensors_constraint(const TensorsConstriant& tensor_constraint) {
  253. m_tensor_constraint = tensor_constraint;
  254. return *this;
  255. }
  256. /*!
  257. * \brief set that exec() on opr should fail, so naive is not called and
  258. * exec() returns directly after opr is called.
  259. *
  260. * This is only valid for next exec() call. It is usually used for
  261. * testing megcore::AsyncErrorInfo.
  262. *
  263. * \param cb callback to be invoked after opr exec (so error would not
  264. * be passed to destructor)
  265. */
  266. Checker& set_expect_exec_fail(const thin_function<void()>& cb) {
  267. m_expect_exec_fail = cb;
  268. return *this;
  269. }
  270. /*!
  271. * \brief set a function to canonize the outputs
  272. *
  273. * For some oprs maybe multiple outputs can be accepted; we can use a
  274. * function to transform them into a canonized form before comparing.
  275. *
  276. * The arguments are tensors on CPU and should be modified in-place.
  277. */
  278. Checker& set_output_canonizer(OutputCanonizer canonizer) {
  279. m_output_canonizer = std::move(canonizer);
  280. return *this;
  281. }
  282. //! get the opr impl so setting other than param() can be modified
  283. Opr* opr() {
  284. if (!m_opr_cur) {
  285. m_opr_cur = m_handle_cur->create_operator<Opr>();
  286. }
  287. return m_opr_cur.get();
  288. }
  289. //! whether previous exec succeeds
  290. bool prev_succ() const { return m_prev_succ; }
  291. private:
  292. BeforeExecCallback m_before_exec_callback;
  293. Param m_param;
  294. Proxy m_naive_proxy, m_cur_proxy;
  295. std::unique_ptr<Opr> m_opr_cur;
  296. };
  297. ::testing::AssertionResult __assert_tensor_eq(
  298. const char* expr0, const char* expr1, const char* expr_maxerr,
  299. const char* expr_maxerr_avg, const char* expr_maxerr_avg_biased,
  300. const TensorND& v0, const TensorND& v1, float maxerr, float maxerr_avg,
  301. float maxerr_avg_biased, bool allow_invalid = false);
  302. ::testing::AssertionResult __assert_tensor_eq_allow_invalid(
  303. const char* expr0, const char* expr1, const char* expr_maxerr,
  304. const char* expr_maxerr_avg, const char* expr_maxerr_avg_biased,
  305. const TensorND& v0, const TensorND& v1, float maxerr, float maxerr_avg,
  306. float maxerr_avg_biased);
  307. #define MEGDNN_ASSERT_TENSOR_EQ_EPS_AVG(v0, v1, maxerr, maxerr_avg, maxerr_avg_biased) \
  308. ASSERT_PRED_FORMAT5( \
  309. ::megdnn::test::__assert_tensor_eq, v0, v1, maxerr, maxerr_avg, \
  310. maxerr_avg_biased)
  311. #define MEGDNN_ASSERT_TENSOR_EQ_EPS_AVG_ALLOW_INVALID( \
  312. v0, v1, maxerr, maxerr_avg, maxerr_avg_biased) \
  313. ASSERT_PRED_FORMAT5( \
  314. ::megdnn::test::__assert_tensor_eq_allow_invalid, v0, v1, maxerr, \
  315. maxerr_avg, maxerr_avg_biased)
  316. #define MEGDNN_ASSERT_TENSOR_EQ_EPS(v0, v1, maxerr) \
  317. MEGDNN_ASSERT_TENSOR_EQ_EPS_AVG(v0, v1, maxerr, maxerr, maxerr)
  318. #define MEGDNN_ASSERT_TENSOR_EQ(v0, v1) MEGDNN_ASSERT_TENSOR_EQ_EPS(v0, v1, 1e-3)
  319. template <typename Opr, typename Proxy>
  320. void Checker<Opr, Proxy>::exec(TensorLayoutArray layouts) {
  321. auto opr_naive = m_handle_naive->create_operator<Opr>();
  322. auto opr_relayout = m_handle_naive->create_operator<RelayoutForward>();
  323. auto opr_cur = this->opr();
  324. opr_naive->param() = m_param;
  325. opr_cur->param() = m_param;
  326. bool deduce_layout = layouts.back().ndim == 0;
  327. if (deduce_layout || m_force_deduce_dst) {
  328. m_naive_proxy.deduce_layout(opr_naive.get(), layouts);
  329. }
  330. auto exec_naive = [this, &opr_naive, &layouts,
  331. &opr_relayout](const TensorValueArray& values) {
  332. TensorValueArray contig_values = values;
  333. TensorValueArray real_values = values;
  334. std::shared_ptr<TensorValueArray> tensors_naive_contig_storage;
  335. if (m_enable_contig_naive) {
  336. TensorLayoutArray contig_layouts;
  337. for (auto&& layout : layouts) {
  338. contig_layouts.emplace_back(TensorLayout{
  339. static_cast<const TensorShape&>(layout), layout.dtype});
  340. }
  341. m_naive_proxy.deduce_layout(opr_naive.get(), contig_layouts);
  342. tensors_naive_contig_storage =
  343. alloc_tensors(m_handle_naive.get(), contig_layouts, m_offset);
  344. contig_values = *tensors_naive_contig_storage;
  345. //! relayout value to the contig_values
  346. for (size_t i = 0; i < contig_values.size(); ++i) {
  347. if (real_values[i].layout.ndim == 0)
  348. continue;
  349. real_values[i].layout.format = {};
  350. opr_relayout->exec(
  351. real_values[i], contig_values[i], m_handle_naive.get());
  352. }
  353. }
  354. m_naive_proxy.exec(opr_naive.get(), contig_values);
  355. if (m_enable_contig_naive) {
  356. //! relayout to the values
  357. for (size_t i = 0; i < contig_values.size(); ++i) {
  358. if (real_values[i].layout.ndim == 0)
  359. continue;
  360. opr_relayout->exec(
  361. contig_values[i], real_values[i], m_handle_naive.get());
  362. }
  363. }
  364. };
  365. auto exec_opr = [this, opr_cur](const TensorValueArray& values) {
  366. if (m_before_exec_callback) {
  367. m_before_exec_callback(opr_cur, values);
  368. }
  369. m_cur_proxy.exec(opr_cur, values);
  370. };
  371. auto user_layouts = layouts;
  372. do_exec(user_layouts, layouts, exec_naive, exec_opr);
  373. }
  374. template <typename Opr, typename Proxy>
  375. Checker<Opr, Proxy>& Checker<Opr, Proxy>::exect(
  376. const TensorValueArray& testcase_in, const TensorValueArray& testcase_out) {
  377. auto opr_cur = this->opr();
  378. opr_cur->param() = m_param;
  379. auto exec_opr = [this, opr_cur](const TensorValueArray& values) {
  380. if (m_before_exec_callback) {
  381. m_before_exec_callback(opr_cur, values);
  382. }
  383. m_cur_proxy.exec(opr_cur, values);
  384. };
  385. do_exec_with_testcases(testcase_in, testcase_out, exec_opr);
  386. return *this;
  387. }
  388. template <typename T, typename U>
  389. TensorND TensorValue(
  390. const TensorShape& shape, T dtype, std::initializer_list<U> values) {
  391. TensorLayout layout{shape, dtype};
  392. auto buf = static_cast<dt_byte*>(malloc(layout.span().dist_byte()));
  393. TensorND tensor{buf, layout};
  394. megdnn_assert(
  395. values.size() == tensor.layout.total_nr_elems(), "%zu == %zu",
  396. values.size(), tensor.layout.total_nr_elems());
  397. auto ptr = tensor.ptr<typename DTypeTrait<T>::ctype>();
  398. for (const auto& v : values) {
  399. *ptr++ = typename DTypeTrait<T>::ctype(v);
  400. }
  401. return tensor;
  402. }
  403. template <typename T, typename U>
  404. TensorND TensorValueLowbit4(const TensorShape& shape, T dtype, std::vector<U> values) {
  405. TensorLayout layout{shape, dtype};
  406. auto buf = static_cast<dt_byte*>(malloc(layout.span().dist_byte()));
  407. TensorND tensor{buf, layout};
  408. megdnn_assert(values.size() == tensor.layout.total_nr_elems());
  409. auto ptr = tensor.ptr<typename DTypeTrait<T>::ctype>();
  410. auto dim_in = shape[layout.ndim - 1];
  411. auto elems = tensor.layout.total_nr_elems();
  412. auto dim_out = elems / dim_in;
  413. auto stride_out = div_ceil(dim_in, 2_z);
  414. size_t in_offset = 0;
  415. for (size_t i = 0; i < dim_out; ++i) {
  416. for (size_t j = 0; j < dim_in; j += 2) {
  417. U a = values[in_offset + j];
  418. U b = 0;
  419. if (j + 1 < dim_in)
  420. b = values[in_offset + j + 1];
  421. megdnn_assert(a >= DTypeTrait<T>::min());
  422. megdnn_assert(a <= DTypeTrait<T>::max());
  423. megdnn_assert(b >= DTypeTrait<T>::min());
  424. megdnn_assert(b <= DTypeTrait<T>::max());
  425. ptr[j / 2] = (a & 0xF) | (b << 4);
  426. }
  427. in_offset += dim_in;
  428. ptr += stride_out;
  429. }
  430. return tensor;
  431. }
  432. class Testcase : public SmallVector<TensorND> {
  433. public:
  434. using SmallVector<TensorND>::SmallVector;
  435. ~Testcase() {
  436. // Suicide
  437. for (const auto& tensor : *this) {
  438. if (tensor.raw_ptr()) {
  439. free(tensor.raw_ptr());
  440. }
  441. }
  442. }
  443. Testcase(const Testcase&) = delete;
  444. Testcase operator=(const Testcase&) = delete;
  445. };
  446. struct ExecutionPolicyAlgoName {
  447. std::string name;
  448. std::vector<ExecutionPolicyAlgoName> sub_policy_names;
  449. ExecutionPolicyAlgoName(const char* name) : name{name} {}
  450. ExecutionPolicyAlgoName(
  451. const char* name, const std::vector<ExecutionPolicyAlgoName>& sub_policy)
  452. : name{name}, sub_policy_names{sub_policy} {}
  453. };
  454. /*!
  455. * \brief a callable to check that given algorithm is used for heuristic
  456. * \param require_algo if its value is true, then requires
  457. * get_algorithm_heuristic() to return the expected algo; otherwise the
  458. * expected algo must exist in get_all_algorithms_safe() and it would be set to
  459. * be used
  460. */
  461. template <class Opr, typename OprAlgoProxy = OprAlgoProxy<Opr>>
  462. class AlgoChecker {
  463. public:
  464. AlgoChecker(ExecutionPolicyAlgoName name, bool* require_algo = nullptr)
  465. : m_policy_name{name}, m_require_algo{require_algo} {}
  466. AlgoChecker(ExecutionPolicy policy, bool* require_algo = nullptr)
  467. : m_policy{policy}, m_require_algo{require_algo} {}
  468. static ExecutionPolicy construct_execution_policy_from_name(
  469. const ExecutionPolicyAlgoName& policy_name,
  470. const TensorLayoutArray& layouts, const std::string& param,
  471. Handle* handle) {
  472. ExecutionPolicy ret;
  473. megdnn_assert(layouts.size() == OprTrait<Opr>::arity);
  474. auto opr = handle->create_operator<Opr>();
  475. opr->param() = Algorithm::deserialize_read_pod<typename Opr::Param>(param);
  476. for (auto algo_info :
  477. AlgoProxy<Opr, OprTrait<Opr>::arity>::get_all_algorithms_info_safe(
  478. opr.get(), layouts)) {
  479. if (std::regex_match(
  480. algo_info.desc.name,
  481. std::regex("(" + policy_name.name + ")(.*)"))) {
  482. ret.algo = algo_info.desc;
  483. } else {
  484. continue;
  485. }
  486. Algorithm* algo = opr->get_algorithm_from_desc(algo_info.desc);
  487. std::vector<Algorithm::SearchItem>&& sub_items =
  488. algo->get_subopr_list(layouts, opr.get());
  489. if (sub_items.size() != policy_name.sub_policy_names.size()) {
  490. printf("Invalid sub_policy_names in %s, expected %zu but got "
  491. "%zu\n",
  492. algo_info.desc.name.c_str(), sub_items.size(),
  493. policy_name.sub_policy_names.size());
  494. return {};
  495. }
  496. FOREACH_OPR_TYPE_DISPATCH(sub_items, {
  497. ExecutionPolicy policy =
  498. AlgoChecker<_Opr>::construct_execution_policy_from_name(
  499. policy_name.sub_policy_names[_item_idx], _item.layouts,
  500. _item.param, handle);
  501. ret.sub_policy.push_back(policy);
  502. });
  503. return ret;
  504. }
  505. megdnn_assert(false, "Expected algo not found: %s\n", policy_name.name.c_str());
  506. return ret;
  507. }
  508. void operator()(Opr* opr, const CheckerHelper::TensorValueArray& arr) {
  509. TensorLayoutArray layouts;
  510. for (auto&& val : arr) {
  511. layouts.push_back(val.layout);
  512. }
  513. if (!m_policy_name.name.empty()) {
  514. std::string param_str;
  515. Algorithm::serialize_write_pod(opr->param(), param_str);
  516. m_policy = construct_execution_policy_from_name(
  517. m_policy_name, layouts, param_str, opr->handle());
  518. ASSERT_TRUE(m_policy.algo.valid())
  519. << "algorithm " << m_policy_name.name << " not found";
  520. }
  521. if (m_require_algo && *m_require_algo) {
  522. auto algo = OprAlgoProxy::get_algorithm_info_heuristic(opr, layouts);
  523. ASSERT_STREQ(
  524. opr->get_algorithm_from_desc(m_policy.algo)->name(),
  525. algo.desc.name.c_str());
  526. } else {
  527. opr->execution_policy() = m_policy;
  528. }
  529. }
  530. private:
  531. ExecutionPolicyAlgoName m_policy_name;
  532. ExecutionPolicy m_policy;
  533. bool* m_require_algo;
  534. };
  535. template <typename Opr>
  536. void construct_sub_execution_policy_heuristic(
  537. ExecutionPolicy& policy, const TensorLayoutArray& layouts,
  538. const std::string& param, Handle* handle) {
  539. megdnn_assert(layouts.size() == OprTrait<Opr>::arity);
  540. auto opr = handle->create_operator<Opr>();
  541. opr->param() = Algorithm::deserialize_read_pod<typename Opr::Param>(param);
  542. if (!policy.algo.valid()) {
  543. policy.algo =
  544. AlgoProxy<Opr, OprTrait<Opr>::arity>::get_algorithm_info_heuristic(
  545. opr.get(), layouts)
  546. .desc;
  547. }
  548. Algorithm* algo = opr->get_algorithm_from_desc(policy.algo);
  549. std::vector<Algorithm::SearchItem>&& sub_items =
  550. algo->get_subopr_list(layouts, opr.get());
  551. FOREACH_OPR_TYPE_DISPATCH(sub_items, {
  552. policy.sub_policy.push_back(ExecutionPolicy{});
  553. construct_sub_execution_policy_heuristic<_Opr>(
  554. policy.sub_policy.back(), _item.layouts, _item.param, handle);
  555. });
  556. }
  557. } // namespace test
  558. } // namespace megdnn
  559. // vim: syntax=cpp.doxygen