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

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