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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  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 Diag : public OperatorBase {
  879. DEF_OPR_IMPL(Diag, OperatorBase, 1, 1);
  880. DEF_OPR_PARAM(Diag);
  881. public:
  882. /**
  883. * \see http://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html
  884. */
  885. virtual void exec(
  886. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  887. _megdnn_workspace workspace) = 0;
  888. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  889. virtual size_t get_workspace_in_bytes(
  890. const TensorLayout& src, const TensorLayout& dst) = 0;
  891. protected:
  892. void check_exec(
  893. const TensorLayout& src, const TensorLayout& dst,
  894. size_t workspace_in_bytes);
  895. };
  896. class IndexingOneHotBase : public OperatorBase {
  897. DEF_OPR_IMPL_CTOR(IndexingOneHotBase, OperatorBase);
  898. DEF_OPR_PARAM(Axis);
  899. protected:
  900. void deduce_layout_fwd(
  901. const TensorLayout& src, const TensorLayout& index, TensorLayout& dst);
  902. void check_layout_fwd(
  903. const TensorLayout& src, const TensorLayout& index,
  904. const TensorLayout& dst);
  905. };
  906. /*!
  907. * \brief Indexing for one-hot encoding
  908. *
  909. * Given src, axis and index,
  910. * for all valid (n-1)-dimensional subscript tuples i iterating through index:
  911. * dst[i[0], ..., i[axis-1], 0, i[axis], ..., i[n-2]] =
  912. * inp[i[0], ..., i[axis-1], index[i], i[axis], ..., i[n-2]]
  913. *
  914. * \param[in] src n-dimensional input data
  915. * \param[in] index (n-1)-dimensional index, must be int
  916. * \param[out] dst n-dimensional output data
  917. */
  918. class IndexingOneHotForward : public IndexingOneHotBase {
  919. DEF_OPR_IMPL(IndexingOneHotForward, IndexingOneHotBase, 2, 1);
  920. public:
  921. void deduce_layout(
  922. const TensorLayout& src, const TensorLayout& index, TensorLayout& dst) {
  923. deduce_layout_fwd(src, index, dst);
  924. }
  925. virtual void exec(
  926. _megdnn_tensor_in src, _megdnn_tensor_in index, _megdnn_tensor_out dst,
  927. _megdnn_workspace workspace) = 0;
  928. virtual size_t get_workspace_in_bytes(
  929. const TensorLayout& src, const TensorLayout& index,
  930. const TensorLayout& dst) = 0;
  931. protected:
  932. void check_exec(
  933. const TensorLayout& src, const TensorLayout& index, const TensorLayout& dst,
  934. size_t workspace_in_bytes);
  935. };
  936. using IndexingOneHot = IndexingOneHotForward;
  937. /*!
  938. * \brief set-subtensor corresponding to IndexingOneHotForward
  939. *
  940. * \param[in,out] data n-dimensional input and output data, whose sub part
  941. * corresponding to *index* would be replaced by *sub*
  942. * \param[in] index (n-1)-dimensional index, must be int
  943. * \param[in] sub n-dimensional sub tensor to be filled in *data*
  944. */
  945. class IndexingSetOneHotForward : public IndexingOneHotBase {
  946. DEF_OPR_IMPL(IndexingSetOneHotForward, IndexingOneHotBase, -1, 1);
  947. public:
  948. virtual void exec(
  949. _megdnn_tensor_inout data, _megdnn_tensor_in index, _megdnn_tensor_in sub,
  950. _megdnn_workspace workspace) = 0;
  951. virtual size_t get_workspace_in_bytes(
  952. const TensorLayout& data, const TensorLayout& index,
  953. const TensorLayout& sub) = 0;
  954. protected:
  955. void check_exec(
  956. const TensorLayout& data, const TensorLayout& index,
  957. const TensorLayout& sub, size_t workspace_in_bytes);
  958. };
  959. using IndexingSetOneHot = IndexingSetOneHotForward;
  960. /*!
  961. * \brief base class for indexing on multiple axes using vector indices
  962. *
  963. * Note that the indexing axes are required to be sorted in ascending order
  964. */
  965. class IndexingMultiAxisVecBase : public OperatorBase {
  966. DEF_OPR_IMPL_CTOR(IndexingMultiAxisVecBase, OperatorBase);
  967. DEF_OPR_PARAM(Empty);
  968. public:
  969. struct AxisIndexer {
  970. size_t axis;
  971. TensorND vec;
  972. };
  973. struct AxisIndexerLayoutOnly {
  974. size_t axis;
  975. TensorLayout layout;
  976. };
  977. using IndexDesc = std::vector<AxisIndexer>;
  978. using IndexDescLayoutOnly = std::vector<AxisIndexerLayoutOnly>;
  979. /*!
  980. * \brief convert IndexDesc to IndexDescLayoutOnly
  981. */
  982. static IndexDescLayoutOnly extract_index_layout(const IndexDesc& index);
  983. /*!
  984. * \brief get the axes on src that are not used in index
  985. * \param[out] out output buffer; suggested size is
  986. * TensorLayout::MAX_NDIM
  987. * \return number of elements written to *out*
  988. */
  989. static size_t get_nonindex_axes(
  990. size_t src_ndim, const IndexDesc& index, size_t* out);
  991. /*!
  992. * \brief get contiguous-collapsed layout for indexing on value
  993. * \param idx_axis indexer axis on value (i.e. ExecInfo::idx_axis)
  994. * \return a tensor layout and an axis to iterate over *value* and also
  995. * access *data*; stride of layout on that axis would be zero, and
  996. * strides on other axes correspond to the strides in *data*
  997. */
  998. static std::tuple<TensorLayout, size_t, TensorShape> get_value_iter_optimized_layout(
  999. const TensorLayout& data, const TensorLayout& value, const IndexDesc& index,
  1000. size_t idx_axis);
  1001. //! helper info for kernel implementation
  1002. struct ExecInfo {
  1003. //! axis in value used by indexer
  1004. size_t idx_axis;
  1005. ptrdiff_t value_stride;
  1006. void* error_tracker;
  1007. megcore::AsyncErrorInfo* error_info;
  1008. };
  1009. protected:
  1010. /*!
  1011. * \return axis on dst used by indexer (i.e. ExecInfo::idx_axis)
  1012. */
  1013. static size_t deduce_layout_fwd(
  1014. const TensorLayout& data, const IndexDescLayoutOnly& index,
  1015. TensorLayout& dst);
  1016. static ExecInfo check_exec_noworkspace(
  1017. const TensorLayout& data, const TensorLayout& value, const IndexDesc& index,
  1018. IndexDescLayoutOnly& index_layout);
  1019. };
  1020. /*!
  1021. * \brief compute indexing result, like numpy advanced indexing
  1022. *
  1023. * src can have arbitrary layout, but dst must be dim1-contig
  1024. */
  1025. class IndexingMultiAxisVec : public IndexingMultiAxisVecBase {
  1026. DEF_OPR_IMPL(IndexingMultiAxisVec, IndexingMultiAxisVecBase, 0, 1);
  1027. public:
  1028. virtual void exec(
  1029. _megdnn_tensor_in src, const IndexDesc& index, _megdnn_tensor_out dst,
  1030. _megdnn_workspace workspace) = 0;
  1031. /*!
  1032. * \brief get workspace size based on output shape and indexing axes
  1033. */
  1034. size_t get_workspace_in_bytes(
  1035. const TensorShape& dst, const size_t* axes, size_t nr_axes,
  1036. size_t idx_ndim);
  1037. static void deduce_layout(
  1038. const TensorLayout& data, const IndexDescLayoutOnly& index,
  1039. TensorLayout& dst) {
  1040. deduce_layout_fwd(data, index, dst);
  1041. }
  1042. protected:
  1043. virtual size_t get_workspace_in_bytes(size_t dst_idx_size) = 0;
  1044. ExecInfo check_exec(
  1045. const TensorLayout& src, const IndexDesc& index, const TensorLayout& dst,
  1046. size_t workspace_in_bytes);
  1047. };
  1048. /*!
  1049. * \brief base class for modifying data by given index
  1050. *
  1051. * data can have arbitrary layout, but value must be dim1-contig
  1052. */
  1053. class IndexingModifyMultiAxisVecBase : public IndexingMultiAxisVecBase {
  1054. DEF_OPR_IMPL_CTOR(IndexingModifyMultiAxisVecBase, IndexingMultiAxisVecBase);
  1055. public:
  1056. virtual void exec(
  1057. _megdnn_tensor_inout data, _megdnn_tensor_in value, const IndexDesc& index,
  1058. _megdnn_workspace workspace) = 0;
  1059. /*!
  1060. * \brief get workspace size based on shape of value input and indexing
  1061. * axes
  1062. */
  1063. size_t get_workspace_in_bytes(
  1064. const TensorShape& value, const size_t* axes, size_t nr_axes,
  1065. size_t idx_ndim);
  1066. protected:
  1067. ExecInfo check_exec(
  1068. const TensorLayout& data, const TensorLayout& value, const IndexDesc& index,
  1069. size_t workspace_in_bytes);
  1070. virtual size_t get_workspace_in_bytes(size_t value_idx_size) = 0;
  1071. };
  1072. //! set value to indexed locations; index values must be non-overlapping
  1073. class IndexingSetMultiAxisVec : public IndexingModifyMultiAxisVecBase {
  1074. DEF_OPR_IMPL(IndexingSetMultiAxisVec, IndexingModifyMultiAxisVecBase, 0, 0);
  1075. };
  1076. //! add value to indexed locations; index values must be non-overlapping
  1077. class IndexingIncrMultiAxisVec : public IndexingModifyMultiAxisVecBase {
  1078. DEF_OPR_IMPL(IndexingIncrMultiAxisVec, IndexingModifyMultiAxisVecBase, 0, 0);
  1079. };
  1080. class MeshBase : public OperatorBase {
  1081. DEF_OPR_PARAM(Empty);
  1082. DEF_OPR_IMPL_CTOR(MeshBase, OperatorBase);
  1083. public:
  1084. using AxisIndexer = IndexingMultiAxisVecBase::AxisIndexer;
  1085. using IndexDesc = IndexingMultiAxisVecBase::IndexDesc;
  1086. using AxisIndexerLayoutOnly = IndexingMultiAxisVecBase::AxisIndexerLayoutOnly;
  1087. using IndexDescLayoutOnly = IndexingMultiAxisVecBase::IndexDescLayoutOnly;
  1088. size_t get_workspace_in_bytes(const TensorShape&, const size_t*, size_t, size_t) {
  1089. return 0;
  1090. }
  1091. protected:
  1092. virtual void check_exec(
  1093. const TensorLayout& origin, const TensorLayout& indexed,
  1094. const IndexDesc& desc);
  1095. };
  1096. class NormalMeshBase : public MeshBase {
  1097. DEF_OPR_IMPL(NormalMeshBase, MeshBase, 0, 0);
  1098. protected:
  1099. virtual void check_exec(
  1100. const TensorLayout& origin, const TensorLayout& indexed,
  1101. const IndexDesc& desc) override final;
  1102. };
  1103. class NormalMeshModifyBase : public NormalMeshBase {
  1104. DEF_OPR_IMPL_CTOR(NormalMeshModifyBase, NormalMeshBase);
  1105. public:
  1106. virtual void exec(
  1107. _megdnn_tensor_inout data, _megdnn_tensor_in value, const IndexDesc& desc,
  1108. _megdnn_workspace workspace) = 0;
  1109. };
  1110. class BatchedMeshBase : public MeshBase {
  1111. DEF_OPR_IMPL_CTOR(BatchedMeshBase, MeshBase);
  1112. protected:
  1113. virtual void check_exec(
  1114. const TensorLayout& origin, const TensorLayout& indexed,
  1115. const IndexDesc& desc) override final;
  1116. };
  1117. class BatchedMeshModifyBase : public BatchedMeshBase {
  1118. DEF_OPR_IMPL_CTOR(BatchedMeshModifyBase, BatchedMeshBase);
  1119. public:
  1120. virtual void exec(
  1121. _megdnn_tensor_inout data, _megdnn_tensor_in value, const IndexDesc& desc,
  1122. _megdnn_workspace workspace) = 0;
  1123. };
  1124. class MeshIndexing : public NormalMeshBase {
  1125. DEF_OPR_IMPL(MeshIndexing, NormalMeshBase, 0, 0);
  1126. public:
  1127. virtual void exec(
  1128. _megdnn_tensor_in src, const IndexDesc& desc, _megdnn_tensor_out dst,
  1129. _megdnn_workspace workspace) = 0;
  1130. static void deduce_layout(
  1131. const TensorLayout& inp, const IndexDescLayoutOnly& layouts,
  1132. TensorLayout& out_layout);
  1133. };
  1134. class IncrMeshIndexing : public NormalMeshModifyBase {
  1135. DEF_OPR_IMPL(IncrMeshIndexing, NormalMeshModifyBase, 0, 0);
  1136. };
  1137. class SetMeshIndexing : public NormalMeshModifyBase {
  1138. DEF_OPR_IMPL(SetMeshIndexing, NormalMeshModifyBase, 0, 0);
  1139. };
  1140. class BatchedMeshIndexing : public BatchedMeshBase {
  1141. DEF_OPR_IMPL(BatchedMeshIndexing, BatchedMeshBase, 0, 0);
  1142. public:
  1143. virtual void exec(
  1144. _megdnn_tensor_in src, const IndexDesc& desc, _megdnn_tensor_out dst,
  1145. _megdnn_workspace workspace) = 0;
  1146. static void deduce_layout(
  1147. const TensorLayout& inp, const IndexDescLayoutOnly& layouts,
  1148. TensorLayout& out_layout);
  1149. };
  1150. class BatchedIncrMeshIndexing : public BatchedMeshModifyBase {
  1151. DEF_OPR_IMPL(BatchedIncrMeshIndexing, BatchedMeshModifyBase, 0, 0);
  1152. };
  1153. class BatchedSetMeshIndexing : public BatchedMeshModifyBase {
  1154. DEF_OPR_IMPL(BatchedSetMeshIndexing, BatchedMeshModifyBase, 0, 0);
  1155. };
  1156. class RelayoutFormat : public OperatorBase {
  1157. DEF_OPR_PARAM(RelayoutFormat);
  1158. DEF_OPR_IMPL(RelayoutFormat, OperatorBase, 1, 1);
  1159. public:
  1160. virtual void exec(
  1161. _megdnn_tensor_in src, _megdnn_tensor_out dst,
  1162. _megdnn_workspace workspace) = 0;
  1163. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  1164. void deduce_format(TensorFormat src, TensorFormat& dst);
  1165. virtual size_t get_workspace_in_bytes(
  1166. const TensorLayout& src, const TensorLayout& dst) = 0;
  1167. protected:
  1168. void deduce_layout_fwd(const TensorLayout& src, TensorLayout& dst);
  1169. void check_layout_fwd(const TensorLayout& src, const TensorLayout& dst);
  1170. void check_exec(
  1171. const TensorLayout& src, const TensorLayout& dst,
  1172. size_t workspace_in_bytes);
  1173. void deduce_exec_layout(
  1174. const TensorLayout& src, const TensorLayout& dst,
  1175. TensorLayout& exec_workspace, TensorLayout& exec_src,
  1176. TensorLayout& exec_dst);
  1177. };
  1178. /*!
  1179. * \brief check whether input contains inf or nan value.
  1180. */
  1181. class CheckNonFinite : public OperatorBase {
  1182. DEF_OPR_PARAM(CheckNonFinite);
  1183. DEF_OPR_IMPL(CheckNonFinite, OperatorBase, -1, 1);
  1184. size_t m_size = 0;
  1185. public:
  1186. virtual size_t get_workspace_in_bytes(
  1187. const TensorNDArray& srcs, const TensorLayout& dst) = 0;
  1188. void deduce_layout(const TensorLayoutArray& srcs, TensorLayout& dst);
  1189. virtual void exec(
  1190. _megdnn_in const TensorNDArray& srcs, _megdnn_tensor_out dst,
  1191. _megdnn_workspace workspace) = 0;
  1192. protected:
  1193. void check_exec(
  1194. const TensorNDArray& srcs, const TensorND& dst, size_t workspace_in_bytes);
  1195. virtual size_t _get_workspace_in_bytes() = 0;
  1196. };
  1197. /*!
  1198. * \brief fill the tensor with a scalar value
  1199. */
  1200. class Fill : public OperatorBase {
  1201. DEF_OPR_PARAM(Fill);
  1202. DEF_OPR_IMPL(Fill, OperatorBase, 0, 1);
  1203. public:
  1204. virtual void exec(_megdnn_tensor_out dst, _megdnn_workspace workspace) = 0;
  1205. virtual size_t get_workspace_in_bytes(const TensorLayout& dst) = 0;
  1206. protected:
  1207. void check_exec(const TensorLayout& dst, size_t workspace_in_bytes);
  1208. };
  1209. /*!
  1210. * \brief standard padding operator
  1211. * Inputs must have the same dtype, and the output tensor shape must greater or equal
  1212. * than input tensor in every dimensions, the extra space will be fulled with m which
  1213. * default to be 0.
  1214. */
  1215. class PaddingBase : public OperatorBase {
  1216. DEF_OPR_PARAM(Padding);
  1217. DEF_OPR_IMPL(PaddingBase, OperatorBase, 1, 1);
  1218. public:
  1219. using Mode = Param::PaddingMode;
  1220. protected:
  1221. SmallVector<size_t> get_offsets();
  1222. void check_exec(const TensorLayout& src, const TensorLayout& dst);
  1223. };
  1224. class PaddingForward : public PaddingBase {
  1225. DEF_OPR_IMPL(PaddingForward, PaddingBase, 1, 1);
  1226. public:
  1227. virtual void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst) = 0;
  1228. void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_workspace) {
  1229. return exec(src, dst);
  1230. }
  1231. virtual size_t get_workspace_in_bytes(
  1232. const TensorLayout& src, const TensorLayout& dst) = 0;
  1233. void deduce_layout(const TensorLayout& src, TensorLayout& dst);
  1234. protected:
  1235. void forward_check_exec(const TensorLayout& src, const TensorLayout& dst);
  1236. };
  1237. using Padding = PaddingForward;
  1238. class PaddingBackward : public PaddingBase {
  1239. DEF_OPR_IMPL(PaddingBackward, PaddingBase, 1, 1);
  1240. public:
  1241. virtual void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst) = 0;
  1242. void exec(_megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_workspace) {
  1243. return exec(src, dst);
  1244. }
  1245. virtual size_t get_workspace_in_bytes(
  1246. const TensorLayout& src, const TensorLayout& dst) = 0;
  1247. protected:
  1248. void backward_check_exec(const TensorLayout& src, const TensorLayout& dst);
  1249. };
  1250. } // namespace megdnn
  1251. #include "megdnn/internal/opr_header_epilogue.h"
  1252. // vim: syntax=cpp.doxygen