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.

base.h 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /**
  2. * \file dnn/include/megdnn/oprs/base.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 <type_traits>
  14. #include "megdnn/basic_types.h"
  15. #include "megdnn/handle.h"
  16. #include "megdnn/internal/visibility_prologue.h"
  17. namespace megdnn {
  18. class Handle;
  19. /**
  20. * \brief base class for all operators
  21. *
  22. * This is an helper class. Users should not use OperatorBase directly.
  23. * Operators should be created by handle->create_opr<>().
  24. *
  25. * Each operator must provides the following constexpr values:
  26. *
  27. * * NR_INPUTS: number of input vars
  28. * * NR_OUTPUTS: number of output vars
  29. * * OPERATOR_TYPE: operator type as an enum
  30. *
  31. * If the operator has dynamic inputs or in_out param, the corresponding
  32. * NR_INPUTS is -1.
  33. *
  34. * For an operator whose NR_INPUTS >= 0 and NR_OUTPUTS >= 0, the operator must
  35. * also provide following methods:
  36. *
  37. * * void exec(_megdnn_in inputs..., _megdnn_tensor_out outputs...,
  38. * _megdnn_workspace workspace)
  39. * * void deduce_layout(const TensorLayout& inputs...,
  40. * TensorLayout& outputs...)
  41. * * size_t get_workspace_in_bytes(const TensorLayout &inputs...,
  42. * const TensorLayout &outputs)
  43. */
  44. class OperatorBase {
  45. public:
  46. explicit OperatorBase(Handle* handle) : m_handle(handle) {}
  47. virtual ~OperatorBase();
  48. //! get the handle from which this operator is created
  49. Handle* handle() const { return m_handle; }
  50. //! whether this opr guarantees that its exec() is thread-safe
  51. virtual bool is_thread_safe() const { return false; }
  52. /*!
  53. * \brief set the tracker to be used with MegcoreAsyncErrorInfo
  54. *
  55. * Most operators do not have async errors so this function has a
  56. * default empty implementation.
  57. */
  58. virtual void set_error_tracker(void*) {}
  59. private:
  60. Handle* m_handle;
  61. };
  62. namespace detail {
  63. /**
  64. * \brief AlgoSelectionStrategy is the advance information for selecting
  65. * algo
  66. */
  67. enum class AlgoSelectionStrategy {
  68. HEURISTIC = 0, //!< heristic to select the algos
  69. FAST_RUN = 1,
  70. FULL_RUN = 2,
  71. };
  72. /**
  73. * \brief separate algo by datatype for Matmul and conv
  74. */
  75. enum class AlgoDataType : uint32_t {
  76. FLOAT32 = 1 << 0,
  77. FLOAT16 = 1 << 1,
  78. QINT8X8X32 = 1 << 2,
  79. QUINT8X8X32 = 1 << 3,
  80. INT8X8X16 = 1 << 4,
  81. INT16X16X32 = 1 << 5,
  82. INT4X4X16 = 1 << 6,
  83. };
  84. /*!
  85. * \brief Abstract representation of an algorithm for implementing
  86. * the operator
  87. */
  88. class Algorithm {
  89. public:
  90. static constexpr uint32_t INVALID_ALGO_TYPE = static_cast<uint32_t>(-1);
  91. /**
  92. * \brief the attribe of the algo, such as REPRODUCIBLE, NAIVE
  93. *
  94. */
  95. enum class Attribute : uint32_t {
  96. /**
  97. * \brief whether the execution result is
  98. * reproducible across multiple runs.
  99. */
  100. REPRODUCIBLE = 1 << 0,
  101. /**
  102. * \brief whether the algo is naive
  103. * Mark algorithms with simple implementation as NAIVE, so we can filter
  104. * these algorithms to speed up fastrun.
  105. * */
  106. NAIVE = 1 << 1,
  107. };
  108. /**
  109. * \brief Algorithm information, we can get real algo from
  110. * AlgorithmInfo::Info::Desc
  111. */
  112. struct Info {
  113. struct Desc {
  114. //! backend of the algo belonging to
  115. Handle::HandleType handle_type;
  116. //! indicate the real algo implementation
  117. uint32_t type = INVALID_ALGO_TYPE;
  118. //! serialized param of the algo type
  119. std::string param;
  120. bool valid() const { return type != INVALID_ALGO_TYPE; }
  121. void reset() { type = INVALID_ALGO_TYPE; }
  122. bool operator==(const Desc& rhs) const {
  123. return handle_type == rhs.handle_type && type == rhs.type &&
  124. param == rhs.param;
  125. }
  126. } desc;
  127. //! algorithm name
  128. std::string name;
  129. Attribute attribute;
  130. bool valid() const { return desc.valid(); }
  131. void reset() { desc.reset(); }
  132. //! desc donate the algo
  133. bool operator==(const Info& rhs) const { return desc == rhs.desc; }
  134. };
  135. virtual ~Algorithm() = default;
  136. /**
  137. * \brief get the attribute of the algo
  138. */
  139. virtual Attribute attribute() const = 0;
  140. virtual const char* name() const = 0;
  141. //! serialized param
  142. virtual std::string param() const { return {}; }
  143. virtual uint32_t type() const = 0;
  144. bool contain_attribute(const Attribute& attr) const;
  145. Handle::HandleType handle_type() const { return m_handle_type; }
  146. Info info() const {
  147. return {{handle_type(), type(), param()}, name(), attribute()};
  148. }
  149. Info::Desc desc() const { return {handle_type(), type(), param()}; }
  150. template <typename T>
  151. static void serialize_write_pod(const T& val, std::string& result) {
  152. static_assert(std::is_standard_layout<T>::value, "invalid type");
  153. result.append(reinterpret_cast<const char*>(&val), sizeof(T));
  154. }
  155. static void serialize_write_pod(const char* val, std::string& result) {
  156. result.append(val, strlen(val));
  157. }
  158. template <typename T>
  159. static T deserialize_read_pod(const std::string& data, size_t offset = 0) {
  160. static_assert(std::is_standard_layout<T>::value, "invalid type");
  161. T ret;
  162. //! A pointer to an object or incomplete type may be converted to a
  163. //! pointer to a different object or incomplete type. If the resulting
  164. //! pointer is not correctly aligned for the pointed-to type, the
  165. //! behavior is undefined.
  166. //!
  167. //! so here we should use memcpy instead of
  168. //! *reinterpret_cast<const T*>(&data[offset]);
  169. memcpy(&ret, data.data() + offset, sizeof(T));
  170. return ret;
  171. }
  172. template <typename T>
  173. static T deserialize_read_pod(const char* data, size_t offset = 0) {
  174. static_assert(std::is_standard_layout<T>::value, "invalid type");
  175. T ret;
  176. //! A pointer to an object or incomplete type may be converted to a
  177. //! pointer to a different object or incomplete type. If the resulting
  178. //! pointer is not correctly aligned for the pointed-to type, the
  179. //! behavior is undefined.
  180. //!
  181. //! so here we should use memcpy instead of
  182. //! *reinterpret_cast<const T*>(&data[offset]);
  183. memcpy(&ret, data + offset, sizeof(T));
  184. return ret;
  185. }
  186. enum class OprType : uint32_t {
  187. MATRIX_MUL_FORWARD,
  188. BATCHED_MATRIX_MUL_FORWARD,
  189. CONVOLUTION_FORWARD,
  190. CONVOLUTION_BACKWARD_DATA,
  191. CONVOLUTION_BACKWARD_FILTER,
  192. CONVOLUTION3D_FORWARD,
  193. CONVOLUTION3D_BACKWARD_DATA,
  194. CONVOLUTION3D_BACKWARD_FILTER,
  195. LOCAL_SHARE_FORWARD,
  196. LOCAL_SHARE_BACKWARD_DATA,
  197. LOCAL_SHARE_BACKWARD_FILTER,
  198. DEFORMABLE_CONV_FORWARD,
  199. DEFORMABLE_CONV_BACKWARD_DATA,
  200. DEFORMABLE_CONV_BACKWARD_FILTER,
  201. CONVBIAS_FORWARD,
  202. BATCH_CONV_FORWARD,
  203. };
  204. struct SearchItem {
  205. OprType opr_type;
  206. //! serialized param
  207. std::string param;
  208. TensorLayoutArray layouts;
  209. };
  210. /**
  211. * \brief get subopr list of the algo
  212. *
  213. * \param layouts origin layouts of the parent opr
  214. * \param opr parent opr
  215. */
  216. virtual std::vector<SearchItem> get_subopr_list(const TensorLayoutArray&,
  217. const OperatorBase*) const {
  218. return {};
  219. }
  220. protected:
  221. Handle::HandleType m_handle_type = Handle::HandleType::NAIVE;
  222. };
  223. //! policy for executing the operator
  224. struct ExecutionPolicy {
  225. //! INVALID_ALGO_TYPE algo_type means using heuristic
  226. Algorithm::Info::Desc algo;
  227. std::vector<ExecutionPolicy> sub_policy;
  228. };
  229. /*!
  230. * \brief define Algorithm and ExecutionPolicy for oprs that have
  231. * multiple impl algos
  232. *
  233. * \tparam Opr the operator class
  234. * \tparam nargs number of arguments
  235. */
  236. template <class Opr, int nargs>
  237. class MultiAlgoOpr;
  238. //! base def
  239. template <class Opr>
  240. class MultiAlgoOpr<Opr, -1> {
  241. public:
  242. using AlgorithmInfo = detail::Algorithm::Info;
  243. using AlgorithmDesc = detail::Algorithm::Info::Desc;
  244. using Algorithm = detail::Algorithm;
  245. /*!
  246. * \brief get a string representation for current algorithm set;
  247. *
  248. * get_all_algorithms() may return different algorithms only if
  249. * algorithm set name differs. This is used for checking cache
  250. * validity.
  251. */
  252. virtual const char* get_algorithm_set_name() const = 0;
  253. ExecutionPolicy& execution_policy() { return m_execution_policy; }
  254. const ExecutionPolicy& execution_policy() const {
  255. return m_execution_policy;
  256. }
  257. virtual Algorithm* get_algorithm_from_desc(const AlgorithmDesc&) = 0;
  258. protected:
  259. ~MultiAlgoOpr() = default;
  260. private:
  261. ExecutionPolicy m_execution_policy;
  262. };
  263. //! specialize for nargs == 3
  264. template <class Opr>
  265. class MultiAlgoOpr<Opr, 3> : public MultiAlgoOpr<Opr, -1> {
  266. public:
  267. using Algorithm = detail::Algorithm;
  268. using AlgorithmInfo = detail::Algorithm::Info;
  269. //! get all possible algorithm decriptions for the specified layouts
  270. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  271. const TensorLayout& p1,
  272. const TensorLayout& p2) {
  273. std::vector<AlgorithmInfo> ret;
  274. for (auto&& algo : get_all_algorithms(p0, p1, p2)) {
  275. ret.emplace_back(algo->info());
  276. }
  277. return ret;
  278. }
  279. /**
  280. * \brief Returns the best algorithm information which indicate the
  281. * algorithm by heuristic.
  282. *
  283. * The selected algorithm should not use workspace more than
  284. * \p workspace_limit_in_bytes.
  285. */
  286. AlgorithmInfo get_algorithm_info_heuristic(
  287. const TensorLayout& p0, const TensorLayout& p1,
  288. const TensorLayout& p2,
  289. size_t workspace_limit_in_bytes =
  290. std::numeric_limits<size_t>::max(),
  291. bool reproducible = false) {
  292. return get_algorithm_heuristic(p0, p1, p2, workspace_limit_in_bytes,
  293. reproducible)
  294. ->info();
  295. }
  296. protected:
  297. ~MultiAlgoOpr() = default;
  298. //! get all possible algorithms for the specified layouts
  299. virtual std::vector<Algorithm*> get_all_algorithms(
  300. const TensorLayout& p0, const TensorLayout& p1,
  301. const TensorLayout& p2) = 0;
  302. /**
  303. * \brief Returns the best algorithm by heuristic.
  304. *
  305. * The selected algorithm should not use workspace more than
  306. * \p workspace_limit_in_bytes.
  307. */
  308. virtual Algorithm* get_algorithm_heuristic(
  309. const TensorLayout& p0, const TensorLayout& p1,
  310. const TensorLayout& p2,
  311. size_t workspace_limit_in_bytes =
  312. std::numeric_limits<size_t>::max(),
  313. bool reproducible = false) = 0;
  314. };
  315. //! specializae for nargs == 4
  316. template <class Opr>
  317. class MultiAlgoOpr<Opr, 4> : public MultiAlgoOpr<Opr, -1> {
  318. public:
  319. using Algorithm = detail::Algorithm;
  320. using AlgorithmInfo = detail::Algorithm::Info;
  321. //! get all possible algorithm decriptions for the specified layouts
  322. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  323. const TensorLayout& p1,
  324. const TensorLayout& p2,
  325. const TensorLayout& p3) {
  326. std::vector<AlgorithmInfo> ret;
  327. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3)) {
  328. ret.emplace_back(algo->info());
  329. }
  330. return ret;
  331. }
  332. /**
  333. * \brief Returns the best algorithm information which indicate the
  334. * algorithm by heuristic.
  335. *
  336. * The selected algorithm should not use workspace more than
  337. * \p workspace_limit_in_bytes.
  338. */
  339. AlgorithmInfo get_algorithm_info_heuristic(
  340. const TensorLayout& p0, const TensorLayout& p1,
  341. const TensorLayout& p2, const TensorLayout& p3,
  342. size_t workspace_limit_in_bytes =
  343. std::numeric_limits<size_t>::max(),
  344. bool reproducible = false) {
  345. return get_algorithm_heuristic(p0, p1, p2, p3, workspace_limit_in_bytes,
  346. reproducible)
  347. ->info();
  348. }
  349. protected:
  350. ~MultiAlgoOpr() = default;
  351. //! get all possible algorithms for the specified layouts
  352. virtual std::vector<Algorithm*> get_all_algorithms(
  353. const TensorLayout& p0, const TensorLayout& p1,
  354. const TensorLayout& p2, const TensorLayout& p3) = 0;
  355. /**
  356. * \brief Returns the best algorithm by heuristic.
  357. *
  358. * The selected algorithm should not use workspace more than
  359. * \p workspace_limit_in_bytes.
  360. */
  361. virtual Algorithm* get_algorithm_heuristic(
  362. const TensorLayout& p0, const TensorLayout& p1,
  363. const TensorLayout& p2, const TensorLayout& p3,
  364. size_t workspace_limit_in_bytes =
  365. std::numeric_limits<size_t>::max(),
  366. bool reproducible = false) = 0;
  367. };
  368. //! specializae for nargs == 5
  369. template <class Opr>
  370. class MultiAlgoOpr<Opr, 5> : public MultiAlgoOpr<Opr, -1> {
  371. public:
  372. using Algorithm = detail::Algorithm;
  373. using AlgorithmInfo = detail::Algorithm::Info;
  374. //! get all possible algorithm decriptions for the specified layouts
  375. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  376. const TensorLayout& p1,
  377. const TensorLayout& p2,
  378. const TensorLayout& p3,
  379. const TensorLayout& p4) {
  380. std::vector<AlgorithmInfo> ret;
  381. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3, p4)) {
  382. ret.emplace_back(algo->info());
  383. }
  384. return ret;
  385. }
  386. /**
  387. * \brief Returns the best algorithm information which indicate the
  388. * algorithm by heuristic.
  389. *
  390. * The selected algorithm should not use workspace more than
  391. * \p workspace_limit_in_bytes.
  392. */
  393. AlgorithmInfo get_algorithm_info_heuristic(
  394. const TensorLayout& p0, const TensorLayout& p1,
  395. const TensorLayout& p2, const TensorLayout& p3,
  396. const TensorLayout& p4,
  397. size_t workspace_limit_in_bytes =
  398. std::numeric_limits<size_t>::max(),
  399. bool reproducible = false) {
  400. return get_algorithm_heuristic(p0, p1, p2, p3, p4,
  401. workspace_limit_in_bytes, reproducible)
  402. ->info();
  403. }
  404. protected:
  405. ~MultiAlgoOpr() = default;
  406. //! get all possible algorithms for the specified layouts
  407. virtual std::vector<Algorithm*> get_all_algorithms(
  408. const TensorLayout& p0, const TensorLayout& p1,
  409. const TensorLayout& p2, const TensorLayout& p3,
  410. const TensorLayout& p4) = 0;
  411. /**
  412. * \brief Returns the best algorithm by heuristic.
  413. *
  414. * The selected algorithm should not use workspace more than
  415. * \p workspace_limit_in_bytes.
  416. */
  417. virtual Algorithm* get_algorithm_heuristic(
  418. const TensorLayout& p0, const TensorLayout& p1,
  419. const TensorLayout& p2, const TensorLayout& p3,
  420. const TensorLayout& p4,
  421. size_t workspace_limit_in_bytes =
  422. std::numeric_limits<size_t>::max(),
  423. bool reproducible = false) = 0;
  424. };
  425. //! specializae for nargs == 8
  426. template <class Opr>
  427. class MultiAlgoOpr<Opr, 8> : public MultiAlgoOpr<Opr, -1> {
  428. public:
  429. using Algorithm = detail::Algorithm;
  430. using AlgorithmInfo = detail::Algorithm::Info;
  431. //! get all possible algorithm decriptions for the specified layouts
  432. std::vector<AlgorithmInfo> get_all_algorithms_info(
  433. const TensorLayout& p0, const TensorLayout& p1,
  434. const TensorLayout& p2, const TensorLayout& p3,
  435. const TensorLayout& p4, const TensorLayout& p5,
  436. const TensorLayout& p6, const TensorLayout& p7) {
  437. std::vector<AlgorithmInfo> ret;
  438. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3, p4, p5, p6, p7)) {
  439. ret.emplace_back(algo->info());
  440. }
  441. return ret;
  442. }
  443. /**
  444. * \brief Returns the best algorithm information which indicate the
  445. * algorithm by heuristic.
  446. *
  447. * The selected algorithm should not use workspace more than
  448. */
  449. AlgorithmInfo get_algorithm_info_heuristic(
  450. const TensorLayout& p0, const TensorLayout& p1,
  451. const TensorLayout& p2, const TensorLayout& p3,
  452. const TensorLayout& p4, const TensorLayout& p5,
  453. const TensorLayout& p6, const TensorLayout& p7,
  454. size_t workspace_limit_in_bytes =
  455. std::numeric_limits<size_t>::max(),
  456. bool reproducible = false) {
  457. return get_algorithm_heuristic(p0, p1, p2, p3, p4, p5, p6, p7,
  458. workspace_limit_in_bytes, reproducible)
  459. ->info();
  460. }
  461. protected:
  462. ~MultiAlgoOpr() = default;
  463. //! get all possible algorithms for the specified layouts
  464. virtual std::vector<Algorithm*> get_all_algorithms(
  465. const TensorLayout& p0, const TensorLayout& p1,
  466. const TensorLayout& p2, const TensorLayout& p3,
  467. const TensorLayout& p4, const TensorLayout& p5,
  468. const TensorLayout& p6, const TensorLayout& p7) = 0;
  469. /**
  470. * \brief Returns the best algorithm by heuristic.
  471. *
  472. * The selected algorithm should not use workspace more than
  473. * \p workspace_limit_in_bytes.
  474. */
  475. virtual Algorithm* get_algorithm_heuristic(
  476. const TensorLayout& p0, const TensorLayout& p1,
  477. const TensorLayout& p2, const TensorLayout& p3,
  478. const TensorLayout& p4, const TensorLayout& p5,
  479. const TensorLayout& p6, const TensorLayout& p7,
  480. size_t workspace_limit_in_bytes =
  481. std::numeric_limits<size_t>::max(),
  482. bool reproducible = false) = 0;
  483. };
  484. } // namespace detail
  485. using Algorithm = detail::Algorithm;
  486. using AlgoAttribute = Algorithm::Attribute;
  487. using ExecutionPolicy = detail::ExecutionPolicy;
  488. } // namespace megdnn
  489. #include "megdnn/internal/visibility_epilogue.h"
  490. // vim: syntax=cpp.doxygen

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台