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.

step_parallel.cc 92 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "parallel/step_parallel.h"
  17. #include <inttypes.h>
  18. #include <sys/time.h>
  19. #include <algorithm>
  20. #include <map>
  21. #include <memory>
  22. #include <set>
  23. #include <string>
  24. #include <unordered_map>
  25. #include <utility>
  26. #include "ir/meta_tensor.h"
  27. #include "operator/ops.h"
  28. #include "optimizer/optimizer.h"
  29. #include "parallel/auto_parallel/graph_costmodel.h"
  30. #include "parallel/context.h"
  31. #include "parallel/device_manager.h"
  32. #include "parallel/dynamic_creator.h"
  33. #include "parallel/graph_util/generate_graph.h"
  34. #include "parallel/graph_util/graph_info.h"
  35. #include "parallel/graph_util/node_info.h"
  36. #include "parallel/node_check.h"
  37. #include "parallel/ops_info/matmul_info.h"
  38. #include "parallel/strategy_checkpoint/parallel_strategy_checkpoint.h"
  39. #include "utils/comm_manager.h"
  40. #include "utils/symbolic.h"
  41. using mindspore::tensor::Tensor;
  42. namespace mindspore {
  43. namespace parallel {
  44. static const std::set<std::string> COMMUNICATION_OPS = {ALL_REDUCE, ALL_GATHER, ALL_TO_ALL, REDUCE_SCATTER};
  45. static const std::set<std::string> INVALID_LOSS_OPS = {GET_NEXT, VIRTUALLOSS};
  46. // g_RefMap, for CNode B input i is a RefKey[Parameter C],
  47. // it will be one item in map with key: C, and value: (B, i)
  48. static std::map<AnfNodePtr, std::pair<AnfNodePtr, int>> g_RefMap;
  49. void SetCommunicationOpGroupLabel(std::vector<AnfNodePtr> new_node_input) {
  50. if (new_node_input.empty()) {
  51. return;
  52. }
  53. ValueNodePtr prim_anf_node = new_node_input[0]->cast<ValueNodePtr>();
  54. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  55. MS_EXCEPTION_IF_NULL(prim);
  56. auto attrs = prim->attrs();
  57. auto iter = attrs.find(GROUP);
  58. if (iter != attrs.end()) {
  59. auto value = iter->second;
  60. MS_EXCEPTION_IF_NULL(value);
  61. if (value->isa<StringImm>()) {
  62. std::string hash_name = value->cast<StringImmPtr>()->value();
  63. MS_EXCEPTION_IF_NULL(g_device_manager);
  64. std::string rank_list_name = g_device_manager->FindRankListNameByHashName(hash_name);
  65. (void)prim->AddAttr(GROUP_RANKS, MakeValue(rank_list_name));
  66. }
  67. }
  68. }
  69. std::vector<AnfNodePtr> CreateInput(const Operator &op, const AnfNodePtr &node, const std::string &instance_name) {
  70. MS_EXCEPTION_IF_NULL(node);
  71. OperatorArgs arg_forward = op.second;
  72. ValuePtr pyop_instance = CreatOpInstance(arg_forward.first, op.first, instance_name);
  73. MS_EXCEPTION_IF_NULL(pyop_instance);
  74. OperatorParams params = arg_forward.second;
  75. std::vector<AnfNodePtr> new_node_input = {NewValueNode(pyop_instance), node};
  76. if (!params.empty()) {
  77. for (auto &param : params) {
  78. AnfNodePtr val = NewValueNode(param.first.second);
  79. MS_EXCEPTION_IF_NULL(val);
  80. int32_t position = param.second;
  81. (void)new_node_input.insert(new_node_input.begin() + position, val);
  82. }
  83. }
  84. // if the op have 'group' attr, set the rank list name for the op
  85. SetCommunicationOpGroupLabel(new_node_input);
  86. return new_node_input;
  87. }
  88. void InsertNode(const Operator &op, const CNodePtr &node, size_t index, const AnfNodePtr &pre_node,
  89. const FuncGraphPtr &func_graph, const std::string &instance_name) {
  90. // insert new node before the node
  91. FuncGraphManagerPtr manager = func_graph->manager();
  92. MS_EXCEPTION_IF_NULL(manager);
  93. ScopePtr scope = node->scope();
  94. MS_EXCEPTION_IF_NULL(scope);
  95. std::vector<AnfNodePtr> node_input = CreateInput(op, pre_node, instance_name);
  96. CNodePtr new_node = func_graph->NewCNode(node_input);
  97. MS_EXCEPTION_IF_NULL(new_node);
  98. if (instance_name.find(SPLIT_SENS) == std::string::npos) {
  99. new_node->set_in_forward_flag(true); // mark forward flag
  100. }
  101. auto new_node_value = node_input[0]->cast<ValueNodePtr>();
  102. MS_EXCEPTION_IF_NULL(new_node_value);
  103. PrimitivePtr new_node_prim = new_node_value->value()->cast<PrimitivePtr>();
  104. new_node_prim->set_instance_name(instance_name);
  105. new_node_prim->set_attr("keep_value_node_input", MakeValue(true));
  106. new_node->set_scope(scope);
  107. node_input[0]->set_scope(scope);
  108. manager->SetEdge(node, SizeToInt(index), new_node);
  109. }
  110. std::string CreateInstanceName(const CNodePtr &node, size_t index) {
  111. MS_EXCEPTION_IF_NULL(node);
  112. if (!IsValueNode<Primitive>(node->input(0))) {
  113. MS_LOG(EXCEPTION) << "CreateInstanceName: " << node->ToString() << " doesn't have primitive";
  114. }
  115. std::string name_base = node->fullname_with_scope();
  116. std::string name = name_base + "_" + std::to_string(index);
  117. std::string instance_name = HashInstanceName(name);
  118. return instance_name;
  119. }
  120. void ForwardCommunication(OperatorVector forward_op, const CNodePtr &node) {
  121. MS_EXCEPTION_IF_NULL(node);
  122. // step1:get graph manager distribute_operator
  123. FuncGraphPtr func_graph = node->func_graph();
  124. MS_EXCEPTION_IF_NULL(func_graph);
  125. FuncGraphManagerPtr manager = func_graph->manager();
  126. MS_EXCEPTION_IF_NULL(manager);
  127. auto uses_set = manager->node_users()[node];
  128. CNodePtr node_to_insert = node;
  129. for (auto &uses_pair : uses_set) {
  130. auto uses_cnode = uses_pair.first->cast<CNodePtr>();
  131. MS_EXCEPTION_IF_NULL(uses_cnode);
  132. if (!IsValueNode<Primitive>(uses_cnode->input(0))) {
  133. break;
  134. }
  135. PrimitivePtr value_node_prim = GetValueNode<PrimitivePtr>(uses_cnode->input(0));
  136. MS_EXCEPTION_IF_NULL(value_node_prim);
  137. if (value_node_prim->name() == TUPLE_GETITEM) {
  138. if (uses_set.size() > 1) {
  139. MS_LOG(EXCEPTION) << "Now only support one output, but got " << uses_set.size();
  140. }
  141. node_to_insert = uses_cnode;
  142. }
  143. }
  144. MS_EXCEPTION_IF_NULL(node_to_insert);
  145. std::reverse(forward_op.begin(), forward_op.end());
  146. // step2:traverse op_list and insert node
  147. for (size_t index = 0; index < forward_op.size(); ++index) {
  148. std::string instance_name_base = FORWARD_OP;
  149. std::string instance_name = instance_name_base + "_" + CreateInstanceName(node, index);
  150. std::vector<AnfNodePtr> forward_input = CreateInput(forward_op[index], node_to_insert, instance_name);
  151. CNodePtr forward_node = func_graph->NewCNode(forward_input); // using NewCNode to creat anfnode
  152. MS_EXCEPTION_IF_NULL(forward_node);
  153. ScopePtr scope = node->scope();
  154. MS_EXCEPTION_IF_NULL(scope);
  155. forward_node->set_scope(scope);
  156. forward_node->set_in_forward_flag(true);
  157. forward_input[0]->set_scope(scope);
  158. (void)manager->Replace(node_to_insert, forward_node); // using Replace function to insert node
  159. }
  160. }
  161. CNodePtr InsertMakeTuple(const AnfNodePtr &prev, uint32_t num, const FuncGraphPtr &func_graph) {
  162. MS_EXCEPTION_IF_NULL(prev);
  163. MS_EXCEPTION_IF_NULL(func_graph);
  164. std::vector<AnfNodePtr> make_tuple_inputs;
  165. make_tuple_inputs.push_back(NewValueNode(prim::kPrimMakeTuple));
  166. for (uint32_t i = 0; i < num; i++) {
  167. std::vector<AnfNodePtr> tuple_get_item_inputs{NewValueNode(prim::kPrimTupleGetItem), prev,
  168. CreatInt32Imm(UintToInt(i))};
  169. auto tuple_get_item = func_graph->NewCNode(tuple_get_item_inputs);
  170. MS_EXCEPTION_IF_NULL(tuple_get_item);
  171. make_tuple_inputs.push_back(tuple_get_item);
  172. }
  173. auto make_tuple = func_graph->NewCNode(make_tuple_inputs);
  174. MS_EXCEPTION_IF_NULL(make_tuple);
  175. FuncGraphManagerPtr manager = func_graph->manager();
  176. MS_EXCEPTION_IF_NULL(manager);
  177. (void)manager->Replace(prev, make_tuple);
  178. return make_tuple;
  179. }
  180. void InsertRedistribution(const RedistributionOpListPtr &redistribution_oplist_ptr, const CNodePtr &node,
  181. const FuncGraphPtr &func_graph, int pos, const CNodePtr &pre_node) {
  182. MS_EXCEPTION_IF_NULL(node);
  183. MS_EXCEPTION_IF_NULL(pre_node);
  184. MS_EXCEPTION_IF_NULL(func_graph);
  185. FuncGraphManagerPtr manager = func_graph->manager();
  186. MS_EXCEPTION_IF_NULL(manager);
  187. if ((redistribution_oplist_ptr->first).size() != (redistribution_oplist_ptr->second).size()) {
  188. MS_LOG(EXCEPTION) << "size of OperatorVector and OutPutInfoVector must be the same!";
  189. }
  190. for (size_t index = 0; index < (redistribution_oplist_ptr->first).size(); ++index) {
  191. if (pos >= SizeToInt(node->inputs().size())) {
  192. MS_LOG(EXCEPTION) << "InsertRedistribution:pos can't be larger than node's inputs'size";
  193. }
  194. // Creat new node
  195. AnfNodePtr target_node = node->input(IntToSize(pos));
  196. MS_EXCEPTION_IF_NULL(target_node);
  197. // Creat instance_name
  198. auto op = (redistribution_oplist_ptr->first)[index];
  199. std::string op_name = (redistribution_oplist_ptr->first)[index].first;
  200. std::string instance_name_base = REDISTRIBUTION_OP;
  201. std::string instance_name = instance_name_base + "_" + CreateInstanceName(pre_node, index) + op_name;
  202. InsertNode(op, node, IntToSize(pos), target_node, func_graph, instance_name);
  203. if ((redistribution_oplist_ptr->second)[index].first) {
  204. target_node = node->input(IntToSize(pos));
  205. MS_EXCEPTION_IF_NULL(target_node);
  206. (void)InsertMakeTuple(target_node, (redistribution_oplist_ptr->second)[index].second, func_graph);
  207. }
  208. }
  209. }
  210. void InsertGetTensorSliceOp(const Operator &op, const CNodePtr &node, const FuncGraphPtr &func_graph, int pos,
  211. const std::string &instance_name) {
  212. if (func_graph == nullptr) {
  213. MS_LOG(EXCEPTION) << "InsertGetTensorSliceOp: the graph is null, the instance name is " << instance_name;
  214. }
  215. FuncGraphManagerPtr manager = func_graph->manager();
  216. MS_EXCEPTION_IF_NULL(manager);
  217. if (pos >= SizeToInt(node->inputs().size())) {
  218. MS_LOG(EXCEPTION) << "InsertGetTensorSliceOp: pos can't be larger than node's inputs'size, the instance name is "
  219. << instance_name;
  220. }
  221. // Creat new node
  222. AnfNodePtr pre_node = node->input(IntToSize(pos));
  223. MS_EXCEPTION_IF_NULL(pre_node);
  224. InsertNode(op, node, IntToSize(pos), pre_node, func_graph, instance_name);
  225. }
  226. TensorLayout GetTensorInLayout(const CNodePtr &middle_node, const PrimitivePtr &middle_prim,
  227. const OperatorInfoPtr &distribute_operator) {
  228. TensorInfo tensorinfo_in;
  229. if (middle_prim->name() == TUPLE_GETITEM) {
  230. auto value_node = middle_node->input(2)->cast<ValueNodePtr>();
  231. MS_EXCEPTION_IF_NULL(value_node);
  232. size_t index_s = IntToSize(GetValue<int>(value_node->value()));
  233. if (index_s >= distribute_operator->outputs_tensor_info().size()) {
  234. MS_LOG(EXCEPTION) << "The index out of range, index: " << index_s
  235. << ", vector size: " << distribute_operator->outputs_tensor_info().size();
  236. }
  237. tensorinfo_in = distribute_operator->outputs_tensor_info()[index_s];
  238. } else {
  239. if (distribute_operator->outputs_tensor_info().empty()) {
  240. MS_LOG(EXCEPTION) << "The outputs tensor info is empty";
  241. }
  242. tensorinfo_in = distribute_operator->outputs_tensor_info()[0];
  243. }
  244. return tensorinfo_in.tensor_layout();
  245. }
  246. OperatorInfoPtr GetDistributeOperator(const CNodePtr &node) {
  247. MS_EXCEPTION_IF_NULL(node);
  248. if (!IsParallelCareNode(node)) {
  249. return nullptr;
  250. }
  251. OperatorInfoPtr distribute_operator = node->operator_info();
  252. if (distribute_operator == nullptr) {
  253. MS_LOG(EXCEPTION) << "GetDistributeOperator:distribute_operator is nullptr";
  254. }
  255. return distribute_operator;
  256. }
  257. void Redistribution(const std::pair<AnfNodePtr, int> &node_pair, const OperatorInfoPtr &distribute_operator,
  258. const CNodePtr &middle_node, int index, TensorRedistribution tensor_redistribution,
  259. const CNodePtr &pre_node) {
  260. FuncGraphPtr func_graph = middle_node->func_graph();
  261. if (func_graph == nullptr) {
  262. MS_LOG(EXCEPTION) << "Redistribution:get graph failed";
  263. }
  264. CNodePtr next_node = node_pair.first->cast<CNodePtr>();
  265. MS_EXCEPTION_IF_NULL(next_node);
  266. auto middle_value = middle_node->input(0)->cast<ValueNodePtr>();
  267. MS_EXCEPTION_IF_NULL(middle_value);
  268. PrimitivePtr middle_prim = middle_value->value()->cast<PrimitivePtr>();
  269. MS_EXCEPTION_IF_NULL(middle_prim);
  270. OperatorInfoPtr next_distribute_operator = GetDistributeOperator(next_node);
  271. if (next_distribute_operator == nullptr) {
  272. MS_LOG(EXCEPTION) << "Failure: " << next_node->ToString() << " GetDistributeOperator failed";
  273. }
  274. RankList dev_list = distribute_operator->global_device_list();
  275. std::string next_prim_name = GetValueNode<PrimitivePtr>(next_node->input(0))->name();
  276. MS_LOG(DEBUG) << "Redistribution: middle_prim " << middle_prim->name() << " next_prim " << next_prim_name;
  277. MS_LOG(DEBUG) << "Redistribution: middle_node " << middle_node->ToString() << " next_node " << next_node->ToString();
  278. // extract tensor layout in and out
  279. if (distribute_operator->outputs_tensor_info().empty()) {
  280. MS_LOG(EXCEPTION) << "Failure:pre_node's tensorinfo_in is empty";
  281. }
  282. if (IntToSize(index - 1) >= next_distribute_operator->inputs_tensor_info().size()) {
  283. MS_LOG(EXCEPTION) << "The index is out of range, the index is " << index - 1 << ", the vector size is "
  284. << next_distribute_operator->inputs_tensor_info().size();
  285. }
  286. TensorInfo tensorinfo_out = next_distribute_operator->inputs_tensor_info()[IntToSize(index - 1)];
  287. TensorLayout tensorlayout_out = tensorinfo_out.tensor_layout();
  288. TensorLayout tensorlayout_in = GetTensorInLayout(middle_node, middle_prim, distribute_operator);
  289. if (tensor_redistribution.Init(tensorlayout_in, tensorlayout_out, dev_list) == FAILED) {
  290. MS_LOG(ERROR) << "Redistribution: middle_prim " << middle_prim->name() << " next_prim : " << next_prim_name;
  291. MS_LOG(ERROR) << "Redistribution: middle_node " << middle_node->ToString() << " next_node "
  292. << next_node->ToString();
  293. DumpGraph(func_graph, "redistribution_error");
  294. MS_LOG(EXCEPTION) << "Failure:tensor_redistribution init failed";
  295. }
  296. RedistributionOpListPtr redistribution_oplist_ptr = tensor_redistribution.InferTensorRedistributionOperatorList();
  297. if (redistribution_oplist_ptr == nullptr) {
  298. MS_LOG(EXCEPTION) << "Failure:InferTensorRedistribution failed";
  299. }
  300. MS_LOG(DEBUG) << "Redistribution size " << redistribution_oplist_ptr->first.size();
  301. if (!redistribution_oplist_ptr->first.empty()) {
  302. // insert node before next node
  303. InsertRedistribution(redistribution_oplist_ptr, next_node, func_graph, node_pair.second, pre_node);
  304. }
  305. }
  306. bool StrategyFound(std::unordered_map<std::string, ValuePtr> attrs) {
  307. auto iter = attrs.find(STRATEGY);
  308. return !((iter == attrs.end()) || (iter->second->type_name() == NONE));
  309. }
  310. bool IsCommunicationOp(const PrimitivePtr &prim) {
  311. MS_EXCEPTION_IF_NULL(prim);
  312. return (COMMUNICATION_OPS.find(prim->name()) != COMMUNICATION_OPS.end());
  313. }
  314. bool FindCommunicationOp(const std::vector<AnfNodePtr> &all_nodes) {
  315. for (auto &node : all_nodes) {
  316. MS_EXCEPTION_IF_NULL(node);
  317. if (!node->isa<CNode>()) {
  318. continue;
  319. }
  320. auto cnode = node->cast<CNodePtr>();
  321. MS_EXCEPTION_IF_NULL(cnode);
  322. if (!IsValueNode<Primitive>(cnode->input(0))) {
  323. continue;
  324. }
  325. ValueNodePtr prim_value_node = cnode->input(0)->cast<ValueNodePtr>();
  326. MS_EXCEPTION_IF_NULL(prim_value_node);
  327. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_value_node);
  328. MS_EXCEPTION_IF_NULL(prim);
  329. if (IsCommunicationOp(prim) && cnode->in_forward_flag()) {
  330. MS_EXCEPTION_IF_NULL(prim_value_node->scope());
  331. MS_LOG(INFO) << "The graph contain communication op: " << prim->name() << ", scope name is "
  332. << prim_value_node->scope()->name();
  333. return true;
  334. }
  335. }
  336. return false;
  337. }
  338. bool IsParallelCareNode(const CNodePtr &cnode) {
  339. MS_EXCEPTION_IF_NULL(cnode);
  340. ValueNodePtr prim_node = cnode->input(0)->cast<ValueNodePtr>();
  341. if (prim_node == nullptr) {
  342. return false;
  343. }
  344. PrimitivePtr prim = prim_node->value()->cast<PrimitivePtr>();
  345. if (prim == nullptr) {
  346. return false;
  347. }
  348. if (IsInBlackList(prim)) {
  349. MS_LOG(INFO) << "Parallel don't care node: " << prim->name();
  350. return false;
  351. }
  352. // get_next is not in the forward graph, we need mark the get_next as the forward node
  353. if (prim->name() == GET_NEXT) {
  354. return true;
  355. }
  356. if ((prim->name() == CAST) && (cnode->operator_info() == nullptr)) {
  357. return false;
  358. }
  359. return cnode->in_forward_flag();
  360. }
  361. void StepRedistribution(const CNodePtr &node, const OperatorInfoPtr &distribute_operator, const CNodePtr &insert_node,
  362. const TensorRedistribution &tensor_redistribution, const CNodePtr &pre_node) {
  363. MS_EXCEPTION_IF_NULL(node->func_graph());
  364. FuncGraphManagerPtr manager = node->func_graph()->manager();
  365. MS_EXCEPTION_IF_NULL(manager);
  366. AnfNodeIndexSet node_set = manager->node_users()[node];
  367. CNodePtr insert_node_new;
  368. if (IsValueNode<Primitive>(node->input(0))) {
  369. auto current_value = node->input(0)->cast<ValueNodePtr>();
  370. MS_EXCEPTION_IF_NULL(current_value);
  371. PrimitivePtr current_prim = current_value->value()->cast<PrimitivePtr>();
  372. MS_EXCEPTION_IF_NULL(current_prim);
  373. insert_node_new = ((current_prim->name() == TUPLE_GETITEM) ? node : insert_node);
  374. } else {
  375. insert_node_new = insert_node;
  376. }
  377. MS_EXCEPTION_IF_NULL(insert_node_new);
  378. for (auto &node_pair : node_set) {
  379. CNodePtr use_cnode = node_pair.first->cast<CNodePtr>();
  380. MS_EXCEPTION_IF_NULL(use_cnode);
  381. if (!IsValueNode<Primitive>(use_cnode->input(0))) {
  382. StepRedistribution(use_cnode, distribute_operator, insert_node_new, tensor_redistribution, pre_node);
  383. } else {
  384. ValueNodePtr prim_anf_node = use_cnode->input(0)->cast<ValueNodePtr>();
  385. MS_EXCEPTION_IF_NULL(prim_anf_node);
  386. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  387. MS_EXCEPTION_IF_NULL(node_prim);
  388. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  389. continue;
  390. }
  391. if (IsParallelCareNode(use_cnode) && (use_cnode->operator_info() != nullptr)) {
  392. Redistribution(node_pair, distribute_operator, insert_node_new, node_pair.second, tensor_redistribution,
  393. pre_node);
  394. } else {
  395. StepRedistribution(use_cnode, distribute_operator, insert_node_new, tensor_redistribution, pre_node);
  396. }
  397. }
  398. }
  399. }
  400. void SplitTensor(const AnfNodePtr &node, const CNodePtr &next_node, int index) {
  401. MS_EXCEPTION_IF_NULL(node);
  402. MS_EXCEPTION_IF_NULL(next_node);
  403. OperatorInfoPtr op_info = next_node->operator_info();
  404. MS_EXCEPTION_IF_NULL(op_info);
  405. // If the shape of tensor is [] or [1], no need to split it.
  406. Shapes shapes = GetNodeShape(node);
  407. if (shapes.size() != 1) {
  408. MS_LOG(EXCEPTION) << "Split tensor for " << op_info->name()
  409. << ": GetNodeShape for tensor_node, output size is not 1";
  410. }
  411. Shape shape = shapes[0];
  412. std::string shape_str = ShapeToString(shape);
  413. if (shape.empty() || ((shape.size() == 1) && (shape[0] == 1))) {
  414. MS_LOG(INFO) << "Split tensor for " << op_info->name() << ": The shape is " << shape_str
  415. << ", no need to split it.";
  416. return;
  417. }
  418. MS_LOG(INFO) << "Split tensor for " << op_info->name() << ": The shape of tensor is " << shape_str;
  419. // extract tensor layout
  420. if (IntToSize(index - 1) >= op_info->inputs_tensor_info().size()) {
  421. MS_LOG(EXCEPTION) << "The index is out of range, index is " << index - 1 << ", vector size is "
  422. << op_info->inputs_tensor_info().size();
  423. }
  424. TensorInfo tensor_info = op_info->inputs_tensor_info()[IntToSize(index - 1)];
  425. TensorLayout tensor_layout = tensor_info.tensor_layout();
  426. // Use _GetTensorSlice operator to split the tensor
  427. FuncGraphPtr func_graph = next_node->func_graph(); // only cnode can get the graph
  428. MS_EXCEPTION_IF_NULL(func_graph);
  429. Operator op = CreateGetTensorSliceOp(tensor_layout);
  430. InsertGetTensorSliceOp(op, next_node, func_graph, index, SPLIT_TENSOR);
  431. if (!op_info->sub_ops().empty()) {
  432. auto sub_ops = op_info->sub_ops();
  433. for (size_t i = 0; i < sub_ops.size(); i++) {
  434. if (!sub_ops.at(i).empty()) {
  435. InsertGetTensorSliceOp(sub_ops.at(i).at(0), next_node, func_graph, index, SUB);
  436. }
  437. }
  438. }
  439. }
  440. void StepSplitTensor(const AnfNodePtr &node, const FuncGraphManagerPtr &manager) {
  441. MS_EXCEPTION_IF_NULL(node);
  442. MS_EXCEPTION_IF_NULL(manager);
  443. AnfNodeIndexSet node_set = manager->node_users()[node];
  444. for (auto &node_pair : node_set) {
  445. CNodePtr use_cnode = node_pair.first->cast<CNodePtr>();
  446. if (use_cnode == nullptr || !IsValueNode<Primitive>(use_cnode->input(0))) {
  447. continue;
  448. }
  449. ValueNodePtr prim_anf_node = use_cnode->input(0)->cast<ValueNodePtr>();
  450. MS_EXCEPTION_IF_NULL(prim_anf_node);
  451. PrimitivePtr use_cnode_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  452. MS_EXCEPTION_IF_NULL(use_cnode_prim);
  453. if (use_cnode_prim->name() == DEPEND && node_pair.second != 1) {
  454. continue;
  455. }
  456. if (IsParallelCareNode(use_cnode)) {
  457. SplitTensor(node, use_cnode, node_pair.second);
  458. }
  459. }
  460. }
  461. std::vector<AnfNodePtr> ReplaceOpInput(const Operator &replace_op, const std::string &instance_name,
  462. const CNodePtr &node) {
  463. OperatorArgs arg_replace_op = replace_op.second;
  464. ValuePtr pyop_instance = CreatOpInstance(arg_replace_op.first, replace_op.first, instance_name);
  465. if (pyop_instance == nullptr) {
  466. MS_LOG(EXCEPTION) << "Failure: " << replace_op.first << " CreatOpInstance failed";
  467. }
  468. OperatorParams params = arg_replace_op.second;
  469. if (node->inputs().size() < 2) {
  470. // GetNext operator dose not has input
  471. if (node->inputs().size() == 1) {
  472. return {NewValueNode(pyop_instance)};
  473. }
  474. MS_LOG(EXCEPTION) << "Failure: " << node->ToString() << " size is smaller than 2";
  475. }
  476. std::vector<AnfNodePtr> replace_input = {NewValueNode(pyop_instance), node->input(1)};
  477. if (!params.empty()) {
  478. Param param_first = *(params.begin());
  479. int32_t first_position = param_first.second;
  480. if (first_position == 1) {
  481. replace_input.pop_back();
  482. }
  483. for (auto &param : params) {
  484. AnfNodePtr val = NewValueNode(param.first.second);
  485. if (val == nullptr) {
  486. MS_LOG(EXCEPTION) << "Failure:val is nullptr";
  487. }
  488. int32_t position = param.second;
  489. (void)replace_input.insert(replace_input.begin() + position, val);
  490. }
  491. }
  492. return replace_input;
  493. }
  494. void ReplaceOneOp(const Operator &replace_op, const CNodePtr &node) {
  495. FuncGraphPtr func_graph = node->func_graph();
  496. MS_EXCEPTION_IF_NULL(func_graph);
  497. FuncGraphManagerPtr manager = func_graph->manager();
  498. if (manager == nullptr) {
  499. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  500. }
  501. std::string instance_name = CreateInstanceName(node, 0);
  502. std::vector<AnfNodePtr> replace_input;
  503. replace_input = ReplaceOpInput(replace_op, instance_name, node);
  504. CNodePtr replace_node = func_graph->NewCNode(replace_input);
  505. MS_EXCEPTION_IF_NULL(replace_node);
  506. ScopePtr scope = node->scope();
  507. MS_EXCEPTION_IF_NULL(scope);
  508. replace_node->set_scope(scope);
  509. replace_node->set_in_forward_flag(true);
  510. replace_input[0]->set_scope(scope);
  511. (void)manager->Replace(node, replace_node);
  512. }
  513. void StepReplaceOp(OperatorVector replace_op, const CNodePtr &node) {
  514. // step1:get graph manager distribute_operator
  515. OperatorInfoPtr distribute_operator = node->operator_info();
  516. if (distribute_operator == nullptr) {
  517. MS_LOG(EXCEPTION) << "Failure:AddNode error since distribute_operator is nullptr";
  518. }
  519. FuncGraphPtr func_graph = node->func_graph();
  520. MS_EXCEPTION_IF_NULL(func_graph);
  521. FuncGraphManagerPtr manager = func_graph->manager();
  522. if (manager == nullptr) {
  523. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  524. }
  525. // step2:traverse op_list and insert node
  526. std::reverse(replace_op.begin(), replace_op.end());
  527. auto replace_op_info = distribute_operator->replace_op_info();
  528. std::reverse(replace_op_info.begin(), replace_op_info.end());
  529. if (!replace_op_info.empty() && replace_op_info.size() != replace_op.size()) {
  530. MS_LOG(EXCEPTION) << "replace_op_info is not empty and size not equal to replace_op!";
  531. }
  532. bool replace_op_info_flag = !replace_op_info.empty();
  533. for (size_t index = 0; index < replace_op.size(); ++index) {
  534. std::string instance_name = CreateInstanceName(node, index);
  535. std::vector<AnfNodePtr> replace_input;
  536. if (index != replace_op.size() - 1) {
  537. replace_input = CreateInput(replace_op[index], node, instance_name);
  538. } else {
  539. replace_input = ReplaceOpInput(replace_op[index], instance_name, node);
  540. }
  541. CNodePtr replace_node = func_graph->NewCNode(replace_input);
  542. MS_EXCEPTION_IF_NULL(replace_node);
  543. ScopePtr scope = node->scope();
  544. MS_EXCEPTION_IF_NULL(scope);
  545. replace_node->set_scope(scope);
  546. if (index == replace_op.size() - 1) {
  547. (void)replace_node->set_operator_info(node->operator_info());
  548. }
  549. replace_node->set_in_forward_flag(true);
  550. replace_input[0]->set_scope(scope);
  551. if (replace_op_info_flag && replace_op_info[index].first) {
  552. auto new_cnode = InsertMakeTuple(replace_node, replace_op_info[index].second, func_graph);
  553. (void)manager->Replace(node, new_cnode); // using Replace function to insert node
  554. } else {
  555. (void)manager->Replace(node, replace_node); // using Replace function to insert node
  556. }
  557. }
  558. MS_LOG(INFO) << "Insert ReplaceOp success for " << distribute_operator->name();
  559. }
  560. bool IsSomePrimitive(const CNodePtr &cnode, const std::string &name) {
  561. ValueNodePtr anf_node = cnode->input(0)->cast<ValueNodePtr>();
  562. MS_EXCEPTION_IF_NULL(anf_node);
  563. PrimitivePtr prim = anf_node->value()->cast<PrimitivePtr>();
  564. return (prim->name() == name);
  565. }
  566. void StepReplaceGraph(const std::shared_ptr<std::pair<std::vector<AnfNodePtr>, AnfNodePtr>> &replace_graph,
  567. const CNodePtr &node) {
  568. MS_EXCEPTION_IF_NULL(replace_graph);
  569. MS_EXCEPTION_IF_NULL(node);
  570. MS_EXCEPTION_IF_NULL(replace_graph->second);
  571. FuncGraphPtr func_graph = node->func_graph();
  572. MS_EXCEPTION_IF_NULL(func_graph);
  573. FuncGraphManagerPtr manager = func_graph->manager();
  574. if (manager == nullptr) {
  575. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  576. }
  577. if (!IsSomePrimitive(node, ONEHOT)) {
  578. MS_LOG(EXCEPTION) << "Failure:Only OneHot Primitive will enter StepReplaceGraph!";
  579. }
  580. if (node->inputs().size() != 5) {
  581. MS_LOG(EXCEPTION) << "Failure:There is 5 inputs for the CNode corresponding to OneHot Primitive!";
  582. }
  583. auto pre_node = node->input(1);
  584. if (replace_graph->first.size() != 2) {
  585. MS_LOG(EXCEPTION) << "Failure:replace_graph->first.size() must be 2 for OneHot Primitive!";
  586. }
  587. for (auto &replace_input : replace_graph->first) {
  588. MS_EXCEPTION_IF_NULL(replace_input);
  589. manager->SetEdge(replace_input, 1, pre_node);
  590. CNodePtr replace_input_cnode = replace_input->cast<CNodePtr>();
  591. MS_EXCEPTION_IF_NULL(replace_input_cnode);
  592. (void)replace_input_cnode->set_operator_info(node->operator_info());
  593. replace_input_cnode->set_in_forward_flag(true); // mark this new cnode is forward node
  594. }
  595. // "(void)manager->Replace(replace_graph->first, pre_node);" can not be called
  596. auto replace_output = replace_graph->second;
  597. MS_EXCEPTION_IF_NULL(replace_output);
  598. (void)manager->Replace(node, replace_output);
  599. CNodePtr replace_output_cnode = replace_graph->second->cast<CNodePtr>();
  600. MS_EXCEPTION_IF_NULL(replace_output_cnode);
  601. (void)replace_output_cnode->set_operator_info(node->operator_info());
  602. replace_output_cnode->set_in_forward_flag(true); // mark this new cnode is forward node
  603. }
  604. int32_t GetTupleGetItemIndex(const CNodePtr &cnode) {
  605. MS_EXCEPTION_IF_NULL(cnode);
  606. if (cnode->inputs().size() != 3) {
  607. MS_LOG(EXCEPTION) << cnode->ToString() << " size( " << cnode->inputs().size() << " ) is not 3";
  608. }
  609. if (!cnode->input(2)->isa<ValueNode>()) {
  610. MS_LOG(EXCEPTION) << "The index of tuple getitem is not a value node";
  611. }
  612. ValuePtr tuple_index_value = GetValueNode(cnode->input(2));
  613. MS_EXCEPTION_IF_NULL(tuple_index_value);
  614. if (!tuple_index_value->isa<Int32Imm>()) {
  615. MS_LOG(EXCEPTION) << "The index of tuple getitem is not int32";
  616. }
  617. return tuple_index_value->cast<Int32ImmPtr>()->value();
  618. }
  619. // Judge whether the node is a loss, and if there are multiple outputs,
  620. // get which output is a grad according to the tuple getitem.
  621. // Currently, it is not supported that the sens is a tuple.
  622. LossNodeInfo GetLossNodeInfo(const AnfNodePtr &loss_node) {
  623. MS_EXCEPTION_IF_NULL(loss_node);
  624. FuncGraphPtr sub_graph = loss_node->func_graph();
  625. MS_EXCEPTION_IF_NULL(sub_graph);
  626. CNodePtr return_node = sub_graph->get_return();
  627. MS_EXCEPTION_IF_NULL(return_node);
  628. if (return_node->inputs().size() < 2) {
  629. MS_LOG(EXCEPTION) << "Failure: " << return_node->ToString() << " size is smaller than 2";
  630. }
  631. AnfNodePtr pre_node = return_node->input(1);
  632. MS_EXCEPTION_IF_NULL(pre_node);
  633. LossNodeInfo node_info;
  634. // return -> cast
  635. auto pre_cnode = pre_node->cast<CNodePtr>();
  636. MS_EXCEPTION_IF_NULL(pre_cnode);
  637. auto pre_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  638. if (pre_prim->name() == CAST && pre_cnode->operator_info() == nullptr) {
  639. pre_node = pre_cnode->input(1);
  640. }
  641. // return -> loss
  642. if (pre_node == loss_node) {
  643. node_info.has_tuple_getitem = false;
  644. node_info.dout_index = 0;
  645. return node_info;
  646. }
  647. // return -> tuple_getitem -> loss
  648. auto cnode = pre_node->cast<CNodePtr>();
  649. MS_EXCEPTION_IF_NULL(cnode);
  650. auto current_value = cnode->input(0)->cast<ValueNodePtr>();
  651. MS_EXCEPTION_IF_NULL(current_value);
  652. PrimitivePtr current_prim = current_value->value()->cast<PrimitivePtr>();
  653. MS_EXCEPTION_IF_NULL(current_prim);
  654. // size of common cnode is larger than 1
  655. if (cnode->inputs().size() < 2) {
  656. MS_LOG(EXCEPTION) << cnode->ToString() << " size( " << cnode->inputs().size() << " ) is smaller than 2";
  657. }
  658. if ((current_prim->name() == TUPLE_GETITEM) && (cnode->input(1) == loss_node)) {
  659. // size of tuple_getitem cnode is 3
  660. auto tuple_index = GetTupleGetItemIndex(cnode);
  661. node_info.has_tuple_getitem = true;
  662. node_info.dout_index = tuple_index;
  663. return node_info;
  664. }
  665. MS_LOG(EXCEPTION) << "Invalid loss";
  666. }
  667. void InsertVirtualDivOp(const VirtualDivOp &virtual_div_op, const CNodePtr &node) {
  668. MS_EXCEPTION_IF_NULL(node);
  669. size_t node_size = node->inputs().size();
  670. FuncGraphPtr func_graph = node->func_graph();
  671. MS_EXCEPTION_IF_NULL(func_graph);
  672. FuncGraphManagerPtr manager = func_graph->manager();
  673. MS_EXCEPTION_IF_NULL(manager);
  674. for (size_t index = 1; index < node_size; ++index) {
  675. AnfNodePtr input = node->input(index);
  676. MS_EXCEPTION_IF_NULL(input);
  677. if (!input->isa<CNode>() && !input->isa<Parameter>()) { // if it is not a tensor, continue
  678. MS_LOG(INFO) << "insert div op: the index " << index << " is not tensor, skip";
  679. continue;
  680. }
  681. for (size_t pos = 0; pos < virtual_div_op.size(); ++pos) {
  682. std::string instance_name = CreateInstanceName(node, pos);
  683. InsertNode(virtual_div_op[pos], node, index, node->input(index), func_graph, instance_name);
  684. }
  685. MS_LOG(INFO) << "insert div op for input index " << index << " of node";
  686. }
  687. }
  688. std::pair<AnfNodePtr, bool> FindParameter(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  689. if (!node->isa<Parameter>() && !node->isa<CNode>() && !node->isa<ValueNode>()) {
  690. return std::make_pair(nullptr, false);
  691. } else if (node->isa<Parameter>()) {
  692. return std::make_pair(node, false);
  693. } else if (node->isa<ValueNode>()) {
  694. if (IsValueNode<RefKey>(node)) {
  695. std::vector<AnfNodePtr> param_v = FindParameterByRefKeyNode(node, func_graph);
  696. if (param_v.size() != 1) {
  697. MS_LOG(EXCEPTION) << "FindParameterByRefKeyNode failed, return vector size must be 1, real is "
  698. << param_v.size();
  699. }
  700. return std::make_pair(node, true);
  701. }
  702. return std::make_pair(nullptr, false);
  703. } else {
  704. CNodePtr cnode = node->cast<CNodePtr>();
  705. MS_EXCEPTION_IF_NULL(cnode);
  706. if (!IsValueNode<Primitive>(cnode->input(0))) {
  707. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  708. if (!FindParameter(cnode->input(index), func_graph).first) {
  709. continue;
  710. }
  711. return FindParameter(cnode->input(index), func_graph);
  712. }
  713. } else {
  714. if (IsParallelCareNode(cnode)) {
  715. return std::make_pair(nullptr, false);
  716. } else {
  717. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  718. MS_EXCEPTION_IF_NULL(prim_anf_node);
  719. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  720. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  721. MS_EXCEPTION_IF_NULL(prim);
  722. if (prim->name() == DEPEND && index != 1) {
  723. continue;
  724. }
  725. if (!FindParameter(cnode->input(index), func_graph).first) {
  726. continue;
  727. }
  728. return FindParameter(cnode->input(index), func_graph);
  729. }
  730. }
  731. }
  732. }
  733. return std::make_pair(nullptr, false);
  734. }
  735. std::pair<bool, CNodePtr> FindCNode(const AnfNodePtr &anode, const std::string &name, const FuncGraphPtr &func_graph) {
  736. MS_EXCEPTION_IF_NULL(anode);
  737. MS_EXCEPTION_IF_NULL(anode->func_graph());
  738. FuncGraphManagerPtr manager = anode->func_graph()->manager();
  739. MS_EXCEPTION_IF_NULL(manager);
  740. AnfNodeIndexSet node_set = manager->node_users()[anode];
  741. bool result = false;
  742. CNodePtr cnode_return = nullptr;
  743. for (auto &node_pair : node_set) {
  744. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  745. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  746. continue;
  747. }
  748. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  749. MS_EXCEPTION_IF_NULL(prim_anf_node);
  750. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  751. MS_EXCEPTION_IF_NULL(node_prim);
  752. if (node_prim->name() == name && node_pair.second == 1) {
  753. if (use_apply->func_graph() == func_graph) {
  754. result = true;
  755. cnode_return = use_apply;
  756. MS_LOG(INFO) << "Find Primitive " << name << " in the same func_graph";
  757. continue;
  758. }
  759. MS_LOG(INFO) << "Find Primitive " << name << " in different func_graph";
  760. }
  761. }
  762. return std::make_pair(result, cnode_return);
  763. }
  764. bool IsCastBeforMirror(const CNodePtr &node, size_t index) {
  765. // only if cast_before_mirror is true, pre node is cast and type is not float32 return true
  766. if (!ParallelContext::GetInstance()->cast_before_mirror()) {
  767. return false;
  768. }
  769. auto pre_node = node->input(index);
  770. MS_EXCEPTION_IF_NULL(pre_node);
  771. auto cnode = pre_node->cast<CNodePtr>();
  772. if (cnode == nullptr || !IsValueNode<Primitive>(cnode->input(0))) {
  773. return false;
  774. }
  775. auto pre_value_node = cnode->input(0)->cast<ValueNodePtr>();
  776. MS_EXCEPTION_IF_NULL(pre_value_node);
  777. auto pre_prim = pre_value_node->value()->cast<PrimitivePtr>();
  778. MS_EXCEPTION_IF_NULL(pre_prim);
  779. if (pre_prim->name() != CAST) {
  780. return false;
  781. }
  782. auto node_type = pre_node->Type();
  783. MS_EXCEPTION_IF_NULL(node_type);
  784. if (!node_type->isa<mindspore::TensorType>()) {
  785. MS_LOG(EXCEPTION) << "Unknown type.";
  786. }
  787. auto input_element_type = node_type->cast<mindspore::TensorTypePtr>()->element();
  788. MS_EXCEPTION_IF_NULL(input_element_type);
  789. auto type_id = input_element_type->type_id();
  790. return (type_id != kNumberTypeFloat32);
  791. }
  792. void InsertMirrorOps(const MirrorOps &mirror_ops, const CNodePtr &node) {
  793. MS_EXCEPTION_IF_NULL(node);
  794. size_t node_size = node->inputs().size();
  795. FuncGraphPtr func_graph = node->func_graph();
  796. MS_EXCEPTION_IF_NULL(func_graph);
  797. FuncGraphManagerPtr manager = func_graph->manager();
  798. MS_EXCEPTION_IF_NULL(manager);
  799. if (mirror_ops.size() != node_size - 1) {
  800. MS_LOG(EXCEPTION) << "Failure:Mirrorops's size is wrong! mirror_ops size is " << mirror_ops.size()
  801. << ", node_size is " << node_size;
  802. }
  803. for (size_t index = 1; index < node_size; ++index) {
  804. OperatorVector backward_op = mirror_ops[index - 1];
  805. if (backward_op.empty()) {
  806. continue;
  807. }
  808. std::pair<AnfNodePtr, bool> param_node_pair = FindParameter(node->input(index), func_graph);
  809. if (!param_node_pair.first) {
  810. continue;
  811. }
  812. // not a RefKey
  813. if (!param_node_pair.second) {
  814. auto next_cnode = FindCNode(param_node_pair.first, MIRROR_OPERATOR, func_graph);
  815. // if there is already a MirrorOp in the same graph, use MirrorOp CNode as a input instead
  816. if (next_cnode.first) {
  817. MS_EXCEPTION_IF_NULL(next_cnode.second);
  818. manager->SetEdge(node, SizeToInt(index), next_cnode.second);
  819. continue;
  820. }
  821. }
  822. // if the parameter found is a RefKey, or no MirrorOp is found in the same graph, insert a new MirrorOp
  823. // only one MirrorOp in backward_op
  824. if (backward_op.size() != 1) {
  825. MS_LOG(EXCEPTION) << "backward_op size must be 1, real is " << backward_op.size();
  826. }
  827. std::string instance_name = MIRROR_OP;
  828. if (IsCastBeforMirror(node, index)) {
  829. for (auto &op : backward_op) {
  830. // insert new node before the node
  831. CNodePtr cnode = node->input(index)->cast<CNodePtr>();
  832. MS_EXCEPTION_IF_NULL(cnode);
  833. AnfNodePtr pre_node = cnode->input(1);
  834. InsertNode(op, cnode, size_t(1), pre_node, func_graph, instance_name);
  835. }
  836. } else {
  837. for (auto &op : backward_op) {
  838. AnfNodePtr pre_node = node->input(index);
  839. InsertNode(op, node, index, pre_node, func_graph, instance_name);
  840. }
  841. }
  842. }
  843. }
  844. void BackwardCommunication(const OperatorInfoPtr &distribute_operator, const CNodePtr &node, bool is_loss_node) {
  845. MS_EXCEPTION_IF_NULL(distribute_operator);
  846. MS_EXCEPTION_IF_NULL(node);
  847. MirrorOps mirror_ops = distribute_operator->mirror_ops();
  848. VirtualDivOp virtual_div_op = distribute_operator->virtual_div_op();
  849. // insert mirror op
  850. if (!mirror_ops.empty()) {
  851. MS_LOG(INFO) << "insert mirror op for " << distribute_operator->name();
  852. InsertMirrorOps(mirror_ops, node);
  853. }
  854. // insert virtual div op
  855. if (!virtual_div_op.empty() && is_loss_node) {
  856. MS_LOG(INFO) << "insert virtual div op for " << distribute_operator->name();
  857. InsertVirtualDivOp(virtual_div_op, node);
  858. }
  859. }
  860. std::string GetDisOpName(const std::string &prim_name) {
  861. std::string op_name = prim_name;
  862. if (!prim_name.empty() && (prim_name[0] == '_')) {
  863. op_name = prim_name.substr(1);
  864. }
  865. return op_name + "Info";
  866. }
  867. OperatorInfoPtr OperatorInstanceByName(const std::string &name, const PrimitiveAttrs &attrs,
  868. const std::vector<Shapes> &shape_list) {
  869. if (shape_list.size() != 2) {
  870. MS_LOG(ERROR) << "The size of shape list is not 2";
  871. return nullptr;
  872. }
  873. if (name.length() == 0) {
  874. MS_LOG(EXCEPTION) << "Length of name is zero!";
  875. }
  876. std::string distribute_opname = GetDisOpName(name);
  877. OperatorInfoPtr operator_ =
  878. (OperatorInfoPtr)DynCreator::Instance().Creat(distribute_opname, shape_list[0], shape_list[1], attrs, TOTAL_OPS);
  879. if (operator_ == nullptr) {
  880. MS_LOG(INFO) << "Creat " << name << " failed";
  881. return nullptr;
  882. }
  883. std::string origin_name = operator_->name();
  884. operator_->set_name(origin_name + std::to_string(TOTAL_OPS));
  885. MS_LOG(INFO) << "Successfully created operator " << origin_name;
  886. ++TOTAL_OPS;
  887. return operator_;
  888. }
  889. OperatorInfoPtr OperatorInstance(const PrimitivePtr &prim, const PrimitiveAttrs &attrs,
  890. const std::vector<Shapes> &shape_list) {
  891. MS_EXCEPTION_IF_NULL(prim);
  892. OperatorInfoPtr operator_ = OperatorInstanceByName(prim->name(), attrs, shape_list);
  893. if (operator_ == nullptr) {
  894. MS_LOG(INFO) << "Creat " << prim->name() << " failed, use batch parallel";
  895. operator_ = OperatorInstanceByName(BATCH_PARALLEL, attrs, shape_list);
  896. MS_EXCEPTION_IF_NULL(operator_);
  897. }
  898. return operator_;
  899. }
  900. OperatorInfoPtr NewOperatorInstance(const PrimitivePtr &prim, const PrimitiveAttrs &attrs,
  901. std::vector<Shapes> shape_list) {
  902. OperatorInfoPtr operator_ = OperatorInstance(prim, attrs, shape_list);
  903. for (size_t i = 0; i < shape_list[0].size(); ++i) {
  904. MS_LOG(INFO) << "No: " << i << " input's shape: " << ShapeToString(shape_list[0][i]);
  905. }
  906. return operator_;
  907. }
  908. StrategyPtr ExtractStrategy(std::unordered_map<std::string, ValuePtr> attrs) {
  909. ValueTuplePtr var = attrs[STRATEGY]->cast<ValueTuplePtr>();
  910. StrategyPtr strategyPtr;
  911. MS_LOG(INFO) << "Extract information: strategy " << attrs[STRATEGY]->ToString();
  912. if (var == nullptr) {
  913. MS_LOG(EXCEPTION) << "Strategy value is nullptr";
  914. }
  915. if (var->size() > 0) {
  916. std::vector<ValuePtr> elements = var->value();
  917. std::vector<Dimensions> strategy;
  918. for (uint32_t index = 0; index < elements.size(); ++index) {
  919. Dimensions dim;
  920. if (elements[index]->isa<ValueSequeue>()) {
  921. ValueTuplePtr value_tuple = elements[index]->cast<ValueTuplePtr>();
  922. if (value_tuple == nullptr) {
  923. MS_LOG(EXCEPTION) << "Failure:value_tuple is nullptr";
  924. }
  925. std::vector<ValuePtr> value_vector = value_tuple->value();
  926. (void)std::transform(value_vector.begin(), value_vector.end(), std::back_inserter(dim),
  927. [](const ValuePtr &value) { return static_cast<int32_t>(GetValue<int>(value)); });
  928. strategy.push_back(dim);
  929. } else {
  930. MS_LOG(EXCEPTION) << "Failure:Strategy's format is wrong! Need ValueSequeue";
  931. }
  932. }
  933. if (strategy.empty()) {
  934. MS_LOG(EXCEPTION) << "ExtractStrategy:failed to extract strategy";
  935. }
  936. strategyPtr = NewStrategy(0, strategy);
  937. }
  938. return strategyPtr;
  939. }
  940. Shapes GetNodeShape(const AnfNodePtr &node) {
  941. MS_EXCEPTION_IF_NULL(node);
  942. Shapes shapes;
  943. BaseShapePtr base_shape_ptr = node->Shape();
  944. if (node->isa<CNode>()) {
  945. auto cnode = node->cast<CNodePtr>();
  946. MS_EXCEPTION_IF_NULL(cnode);
  947. if (IsValueNode<Primitive>(cnode->input(0))) {
  948. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  949. MS_EXCEPTION_IF_NULL(prim);
  950. if (prim->name() == MAKEREF) {
  951. AnfNodePtr ref_node = cnode->input(1);
  952. auto func_graph = cnode->func_graph();
  953. MS_EXCEPTION_IF_NULL(ref_node);
  954. MS_EXCEPTION_IF_NULL(func_graph);
  955. return GetRefKeyNodeShape(ref_node, func_graph);
  956. }
  957. }
  958. if (cnode->input(0)->isa<CNode>()) {
  959. if (cnode->inputs().size() < 2) {
  960. MS_LOG(EXCEPTION) << "GetNodeShape: " << node->ToString() << " size is samller than 2";
  961. }
  962. base_shape_ptr = cnode->input(1)->Shape();
  963. }
  964. }
  965. if (base_shape_ptr == nullptr) {
  966. MS_LOG(EXCEPTION) << "GetNodeShape: " << node->ToString() << " shape_ptr is nullptr, full name is "
  967. << node->fullname_with_scope();
  968. }
  969. auto tuple_shape_ptr = dyn_cast<abstract::TupleShape>(base_shape_ptr);
  970. if (tuple_shape_ptr != nullptr) {
  971. auto tuple_shape = tuple_shape_ptr->shape();
  972. for (auto &shape : tuple_shape) {
  973. auto each_shape = dyn_cast<abstract::Shape>(shape);
  974. MS_EXCEPTION_IF_NULL(each_shape);
  975. shapes.push_back(each_shape->shape());
  976. }
  977. } else {
  978. auto shape_ptr = dyn_cast<abstract::Shape>(base_shape_ptr);
  979. MS_EXCEPTION_IF_NULL(shape_ptr);
  980. shapes.push_back(shape_ptr->shape());
  981. }
  982. return shapes;
  983. }
  984. std::vector<AnfNodePtr> FindParameterByRefKeyNode(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  985. MS_EXCEPTION_IF_NULL(node);
  986. MS_EXCEPTION_IF_NULL(func_graph);
  987. std::vector<AnfNodePtr> parameters;
  988. if (!IsValueNode<RefKey>(node)) {
  989. MS_LOG(ERROR) << "The node is not a ref key";
  990. return parameters;
  991. }
  992. auto ref_key = GetValueNode<RefKeyPtr>(node);
  993. MS_EXCEPTION_IF_NULL(ref_key);
  994. auto name = ref_key->tag();
  995. auto manager = func_graph->manager();
  996. MS_EXCEPTION_IF_NULL(manager);
  997. auto roots = manager->roots();
  998. if (roots.size() != 1) {
  999. MS_LOG(ERROR) << "The size of roots ( " << roots.size() << " ) is not 1";
  1000. return parameters;
  1001. }
  1002. FuncGraphPtr root_g = roots.back();
  1003. MS_EXCEPTION_IF_NULL(root_g);
  1004. for (auto &param_node : root_g->parameters()) {
  1005. auto param = param_node->cast<ParameterPtr>();
  1006. if (param && (name == param->name())) {
  1007. parameters.push_back(param_node);
  1008. MS_LOG(INFO) << "The name of ref key is: " << name;
  1009. return parameters;
  1010. }
  1011. }
  1012. MS_LOG(ERROR) << "The name of ref key is: " << name << ", but have not found the parameter";
  1013. return parameters;
  1014. }
  1015. Shapes GetRefKeyNodeShape(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  1016. MS_EXCEPTION_IF_NULL(node);
  1017. MS_EXCEPTION_IF_NULL(func_graph);
  1018. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(node, func_graph);
  1019. if (parameters.size() != 1) {
  1020. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  1021. }
  1022. Shapes input_shapes;
  1023. input_shapes = GetNodeShape(parameters[0]);
  1024. if (input_shapes.size() != 1) {
  1025. MS_LOG(EXCEPTION) << "Get input shape failed";
  1026. }
  1027. MS_LOG(INFO) << "The parameter shape is " << ShapeToString(input_shapes[0]);
  1028. return input_shapes;
  1029. }
  1030. std::vector<Shapes> ExtractShape(const CNodePtr &node) {
  1031. MS_EXCEPTION_IF_NULL(node);
  1032. Shapes shape_inputs, shape_outputs;
  1033. std::vector<Shapes> shape_all;
  1034. std::vector<AnfNodePtr> all_inputs = node->inputs();
  1035. std::vector<AnfNodePtr> node_inputs{all_inputs.begin() + 1, all_inputs.end()};
  1036. size_t inputs_size = all_inputs.size();
  1037. for (size_t i = 1; i < inputs_size; ++i) {
  1038. Shapes input_shapes;
  1039. AnfNodePtr input = all_inputs[i];
  1040. if (IsValueNode<RefKey>(input)) {
  1041. auto func_graph = node->func_graph();
  1042. MS_EXCEPTION_IF_NULL(func_graph);
  1043. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(input, func_graph);
  1044. if (parameters.size() != 1) {
  1045. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  1046. }
  1047. std::pair<AnfNodePtr, int> node_pair = std::make_pair(node, SizeToInt(i));
  1048. g_RefMap[parameters[0]] = node_pair;
  1049. input_shapes = GetRefKeyNodeShape(input, func_graph);
  1050. } else if (IsValueNode<Tensor>(input) || input->isa<CNode>() || input->isa<Parameter>()) {
  1051. input_shapes = GetNodeShape(input);
  1052. } else {
  1053. continue;
  1054. }
  1055. if (input_shapes.size() != 1) {
  1056. MS_LOG(EXCEPTION) << "ExtractShape:Get input shape failed";
  1057. }
  1058. shape_inputs.push_back(input_shapes[0]);
  1059. }
  1060. shape_all.push_back(shape_inputs);
  1061. // extract out shape
  1062. shape_outputs = GetNodeShape(node);
  1063. shape_all.push_back(shape_outputs);
  1064. return shape_all;
  1065. }
  1066. std::pair<AnfNodePtr, int> FindParallelCareNode(const AnfNodePtr &node) {
  1067. MS_EXCEPTION_IF_NULL(node);
  1068. FuncGraphPtr func_graph = node->func_graph();
  1069. MS_EXCEPTION_IF_NULL(func_graph);
  1070. FuncGraphManagerPtr manager = func_graph->manager();
  1071. MS_EXCEPTION_IF_NULL(manager);
  1072. AnfNodeIndexSet node_set = manager->node_users()[node];
  1073. for (auto &node_pair : node_set) {
  1074. CNodePtr cnode = node_pair.first->cast<CNodePtr>();
  1075. MS_EXCEPTION_IF_NULL(cnode);
  1076. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1077. continue;
  1078. }
  1079. ValueNodePtr prim_node_anf = cnode->input(0)->cast<ValueNodePtr>();
  1080. MS_EXCEPTION_IF_NULL(prim_node_anf);
  1081. PrimitivePtr node_prim = prim_node_anf->value()->cast<PrimitivePtr>();
  1082. MS_EXCEPTION_IF_NULL(node_prim);
  1083. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  1084. continue;
  1085. }
  1086. if (IsParallelCareNode(cnode) && cnode->operator_info() != nullptr) {
  1087. return node_pair;
  1088. } else if (FindParallelCareNode(node_pair.first).first != nullptr) {
  1089. return FindParallelCareNode(node_pair.first);
  1090. }
  1091. }
  1092. return std::make_pair(nullptr, 0);
  1093. }
  1094. std::pair<AnfNodePtr, int> FindSubGraph(const FuncGraphPtr &graph, const AnfNodePtr &parameter) {
  1095. MS_EXCEPTION_IF_NULL(graph);
  1096. MS_EXCEPTION_IF_NULL(parameter);
  1097. FuncGraphManagerPtr manager = graph->manager();
  1098. MS_EXCEPTION_IF_NULL(manager);
  1099. std::pair<AnfNodePtr, int> prim_anf_node_pair = FindParallelCareNode(parameter);
  1100. if (prim_anf_node_pair.first != nullptr) {
  1101. return prim_anf_node_pair;
  1102. } else {
  1103. AnfNodeIndexSet param_sub_set = manager->node_users()[parameter];
  1104. for (auto &param_pair : param_sub_set) {
  1105. CNodePtr graph_cnode = param_pair.first->cast<CNodePtr>();
  1106. if ((graph_cnode == nullptr) || !graph_cnode->input(0)->isa<CNode>()) {
  1107. continue;
  1108. }
  1109. CNodePtr graph_cnode_inp0 = graph_cnode->input(0)->cast<CNodePtr>();
  1110. if ((graph_cnode_inp0 == nullptr) || !IsValueNode<FuncGraph>(graph_cnode_inp0->input(1))) {
  1111. continue;
  1112. }
  1113. FuncGraphPtr graph_sub = GetValueNode<FuncGraphPtr>(graph_cnode_inp0->input(1));
  1114. auto parameters = graph_sub->parameters();
  1115. if (IntToSize(param_pair.second - 1) >= parameters.size()) {
  1116. MS_LOG(EXCEPTION) << "The index is out of range, index is " << param_pair.second - 1 << ", vector size is "
  1117. << parameters.size();
  1118. }
  1119. std::pair<AnfNodePtr, int> res = FindSubGraph(graph_sub, parameters[IntToSize(param_pair.second - 1)]);
  1120. if (res.first != nullptr) {
  1121. return res;
  1122. }
  1123. }
  1124. }
  1125. return std::make_pair(nullptr, 0);
  1126. }
  1127. void SetParallelShape(const AnfNodePtr &parameter, const std::pair<AnfNodePtr, int> &res) {
  1128. MS_EXCEPTION_IF_NULL(parameter);
  1129. AbstractBasePtr abstract = parameter->abstract();
  1130. MS_EXCEPTION_IF_NULL(abstract);
  1131. MS_LOG(DEBUG) << "SetParallelShape " << parameter->ToString() << " shape " << parameter->Shape()->ToString();
  1132. CNodePtr cnode = res.first->cast<CNodePtr>();
  1133. MS_EXCEPTION_IF_NULL(cnode);
  1134. OperatorInfoPtr distribute_operator = cnode->operator_info();
  1135. if (distribute_operator == nullptr) {
  1136. MS_LOG(EXCEPTION) << "Failure:node " << cnode->ToString() << " 's OperatorInfoPtr is nullptr";
  1137. }
  1138. if (IntToSize(res.second - 1) >= distribute_operator->inputs_tensor_info().size()) {
  1139. MS_LOG(EXCEPTION) << "The index is out of range, index is " << res.second - 1 << ", vector size is "
  1140. << distribute_operator->inputs_tensor_info().size();
  1141. }
  1142. TensorInfo tensorinfo_in = distribute_operator->inputs_tensor_info()[IntToSize(res.second - 1)];
  1143. Shape slice_shape = tensorinfo_in.slice_shape();
  1144. MS_LOG(DEBUG) << "SetParallelShape slice_shape " << parameter->ToString() << " shape "
  1145. << MakeValue(slice_shape)->ToString();
  1146. std::shared_ptr<abstract::BaseShape> parallel_shape = std::make_shared<abstract::Shape>(slice_shape);
  1147. MS_EXCEPTION_IF_NULL(parallel_shape);
  1148. abstract->set_shape(parallel_shape);
  1149. TensorLayout tensor_layout = tensorinfo_in.tensor_layout();
  1150. ParameterPtr parameter_ptr = parameter->cast<ParameterPtr>();
  1151. MS_EXCEPTION_IF_NULL(parameter_ptr);
  1152. parameter_ptr->set_tensor_layout(std::make_shared<TensorLayout>(tensor_layout));
  1153. }
  1154. void CoverSliceShape(const FuncGraphPtr &root) {
  1155. MS_EXCEPTION_IF_NULL(root);
  1156. auto parameters = root->parameters();
  1157. for (auto &parameter : parameters) {
  1158. MS_EXCEPTION_IF_NULL(parameter->Shape());
  1159. auto iter = g_RefMap.find(parameter);
  1160. if (iter != g_RefMap.end()) {
  1161. SetParallelShape(parameter, g_RefMap[parameter]);
  1162. continue;
  1163. }
  1164. std::pair<AnfNodePtr, int> res = FindSubGraph(root, parameter);
  1165. if (res.first == nullptr) {
  1166. MS_LOG(INFO) << "Parameter " << parameter->ToString() << " don't need to set parallel shape";
  1167. } else {
  1168. SetParallelShape(parameter, res);
  1169. MS_LOG(DEBUG) << "Parameter " << parameter->ToString() << " shape " << parameter->Shape()->ToString();
  1170. }
  1171. }
  1172. g_RefMap.clear();
  1173. }
  1174. bool ParameterIsCloned(const FuncGraphPtr &root, const AnfNodePtr &parameter_node) {
  1175. MS_EXCEPTION_IF_NULL(root);
  1176. MS_EXCEPTION_IF_NULL(parameter_node);
  1177. FuncGraphManagerPtr manager = root->manager();
  1178. MS_EXCEPTION_IF_NULL(manager);
  1179. auto cloned_parameter = parameter_node->cast<ParameterPtr>();
  1180. MS_EXCEPTION_IF_NULL(cloned_parameter);
  1181. // find the clone parameter
  1182. if (!cloned_parameter->has_default()) {
  1183. return false;
  1184. }
  1185. py::object clone_info = parse::python_adapter::GetPyObjAttr(cloned_parameter->default_param(), CLONE_INFO);
  1186. bool cloned = py::cast<bool>(parse::python_adapter::GetPyObjAttr(clone_info, CLONED));
  1187. if (!cloned) {
  1188. return false;
  1189. }
  1190. MS_LOG(INFO) << "The parameter: " << cloned_parameter->name() << " is cloned";
  1191. return true;
  1192. }
  1193. void SetClonedTensorShapeForOptimizer(const FuncGraphPtr &root) {
  1194. MS_EXCEPTION_IF_NULL(root);
  1195. for (auto &cloned_parameter_node : root->parameters()) {
  1196. MS_EXCEPTION_IF_NULL(cloned_parameter_node);
  1197. auto cloned_parameter = cloned_parameter_node->cast<ParameterPtr>();
  1198. MS_EXCEPTION_IF_NULL(cloned_parameter);
  1199. if (!ParameterIsCloned(root, cloned_parameter_node)) {
  1200. continue;
  1201. }
  1202. // get the cloned index
  1203. py::object cloned_info = parse::python_adapter::GetPyObjAttr(cloned_parameter->default_param(), CLONE_INFO);
  1204. int32_t cloned_index = py::cast<int32_t>(parse::python_adapter::GetPyObjAttr(cloned_info, CLONED_INDEX));
  1205. // find the be cloned parameter
  1206. bool found_be_cloned_parameter = false;
  1207. ParameterPtr cloned_from_parameter = nullptr;
  1208. AnfNodePtr cloned_from_node = nullptr;
  1209. for (auto &be_cloned_parameter_node : root->parameters()) {
  1210. MS_EXCEPTION_IF_NULL(be_cloned_parameter_node);
  1211. auto be_cloned_parameter = be_cloned_parameter_node->cast<ParameterPtr>();
  1212. MS_EXCEPTION_IF_NULL(be_cloned_parameter);
  1213. if (!be_cloned_parameter->has_default()) {
  1214. continue;
  1215. }
  1216. py::object be_cloned_info = parse::python_adapter::GetPyObjAttr(be_cloned_parameter->default_param(), CLONE_INFO);
  1217. if (!py::cast<bool>(parse::python_adapter::GetPyObjAttr(be_cloned_info, BE_CLONED))) {
  1218. continue;
  1219. }
  1220. // get the be cloned index
  1221. py::list be_cloned_index = parse::python_adapter::GetPyObjAttr(be_cloned_info, BE_CLONED_INDEX);
  1222. for (auto &index : be_cloned_index) {
  1223. if (cloned_index == py::cast<int32_t>(index)) {
  1224. found_be_cloned_parameter = true;
  1225. cloned_from_parameter = be_cloned_parameter;
  1226. cloned_from_node = be_cloned_parameter_node;
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. if (found_be_cloned_parameter) {
  1232. // set the shape and tensor layout for cloned parameter
  1233. cloned_parameter->set_tensor_layout(cloned_from_parameter->tensor_layout());
  1234. MS_EXCEPTION_IF_NULL(cloned_parameter_node->abstract());
  1235. MS_EXCEPTION_IF_NULL(cloned_from_node->abstract());
  1236. cloned_parameter_node->abstract()->set_shape(cloned_from_node->abstract()->GetShapeTrack());
  1237. MS_LOG(INFO) << "The parameter: " << cloned_parameter->name()
  1238. << " is cloned, the be cloned parameter is: " << cloned_from_parameter->name()
  1239. << ", clone index is: " << cloned_index;
  1240. } else {
  1241. MS_LOG(EXCEPTION) << "The parameter: " << cloned_parameter->name() << " is cloned, cloned index is "
  1242. << cloned_index << ", but not found the be cloned parameter";
  1243. }
  1244. }
  1245. }
  1246. void SetVirtualDatasetStrategy(const CNodePtr &node) {
  1247. MS_EXCEPTION_IF_NULL(node);
  1248. PrimitivePtr prim = GetValueNode<PrimitivePtr>(node->input(0));
  1249. MS_EXCEPTION_IF_NULL(prim);
  1250. if (prim->name() == VIRTUAL_DATA_SET) {
  1251. CheckGlobalDeviceManager();
  1252. int32_t dev_num = SizeToInt(g_device_manager->GetDeviceListByStageId(0).size());
  1253. auto attrs_temp = prim->attrs();
  1254. std::vector<Shapes> shape_list = ExtractShape(node);
  1255. if (shape_list.empty()) {
  1256. MS_LOG(EXCEPTION) << "Failure:node " << node->ToString() << " failed to extract shape";
  1257. }
  1258. std::vector<ValuePtr> elements;
  1259. for (size_t i = 0; i < shape_list[0].size(); i++) {
  1260. if (shape_list[0][i].empty()) {
  1261. MS_LOG(EXCEPTION) << "shape_list[ " << i << " ].size() is zero";
  1262. }
  1263. std::vector<int32_t> input_strategy = {dev_num};
  1264. for (size_t j = 1; j < shape_list[0][i].size(); j++) {
  1265. input_strategy.push_back(1);
  1266. }
  1267. elements.push_back(MakeValue(input_strategy));
  1268. }
  1269. ValueTuplePtr strategy = std::make_shared<ValueTuple>(elements);
  1270. attrs_temp[STRATEGY] = strategy;
  1271. (void)prim->SetAttrs(attrs_temp);
  1272. }
  1273. }
  1274. void ExtractInformation(const std::vector<AnfNodePtr> &all_nodes) {
  1275. for (auto &node : all_nodes) {
  1276. auto cnode = node->cast<CNodePtr>();
  1277. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1278. continue;
  1279. }
  1280. SetVirtualDatasetStrategy(cnode);
  1281. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1282. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1283. auto attrs = prim->attrs();
  1284. MS_LOG(INFO) << "extract information: node: " << node->ToString() << " prim " << prim->name();
  1285. if (IsParallelCareNode(cnode)) {
  1286. std::vector<Shapes> shape_list = ExtractShape(cnode);
  1287. if (shape_list.empty()) {
  1288. MS_LOG(EXCEPTION) << "Failure:node " << node->ToString() << " failed to extract shape";
  1289. }
  1290. OperatorInfoPtr operator_ = OperatorInstance(prim, attrs, shape_list);
  1291. if (operator_ == nullptr) {
  1292. MS_LOG(EXCEPTION) << "Failure:Primitive " << prim->name() << " OperatorInstance failed";
  1293. }
  1294. auto &inputs = cnode->inputs();
  1295. std::vector<ValuePtr> input_value;
  1296. for (size_t index = 1; index < inputs.size(); ++index) {
  1297. if (inputs[index]->isa<ValueNode>()) {
  1298. input_value.push_back(GetValueNode(inputs[index]));
  1299. } else {
  1300. input_value.emplace_back(nullptr);
  1301. }
  1302. }
  1303. StrategyPtr strategyPtr = nullptr;
  1304. (*operator_).set_input_value(input_value);
  1305. (*operator_).set_outputs_dtype(cnode->Type());
  1306. (*operator_).set_cnode(cnode);
  1307. if (prim->name() == RESHAPE) {
  1308. (void)cnode->set_operator_info(operator_);
  1309. continue;
  1310. }
  1311. if (!StrategyFound(attrs)) {
  1312. MS_LOG(INFO) << "ExtractInformation: the strategy of node " << node->ToString() << " prim " << prim->name()
  1313. << " is empty, using batch parallel";
  1314. std::shared_ptr<std::vector<Dimensions>> strategy_v_ptr = operator_->GenerateBatchStrategies();
  1315. if (strategy_v_ptr == nullptr) {
  1316. MS_LOG(EXCEPTION) << "Failure:Generate batch parallel strategy failed";
  1317. }
  1318. std::vector<ValuePtr> elements;
  1319. for (size_t i = 0; i < strategy_v_ptr->size(); i++) {
  1320. elements.push_back(MakeValue((*strategy_v_ptr)[i]));
  1321. }
  1322. ValueTuplePtr strategy = std::make_shared<ValueTuple>(elements);
  1323. // display the strategy generated by batch parallel
  1324. attrs[GEN_STRATEGY] = strategy;
  1325. (void)prim->SetAttrs(attrs);
  1326. MS_LOG(INFO) << "node " << node->ToString() << " prim " << prim->name() << " batch parallel strategy is "
  1327. << attrs[GEN_STRATEGY]->ToString();
  1328. strategyPtr = NewStrategy(0, *strategy_v_ptr);
  1329. } else {
  1330. strategyPtr = ExtractStrategy(attrs);
  1331. }
  1332. if (strategyPtr != nullptr) {
  1333. if (operator_->Init(strategyPtr) == FAILED) {
  1334. MS_LOG(EXCEPTION) << "Failure:operator " << prim->name() << " init failed";
  1335. }
  1336. (void)cnode->set_operator_info(operator_);
  1337. } else {
  1338. MS_LOG(EXCEPTION) << "ERROR:strategy_ptr is nullptr";
  1339. }
  1340. }
  1341. }
  1342. }
  1343. TensorLayout GetInputLayoutFromCNode(const std::pair<AnfNodePtr, int> &node_pair) {
  1344. CNodePtr cnode = node_pair.first->cast<CNodePtr>();
  1345. MS_EXCEPTION_IF_NULL(cnode);
  1346. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1347. MS_EXCEPTION_IF_NULL(distribute_operator);
  1348. int index = node_pair.second;
  1349. if (index > SizeToInt(distribute_operator->inputs_tensor_info().size())) {
  1350. MS_LOG(EXCEPTION) << "The index is out of range, the node_pair.second is " << index - 1 << ", the vector size is "
  1351. << distribute_operator->inputs_tensor_info().size();
  1352. }
  1353. TensorInfo tensorinfo_in = distribute_operator->inputs_tensor_info()[IntToSize(index - 1)];
  1354. TensorLayout tensorlayout_in = tensorinfo_in.tensor_layout();
  1355. return tensorlayout_in;
  1356. }
  1357. // if reshape's output connect to several primitive, return the first layout found
  1358. std::shared_ptr<TensorLayout> FindNextLayout(const CNodePtr &cnode) {
  1359. MS_EXCEPTION_IF_NULL(cnode);
  1360. MS_EXCEPTION_IF_NULL(cnode->func_graph());
  1361. FuncGraphManagerPtr manager = cnode->func_graph()->manager();
  1362. MS_EXCEPTION_IF_NULL(manager);
  1363. AnfNodeIndexSet node_set = manager->node_users()[cnode];
  1364. for (auto &node_pair : node_set) {
  1365. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  1366. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  1367. continue;
  1368. }
  1369. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  1370. MS_EXCEPTION_IF_NULL(prim_anf_node);
  1371. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1372. MS_EXCEPTION_IF_NULL(node_prim);
  1373. MS_LOG(INFO) << "FindNextLayout prim " << node_prim->name();
  1374. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  1375. continue;
  1376. }
  1377. if (IsParallelCareNode(use_apply) && (use_apply->operator_info() != nullptr)) {
  1378. MS_LOG(INFO) << "FindNextLayout success prim " << node_prim->name();
  1379. auto layout = GetInputLayoutFromCNode(node_pair);
  1380. return std::make_shared<TensorLayout>(layout);
  1381. }
  1382. MS_LOG(DEBUG) << "FindNextLayout failed prim " << node_prim->name() << " " << IsParallelCareNode(use_apply)
  1383. << " " << (use_apply->operator_info() != nullptr);
  1384. auto layout_ptr = FindNextLayout(use_apply);
  1385. if (layout_ptr) {
  1386. return layout_ptr;
  1387. }
  1388. }
  1389. MS_LOG(WARNING) << "FindNextLayout return nullptr, if reshape is not the last primitive, there must be some error";
  1390. return nullptr;
  1391. }
  1392. std::shared_ptr<TensorLayout> GetOutputLayoutFromCNode(const CNodePtr &cnode, size_t output_index) {
  1393. MS_EXCEPTION_IF_NULL(cnode);
  1394. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1395. MS_EXCEPTION_IF_NULL(distribute_operator);
  1396. if (distribute_operator->outputs_tensor_info().size() < output_index) {
  1397. MS_LOG(EXCEPTION) << "outputs_tensor_info size is " << distribute_operator->inputs_tensor_info().size()
  1398. << ", must be less than output_index " << output_index;
  1399. }
  1400. TensorInfo tensorinfo_out = distribute_operator->outputs_tensor_info()[output_index];
  1401. TensorLayout tensorlayout_out = tensorinfo_out.tensor_layout();
  1402. return std::make_shared<TensorLayout>(tensorlayout_out);
  1403. }
  1404. std::shared_ptr<TensorLayout> FindPrevParallelCareNodeLayout(const AnfNodePtr &node, size_t output_index) {
  1405. if (!node->isa<CNode>()) {
  1406. return nullptr;
  1407. }
  1408. CNodePtr cnode = node->cast<CNodePtr>();
  1409. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1410. return nullptr;
  1411. }
  1412. if (IsParallelCareNode(cnode) && (cnode->operator_info() != nullptr)) {
  1413. auto layout_ptr = GetOutputLayoutFromCNode(cnode, output_index);
  1414. if (!layout_ptr) {
  1415. MS_LOG(EXCEPTION) << "Failure:GetLayoutFromCNode failed";
  1416. }
  1417. return layout_ptr;
  1418. }
  1419. return nullptr;
  1420. }
  1421. std::shared_ptr<TensorLayout> FindPrevLayout(const AnfNodePtr &node) {
  1422. if (node->isa<Parameter>()) {
  1423. MS_LOG(EXCEPTION) << "Failure: parameter before reshape is not supported temporary";
  1424. }
  1425. if (!node->isa<CNode>()) {
  1426. return nullptr;
  1427. }
  1428. CNodePtr cnode = node->cast<CNodePtr>();
  1429. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1430. return nullptr;
  1431. }
  1432. if (IsParallelCareNode(cnode) && (cnode->operator_info() != nullptr)) {
  1433. auto layout_ptr = GetOutputLayoutFromCNode(cnode, 0);
  1434. if (!layout_ptr) {
  1435. MS_LOG(EXCEPTION) << "Failure:GetLayoutFromCNode failed";
  1436. }
  1437. return layout_ptr;
  1438. }
  1439. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1440. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1441. if (prim->name() == TUPLE_GETITEM) {
  1442. auto tuple_index = GetTupleGetItemIndex(cnode);
  1443. auto layout_ptr = FindPrevParallelCareNodeLayout(cnode->input(1), IntToSize(tuple_index));
  1444. if (!layout_ptr) {
  1445. MS_LOG(EXCEPTION)
  1446. << " Failure:FindPrevLayout failed, tuple_getitem before reshape, but there does not exit a parallel care node "
  1447. "before tuple_getitem!";
  1448. }
  1449. return layout_ptr;
  1450. }
  1451. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  1452. if (prim->name() == DEPEND && index != 1) {
  1453. continue;
  1454. }
  1455. auto layout_ptr = FindPrevLayout(cnode->inputs()[index]);
  1456. if (!layout_ptr) {
  1457. continue;
  1458. }
  1459. return layout_ptr;
  1460. }
  1461. MS_LOG(WARNING) << "FindPrevLayout return nullptr, if reshape is not the first primitive, there must be some error";
  1462. return nullptr;
  1463. }
  1464. void ReshapeInit(const std::vector<AnfNodePtr> &all_nodes) {
  1465. for (auto &node : all_nodes) {
  1466. auto cnode = node->cast<CNodePtr>();
  1467. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1468. continue;
  1469. }
  1470. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1471. if (!IsParallelCareNode(cnode) || (cnode->operator_info() == nullptr)) {
  1472. continue;
  1473. }
  1474. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1475. MS_EXCEPTION_IF_NULL(prim);
  1476. OperatorInfoPtr operator_info = cnode->operator_info();
  1477. if (operator_info == nullptr) {
  1478. MS_LOG(EXCEPTION) << "Failure:Primitive " << prim->ToString() << " OperatorInstance is nullptr";
  1479. }
  1480. if (prim->name() != RESHAPE) {
  1481. continue;
  1482. }
  1483. auto attrs = prim->attrs();
  1484. if (StrategyFound(attrs)) {
  1485. MS_LOG(EXCEPTION) << "Setting strategy for Reshape goes for nothing!";
  1486. }
  1487. MS_ASSERT(cnode->inputs().size() == 3);
  1488. auto prev_layout_ptr = FindPrevLayout(cnode->input(1));
  1489. if (prev_layout_ptr) {
  1490. auto reshape_info_ptr = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  1491. reshape_info_ptr->SetInputLayout(*prev_layout_ptr);
  1492. }
  1493. auto next_layout_ptr = FindNextLayout(cnode);
  1494. if (next_layout_ptr) {
  1495. auto reshape_info_ptr = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  1496. reshape_info_ptr->SetOutputLayout(*next_layout_ptr);
  1497. }
  1498. if (operator_info->Init(nullptr) == FAILED) {
  1499. MS_LOG(EXCEPTION) << "Failure:operator " << prim->ToString() << " init failed";
  1500. }
  1501. }
  1502. }
  1503. CNodePtr FindLossCNode(const FuncGraphPtr &func_graph) {
  1504. MS_EXCEPTION_IF_NULL(func_graph);
  1505. CNodePtr return_node = func_graph->get_return();
  1506. MS_EXCEPTION_IF_NULL(return_node);
  1507. if (return_node->size() < 2) {
  1508. MS_LOG(EXCEPTION) << "Failure: " << return_node->ToString() << " size is smaller than 2";
  1509. }
  1510. AnfNodePtr pre_node = return_node->input(1);
  1511. MS_EXCEPTION_IF_NULL(pre_node);
  1512. auto pre_cnode = pre_node->cast<CNodePtr>();
  1513. MS_EXCEPTION_IF_NULL(pre_cnode);
  1514. auto current_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  1515. // return -> cast
  1516. if (current_prim->name() == CAST && pre_cnode->operator_info() == nullptr) {
  1517. pre_cnode = pre_cnode->input(1)->cast<CNodePtr>();
  1518. MS_EXCEPTION_IF_NULL(pre_cnode);
  1519. current_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  1520. }
  1521. // notice: the GetNext op has not input
  1522. if (INVALID_LOSS_OPS.find(current_prim->name()) != INVALID_LOSS_OPS.end()) {
  1523. MS_LOG(INFO) << "The loss is: " << current_prim->name();
  1524. return pre_cnode;
  1525. }
  1526. // size of common cnode is larger than 1
  1527. if (pre_cnode->size() < 2) {
  1528. MS_LOG(EXCEPTION) << pre_cnode->ToString() << " size( " << pre_cnode->inputs().size() << " ) is smaller than 2";
  1529. }
  1530. // return -> tuple_getitem -> loss
  1531. if (current_prim->name() == TUPLE_GETITEM) {
  1532. AnfNodePtr pre_pre_node = pre_cnode->input(1);
  1533. MS_EXCEPTION_IF_NULL(pre_pre_node);
  1534. auto pre_pre_cnode = pre_pre_node->cast<CNodePtr>();
  1535. auto value = pre_pre_cnode->input(0)->cast<ValueNodePtr>();
  1536. MS_EXCEPTION_IF_NULL(value);
  1537. PrimitivePtr prim = value->value()->cast<PrimitivePtr>();
  1538. MS_EXCEPTION_IF_NULL(prim);
  1539. MS_LOG(DEBUG) << "The loss name is " << prim->name();
  1540. return pre_pre_cnode;
  1541. }
  1542. // return -> make_tuple
  1543. if (current_prim->name() == MAKE_TUPLE) {
  1544. MS_LOG(EXCEPTION) << "The loss have make_tuple, it is not supported";
  1545. }
  1546. // return -> loss
  1547. MS_LOG(DEBUG) << "The loss name is " << current_prim->name();
  1548. return pre_cnode;
  1549. }
  1550. TensorLayouts GetLossNodeGradOutputLayout(const CNodePtr &cnode) {
  1551. MS_EXCEPTION_IF_NULL(cnode);
  1552. TensorLayouts ret;
  1553. if (!IsValueNode<FuncGraph>(cnode->input(1))) {
  1554. MS_LOG(EXCEPTION) << "Sens can't find the corresponding graph.";
  1555. }
  1556. auto func_graph = GetValueNode<FuncGraphPtr>(cnode->input(1));
  1557. auto loss_cnode = FindLossCNode(func_graph);
  1558. MS_EXCEPTION_IF_NULL(loss_cnode);
  1559. AnfNodePtr node = loss_cnode->cast<AnfNodePtr>();
  1560. MS_EXCEPTION_IF_NULL(node);
  1561. LossNodeInfo node_info = GetLossNodeInfo(node);
  1562. ValueNodePtr prim_anf_node = loss_cnode->input(0)->cast<ValueNodePtr>();
  1563. MS_EXCEPTION_IF_NULL(prim_anf_node);
  1564. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1565. MS_EXCEPTION_IF_NULL(prim);
  1566. if (INVALID_LOSS_OPS.find(prim->name()) != INVALID_LOSS_OPS.end()) {
  1567. MS_LOG(WARNING) << "The loss name is: " << prim->name() << ", do nothing for split sens now";
  1568. return ret;
  1569. }
  1570. OperatorInfoPtr operator_info = loss_cnode->operator_info();
  1571. MS_EXCEPTION_IF_NULL(operator_info);
  1572. TensorInfo loss_grad_tensor_info;
  1573. size_t op_output_size = operator_info->outputs_tensor_info().size();
  1574. MS_LOG(INFO) << "The loss name is " << operator_info->name() << ", the has tuple item is "
  1575. << node_info.has_tuple_getitem << ", the output size is " << op_output_size << ", the dout_index is "
  1576. << node_info.dout_index;
  1577. if ((op_output_size == 0) || (op_output_size <= IntToSize(node_info.dout_index))) {
  1578. MS_LOG(EXCEPTION) << "The index is " << node_info.dout_index << ", but the size of outputs is " << op_output_size;
  1579. }
  1580. if (!node_info.has_tuple_getitem && (op_output_size > 1)) {
  1581. MS_LOG(EXCEPTION) << "Currently, it is not supported that the sens is a tuple.";
  1582. }
  1583. loss_grad_tensor_info = operator_info->outputs_tensor_info()[IntToSize(node_info.dout_index)];
  1584. ret.push_back(loss_grad_tensor_info.tensor_layout());
  1585. return ret;
  1586. }
  1587. void SplitSens(const AnfNodePtr &grad_sens_node, const TensorLayout &loss_grad_layout) {
  1588. MS_EXCEPTION_IF_NULL(grad_sens_node);
  1589. auto cnode = grad_sens_node->cast<CNodePtr>();
  1590. MS_EXCEPTION_IF_NULL(cnode);
  1591. AnfNodePtr sens_tensor_node = cnode->input(1);
  1592. MS_EXCEPTION_IF_NULL(sens_tensor_node);
  1593. Shapes sens_shapes = GetNodeShape(sens_tensor_node);
  1594. if (sens_shapes.size() != 1) {
  1595. MS_LOG(EXCEPTION) << "SplitSens: GetNodeShape for sens_tensor_node, output size is not 1";
  1596. }
  1597. // If the shape of sens tensor is [] or [1], no need to split it.
  1598. Shape sens_shape = sens_shapes[0];
  1599. if (sens_shape.empty() || ((sens_shape.size() == 1) && (sens_shape[0] == 1))) {
  1600. if (sens_tensor_node->isa<Parameter>()) {
  1601. auto sens_tensor_param = sens_tensor_node->cast<ParameterPtr>();
  1602. MS_LOG(DEBUG) << "loss layout " << loss_grad_layout.ToString();
  1603. sens_tensor_param->set_tensor_layout(std::make_shared<TensorLayout>(loss_grad_layout));
  1604. }
  1605. MS_LOG(INFO) << "The shape of sens is " << ShapeToString(sens_shape) << ", no need to split sens";
  1606. return;
  1607. }
  1608. auto loss_shape = loss_grad_layout.tensor_shape().array();
  1609. if (loss_shape != sens_shape) {
  1610. MS_LOG(EXCEPTION) << "The shape of sens is not equal to loss output, it is unsupported now. Sens shape is "
  1611. << ShapeToString(sens_shape) << ", loss shape is " << ShapeToString(loss_shape);
  1612. }
  1613. MS_LOG(INFO) << "The shape of sens is " << ShapeToString(sens_shape) << ", split it.";
  1614. if (!IsValueNode<Tensor>(sens_tensor_node)) {
  1615. if (sens_tensor_node->isa<Parameter>()) {
  1616. MS_LOG(DEBUG) << "loss layout " << loss_grad_layout.ToString();
  1617. AbstractBasePtr abstract = sens_tensor_node->abstract();
  1618. MS_EXCEPTION_IF_NULL(abstract);
  1619. auto slice_shape = loss_grad_layout.slice_shape().array();
  1620. std::shared_ptr<abstract::BaseShape> parallel_shape = std::make_shared<abstract::Shape>(slice_shape);
  1621. MS_EXCEPTION_IF_NULL(parallel_shape);
  1622. abstract->set_shape(parallel_shape);
  1623. auto sens_tensor_param = sens_tensor_node->cast<ParameterPtr>();
  1624. sens_tensor_param->set_tensor_layout(std::make_shared<TensorLayout>(loss_grad_layout));
  1625. return;
  1626. }
  1627. MS_LOG(EXCEPTION) << "SplitSens: the type of sens node is not Tensor or Parameter, it is unsupported now.";
  1628. }
  1629. // Use _GetTensorSlice operator to split the sens tensor
  1630. FuncGraphPtr func_graph = cnode->func_graph(); // only cnode can get the graph
  1631. MS_EXCEPTION_IF_NULL(func_graph);
  1632. Operator op = CreateGetTensorSliceOp(loss_grad_layout);
  1633. InsertGetTensorSliceOp(op, cnode, func_graph, 1, SPLIT_SENS);
  1634. }
  1635. void InsertForwardOps(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1636. MS_EXCEPTION_IF_NULL(distribute_operator);
  1637. MS_EXCEPTION_IF_NULL(cnode);
  1638. OperatorVector forward_op = distribute_operator->forward_op();
  1639. if (!forward_op.empty()) {
  1640. MS_LOG(INFO) << "Insert forward op for " << distribute_operator->name();
  1641. ForwardCommunication(forward_op, cnode);
  1642. }
  1643. }
  1644. void StepReplace(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1645. MS_EXCEPTION_IF_NULL(distribute_operator);
  1646. MS_EXCEPTION_IF_NULL(cnode);
  1647. // StepReplaceOp
  1648. OperatorVector replace_op = distribute_operator->replace_op();
  1649. if (!replace_op.empty()) {
  1650. MS_LOG(INFO) << "StepReplaceOp " << cnode->ToString();
  1651. StepReplaceOp(replace_op, cnode);
  1652. }
  1653. // StepReplaceGraph: after calling StepReplaceGraph, cnode can not be used anymore.
  1654. ReplaceGraphPtr replace_graph = distribute_operator->replace_graph(cnode);
  1655. if (!replace_op.empty() && replace_graph) {
  1656. MS_LOG(EXCEPTION) << "Only one of replace_op or replace_op can be used";
  1657. }
  1658. if (replace_graph) {
  1659. MS_LOG(INFO) << "StepReplaceGraph " << cnode->ToString();
  1660. StepReplaceGraph(replace_graph, cnode);
  1661. }
  1662. }
  1663. void HandleDropoutNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1664. MS_EXCEPTION_IF_NULL(distribute_operator);
  1665. MS_EXCEPTION_IF_NULL(cnode);
  1666. std::string op_name = distribute_operator->name();
  1667. if (op_name.find(DROPOUT_DO_MASK) == std::string::npos) {
  1668. return;
  1669. }
  1670. DropoutDoMaskInfoPtr dropout_do_mask = std::dynamic_pointer_cast<DropoutDoMaskInfo>(distribute_operator);
  1671. MS_EXCEPTION_IF_NULL(dropout_do_mask);
  1672. Operator replace_op = dropout_do_mask->GetDropoutGenMaskReplaceOp(cnode);
  1673. if (cnode->inputs().size() != DROPOUT_DO_MASK_CNODE_INPUT_SIZE) {
  1674. MS_LOG(EXCEPTION) << "The size of drop out do mask cnode's input is not " << DROPOUT_DO_MASK_CNODE_INPUT_SIZE;
  1675. }
  1676. ReplaceOneOp(replace_op, cnode->input(DROPOUT_GEN_MASK_INDEX)->cast<CNodePtr>());
  1677. }
  1678. void HandleSpecialNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1679. HandleDropoutNode(distribute_operator, cnode);
  1680. }
  1681. std::set<FuncGraphPtr> FindForwardGraphByRootNodes(const AnfNodeSet &root_all_nodes) {
  1682. // J->CNode->Graph
  1683. std::set<FuncGraphPtr> graph_set;
  1684. for (auto &node : root_all_nodes) {
  1685. MS_EXCEPTION_IF_NULL(node);
  1686. if (!node->isa<CNode>()) {
  1687. continue;
  1688. }
  1689. auto cnode = node->cast<CNodePtr>();
  1690. MS_EXCEPTION_IF_NULL(cnode);
  1691. if ((cnode->size() < 2) || !IsValueNode<Primitive>(cnode->input(0))) {
  1692. continue;
  1693. }
  1694. auto expect_j_prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1695. if (expect_j_prim->name() != J) {
  1696. continue;
  1697. }
  1698. if (IsValueNode<FuncGraph>(cnode->input(1))) {
  1699. auto graph = GetValueNode<FuncGraphPtr>(cnode->input(1));
  1700. MS_LOG(DEBUG) << "Find the forward graph success";
  1701. graph_set.insert(graph);
  1702. }
  1703. }
  1704. return graph_set;
  1705. }
  1706. // Sens node satisfies the following conditions: cnode(sens)-->cnode(tuple_getitem)-->cnode-->cnode(J)
  1707. void StepSplitSens(const AnfNodePtr &node) {
  1708. if (!node->isa<CNode>()) {
  1709. return;
  1710. }
  1711. // cnode(sens)-->cnode(tuple_getitem)
  1712. auto cnode = node->cast<CNodePtr>();
  1713. AnfNodePtr expect_tuple_getitem = cnode->input(0);
  1714. MS_EXCEPTION_IF_NULL(expect_tuple_getitem);
  1715. if (!expect_tuple_getitem->isa<CNode>()) {
  1716. return;
  1717. }
  1718. auto expect_tuple_getitem_cnode = expect_tuple_getitem->cast<CNodePtr>();
  1719. MS_EXCEPTION_IF_NULL(expect_tuple_getitem_cnode);
  1720. if (!IsValueNode<Primitive>(expect_tuple_getitem_cnode->input(0))) {
  1721. return;
  1722. }
  1723. auto expect_tuple_getitem_prim = GetValueNode<PrimitivePtr>(expect_tuple_getitem_cnode->input(0));
  1724. if (expect_tuple_getitem_prim->name() != TUPLE_GETITEM) {
  1725. return;
  1726. }
  1727. // cnode(sens)-->cnode(tuple_getitem)-->cnode
  1728. AnfNodePtr expect_anonymous = expect_tuple_getitem_cnode->input(1);
  1729. MS_EXCEPTION_IF_NULL(expect_anonymous);
  1730. if (!expect_anonymous->isa<CNode>()) {
  1731. return;
  1732. }
  1733. // cnode(sens)-->cnode(tuple_getitem)-->cnode-->cnode(J)
  1734. auto expect_anonymous_cnode = expect_anonymous->cast<CNodePtr>();
  1735. MS_EXCEPTION_IF_NULL(expect_anonymous_cnode);
  1736. AnfNodePtr expect_j = expect_anonymous_cnode->input(0);
  1737. MS_EXCEPTION_IF_NULL(expect_j);
  1738. if (!expect_j->isa<CNode>()) {
  1739. return;
  1740. }
  1741. auto expect_j_cnode = expect_j->cast<CNodePtr>();
  1742. MS_EXCEPTION_IF_NULL(expect_j_cnode);
  1743. if (!IsValueNode<Primitive>(expect_j_cnode->input(0))) {
  1744. return;
  1745. }
  1746. auto expect_j_prim = GetValueNode<PrimitivePtr>(expect_j_cnode->input(0));
  1747. if (expect_j_prim->name() == J) {
  1748. auto loss_grad_layout = GetLossNodeGradOutputLayout(expect_j_cnode);
  1749. if (!loss_grad_layout.empty()) {
  1750. SplitSens(node, loss_grad_layout[0]);
  1751. }
  1752. }
  1753. }
  1754. std::vector<CNodePtr> FindLossCNodeFromRoot(const FuncGraphPtr &root) {
  1755. MS_EXCEPTION_IF_NULL(root);
  1756. AnfNodePtr root_return_node = root->get_return();
  1757. MS_EXCEPTION_IF_NULL(root_return_node);
  1758. std::vector<CNodePtr> loss_node;
  1759. const auto &all_nodes = root->nodes();
  1760. std::set<FuncGraphPtr> graph_set = FindForwardGraphByRootNodes(all_nodes);
  1761. if (graph_set.empty()) {
  1762. loss_node.push_back(FindLossCNode(root));
  1763. }
  1764. (void)std::transform(graph_set.begin(), graph_set.end(), std::back_inserter(loss_node),
  1765. [](const FuncGraphPtr &graph) { return FindLossCNode(graph); });
  1766. return loss_node;
  1767. }
  1768. void ParallelCommunication(const FuncGraphPtr &root, const std::vector<AnfNodePtr> &all_nodes,
  1769. const FuncGraphManagerPtr &manager) {
  1770. MS_EXCEPTION_IF_NULL(root);
  1771. MS_EXCEPTION_IF_NULL(manager);
  1772. TensorRedistribution tensor_redistribution;
  1773. AnfNodePtr grad_sens_node = nullptr;
  1774. std::vector<CNodePtr> loss_cnode = FindLossCNodeFromRoot(root);
  1775. // split sens must before inserting the operators.
  1776. for (auto &node : all_nodes) {
  1777. // If the shape of grad-sens tensor is not [] or [1], use get tensor slice to handel it.
  1778. // If the type of sens node is not Tensor, it is unsupported now, do nothing default.
  1779. StepSplitSens(node);
  1780. }
  1781. for (auto &node : all_nodes) {
  1782. MS_EXCEPTION_IF_NULL(node);
  1783. if (node->isa<CNode>()) {
  1784. auto cnode = node->cast<CNodePtr>();
  1785. MS_EXCEPTION_IF_NULL(cnode);
  1786. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1787. continue;
  1788. }
  1789. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1790. if (distribute_operator == nullptr) {
  1791. continue;
  1792. }
  1793. bool is_loss_cnode = false;
  1794. auto iter = std::find(loss_cnode.begin(), loss_cnode.end(), cnode);
  1795. if (iter != loss_cnode.end()) {
  1796. is_loss_cnode = true;
  1797. }
  1798. // insert forward ops
  1799. InsertForwardOps(distribute_operator, cnode);
  1800. // insert redistribution ops
  1801. StepRedistribution(cnode, distribute_operator, cnode, tensor_redistribution, cnode);
  1802. // insert backward ops
  1803. BackwardCommunication(distribute_operator, cnode, is_loss_cnode);
  1804. // StepReplace
  1805. StepReplace(distribute_operator, cnode);
  1806. HandleSpecialNode(distribute_operator, cnode);
  1807. } else if (IsValueNode<Tensor>(node)) {
  1808. StepSplitTensor(node, manager);
  1809. }
  1810. }
  1811. }
  1812. namespace {
  1813. void RevertSymbolicKeyInstance(const FuncGraphPtr &root, const AnfNodePtr &node) {
  1814. MS_EXCEPTION_IF_NULL(root);
  1815. MS_EXCEPTION_IF_NULL(node);
  1816. auto symbolic_key = GetValueNode<SymbolicKeyInstancePtr>(node);
  1817. MS_EXCEPTION_IF_NULL(symbolic_key);
  1818. auto all_upstream_node = root->manager()->node_users()[node];
  1819. for (auto &upstream_node : all_upstream_node) {
  1820. FuncGraphPtr fg = upstream_node.first->func_graph();
  1821. if (symbolic_key->node()->isa<Parameter>()) {
  1822. for (auto &param : root->parameters()) {
  1823. if (*param == *symbolic_key->node()) {
  1824. AnfNodePtr reverted_node = root->NewCNode({NewValueNode(prim::kPrimEmbed), param});
  1825. MS_EXCEPTION_IF_NULL(reverted_node);
  1826. MS_LOG(DEBUG) << "before replace " << node->ToString() << " to node " << reverted_node->DebugString();
  1827. (void)fg->manager()->Replace(node, reverted_node);
  1828. MS_LOG(DEBUG) << "revert node " << node->ToString() << " to node " << reverted_node->DebugString();
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. } // namespace
  1835. void HandleSymbolicKeyInstance(const FuncGraphPtr &root, const std::vector<AnfNodePtr> &all_nodes) {
  1836. MS_EXCEPTION_IF_NULL(root);
  1837. for (auto &node : all_nodes) {
  1838. // revert back SymbolicKeyInstance to embed() primitive
  1839. if (IsValueNode<SymbolicKeyInstance>(node)) {
  1840. RevertSymbolicKeyInstance(root, node);
  1841. continue;
  1842. }
  1843. }
  1844. }
  1845. void CheckpointStrategy(const FuncGraphPtr &func_graph) {
  1846. MS_EXCEPTION_IF_NULL(func_graph);
  1847. MS_LOG(INFO) << "Save strategy to checkpoint begin";
  1848. StrategyMap straMap;
  1849. auto ret = func_graph->get_return();
  1850. auto all_nodes = DeepScopedGraphSearch(ret);
  1851. for (auto &node : all_nodes) {
  1852. MS_EXCEPTION_IF_NULL(node);
  1853. auto cnode = node->cast<CNodePtr>();
  1854. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1855. continue;
  1856. }
  1857. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1858. MS_EXCEPTION_IF_NULL(prim);
  1859. OperatorInfoPtr operator_info = cnode->operator_info();
  1860. if (operator_info) {
  1861. if (prim->instance_name().empty()) {
  1862. continue;
  1863. }
  1864. std::string instance_name = prim->instance_name();
  1865. StrategyPtr strategyPtr = operator_info->strategy();
  1866. MS_EXCEPTION_IF_NULL(node->scope());
  1867. std::string node_name = node->scope()->name() + std::string(CONNSYMBOL) + instance_name;
  1868. straMap[node_name] = strategyPtr;
  1869. }
  1870. }
  1871. if (StrategyCheckpoint::GetInstance().Save(straMap) != SUCCESS) {
  1872. MS_LOG(EXCEPTION) << "Save strategy checkpoint failed";
  1873. }
  1874. }
  1875. void RestoreStrategy(const FuncGraphPtr &func_graph) {
  1876. MS_EXCEPTION_IF_NULL(func_graph);
  1877. MS_LOG(INFO) << "Extract strategy from checkpoint begin";
  1878. StrategyMap straMap;
  1879. if (StrategyCheckpoint::GetInstance().Load(&straMap) != SUCCESS) {
  1880. MS_LOG(EXCEPTION) << "Load strategy checkpoint failed";
  1881. }
  1882. if (StrategyCheckpoint::GetInstance().RemoveCheckPoint() != SUCCESS) {
  1883. MS_LOG(EXCEPTION) << "Remove strategy checkpoint failed";
  1884. }
  1885. auto ret = func_graph->get_return();
  1886. auto all_nodes = DeepScopedGraphSearch(ret);
  1887. for (auto &node : all_nodes) {
  1888. MS_EXCEPTION_IF_NULL(node);
  1889. auto cnode = node->cast<CNodePtr>();
  1890. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1891. continue;
  1892. }
  1893. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1894. MS_EXCEPTION_IF_NULL(prim);
  1895. OperatorInfoPtr operator_info = cnode->operator_info();
  1896. if (operator_info) {
  1897. if (prim->instance_name().empty()) {
  1898. continue;
  1899. }
  1900. std::string instance_name = prim->instance_name();
  1901. MS_EXCEPTION_IF_NULL(node->scope());
  1902. std::string node_name = node->scope()->name() + std::string(CONNSYMBOL) + instance_name;
  1903. MS_LOG(INFO) << "Node name is " << node_name;
  1904. if (straMap.find(node_name) != straMap.end()) {
  1905. StrategyPtr strategyPtr = straMap[node_name];
  1906. operator_info->set_strategy(strategyPtr);
  1907. }
  1908. }
  1909. }
  1910. }
  1911. void SetForwardFlag(const std::vector<AnfNodePtr> &all_nodes) {
  1912. for (auto &node : all_nodes) {
  1913. MS_EXCEPTION_IF_NULL(node);
  1914. if (!node->isa<CNode>()) {
  1915. continue;
  1916. }
  1917. auto cnode = node->cast<CNodePtr>();
  1918. MS_EXCEPTION_IF_NULL(cnode);
  1919. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1920. continue;
  1921. }
  1922. // CNode is globally unique.
  1923. MS_LOG(DEBUG) << "Set forward flag " << cnode->DebugString() << ".";
  1924. cnode->set_in_forward_flag(true);
  1925. }
  1926. }
  1927. void SetForwardFlag(const AnfNodeSet &all_nodes) {
  1928. for (auto &node : all_nodes) {
  1929. MS_EXCEPTION_IF_NULL(node);
  1930. if (!node->isa<CNode>()) {
  1931. continue;
  1932. }
  1933. auto cnode = node->cast<CNodePtr>();
  1934. MS_EXCEPTION_IF_NULL(cnode);
  1935. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1936. continue;
  1937. }
  1938. // CNode is globally unique.
  1939. cnode->set_in_forward_flag(true);
  1940. }
  1941. }
  1942. std::set<FuncGraphPtr> ForwardGraph(const FuncGraphPtr &root) {
  1943. MS_EXCEPTION_IF_NULL(root);
  1944. const auto &all_nodes = root->nodes();
  1945. std::set<FuncGraphPtr> graph_set = FindForwardGraphByRootNodes(all_nodes);
  1946. return graph_set;
  1947. }
  1948. std::vector<AnfNodePtr> FindRootForwardCNode(const FuncGraphPtr &graph, const AnfNodeSet &all_nodes) {
  1949. MS_EXCEPTION_IF_NULL(graph);
  1950. auto loss_cnode = FindLossCNode(graph);
  1951. MS_EXCEPTION_IF_NULL(loss_cnode);
  1952. auto loss_cnode_id = loss_cnode->UniqueIdThroughCopy();
  1953. std::vector<AnfNodePtr> root_forward_nodes;
  1954. for (auto &node : all_nodes) {
  1955. MS_EXCEPTION_IF_NULL(node);
  1956. if (!node->isa<CNode>()) {
  1957. continue;
  1958. }
  1959. auto cnode = node->cast<CNodePtr>();
  1960. MS_EXCEPTION_IF_NULL(cnode);
  1961. auto root_node_id = node->UniqueIdThroughCopy();
  1962. if (loss_cnode_id == root_node_id) {
  1963. root_forward_nodes = DeepLinkedGraphSearch(cnode);
  1964. break;
  1965. }
  1966. }
  1967. return root_forward_nodes;
  1968. }
  1969. void MarkForwardCNode(const FuncGraphPtr &root) {
  1970. MS_EXCEPTION_IF_NULL(root);
  1971. auto all_nodes = root->nodes();
  1972. std::set<FuncGraphPtr> graph_set = FindForwardGraphByRootNodes(all_nodes);
  1973. if (graph_set.empty()) {
  1974. MS_LOG(INFO) << "Can not find the forward graph, so mark the ops in root graph";
  1975. SetForwardFlag(all_nodes);
  1976. } else {
  1977. for (auto &func_graph : graph_set) {
  1978. MS_LOG(INFO) << "The sub graph size of root is " << root->func_graphs_used().size();
  1979. auto return_node = func_graph->get_return();
  1980. MS_EXCEPTION_IF_NULL(return_node);
  1981. auto all_dfs_nodes = DeepLinkedGraphSearch(return_node);
  1982. SetForwardFlag(all_dfs_nodes);
  1983. auto root_forward_nodes = FindRootForwardCNode(func_graph, all_nodes);
  1984. if (root_forward_nodes.empty()) {
  1985. continue;
  1986. }
  1987. // Mark forward flag for the nodes in root graph.
  1988. SetForwardFlag(root_forward_nodes);
  1989. }
  1990. }
  1991. }
  1992. Status ParallelInit() {
  1993. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  1994. int32_t device_num = ParallelContext::GetInstance()->device_num();
  1995. int32_t global_rank = ParallelContext::GetInstance()->global_rank();
  1996. std::string backend = ParallelContext::GetInstance()->communication_backend();
  1997. std::string world_group;
  1998. if (backend == HCCL_BACKEND) {
  1999. world_group = HCCL_WORLD_GROUP;
  2000. } else if (backend == NCCL_BACKEND) {
  2001. world_group = NCCL_WORLD_GROUP;
  2002. } else {
  2003. MS_LOG(EXCEPTION) << "Invalid communication backend: " << backend;
  2004. }
  2005. uint32_t world_rank_size = 0;
  2006. if (!ParallelContext::GetInstance()->device_num_is_set()) {
  2007. if (!CommManager::GetInstance().GetRankSize(world_group, &world_rank_size)) {
  2008. MS_LOG(EXCEPTION) << "Get rank size failed";
  2009. }
  2010. device_num = UintToInt(world_rank_size);
  2011. MS_LOG(INFO) << "Get device num from communication model, the device num is " << device_num;
  2012. }
  2013. uint32_t rank_id = 0;
  2014. if (!ParallelContext::GetInstance()->global_rank_is_set()) {
  2015. if (!CommManager::GetInstance().GetRankID(world_group, &rank_id)) {
  2016. MS_LOG(EXCEPTION) << "Get rank id failed";
  2017. }
  2018. global_rank = UintToInt(rank_id);
  2019. MS_LOG(INFO) << "Get global rank from communication model, the global rank is " << global_rank;
  2020. }
  2021. if (!InitDevice(device_num, global_rank, backend)) {
  2022. MS_LOG(ERROR) << "Init device failed";
  2023. return FAILED;
  2024. }
  2025. MS_LOG(INFO) << "The parallel context: dev num: " << device_num << ", global rank: " << global_rank
  2026. << ", backend: " << backend << ", mirror_mean: " << ParallelContext::GetInstance()->mirror_mean()
  2027. << ", cast_before_mirror: " << ParallelContext::GetInstance()->cast_before_mirror();
  2028. return SUCCESS;
  2029. }
  2030. bool StepParallel(const FuncGraphPtr &root, const opt::OptimizerPtr &optimizer) {
  2031. MS_EXCEPTION_IF_NULL(root);
  2032. MS_EXCEPTION_IF_NULL(optimizer);
  2033. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  2034. std::string parallel_mode = ParallelContext::GetInstance()->parallel_mode();
  2035. // assume no change to graph
  2036. bool changes = false;
  2037. // control whether use model_parallel mode
  2038. if (((parallel_mode != AUTO_PARALLEL) && (parallel_mode != SEMI_AUTO_PARALLEL)) ||
  2039. (root->has_flag(SEMI_AUTO_PARALLEL_RUN_ONCE_ONLY))) {
  2040. return changes;
  2041. }
  2042. struct timeval start_time, end_time;
  2043. (void)gettimeofday(&start_time, nullptr);
  2044. MS_LOG(INFO) << "Now entering step parallel";
  2045. DumpGraph(root, std::string(STEP_PARALLEL_BEGIN));
  2046. pipeline::ResourceBasePtr res = optimizer->resource();
  2047. MS_EXCEPTION_IF_NULL(res);
  2048. FuncGraphManagerPtr manager = res->manager();
  2049. MS_EXCEPTION_IF_NULL(manager);
  2050. AnfNodePtr ret = root->get_return();
  2051. MS_EXCEPTION_IF_NULL(ret);
  2052. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  2053. std::reverse(all_nodes.begin(), all_nodes.end());
  2054. if (parallel_mode != AUTO_PARALLEL) {
  2055. TOTAL_OPS = 0;
  2056. if (ParallelInit() != SUCCESS) {
  2057. MS_LOG(EXCEPTION) << "Parallel init failed";
  2058. }
  2059. // mark the forward cnodes, parallel only care these nodes
  2060. MarkForwardCNode(root);
  2061. if (FindCommunicationOp(all_nodes)) {
  2062. MS_LOG(EXCEPTION) << "The graph contain communication op";
  2063. }
  2064. // extract shape and strategy, set operator_info
  2065. ExtractInformation(all_nodes);
  2066. ReshapeInit(all_nodes);
  2067. // extract strategy from checkpoint for multi-train
  2068. if (StrategyCheckpoint::GetInstance().CheckPointOn() && StrategyCheckpoint::GetInstance().CheckPointExit()) {
  2069. RestoreStrategy(root);
  2070. }
  2071. }
  2072. // save strategy as checkpoint for multi-train
  2073. if (StrategyCheckpoint::GetInstance().CheckPointOn() &&
  2074. StrategyCheckpoint::GetInstance().GetCurrentTrainTime() < StrategyCheckpoint::GetInstance().GetTrainTimes()) {
  2075. CheckpointStrategy(root);
  2076. }
  2077. HandleSymbolicKeyInstance(root, all_nodes);
  2078. // cover Parallel shape
  2079. CoverSliceShape(root);
  2080. // set the shape for optimizer's clone tensor
  2081. SetClonedTensorShapeForOptimizer(root);
  2082. // ForwardCommunication BackwardCommunication TensorRedistribution
  2083. ParallelCommunication(root, all_nodes, manager);
  2084. DumpGraph(root, std::string(STEP_PARALLEL_END));
  2085. // step parallel only run once
  2086. root->flags()[SEMI_AUTO_PARALLEL_RUN_ONCE_ONLY] = true;
  2087. res->results()[pipeline::kStepParallelGraph] = root;
  2088. (void)gettimeofday(&end_time, nullptr);
  2089. uint64_t time = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec);
  2090. time += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec);
  2091. MS_LOG(INFO) << "Now leaving step parallel, used time: " << time << " us";
  2092. return changes;
  2093. }
  2094. // Needed by rec_parser
  2095. std::vector<std::string> ExtractInputsTensorName(const CNodePtr &node) {
  2096. std::vector<std::string> name_inputs;
  2097. std::vector<AnfNodePtr> all_inputs = node->inputs();
  2098. std::vector<AnfNodePtr> node_inputs{all_inputs.begin() + 1, all_inputs.end()};
  2099. std::string node_id = node->UniqueId();
  2100. name_inputs.push_back(node_id);
  2101. for (auto &input : node_inputs) {
  2102. std::string name = input->UniqueId();
  2103. name_inputs.push_back(name);
  2104. }
  2105. return name_inputs;
  2106. }
  2107. } // namespace parallel
  2108. } // namespace mindspore