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

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