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.

matmul.cpp 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. #include <numeric>
  2. #include "../blob_manager_impl.h"
  3. #include "../dnn_op_helper.h"
  4. #include "../op_trait.h"
  5. #include "megbrain/graph/symbol_var.h"
  6. #include "megbrain/imperative/ops/autogen.h"
  7. #include "megbrain/opr/basic_arith.h"
  8. #include "megbrain/opr/blas.h"
  9. #include "megbrain/opr/io.h"
  10. #include "megbrain/opr/tensor_manip.h"
  11. #include "../algo_chooser.h"
  12. namespace mgb {
  13. namespace imperative {
  14. namespace {
  15. namespace matrix_mul {
  16. auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
  17. auto&& matmul = def.cast_final_safe<MatrixMul>();
  18. mgb_assert(inputs.size() == 2);
  19. auto inp1 = SymbolVar{inputs[0]}, inp2 = SymbolVar{inputs[1]};
  20. auto dim1 = matmul.dimA, dim2 = matmul.dimB;
  21. auto cn = inputs[0]->comp_node();
  22. using Desc = opr::AxisAddRemove::AxisDesc;
  23. using IndexDesc = opr::Subtensor::IndexDesc;
  24. OperatorNodeConfig config{matmul.make_name(), cn};
  25. DTypeScalar vi{-1};
  26. auto graph = inputs[0]->owner_graph();
  27. SymbolVar shp1_head, shp1_tail, shp2_head, shp2_tail;
  28. if (dim1 > 2) {
  29. auto idx = opr::ImmutableTensor::make(*graph, vi, config);
  30. auto shp1 = inp1.symshape();
  31. IndexDesc head_desc(1);
  32. head_desc[0].end = idx;
  33. shp1_head = opr::Subtensor::make(shp1, head_desc);
  34. auto batch = opr::Reduce::make(shp1_head, {Reduce::Mode::PRODUCT, 0});
  35. IndexDesc tail_desc(1);
  36. tail_desc[0].begin = idx;
  37. shp1_tail = opr::Subtensor::make(shp1, tail_desc);
  38. auto tshp = opr::Concat::make({batch, shp1_tail}, 0, cn);
  39. inp1 = inp1.reshape(tshp);
  40. }
  41. if (dim2 > 2) {
  42. auto idx = opr::ImmutableTensor::make(*graph, vi, config);
  43. auto shp2 = inp2.symshape();
  44. IndexDesc head_desc(1);
  45. head_desc[0].end = idx;
  46. shp2_head = opr::Subtensor::make(shp2, head_desc);
  47. auto batch = opr::Reduce::make(shp2_head, {Reduce::Mode::PRODUCT, 0});
  48. IndexDesc tail_desc(1);
  49. tail_desc[0].begin = idx;
  50. auto shp2_tail = opr::Subtensor::make(shp2, tail_desc);
  51. auto tshp = opr::Concat::make({batch, shp2_tail}, 0, cn);
  52. inp2 = inp2.reshape(tshp);
  53. }
  54. auto result =
  55. opr::MatrixMul::make(inp1, inp2, matmul.param(), matmul.policy(), config);
  56. if (dim1 > 2) {
  57. auto idx = opr::ImmutableTensor::make(*graph, vi, config);
  58. auto result_shape = result.symshape();
  59. IndexDesc tail_desc(1);
  60. tail_desc[0].begin = idx;
  61. auto shp_tail = opr::Subtensor::make(result_shape, tail_desc);
  62. auto tshp = opr::Concat::make({shp1_head, shp_tail}, 0, cn);
  63. result = result.reshape(tshp);
  64. }
  65. if (dim2 > 2) {
  66. auto idx = opr::ImmutableTensor::make(*graph, vi, config);
  67. auto result_shape = result.symshape();
  68. IndexDesc tail_desc(1);
  69. tail_desc[0].begin = idx;
  70. auto shp_tail = opr::Subtensor::make(result_shape, tail_desc);
  71. auto tshp = opr::Concat::make({shp2_head, shp_tail}, 0, cn);
  72. result = result.reshape(tshp);
  73. }
  74. return result;
  75. }
  76. std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
  77. const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
  78. auto&& matmul = def.cast_final_safe<MatrixMul>();
  79. auto layout1 = inputs[0].layout;
  80. auto layout2 = inputs[1].layout;
  81. size_t dim1 = layout1.ndim, dim2 = layout2.ndim;
  82. DType dst_dtype;
  83. if (dim1 == dim2 && dim2 >= 3) { // only happens in backward
  84. for (size_t i = 1; i + 1 < layout1.ndim; ++i) {
  85. layout1[0] *= layout1[i];
  86. layout2[0] *= layout2[i];
  87. }
  88. layout1[1] = layout1[layout1.ndim - 1];
  89. layout1.ndim = 2;
  90. layout1.init_contiguous_stride();
  91. layout2[1] = layout2[layout2.ndim - 1];
  92. layout2.ndim = 2;
  93. layout2.init_contiguous_stride();
  94. dim1 = dim2 = 2;
  95. }
  96. DnnOprCaller<megdnn::MatrixMul> dnn_opr(inputs[0].comp_node);
  97. dnn_opr.op->param() = matmul.param();
  98. dnn_opr.op->deduce_dtype(layout1.dtype, layout1.dtype, dst_dtype);
  99. if (dim1 == 0 || dim2 == 0) {
  100. return {{{TensorLayout(dst_dtype), inputs[0].comp_node}}, false};
  101. }
  102. if (matmul.transposeA)
  103. std::swap(layout1[0], layout1[1]);
  104. if (matmul.transposeB)
  105. std::swap(layout2[0], layout2[1]);
  106. mgb_assert(layout1[dim1 - 1] == layout2[0]);
  107. TensorLayout dst_layout(dst_dtype);
  108. size_t ci = 0;
  109. for (size_t i = 0; i < dim1 - 1; i++)
  110. dst_layout[ci++] = layout1[i];
  111. if (dim2 == 2)
  112. dst_layout[ci++] = layout2[1];
  113. dst_layout.ndim = ci;
  114. dst_layout.init_contiguous_stride();
  115. SmallVector<LogicalTensorDesc> out_descs(1u);
  116. out_descs[0] = {dst_layout, inputs[0].comp_node};
  117. return {out_descs, true};
  118. }
  119. SmallVector<TensorPtr> apply_on_physical_tensor(
  120. const OpDef& def, const SmallVector<TensorPtr>& inputs,
  121. SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
  122. auto&& matmul = def.cast_final_safe<MatrixMul>();
  123. auto&& cn = inputs[0]->comp_node();
  124. using TensorND = megdnn::TensorND;
  125. SmallVector<TensorND> inp_tensornds(inputs.size());
  126. TensorLayout layout1 = inputs[0]->layout(), layout2 = inputs[1]->layout();
  127. DnnOprCaller<megdnn::MatrixMul> dnn_opr(cn);
  128. dnn_opr.op->param() = matmul.param();
  129. if (matmul.dimA == matmul.dimB && matmul.dimB >= 3) { // only happens in backward
  130. for (size_t i = 1; i + 1 < layout1.ndim; ++i) {
  131. layout1[0] *= layout1[i];
  132. layout2[0] *= layout2[i];
  133. }
  134. layout1[1] = layout1[layout1.ndim - 1];
  135. layout1.ndim = 2;
  136. layout1.init_contiguous_stride();
  137. layout2[1] = layout2[layout2.ndim - 1];
  138. layout2.ndim = 2;
  139. layout2.init_contiguous_stride();
  140. }
  141. DType dst_dtype;
  142. dnn_opr.op->deduce_dtype(layout1.dtype, layout1.dtype, dst_dtype);
  143. // only matters when layout1 has dim 2
  144. if (matmul.transposeA)
  145. std::swap(layout1.shape[0], layout1.shape[1]);
  146. // only matters when layout2 has dim 2
  147. if (matmul.transposeB)
  148. std::swap(layout2.shape[0], layout2.shape[1]);
  149. size_t dim1 = layout1.ndim, dim2 = layout2.ndim;
  150. TensorLayout real_dst_layout(dst_dtype);
  151. if (validated) {
  152. real_dst_layout = output_descs[0].layout;
  153. } else {
  154. size_t ri = 0;
  155. for (size_t i = 0; i < dim1 - 2; i++)
  156. real_dst_layout[ri++] = layout1[i];
  157. real_dst_layout[ri++] = layout1[dim1 - 2];
  158. if (dim2 == 2)
  159. real_dst_layout[ri++] = layout2[dim2 - 1];
  160. real_dst_layout.ndim = ri;
  161. real_dst_layout.init_contiguous_stride();
  162. }
  163. if (dim1 == 0 || dim2 == 0 || layout1[layout1.ndim - 1] == 0) {
  164. DeviceTensorND out =
  165. BlobManager::inst()->alloc_workspace_with_defrag(cn, real_dst_layout);
  166. if (!out.empty()) {
  167. dev_tensor_memset(out, 0);
  168. }
  169. return {Tensor::make(out)};
  170. }
  171. TensorLayout layout_a = layout1, layout_b = layout2;
  172. if (dim1 > 2) {
  173. size_t batch = std::accumulate(
  174. layout1.shape, layout1.shape + dim1 - 1, (size_t)1,
  175. std::multiplies<size_t>());
  176. TensorShape na = TensorShape{batch, layout1[dim1 - 1]};
  177. auto inp1 = inputs[0];
  178. if (!layout1.try_reshape(layout_a, na)) {
  179. inp1 = Tensor::make(inp1->blob(), inp1->offset(), layout1);
  180. inp1->to_contiguous_inplace();
  181. layout1 = inp1->layout();
  182. layout_a = TensorLayout{{batch, layout1[dim1 - 1]}, layout1.dtype};
  183. }
  184. layout_a.init_contiguous_stride();
  185. inp_tensornds[0] = inp1->dnn_tensor();
  186. inp_tensornds[0].layout = layout_a;
  187. } else {
  188. inp_tensornds[0] = inputs[0]->dnn_tensor();
  189. }
  190. inp_tensornds[1] = inputs[1]->dnn_tensor();
  191. TensorLayout dst_layout = TensorLayout({layout_a[0], layout_b[1]}, dst_dtype);
  192. dst_layout.init_contiguous_stride();
  193. if (matmul.transposeA)
  194. std::swap(layout_a.shape[0], layout_a.shape[1]);
  195. if (matmul.transposeB)
  196. std::swap(layout_b.shape[0], layout_b.shape[1]);
  197. if (matmul.dimA == matmul.dimB && matmul.dimB >= 3) { // only happens in backward
  198. inp_tensornds[0].layout = layout_a;
  199. inp_tensornds[1].layout = layout_b;
  200. }
  201. DeviceTensorND out =
  202. BlobManager::inst()->alloc_workspace_with_defrag(cn, dst_layout);
  203. size_t sz = setup_algo<megdnn::MatrixMul>(
  204. {layout_a, layout_b, dst_layout}, dnn_opr.op.get(), 0, false, false, cn,
  205. matmul.policy(), false);
  206. TensorLayout w_layout({sz}, dtype::Byte());
  207. auto dnn_wk = dnn_opr.create_workspace(w_layout);
  208. dnn_opr.op->exec(inp_tensornds[0], inp_tensornds[1], out.as_megdnn(), dnn_wk);
  209. return {Tensor::make(out.sub(SubTensorSpec::make_from_layout(real_dst_layout)))};
  210. }
  211. SmallVector<VarNode::LayoutConstraintCallback> get_input_layout_constraint(
  212. const OpDef& def, const SmallVector<TensorPtr>& inputs) {
  213. SmallVector<VarNode::LayoutConstraintCallback> layout_checker(inputs.size());
  214. layout_checker[0] = layout_checker[1] = [](const TensorLayout& layout) {
  215. return layout.is_contiguous();
  216. };
  217. return layout_checker;
  218. }
  219. OP_TRAIT_REG(MatrixMul, MatrixMul)
  220. .apply_on_var_node(apply_on_var_node)
  221. .infer_output_attrs_fallible(infer_output_attrs_fallible)
  222. .apply_on_physical_tensor(apply_on_physical_tensor)
  223. .get_input_layout_constraint(get_input_layout_constraint)
  224. .fallback();
  225. } // namespace matrix_mul
  226. } // namespace
  227. namespace {
  228. namespace batched_matrix_mul {
  229. auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
  230. auto&& matmul = def.cast_final_safe<BatchedMatrixMul>();
  231. mgb_assert(inputs.size() == 2);
  232. auto inp1 = SymbolVar{inputs[0]}, inp2 = SymbolVar{inputs[1]};
  233. auto dim1 = matmul.dimA, dim2 = matmul.dimB;
  234. auto cn = inputs[0]->comp_node();
  235. using Desc = opr::AxisAddRemove::AxisDesc;
  236. using IndexDesc = opr::Subtensor::IndexDesc;
  237. OperatorNodeConfig config{matmul.make_name(), cn};
  238. DTypeScalar vi{-2};
  239. auto graph = inputs[0]->owner_graph();
  240. auto idx = opr::ImmutableTensor::make(*graph, vi, config);
  241. auto shp1 = inp1.symshape();
  242. auto shp2 = inp2.symshape();
  243. SymbolVar shp1_head, shp1_tail, shp2_head, shp2_tail;
  244. SymbolVar batch_shape;
  245. if (dim1 > dim2) {
  246. HostTensorND hv = HostTensorND(cn, {1}, dtype::Int32());
  247. auto* ptr = hv.ptr<dt_int32>();
  248. ptr[0] = -dim2;
  249. IndexDesc head_desc(1);
  250. head_desc[0].end = opr::ImmutableTensor::make(*graph, hv, config);
  251. shp1_head = opr::Subtensor::make(shp1, head_desc);
  252. shp2 = opr::Concat::make({shp1_head, shp2}, 0, cn);
  253. inp2 = inp2.broadcast(shp2);
  254. head_desc[0].end = idx;
  255. batch_shape = opr::Subtensor::make(shp1, head_desc);
  256. }
  257. if (dim2 > dim1) {
  258. HostTensorND hv = HostTensorND(cn, {1}, dtype::Int32());
  259. auto* ptr = hv.ptr<dt_int32>();
  260. ptr[0] = -dim1;
  261. IndexDesc head_desc(1);
  262. head_desc[0].end = opr::ImmutableTensor::make(*graph, hv, config);
  263. shp2_head = opr::Subtensor::make(shp2, head_desc);
  264. shp1 = opr::Concat::make({shp2_head, shp1}, 0, cn);
  265. inp1 = inp1.broadcast(shp1);
  266. head_desc[0].end = idx;
  267. batch_shape = opr::Subtensor::make(shp2, head_desc);
  268. }
  269. if (dim1 == dim2) {
  270. IndexDesc head_desc(1);
  271. head_desc[0].end = idx;
  272. batch_shape = opr::Subtensor::make(shp1, head_desc);
  273. }
  274. auto maxdim = dim1 > dim2 ? dim1 : dim2;
  275. if (maxdim > 3) {
  276. IndexDesc tail_desc(1);
  277. tail_desc[0].begin = idx;
  278. shp1_tail = opr::Subtensor::make(shp1, tail_desc);
  279. auto batch = opr::Reduce::make(batch_shape, {Reduce::Mode::PRODUCT, 0});
  280. shp1 = opr::Concat::make({batch, shp1_tail}, 0, cn);
  281. inp1 = inp1.reshape(shp1);
  282. shp2_tail = opr::Subtensor::make(shp2, tail_desc);
  283. shp2 = opr::Concat::make({batch, shp2_tail}, 0, cn);
  284. inp2 = inp2.reshape(shp2);
  285. }
  286. auto result = opr::BatchedMatrixMul::make(
  287. inp1, inp2, matmul.param(), matmul.policy(), config);
  288. if (maxdim > 3) {
  289. auto result_shp = result.symshape();
  290. IndexDesc tail_desc(1);
  291. tail_desc[0].begin = idx;
  292. auto shp_tail = opr::Subtensor::make(result_shp, tail_desc);
  293. result_shp = opr::Concat::make({batch_shape, shp_tail}, 0, cn);
  294. result = result.reshape(result_shp);
  295. }
  296. return result;
  297. }
  298. std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
  299. const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
  300. auto&& matmul = def.cast_final_safe<BatchedMatrixMul>();
  301. TensorLayout layout1 = inputs[0].layout, layout2 = inputs[1].layout;
  302. size_t dim1 = layout1.ndim, dim2 = layout2.ndim;
  303. DType dst_dtype;
  304. DnnOprCaller<megdnn::MatrixMul> dnn_opr(inputs[0].comp_node);
  305. dnn_opr.op->param() = matmul.param();
  306. dnn_opr.op->deduce_dtype(layout1.dtype, layout1.dtype, dst_dtype);
  307. if (dim1 == 0 || dim2 == 0) {
  308. return {{{TensorLayout(dst_dtype), inputs[0].comp_node}}, false};
  309. }
  310. if (matmul.transposeA)
  311. std::swap(layout1[dim1 - 1], layout1[dim1 - 2]);
  312. if (matmul.transposeB)
  313. std::swap(layout2[dim2 - 1], layout2[dim2 - 2]);
  314. TensorLayout dst_layout(dst_dtype);
  315. size_t di = 0;
  316. if (dim1 > dim2) {
  317. for (size_t i = 0; i < dim1 - 2; i++)
  318. dst_layout[di++] = layout1[i];
  319. } else {
  320. for (size_t i = 0; i < dim2 - 2; i++)
  321. dst_layout[di++] = layout2[i];
  322. }
  323. if (dim1 > 1)
  324. dst_layout[di++] = layout1[dim1 - 2];
  325. if (dim2 > 1)
  326. dst_layout[di++] = layout2[dim2 - 1];
  327. dst_layout.ndim = di;
  328. dst_layout.init_contiguous_stride();
  329. SmallVector<LogicalTensorDesc> out_descs(1u);
  330. out_descs[0] = {dst_layout, inputs[0].comp_node};
  331. return {out_descs, true};
  332. }
  333. SmallVector<TensorPtr> apply_on_physical_tensor(
  334. const OpDef& def, const SmallVector<TensorPtr>& inputs,
  335. SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
  336. auto&& matmul = def.cast_final_safe<BatchedMatrixMul>();
  337. auto&& cn = inputs[0]->comp_node();
  338. TensorLayout layout1 = inputs[0]->layout(), layout2 = inputs[1]->layout();
  339. size_t dim1 = layout1.ndim, dim2 = layout2.ndim;
  340. DnnOprCaller<megdnn::BatchedMatrixMul> dnn_opr(cn);
  341. dnn_opr.op->param() = matmul.param();
  342. DType dst_dtype;
  343. dnn_opr.op->deduce_dtype(layout1.dtype, layout1.dtype, dst_dtype);
  344. TensorShape tshp, batch_shp;
  345. size_t j = 0;
  346. auto inp1 = inputs[0], inp2 = inputs[1];
  347. if (dim1 > dim2) {
  348. for (size_t i = 0; i < dim1 - 2; i++)
  349. tshp[j++] = layout1.shape[i];
  350. batch_shp = tshp;
  351. batch_shp.ndim = dim1 - 2;
  352. tshp[j++] = layout2[layout2.ndim - 2];
  353. tshp[j++] = layout2[layout2.ndim - 1];
  354. tshp.ndim = j;
  355. layout2 = layout2.broadcast(tshp);
  356. }
  357. if (dim2 > dim1) {
  358. for (size_t i = 0; i < dim2 - 2; i++)
  359. tshp[j++] = layout2.shape[i];
  360. batch_shp = tshp;
  361. batch_shp.ndim = dim2 - 2;
  362. tshp[j++] = layout1[layout1.ndim - 2];
  363. tshp[j++] = layout1[layout1.ndim - 1];
  364. tshp.ndim = j;
  365. layout1 = layout1.broadcast(tshp);
  366. }
  367. if (dim1 == dim2) {
  368. for (size_t i = 0; i < dim1 - 2; i++)
  369. tshp[j++] = layout1.shape[i];
  370. batch_shp = tshp;
  371. batch_shp.ndim = dim1 - 2;
  372. }
  373. TensorShape shp1 = batch_shp, shp2 = batch_shp;
  374. shp1.ndim += 2;
  375. shp2.ndim += 2;
  376. size_t maxdim = dim1 > dim2 ? dim1 : dim2;
  377. size_t nbatch = batch_shp[0];
  378. if (maxdim > 3) {
  379. nbatch = std::accumulate(
  380. batch_shp.shape, batch_shp.shape + batch_shp.ndim, (size_t)1,
  381. std::multiplies<size_t>());
  382. TensorLayout layout_a;
  383. // batched_matmul does not support memory forwarding, so ensure contiguous
  384. // manually
  385. TensorShape nl1 = TensorShape(
  386. {nbatch, layout1[layout1.ndim - 2], layout1[layout1.ndim - 1]});
  387. inp1 = Tensor::make(inputs[0]->blob(), inputs[0]->offset(), layout1);
  388. inp1->to_contiguous_inplace();
  389. layout1 = inp1->layout();
  390. layout_a = layout1.reshape(nl1);
  391. layout1 = layout_a;
  392. TensorShape nl2 = TensorShape(
  393. {nbatch, layout2[layout2.ndim - 2], layout2[layout2.ndim - 1]});
  394. inp2 = Tensor::make(inputs[1]->blob(), inputs[1]->offset(), layout2);
  395. inp2->to_contiguous_inplace();
  396. layout2 = inp2->layout();
  397. layout_a = layout2.reshape(nl2);
  398. layout2 = layout_a;
  399. }
  400. TensorLayout dst_layout(
  401. {nbatch, matmul.transposeA ? layout1[2] : layout1[1],
  402. matmul.transposeB ? layout2[1] : layout2[2]},
  403. dst_dtype);
  404. dst_layout.init_contiguous_stride();
  405. if (dim1 == 0 || dim2 == 0 || layout1[layout1.ndim - 1] == 0) {
  406. DeviceTensorND out =
  407. BlobManager::inst()->alloc_workspace_with_defrag(cn, dst_layout);
  408. if (!out.empty()) {
  409. dev_tensor_memset(out, 0);
  410. }
  411. return {Tensor::make(out)};
  412. }
  413. using TensorND = megdnn::TensorND;
  414. TensorND inp_nd1 = inp1->dnn_tensor();
  415. inp_nd1.layout = layout1;
  416. TensorND inp_nd2 = inp2->dnn_tensor();
  417. inp_nd2.layout = layout2;
  418. DeviceTensorND out =
  419. BlobManager::inst()->alloc_workspace_with_defrag(cn, dst_layout);
  420. size_t sz = setup_algo<megdnn::BatchedMatrixMul>(
  421. {layout1, layout2, dst_layout}, dnn_opr.op.get(), 0, false, false, cn,
  422. matmul.policy(), false);
  423. TensorLayout w_layout({sz}, dtype::Byte());
  424. auto dnn_wk = dnn_opr.create_workspace(w_layout);
  425. dnn_opr.op->exec(inp_nd1, inp_nd2, out.as_megdnn(), dnn_wk);
  426. shp1[shp1.ndim - 2] = dst_layout[dst_layout.ndim - 2];
  427. shp1[shp1.ndim - 1] = dst_layout[dst_layout.ndim - 1];
  428. if (maxdim > 3) {
  429. dst_layout = dst_layout.reshape(shp1);
  430. }
  431. return {Tensor::make(out.sub(SubTensorSpec::make_from_layout(dst_layout)))};
  432. }
  433. SmallVector<VarNode::LayoutConstraintCallback> get_input_layout_constraint(
  434. const OpDef& def, const SmallVector<TensorPtr>& inputs) {
  435. SmallVector<VarNode::LayoutConstraintCallback> layout_checker(inputs.size());
  436. layout_checker[0] = layout_checker[1] = [](const TensorLayout& layout) {
  437. return layout.is_contiguous();
  438. };
  439. return layout_checker;
  440. }
  441. OP_TRAIT_REG(BatchedMatrixMul, BatchedMatrixMul)
  442. .apply_on_var_node(apply_on_var_node)
  443. .infer_output_attrs_fallible(infer_output_attrs_fallible)
  444. .get_input_layout_constraint(get_input_layout_constraint)
  445. .apply_on_physical_tensor(apply_on_physical_tensor)
  446. .fallback();
  447. } // namespace batched_matrix_mul
  448. } // namespace
  449. namespace {
  450. namespace dot {
  451. auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
  452. auto&& op = def.cast_final_safe<Dot>();
  453. mgb_assert(inputs.size() == 2);
  454. OperatorNodeConfig config{op.make_name()};
  455. return opr::Dot::make(inputs[0], inputs[1], config);
  456. }
  457. SmallVector<TensorPtr> apply_on_physical_tensor(
  458. const OpDef& def, const SmallVector<TensorPtr>& inputs,
  459. SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
  460. auto comp_node = inputs[0]->comp_node();
  461. using TensorND = megdnn::TensorND;
  462. SmallVector<TensorND> inp_tensornds;
  463. inp_tensornds.reserve(inputs.size());
  464. DnnOprCaller<megdnn::Dot> dnn_opr(comp_node);
  465. for (unsigned i = 0; i < inputs.size(); ++i) {
  466. auto dnn_ten = inputs[i]->dnn_tensor();
  467. inp_tensornds.push_back(dnn_ten);
  468. }
  469. TensorLayout oup_layout{inputs[0]->dtype()};
  470. auto inp1_tensor = inputs[0]->dnn_tensor();
  471. auto inp2_tensor = inputs[1]->dnn_tensor();
  472. dnn_opr.op->deduce_layout(inp1_tensor.layout, inp2_tensor.layout, oup_layout);
  473. if (inputs[0]->layout().is_empty() || inputs[1]->layout().is_empty()) {
  474. DeviceTensorND out =
  475. BlobManager::inst()->alloc_workspace_with_defrag(comp_node, oup_layout);
  476. if (!out.empty()) {
  477. dev_tensor_memset(out, 0);
  478. }
  479. return {Tensor::make(out)};
  480. }
  481. auto sz = dnn_opr.op->get_workspace_in_bytes(
  482. inp_tensornds[0].layout, inp_tensornds[1].layout, output_descs[0].layout);
  483. DeviceTensorND out_devtensor =
  484. BlobManager::inst()->alloc_workspace_with_defrag(comp_node, oup_layout);
  485. TensorLayout w_layout({sz}, dtype::Byte());
  486. auto dnn_wk = dnn_opr.create_workspace(w_layout);
  487. dnn_opr.op->exec(
  488. inp_tensornds[0], inp_tensornds[1], out_devtensor.as_megdnn(), dnn_wk);
  489. return {Tensor::make(out_devtensor)};
  490. }
  491. std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
  492. const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
  493. mgb_assert(
  494. inputs.size() == 2, "Dot expects 2 inputs; got %lu actually",
  495. inputs.size());
  496. SmallVector<LogicalTensorDesc> dests(1);
  497. dests[0].layout = TensorLayout(TensorShape{1}, inputs[0].layout.dtype);
  498. dests[0].comp_node = inputs[0].comp_node;
  499. bool validated = inputs[0].layout.ndim != 0 && inputs[1].layout.ndim != 0;
  500. return {dests, validated};
  501. }
  502. OP_TRAIT_REG(Dot, Dot, mgb::opr::Dot)
  503. .apply_on_var_node(apply_on_var_node)
  504. .infer_output_attrs_fallible(infer_output_attrs_fallible)
  505. .apply_on_physical_tensor(apply_on_physical_tensor)
  506. .fallback();
  507. } // namespace dot
  508. } // anonymous namespace
  509. } // namespace imperative
  510. } // namespace mgb