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

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

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