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.

general.h 49 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. /**
  2. * \file dnn/include/megdnn/oprs/general.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 implied.
  10. */
  11. #pragma once
  12. #include "megdnn/internal/opr_header_prologue.h"
  13. #include "megdnn/thin/small_vector.h"
  14. namespace megdnn {
  15. /*!
  16. * \brief standard element-wise operator
  17. *
  18. * Inputs must have same dtype, and their shapes must broadcastable into a final
  19. * shape. They can have arbitrary layouts, but non-contiguous and non-broadcast
  20. * layouts may harm performance seriously.
  21. *
  22. * Output dtype is the same as input dtype (note that even for compare oprs this
  23. * is true, e.g. float == float returns value of float). Output layout must be
  24. * contiguous.
  25. */
  26. class ElemwiseForward : public OperatorBase {
  27. DEF_OPR_PARAM(Elemwise);
  28. DEF_OPR_IMPL(ElemwiseForward, OperatorBase, -1, 1);
  29. public:
  30. using Mode = Param::Mode;
  31. //! information about a mode
  32. struct ModeTrait {
  33. uint32_t arity; //!< number of inputs needed
  34. bool commutable; //!< whether arity == 2 and inputs commutable
  35. bool allow_int; //!< whether int inputs allowed
  36. bool allow_float; //!< whether float inputs allowed
  37. bool allow_bool; //!< whether bool inputs allowed
  38. const char* name; //!< name of the mode
  39. ModeTrait()
  40. : arity(0),
  41. commutable(0),
  42. allow_int(0),
  43. allow_float(0),
  44. allow_bool(0),
  45. name(NULL) {}
  46. //! get trait from a mode; this function is thread safe
  47. MGE_WIN_DECLSPEC_FUC static const ModeTrait& from_mode(Mode mode);
  48. };
  49. //! get trait of current mode
  50. const ModeTrait& mode_trait() const { return ModeTrait::from_mode(m_param.mode); }
  51. /**
  52. * \param[in] src input tensor
  53. * \param[out] dst output tensor
  54. *
  55. * src and dst should have the same shape;
  56. * layouts should be contiguous;
  57. * the underlying data pointer can point to the same memory region for
  58. * src and dst.
  59. */
  60. virtual void exec(_megdnn_in const TensorNDArray& src, _megdnn_tensor_out dst) = 0;
  61. //! deduce output shape (do not check whether arity matches)
  62. MGE_WIN_DECLSPEC_FUC static void deduce_shape(
  63. const TensorShapeArray& src, TensorShape& dst);
  64. MGE_WIN_DECLSPEC_FUC static void deduce_format(
  65. const TensorFormatArray& src, TensorFormat& dst);
  66. //! deduce output layout
  67. MGE_WIN_DECLSPEC_FUC void deduce_layout(
  68. const TensorLayoutArray& src, TensorLayout& dst);
  69. protected:
  70. //! throw exception if incorrect layout; broadcast input shape to
  71. //! output shape
  72. MGE_WIN_DECLSPEC_FUC void check_layout_and_broadcast(
  73. const TensorLayoutPtrArray& src, const TensorLayout& dst);
  74. private:
  75. void check_dtype(DType dtype);
  76. };
  77. using Elemwise = ElemwiseForward;
  78. /*!
  79. * \brief compute ``x**a`` where ``a`` is a constant from the Param
  80. *
  81. * This opr is usually not directly accessible by the end user and it is created
  82. * by mgb optimizer, aiming to work around numerical stability issues with pow.
  83. * For example ``powf(x, 2.f)`` with ``x < 0`` in fast math mode may return NaN.
  84. *
  85. * Like elemwise, this opr supports arbitrary strides. But it should only be
  86. * used with monotone strides. Input and output should have the same
  87. * float-category dtype.
  88. */
  89. class PowC : public OperatorBase {
  90. DEF_OPR_PARAM(PowC);
  91. DEF_OPR_IMPL(PowC, OperatorBase, 1, 1);
  92. public:
  93. void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst);
  94. //! compatible API for mgb; workspace is not used
  95. void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_workspace) {
  96. return exec(src, dst);
  97. }
  98. size_t get_workspace_in_bytes(const TensorLayout&, const TensorLayout&) {
  99. // the impls should require no workspace; this can be later changed to a
  100. // virtual function if this situation changes
  101. return 0;
  102. }
  103. void deduce_layout(const TensorLayout& src, TensorLayout& dst) {
  104. dst.dtype = src.dtype;
  105. dst.init_contiguous_stride(src);
  106. }
  107. protected:
  108. /*!
  109. * Perform the computing where layouts have been verified.
  110. *
  111. * \p src can have arbitrary layout, and \p dst is contiguous. They have the
  112. * same shape and dtype.
  113. *
  114. * The implementation should not access param(). It should check \p exp_f
  115. * and \p exp_i for the exponent value. Exactly one of them would be
  116. * non-null.
  117. *
  118. * Note: \p exp_f and \p exp_i must be dereferenced before dispatching any
  119. * kernel. They are allocated on the caller's stack.
  120. */
  121. virtual void do_exec(
  122. _megdnn_tensor_in src, _megdnn_tensor_out dst, const float* exp_f,
  123. const int* exp_i) = 0;
  124. };
  125. /*!
  126. * \brief modify a tensor inplace by adding another tensor to it
  127. *
  128. * dst and delta can have arbitrary layout but must have the same shape.
  129. */
  130. class AddUpdateForward : public OperatorBase {
  131. DEF_OPR_PARAM(AddUpdate);
  132. DEF_OPR_IMPL(AddUpdateForward, OperatorBase, -1, 1);
  133. public:
  134. virtual void exec(_megdnn_tensor_inout dst, _megdnn_tensor_in delta) = 0;
  135. protected:
  136. void check_exec(const TensorLayout& dst, const TensorLayout& delta);
  137. };
  138. using AddUpdate = AddUpdateForward;
  139. class ReduceForward : public OperatorBase {
  140. DEF_OPR_PARAM(Reduce);
  141. DEF_OPR_IMPL(ReduceForward, OperatorBase, 1, 1);
  142. public:
  143. using Mode = Param::Mode;
  144. using DataType = Param::DataType;
  145. /**
  146. * \param[in] src input tensor
  147. * \param[out] dst output tensor
  148. *
  149. * src and dst should be contiguous.
  150. * src and dst should be of the same shape for all dimensions except
  151. * param().axis.
  152. * the param().axis-th dimension shape for dst should be one.
  153. */
  154. virtual void exec(
  155. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  156. _megdnn_workspace workspace) = 0;
  157. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  158. virtual size_t get_workspace_in_bytes(
  159. const TensorLayout& src, const TensorLayout& dst) = 0;
  160. protected:
  161. void check_exec(
  162. const TensorLayout& src, const TensorLayout& dst,
  163. size_t workspace_in_bytes);
  164. };
  165. using Reduce = ReduceForward;
  166. class CorrelationBase : public OperatorBase {
  167. DEF_OPR_IMPL_CTOR(CorrelationBase, OperatorBase);
  168. DEF_OPR_PARAM(Correlation);
  169. protected:
  170. void deduce_layout_fwd(
  171. const TensorLayout& data1, const TensorLayout& data2, TensorLayout& dst);
  172. void check_layout_fwd(
  173. const TensorLayout& data1, const TensorLayout& data2,
  174. const TensorLayout& dst);
  175. };
  176. class CorrelationForward : public CorrelationBase {
  177. DEF_OPR_IMPL(CorrelationForward, CorrelationBase, 2, 1);
  178. public:
  179. /**
  180. * \param[in] data1 (n, c, ih, iw)
  181. * \param[in] data2 (n, c, ih, iw)
  182. * \param[out] dst (n, q, oh, ow), q is the number of neighborhood
  183. * */
  184. virtual void exec(
  185. _megdnn_tensor_in data1, _megdnn_tensor_in data2, _megdnn_tensor_out dst,
  186. _megdnn_workspace workspace) = 0;
  187. void deduce_layout(
  188. const TensorLayout& data1, const TensorLayout& data2, TensorLayout& dst);
  189. virtual size_t get_workspace_in_bytes(
  190. const TensorLayout& data1, const TensorLayout& data2,
  191. const TensorLayout& dst) = 0;
  192. protected:
  193. void check_exec(
  194. const TensorLayout& data1, const TensorLayout& data2,
  195. const TensorLayout& dst, size_t workspace_in_bytes);
  196. };
  197. using Correlation = CorrelationForward;
  198. class CorrelationBackwardData1 : public CorrelationBase {
  199. DEF_OPR_IMPL(CorrelationBackwardData1, CorrelationBase, 3, 1);
  200. public:
  201. /**
  202. * \param[in] diff the backpropagated gradient wrt. dst
  203. * \param[in] data1 the `data1' parameter in CorrelationForward::exec
  204. * \param[in] data2 the `data2' parameter in CorrelationForward::exec
  205. * \param[out] grad1 the backpropagated gradient wrt. data1
  206. */
  207. virtual void exec(
  208. _megdnn_tensor_in diff, _megdnn_tensor_in data1, _megdnn_tensor_in data2,
  209. _megdnn_tensor_out grad1, _megdnn_workspace workspace) = 0;
  210. void deduce_layout(
  211. const TensorLayout& diff1, const TensorLayout& data1,
  212. const TensorLayout& data2, TensorLayout& dst);
  213. virtual size_t get_workspace_in_bytes(
  214. const TensorLayout& diff, const TensorLayout& data1,
  215. const TensorLayout& data2, const TensorLayout& grad1) = 0;
  216. protected:
  217. void check_exec(
  218. const TensorLayout& diff, const TensorLayout& data1,
  219. const TensorLayout& data2, const TensorLayout& grad1,
  220. size_t workspace_in_bytes);
  221. };
  222. class CorrelationBackwardData2 : public CorrelationBase {
  223. DEF_OPR_IMPL(CorrelationBackwardData2, CorrelationBase, 3, 1);
  224. public:
  225. /**
  226. * \param[in] diff the backpropagated gradient wrt. dst
  227. * \param[in] data1 the `data1' parameter in CorrelationForward::exec
  228. * \param[in] data2 the `data2' parameter in CorrelationForward::exec
  229. * \param[out] grad2 the backpropagated gradient wrt. data2
  230. */
  231. virtual void exec(
  232. _megdnn_tensor_in diff, _megdnn_tensor_in data1, _megdnn_tensor_in data2,
  233. _megdnn_tensor_out grad2, _megdnn_workspace workspace) = 0;
  234. void deduce_layout(
  235. const TensorLayout& diff1, const TensorLayout& data1,
  236. const TensorLayout& data2, TensorLayout& dst);
  237. virtual size_t get_workspace_in_bytes(
  238. const TensorLayout& diff, const TensorLayout& data1,
  239. const TensorLayout& data2, const TensorLayout& grad2) = 0;
  240. protected:
  241. void check_exec(
  242. const TensorLayout& diff, const TensorLayout& data1,
  243. const TensorLayout& data2, const TensorLayout& grad2,
  244. size_t workspace_in_bytes);
  245. };
  246. class CumsumForward : public OperatorBase {
  247. DEF_OPR_PARAM(Cumsum);
  248. DEF_OPR_IMPL(CumsumForward, OperatorBase, 1, 1);
  249. public:
  250. /**
  251. * \param[in] src input tensor
  252. * \param[out] dst output tensor
  253. *
  254. * src and dst should be contiguous.
  255. * src and dst should have the same shape.
  256. *
  257. * The exclusive flag specifies whether the current element it taken
  258. * into account when calculating results.
  259. *
  260. * The reverse flag specifies whether cumsum is forward (
  261. * from 0 to n) or backward (from n downto 0).
  262. *
  263. * Example:
  264. * exclusive && reverse:
  265. * dst_i = src_{i+1} + src_{i+2} + ... + src_{n-1}
  266. * exclusive && !reverse
  267. * dst_i = src_0 + src_1 + ... + src_{i-1}
  268. * !exclusive && reverse:
  269. * dst_i = src_i + src_{i+1} + ... + src_{n-1}
  270. * !exclusive && !reverse:
  271. * dst_i = src_0 + src_1 + ... + src_i
  272. */
  273. virtual void exec(
  274. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  275. _megdnn_workspace workspace) = 0;
  276. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  277. virtual size_t get_workspace_in_bytes(
  278. const TensorLayout& src, const TensorLayout& dst) = 0;
  279. protected:
  280. void check_exec(
  281. const TensorLayout& src, const TensorLayout& dst,
  282. size_t workspace_in_bytes);
  283. };
  284. using Cumsum = CumsumForward;
  285. // mxx can be max or min
  286. class ArgmxxBase : public OperatorBase {
  287. DEF_OPR_IMPL_CTOR(ArgmxxBase, OperatorBase);
  288. DEF_OPR_PARAM(Axis);
  289. protected:
  290. void check_layout_fwd(const TensorLayout& src, const TensorLayout& dst);
  291. };
  292. class ArgmaxForward : public ArgmxxBase {
  293. DEF_OPR_IMPL(ArgmaxForward, ArgmxxBase, 1, 1);
  294. public:
  295. /**
  296. * \param[in] src input tensor
  297. * \param[out] dst output tensor containing the argmax indices
  298. *
  299. * src and dst should be contiguous.
  300. * src and dst should be of the same shape for all dimensions except
  301. * param().axis.
  302. * the param().axis-th dimension shape for dst should be one.
  303. */
  304. virtual void exec(
  305. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  306. _megdnn_workspace workspace) = 0;
  307. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  308. virtual size_t get_workspace_in_bytes(
  309. const TensorLayout& src, const TensorLayout& dst) = 0;
  310. protected:
  311. void check_exec(
  312. const TensorLayout& src, const TensorLayout& dst,
  313. size_t workspace_in_bytes);
  314. };
  315. using Argmax = ArgmaxForward;
  316. class ArgminForward : public ArgmxxBase {
  317. DEF_OPR_IMPL(ArgminForward, ArgmxxBase, 1, 1);
  318. public:
  319. /**
  320. * \param[in] src input tensor
  321. * \param[out] dst output tensor containing the argmax indices
  322. *
  323. * src and dst should be contiguous.
  324. * src and dst should be of the same shape for all dimensions except
  325. * param().axis.
  326. * the param().axis-th dimension shape for dst should be one.
  327. */
  328. virtual void exec(
  329. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  330. _megdnn_workspace workspace) = 0;
  331. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  332. virtual size_t get_workspace_in_bytes(
  333. const TensorLayout& src, const TensorLayout& dst) = 0;
  334. protected:
  335. void check_exec(
  336. const TensorLayout& src, const TensorLayout& dst,
  337. size_t workspace_in_bytes);
  338. };
  339. using Argmin = ArgminForward;
  340. /*!
  341. * \brief take values from input according to given condition
  342. *
  343. * Output two tensors:
  344. * 1. values copied from *data*, with same dtype as *data*
  345. * 2. selected indices with dtype int32; note that it is 1-dimensional and
  346. * based on the flatten input.
  347. *
  348. * Require data and mask to have the same shape and both be contiguous.
  349. */
  350. class CondTake : public OperatorBase {
  351. DEF_OPR_IMPL(CondTake, OperatorBase, 2, 2);
  352. DEF_OPR_PARAM(CondTake);
  353. public:
  354. using Output = std::array<TensorND, 2>;
  355. using OutputDType = std::array<DType, 2>;
  356. OutputDType infer_dtype(DType data, DType mask);
  357. virtual size_t get_workspace_in_bytes(const TensorLayout& data) = 0;
  358. virtual Output exec(
  359. _megdnn_tensor_in data, _megdnn_tensor_in mask, _megdnn_workspace workspace,
  360. DynOutMallocPolicyCall malloc_policy) = 0;
  361. protected:
  362. //! check input layouts and get flattened size
  363. size_t check_exec_get_size(
  364. const TensorLayout& data, const TensorLayout& mask,
  365. size_t workspace_in_bytes);
  366. };
  367. class TransposeForward : public OperatorBase {
  368. DEF_OPR_IMPL(TransposeForward, OperatorBase, 1, 1);
  369. DEF_OPR_PARAM(Empty);
  370. public:
  371. /**
  372. * \param[in] src (m, n) stride[0] >= n && stride[1] == 1
  373. * \param[out] dst (n, m) stride[0] >= m && stride[1] == 1
  374. */
  375. virtual void exec(
  376. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  377. _megdnn_workspace workspace) = 0;
  378. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  379. virtual size_t get_workspace_in_bytes(
  380. const TensorLayout& src, const TensorLayout& dst) = 0;
  381. protected:
  382. void check_exec(
  383. const TensorLayout& src, const TensorLayout& dst,
  384. size_t workspace_in_bytes);
  385. };
  386. using Transpose = TransposeForward;
  387. /**
  388. * Change a tensor to another layout that has the same dtype and total number of
  389. * elements, and non-overlapping stride.
  390. *
  391. * ON CPU:
  392. * This operator is optimized for some cases(e.g. both dst and last dim of src
  393. * are contiguous)
  394. *
  395. * ON CUDA:
  396. * More contiguous the input/output layouts, higher performance. There is also
  397. * special optimization for broadcast case.
  398. */
  399. class RelayoutForward : public OperatorBase {
  400. DEF_OPR_IMPL(RelayoutForward, OperatorBase, 1, 1);
  401. DEF_OPR_PARAM(Empty);
  402. public:
  403. /*!
  404. * \brief execute relayout opr
  405. *
  406. * This operator should be placed on the same computing device of *dst*.
  407. *
  408. * \param src_handle handle of input tensor; for CUDA d2d copy, the
  409. * src handle can be on a different GPU for copy tensor with
  410. * non-contig dims <= 2
  411. */
  412. virtual void exec(
  413. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  414. Handle* src_handle = nullptr) = 0;
  415. protected:
  416. //! check layout and collapse contiguous
  417. void check_layout_and_canonize(TensorLayout& src, TensorLayout& dst);
  418. };
  419. using Relayout = RelayoutForward;
  420. /**
  421. * \brief Base class for Concat and Split operators
  422. */
  423. class ConcatSplitBase : public OperatorBase {
  424. public:
  425. using Param = param::Axis;
  426. ConcatSplitBase(Handle* handle);
  427. const Param& param() const { return m_param; }
  428. Param& param() { return m_param; }
  429. protected:
  430. void check_layout_common(const TensorLayoutArray& srcs, const TensorLayout& dst);
  431. Param m_param;
  432. /**
  433. * \brief a helper function
  434. *
  435. * A = shape[0] * shape[1] * ... * shape[axis-1]
  436. * B = {srcs[0].shape[axis], srcs[1].shape[axis], ...}
  437. * C = shape[axis+1] * shape[axis+2] * ... * shape[ndim-1]
  438. */
  439. void get_ABC(const TensorShapeArray& srcs, size_t& A, size_t* B, size_t& C);
  440. thin_function<TensorLayout(const TensorND& tensor)> m_get_layout;
  441. thin_function<TensorShape(const TensorLayout& layout)> m_get_shape;
  442. };
  443. class ConcatForward : public ConcatSplitBase {
  444. DEF_OPR_IMPL(ConcatForward, ConcatSplitBase, 1, 1);
  445. public:
  446. /**
  447. * \param[in] srcs a vector containing all inputs to be concatenated
  448. * \param[out] dst the output tensor.
  449. *
  450. * All tensors in srcs and dst should be contiguous.
  451. * All tensors should have the same shape for all axes except
  452. * param().axis.
  453. * For the param().axis-th axis, the axis shape for dst should be the
  454. * sum of corresponding axis shapes for all srcs.
  455. */
  456. virtual void exec(
  457. _megdnn_in const TensorNDArray& srcs, _megdnn_tensor_out dst,
  458. _megdnn_workspace workspace) = 0;
  459. void deduce_layout(const TensorLayoutArray& srcs, TensorLayout& dst);
  460. virtual size_t get_workspace_in_bytes(
  461. const TensorLayoutArray& srcs, const TensorLayout& dst) = 0;
  462. protected:
  463. void check_exec(
  464. const TensorLayoutArray& srcs, const TensorLayout& dst,
  465. size_t workspace_in_bytes);
  466. };
  467. using Concat = ConcatForward;
  468. class SplitForward : public ConcatSplitBase {
  469. DEF_OPR_IMPL(SplitForward, ConcatSplitBase, 1, 1);
  470. public:
  471. /**
  472. * \param[in] src input tensor
  473. * \param[out] dsts a vector containing all splitted result
  474. *
  475. * All tensors in src and dsts should be contiguous.
  476. * All tensors should have the same shape for all axes except
  477. * param().axis.
  478. * For the param().axis-th axis, the axis shape for src should be the
  479. * sum of corresponding axis shapes for all dsts.
  480. */
  481. virtual void exec(
  482. _megdnn_tensor_in src, const TensorNDArray& dsts,
  483. _megdnn_workspace workspace) = 0;
  484. virtual size_t get_workspace_in_bytes(
  485. const TensorLayout& src, const TensorLayoutArray& dsts) = 0;
  486. protected:
  487. void check_exec(
  488. const TensorLayout& src, const TensorLayoutArray& dsts,
  489. size_t workspace_in_bytes);
  490. };
  491. using Split = SplitForward;
  492. /**
  493. * \brief Base class for ParamPackConcat and ParamPackSplit Operators.
  494. *
  495. * ParamPack oprs act like Concat and Split, but they also are optimized for a
  496. * large number of inputs and can handle alignment requirements. Axis is also
  497. * not supported.
  498. *
  499. * The offsets can be generated by gen_offsets().
  500. */
  501. class ParamPackConcatSplitBase : public OperatorBase {
  502. protected:
  503. void check_exec(
  504. const TensorLayout& concated, const TensorLayout& offsets,
  505. const TensorLayout& parts);
  506. public:
  507. using Param = megdnn::param::Empty;
  508. ParamPackConcatSplitBase(Handle* handle) : OperatorBase(handle) {}
  509. //! generate offsets to be used with ParamPackConcat and ParamPackSplit
  510. MGE_WIN_DECLSPEC_FUC static std::vector<dt_int32> gen_offsets(
  511. const TensorShapeArray& shapes, size_t alignment, size_t dtype_size);
  512. };
  513. /**
  514. * \brief ParamPackConcat, used for calculating gradient of ParamPackSplit
  515. * Combine multiple gradient tensors into a single large tensor, use copy
  516. * strategy due to AddUpdate or other dynamic situation.
  517. */
  518. class ParamPackConcat : public ParamPackConcatSplitBase {
  519. DEF_OPR_IMPL(ParamPackConcat, ParamPackConcatSplitBase, 2, 1);
  520. public:
  521. /*
  522. * \param[in] srcs: TensorND on cpu. srcs[i] corresponding to the
  523. * address of i-th Tensor.
  524. * \param[in] offsets: with size `2 * srcs.shape[0]`.
  525. * offsets[i * 2] and offsets[i * 2 + 1] means
  526. * the begin and the end of srcs[i]'s offsets in dst
  527. * \param[out] dst: output TensorND, live on cpu or gpu
  528. */
  529. virtual void exec(
  530. _megdnn_tensor_in srcs, _megdnn_tensor_in offsets, _megdnn_tensor_out dst,
  531. _megdnn_workspace workspace) = 0;
  532. virtual size_t get_workspace_in_bytes(
  533. const TensorShapeArray& srcs, const TensorShape& offsets,
  534. const TensorShape& dst) = 0;
  535. };
  536. /**
  537. * \brief base class for Tile and Repeat
  538. */
  539. class TileRepeatBase : public OperatorBase {
  540. public:
  541. TileRepeatBase(Handle* handle) : OperatorBase(handle) {}
  542. struct Param {
  543. TensorShape times;
  544. };
  545. Param& param() { return m_param; }
  546. const Param& param() const { return m_param; }
  547. protected:
  548. void check_layout_fwd(const TensorLayout& src, const TensorLayout& dst);
  549. void deduce_layout_fwd(const TensorLayout& src, TensorLayout& dst);
  550. /**
  551. * Assuming src/dst/times are already simplified on entrance.
  552. */
  553. size_t get_workspace_in_bytes_fwd(
  554. const TensorShape& src, const TensorShape& dst, const TensorShape& times,
  555. DType dtype);
  556. Param m_param;
  557. };
  558. class TileBase : public TileRepeatBase {
  559. public:
  560. TileBase(Handle* handle) : TileRepeatBase(handle) {}
  561. protected:
  562. void simplify_shape(
  563. const TensorShape& src, const TensorShape& dst, const TensorShape& times,
  564. TensorShape& src2, TensorShape& dst2, TensorShape& times2);
  565. /**
  566. * This is a helper function that would facilitate other backends'
  567. * implementation.
  568. */
  569. size_t get_workspace_in_bytes_fwd(const TensorLayout& src, const TensorLayout& dst);
  570. };
  571. class TileForward : public TileBase {
  572. DEF_OPR_IMPL(TileForward, TileBase, 1, 1);
  573. public:
  574. /**
  575. * \brief Tile src times to get dst.
  576. * \param[in] src input tensor
  577. * \param[out] dst output tensor
  578. * \param[out] workspace temporary workspace
  579. *
  580. * src and dst must be contiguous.
  581. * dst.shape should be {src.shape[0]*param().times[0],
  582. * src.shape[1]*param().times[1], ...}
  583. *
  584. * \see http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html
  585. *
  586. * Difference between Tile and Repeat:
  587. * Tiling `abc' twice yields `abcabc', whereas repeating `abc' twice
  588. * yields `aabbcc'.
  589. */
  590. virtual void exec(
  591. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  592. _megdnn_workspace workspace) = 0;
  593. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  594. virtual size_t get_workspace_in_bytes(
  595. const TensorLayout& src, const TensorLayout& dst) = 0;
  596. protected:
  597. void check_exec(
  598. const TensorLayout& src, const TensorLayout& dst,
  599. size_t workspace_in_bytes);
  600. };
  601. using Tile = TileForward;
  602. class TileBackward : public TileBase {
  603. DEF_OPR_IMPL(TileBackward, TileBase, 1, 1);
  604. public:
  605. /**
  606. * \param[in] diff the backpropagated gradient wrt. dst
  607. * \param[out] grad the backpropagated gradient wrt. src
  608. * \param[out] workspace temporary workspace
  609. */
  610. virtual void exec(
  611. _megdnn_tensor_in diff, _megdnn_tensor_out grad,
  612. _megdnn_workspace workspace) = 0;
  613. virtual size_t get_workspace_in_bytes(
  614. const TensorLayout& diff, const TensorLayout& grad) = 0;
  615. protected:
  616. void check_exec(
  617. const TensorLayout& diff, const TensorLayout& grad,
  618. size_t workspace_in_bytes);
  619. };
  620. class RepeatBase : public TileRepeatBase {
  621. public:
  622. RepeatBase(Handle* handle) : TileRepeatBase(handle) {}
  623. protected:
  624. void simplify_shape(
  625. const TensorShape& src, const TensorShape& dst, const TensorShape& times,
  626. TensorShape& src2, TensorShape& dst2, TensorShape& times2);
  627. /**
  628. * This is a helper function that would facilitate other backends'
  629. * implementation.
  630. */
  631. size_t get_workspace_in_bytes_fwd(const TensorLayout& src, const TensorLayout& dst);
  632. };
  633. class RepeatForward : public RepeatBase {
  634. DEF_OPR_IMPL(RepeatForward, RepeatBase, 1, 1);
  635. public:
  636. /**
  637. * \brief Repeat src times to get dst.
  638. * \param[in] src input tensor
  639. * \param[out] dst output tensor
  640. * \param[out] workspace temporary workspace
  641. *
  642. * src and dst must be contiguous.
  643. * dst.shape should be {src.shape[0]*param().times[0],
  644. * src.shape[1]*param().times[1], ...}
  645. *
  646. * \see http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html
  647. * \see TileForward
  648. */
  649. virtual void exec(
  650. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  651. _megdnn_workspace workspace) = 0;
  652. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  653. virtual size_t get_workspace_in_bytes(
  654. const TensorLayout& src, const TensorLayout& dst) = 0;
  655. protected:
  656. void check_exec(
  657. const TensorLayout& src, const TensorLayout& dst,
  658. size_t workspace_in_bytes);
  659. };
  660. using Repeat = RepeatForward;
  661. class RepeatBackward : public RepeatBase {
  662. DEF_OPR_IMPL(RepeatBackward, RepeatBase, 1, 1);
  663. public:
  664. /**
  665. * \param[in] diff the backpropagated gradient wrt. dst
  666. * \param[out] grad the backpropagated gradient wrt. src
  667. * \param[out] workspace temporary workspace
  668. */
  669. virtual void exec(
  670. _megdnn_tensor_in diff, _megdnn_tensor_out grad,
  671. _megdnn_workspace workspace) = 0;
  672. virtual size_t get_workspace_in_bytes(
  673. const TensorLayout& diff, const TensorLayout& grad) = 0;
  674. protected:
  675. void check_exec(
  676. const TensorLayout& diff, const TensorLayout& grad,
  677. size_t workspace_in_bytes);
  678. };
  679. class ArgsortForward : public OperatorBase {
  680. DEF_OPR_IMPL(ArgsortForward, OperatorBase, 1, 2);
  681. DEF_OPR_PARAM(Argsort);
  682. public:
  683. using Order = Param::Order;
  684. /**
  685. * \param[in] src (m, n)
  686. * \param[out] dst (m, n)
  687. * \param[out] indices (m, n)
  688. *
  689. * src, dst and indices should be contiguous.
  690. * Performing m independent sorting on m arrays of length n.
  691. * Sorting arrays and storing the resulting array in `dst',
  692. * and the corresponding indices in `indices'.
  693. *
  694. * Indices range from 0 to n-1.
  695. *
  696. * Note that indices is a TensorND of type int.
  697. */
  698. virtual void exec(
  699. _megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_tensor_out indices,
  700. _megdnn_workspace workspace) = 0;
  701. void deduce_layout(
  702. const TensorLayout& src, TensorLayout& dst, TensorLayout& indices);
  703. virtual size_t get_workspace_in_bytes(
  704. const TensorLayout& src, const TensorLayout& dst,
  705. const TensorLayout& indices) = 0;
  706. protected:
  707. void check_exec(
  708. const TensorLayout& src, const TensorLayout& dst,
  709. const TensorLayout& indices, size_t workspace_in_bytes);
  710. };
  711. using Argsort = ArgsortForward;
  712. /*!
  713. * \brief backward opr for Argsort
  714. *
  715. * Note: the name is kept for backward compatibility. This opr is actually a
  716. * batched value setter. It is used for gradient computing of Argsort and TopK.
  717. */
  718. class ArgsortBackward : public OperatorBase {
  719. DEF_OPR_IMPL(ArgsortBackward, OperatorBase, 2, 1);
  720. DEF_OPR_PARAM(Empty);
  721. public:
  722. /**
  723. * \param[in] diff (m, k) the backpropagated gradient wrt. dst
  724. * \param[in] indices (m, k) the `indices' parameter in
  725. * ArgsortForward::exec
  726. * \param[out] grad (m, n) the backpropagated gradient wrt. src
  727. *
  728. * Constraint: n >= k. Untouched values would be initialized as zero.
  729. */
  730. virtual void exec(
  731. _megdnn_tensor_in diff, _megdnn_tensor_in indices, _megdnn_tensor_out grad,
  732. _megdnn_workspace workspace) = 0;
  733. virtual size_t get_workspace_in_bytes(
  734. const TensorLayout& diff, const TensorLayout& indices,
  735. const TensorLayout& grad) = 0;
  736. protected:
  737. void check_exec(
  738. const TensorLayout& diff, const TensorLayout& indices,
  739. const TensorLayout& grad, size_t workspace_in_bytes);
  740. };
  741. class TopK : public OperatorBase {
  742. DEF_OPR_IMPL(TopK, OperatorBase, 1, 2);
  743. DEF_OPR_PARAM(TopK);
  744. protected:
  745. //! impl exec; inputs have been validated
  746. virtual void do_exec(
  747. int k, _megdnn_tensor_in data, _megdnn_tensor_out values, int32_t* indices,
  748. _megdnn_workspace workspace) = 0;
  749. public:
  750. /*!
  751. * \param[in] k if positive, compute the smallest top-k values; otherwise
  752. * compute the largest top-k values
  753. * \param[in] data (m, n) input data, where top-k is computed on the
  754. * second axis. The second dimension must be contiguous, and the first
  755. * dimension can have arbitrary stride.
  756. * \param[out] values (m, ) or (m, k) output values; its shape depends
  757. * on mode
  758. * \param[out] indices () or (m, ) or (m, k) output values; its shape
  759. * depends on mode
  760. */
  761. void exec(
  762. int k, _megdnn_tensor_in data, _megdnn_tensor_out values,
  763. _megdnn_tensor_out indices, _megdnn_workspace workspace);
  764. virtual size_t get_workspace_in_bytes(
  765. int k, const TensorLayout& data, const TensorLayout& values,
  766. const TensorLayout& indices) = 0;
  767. void deduce_layout(
  768. int k, const TensorLayout& data, TensorLayout& values,
  769. TensorLayout& indices);
  770. };
  771. /*!
  772. * \brief convert dtype of *src* to match dtype of *dst*; *src* may have
  773. * arbitrary layout and *dst* must be contiguous.
  774. */
  775. class TypeCvtForward : public OperatorBase {
  776. DEF_OPR_PARAM(Empty);
  777. DEF_OPR_IMPL(TypeCvtForward, OperatorBase, 1, 1);
  778. public:
  779. virtual void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst) = 0;
  780. protected:
  781. void check_exec(const TensorLayout& src, const TensorLayout& dst);
  782. };
  783. using TypeCvt = TypeCvtForward;
  784. class IndexingRemapBase : public OperatorBase {
  785. public:
  786. using Param = param::IndexingRemap;
  787. IndexingRemapBase(Handle* handle) : OperatorBase(handle) {}
  788. Param& param() { return m_param; }
  789. const Param& param() const { return m_param; }
  790. protected:
  791. Param m_param;
  792. void check_layout_fwd(
  793. const TensorLayout& src, const TensorLayout& map, const TensorLayout& dst);
  794. };
  795. class IndexingRemapForward : public IndexingRemapBase {
  796. DEF_OPR_IMPL(IndexingRemapForward, IndexingRemapBase, 2, 1);
  797. public:
  798. /**
  799. * \param[in] src input tensor
  800. * \param[in] map input map
  801. * \param[out] dst output tensor
  802. *
  803. * Suppose:
  804. * the shape of src is \f$(s_0, s_1, ..., s_{m-1}\f$;
  805. * the shape of dst is \f$(d_0, d_1, ..., d_{n-1})\f$;
  806. * then:
  807. * the shape of map must be \f$(d_0, d_1, ..., d_{n-1}, m)\f$.
  808. *
  809. * The last dimension of map indicates the src indices for the
  810. * corresponding dst entry.
  811. *
  812. * src and dst can be non-contiguous in a non-overlapping manner.
  813. */
  814. virtual void exec(
  815. _megdnn_tensor_in src, _megdnn_tensor_in map, _megdnn_tensor_out dst,
  816. _megdnn_workspace workspace) = 0;
  817. void deduce_layout(
  818. const TensorLayout& src, const TensorLayout& map, TensorLayout& dst);
  819. virtual size_t get_workspace_in_bytes(
  820. const TensorLayout& src, const TensorLayout& map,
  821. const TensorLayout& dst) = 0;
  822. protected:
  823. void check_exec(
  824. const TensorLayout& src, const TensorLayout& map, const TensorLayout& dst,
  825. size_t workspace_in_bytes);
  826. };
  827. using IndexingRemap = IndexingRemapForward;
  828. // The using directives preserve backward compatibility.
  829. using TensorRemapForward = IndexingRemap;
  830. using TensorRemap = TensorRemapForward;
  831. class IndexingRemapBackward : public IndexingRemapBase {
  832. DEF_OPR_IMPL(IndexingRemapBackward, IndexingRemapBase, 2, 1);
  833. public:
  834. /**
  835. * \param[in] diff the backpropagated gradient wrt. dst
  836. * \param[in] map the `map' parameter in IndexingRemapForward::exec
  837. * \param[out] grad the backpropagated gradient wrt. src
  838. */
  839. virtual void exec(
  840. _megdnn_tensor_in diff, _megdnn_tensor_in map, _megdnn_tensor_out grad,
  841. _megdnn_workspace workspace) = 0;
  842. virtual size_t get_workspace_in_bytes(
  843. const TensorLayout& diff, const TensorLayout& map,
  844. const TensorLayout& grad) = 0;
  845. protected:
  846. void check_exec(
  847. const TensorLayout& diff, const TensorLayout& map, const TensorLayout& grad,
  848. size_t workspace_in_bytes);
  849. };
  850. // The using directives preserve backward compatibility.
  851. using TensorRemapBackward = IndexingRemapBackward;
  852. class Linspace : public OperatorBase {
  853. DEF_OPR_IMPL(Linspace, OperatorBase, 0, 1);
  854. DEF_OPR_PARAM(LinspaceFull);
  855. public:
  856. /**
  857. * \param[out] dst must be 1d.
  858. *
  859. * \see http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html
  860. */
  861. virtual void exec(_megdnn_tensor_out dst, _megdnn_workspace workspace) = 0;
  862. virtual size_t get_workspace_in_bytes(const TensorLayout& dst) = 0;
  863. protected:
  864. void check_exec(const TensorLayout& dst, size_t workspace_in_bytes);
  865. };
  866. class Eye : public OperatorBase {
  867. DEF_OPR_IMPL(Eye, OperatorBase, 0, 1);
  868. DEF_OPR_PARAM(Eye);
  869. public:
  870. /**
  871. * \see http://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html
  872. */
  873. virtual void exec(_megdnn_tensor_out dst, _megdnn_workspace workspace) = 0;
  874. virtual size_t get_workspace_in_bytes(const TensorLayout& dst) = 0;
  875. protected:
  876. void check_exec(const TensorLayout& dst, size_t workspace_in_bytes);
  877. };
  878. class IndexingOneHotBase : public OperatorBase {
  879. DEF_OPR_IMPL_CTOR(IndexingOneHotBase, OperatorBase);
  880. DEF_OPR_PARAM(Axis);
  881. protected:
  882. void deduce_layout_fwd(
  883. const TensorLayout& src, const TensorLayout& index, TensorLayout& dst);
  884. void check_layout_fwd(
  885. const TensorLayout& src, const TensorLayout& index,
  886. const TensorLayout& dst);
  887. };
  888. /*!
  889. * \brief Indexing for one-hot encoding
  890. *
  891. * Given src, axis and index,
  892. * for all valid (n-1)-dimensional subscript tuples i iterating through index:
  893. * dst[i[0], ..., i[axis-1], 0, i[axis], ..., i[n-2]] =
  894. * inp[i[0], ..., i[axis-1], index[i], i[axis], ..., i[n-2]]
  895. *
  896. * \param[in] src n-dimensional input data
  897. * \param[in] index (n-1)-dimensional index, must be int
  898. * \param[out] dst n-dimensional output data
  899. */
  900. class IndexingOneHotForward : public IndexingOneHotBase {
  901. DEF_OPR_IMPL(IndexingOneHotForward, IndexingOneHotBase, 2, 1);
  902. public:
  903. void deduce_layout(
  904. const TensorLayout& src, const TensorLayout& index, TensorLayout& dst) {
  905. deduce_layout_fwd(src, index, dst);
  906. }
  907. virtual void exec(
  908. _megdnn_tensor_in src, _megdnn_tensor_in index, _megdnn_tensor_out dst,
  909. _megdnn_workspace workspace) = 0;
  910. virtual size_t get_workspace_in_bytes(
  911. const TensorLayout& src, const TensorLayout& index,
  912. const TensorLayout& dst) = 0;
  913. protected:
  914. void check_exec(
  915. const TensorLayout& src, const TensorLayout& index, const TensorLayout& dst,
  916. size_t workspace_in_bytes);
  917. };
  918. using IndexingOneHot = IndexingOneHotForward;
  919. /*!
  920. * \brief set-subtensor corresponding to IndexingOneHotForward
  921. *
  922. * \param[in,out] data n-dimensional input and output data, whose sub part
  923. * corresponding to *index* would be replaced by *sub*
  924. * \param[in] index (n-1)-dimensional index, must be int
  925. * \param[in] sub n-dimensional sub tensor to be filled in *data*
  926. */
  927. class IndexingSetOneHotForward : public IndexingOneHotBase {
  928. DEF_OPR_IMPL(IndexingSetOneHotForward, IndexingOneHotBase, -1, 1);
  929. public:
  930. virtual void exec(
  931. _megdnn_tensor_inout data, _megdnn_tensor_in index, _megdnn_tensor_in sub,
  932. _megdnn_workspace workspace) = 0;
  933. virtual size_t get_workspace_in_bytes(
  934. const TensorLayout& data, const TensorLayout& index,
  935. const TensorLayout& sub) = 0;
  936. protected:
  937. void check_exec(
  938. const TensorLayout& data, const TensorLayout& index,
  939. const TensorLayout& sub, size_t workspace_in_bytes);
  940. };
  941. using IndexingSetOneHot = IndexingSetOneHotForward;
  942. /*!
  943. * \brief base class for indexing on multiple axes using vector indices
  944. *
  945. * Note that the indexing axes are required to be sorted in ascending order
  946. */
  947. class IndexingMultiAxisVecBase : public OperatorBase {
  948. DEF_OPR_IMPL_CTOR(IndexingMultiAxisVecBase, OperatorBase);
  949. DEF_OPR_PARAM(Empty);
  950. public:
  951. struct AxisIndexer {
  952. size_t axis;
  953. TensorND vec;
  954. };
  955. struct AxisIndexerLayoutOnly {
  956. size_t axis;
  957. TensorLayout layout;
  958. };
  959. using IndexDesc = std::vector<AxisIndexer>;
  960. using IndexDescLayoutOnly = std::vector<AxisIndexerLayoutOnly>;
  961. /*!
  962. * \brief convert IndexDesc to IndexDescLayoutOnly
  963. */
  964. static IndexDescLayoutOnly extract_index_layout(const IndexDesc& index);
  965. /*!
  966. * \brief get the axes on src that are not used in index
  967. * \param[out] out output buffer; suggested size is
  968. * TensorLayout::MAX_NDIM
  969. * \return number of elements written to *out*
  970. */
  971. static size_t get_nonindex_axes(
  972. size_t src_ndim, const IndexDesc& index, size_t* out);
  973. /*!
  974. * \brief get contiguous-collapsed layout for indexing on value
  975. * \param idx_axis indexer axis on value (i.e. ExecInfo::idx_axis)
  976. * \return a tensor layout and an axis to iterate over *value* and also
  977. * access *data*; stride of layout on that axis would be zero, and
  978. * strides on other axes correspond to the strides in *data*
  979. */
  980. static std::tuple<TensorLayout, size_t, TensorShape> get_value_iter_optimized_layout(
  981. const TensorLayout& data, const TensorLayout& value, const IndexDesc& index,
  982. size_t idx_axis);
  983. //! helper info for kernel implementation
  984. struct ExecInfo {
  985. //! axis in value used by indexer
  986. size_t idx_axis;
  987. ptrdiff_t value_stride;
  988. void* error_tracker;
  989. megcore::AsyncErrorInfo* error_info;
  990. };
  991. protected:
  992. /*!
  993. * \return axis on dst used by indexer (i.e. ExecInfo::idx_axis)
  994. */
  995. static size_t deduce_layout_fwd(
  996. const TensorLayout& data, const IndexDescLayoutOnly& index,
  997. TensorLayout& dst);
  998. static ExecInfo check_exec_noworkspace(
  999. const TensorLayout& data, const TensorLayout& value, const IndexDesc& index,
  1000. IndexDescLayoutOnly& index_layout);
  1001. };
  1002. /*!
  1003. * \brief compute indexing result, like numpy advanced indexing
  1004. *
  1005. * src can have arbitrary layout, but dst must be dim1-contig
  1006. */
  1007. class IndexingMultiAxisVec : public IndexingMultiAxisVecBase {
  1008. DEF_OPR_IMPL(IndexingMultiAxisVec, IndexingMultiAxisVecBase, 0, 1);
  1009. public:
  1010. virtual void exec(
  1011. _megdnn_tensor_in src, const IndexDesc& index, _megdnn_tensor_out dst,
  1012. _megdnn_workspace workspace) = 0;
  1013. /*!
  1014. * \brief get workspace size based on output shape and indexing axes
  1015. */
  1016. size_t get_workspace_in_bytes(
  1017. const TensorShape& dst, const size_t* axes, size_t nr_axes,
  1018. size_t idx_ndim);
  1019. static void deduce_layout(
  1020. const TensorLayout& data, const IndexDescLayoutOnly& index,
  1021. TensorLayout& dst) {
  1022. deduce_layout_fwd(data, index, dst);
  1023. }
  1024. protected:
  1025. virtual size_t get_workspace_in_bytes(size_t dst_idx_size) = 0;
  1026. ExecInfo check_exec(
  1027. const TensorLayout& src, const IndexDesc& index, const TensorLayout& dst,
  1028. size_t workspace_in_bytes);
  1029. };
  1030. /*!
  1031. * \brief base class for modifying data by given index
  1032. *
  1033. * data can have arbitrary layout, but value must be dim1-contig
  1034. */
  1035. class IndexingModifyMultiAxisVecBase : public IndexingMultiAxisVecBase {
  1036. DEF_OPR_IMPL_CTOR(IndexingModifyMultiAxisVecBase, IndexingMultiAxisVecBase);
  1037. public:
  1038. virtual void exec(
  1039. _megdnn_tensor_inout data, _megdnn_tensor_in value, const IndexDesc& index,
  1040. _megdnn_workspace workspace) = 0;
  1041. /*!
  1042. * \brief get workspace size based on shape of value input and indexing
  1043. * axes
  1044. */
  1045. size_t get_workspace_in_bytes(
  1046. const TensorShape& value, const size_t* axes, size_t nr_axes,
  1047. size_t idx_ndim);
  1048. protected:
  1049. ExecInfo check_exec(
  1050. const TensorLayout& data, const TensorLayout& value, const IndexDesc& index,
  1051. size_t workspace_in_bytes);
  1052. virtual size_t get_workspace_in_bytes(size_t value_idx_size) = 0;
  1053. };
  1054. //! set value to indexed locations; index values must be non-overlapping
  1055. class IndexingSetMultiAxisVec : public IndexingModifyMultiAxisVecBase {
  1056. DEF_OPR_IMPL(IndexingSetMultiAxisVec, IndexingModifyMultiAxisVecBase, 0, 0);
  1057. };
  1058. //! add value to indexed locations; index values must be non-overlapping
  1059. class IndexingIncrMultiAxisVec : public IndexingModifyMultiAxisVecBase {
  1060. DEF_OPR_IMPL(IndexingIncrMultiAxisVec, IndexingModifyMultiAxisVecBase, 0, 0);
  1061. };
  1062. class MeshBase : public OperatorBase {
  1063. DEF_OPR_PARAM(Empty);
  1064. DEF_OPR_IMPL_CTOR(MeshBase, OperatorBase);
  1065. public:
  1066. using AxisIndexer = IndexingMultiAxisVecBase::AxisIndexer;
  1067. using IndexDesc = IndexingMultiAxisVecBase::IndexDesc;
  1068. using AxisIndexerLayoutOnly = IndexingMultiAxisVecBase::AxisIndexerLayoutOnly;
  1069. using IndexDescLayoutOnly = IndexingMultiAxisVecBase::IndexDescLayoutOnly;
  1070. size_t get_workspace_in_bytes(const TensorShape&, const size_t*, size_t, size_t) {
  1071. return 0;
  1072. }
  1073. protected:
  1074. virtual void check_exec(
  1075. const TensorLayout& origin, const TensorLayout& indexed,
  1076. const IndexDesc& desc);
  1077. };
  1078. class NormalMeshBase : public MeshBase {
  1079. DEF_OPR_IMPL(NormalMeshBase, MeshBase, 0, 0);
  1080. protected:
  1081. virtual void check_exec(
  1082. const TensorLayout& origin, const TensorLayout& indexed,
  1083. const IndexDesc& desc) override final;
  1084. };
  1085. class NormalMeshModifyBase : public NormalMeshBase {
  1086. DEF_OPR_IMPL_CTOR(NormalMeshModifyBase, NormalMeshBase);
  1087. public:
  1088. virtual void exec(
  1089. _megdnn_tensor_inout data, _megdnn_tensor_in value, const IndexDesc& desc,
  1090. _megdnn_workspace workspace) = 0;
  1091. };
  1092. class BatchedMeshBase : public MeshBase {
  1093. DEF_OPR_IMPL_CTOR(BatchedMeshBase, MeshBase);
  1094. protected:
  1095. virtual void check_exec(
  1096. const TensorLayout& origin, const TensorLayout& indexed,
  1097. const IndexDesc& desc) override final;
  1098. };
  1099. class BatchedMeshModifyBase : public BatchedMeshBase {
  1100. DEF_OPR_IMPL_CTOR(BatchedMeshModifyBase, BatchedMeshBase);
  1101. public:
  1102. virtual void exec(
  1103. _megdnn_tensor_inout data, _megdnn_tensor_in value, const IndexDesc& desc,
  1104. _megdnn_workspace workspace) = 0;
  1105. };
  1106. class MeshIndexing : public NormalMeshBase {
  1107. DEF_OPR_IMPL(MeshIndexing, NormalMeshBase, 0, 0);
  1108. public:
  1109. virtual void exec(
  1110. _megdnn_tensor_in src, const IndexDesc& desc, _megdnn_tensor_out dst,
  1111. _megdnn_workspace workspace) = 0;
  1112. static void deduce_layout(
  1113. const TensorLayout& inp, const IndexDescLayoutOnly& layouts,
  1114. TensorLayout& out_layout);
  1115. };
  1116. class IncrMeshIndexing : public NormalMeshModifyBase {
  1117. DEF_OPR_IMPL(IncrMeshIndexing, NormalMeshModifyBase, 0, 0);
  1118. };
  1119. class SetMeshIndexing : public NormalMeshModifyBase {
  1120. DEF_OPR_IMPL(SetMeshIndexing, NormalMeshModifyBase, 0, 0);
  1121. };
  1122. class BatchedMeshIndexing : public BatchedMeshBase {
  1123. DEF_OPR_IMPL(BatchedMeshIndexing, BatchedMeshBase, 0, 0);
  1124. public:
  1125. virtual void exec(
  1126. _megdnn_tensor_in src, const IndexDesc& desc, _megdnn_tensor_out dst,
  1127. _megdnn_workspace workspace) = 0;
  1128. static void deduce_layout(
  1129. const TensorLayout& inp, const IndexDescLayoutOnly& layouts,
  1130. TensorLayout& out_layout);
  1131. };
  1132. class BatchedIncrMeshIndexing : public BatchedMeshModifyBase {
  1133. DEF_OPR_IMPL(BatchedIncrMeshIndexing, BatchedMeshModifyBase, 0, 0);
  1134. };
  1135. class BatchedSetMeshIndexing : public BatchedMeshModifyBase {
  1136. DEF_OPR_IMPL(BatchedSetMeshIndexing, BatchedMeshModifyBase, 0, 0);
  1137. };
  1138. class RelayoutFormat : public OperatorBase {
  1139. DEF_OPR_PARAM(RelayoutFormat);
  1140. DEF_OPR_IMPL(RelayoutFormat, OperatorBase, 1, 1);
  1141. public:
  1142. virtual void exec(
  1143. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  1144. _megdnn_workspace workspace) = 0;
  1145. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  1146. void deduce_format(TensorFormat src, TensorFormat& dst);
  1147. virtual size_t get_workspace_in_bytes(
  1148. const TensorLayout& src, const TensorLayout& dst) = 0;
  1149. protected:
  1150. void deduce_layout_fwd(const TensorLayout& src, TensorLayout& dst);
  1151. void check_layout_fwd(const TensorLayout& src, const TensorLayout& dst);
  1152. void check_exec(
  1153. const TensorLayout& src, const TensorLayout& dst,
  1154. size_t workspace_in_bytes);
  1155. void deduce_exec_layout(
  1156. const TensorLayout& src, const TensorLayout& dst,
  1157. TensorLayout& exec_workspace, TensorLayout& exec_src,
  1158. TensorLayout& exec_dst);
  1159. };
  1160. /*!
  1161. * \brief check whether input contains inf or nan value.
  1162. */
  1163. class CheckNonFinite : public OperatorBase {
  1164. DEF_OPR_PARAM(Empty);
  1165. DEF_OPR_IMPL(CheckNonFinite, OperatorBase, 1, 1);
  1166. public:
  1167. virtual size_t get_workspace_in_bytes(
  1168. const TensorLayout& src, const TensorLayout& dst) = 0;
  1169. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  1170. virtual void exec(
  1171. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  1172. _megdnn_workspace workspace) = 0;
  1173. protected:
  1174. void check_exec(
  1175. const TensorLayout& src, const TensorLayout& dst,
  1176. size_t workspace_in_bytes);
  1177. };
  1178. /*!
  1179. * \brief fill the tensor with a scalar value
  1180. */
  1181. class Fill : public OperatorBase {
  1182. DEF_OPR_PARAM(Fill);
  1183. DEF_OPR_IMPL(Fill, OperatorBase, 0, 1);
  1184. public:
  1185. virtual void exec(_megdnn_tensor_out dst, _megdnn_workspace workspace) = 0;
  1186. virtual size_t get_workspace_in_bytes(const TensorLayout& dst) = 0;
  1187. protected:
  1188. void check_exec(const TensorLayout& dst, size_t workspace_in_bytes);
  1189. };
  1190. /*!
  1191. * \brief standard padding operator
  1192. * Inputs must have the same dtype, and the output tensor shape must greater or equal
  1193. * than input tensor in every dimensions, the extra space will be fulled with m which
  1194. * default to be 0.
  1195. */
  1196. class PaddingBase : public OperatorBase {
  1197. DEF_OPR_PARAM(Padding);
  1198. DEF_OPR_IMPL(PaddingBase, OperatorBase, 1, 1);
  1199. public:
  1200. using Mode = Param::PaddingMode;
  1201. protected:
  1202. SmallVector<size_t> get_offsets();
  1203. void check_exec(const TensorLayout& src, const TensorLayout& dst);
  1204. };
  1205. class PaddingForward : public PaddingBase {
  1206. DEF_OPR_IMPL(PaddingForward, PaddingBase, 1, 1);
  1207. public:
  1208. virtual void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst) = 0;
  1209. void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_workspace) {
  1210. return exec(src, dst);
  1211. }
  1212. virtual size_t get_workspace_in_bytes(
  1213. const TensorLayout& src, const TensorLayout& dst) = 0;
  1214. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  1215. protected:
  1216. void forward_check_exec(const TensorLayout& src, const TensorLayout& dst);
  1217. };
  1218. using Padding = PaddingForward;
  1219. class PaddingBackward : public PaddingBase {
  1220. DEF_OPR_IMPL(PaddingBackward, PaddingBase, 1, 1);
  1221. public:
  1222. virtual void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst) = 0;
  1223. void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_workspace) {
  1224. return exec(src, dst);
  1225. }
  1226. virtual size_t get_workspace_in_bytes(
  1227. const TensorLayout& src, const TensorLayout& dst) = 0;
  1228. protected:
  1229. void backward_check_exec(const TensorLayout& src, const TensorLayout& dst);
  1230. };
  1231. } // namespace megdnn
  1232. #include "megdnn/internal/opr_header_epilogue.h"
  1233. // vim: syntax=cpp.doxygen

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