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.

basic_arith.cpp 63 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. /**
  2. * \file src/opr/impl/basic_arith.cpp
  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. #include "megbrain/opr/basic_arith.h"
  12. #include "megbrain/opr/basic_arith_wrapper.h"
  13. #include "megbrain/opr/utility.h"
  14. #include "megbrain/opr/io.h"
  15. #include "megbrain/opr/cond.h"
  16. #include "megbrain/opr/tensor_manip.h"
  17. #include "megbrain/gopt/basic_arith.h"
  18. #include "megbrain/gopt/gtrans.h"
  19. #include "megbrain/utils/arith_helper.h"
  20. #include "megbrain/graph/grad_impl.h"
  21. #include "./internal/megdnn_opr_wrapper.inl"
  22. #include <cmath>
  23. using namespace mgb;
  24. using namespace opr;
  25. namespace {
  26. //! global operator instance for static inference
  27. template<class Opr>
  28. class StaticInferOpr {
  29. intl::UniqPtrWithCN<Opr> m_opr;
  30. std::mutex m_mtx;
  31. public:
  32. class Lock {
  33. friend class StaticInferOpr;
  34. StaticInferOpr *m_owner;
  35. explicit Lock(StaticInferOpr *owner):
  36. m_owner{owner}
  37. {
  38. m_owner->m_mtx.lock();
  39. }
  40. public:
  41. Lock(Lock &&rhs):
  42. m_owner{rhs.m_owner}
  43. {
  44. rhs.m_owner = nullptr;
  45. }
  46. ~Lock() {
  47. if (m_owner)
  48. m_owner->m_mtx.unlock();
  49. }
  50. Lock& operator = (const Lock &) = delete;
  51. Lock& operator = (Lock&&) = delete;
  52. intl::UniqPtrWithCN<Opr>& operator() () {
  53. return m_owner->m_opr;
  54. }
  55. };
  56. //! lock and acquire the operator
  57. Lock lock() {
  58. Lock ret{this};
  59. if (!m_opr) {
  60. m_opr = intl::create_megdnn_opr<Opr>(
  61. CompNode::default_cpu());
  62. }
  63. return ret;
  64. }
  65. };
  66. } // anonymous namespace
  67. /* ========================= BatchedDTypePromotion ========================= */
  68. intl::BatchedDTypePromotion::BatchedDTypePromotion(const VarNodeArrayView& vars)
  69. : m_orig_vars{vars} {
  70. mgb_assert(!vars.empty());
  71. DType final_dtype;
  72. bool changed = false;
  73. for (size_t i = 0; i < vars.size(); ++i) {
  74. auto cur = vars[i]->dtype();
  75. if (!i) {
  76. final_dtype = cur;
  77. } else {
  78. auto promoted = dtype_promotion(final_dtype, cur);
  79. changed |= promoted != final_dtype || promoted != cur;
  80. final_dtype = promoted;
  81. }
  82. }
  83. m_changed = changed;
  84. m_final_dtype = final_dtype;
  85. }
  86. void intl::BatchedDTypePromotion::set_dtype(DType dtype) {
  87. mgb_assert(!m_finalized);
  88. if (m_final_dtype != dtype) {
  89. m_final_dtype = dtype;
  90. m_changed = true;
  91. }
  92. }
  93. const VarNodeArrayView& intl::BatchedDTypePromotion::get_vars() {
  94. m_finalized = true;
  95. if (!m_changed) {
  96. return m_orig_vars;
  97. }
  98. if (!m_cvt_vars_view.valid()) {
  99. m_cvt_vars.resize(m_orig_vars.size());
  100. auto dtype = m_final_dtype;
  101. for (size_t i = 0; i < m_cvt_vars.size(); ++i) {
  102. m_cvt_vars[i] = TypeCvt::make(m_orig_vars[i], dtype).node();
  103. }
  104. m_cvt_vars_view.emplace(m_cvt_vars);
  105. }
  106. return m_cvt_vars_view.val();
  107. }
  108. /* =========================== Elemwise =========================== */
  109. MGB_DYN_TYPE_OBJ_FINAL_IMPL(Elemwise);
  110. Elemwise::Elemwise(
  111. const ModeTrait &mode_trait,
  112. const VarNodeArrayView &inputs, Param param,
  113. const OperatorNodeConfig &config):
  114. Super{inputs.at(0)->owner_graph(), config, mode_trait.name, inputs}
  115. {
  116. init_megdnn_opr(*this, param);
  117. output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
  118. if (mode_trait.commutable) {
  119. mgb_assert(inputs.size() == 2);
  120. add_input({inputs[0], inputs[1]}, AddInputSortType::CUR_ADDED);
  121. } else {
  122. if (param.mode == Mode::FUSE_MUL_ADD3) {
  123. add_input({inputs[0], inputs[1]}, AddInputSortType::CUR_ADDED);
  124. add_input({inputs[2]});
  125. } else if (param.mode == Mode::FUSE_MUL_ADD4) {
  126. auto i0 = inputs[0], i1 = inputs[1], i2 = inputs[2], i3 = inputs[3];
  127. if (i0->id() > i1->id())
  128. std::swap(i0, i1);
  129. if (i2->id() > i3->id())
  130. std::swap(i2, i3);
  131. if (i0->id() > i2->id()) {
  132. std::swap(i0, i2);
  133. std::swap(i1, i3);
  134. }
  135. add_input({i0, i1, i2, i3});
  136. } else {
  137. for (auto i: inputs)
  138. add_input({i});
  139. }
  140. }
  141. mgb_assert(m_input_broadcastable.size() >= inputs.size());
  142. for (size_t i = 0; i < inputs.size(); ++ i) {
  143. if (input()[i]->owner_opr()->same_type<
  144. opr::MarkNoBroadcastElemwise>()) {
  145. m_input_broadcastable[i] = false;
  146. } else {
  147. m_input_broadcastable[i] = true;
  148. }
  149. }
  150. if (inputs.size() == 1) {
  151. m_input_broadcastable[0] = false;
  152. } else {
  153. Maybe<size_t> non_scalar;
  154. using namespace cg::static_infer;
  155. auto &&mgr = owner_graph()->static_infer_manager();
  156. for (size_t i = 0; i < input().size(); ++ i) {
  157. auto it = mgr.get_infer_type(input(i));
  158. if (!((it.shape & InferType::CONST) &&
  159. mgr.infer_shape(input(i)).is_scalar())) {
  160. if (non_scalar.valid()) {
  161. non_scalar.invalidate();
  162. break;
  163. }
  164. non_scalar = i;
  165. }
  166. }
  167. if (non_scalar.valid()) {
  168. // exactly one input is non-scalar
  169. m_input_broadcastable[non_scalar.val()] = false;
  170. }
  171. }
  172. if (inputs.size() &&
  173. inputs[0]->dtype().category() == DTypeCategory::QUANTIZED) {
  174. mgb_assert(param.mode == Param::Mode::ADD ||
  175. param.mode == Param::Mode::SUB ||
  176. param.mode == Param::Mode::NEGATE ||
  177. param.mode == Param::Mode::RELU ||
  178. param.mode == Param::Mode::MAX ||
  179. param.mode == Param::Mode::MIN,
  180. "Only ADD, SUB, NEGATE, RELU, MAX and MIN is guaranteed "
  181. "to be supported on Elemwise for quantized DType, no support %d", (int)param.mode);
  182. }
  183. }
  184. SymbolVar Elemwise::make(const VarNodeArrayView& inputs, Param param,
  185. const OperatorNodeConfig& config) {
  186. auto trait = ModeTrait::from_mode(param.mode);
  187. mgb_assert(inputs.size() == trait.arity,
  188. "%s expects %u inputs; got %zu actually", trait.name,
  189. trait.arity, inputs.size());
  190. intl::BatchedDTypePromotion dtp{inputs};
  191. if (dtp.get_dtype().category() == DTypeCategory::INT && !trait.allow_int) {
  192. dtp.set_dtype(dtype::Float32());
  193. }
  194. mgb_throw_if(dtp.get_dtype().category() == DTypeCategory::FLOAT &&
  195. !trait.allow_float,
  196. ConversionError,
  197. "elemwise mode %s does not allow float input; "
  198. "got inputs: %s",
  199. trait.name, cg::dump_var_info(inputs).c_str());
  200. #if !MGB_BUILD_SLIM_SERVING
  201. auto&& options = inputs[0]->owner_graph()->options();
  202. if (options.graph_opt_level && !(options.disable_inplace_arith_opt)) {
  203. auto repl = gopt::optimize_elemwise_expr_inplace(dtp.get_vars(), param,
  204. config);
  205. if (repl)
  206. return repl;
  207. }
  208. #endif
  209. return SymbolVar{inputs[0]}.insert_single_output_opr<Elemwise>(
  210. trait, dtp.get_vars(), param, config);
  211. }
  212. TensorShape Elemwise::get_output_var_shape(
  213. Mode mode, const TensorShapeArray &input_shapes) {
  214. mgb_assert(input_shapes.size() == ModeTrait::from_mode(mode).arity);
  215. TensorShape ret;
  216. megdnn::Elemwise::deduce_shape(input_shapes, ret);
  217. return ret;
  218. }
  219. void Elemwise::perform(
  220. Mode mode, DeviceTensorND &dest,
  221. const SmallVector<DeviceTensorND> &inputs,
  222. intl::UniqPtrWithCN<megdnn::Elemwise> &opr) {
  223. megdnn::TensorNDArray dnn_inputs(inputs.size());
  224. TensorShapeArray inp_shapes(inputs.size());
  225. DType out_dt;
  226. CompNode out_cn;
  227. for (size_t i = 0; i < inputs.size(); ++ i) {
  228. auto &&t = inputs[i];
  229. if (!i) {
  230. out_cn = t.comp_node();
  231. out_dt = t.dtype();
  232. } else {
  233. mgb_assert(t.comp_node() == out_cn);
  234. mgb_assert(t.dtype() == out_dt);
  235. }
  236. inp_shapes[i] = t.shape();
  237. }
  238. if (!opr) {
  239. opr = intl::create_megdnn_opr<megdnn::Elemwise>(out_cn);
  240. } else {
  241. mgb_assert(out_cn == opr.comp_node());
  242. }
  243. out_cn.activate();
  244. for (size_t i = 0; i < inputs.size(); ++ i)
  245. dnn_inputs[i] = inputs[i].as_megdnn();
  246. dest.comp_node(out_cn).dtype(out_dt).resize(
  247. get_output_var_shape(mode, inp_shapes));
  248. opr->param() = {mode};
  249. call_megdnn_opr_exec(out_cn, dnn_inputs, dest.as_megdnn(), opr.get(),
  250. nullptr);
  251. }
  252. TensorLayoutArray Elemwise::collective_collapse(
  253. const TensorLayoutArray& layouts) {
  254. TensorLayoutPtrArray inp(layouts.size());
  255. TensorLayoutArray result(inp.size());
  256. for (size_t i = 0; i < layouts.size(); ++ i) {
  257. result[i] = layouts[i];
  258. inp[i] = &result[i];
  259. }
  260. collective_collapse_inplace(inp);
  261. return result;
  262. }
  263. void Elemwise::collective_collapse_inplace(
  264. const TensorLayoutPtrArray& layouts) {
  265. mgb_assert(layouts.size());
  266. size_t ndim = layouts[0]->ndim;
  267. for (auto i: layouts) {
  268. if (i->ndim != ndim)
  269. mgb_throw(MegBrainError, "ndims must be same");
  270. }
  271. auto update_all = [&layouts](size_t axis) {
  272. for (auto i: layouts) {
  273. i->shape[axis] *= i->shape[axis + 1];
  274. i->stride[axis] = i->stride[axis + 1];
  275. i->remove_axis_inplace(axis + 1);
  276. }
  277. };
  278. auto check = [&layouts](size_t axis) -> bool {
  279. auto std_p = std::make_pair(
  280. layouts[0]->shape[axis], layouts[0]->shape[axis + 1]);
  281. for (auto i: layouts) {
  282. auto cur_p = std::make_pair(i->shape[axis], i->shape[axis + 1]);
  283. if (std_p != cur_p) return false;
  284. if (i->stride[axis] != i->stride[axis + 1] *
  285. static_cast<ptrdiff_t>(i->shape[axis+1]) )
  286. return false;
  287. }
  288. return true;
  289. };
  290. for (int i = static_cast<int>(ndim) - 2; i >= 0; i--) {
  291. if (check(i)) {
  292. update_all(i);
  293. }
  294. }
  295. }
  296. void Elemwise::broadcast_collective_collapse(
  297. const TensorLayoutPtrArray &inp_layouts, TensorLayout *target_layout) {
  298. for (auto &&p: inp_layouts) {
  299. *p = p->broadcast(*target_layout);
  300. }
  301. TensorLayoutPtrArray buf(inp_layouts.size() + 1);
  302. buf[0] = target_layout;
  303. for (size_t i = 0; i < inp_layouts.size(); i++) {
  304. buf[i+1] = inp_layouts[i];
  305. }
  306. collective_collapse_inplace(buf);
  307. }
  308. void Elemwise::mem_plan_fwd_in2out_writable() {
  309. mixin_mem_plan_fwd_in2out_writable(*this);
  310. }
  311. void Elemwise::scn_do_execute() {
  312. auto&& inp = input();
  313. megdnn::TensorNDArray dnn_inp;
  314. mgb_assert(dnn_inp.capacity() >= inp.size(),
  315. "heap allocation in elemwise exec");
  316. dnn_inp.resize(inp.size());
  317. for (size_t i = 0; i < inp.size(); ++i) {
  318. if (inp[i]->dev_tensor().empty()) {
  319. mgb_assert(output(0)->dev_tensor().empty());
  320. return;
  321. }
  322. dnn_inp[i] = (inp[i]->dev_tensor().as_megdnn());
  323. }
  324. mgb_assert(!output(0)->dev_tensor().empty());
  325. megdnn_opr()->param() = param();
  326. call_megdnn_opr_exec(comp_node(), dnn_inp,
  327. output(0)->dev_tensor().as_megdnn(), megdnn_opr(),
  328. this);
  329. }
  330. void Elemwise::init_output_static_infer_desc() {
  331. Super::init_output_static_infer_desc();
  332. static StaticInferOpr<megdnn::Elemwise> static_infer_opr;
  333. using namespace cg::static_infer;
  334. auto infer_value = [this](DeviceTensorND &dest, const InpVal &inp) {
  335. SmallVector<DeviceTensorND> inp_vals(inp.val.size());
  336. for (size_t i = 0; i < inp_vals.size(); ++ i)
  337. inp_vals[i] = inp.val[i].value();
  338. auto sopr = static_infer_opr.lock();
  339. perform(param().mode, dest, inp_vals, sopr());
  340. return true;
  341. };
  342. DepVal deps(input().size());
  343. for (size_t i = 0; i < input().size(); ++ i)
  344. deps[i] = {input(i), DepType::VALUE};
  345. owner_graph()->static_infer_manager().register_value_infer(
  346. output(0), {SourceType::DEP, deps, infer_value});
  347. }
  348. void Elemwise::get_output_var_shape(
  349. const TensorShapeArray &inp_shape, TensorShapeArray &out_shape) const {
  350. out_shape.at(0) = get_output_var_shape(param().mode, inp_shape);
  351. for (size_t i = 0; i < input().size(); ++ i) {
  352. mgb_throw_if(!m_input_broadcastable[i] &&
  353. !out_shape[0].eq_shape(inp_shape[i]), GraphError,
  354. "input %zu declared to be non-broadcastable but broacast "
  355. "actually happened", i);
  356. }
  357. }
  358. void Elemwise::add_input_layout_constraint() {
  359. for (auto i: input()) {
  360. i->add_layout_constraint_monotone();
  361. }
  362. }
  363. void Elemwise::call_megdnn_opr_exec(
  364. CompNode comp_node,
  365. megdnn::TensorNDArray &inp, const megdnn::TensorND &out,
  366. megdnn::Elemwise *opr, Elemwise *caller) {
  367. if (opr->param().mode == Mode::FUSE_MUL_ADD3 &&
  368. !(inp[2].layout.eq_layout(inp[0].layout) ||
  369. inp[2].layout.eq_layout(inp[1].layout) ||
  370. inp[2].layout.is_scalar())) {
  371. if (caller && !caller->fuse_badlayout_warn_printed()) {
  372. mgb_log_debug("%s: FUSE_MUL_ADD3 input layouts mismatch: %s %s %s; "
  373. "fallback to normal computing",
  374. caller->cname(),
  375. inp[0].layout.to_string().c_str(),
  376. inp[1].layout.to_string().c_str(),
  377. inp[2].layout.to_string().c_str()
  378. );
  379. caller->m_fuse_badlayout_warn_printed = true;
  380. }
  381. for (auto &&i: inp) {
  382. i.layout = i.layout.broadcast(out.layout);
  383. }
  384. megdnn::TensorNDArray run_inp(2);
  385. auto run = [&](Mode mode,
  386. const megdnn::TensorND &i0, const megdnn::TensorND &i1,
  387. const megdnn::TensorND &out) {
  388. run_inp[0] = i0;
  389. run_inp[1] = i1;
  390. opr->param() = {mode};
  391. opr->exec(run_inp, out);
  392. };
  393. auto tmp =
  394. intl::get_temp_tensor(caller ? caller->owner_graph() : nullptr,
  395. comp_node, out.layout);
  396. auto tmpv = tmp.as_megdnn();
  397. MGB_TRY {
  398. run(Mode::MUL, inp[0], inp[1], tmpv);
  399. run(Mode::ADD, inp[2], tmpv, out);
  400. } MGB_FINALLY(opr->param() = {Mode::FUSE_MUL_ADD3});
  401. return;
  402. }
  403. if (opr->param().mode == Mode::FUSE_MUL_ADD4 &&
  404. !(inp[0].layout.eq_layout(inp[2].layout) &&
  405. inp[1].layout.eq_layout(inp[3].layout)) &&
  406. !(inp[0].layout.eq_layout(inp[3].layout) &&
  407. inp[1].layout.eq_layout(inp[2].layout))) {
  408. if (caller && !caller->fuse_badlayout_warn_printed()) {
  409. mgb_log_debug(
  410. "%s: FUSE_MUL_ADD4 input layouts mismatch: %s %s %s %s; "
  411. "fallback to normal computing",
  412. caller->cname(),
  413. inp[0].layout.to_string().c_str(),
  414. inp[1].layout.to_string().c_str(),
  415. inp[2].layout.to_string().c_str(),
  416. inp[3].layout.to_string().c_str()
  417. );
  418. caller->m_fuse_badlayout_warn_printed = true;
  419. }
  420. for (auto &&i: inp) {
  421. i.layout = i.layout.broadcast(out.layout);
  422. }
  423. megdnn::TensorNDArray run_inp(2);
  424. auto run = [&](Mode mode,
  425. const megdnn::TensorND &i0, const megdnn::TensorND &i1,
  426. const megdnn::TensorND &out) {
  427. run_inp[0] = i0;
  428. run_inp[1] = i1;
  429. opr->param() = {mode};
  430. opr->exec(run_inp, out);
  431. };
  432. auto tmp =
  433. intl::get_temp_tensor(caller ? caller->owner_graph() : nullptr,
  434. comp_node, out.layout);
  435. auto tmpv = tmp.as_megdnn();
  436. MGB_TRY {
  437. run(Mode::MUL, inp[0], inp[1], tmpv);
  438. run(Mode::MUL, inp[2], inp[3], out);
  439. run(Mode::ADD, out, tmpv, out);
  440. } MGB_FINALLY(opr->param() = {Mode::FUSE_MUL_ADD4});
  441. return;
  442. }
  443. // All Elemwise operations on QuantizedS32/QuantizedS8 are not related to
  444. // scale. MegDNN does not support computing Elemwise for
  445. // QuantizedS32/QuantizedS8, we translate the data type to Int32/Int8 before
  446. // passing to MegDNN.
  447. if (inp.size() &&
  448. inp[0].layout.dtype.category() == DTypeCategory::QUANTIZED) {
  449. auto inp_dtype = inp[0].layout.dtype;
  450. DType compute_dtype;
  451. if (inp_dtype.enumv() == DTypeEnum::QuantizedS32) {
  452. compute_dtype = dtype::Int32();
  453. } else if (inp_dtype.enumv() == DTypeEnum::QuantizedS8) {
  454. compute_dtype = dtype::Int8();
  455. } else {
  456. mgb_throw(MegBrainError,
  457. "Unsupported Quantized Elemwise Mode %s: %d on %s",
  458. inp[0].layout.dtype.name(), int(opr->param().mode),
  459. comp_node.to_string().c_str());
  460. }
  461. megdnn::TensorNDArray run_inp(inp);
  462. for (size_t i = 0; i < inp.size(); i++) {
  463. run_inp[i].layout.dtype = compute_dtype;
  464. }
  465. megdnn::TensorND run_out = out;
  466. run_out.layout.dtype = compute_dtype;
  467. opr->exec(run_inp, run_out);
  468. return;
  469. }
  470. opr->exec(inp, out);
  471. }
  472. #if MGB_ENABLE_GRAD
  473. MGB_IMPL_OPR_GRAD(Elemwise) {
  474. SymbolVar i[5];
  475. SymbolVar i0(opr.input(0)), i1, i2, out(opr.output(0)),
  476. og{out_grad.at(0)}, result;
  477. for (size_t t = 0; t < opr.input().size(); ++ t)
  478. i[t] = opr.input()[t];
  479. if (opr.input().size() >= 2)
  480. i1 = opr.input(1);
  481. if (opr.input().size() >= 3)
  482. i2 = opr.input(2);
  483. // negate after reduce, for better performance
  484. bool negate_result = false;
  485. #define RET(_v) result = (_v); break
  486. #define EL1(_mode, _a) Elemwise::make({_a}, Mode::_mode)
  487. #define EL2(_mode, _a, _b) Elemwise::make({_a, _b}, Mode::_mode)
  488. #define EL3(_mode, _a, _b, _c) Elemwise::make({_a, _b, _c}, Mode::_mode)
  489. #define RET_INVALID() return InvalidGrad::make(opr, wrt_idx)
  490. using Mode = Elemwise::Mode;
  491. switch (opr.param().mode) {
  492. // unary
  493. case Mode::RELU:
  494. case Mode::FUSE_ADD_RELU:
  495. RET(EL2(SWITCH_GT0, out, og));
  496. case Mode::ABS:
  497. RET(EL2(ABS_GRAD, i0, og));
  498. case Mode::ACOS:
  499. negate_result = true;
  500. RET(og / EL1(SIN, out));
  501. case Mode::ASIN:
  502. RET(og / EL1(COS, out));
  503. case Mode::ATAN2:
  504. if (wrt_idx) {
  505. negate_result = true;
  506. }
  507. RET(og * i[!wrt_idx] / (i0 * i0 + i1 * i1));
  508. case Mode::CEIL:
  509. return nullptr;
  510. case Mode::COS:
  511. negate_result = true;
  512. RET(EL1(SIN, i0) * og);
  513. case Mode::EXP:
  514. RET(og * out);
  515. case Mode::EXPM1:
  516. RET(og * EL1(EXP, i0));
  517. case Mode::FLOOR:
  518. return nullptr;
  519. case Mode::LOG:
  520. RET(og / i0);
  521. case Mode::LOG1P:
  522. RET(og / (i0 + 1));
  523. case Mode::NEGATE:
  524. negate_result = true;
  525. RET(og);
  526. case Mode::SIGMOID:
  527. case Mode::FUSE_ADD_SIGMOID:
  528. RET(EL2(SIGMOID_GRAD, out, og));
  529. case Mode::SIN:
  530. RET(EL1(COS, i0) * og);
  531. case Mode::TANH:
  532. case Mode::FUSE_ADD_TANH:
  533. RET(EL2(TANH_GRAD, out, og));
  534. case Mode::FAST_TANH:
  535. RET(EL2(FAST_TANH_GRAD, i0, og));
  536. case Mode::ROUND:
  537. return nullptr;
  538. case Mode::ERF:
  539. RET(EL1(EXP, - i0 * i0) * 2 / static_cast<float>(sqrt(M_PI)) * og);
  540. case Mode::ERFINV:
  541. RET(EL1(EXP, out * out) * static_cast<float>(sqrt(M_PI)) / 2 * og);
  542. case Mode::ERFC:
  543. RET(-EL1(EXP, -i0 * i0) * 2 / static_cast<float>(sqrt(M_PI)) * og);
  544. case Mode::H_SWISH:
  545. RET(EL2(H_SWISH_GRAD, i0, og));
  546. case Mode::FUSE_ADD_H_SWISH:
  547. RET(EL2(H_SWISH_GRAD, (i0 + i1), og));
  548. case Mode::NOT:
  549. return nullptr;
  550. // binary
  551. case Mode::ABS_GRAD:
  552. if (wrt_idx == 0) {
  553. return nullptr;
  554. }
  555. RET(EL2(ABS_GRAD, i0, og));
  556. case Mode::ADD:
  557. RET(og);
  558. case Mode::FLOOR_DIV:
  559. return nullptr;
  560. case Mode::MAX:
  561. RET(EL3(COND_LEQ_MOV, i[!wrt_idx], i[wrt_idx], og));
  562. case Mode::MIN:
  563. RET(EL3(COND_LEQ_MOV, i[wrt_idx], i[!wrt_idx], og));
  564. case Mode::MOD:
  565. if (wrt_idx == 0) {
  566. RET(og);
  567. }
  568. RET_INVALID();
  569. case Mode::MUL:
  570. RET(og * i[!wrt_idx]);
  571. case Mode::POW:
  572. if (wrt_idx) {
  573. RET(out * EL1(LOG, i0) * og);
  574. }
  575. RET(og * i1 * EL2(POW, i0, i1 - 1));
  576. case Mode::SIGMOID_GRAD:
  577. if (wrt_idx == 0) {
  578. auto one = i0.make_scalar_dt(1), two = i0.make_scalar_dt(2);
  579. RET((one - i0 * two) * i1 * og);
  580. }
  581. RET(EL2(SIGMOID_GRAD, i0, og));
  582. case Mode::SUB:
  583. negate_result = wrt_idx;
  584. RET(og);
  585. case Mode::SWITCH_GT0:
  586. if (!wrt_idx)
  587. return nullptr;
  588. RET(EL2(SWITCH_GT0, i0, og));
  589. case Mode::TANH_GRAD:
  590. if (wrt_idx == 0) {
  591. auto mtwo = i0.make_scalar_dt(-2);
  592. RET(mtwo * i0 * i1 * og);
  593. }
  594. RET(EL2(TANH_GRAD, i0, og));
  595. case Mode::TRUE_DIV:
  596. if (wrt_idx == 0) {
  597. RET(og / i1);
  598. }
  599. negate_result = true;
  600. RET((og * i0) * EL2(POW, i1, i1.make_scalar(-2)));
  601. case Mode::LOG_SUM_EXP:
  602. if (wrt_idx == 0) {
  603. RET(og * EL1(SIGMOID, i0 - i1));
  604. }
  605. RET(og * EL1(SIGMOID, i1 - i0));
  606. case Mode::LT:
  607. case Mode::LEQ:
  608. return nullptr;
  609. case Mode::EQ:
  610. RET_INVALID();
  611. case Mode::OR:
  612. case Mode::XOR:
  613. case Mode::AND:
  614. return nullptr;
  615. // ternary
  616. case Mode::COND_LEQ_MOV:
  617. if (wrt_idx <= 1)
  618. return nullptr;
  619. RET(EL3(COND_LEQ_MOV, i0, i1, og));
  620. // fuse oprs
  621. case Mode::FUSE_MUL_ADD3:
  622. if (wrt_idx < 2) {
  623. RET(og * i[wrt_idx ^ 1]);
  624. } else {
  625. RET(og);
  626. }
  627. case Mode::FUSE_MUL_ADD4:
  628. RET(og * i[wrt_idx ^ 1]);
  629. default:
  630. mgb_throw(GraphError, "grad for elemwise mode %s unimplemented",
  631. megdnn::Elemwise::ModeTrait::from_mode(
  632. opr.param().mode).name);
  633. }
  634. #undef EL3
  635. #undef EL2
  636. #undef EL1
  637. #undef RET
  638. if (opr.input_broadcastable()[wrt_idx]) {
  639. result = reduce_sum(result,
  640. opr::GetVarShape::make(opr.input(wrt_idx)));
  641. } else if (result.node()->owner_opr()->same_type<Broadcast>()) {
  642. // forward broadcast for optimizer to work
  643. result = opr::Broadcast::make(result.node()->owner_opr()->input(0),
  644. opr::GetVarShape::make(i[wrt_idx]));
  645. }
  646. if (negate_result)
  647. result = -result;
  648. return result.node();
  649. }
  650. #endif
  651. VarNode* Elemwise::sum_grad_list(VarNode *wrt, VarNodeArray &grads) {
  652. mgb_assert(!grads.empty());
  653. if (grads.size() == 1)
  654. return grads[0];
  655. #if MGB_ENABLE_COND_EXEC
  656. CondExecMerge::modify_grad_sum_list(wrt, grads);
  657. #endif
  658. VarNodeArray mid_results;
  659. VarNode *ret;
  660. if (wrt->owner_graph()->options().graph_opt_level) {
  661. ret = gopt::GradSumListOptimizer{wrt, grads, mid_results}.get_sum();
  662. } else {
  663. ret = gopt::elemwise_reduce_var_list(
  664. grads, Elemwise::Mode::ADD, &mid_results);
  665. }
  666. mid_results.swap(grads);
  667. return ret;
  668. }
  669. void Elemwise::record_execute_deps(ExecDependencyArray& deps) {
  670. record_megdnn_opr(deps);
  671. }
  672. Elemwise::NodeProp* Elemwise::do_make_node_prop() const {
  673. auto ret = Super::do_make_node_prop();
  674. for (auto& inp : input()) {
  675. ret->add_dep_type_existing_var(inp,
  676. NodeProp::DepType::VALUE_ALLOW_EMPTY);
  677. }
  678. return ret;
  679. }
  680. /* =========================== TypeCvt =========================== */
  681. MGB_DYN_TYPE_OBJ_FINAL_IMPL(TypeCvt);
  682. TypeCvt::TypeCvt(
  683. VarNode *inp, DType dest_type, const OperatorNodeConfig &config):
  684. Super{inp->owner_graph(), config, std::string("as") + dest_type.name(),
  685. {inp}}
  686. {
  687. init_megdnn_opr(*this, {});
  688. mgb_assert(dest_type.valid());
  689. add_input({inp});
  690. add_equivalence_component<ScalarHash<const void*>>(dest_type.handle());
  691. output(0)->dtype(dest_type).add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
  692. }
  693. SymbolVar TypeCvt::make(
  694. SymbolVar input, DType dest_type, const OperatorNodeConfig &config) {
  695. if (input.dtype() == dest_type)
  696. return input;
  697. return input.insert_single_output_opr<TypeCvt>(
  698. input.node(), dest_type, config);
  699. }
  700. void TypeCvt::perform(DeviceTensorND &dest,
  701. DType dest_type, const DeviceTensorND &src,
  702. intl::UniqPtrWithCN<megdnn::TypeCvt> &opr) {
  703. mgb_assert(src.comp_node() == opr.comp_node());
  704. mgb_assert(dest_type.valid());
  705. if (src.dtype() == dest_type) {
  706. dest.copy_from(src);
  707. return;
  708. }
  709. src.comp_node().activate();
  710. dest.comp_node(src.comp_node()).dtype(dest_type).resize(src.shape());
  711. opr->exec(src.as_megdnn(), dest.as_megdnn());
  712. }
  713. void TypeCvt::add_input_layout_constraint() {
  714. for (auto i: input()) {
  715. i->add_layout_constraint_contiguous();
  716. }
  717. }
  718. TypeCvt::NodeProp* TypeCvt::do_make_node_prop() const {
  719. auto ret = Super::do_make_node_prop();
  720. ret->add_dep_type_existing_var(input(0),
  721. NodeProp::DepType::VALUE_ALLOW_EMPTY);
  722. return ret;
  723. }
  724. #if MGB_ENABLE_GRAD
  725. MGB_IMPL_OPR_GRAD(TypeCvt) {
  726. MGB_MARK_USED_VAR(wrt_idx);
  727. auto itype = opr.input(0)->dtype(), otype = opr.output(0)->dtype();
  728. if (itype.category() == DTypeCategory::FLOAT &&
  729. otype.category() == DTypeCategory::INT) {
  730. return nullptr;
  731. }
  732. if (itype.category() != DTypeCategory::FLOAT) {
  733. return InvalidGrad::make(opr, 0);
  734. }
  735. return TypeCvt::make(out_grad[0], opr.input(0)->dtype()).node();
  736. }
  737. #endif
  738. void TypeCvt::mem_plan_fwd_in2out_writable() {
  739. bool cond_low_bit =
  740. input(0)->dtype().is_low_bit() && output(0)->dtype().is_low_bit() &&
  741. input(0)->dtype().low_bit() == output(0)->dtype().low_bit();
  742. bool cond_normal = !input(0)->dtype().is_low_bit() &&
  743. !output(0)->dtype().is_low_bit() &&
  744. input(0)->dtype().size() == output(0)->dtype().size();
  745. if ((cond_low_bit || cond_normal) && input(0)->layout().is_contiguous()) {
  746. output(0)->set_fwd_in2out_writable(input(0));
  747. }
  748. }
  749. void TypeCvt::scn_do_execute() {
  750. auto ovar = output(0)->dev_tensor().as_megdnn();
  751. for (size_t i = 0; i < ovar.layout.ndim; ++i) {
  752. if (!ovar.layout[i]) {
  753. // skip execution for empty var
  754. return;
  755. }
  756. }
  757. megdnn_opr()->exec(input(0)->dev_tensor().as_megdnn(), ovar);
  758. }
  759. void TypeCvt::init_output_static_infer_desc() {
  760. static StaticInferOpr<megdnn::TypeCvt> static_infer_opr;
  761. Super::init_output_static_infer_desc();
  762. using namespace cg::static_infer;
  763. auto infer_value = [this](DeviceTensorND &dest, const InpVal &inp) {
  764. auto sopr = static_infer_opr.lock();
  765. perform(dest, output(0)->dtype(), inp.val.at(0).value(), sopr());
  766. return true;
  767. };
  768. owner_graph()->static_infer_manager().register_value_infer(
  769. output(0), {SourceType::DEP, {{input(0), DepType::VALUE}},
  770. infer_value});
  771. }
  772. void TypeCvt::record_execute_deps(ExecDependencyArray& deps) {
  773. record_megdnn_opr(deps);
  774. }
  775. /* =========================== AddUpdate =========================== */
  776. MGB_DYN_TYPE_OBJ_FINAL_IMPL(AddUpdate);
  777. AddUpdate::AddUpdate(VarNode *dest, VarNode *delta,
  778. const Param &param,
  779. const OperatorNodeConfig &config):
  780. Super{dest->owner_graph(), config, "inplace_add", {dest, delta}},
  781. m_param{param}
  782. {
  783. auto dest_opr = dest->owner_opr();
  784. mgb_throw_if(dest_opr->same_type<ImmutableTensor>(),
  785. GraphError,
  786. "AddUpdate cannot be applied on ImmutableTensor; ");
  787. add_input({dest, delta});
  788. /*
  789. * here we tell the system that output(0) would force-update input(0); the
  790. * topo-sorting system would ensure that all the readers finish before
  791. * executing this AddUpdate operation
  792. */
  793. add_output(None)->
  794. set_fwd_in2out_writable_force(input(0)).
  795. add_flag(VarNode::Flag::NO_MEM_RECLAIM);
  796. mgb_assert(m_param.disable->dtype() == dtype::Int32{},
  797. "dtype of disable flag on AddUpdate must be Int32, got %s actually.",
  798. m_param.disable->dtype().name());
  799. add_equivalence_component<ScalarHash<void*>>(m_param.alpha.get());
  800. add_equivalence_component<ScalarHash<void*>>(m_param.beta.get());
  801. add_equivalence_component<ScalarHash<void*>>(m_param.bias.get());
  802. add_equivalence_component<ScalarHash<void*>>(m_param.disable.get());
  803. }
  804. SymbolVar AddUpdate::make(SymbolVar dest, SymbolVar delta,
  805. const Param &param, const OperatorNodeConfig &config) {
  806. delta = opr::TypeCvt::make(delta, dest.dtype());
  807. return dest.insert_single_output_opr<AddUpdate>(
  808. dest.node(), delta.node(), param, config);
  809. }
  810. cg::OperatorNodeBase::NodeProp* AddUpdate::do_make_node_prop() const {
  811. auto ret = Super::do_make_node_prop();
  812. ret->add_flag(NodeProp::Flag::FORCE_UPDATE_INPUT_VAR);
  813. return ret;
  814. }
  815. void AddUpdate::create_megdnn_opr() {
  816. set_megdnn_opr(intl::get_megdnn_handle(comp_node())->
  817. create_operator<megdnn::AddUpdate>());
  818. }
  819. void AddUpdate::scn_do_execute() {
  820. mgb_assert(m_param.disable->dtype() == dtype::Int32{},
  821. "dtype of disable flag on AddUpdate must be Int32, got %s actually.",
  822. m_param.disable->dtype().name());
  823. auto disable = m_param.disable->get_cast<int>();
  824. if(disable == 1) return;
  825. mgb_assert(disable == 0, "disable flag on AddUpdate can only be 0 or 1,"
  826. " got %d actually.", disable);
  827. auto &&dest = output(0)->dev_tensor();
  828. auto &&delta_nobrd = input(1)->dev_tensor();
  829. auto delta = delta_nobrd.sub(SubTensorSpec::make_from_offset_elem(
  830. delta_nobrd.layout().broadcast(dest.shape()), 0));
  831. mgb_assert(input(0)->dev_tensor().raw_ptr() == dest.raw_ptr());
  832. auto beta = m_param.beta->get_cast<float>();
  833. if (!m_param.alpha->get_cast<bool>() && beta == 1 &&
  834. !m_param.bias->get_cast<bool>()) {
  835. dest.copy_from_fixlayout(delta);
  836. } else {
  837. auto opr = static_cast<megdnn::AddUpdate*>(megdnn_opr());
  838. opr->param() = {
  839. m_param.alpha->get_cast<float>(),
  840. beta,
  841. m_param.bias->get_cast<float>()};
  842. opr->exec(dest.as_megdnn(), delta.as_megdnn());
  843. }
  844. }
  845. void AddUpdate::init_output_static_infer_desc() {
  846. using namespace cg::static_infer;
  847. owner_graph()->static_infer_manager().register_shape_infer(
  848. output(0), ShapeInferDesc::make_identity(input(0)));
  849. }
  850. void AddUpdate::record_execute_deps(ExecDependencyArray& deps) {
  851. record_megdnn_opr(deps);
  852. }
  853. #if MGB_ENABLE_GRAD
  854. MGB_IMPL_OPR_GRAD(AddUpdate) {
  855. // actually valid, just not implemented
  856. return InvalidGrad::make(opr, wrt_idx);
  857. }
  858. #endif
  859. /* =========================== Reduce =========================== */
  860. class Reduce::KernScheduler {
  861. class ValueDep final : public ExecDependency {
  862. DeviceTensorStorage m_val;
  863. public:
  864. explicit ValueDep(DeviceTensorStorage val) : m_val(std::move(val)) {}
  865. };
  866. public:
  867. bool has_actual_computing() const {
  868. mgb_assert(m_shape_computed);
  869. return !m_kern_param.empty() || m_apply_side_effect;
  870. }
  871. size_t workspace_size() const {
  872. return m_workspace_spec[2].end();
  873. }
  874. bool shape_computed() const {
  875. return m_shape_computed;
  876. }
  877. //! init shapes in kern param
  878. void init_shapes(
  879. megdnn::Reduce *opr, CompNode comp_node, DType dtype, Mode mode,
  880. TensorShape ishp, TensorShape oshp, const Param::DataType data_type);
  881. void setup_kern_params_layout_and_mode(Mode mode, DType inp_dtype,
  882. TensorShape& inp_shp,
  883. const Param::DataType);
  884. void check_shapes(const TensorShape &ishp, const TensorShape &oshp) {
  885. mgb_assert(m_prev_ishp.eq_shape(ishp) &&
  886. m_prev_oshp.eq_shape(oshp));
  887. }
  888. //! update pointers in kern param; the tensors must have been allocated
  889. void update_ptr(
  890. const DeviceTensorND &input, const DeviceTensorND &dest,
  891. const DeviceTensorND &workspace);
  892. void execute(megdnn::Reduce *opr,
  893. const DeviceTensorND &input, const DeviceTensorND &dest);
  894. void record_execute_deps(ExecDependencyArray& deps) {
  895. if (m_elemwise_trans_opr) {
  896. deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(
  897. std::move(m_elemwise_trans_opr)));
  898. }
  899. if (m_typecvt_opr) {
  900. deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(
  901. std::move(m_typecvt_opr)));
  902. }
  903. deps.emplace_back(
  904. std::make_unique<ValueDep>(m_side_affect_wkspc.storage()));
  905. }
  906. private:
  907. struct KernParam {
  908. megdnn::TensorND input, output;
  909. //! param passed to megdnn
  910. megdnn::param::Reduce kparam;
  911. megdnn::Workspace workspace;
  912. KernParam(Mode mode, int32_t ra):
  913. kparam{mode, ra}
  914. {
  915. }
  916. };
  917. struct SubWorkspace {
  918. size_t size, offset;
  919. size_t end() const {
  920. return size + offset;
  921. }
  922. };
  923. void update_kparam_for_elemwise_side_effect(
  924. CompNode comp_node, Mode mode, const Param::DataType data_type);
  925. bool m_shape_computed = false;
  926. std::vector<KernParam> m_kern_param;
  927. TensorShape m_prev_ishp, m_prev_oshp;
  928. SubWorkspace m_workspace_spec[3]; //! tmp output[2], kern workspce
  929. /*!
  930. * some reduce mode (like SUM_SQR) has side effect of element-wise
  931. * trans. If this is the case and there is no kernel param,
  932. * m_apply_side_effect would be non-null
  933. */
  934. thin_function<void(const DeviceTensorND &in,
  935. const DeviceTensorND &out)>
  936. m_apply_side_effect;
  937. std::unique_ptr<megdnn::Elemwise> m_elemwise_trans_opr;
  938. std::unique_ptr<megdnn::TypeCvt> m_typecvt_opr;
  939. DeviceTensorND m_side_affect_wkspc;
  940. };
  941. void Reduce::KernScheduler::setup_kern_params_layout_and_mode(Mode mode,
  942. DType inp_dtype,
  943. TensorShape& ishp,
  944. const Param::DataType data_type) {
  945. auto prev_dtype = inp_dtype;
  946. for (size_t idx = 0; idx < m_kern_param.size(); ++idx) {
  947. auto&& i = m_kern_param[idx];
  948. #if !MEGDNN_DISABLE_FLOAT16
  949. if (idx == 0 && data_type == Param::DataType::FLOAT_O32xC32) {
  950. i.input.layout.dtype = inp_dtype;
  951. i.output.layout.dtype = dtype::Float32();
  952. i.kparam.data_type = data_type;
  953. } else if (data_type == Param::DataType::FLOAT_O16xC32) {
  954. i.input.layout.dtype = prev_dtype;
  955. if (idx + 1 == m_kern_param.size()) {
  956. i.output.layout.dtype = dtype::Float16();
  957. i.kparam.data_type = data_type;
  958. }
  959. else {
  960. i.output.layout.dtype = dtype::Float32();
  961. i.kparam.data_type = Param::DataType::FLOAT_O32xC32;
  962. }
  963. } else
  964. #endif
  965. {
  966. mgb_assert(data_type == Param::DataType::DEFAULT || (
  967. data_type == Param::DataType::FLOAT_O32xC32 &&
  968. idx));
  969. i.input.layout.dtype = prev_dtype;
  970. i.output.layout.dtype = prev_dtype;
  971. i.kparam.data_type = Param::DataType::DEFAULT;
  972. }
  973. prev_dtype = i.output.layout.dtype;
  974. i.input.layout.init_contiguous_stride(ishp);
  975. ishp.shape[i.kparam.axis] = 1;
  976. i.output.layout.init_contiguous_stride(ishp);
  977. }
  978. if (mode == Mode::SUM_SQR) {
  979. for (size_t i = 1; i < m_kern_param.size(); ++ i)
  980. m_kern_param[i].kparam.mode = Mode::SUM;
  981. }
  982. }
  983. void Reduce::KernScheduler::init_shapes(
  984. megdnn::Reduce *opr, CompNode comp_node, DType inp_dtype, Mode mode,
  985. TensorShape ishp, TensorShape oshp, const Param::DataType data_type) {
  986. mgb_assert(ishp.ndim && oshp.ndim);
  987. if (ishp.eq_shape(m_prev_ishp) && oshp.eq_shape(m_prev_oshp))
  988. return;
  989. m_prev_ishp = ishp;
  990. m_prev_oshp = oshp;
  991. m_kern_param.clear();
  992. if (oshp.is_scalar()) {
  993. // if ishp is non-contiguous, add_layout_constraint_contiguous would be
  994. // added; so we do not have to worry about this
  995. ishp.shape[0] = ishp.total_nr_elems();
  996. ishp.ndim = 1;
  997. }
  998. mgb_assert(oshp.ndim == ishp.ndim,
  999. "input and output ndim mismatch for reduction: ishp=%s oshp=%s",
  1000. ishp.to_string().c_str(), oshp.to_string().c_str());
  1001. for (size_t i = 0; i < ishp.ndim; ++ i) {
  1002. if (ishp.shape[i] != oshp.shape[i]) {
  1003. mgb_assert(oshp.shape[i] == 1,
  1004. "input and output shape mismatch for reduction: "
  1005. "ishp=%s oshp=%s",
  1006. ishp.to_string().c_str(), oshp.to_string().c_str());
  1007. }
  1008. }
  1009. auto remove_axis = [](TensorShape &shp, size_t ax) {
  1010. mgb_assert(shp.ndim > 1);
  1011. for (auto i = ax + 1; i < shp.ndim; ++ i)
  1012. shp.shape[i - 1] = shp.shape[i];
  1013. -- shp.ndim;
  1014. };
  1015. // collapse consecutive shape-1 axes in oshp
  1016. for (size_t i = 0; i < oshp.ndim; ++ i) {
  1017. auto start = i;
  1018. while (i < oshp.ndim && oshp.shape[i] == 1)
  1019. ++ i;
  1020. if (start + 1 < i) {
  1021. for (auto j = start + 1; j < i; ++ j)
  1022. ishp.shape[start] *= ishp.shape[j];
  1023. for (auto j = start + 1; j < i; ++ j) {
  1024. remove_axis(ishp, start + 1);
  1025. remove_axis(oshp, start + 1);
  1026. }
  1027. i = start;
  1028. }
  1029. }
  1030. for (uint32_t i = 0; i < ishp.ndim; ++ i) {
  1031. if (ishp.shape[i] != oshp.shape[i]) {
  1032. mgb_assert(oshp.shape[i] == 1);
  1033. m_kern_param.push_back({mode, static_cast<int32_t>(i)});
  1034. }
  1035. }
  1036. // sort according to reduction size, so workspace can be smaller
  1037. small_sort(m_kern_param.begin(), m_kern_param.end(),
  1038. [&](const KernParam &a, const KernParam &b) {
  1039. return ishp.shape[a.kparam.axis] > ishp.shape[b.kparam.axis];
  1040. });
  1041. // init kparam input/output layout
  1042. setup_kern_params_layout_and_mode(mode, inp_dtype, ishp, data_type);
  1043. // init workspace size
  1044. memset(m_workspace_spec, 0, sizeof(m_workspace_spec));
  1045. for (auto&& i : m_kern_param) {
  1046. opr->param() = i.kparam;
  1047. i.workspace.size = opr->get_workspace_in_bytes(
  1048. i.input.layout, i.output.layout);
  1049. update_max(m_workspace_spec[2].size, i.workspace.size);
  1050. }
  1051. mgb_assert(ishp.eq_shape(oshp));
  1052. if (m_kern_param.size() >= 2) {
  1053. m_workspace_spec[0].size =
  1054. m_kern_param[1].input.layout.span().high_byte;
  1055. }
  1056. if (m_kern_param.size() >= 3) {
  1057. m_workspace_spec[1].size =
  1058. m_kern_param[2].input.layout.span().high_byte;
  1059. }
  1060. auto align = comp_node.get_mem_addr_alignment();
  1061. for (int i = 0; i < 2; ++ i) {
  1062. m_workspace_spec[i + 1].offset = get_aligned_power2(
  1063. m_workspace_spec[i].end(), align);
  1064. }
  1065. update_kparam_for_elemwise_side_effect(comp_node, mode, data_type);
  1066. m_shape_computed = true;
  1067. }
  1068. void Reduce::KernScheduler::update_kparam_for_elemwise_side_effect(
  1069. CompNode comp_node, Mode mode, const Param::DataType data_type) {
  1070. m_apply_side_effect = nullptr;
  1071. m_elemwise_trans_opr.reset();
  1072. m_typecvt_opr.reset();
  1073. if (!m_kern_param.empty()) {
  1074. // no need to set m_apply_side_effect
  1075. return;
  1076. } /* else */
  1077. // case A: input.layout == output.layout
  1078. // case B: input.total_nr_elems == 1 and output is a scalar
  1079. if (mode == Mode::SUM_SQR) {
  1080. m_elemwise_trans_opr = intl::get_megdnn_handle(comp_node)->
  1081. create_operator<megdnn::Elemwise>();
  1082. m_elemwise_trans_opr->param() = {Elemwise::Mode::MUL};
  1083. }
  1084. if (data_type != Param::DataType::DEFAULT) {
  1085. m_side_affect_wkspc = DeviceTensorND{comp_node, dtype::Float32()};
  1086. m_typecvt_opr = intl::get_megdnn_handle(comp_node)->
  1087. create_operator<megdnn::TypeCvt>();
  1088. }
  1089. if (!m_typecvt_opr && !m_elemwise_trans_opr)
  1090. return;
  1091. m_apply_side_effect = [this](const DeviceTensorND &in,
  1092. const DeviceTensorND &out) {
  1093. if (m_typecvt_opr) {
  1094. m_side_affect_wkspc.resize(in.shape());
  1095. }
  1096. if (!m_elemwise_trans_opr) {
  1097. mgb_assert(m_typecvt_opr);
  1098. m_typecvt_opr->exec(in.as_megdnn(), out.as_megdnn());
  1099. return;
  1100. }
  1101. auto im = in.as_megdnn();
  1102. megdnn::TensorND wm;
  1103. if (m_typecvt_opr && in.dtype() != m_side_affect_wkspc.dtype()) {
  1104. m_side_affect_wkspc.resize(in.shape());
  1105. wm = m_side_affect_wkspc.as_megdnn();
  1106. m_typecvt_opr->exec(im, wm);
  1107. } else {
  1108. wm = im;
  1109. }
  1110. if (m_typecvt_opr && wm.layout.dtype != out.dtype()) {
  1111. m_elemwise_trans_opr->exec({wm, wm}, wm);
  1112. m_typecvt_opr->exec(wm, out.as_megdnn());
  1113. } else {
  1114. auto &&wshp = wm.layout;
  1115. if (wshp.ndim != out.layout().ndim) {
  1116. // to ensure that wkspc.ndim equals out.ndim in the case:
  1117. // wkspc.shape=(1, 1, ..., 1) and out.shape=(1), otherwise it
  1118. // may lead the 'TensorShape Dimension' assertion failed in
  1119. // the following broadcast operator
  1120. mgb_assert(wshp.total_nr_elems() == 1 && out.layout().ndim == 1);
  1121. wshp.ndim = 1;
  1122. }
  1123. m_elemwise_trans_opr->exec({wm, wm}, out.as_megdnn());
  1124. }
  1125. };
  1126. }
  1127. void Reduce::KernScheduler::update_ptr(
  1128. const DeviceTensorND &input, const DeviceTensorND &dest,
  1129. const DeviceTensorND &workspace) {
  1130. auto dtype = dest.layout().dtype;
  1131. mgb_assert(dtype.valid());
  1132. mgb_assert(m_shape_computed);
  1133. if (workspace_size()) {
  1134. mgb_assert(workspace.layout().dtype == dtype::Byte() &&
  1135. workspace.layout().ndim == 1 &&
  1136. workspace.shape()[0] >= workspace_size());
  1137. }
  1138. if (m_kern_param.empty())
  1139. return;
  1140. mgb_assert(input.layout().total_nr_elems() ==
  1141. m_kern_param[0].input.layout.total_nr_elems());
  1142. mgb_assert(dest.shape().total_nr_elems() ==
  1143. m_kern_param.back().output.layout.total_nr_elems());
  1144. m_kern_param[0].input.raw_ptr = const_cast<dt_byte*>(input.raw_ptr());
  1145. dt_byte
  1146. *workspace_begin = workspace_size() ?
  1147. const_cast<dt_byte*>(workspace.raw_ptr()) : nullptr,
  1148. *tmp_reduce_ptr[2] = {
  1149. workspace_begin + m_workspace_spec[0].offset,
  1150. workspace_begin + m_workspace_spec[1].offset},
  1151. *kern_workspace = workspace_begin + m_workspace_spec[2].offset;
  1152. for (size_t i = 0; i < m_kern_param.size() - 1; ++ i) {
  1153. auto optr = tmp_reduce_ptr[i % 2];
  1154. m_kern_param[i].output.raw_ptr = optr;
  1155. m_kern_param[i + 1].input.raw_ptr = optr;
  1156. }
  1157. for (auto &&i: m_kern_param)
  1158. i.workspace.raw_ptr = kern_workspace;
  1159. m_kern_param.back().output.raw_ptr = const_cast<dt_byte*>(dest.raw_ptr());
  1160. }
  1161. void Reduce::KernScheduler::execute(
  1162. megdnn::Reduce *opr,
  1163. const DeviceTensorND &input, const DeviceTensorND &dest) {
  1164. if (m_apply_side_effect) {
  1165. mgb_assert(m_kern_param.empty());
  1166. m_apply_side_effect(input, dest);
  1167. return;
  1168. }
  1169. mgb_assert(!m_kern_param.empty());
  1170. mgb_assert(input.layout().is_contiguous() &&
  1171. input.raw_ptr() == m_kern_param[0].input.raw_ptr &&
  1172. dest.raw_ptr() == m_kern_param.back().output.raw_ptr);
  1173. for (auto &&i: m_kern_param) {
  1174. opr->param() = i.KernParam::kparam;
  1175. opr->exec(i.input, i.output, i.workspace);
  1176. }
  1177. }
  1178. class Reduce::OutTensorShapeExtender {
  1179. public:
  1180. OutTensorShapeExtender(const TensorShape& ishp, const TensorShape& oshp)
  1181. : m_oshp(oshp) {
  1182. mgb_assert(oshp.ndim <= ishp.ndim,
  1183. "output ndim should be less and equal than input ndim for "
  1184. "reduction: "
  1185. "ishp=%s oshp=%s",
  1186. ishp.to_string().c_str(), oshp.to_string().c_str());
  1187. // Ex. ishp = (a, b, c, d), oshp = (c, d)
  1188. if (!oshp.is_scalar() && ishp.ndim != oshp.ndim) {
  1189. size_t ndim_diff = ishp.ndim - oshp.ndim;
  1190. auto&& canonized_oshp = m_canonized_oshp_storage.emplace(oshp);
  1191. for (size_t i = 0; i < ishp.ndim; ++i)
  1192. if (i < ndim_diff)
  1193. canonized_oshp[i] = 1;
  1194. else
  1195. canonized_oshp[i] = oshp[i - ndim_diff];
  1196. canonized_oshp.ndim = ishp.ndim;
  1197. }
  1198. }
  1199. const TensorShape& get() const {
  1200. return m_canonized_oshp_storage.valid() ? m_canonized_oshp_storage.val()
  1201. : m_oshp;
  1202. }
  1203. private:
  1204. Maybe<TensorShape> m_canonized_oshp_storage;
  1205. const TensorShape& m_oshp;
  1206. };
  1207. MGB_DYN_TYPE_OBJ_FINAL_IMPL(Reduce);
  1208. Reduce::Reduce(VarNode *inp, VarNode *target_shape, const Param &param,
  1209. const OperatorNodeConfig &config):
  1210. Super{inp->owner_graph(), config,
  1211. ssprintf("reduce%d", static_cast<int>(param.mode)), {inp}},
  1212. m_param{param}, m_kern_scheduler{std::make_unique<KernScheduler>()}
  1213. {
  1214. add_input({inp});
  1215. if (inp->dtype().enumv() == DTypeEnum::Quantized8Asymm &&
  1216. inp->dtype().category() == DTypeCategory::QUANTIZED) {
  1217. mgb_assert(param.mode != Param::Mode::PRODUCT,
  1218. "Reduce does not support PRODUCT mode on quantized input");
  1219. mgb_assert(param.mode != Param::Mode::SUM_SQR,
  1220. "Reduce does not support SUM_SQR mode on quantized input");
  1221. mgb_assert(param.mode != Param::Mode::SUM,
  1222. "Reduce does not support SUM mode on quantized input");
  1223. }
  1224. DType out_dtype;
  1225. switch (param.data_type) {
  1226. case Param::DataType::DEFAULT:
  1227. out_dtype = inp->dtype();
  1228. break;
  1229. #if !MEGDNN_DISABLE_FLOAT16
  1230. case Param::DataType::FLOAT_O16xC32:
  1231. out_dtype = dtype::Float16();
  1232. break;
  1233. case Param::DataType::FLOAT_IO16xC32:
  1234. mgb_assert(false);
  1235. #endif
  1236. case Param::DataType::FLOAT_O32xC32:
  1237. out_dtype = dtype::Float32();
  1238. break;
  1239. case Param::DataType::QUINT_I8xO32:
  1240. out_dtype = dtype::QuantizedS32(
  1241. inp->dtype().param<dtype::Quantized8Asymm>().scale);
  1242. break;
  1243. case Param::DataType::QINT_I8xO32:
  1244. out_dtype = dtype::QuantizedS32(
  1245. inp->dtype().param<dtype::QuantizedS8>().scale);
  1246. break;
  1247. default:
  1248. mgb_throw(GraphError, "invalid param data_type: %d",
  1249. int(param.data_type));
  1250. }
  1251. add_output(None)->dtype(out_dtype);
  1252. cg::add_workspace_output(this);
  1253. add_equivalence_component<PODHash<Param>>(&m_param);
  1254. if (param.axis >= -MEGDNN_MAX_NDIM && param.axis < MEGDNN_MAX_NDIM) {
  1255. mgb_throw_if(target_shape, GraphError,
  1256. "could not specify both axis and target shape");
  1257. m_is_symtshp = false;
  1258. } else {
  1259. mgb_throw_if(!target_shape, GraphError,
  1260. "neither axis or target_shape specified");
  1261. add_input({target_shape});
  1262. m_is_symtshp = true;
  1263. outshape_by_symvar_enable(0, 1);
  1264. }
  1265. }
  1266. Reduce::~Reduce() = default;
  1267. SymbolVar Reduce::make(
  1268. SymbolVar src, Param param, SymbolVar target_shape,
  1269. const OperatorNodeConfig &config) {
  1270. if (param.data_type == Param::DataType::FLOAT_IO16xC32) {
  1271. mgb_log_warn("DataType FLOAT_IO16xC32 has been deprecated "
  1272. "use FLOAT_O16xC32 instead");
  1273. param.data_type = Param::DataType::FLOAT_O16xC32;
  1274. }
  1275. if (param.mode == Mode::SUM &&
  1276. src.node()->owner_opr()->same_type<Elemwise>()) {
  1277. // replace sum(x^2) by sum_sqr(x)
  1278. auto &&opr = src.node()->owner_opr()->cast_final<Elemwise>();
  1279. if (opr.param().mode == Elemwise::Mode::POW) {
  1280. mgb_assert(opr.input().size() == 2);
  1281. auto pow = SymbolVar{opr.input(1)}.as_immutable_scalar();
  1282. if (pow.valid() && pow->get_cast<float>() == 2) {
  1283. src = opr.input(0);
  1284. param.mode = Mode::SUM_SQR;
  1285. }
  1286. }
  1287. }
  1288. return src.insert_single_output_opr<Reduce>(
  1289. src.node(), target_shape.node(), param, config);
  1290. }
  1291. void Reduce::outshape_by_symvar_do_get_output_shape(
  1292. TensorShape &dest, const ShapeInferInfo &shpinfo) {
  1293. cg::copy_tensor_value_to_shape(dest, *shpinfo.shpval_inp_val.at(0));
  1294. }
  1295. void Reduce::init_output_static_infer_desc() {
  1296. using namespace cg::static_infer;
  1297. auto &&mgr = owner_graph()->static_infer_manager();
  1298. // infer output shape
  1299. if (m_is_symtshp) {
  1300. // reduce to target shape
  1301. Super::init_output_static_infer_desc();
  1302. } else {
  1303. // reduce along axis
  1304. auto infer_shape = [this](TensorShape &dest, const InpVal &inp) {
  1305. dest = inp.val.at(0).shape();
  1306. mgb_assert(m_param.axis < static_cast<int>(dest.ndim) &&
  1307. m_param.axis >= -static_cast<int>(dest.ndim),
  1308. "invalid axis for reduction: shape=%s axis=%d",
  1309. dest.to_string().c_str(), m_param.axis);
  1310. int real_axis = m_param.axis;
  1311. if (real_axis < 0)
  1312. real_axis += dest.ndim;
  1313. dest.shape[real_axis] = 1;
  1314. return true;
  1315. };
  1316. mgr.register_shape_infer(
  1317. output(0), {
  1318. SourceType::DEP, {{input(0), DepType::SHAPE}}, infer_shape});
  1319. }
  1320. // infer workspace
  1321. auto infer_workspace = [this](TensorShape &dest, const InpVal &inp) {
  1322. init_kern_sched_shape(inp.val[0].shape(), inp.val[1].shape());
  1323. dest.ndim = 1;
  1324. dest.shape[0] = m_kern_scheduler->workspace_size();
  1325. return true;
  1326. };
  1327. mgr.register_shape_infer(output(1),
  1328. {SourceType::DEP,
  1329. {{input(0), DepType::SHAPE}, {output(0), DepType::SHAPE}},
  1330. infer_workspace});
  1331. // infer value
  1332. static StaticInferOpr<megdnn::Reduce> static_infer_opr;
  1333. auto infer_value = [this](DeviceTensorND &dest, const InpVal &inp) {
  1334. DeviceTensorND workspace;
  1335. auto sopr = static_infer_opr.lock();
  1336. perform(m_param.mode, dest, workspace, inp.val[0].value(),
  1337. output(0)->dtype(), inp.val.at(1).shape(), sopr(),
  1338. m_param.data_type);
  1339. return true;
  1340. };
  1341. mgr.register_value_infer(output(0),
  1342. {SourceType::DEP,
  1343. {{input(0), DepType::VALUE}, {output(0), DepType::SHAPE}},
  1344. infer_value});
  1345. }
  1346. void Reduce::init_kern_sched_shape(const TensorShape& ishp,
  1347. const TensorShape& oshp) {
  1348. OutTensorShapeExtender extender(ishp, oshp);
  1349. auto&& canonized_oshp = extender.get();
  1350. m_kern_scheduler->init_shapes(static_cast<megdnn::Reduce*>(megdnn_opr()),
  1351. comp_node(), input(0)->dtype(), m_param.mode,
  1352. ishp, canonized_oshp, m_param.data_type);
  1353. }
  1354. cg::OperatorNodeBase::OprEventCallback Reduce::get_opr_event_callback() {
  1355. auto on_mem_status_changed = [this]() {
  1356. auto&& ishp = input(0)->shape();
  1357. auto&& oshp = output(0)->shape();
  1358. OutTensorShapeExtender extender(ishp, oshp);
  1359. auto&& canonized_oshp = extender.get();
  1360. m_kern_scheduler->check_shapes(input(0)->shape(), canonized_oshp);
  1361. m_kern_scheduler->update_ptr(
  1362. input(0)->dev_tensor(), output(0)->dev_tensor(),
  1363. output(1)->shape()[0] ? output(1)->dev_tensor()
  1364. : DeviceTensorND{});
  1365. };
  1366. return {on_mem_status_changed};
  1367. }
  1368. void Reduce::mem_plan_fwd_in2out_readonly() {
  1369. init_kern_sched_shape(input(0)->shape(), output(0)->shape());
  1370. if (!m_kern_scheduler->has_actual_computing()) {
  1371. // forward memory if no actual computing needed
  1372. if (!output(0)->mem_plan().valid()) {
  1373. // output(0) is dynamic but current is staic alloc phase (for
  1374. // workspace)
  1375. return;
  1376. }
  1377. auto&& ily = input(0)->layout();
  1378. auto&& oly = output(0)->layout();
  1379. const TensorLayout* fwd_spec = nullptr;
  1380. Maybe<TensorLayout> ily_modified_storage;
  1381. if (!ily.eq_shape(oly)) {
  1382. auto&& ily_modified = ily_modified_storage.emplace(ily);
  1383. mgb_assert(ily.ndim > oly.ndim);
  1384. for (size_t i = 0; i < ily.ndim - oly.ndim; ++i)
  1385. mgb_assert(ily.shape[i] == 1);
  1386. ily_modified = ily_modified.reshape(oly);
  1387. fwd_spec = &ily_modified;
  1388. } else {
  1389. fwd_spec = &ily;
  1390. }
  1391. m_mem_fwd_success = output(0)->set_fwd_in2out_readonly(
  1392. input(0), SubTensorSpec::make_from_layout(*fwd_spec));
  1393. }
  1394. }
  1395. void Reduce::add_input_layout_constraint() {
  1396. if (!cg::is_static_var_shape(output(0))) {
  1397. // output shape can not be inferred; require contiguous to be safe
  1398. input(0)->add_layout_constraint_contiguous();
  1399. } else {
  1400. auto check = [this](const TensorLayout &ily) {
  1401. auto &&mgr = owner_graph()->static_infer_manager();
  1402. auto oshp = mgr.infer_shape(output(0));
  1403. init_kern_sched_shape(ily, oshp);
  1404. if (m_kern_scheduler->has_actual_computing())
  1405. return ily.is_contiguous();
  1406. return true;
  1407. };
  1408. input(0)->add_layout_constraint(check);
  1409. }
  1410. }
  1411. void Reduce::scn_do_execute() {
  1412. auto&& inp = input(0)->dev_tensor();
  1413. auto&& out = output(0)->dev_tensor();
  1414. auto&& ishp = input(0)->shape();
  1415. auto&& oshp = output(0)->shape();
  1416. const DeviceTensorND* out_ptr;
  1417. Maybe<DeviceTensorND> canonized_storage;
  1418. OutTensorShapeExtender extender(ishp, oshp);
  1419. auto&& canonized_oshp = extender.get();
  1420. if (canonized_oshp.ndim != out.shape().ndim) {
  1421. auto&& canonized_out = canonized_storage.emplace(out);
  1422. canonized_out.reset(
  1423. canonized_out.storage(),
  1424. canonized_out.layout().reshape(canonized_oshp));
  1425. out_ptr = &canonized_out;
  1426. } else {
  1427. out_ptr = &out;
  1428. }
  1429. // shape initialized either in deducing workspace,
  1430. // mem_plan_fwd_in2out_readonly, or check input layout
  1431. m_kern_scheduler->check_shapes(inp.shape(), out_ptr->shape());
  1432. if (m_kern_scheduler->has_actual_computing()) {
  1433. m_kern_scheduler->execute(static_cast<megdnn::Reduce*>(megdnn_opr()),
  1434. inp, *out_ptr);
  1435. } else {
  1436. // no reduction needed, just forward
  1437. if (m_mem_fwd_success) {
  1438. mgb_assert(inp.raw_ptr() == out_ptr->raw_ptr() &&
  1439. out_ptr->layout().total_nr_elems() ==
  1440. inp.layout().total_nr_elems());
  1441. } else {
  1442. if (!out_ptr->shape().eq_shape(inp.shape())) {
  1443. mgb_assert(out_ptr->shape().is_scalar() &&
  1444. inp.shape().total_nr_elems() == 1);
  1445. out_ptr->sub(SubTensorSpec::make_from_layout(inp.layout()))
  1446. .copy_from_fixlayout(inp);
  1447. } else {
  1448. out_ptr->copy_from_fixlayout(inp);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. void Reduce::perform(
  1454. Mode mode,
  1455. DeviceTensorND &dest, DeviceTensorND &workspace,
  1456. const DeviceTensorND &input,
  1457. const DType &target_dtype,
  1458. const TensorShape &target_shape,
  1459. intl::UniqPtrWithCN<megdnn::Reduce> &opr, const Param::DataType data_type) {
  1460. mgb_assert(!dest.storage().comp_node_valid() ||
  1461. opr.comp_node() == dest.comp_node());
  1462. KernScheduler ksched;
  1463. OutTensorShapeExtender extender(input.shape(), target_shape);
  1464. auto&& canonized_oshp = extender.get();
  1465. ksched.init_shapes(opr.get(), opr.comp_node(), input.layout().dtype,
  1466. mode, input.shape(), canonized_oshp, data_type);
  1467. if (!ksched.has_actual_computing()) {
  1468. mgb_assert(target_shape.total_nr_elems() ==
  1469. input.layout().total_nr_elems());
  1470. dest.copy_from(input);
  1471. dest.reset(dest.storage(), {target_shape, dest.dtype()});
  1472. return;
  1473. }
  1474. workspace.
  1475. comp_node(opr.comp_node()).
  1476. dtype(dtype::Byte());
  1477. size_t workspace_size = ksched.workspace_size();
  1478. DeviceTensorND input_contig_storage;
  1479. const DeviceTensorND *input_contig = &input;
  1480. if (!input.layout().is_contiguous()) {
  1481. auto offset = get_aligned_power2(
  1482. workspace_size, opr.comp_node().get_mem_addr_alignment());
  1483. workspace_size = offset +
  1484. input.dtype().size(input.shape().total_nr_elems());
  1485. workspace.resize({workspace_size});
  1486. input_contig_storage.
  1487. reset(workspace.storage().sub(offset), {
  1488. input.shape(), input.dtype()}).
  1489. copy_from(input);
  1490. input_contig = &input_contig_storage;
  1491. } else {
  1492. workspace.resize({workspace_size});
  1493. }
  1494. opr.comp_node().activate();
  1495. dest.comp_node(opr.comp_node()).dtype(target_dtype).resize(target_shape);
  1496. ksched.update_ptr(*input_contig, dest, workspace);
  1497. ksched.execute(opr.get(), *input_contig, dest);
  1498. }
  1499. void Reduce::create_megdnn_opr() {
  1500. set_megdnn_opr(intl::get_megdnn_handle(comp_node())->
  1501. create_operator<megdnn::Reduce>());
  1502. }
  1503. #if MGB_ENABLE_GRAD
  1504. MGB_IMPL_OPR_GRAD(Reduce) {
  1505. for (size_t i = 1; i < opr.output().size(); ++ i)
  1506. mgb_assert(!out_grad[i]);
  1507. if (wrt_idx || opr.input(0)->dtype().category() != DTypeCategory::FLOAT)
  1508. return InvalidGrad::make(opr, wrt_idx);
  1509. SymbolVar og{out_grad[0]}, iv{opr.input(0)}, ov{opr.output(0)};
  1510. constexpr auto cmv = Elemwise::Mode::COND_LEQ_MOV;
  1511. using Mode = Reduce::Mode;
  1512. SymbolVar grad = [&]() {
  1513. switch (opr.param().mode) {
  1514. case Mode::SUM:
  1515. return Broadcast::make(og, GetVarShape::make(iv));
  1516. case Mode::SUM_SQR:
  1517. return (og * og.make_scalar_dt(2) * iv);
  1518. case Mode::PRODUCT:
  1519. return ((og * ov) / iv);
  1520. case Mode::MIN:
  1521. return Elemwise::make({iv, ov, og}, cmv);
  1522. case Mode::MAX:
  1523. return Elemwise::make({ov, iv, og}, cmv);
  1524. case Mode::MEAN: {
  1525. auto og_shape = opr::GetVarShape::make(og),
  1526. iv_shape = opr::GetVarShape::make(iv),
  1527. scale = div(
  1528. opr::reduce_prod(og_shape, og_shape.make_scalar(1)),
  1529. opr::reduce_prod(iv_shape, iv_shape.make_scalar(1)));
  1530. return scale * Broadcast::make(og, GetVarShape::make(iv));
  1531. }
  1532. default:
  1533. mgb_throw(MegBrainError, "bad reduce mode");
  1534. }
  1535. }();
  1536. grad = TypeCvt::make(grad, iv.dtype());
  1537. return grad.node();
  1538. }
  1539. #endif
  1540. void Reduce::record_execute_deps(ExecDependencyArray& deps) {
  1541. record_megdnn_opr(deps);
  1542. m_kern_scheduler->record_execute_deps(deps);
  1543. }
  1544. /* =========================== PowC =========================== */
  1545. MGB_DYN_TYPE_OBJ_FINAL_IMPL(PowC);
  1546. MEGDNN_OPR_CTOR_INIT1(PowC, ssprintf("powc_%g", param.exp))
  1547. SymbolVar PowC::make(SymbolVar x, const Param& param,
  1548. const OperatorNodeConfig& config) {
  1549. if (almost_equal(param.exp, 1.f)) {
  1550. return x;
  1551. }
  1552. if (almost_equal(param.exp, 0.f)) {
  1553. return x.make_scalar_dt(1).broadcast(x.symshape());
  1554. }
  1555. return x.insert_single_output_opr<PowC>(x.node(), param, config);
  1556. }
  1557. void PowC::add_input_layout_constraint() {
  1558. input(0)->add_layout_constraint_monotone();
  1559. }
  1560. void PowC::mem_plan_fwd_in2out_writable() {
  1561. output(0)->set_fwd_in2out_writable(input(0));
  1562. }
  1563. void PowC::init_output_static_infer_desc() {
  1564. Super::init_output_static_infer_desc();
  1565. static StaticInferOpr<megdnn::PowC> static_infer_opr;
  1566. using namespace cg::static_infer;
  1567. auto infer_value = [this](DeviceTensorND& dest, const InpVal& inp) {
  1568. auto infer_opr_lock = static_infer_opr.lock();
  1569. auto&& infer_opr = infer_opr_lock();
  1570. infer_opr->param() = this->param();
  1571. auto&& ival = inp.val[0].value().as_megdnn();
  1572. infer_opr->exec(ival, dest.resize(ival.layout).as_megdnn());
  1573. return true;
  1574. };
  1575. owner_graph()->static_infer_manager().register_value_infer(
  1576. output(0),
  1577. {SourceType::DEP, {{input(0), DepType::VALUE}}, infer_value});
  1578. }
  1579. #if MGB_ENABLE_GRAD
  1580. MGB_IMPL_OPR_GRAD(PowC) {
  1581. auto exp = opr.param().exp;
  1582. return (exp * SymbolVar{out_grad[0]} *
  1583. PowC::make(opr.input(0), exp - 1, opr.config()))
  1584. .node();
  1585. }
  1586. #endif
  1587. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

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