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 53 kB

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