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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189
  1. /**
  2. * Copyright 2019-2020 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 "frontend/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 "frontend/operator/ops.h"
  27. #include "frontend/optimizer/optimizer.h"
  28. #include "frontend/parallel/auto_parallel/graph_costmodel.h"
  29. #include "frontend/parallel/context.h"
  30. #include "frontend/parallel/device_manager.h"
  31. #include "frontend/parallel/dynamic_creator.h"
  32. #include "frontend/parallel/graph_util/generate_graph.h"
  33. #include "frontend/parallel/graph_util/graph_info.h"
  34. #include "frontend/parallel/graph_util/node_info.h"
  35. #include "frontend/parallel/node_check.h"
  36. #include "frontend/parallel/ops_info/matmul_info.h"
  37. #include "frontend/parallel/strategy_checkpoint/parallel_strategy_checkpoint.h"
  38. #include "ir/param_info.h"
  39. #include "ir/tensor.h"
  40. #include "utils/comm_manager.h"
  41. #include "utils/ms_context.h"
  42. #include "utils/symbolic.h"
  43. using mindspore::tensor::Tensor;
  44. namespace mindspore {
  45. namespace parallel {
  46. static const std::set<std::string> COMMUNICATION_OPS = {ALL_REDUCE, ALL_GATHER, ALL_TO_ALL, REDUCE_SCATTER};
  47. static const std::set<std::string> INVALID_LOSS_OPS = {GET_NEXT, VIRTUALLOSS};
  48. // g_RefMap, for CNode B input i is a RefKey[Parameter C],
  49. // it will be one item in map with key: C, and value: (B, i)
  50. static std::map<AnfNodePtr, std::pair<AnfNodePtr, int64_t>> g_RefMap;
  51. void SetCommunicationOpGroupLabel(std::vector<AnfNodePtr> new_node_input) {
  52. if (new_node_input.empty()) {
  53. return;
  54. }
  55. ValueNodePtr prim_anf_node = new_node_input[0]->cast<ValueNodePtr>();
  56. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  57. MS_EXCEPTION_IF_NULL(prim);
  58. auto attrs = prim->attrs();
  59. auto iter = attrs.find(GROUP);
  60. if (iter != attrs.end()) {
  61. auto value = iter->second;
  62. MS_EXCEPTION_IF_NULL(value);
  63. if (value->isa<StringImm>()) {
  64. std::string hash_name = value->cast<StringImmPtr>()->value();
  65. MS_EXCEPTION_IF_NULL(g_device_manager);
  66. std::string rank_list_name = g_device_manager->FindRankListNameByHashName(hash_name);
  67. (void)prim->AddAttr(GROUP_RANKS, MakeValue(rank_list_name));
  68. }
  69. }
  70. }
  71. std::vector<AnfNodePtr> CreateInput(const Operator &op, const AnfNodePtr &node, const std::string &instance_name) {
  72. MS_EXCEPTION_IF_NULL(node);
  73. OperatorArgs arg_forward = op.second;
  74. ValuePtr pyop_instance = CreatOpInstance(arg_forward.first, op.first, instance_name);
  75. MS_EXCEPTION_IF_NULL(pyop_instance);
  76. OperatorParams params = arg_forward.second;
  77. std::vector<AnfNodePtr> new_node_input = {NewValueNode(pyop_instance), node};
  78. if (!params.empty()) {
  79. for (auto &param : params) {
  80. AnfNodePtr val = NewValueNode(param.first.second);
  81. MS_EXCEPTION_IF_NULL(val);
  82. int64_t position = param.second;
  83. (void)new_node_input.insert(new_node_input.begin() + position, val);
  84. }
  85. }
  86. // if the op have 'group' attr, set the rank list name for the op
  87. SetCommunicationOpGroupLabel(new_node_input);
  88. return new_node_input;
  89. }
  90. void InsertNode(const Operator &op, const CNodePtr &node, size_t index, const AnfNodePtr &pre_node,
  91. const FuncGraphPtr &func_graph, const std::string &instance_name) {
  92. // insert new node before the node
  93. FuncGraphManagerPtr manager = func_graph->manager();
  94. MS_EXCEPTION_IF_NULL(manager);
  95. ScopePtr scope = node->scope();
  96. MS_EXCEPTION_IF_NULL(scope);
  97. std::vector<AnfNodePtr> node_input = CreateInput(op, pre_node, instance_name);
  98. CNodePtr new_node = func_graph->NewCNode(node_input);
  99. MS_EXCEPTION_IF_NULL(new_node);
  100. if (instance_name.find(SPLIT_SENS) == std::string::npos) {
  101. new_node->set_in_forward_flag(true); // mark forward flag
  102. }
  103. auto new_node_value = node_input[0]->cast<ValueNodePtr>();
  104. MS_EXCEPTION_IF_NULL(new_node_value);
  105. PrimitivePtr new_node_prim = new_node_value->value()->cast<PrimitivePtr>();
  106. new_node_prim->set_instance_name(instance_name);
  107. new_node_prim->set_attr("keep_value_node_input", MakeValue(true));
  108. new_node->set_scope(scope);
  109. node_input[0]->set_scope(scope);
  110. manager->SetEdge(node, SizeToLong(index), new_node);
  111. MS_LOG(INFO) << "Insert " << instance_name << " success";
  112. }
  113. // Replace pre_node with pre_node->op
  114. static CNodePtr ReplaceNode(const Operator &op, const AnfNodePtr &pre_node, const FuncGraphPtr &func_graph,
  115. const std::string &instance_name) {
  116. // insert new node before the node
  117. FuncGraphManagerPtr manager = func_graph->manager();
  118. MS_EXCEPTION_IF_NULL(manager);
  119. ScopePtr scope = pre_node->scope();
  120. MS_EXCEPTION_IF_NULL(scope);
  121. std::vector<AnfNodePtr> node_input = CreateInput(op, pre_node, instance_name);
  122. CNodePtr new_node = func_graph->NewCNode(node_input);
  123. MS_EXCEPTION_IF_NULL(new_node);
  124. if (instance_name.find(SPLIT_SENS) == std::string::npos) {
  125. new_node->set_in_forward_flag(true); // mark forward flag
  126. }
  127. auto new_node_prim = GetValueNode<PrimitivePtr>(node_input[0]);
  128. new_node_prim->set_instance_name(instance_name);
  129. new_node_prim->set_attr("keep_value_node_input", MakeValue(true));
  130. new_node->set_scope(scope);
  131. node_input[0]->set_scope(scope);
  132. manager->Replace(pre_node, new_node);
  133. MS_LOG(INFO) << "Insert " << instance_name << " success";
  134. return new_node;
  135. }
  136. std::string CreateInstanceName(const CNodePtr &node, size_t index) {
  137. MS_EXCEPTION_IF_NULL(node);
  138. if (!IsValueNode<Primitive>(node->input(0))) {
  139. MS_LOG(EXCEPTION) << "CreateInstanceName: " << node->ToString() << " doesn't have primitive";
  140. }
  141. std::string name_base = node->fullname_with_scope();
  142. std::string name = name_base + "_" + std::to_string(index);
  143. std::string instance_name = HashInstanceName(name);
  144. return instance_name;
  145. }
  146. void ForwardCommunication(OperatorVector forward_op, const CNodePtr &node) {
  147. MS_EXCEPTION_IF_NULL(node);
  148. // step1:get graph manager distribute_operator
  149. FuncGraphPtr func_graph = node->func_graph();
  150. MS_EXCEPTION_IF_NULL(func_graph);
  151. FuncGraphManagerPtr manager = func_graph->manager();
  152. MS_EXCEPTION_IF_NULL(manager);
  153. auto uses_set = manager->node_users()[node];
  154. CNodePtr node_to_insert = node;
  155. for (auto &uses_pair : uses_set) {
  156. auto uses_cnode = uses_pair.first->cast<CNodePtr>();
  157. MS_EXCEPTION_IF_NULL(uses_cnode);
  158. if (!IsValueNode<Primitive>(uses_cnode->input(0))) {
  159. break;
  160. }
  161. PrimitivePtr value_node_prim = GetValueNode<PrimitivePtr>(uses_cnode->input(0));
  162. MS_EXCEPTION_IF_NULL(value_node_prim);
  163. if (value_node_prim->name() == TUPLE_GETITEM) {
  164. if (uses_set.size() > 1) {
  165. MS_LOG(EXCEPTION) << "Now only support one output, but got " << uses_set.size();
  166. }
  167. node_to_insert = uses_cnode;
  168. }
  169. }
  170. MS_EXCEPTION_IF_NULL(node_to_insert);
  171. std::reverse(forward_op.begin(), forward_op.end());
  172. // step2:traverse op_list and insert node
  173. for (size_t index = 0; index < forward_op.size(); ++index) {
  174. std::string instance_name_base = FORWARD_OP;
  175. std::string instance_name = instance_name_base + "_" + CreateInstanceName(node, index);
  176. std::vector<AnfNodePtr> forward_input = CreateInput(forward_op[index], node_to_insert, instance_name);
  177. CNodePtr forward_node = func_graph->NewCNode(forward_input); // using NewCNode to creat anfnode
  178. MS_EXCEPTION_IF_NULL(forward_node);
  179. ScopePtr scope = node->scope();
  180. MS_EXCEPTION_IF_NULL(scope);
  181. forward_node->set_scope(scope);
  182. forward_node->set_in_forward_flag(true);
  183. forward_input[0]->set_scope(scope);
  184. (void)manager->Replace(node_to_insert, forward_node); // using Replace function to insert node
  185. }
  186. }
  187. CNodePtr InsertMakeTuple(const AnfNodePtr &prev, uint64_t num, const FuncGraphPtr &func_graph) {
  188. MS_EXCEPTION_IF_NULL(prev);
  189. MS_EXCEPTION_IF_NULL(func_graph);
  190. std::vector<AnfNodePtr> make_tuple_inputs;
  191. make_tuple_inputs.push_back(NewValueNode(prim::kPrimMakeTuple));
  192. for (uint64_t i = 0; i < num; i++) {
  193. std::vector<AnfNodePtr> tuple_get_item_inputs{NewValueNode(prim::kPrimTupleGetItem), prev,
  194. CreatInt64Imm(UlongToLong(i))};
  195. auto tuple_get_item = func_graph->NewCNode(tuple_get_item_inputs);
  196. MS_EXCEPTION_IF_NULL(tuple_get_item);
  197. make_tuple_inputs.push_back(tuple_get_item);
  198. }
  199. auto make_tuple = func_graph->NewCNode(make_tuple_inputs);
  200. MS_EXCEPTION_IF_NULL(make_tuple);
  201. FuncGraphManagerPtr manager = func_graph->manager();
  202. MS_EXCEPTION_IF_NULL(manager);
  203. (void)manager->Replace(prev, make_tuple);
  204. return make_tuple;
  205. }
  206. void InsertRedistribution(const RedistributionOpListPtr &redistribution_oplist_ptr, const CNodePtr &node,
  207. const FuncGraphPtr &func_graph, int64_t pos, const CNodePtr &pre_node) {
  208. MS_EXCEPTION_IF_NULL(node);
  209. MS_EXCEPTION_IF_NULL(pre_node);
  210. MS_EXCEPTION_IF_NULL(func_graph);
  211. FuncGraphManagerPtr manager = func_graph->manager();
  212. MS_EXCEPTION_IF_NULL(manager);
  213. if ((redistribution_oplist_ptr->first).size() != (redistribution_oplist_ptr->second).size()) {
  214. MS_LOG(EXCEPTION) << "size of OperatorVector and OutPutInfoVector must be the same!";
  215. }
  216. for (size_t index = 0; index < (redistribution_oplist_ptr->first).size(); ++index) {
  217. if (pos >= SizeToLong(node->inputs().size())) {
  218. MS_LOG(EXCEPTION) << "InsertRedistribution:pos can't be larger than node's inputs'size";
  219. }
  220. // Creat new node
  221. AnfNodePtr target_node = node->input(LongToSize(pos));
  222. MS_EXCEPTION_IF_NULL(target_node);
  223. // Creat instance_name
  224. auto op = (redistribution_oplist_ptr->first)[index];
  225. std::string op_name = (redistribution_oplist_ptr->first)[index].first;
  226. std::string instance_name_base = REDISTRIBUTION_OP;
  227. std::string instance_name = instance_name_base + "_" + CreateInstanceName(pre_node, index) + op_name;
  228. InsertNode(op, node, LongToSize(pos), target_node, func_graph, instance_name);
  229. if ((redistribution_oplist_ptr->second)[index].first) {
  230. target_node = node->input(LongToSize(pos));
  231. MS_EXCEPTION_IF_NULL(target_node);
  232. (void)InsertMakeTuple(target_node, (redistribution_oplist_ptr->second)[index].second, func_graph);
  233. }
  234. }
  235. }
  236. void InsertGetTensorSliceOp(const Operator &op, const CNodePtr &node, const FuncGraphPtr &func_graph, int64_t pos,
  237. const std::string &instance_name) {
  238. if (func_graph == nullptr) {
  239. MS_LOG(EXCEPTION) << "InsertGetTensorSliceOp: the graph is null, the instance name is " << instance_name;
  240. }
  241. FuncGraphManagerPtr manager = func_graph->manager();
  242. MS_EXCEPTION_IF_NULL(manager);
  243. if (pos >= SizeToLong(node->inputs().size())) {
  244. MS_LOG(EXCEPTION) << "InsertGetTensorSliceOp: pos can't be larger than node's inputs'size, the instance name is "
  245. << instance_name;
  246. }
  247. // Creat new node
  248. AnfNodePtr pre_node = node->input(LongToSize(pos));
  249. MS_EXCEPTION_IF_NULL(pre_node);
  250. InsertNode(op, node, LongToSize(pos), pre_node, func_graph, instance_name);
  251. }
  252. TensorLayout GetTensorInLayout(const CNodePtr &middle_node, const PrimitivePtr &middle_prim,
  253. const OperatorInfoPtr &distribute_operator) {
  254. TensorInfo tensorinfo_in;
  255. if (middle_prim->name() == TUPLE_GETITEM) {
  256. auto value_node = middle_node->input(2)->cast<ValueNodePtr>();
  257. MS_EXCEPTION_IF_NULL(value_node);
  258. size_t index_s = LongToSize(GetValue<int64_t>(value_node->value()));
  259. if (index_s >= distribute_operator->outputs_tensor_info().size()) {
  260. MS_LOG(EXCEPTION) << "The index out of range, index: " << index_s
  261. << ", vector size: " << distribute_operator->outputs_tensor_info().size();
  262. }
  263. tensorinfo_in = distribute_operator->outputs_tensor_info()[index_s];
  264. } else {
  265. if (distribute_operator->outputs_tensor_info().empty()) {
  266. MS_LOG(EXCEPTION) << "The outputs tensor info is empty";
  267. }
  268. tensorinfo_in = distribute_operator->outputs_tensor_info()[0];
  269. }
  270. return tensorinfo_in.tensor_layout();
  271. }
  272. bool AnfNodeIsPrimitive(const AnfNodePtr &anf_node, const std::string &prim_name) {
  273. MS_EXCEPTION_IF_NULL(anf_node);
  274. auto cnode = anf_node->cast<CNodePtr>();
  275. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  276. return false;
  277. }
  278. auto value_node = cnode->input(0)->cast<ValueNodePtr>();
  279. auto prim = GetValueNode<PrimitivePtr>(value_node);
  280. MS_EXCEPTION_IF_NULL(prim);
  281. if (prim->name() == prim_name) {
  282. return true;
  283. }
  284. return false;
  285. }
  286. std::string GetPrimName(const CNodePtr &node) {
  287. MS_EXCEPTION_IF_NULL(node);
  288. if (!IsValueNode<Primitive>(node->input(0))) {
  289. MS_LOG(EXCEPTION) << "The node is not a primitive";
  290. }
  291. auto value_node = node->input(0)->cast<ValueNodePtr>();
  292. auto prim = GetValueNode<PrimitivePtr>(value_node);
  293. MS_EXCEPTION_IF_NULL(prim);
  294. return prim->name();
  295. }
  296. OperatorInfoPtr GetDistributeOperator(const CNodePtr &node) {
  297. MS_EXCEPTION_IF_NULL(node);
  298. if (!IsParallelCareNode(node)) {
  299. return nullptr;
  300. }
  301. OperatorInfoPtr distribute_operator = node->user_data<OperatorInfo>();
  302. if (distribute_operator == nullptr) {
  303. MS_LOG(EXCEPTION) << "Distribute operator is nullptr, the prim is " << GetPrimName(node);
  304. }
  305. return distribute_operator;
  306. }
  307. void Redistribution(const std::pair<AnfNodePtr, int64_t> &node_pair, const OperatorInfoPtr &distribute_operator,
  308. const CNodePtr &middle_node, int64_t index, TensorRedistribution tensor_redistribution,
  309. const CNodePtr &pre_node) {
  310. FuncGraphPtr func_graph = middle_node->func_graph();
  311. if (func_graph == nullptr) {
  312. MS_LOG(EXCEPTION) << "Redistribution:get graph failed";
  313. }
  314. CNodePtr next_node = node_pair.first->cast<CNodePtr>();
  315. MS_EXCEPTION_IF_NULL(next_node);
  316. auto middle_value = middle_node->input(0)->cast<ValueNodePtr>();
  317. MS_EXCEPTION_IF_NULL(middle_value);
  318. PrimitivePtr middle_prim = middle_value->value()->cast<PrimitivePtr>();
  319. MS_EXCEPTION_IF_NULL(middle_prim);
  320. OperatorInfoPtr next_distribute_operator = GetDistributeOperator(next_node);
  321. if (next_distribute_operator == nullptr) {
  322. MS_LOG(EXCEPTION) << "Failure: " << next_node->ToString() << " GetDistributeOperator failed";
  323. }
  324. RankList dev_list = distribute_operator->stage_device_list();
  325. std::string next_prim_name = GetValueNode<PrimitivePtr>(next_node->input(0))->name();
  326. MS_LOG(DEBUG) << "Redistribution: middle_prim " << middle_prim->name() << " next_prim " << next_prim_name;
  327. MS_LOG(DEBUG) << "Redistribution: middle_node " << middle_node->ToString() << " next_node " << next_node->ToString();
  328. // extract tensor layout in and out
  329. if (distribute_operator->outputs_tensor_info().empty()) {
  330. MS_LOG(WARNING) << "pre_node's tensorinfo_in is empty, operator name is " << distribute_operator->name();
  331. return;
  332. }
  333. if (LongToSize(index - 1) >= next_distribute_operator->inputs_tensor_info().size()) {
  334. MS_LOG(WARNING) << "The index is out of range, the index is " << index - 1 << ", the vector size is "
  335. << next_distribute_operator->inputs_tensor_info().size() << "next operator name is "
  336. << next_distribute_operator->name();
  337. return;
  338. }
  339. TensorInfo tensorinfo_out = next_distribute_operator->inputs_tensor_info()[LongToSize(index - 1)];
  340. TensorLayout tensorlayout_out = tensorinfo_out.tensor_layout();
  341. TensorLayout tensorlayout_in = GetTensorInLayout(middle_node, middle_prim, distribute_operator);
  342. if (tensor_redistribution.Init(tensorlayout_in, tensorlayout_out, dev_list) == FAILED) {
  343. MS_LOG(ERROR) << "Redistribution: middle_prim " << middle_prim->name() << " next_prim : " << next_prim_name;
  344. MS_LOG(ERROR) << "Redistribution: middle_node " << middle_node->ToString() << " next_node "
  345. << next_node->ToString();
  346. DumpGraph(func_graph, "redistribution_error");
  347. MS_LOG(EXCEPTION) << "Failure:tensor_redistribution init failed";
  348. }
  349. RedistributionOpListPtr redistribution_oplist_ptr = tensor_redistribution.InferTensorRedistributionOperatorList();
  350. if (redistribution_oplist_ptr == nullptr) {
  351. MS_LOG(EXCEPTION) << "Failure:InferTensorRedistribution failed";
  352. }
  353. MS_LOG(DEBUG) << "Redistribution size " << redistribution_oplist_ptr->first.size();
  354. if (!redistribution_oplist_ptr->first.empty()) {
  355. // insert node before next node
  356. InsertRedistribution(redistribution_oplist_ptr, next_node, func_graph, node_pair.second, pre_node);
  357. }
  358. }
  359. bool StrategyFound(std::unordered_map<std::string, ValuePtr> attrs) {
  360. auto iter = attrs.find(STRATEGY);
  361. return !((iter == attrs.end()) || (iter->second->type_name() == NONE));
  362. }
  363. bool HasStrategy(const FuncGraphPtr &root) {
  364. AnfNodePtr ret = root->get_return();
  365. MS_EXCEPTION_IF_NULL(ret);
  366. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  367. for (auto &node : all_nodes) {
  368. auto cnode = node->cast<CNodePtr>();
  369. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  370. continue;
  371. }
  372. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  373. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  374. auto attrs = prim->attrs();
  375. if (StrategyFound(attrs)) {
  376. return true;
  377. }
  378. }
  379. return false;
  380. }
  381. bool IsCommunicationOp(const PrimitivePtr &prim) {
  382. MS_EXCEPTION_IF_NULL(prim);
  383. return (COMMUNICATION_OPS.find(prim->name()) != COMMUNICATION_OPS.end());
  384. }
  385. bool FindCommunicationOp(const std::vector<AnfNodePtr> &all_nodes) {
  386. for (auto &node : all_nodes) {
  387. MS_EXCEPTION_IF_NULL(node);
  388. if (!node->isa<CNode>()) {
  389. continue;
  390. }
  391. auto cnode = node->cast<CNodePtr>();
  392. if (!IsValueNode<Primitive>(cnode->input(0))) {
  393. continue;
  394. }
  395. ValueNodePtr prim_value_node = cnode->input(0)->cast<ValueNodePtr>();
  396. MS_EXCEPTION_IF_NULL(prim_value_node);
  397. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_value_node);
  398. MS_EXCEPTION_IF_NULL(prim);
  399. if (IsCommunicationOp(prim) && cnode->in_forward_flag()) {
  400. MS_EXCEPTION_IF_NULL(prim_value_node->scope());
  401. MS_LOG(INFO) << "The graph contain communication op: " << prim->name() << ", scope name is "
  402. << prim_value_node->scope()->name();
  403. return true;
  404. }
  405. }
  406. return false;
  407. }
  408. bool IsParallelCareNode(const CNodePtr &cnode) {
  409. MS_EXCEPTION_IF_NULL(cnode);
  410. ValueNodePtr prim_node = cnode->input(0)->cast<ValueNodePtr>();
  411. if (prim_node == nullptr) {
  412. return false;
  413. }
  414. PrimitivePtr prim = prim_node->value()->cast<PrimitivePtr>();
  415. if (prim == nullptr) {
  416. return false;
  417. }
  418. if (IsInBlackList(prim)) {
  419. MS_LOG(DEBUG) << "Parallel don't care node: " << prim->name();
  420. return false;
  421. }
  422. // get_next is not in the forward graph, we need mark the get_next as the forward node
  423. if (prim->name() == GET_NEXT) {
  424. return true;
  425. }
  426. if ((prim->name() == CAST) && !cnode->has_user_data<OperatorInfo>()) {
  427. return false;
  428. }
  429. return cnode->in_forward_flag();
  430. }
  431. void StepRedistribution(const CNodePtr &node, const OperatorInfoPtr &distribute_operator, const CNodePtr &insert_node,
  432. const TensorRedistribution &tensor_redistribution, const CNodePtr &pre_node) {
  433. MS_EXCEPTION_IF_NULL(node->func_graph());
  434. FuncGraphManagerPtr manager = node->func_graph()->manager();
  435. MS_EXCEPTION_IF_NULL(manager);
  436. AnfNodeIndexSet node_set = manager->node_users()[node];
  437. CNodePtr insert_node_new;
  438. if (AnfNodeIsPrimitive(node, MAKE_TUPLE) || AnfNodeIsPrimitive(node, MAKE_LIST)) {
  439. MS_LOG(INFO) << "No need to insert redistribution op betweend make_tuple node and the next node";
  440. return;
  441. }
  442. if (IsValueNode<Primitive>(node->input(0))) {
  443. auto current_value = node->input(0)->cast<ValueNodePtr>();
  444. MS_EXCEPTION_IF_NULL(current_value);
  445. PrimitivePtr current_prim = current_value->value()->cast<PrimitivePtr>();
  446. MS_EXCEPTION_IF_NULL(current_prim);
  447. insert_node_new = ((current_prim->name() == TUPLE_GETITEM) ? node : insert_node);
  448. } else {
  449. insert_node_new = insert_node;
  450. }
  451. MS_EXCEPTION_IF_NULL(insert_node_new);
  452. for (auto &node_pair : node_set) {
  453. CNodePtr use_cnode = node_pair.first->cast<CNodePtr>();
  454. MS_EXCEPTION_IF_NULL(use_cnode);
  455. if (!IsValueNode<Primitive>(use_cnode->input(0))) {
  456. StepRedistribution(use_cnode, distribute_operator, insert_node_new, tensor_redistribution, pre_node);
  457. } else {
  458. ValueNodePtr prim_anf_node = use_cnode->input(0)->cast<ValueNodePtr>();
  459. MS_EXCEPTION_IF_NULL(prim_anf_node);
  460. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  461. MS_EXCEPTION_IF_NULL(node_prim);
  462. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  463. continue;
  464. }
  465. if (IsParallelCareNode(use_cnode) && use_cnode->has_user_data<OperatorInfo>()) {
  466. Redistribution(node_pair, distribute_operator, insert_node_new, node_pair.second, tensor_redistribution,
  467. pre_node);
  468. } else {
  469. StepRedistribution(use_cnode, distribute_operator, insert_node_new, tensor_redistribution, pre_node);
  470. }
  471. }
  472. }
  473. }
  474. void SplitTensor(const AnfNodePtr &node, const CNodePtr &next_node, int64_t index) {
  475. MS_EXCEPTION_IF_NULL(node);
  476. MS_EXCEPTION_IF_NULL(next_node);
  477. OperatorInfoPtr op_info = next_node->user_data<OperatorInfo>();
  478. MS_EXCEPTION_IF_NULL(op_info);
  479. // If the shape of tensor is [] or [1], no need to split it.
  480. Shapes shapes = GetNodeShape(node);
  481. if (shapes.size() != 1) {
  482. MS_LOG(EXCEPTION) << "Split tensor for " << op_info->name()
  483. << ": GetNodeShape for tensor_node, output size is not 1";
  484. }
  485. Shape shape = shapes[0];
  486. std::string shape_str = ShapeToString(shape);
  487. if (shape.empty() || ((shape.size() == 1) && (shape[0] == 1))) {
  488. MS_LOG(INFO) << "Split tensor for " << op_info->name() << ": The shape is " << shape_str
  489. << ", no need to split it.";
  490. return;
  491. }
  492. MS_LOG(INFO) << "Split tensor for " << op_info->name() << ": The shape of tensor is " << shape_str;
  493. // extract tensor layout
  494. if (LongToSize(index - 1) >= op_info->inputs_tensor_info().size()) {
  495. MS_LOG(EXCEPTION) << "The index is out of range, index is " << index - 1 << ", vector size is "
  496. << op_info->inputs_tensor_info().size();
  497. }
  498. TensorInfo tensor_info = op_info->inputs_tensor_info()[LongToSize(index - 1)];
  499. TensorLayout tensor_layout = tensor_info.tensor_layout();
  500. // Use _GetTensorSlice operator to split the tensor
  501. FuncGraphPtr func_graph = next_node->func_graph(); // only cnode can get the graph
  502. MS_EXCEPTION_IF_NULL(func_graph);
  503. Operator op = CreateGetTensorSliceOp(tensor_layout);
  504. InsertGetTensorSliceOp(op, next_node, func_graph, index, SPLIT_TENSOR);
  505. if (!op_info->sub_ops().empty()) {
  506. auto sub_ops = op_info->sub_ops();
  507. for (size_t i = 0; i < sub_ops.size(); i++) {
  508. if (!sub_ops.at(i).empty()) {
  509. InsertGetTensorSliceOp(sub_ops.at(i).at(0), next_node, func_graph, index, SUB);
  510. }
  511. }
  512. }
  513. }
  514. void SplitTensorList(const AnfNodePtr &node, const CNodePtr &next_node, int index) {
  515. MS_EXCEPTION_IF_NULL(node);
  516. MS_EXCEPTION_IF_NULL(next_node);
  517. if (next_node->inputs().size() != 2 || index != 1) {
  518. MS_LOG(INFO) << next_node->fullname_with_scope() << " Inputs must have only one input, get "
  519. << next_node->inputs().size() - 1 << " index should be 1, get " << index;
  520. return;
  521. }
  522. OperatorInfoPtr op_info = next_node->user_data<OperatorInfo>();
  523. MS_EXCEPTION_IF_NULL(op_info);
  524. std::vector<ValuePtr> inputs_values;
  525. if (IsValueNode<ValueList>(node)) {
  526. inputs_values = node->cast<ValueNodePtr>()->value()->cast<ValueListPtr>()->value();
  527. } else {
  528. inputs_values = node->cast<ValueNodePtr>()->value()->cast<ValueTuplePtr>()->value();
  529. }
  530. if (inputs_values.size() != op_info->inputs_tensor_info().size()) {
  531. MS_LOG(EXCEPTION) << "The inputs size " << inputs_values.size() << ", is not equal to inputs shape size "
  532. << op_info->inputs_tensor_info().size();
  533. }
  534. std::vector<AnfNodePtr> make_tuple_inputs = {NewValueNode(prim::kPrimMakeTuple)};
  535. FuncGraphPtr func_graph = next_node->func_graph();
  536. MS_EXCEPTION_IF_NULL(func_graph);
  537. FuncGraphManagerPtr manager = func_graph->manager();
  538. MS_EXCEPTION_IF_NULL(manager);
  539. ScopePtr scope = next_node->scope();
  540. MS_EXCEPTION_IF_NULL(scope);
  541. for (size_t i = 0; i < inputs_values.size(); ++i) {
  542. auto value_ptr = inputs_values[i];
  543. auto tensor = value_ptr->cast<tensor::TensorPtr>();
  544. MS_EXCEPTION_IF_NULL(tensor);
  545. TensorInfo tensor_info = op_info->inputs_tensor_info()[i];
  546. TensorLayout tensor_layout = tensor_info.tensor_layout();
  547. auto value_node = NewValueNode(value_ptr)->cast<AnfNodePtr>();
  548. Operator op = CreateGetTensorSliceOp(tensor_layout);
  549. std::vector<AnfNodePtr> node_input = CreateInput(op, value_node, SPLIT_TENSOR);
  550. CNodePtr new_node = func_graph->NewCNode(node_input);
  551. new_node->set_in_forward_flag(true);
  552. auto new_node_value = node_input[0]->cast<ValueNodePtr>();
  553. MS_EXCEPTION_IF_NULL(new_node_value);
  554. PrimitivePtr new_node_prim = new_node_value->value()->cast<PrimitivePtr>();
  555. new_node_prim->set_instance_name(SPLIT_TENSOR);
  556. new_node_prim->set_attr("keep_value_node_input", MakeValue(true));
  557. new_node->set_scope(scope);
  558. node_input[0]->set_scope(scope);
  559. make_tuple_inputs.push_back(new_node);
  560. }
  561. CNodePtr make_tuple = func_graph->NewCNode(make_tuple_inputs);
  562. manager->Replace(node, make_tuple);
  563. }
  564. void StepSplitTensor(const AnfNodePtr &node, const FuncGraphManagerPtr &manager) {
  565. MS_EXCEPTION_IF_NULL(node);
  566. MS_EXCEPTION_IF_NULL(manager);
  567. AnfNodeIndexSet node_set = manager->node_users()[node];
  568. for (auto &node_pair : node_set) {
  569. CNodePtr use_cnode = node_pair.first->cast<CNodePtr>();
  570. if (use_cnode == nullptr || !IsValueNode<Primitive>(use_cnode->input(0))) {
  571. continue;
  572. }
  573. ValueNodePtr prim_anf_node = use_cnode->input(0)->cast<ValueNodePtr>();
  574. MS_EXCEPTION_IF_NULL(prim_anf_node);
  575. PrimitivePtr use_cnode_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  576. MS_EXCEPTION_IF_NULL(use_cnode_prim);
  577. if (use_cnode_prim->name() == DEPEND && node_pair.second != 1) {
  578. continue;
  579. }
  580. if (IsParallelCareNode(use_cnode)) {
  581. if (IsValueNode<ValueList>(node) || IsValueNode<ValueTuple>(node)) {
  582. SplitTensorList(node, use_cnode, node_pair.second);
  583. } else {
  584. SplitTensor(node, use_cnode, node_pair.second);
  585. }
  586. }
  587. }
  588. }
  589. std::vector<AnfNodePtr> ReplaceOpInput(const Operator &replace_op, const std::string &instance_name,
  590. const CNodePtr &node) {
  591. OperatorArgs arg_replace_op = replace_op.second;
  592. ValuePtr pyop_instance = CreatOpInstance(arg_replace_op.first, replace_op.first, instance_name);
  593. if (pyop_instance == nullptr) {
  594. MS_LOG(EXCEPTION) << "Failure: " << replace_op.first << " CreatOpInstance failed";
  595. }
  596. OperatorParams params = arg_replace_op.second;
  597. if (node->inputs().size() < 2) {
  598. // GetNext operator dose not has input
  599. if (node->inputs().size() == 1) {
  600. return {NewValueNode(pyop_instance)};
  601. }
  602. MS_LOG(EXCEPTION) << "Failure: " << node->ToString() << " size is smaller than 2";
  603. }
  604. std::vector<AnfNodePtr> replace_input = {NewValueNode(pyop_instance), node->input(1)};
  605. if (replace_op.first == EMBEDDING_LOOKUP) {
  606. replace_input = {NewValueNode(pyop_instance), node->input(1), node->input(2)};
  607. }
  608. if (!params.empty()) {
  609. Param param_first = *(params.begin());
  610. int64_t first_position = param_first.second;
  611. if (first_position == 1) {
  612. replace_input.pop_back();
  613. }
  614. for (auto &param : params) {
  615. AnfNodePtr val = NewValueNode(param.first.second);
  616. if (val == nullptr) {
  617. MS_LOG(EXCEPTION) << "Failure:val is nullptr";
  618. }
  619. int64_t position = param.second;
  620. (void)replace_input.insert(replace_input.begin() + position, val);
  621. }
  622. }
  623. return replace_input;
  624. }
  625. void ReplaceOneOp(const Operator &replace_op, const CNodePtr &node) {
  626. FuncGraphPtr func_graph = node->func_graph();
  627. MS_EXCEPTION_IF_NULL(func_graph);
  628. FuncGraphManagerPtr manager = func_graph->manager();
  629. if (manager == nullptr) {
  630. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  631. }
  632. std::string instance_name = CreateInstanceName(node, 0);
  633. std::vector<AnfNodePtr> replace_input;
  634. replace_input = ReplaceOpInput(replace_op, instance_name, node);
  635. CNodePtr replace_node = func_graph->NewCNode(replace_input);
  636. MS_EXCEPTION_IF_NULL(replace_node);
  637. ScopePtr scope = node->scope();
  638. MS_EXCEPTION_IF_NULL(scope);
  639. replace_node->set_scope(scope);
  640. replace_node->set_in_forward_flag(true);
  641. replace_input[0]->set_scope(scope);
  642. (void)manager->Replace(node, replace_node);
  643. }
  644. void StepReplaceOp(OperatorVector replace_op, const CNodePtr &node) {
  645. // step1:get graph manager distribute_operator
  646. OperatorInfoPtr distribute_operator = node->user_data<OperatorInfo>();
  647. if (distribute_operator == nullptr) {
  648. MS_LOG(EXCEPTION) << "Failure:AddNode error since distribute_operator is nullptr";
  649. }
  650. FuncGraphPtr func_graph = node->func_graph();
  651. MS_EXCEPTION_IF_NULL(func_graph);
  652. FuncGraphManagerPtr manager = func_graph->manager();
  653. if (manager == nullptr) {
  654. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  655. }
  656. // step2:traverse op_list and insert node
  657. std::reverse(replace_op.begin(), replace_op.end());
  658. auto replace_op_info = distribute_operator->replace_op_info();
  659. std::reverse(replace_op_info.begin(), replace_op_info.end());
  660. if (!replace_op_info.empty() && replace_op_info.size() != replace_op.size()) {
  661. MS_LOG(EXCEPTION) << "replace_op_info is not empty and size not equal to replace_op!";
  662. }
  663. bool replace_op_info_flag = !replace_op_info.empty();
  664. for (size_t index = 0; index < replace_op.size(); ++index) {
  665. std::string instance_name = CreateInstanceName(node, index);
  666. std::vector<AnfNodePtr> replace_input;
  667. if (index != replace_op.size() - 1) {
  668. replace_input = CreateInput(replace_op[index], node, instance_name);
  669. } else {
  670. replace_input = ReplaceOpInput(replace_op[index], instance_name, node);
  671. }
  672. CNodePtr replace_node = func_graph->NewCNode(replace_input);
  673. MS_EXCEPTION_IF_NULL(replace_node);
  674. ScopePtr scope = node->scope();
  675. MS_EXCEPTION_IF_NULL(scope);
  676. replace_node->set_scope(scope);
  677. PrimitivePtr prim = GetValueNode<PrimitivePtr>(replace_node->input(0));
  678. if (prim->name() == EMBEDDING_LOOKUP) {
  679. auto attrs = prim->attrs();
  680. attrs[TARGET] = MakeValue(CPU);
  681. (void)prim->SetAttrs(attrs);
  682. }
  683. if (index == replace_op.size() - 1) {
  684. replace_node->set_user_data<OperatorInfo>(node->user_data<OperatorInfo>());
  685. }
  686. replace_node->set_in_forward_flag(true);
  687. replace_input[0]->set_scope(scope);
  688. if (replace_op_info_flag && replace_op_info[index].first) {
  689. auto new_cnode = InsertMakeTuple(replace_node, replace_op_info[index].second, func_graph);
  690. (void)manager->Replace(node, new_cnode); // using Replace function to insert node
  691. } else {
  692. (void)manager->Replace(node, replace_node); // using Replace function to insert node
  693. }
  694. }
  695. MS_LOG(INFO) << "Insert ReplaceOp success for " << distribute_operator->name();
  696. }
  697. bool IsSomePrimitive(const CNodePtr &cnode, const std::string &name) {
  698. ValueNodePtr anf_node = cnode->input(0)->cast<ValueNodePtr>();
  699. MS_EXCEPTION_IF_NULL(anf_node);
  700. PrimitivePtr prim = anf_node->value()->cast<PrimitivePtr>();
  701. return (prim->name() == name);
  702. }
  703. void StepReplaceGraph(const ReplaceGraphPtr &replace_graph, const CNodePtr &node) {
  704. MS_EXCEPTION_IF_NULL(replace_graph);
  705. MS_EXCEPTION_IF_NULL(node);
  706. MS_EXCEPTION_IF_NULL(replace_graph->second);
  707. FuncGraphPtr func_graph = node->func_graph();
  708. MS_EXCEPTION_IF_NULL(func_graph);
  709. FuncGraphManagerPtr manager = func_graph->manager();
  710. if (manager == nullptr) {
  711. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  712. }
  713. // Sovle the input order
  714. // For example input_node:{segment_sum:1, segment_sum:2, gahter:2}
  715. // The Original code here will bind the all operations to the first inputs of theses operatos
  716. // However, the segment_sum operation needs two inputs, To sovle this
  717. // We maintain a dict to count the times of the same operations,
  718. // and bind the inputs according to the times of the op appears.
  719. static std::unordered_map<AnfNodePtr, int> input_map = {};
  720. static int appear_count = 0;
  721. for (auto &replace_input : replace_graph->first) {
  722. auto pre_node = node->input(LongToSize(replace_input.second));
  723. auto it = input_map.find(replace_input.first);
  724. if (it != input_map.end()) {
  725. appear_count = 1 + it->second;
  726. } else {
  727. appear_count = 1;
  728. }
  729. input_map[replace_input.first] = appear_count;
  730. manager->SetEdge(replace_input.first, appear_count, pre_node);
  731. }
  732. // "(void)manager->Replace(replace_graph->first, pre_node);" can not be called
  733. auto replace_output = replace_graph->second;
  734. MS_EXCEPTION_IF_NULL(replace_output);
  735. (void)manager->Replace(node, replace_output);
  736. }
  737. int64_t GetTupleGetItemIndex(const CNodePtr &cnode) {
  738. MS_EXCEPTION_IF_NULL(cnode);
  739. if (cnode->inputs().size() != 3) {
  740. MS_LOG(EXCEPTION) << cnode->ToString() << " size( " << cnode->inputs().size() << " ) is not 3";
  741. }
  742. if (!cnode->input(2)->isa<ValueNode>()) {
  743. MS_LOG(EXCEPTION) << "The index of tuple getitem is not a value node";
  744. }
  745. ValuePtr tuple_index_value = GetValueNode(cnode->input(2));
  746. MS_EXCEPTION_IF_NULL(tuple_index_value);
  747. if (!tuple_index_value->isa<Int64Imm>()) {
  748. MS_LOG(EXCEPTION) << "The index of tuple getitem is not int32";
  749. }
  750. return tuple_index_value->cast<Int64ImmPtr>()->value();
  751. }
  752. void InsertVirtualDivOp(const VirtualDivOp &virtual_div_op, const CNodePtr &node) {
  753. MS_EXCEPTION_IF_NULL(node);
  754. size_t node_size = node->inputs().size();
  755. FuncGraphPtr func_graph = node->func_graph();
  756. MS_EXCEPTION_IF_NULL(func_graph);
  757. FuncGraphManagerPtr manager = func_graph->manager();
  758. MS_EXCEPTION_IF_NULL(manager);
  759. for (size_t index = 1; index < node_size; ++index) {
  760. AnfNodePtr input = node->input(index);
  761. MS_EXCEPTION_IF_NULL(input);
  762. if (!input->isa<CNode>() && !input->isa<Parameter>()) { // if it is not a tensor, continue
  763. MS_LOG(INFO) << "insert div op: the index " << index << " is not tensor, skip";
  764. continue;
  765. }
  766. for (size_t pos = 0; pos < virtual_div_op.size(); ++pos) {
  767. std::string instance_name = CreateInstanceName(node, pos);
  768. InsertNode(virtual_div_op[pos], node, index, node->input(index), func_graph, instance_name);
  769. }
  770. MS_LOG(INFO) << "insert div op for input index " << index << " of node";
  771. }
  772. }
  773. // Only used for InsertMirrorOps
  774. std::pair<AnfNodePtr, bool> FindParameter(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  775. if (!node->isa<Parameter>() && !node->isa<CNode>() && !node->isa<ValueNode>()) {
  776. return std::make_pair(nullptr, false);
  777. } else if (node->isa<Parameter>()) {
  778. auto param_ptr = node->user_data<parallel::TensorLayout>();
  779. if (param_ptr != nullptr && !param_ptr->opt_shard_group().empty()) {
  780. return std::make_pair(nullptr, false);
  781. } else {
  782. return std::make_pair(node, false);
  783. }
  784. } else if (node->isa<ValueNode>()) {
  785. if (IsValueNode<RefKey>(node)) {
  786. std::vector<AnfNodePtr> param_v = FindParameterByRefKeyNode(node, func_graph);
  787. if (param_v.size() != 1) {
  788. MS_LOG(EXCEPTION) << "FindParameterByRefKeyNode failed, return vector size must be 1, real is "
  789. << param_v.size();
  790. }
  791. auto param_ptr = param_v[0]->user_data<parallel::TensorLayout>();
  792. if (param_ptr != nullptr && !param_ptr->opt_shard_group().empty()) {
  793. return std::make_pair(nullptr, true);
  794. } else {
  795. return std::make_pair(node, true);
  796. }
  797. }
  798. return std::make_pair(nullptr, false);
  799. } else {
  800. CNodePtr cnode = node->cast<CNodePtr>();
  801. MS_EXCEPTION_IF_NULL(cnode);
  802. if (!IsValueNode<Primitive>(cnode->input(0))) {
  803. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  804. if (!FindParameter(cnode->input(index), func_graph).first) {
  805. continue;
  806. }
  807. return FindParameter(cnode->input(index), func_graph);
  808. }
  809. } else {
  810. if (IsParallelCareNode(cnode)) {
  811. return std::make_pair(nullptr, false);
  812. } else {
  813. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  814. MS_EXCEPTION_IF_NULL(prim_anf_node);
  815. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  816. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  817. MS_EXCEPTION_IF_NULL(prim);
  818. if (prim->name() == DEPEND && index != 1) {
  819. continue;
  820. }
  821. if (!FindParameter(cnode->input(index), func_graph).first) {
  822. continue;
  823. }
  824. return FindParameter(cnode->input(index), func_graph);
  825. }
  826. }
  827. }
  828. }
  829. return std::make_pair(nullptr, false);
  830. }
  831. std::pair<bool, CNodePtr> FindCNode(const AnfNodePtr &anode, const std::string &name, const FuncGraphPtr &func_graph) {
  832. MS_EXCEPTION_IF_NULL(anode);
  833. MS_EXCEPTION_IF_NULL(anode->func_graph());
  834. FuncGraphManagerPtr manager = anode->func_graph()->manager();
  835. MS_EXCEPTION_IF_NULL(manager);
  836. AnfNodeIndexSet node_set = manager->node_users()[anode];
  837. bool result = false;
  838. CNodePtr cnode_return = nullptr;
  839. for (auto &node_pair : node_set) {
  840. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  841. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  842. continue;
  843. }
  844. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  845. MS_EXCEPTION_IF_NULL(prim_anf_node);
  846. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  847. MS_EXCEPTION_IF_NULL(node_prim);
  848. if (node_prim->name() == name && node_pair.second == 1) {
  849. if (use_apply->func_graph() == func_graph) {
  850. result = true;
  851. cnode_return = use_apply;
  852. MS_LOG(INFO) << "Find Primitive " << name << " in the same func_graph";
  853. continue;
  854. }
  855. MS_LOG(INFO) << "Find Primitive " << name << " in different func_graph";
  856. }
  857. }
  858. return std::make_pair(result, cnode_return);
  859. }
  860. bool IsCastBeforMirror(const CNodePtr &node, size_t index) {
  861. // only if gradient_fp32_sync is true, pre node is cast and type is not float32 return true
  862. if (!ParallelContext::GetInstance()->gradient_fp32_sync()) {
  863. return false;
  864. }
  865. auto pre_node = node->input(index);
  866. MS_EXCEPTION_IF_NULL(pre_node);
  867. auto cnode = pre_node->cast<CNodePtr>();
  868. if (cnode == nullptr || !IsValueNode<Primitive>(cnode->input(0))) {
  869. return false;
  870. }
  871. auto pre_value_node = cnode->input(0)->cast<ValueNodePtr>();
  872. MS_EXCEPTION_IF_NULL(pre_value_node);
  873. auto pre_prim = pre_value_node->value()->cast<PrimitivePtr>();
  874. MS_EXCEPTION_IF_NULL(pre_prim);
  875. if (pre_prim->name() != CAST) {
  876. return false;
  877. }
  878. auto node_type = pre_node->Type();
  879. MS_EXCEPTION_IF_NULL(node_type);
  880. if (!node_type->isa<mindspore::TensorType>()) {
  881. MS_LOG(EXCEPTION) << "Unknown type.";
  882. }
  883. auto input_element_type = node_type->cast<mindspore::TensorTypePtr>()->element();
  884. MS_EXCEPTION_IF_NULL(input_element_type);
  885. auto type_id = input_element_type->type_id();
  886. return (type_id != kNumberTypeFloat32);
  887. }
  888. void InsertMirrorOps(const MirrorOps &mirror_ops, const CNodePtr &node) {
  889. MS_EXCEPTION_IF_NULL(node);
  890. size_t node_size = node->inputs().size();
  891. FuncGraphPtr func_graph = node->func_graph();
  892. MS_EXCEPTION_IF_NULL(func_graph);
  893. FuncGraphManagerPtr manager = func_graph->manager();
  894. MS_EXCEPTION_IF_NULL(manager);
  895. if ((node->inputs().size() == 2) && (IsValueNode<ValueSequeue>(node->input(1)))) {
  896. MS_LOG(INFO) << "Input is ValueList, skip it.";
  897. return;
  898. }
  899. if ((node->inputs().size() == 2) &&
  900. (AnfNodeIsPrimitive(node->input(1), MAKE_TUPLE) || AnfNodeIsPrimitive(node->input(1), MAKE_LIST))) {
  901. MS_LOG(INFO) << "The mirror for " << GetPrimName(node) << " has handle by make_tuple node";
  902. return;
  903. }
  904. if (mirror_ops.size() != node_size - 1) {
  905. MS_LOG(EXCEPTION) << "Mirrorops's size is wrong! mirror_ops size is " << mirror_ops.size() << ", node_size is "
  906. << node_size - 1;
  907. }
  908. for (size_t index = 1; index < node_size; ++index) {
  909. OperatorVector backward_op = mirror_ops[index - 1];
  910. if (backward_op.empty()) {
  911. continue;
  912. }
  913. std::pair<AnfNodePtr, bool> param_node_pair = FindParameter(node->input(index), func_graph);
  914. if (!param_node_pair.first) {
  915. continue;
  916. }
  917. // not a RefKey
  918. if (!param_node_pair.second) {
  919. auto next_cnode = FindCNode(param_node_pair.first, MIRROR_OPERATOR, func_graph);
  920. // if there is already a MirrorOp in the same graph, use MirrorOp CNode as a input instead
  921. if (next_cnode.first) {
  922. MS_EXCEPTION_IF_NULL(next_cnode.second);
  923. // param->cast->op, insert mirror before cast
  924. if (node->input(index)->isa<CNode>()) {
  925. auto pre_cnode = node->input(index)->cast<CNodePtr>();
  926. auto pre_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  927. if (pre_prim->name() == CAST) {
  928. manager->SetEdge(pre_cnode, 1, next_cnode.second);
  929. continue;
  930. }
  931. }
  932. manager->SetEdge(node, SizeToLong(index), next_cnode.second);
  933. continue;
  934. }
  935. }
  936. // if the parameter found is a RefKey, or no MirrorOp is found in the same graph, insert a new MirrorOp
  937. // only one MirrorOp in backward_op
  938. if (backward_op.size() != 1) {
  939. MS_LOG(EXCEPTION) << "backward_op size must be 1, real is " << backward_op.size();
  940. }
  941. std::string instance_name = MIRROR_OP;
  942. if (IsCastBeforMirror(node, index)) {
  943. for (auto &op : backward_op) {
  944. // insert new node before the node
  945. CNodePtr cnode = node->input(index)->cast<CNodePtr>();
  946. MS_EXCEPTION_IF_NULL(cnode);
  947. AnfNodePtr pre_node = cnode->input(1);
  948. InsertNode(op, cnode, size_t(1), pre_node, func_graph, instance_name);
  949. }
  950. } else {
  951. for (auto &op : backward_op) {
  952. AnfNodePtr pre_node = node->input(index);
  953. InsertNode(op, node, index, pre_node, func_graph, instance_name);
  954. }
  955. }
  956. }
  957. }
  958. void BackwardCommunication(const OperatorInfoPtr &distribute_operator, const CNodePtr &node,
  959. const std::vector<std::pair<CNodePtr, LossNodeInfo>> &sens_loss_pairs) {
  960. MS_EXCEPTION_IF_NULL(distribute_operator);
  961. MS_EXCEPTION_IF_NULL(node);
  962. bool is_loss_cnode =
  963. std::any_of(sens_loss_pairs.begin(), sens_loss_pairs.end(),
  964. [node](const std::pair<CNodePtr, LossNodeInfo> &element) { return element.second.loss_node == node; });
  965. MirrorOps mirror_ops = distribute_operator->mirror_ops();
  966. VirtualDivOp virtual_div_op = distribute_operator->virtual_div_op();
  967. // insert mirror op
  968. if (!mirror_ops.empty()) {
  969. MS_LOG(INFO) << "insert mirror op for " << distribute_operator->name();
  970. InsertMirrorOps(mirror_ops, node);
  971. }
  972. // insert virtual div op
  973. if (!virtual_div_op.empty() && is_loss_cnode) {
  974. MS_LOG(INFO) << "insert virtual div op for " << distribute_operator->name();
  975. InsertVirtualDivOp(virtual_div_op, node);
  976. }
  977. }
  978. std::string GetDisOpName(const std::string &prim_name) {
  979. std::string op_name = prim_name;
  980. if (!prim_name.empty() && (prim_name[0] == '_')) {
  981. op_name = prim_name.substr(1);
  982. }
  983. return op_name + "Info";
  984. }
  985. OperatorInfoPtr OperatorInstanceByName(const std::string &name, const PrimitiveAttrs &attrs,
  986. const std::vector<Shapes> &shape_list) {
  987. if (shape_list.size() != 2) {
  988. MS_LOG(ERROR) << "The size of shape list is not 2";
  989. return nullptr;
  990. }
  991. if (name.length() == 0) {
  992. MS_LOG(EXCEPTION) << "Length of name is zero!";
  993. }
  994. std::string distribute_opname = GetDisOpName(name);
  995. if (name == GATHERV2) {
  996. distribute_opname = name + "PInfo";
  997. auto data_parallel_iter = attrs.find(DATA_PARALLEL);
  998. if (data_parallel_iter != attrs.end()) {
  999. MS_EXCEPTION_IF_NULL(data_parallel_iter->second);
  1000. if (!data_parallel_iter->second->isa<BoolImm>()) {
  1001. MS_LOG(EXCEPTION) << ": data_parallel flag's type is not a bool.";
  1002. }
  1003. bool data_parallel = data_parallel_iter->second->cast<BoolImmPtr>()->value();
  1004. if (data_parallel) {
  1005. distribute_opname = name + "Info";
  1006. }
  1007. }
  1008. }
  1009. OperatorInfoPtr operator_ =
  1010. (OperatorInfoPtr)DynCreator::Instance().Creat(distribute_opname, shape_list[0], shape_list[1], attrs, TOTAL_OPS);
  1011. if (operator_ == nullptr) {
  1012. MS_LOG(INFO) << "Creat " << name << " failed";
  1013. return nullptr;
  1014. }
  1015. std::string origin_name = operator_->name();
  1016. operator_->set_name(origin_name + std::to_string(TOTAL_OPS));
  1017. MS_LOG(INFO) << "Successfully created operator " << origin_name;
  1018. ++TOTAL_OPS;
  1019. return operator_;
  1020. }
  1021. OperatorInfoPtr OperatorInstance(const PrimitivePtr &prim, const PrimitiveAttrs &attrs,
  1022. const std::vector<Shapes> &shape_list) {
  1023. MS_EXCEPTION_IF_NULL(prim);
  1024. OperatorInfoPtr operator_ = OperatorInstanceByName(prim->name(), attrs, shape_list);
  1025. if (operator_ == nullptr) {
  1026. if (IsInBatchParallelBlackList(prim)) {
  1027. MS_LOG(EXCEPTION) << "Operator " << prim->name() << " is not supported yet in auto parallel mode.";
  1028. }
  1029. MS_LOG(INFO) << "Creat " << prim->name() << " failed, use batch parallel";
  1030. operator_ = OperatorInstanceByName(BATCH_PARALLEL, attrs, shape_list);
  1031. MS_EXCEPTION_IF_NULL(operator_);
  1032. }
  1033. return operator_;
  1034. }
  1035. OperatorInfoPtr NewOperatorInstance(const PrimitivePtr &prim, const PrimitiveAttrs &attrs,
  1036. std::vector<Shapes> shape_list) {
  1037. OperatorInfoPtr operator_ = OperatorInstance(prim, attrs, shape_list);
  1038. for (size_t i = 0; i < shape_list[0].size(); ++i) {
  1039. MS_LOG(INFO) << "No: " << i << " input's shape: " << ShapeToString(shape_list[0][i]);
  1040. }
  1041. return operator_;
  1042. }
  1043. StrategyPtr ExtractStrategy(std::unordered_map<std::string, ValuePtr> attrs) {
  1044. ValueTuplePtr var = attrs[STRATEGY]->cast<ValueTuplePtr>();
  1045. StrategyPtr strategyPtr;
  1046. int64_t stage_id = g_device_manager->stage_id();
  1047. MS_LOG(INFO) << "Extract information: strategy " << attrs[STRATEGY]->ToString();
  1048. if (var == nullptr) {
  1049. MS_LOG(EXCEPTION) << "Strategy value is nullptr";
  1050. }
  1051. if (var->size() > 0) {
  1052. std::vector<ValuePtr> elements = var->value();
  1053. Strategys strategy;
  1054. for (uint64_t index = 0; index < elements.size(); ++index) {
  1055. Dimensions dim;
  1056. if (elements[index]->isa<ValueSequeue>()) {
  1057. ValueTuplePtr value_tuple = elements[index]->cast<ValueTuplePtr>();
  1058. std::vector<ValuePtr> value_vector = value_tuple->value();
  1059. (void)std::transform(value_vector.begin(), value_vector.end(), std::back_inserter(dim),
  1060. [](const ValuePtr &value) { return static_cast<int64_t>(GetValue<int64_t>(value)); });
  1061. strategy.push_back(dim);
  1062. } else {
  1063. MS_LOG(EXCEPTION) << "Failure: Strategy's format is wrong! Need ValueSequence";
  1064. }
  1065. }
  1066. if (strategy.empty()) {
  1067. MS_LOG(EXCEPTION) << "ExtractStrategy: failed to extract strategy";
  1068. }
  1069. strategyPtr = NewStrategy(stage_id, strategy);
  1070. }
  1071. return strategyPtr;
  1072. }
  1073. Shapes GetValueListShape(const AnfNodePtr &node) {
  1074. Shapes shapes;
  1075. std::vector<ValuePtr> inputs_seq;
  1076. if (IsValueNode<ValueList>(node)) {
  1077. inputs_seq = node->cast<ValueNodePtr>()->value()->cast<ValueListPtr>()->value();
  1078. } else if (IsValueNode<ValueTuple>(node)) {
  1079. inputs_seq = node->cast<ValueNodePtr>()->value()->cast<ValueTuplePtr>()->value();
  1080. } else {
  1081. MS_LOG(EXCEPTION) << "node is eigther ValueList or ValueTuple";
  1082. }
  1083. for (auto &ele : inputs_seq) {
  1084. auto tensor = ele->cast<tensor::TensorPtr>();
  1085. MS_EXCEPTION_IF_NULL(tensor);
  1086. auto one_shape = tensor->shape();
  1087. shapes.push_back(one_shape);
  1088. }
  1089. return shapes;
  1090. }
  1091. Shapes GetNodeShape(const AnfNodePtr &node) {
  1092. MS_EXCEPTION_IF_NULL(node);
  1093. Shapes shapes;
  1094. if (IsValueNode<ValueList>(node) || IsValueNode<ValueTuple>(node)) {
  1095. return GetValueListShape(node);
  1096. }
  1097. BaseShapePtr base_shape_ptr = node->Shape();
  1098. if (node->isa<CNode>()) {
  1099. auto cnode = node->cast<CNodePtr>();
  1100. if (IsValueNode<Primitive>(cnode->input(0))) {
  1101. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1102. MS_EXCEPTION_IF_NULL(prim);
  1103. if (prim->name() == MAKEREF) {
  1104. AnfNodePtr ref_node = cnode->input(1);
  1105. auto func_graph = cnode->func_graph();
  1106. MS_EXCEPTION_IF_NULL(ref_node);
  1107. MS_EXCEPTION_IF_NULL(func_graph);
  1108. return GetRefKeyNodeShape(ref_node, func_graph);
  1109. }
  1110. }
  1111. if (cnode->input(0)->isa<CNode>()) {
  1112. if (cnode->inputs().size() < 2) {
  1113. MS_LOG(EXCEPTION) << "GetNodeShape: " << node->ToString() << " size is samller than 2";
  1114. }
  1115. base_shape_ptr = cnode->input(1)->Shape();
  1116. }
  1117. }
  1118. if (base_shape_ptr == nullptr) {
  1119. MS_LOG(EXCEPTION) << "GetNodeShape: " << node->ToString() << " shape_ptr is nullptr, full name is "
  1120. << node->fullname_with_scope();
  1121. }
  1122. auto tuple_shape_ptr = dyn_cast<abstract::SequeueShape>(base_shape_ptr);
  1123. if (tuple_shape_ptr != nullptr) {
  1124. auto tuple_shape = tuple_shape_ptr->shape();
  1125. for (auto &shape : tuple_shape) {
  1126. auto each_shape = dyn_cast<abstract::Shape>(shape);
  1127. MS_EXCEPTION_IF_NULL(each_shape);
  1128. shapes.push_back(each_shape->shape());
  1129. }
  1130. } else {
  1131. auto shape_ptr = dyn_cast<abstract::Shape>(base_shape_ptr);
  1132. MS_EXCEPTION_IF_NULL(shape_ptr);
  1133. shapes.push_back(shape_ptr->shape());
  1134. }
  1135. return shapes;
  1136. }
  1137. std::vector<AnfNodePtr> FindParameterByRefKeyNode(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  1138. MS_EXCEPTION_IF_NULL(node);
  1139. MS_EXCEPTION_IF_NULL(func_graph);
  1140. std::vector<AnfNodePtr> parameters;
  1141. if (!IsValueNode<RefKey>(node)) {
  1142. MS_LOG(ERROR) << "The node is not a ref key";
  1143. return parameters;
  1144. }
  1145. auto ref_key = GetValueNode<RefKeyPtr>(node);
  1146. MS_EXCEPTION_IF_NULL(ref_key);
  1147. auto name = ref_key->tag();
  1148. auto manager = func_graph->manager();
  1149. MS_EXCEPTION_IF_NULL(manager);
  1150. auto roots = manager->roots();
  1151. if (roots.size() != 1) {
  1152. MS_LOG(ERROR) << "The size of roots ( " << roots.size() << " ) is not 1";
  1153. return parameters;
  1154. }
  1155. FuncGraphPtr root_g = roots.back();
  1156. MS_EXCEPTION_IF_NULL(root_g);
  1157. for (auto &param_node : root_g->parameters()) {
  1158. auto param = param_node->cast<ParameterPtr>();
  1159. if (param && (name == param->name())) {
  1160. parameters.push_back(param_node);
  1161. MS_LOG(INFO) << "The name of ref key is: " << name;
  1162. return parameters;
  1163. }
  1164. }
  1165. MS_LOG(ERROR) << "The name of ref key is: " << name << ", but have not found the parameter";
  1166. return parameters;
  1167. }
  1168. Shapes GetRefKeyNodeShape(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  1169. MS_EXCEPTION_IF_NULL(node);
  1170. MS_EXCEPTION_IF_NULL(func_graph);
  1171. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(node, func_graph);
  1172. if (parameters.size() != 1) {
  1173. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  1174. }
  1175. Shapes input_shapes;
  1176. input_shapes = GetNodeShape(parameters[0]);
  1177. if (input_shapes.size() != 1) {
  1178. MS_LOG(EXCEPTION) << "Get input shape failed";
  1179. }
  1180. MS_LOG(INFO) << "The parameter shape is " << ShapeToString(input_shapes[0]);
  1181. return input_shapes;
  1182. }
  1183. std::vector<Shapes> ExtractShape(const CNodePtr &node) {
  1184. MS_EXCEPTION_IF_NULL(node);
  1185. Shapes shape_inputs, shape_outputs;
  1186. std::vector<Shapes> shape_all;
  1187. std::vector<AnfNodePtr> all_inputs = node->inputs();
  1188. std::vector<AnfNodePtr> node_inputs{all_inputs.begin() + 1, all_inputs.end()};
  1189. size_t inputs_size = all_inputs.size();
  1190. for (size_t i = 1; i < inputs_size; ++i) {
  1191. Shapes input_shapes;
  1192. AnfNodePtr input = all_inputs[i];
  1193. if (IsValueNode<RefKey>(input)) {
  1194. auto func_graph = node->func_graph();
  1195. MS_EXCEPTION_IF_NULL(func_graph);
  1196. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(input, func_graph);
  1197. if (parameters.size() != 1) {
  1198. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  1199. }
  1200. std::pair<AnfNodePtr, int64_t> node_pair = std::make_pair(node, SizeToLong(i));
  1201. g_RefMap[parameters[0]] = node_pair;
  1202. input_shapes = GetRefKeyNodeShape(input, func_graph);
  1203. } else if (IsValueNode<Tensor>(input) || input->isa<CNode>() || input->isa<Parameter>() ||
  1204. ((IsValueNode<ValueList>(input) || IsValueNode<ValueTuple>(input)) && (inputs_size == 2))) {
  1205. input_shapes = GetNodeShape(input);
  1206. } else {
  1207. continue;
  1208. }
  1209. if (input_shapes.size() != 1) {
  1210. if (inputs_size == 2) { // like concat
  1211. shape_inputs = input_shapes;
  1212. break;
  1213. } else {
  1214. MS_LOG(EXCEPTION) << "ExtractShape: Get input shape failed";
  1215. }
  1216. }
  1217. shape_inputs.push_back(input_shapes[0]);
  1218. }
  1219. shape_all.push_back(shape_inputs);
  1220. // extract out shape
  1221. shape_outputs = GetNodeShape(node);
  1222. shape_all.push_back(shape_outputs);
  1223. return shape_all;
  1224. }
  1225. std::pair<AnfNodePtr, int64_t> FindParallelCareNode(const AnfNodePtr &node, int32_t recursion_num) {
  1226. if (recursion_num >= RECURSION_LIMIT) {
  1227. return std::make_pair(nullptr, 0);
  1228. }
  1229. MS_EXCEPTION_IF_NULL(node);
  1230. FuncGraphPtr func_graph = node->func_graph();
  1231. MS_EXCEPTION_IF_NULL(func_graph);
  1232. FuncGraphManagerPtr manager = func_graph->manager();
  1233. MS_EXCEPTION_IF_NULL(manager);
  1234. AnfNodeIndexSet node_set = manager->node_users()[node];
  1235. for (auto &node_pair : node_set) {
  1236. CNodePtr cnode = node_pair.first->cast<CNodePtr>();
  1237. MS_EXCEPTION_IF_NULL(cnode);
  1238. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1239. continue;
  1240. }
  1241. ValueNodePtr prim_node_anf = cnode->input(0)->cast<ValueNodePtr>();
  1242. MS_EXCEPTION_IF_NULL(prim_node_anf);
  1243. PrimitivePtr node_prim = prim_node_anf->value()->cast<PrimitivePtr>();
  1244. MS_EXCEPTION_IF_NULL(node_prim);
  1245. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  1246. continue;
  1247. }
  1248. if (IsParallelCareNode(cnode) && cnode->has_user_data<OperatorInfo>()) {
  1249. return node_pair;
  1250. } else {
  1251. auto tmp_pair = FindParallelCareNode(node_pair.first, recursion_num + 1);
  1252. if (tmp_pair.first != nullptr) {
  1253. return tmp_pair;
  1254. }
  1255. }
  1256. }
  1257. return std::make_pair(nullptr, 0);
  1258. }
  1259. std::pair<AnfNodePtr, int64_t> FindSubGraph(const FuncGraphPtr &graph, const AnfNodePtr &parameter) {
  1260. MS_EXCEPTION_IF_NULL(graph);
  1261. MS_EXCEPTION_IF_NULL(parameter);
  1262. FuncGraphManagerPtr manager = graph->manager();
  1263. MS_EXCEPTION_IF_NULL(manager);
  1264. std::pair<AnfNodePtr, int64_t> prim_anf_node_pair = FindParallelCareNode(parameter, 0);
  1265. if (prim_anf_node_pair.first != nullptr) {
  1266. return prim_anf_node_pair;
  1267. } else {
  1268. AnfNodeIndexSet param_sub_set = manager->node_users()[parameter];
  1269. for (auto &param_pair : param_sub_set) {
  1270. CNodePtr param_cnode = param_pair.first->cast<CNodePtr>();
  1271. AnfNodePtr graph_value_node;
  1272. if (param_cnode->input(0)->isa<CNode>()) {
  1273. graph_value_node = param_cnode->input(0)->cast<CNodePtr>()->input(1);
  1274. } else {
  1275. graph_value_node = param_cnode->input(0);
  1276. }
  1277. if (!IsValueNode<FuncGraph>(graph_value_node)) {
  1278. continue;
  1279. }
  1280. FuncGraphPtr graph_sub = GetValueNode<FuncGraphPtr>(graph_value_node);
  1281. auto parameters = graph_sub->parameters();
  1282. if (LongToSize(param_pair.second - 1) >= parameters.size()) {
  1283. MS_LOG(EXCEPTION) << "The index is out of range, index is " << param_pair.second - 1 << ", vector size is "
  1284. << parameters.size();
  1285. }
  1286. std::pair<AnfNodePtr, int64_t> res = FindSubGraph(graph_sub, parameters[LongToSize(param_pair.second - 1)]);
  1287. if (res.first != nullptr) {
  1288. return res;
  1289. }
  1290. }
  1291. }
  1292. return std::make_pair(nullptr, 0);
  1293. }
  1294. void InsertAllGatherOp(const std::string &group, const std::pair<AnfNodePtr, int> &res, const AnfNodePtr &parameter) {
  1295. Operator op = CreateAllGatherOp(group);
  1296. MS_EXCEPTION_IF_NULL(res.first);
  1297. MS_EXCEPTION_IF_NULL(parameter);
  1298. auto cnode = res.first->cast<CNodePtr>();
  1299. auto graph = cnode->func_graph();
  1300. MS_EXCEPTION_IF_NULL(graph);
  1301. auto cnode_prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1302. MS_EXCEPTION_IF_NULL(cnode_prim);
  1303. CNodePtr allgather;
  1304. if (cnode_prim->name() == CAST) {
  1305. allgather = ReplaceNode(op, cnode, graph, PARALLEL_OPTIMIZER_ALLGATHER);
  1306. } else {
  1307. InsertNode(op, cnode, res.second, parameter, graph, PARALLEL_OPTIMIZER_ALLGATHER);
  1308. allgather = cnode->input(res.second)->cast<CNodePtr>();
  1309. }
  1310. // add fusion flag
  1311. MS_EXCEPTION_IF_NULL(allgather);
  1312. auto prim = GetValueNode<PrimitivePtr>(allgather->input(0));
  1313. auto attrs = prim->attrs();
  1314. // enable fusion flag later when it's supported in backend
  1315. attrs["fusion"] = MakeValue<int64_t>(0);
  1316. prim->SetAttrs(attrs);
  1317. }
  1318. static void ApplyParallelOptOnParam(const FuncGraphPtr &root, const AnfNodePtr &parameter,
  1319. const std::string &opt_shard_group) {
  1320. if (opt_shard_group.empty()) {
  1321. return;
  1322. }
  1323. FuncGraphManagerPtr manager = root->manager();
  1324. MS_EXCEPTION_IF_NULL(manager);
  1325. auto param_sub_set = manager->node_users()[parameter];
  1326. for (auto &param_pair : param_sub_set) {
  1327. auto cnode = param_pair.first->cast<CNodePtr>();
  1328. MS_EXCEPTION_IF_NULL(cnode);
  1329. if (cnode->in_forward_flag()) {
  1330. OperatorInfoPtr distribute_operator = cnode->user_data<OperatorInfo>();
  1331. if (distribute_operator == nullptr) {
  1332. MS_LOG(WARNING) << "Parallel optimizer: " << cnode->ToString() << " 's OperatorInfoPtr is nullptr";
  1333. } else if (IntToSize(param_pair.second - 1) >= distribute_operator->inputs_tensor_info().size()) {
  1334. MS_LOG(EXCEPTION) << "The index is out of range, index is " << param_pair.second - 1 << ", vector size is "
  1335. << distribute_operator->inputs_tensor_info().size();
  1336. }
  1337. // insert allgather operator between shard parameter and cnode
  1338. InsertAllGatherOp(opt_shard_group, param_pair, parameter);
  1339. MS_LOG(INFO) << "Parallel optimizer is applied between " << parameter->ToString() << " and " << cnode->ToString();
  1340. }
  1341. }
  1342. }
  1343. // When this function returns non-empty string, that means parallel optimizer is applied on this parameter.
  1344. std::string SetParallelShape(const AnfNodePtr &parameter, const std::pair<AnfNodePtr, int64_t> &res) {
  1345. MS_EXCEPTION_IF_NULL(parameter);
  1346. AbstractBasePtr abstract = parameter->abstract();
  1347. MS_EXCEPTION_IF_NULL(abstract);
  1348. MS_LOG(DEBUG) << "SetParallelShape " << parameter->ToString() << " shape " << parameter->Shape()->ToString();
  1349. CNodePtr cnode = res.first->cast<CNodePtr>();
  1350. MS_EXCEPTION_IF_NULL(cnode);
  1351. OperatorInfoPtr distribute_operator = cnode->user_data<OperatorInfo>();
  1352. if (distribute_operator == nullptr) {
  1353. MS_LOG(EXCEPTION) << "Failure:node " << cnode->ToString() << " 's OperatorInfoPtr is nullptr";
  1354. }
  1355. if (LongToSize(res.second - 1) >= distribute_operator->inputs_tensor_info().size()) {
  1356. MS_LOG(EXCEPTION) << "The index is out of range, index is " << res.second - 1 << ", vector size is "
  1357. << distribute_operator->inputs_tensor_info().size();
  1358. }
  1359. TensorInfo tensorinfo_in = distribute_operator->inputs_tensor_info()[LongToSize(res.second - 1)];
  1360. TensorLayout tensor_layout = tensorinfo_in.tensor_layout();
  1361. Shape slice_shape = tensor_layout.slice_shape().array();
  1362. std::string opt_shard_group;
  1363. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  1364. bool enable_parallel_optimizer = ParallelContext::GetInstance()->enable_parallel_optimizer();
  1365. if (enable_parallel_optimizer) {
  1366. if (!ParameterRequireGrad(parameter)) {
  1367. // only trainable parameters need parallel optimizer
  1368. MS_LOG(INFO) << "Parallel optimizer: " << parameter->ToString() << " is not trainable parameter.";
  1369. } else if (tensor_layout.GenerateOptShardSliceShape() == Status::SUCCESS) {
  1370. // get a totally shard tensor slice shape if the weight is repeated on devices
  1371. // and the shape of the first dimension could be divided
  1372. // apply parallel optimizer on parameters
  1373. // create communication group for allgather operator
  1374. slice_shape = tensor_layout.opt_shard_slice_shape();
  1375. std::vector<Group> dev_group;
  1376. if (distribute_operator->CreateGroupByTensorMap(tensor_layout.origin_tensor_map().array(), &dev_group) ==
  1377. Status::SUCCESS &&
  1378. !dev_group.empty()) {
  1379. opt_shard_group = dev_group[0].name();
  1380. // set communication group in tensor layout for checkpoint saving
  1381. tensor_layout.set_opt_shard_group(opt_shard_group);
  1382. MS_LOG(INFO) << "Parallel optimizer: create group " << opt_shard_group << " for " << parameter->ToString()
  1383. << " success.";
  1384. } else {
  1385. MS_LOG(WARNING) << "Parallel optimizer: create group for " << parameter->ToString() << " failed.";
  1386. }
  1387. } else {
  1388. MS_LOG(INFO) << "Parallel optimizer: " << parameter->ToString() << "'s shape does not satisfy the conditions.";
  1389. }
  1390. }
  1391. MS_LOG(INFO) << "SetParallelShape slice_shape " << parameter->ToString() << " shape "
  1392. << MakeValue(slice_shape)->ToString() << ", op name is " << distribute_operator->name();
  1393. std::shared_ptr<abstract::BaseShape> parallel_shape = std::make_shared<abstract::Shape>(slice_shape);
  1394. MS_EXCEPTION_IF_NULL(parallel_shape);
  1395. // Don't modify it in-place as the pointer of this AbstractValue may used as cache key in StaticAnalysis.
  1396. auto cloned_abstract = abstract->Clone();
  1397. MS_EXCEPTION_IF_NULL(cloned_abstract);
  1398. cloned_abstract->set_shape(parallel_shape);
  1399. parameter->set_abstract(cloned_abstract);
  1400. ParameterPtr parameter_ptr = parameter->cast<ParameterPtr>();
  1401. MS_EXCEPTION_IF_NULL(parameter_ptr);
  1402. parameter_ptr->set_user_data<TensorLayout>(std::make_shared<TensorLayout>(tensor_layout));
  1403. return opt_shard_group;
  1404. }
  1405. void CoverSliceShape(const FuncGraphPtr &root) {
  1406. MS_EXCEPTION_IF_NULL(root);
  1407. auto parameters = root->parameters();
  1408. for (auto &parameter : parameters) {
  1409. MS_EXCEPTION_IF_NULL(parameter->Shape());
  1410. auto iter = g_RefMap.find(parameter);
  1411. if (iter != g_RefMap.end()) {
  1412. std::string group = SetParallelShape(parameter, g_RefMap[parameter]);
  1413. // find all forward nodes that use parameter in graphs and insert allgather if group is not empty
  1414. ApplyParallelOptOnParam(root, parameter, group);
  1415. continue;
  1416. }
  1417. std::pair<AnfNodePtr, int64_t> res = FindSubGraph(root, parameter);
  1418. if (res.first == nullptr) {
  1419. MS_LOG(INFO) << "Parameter " << parameter->ToString() << " don't need to set parallel shape";
  1420. } else {
  1421. std::string group = SetParallelShape(parameter, res);
  1422. // find all forward nodes that use parameter in graphs and insert allgather if group is not empty
  1423. ApplyParallelOptOnParam(root, parameter, group);
  1424. MS_LOG(DEBUG) << "Parameter " << parameter->ToString() << " shape " << parameter->Shape()->ToString();
  1425. }
  1426. }
  1427. g_RefMap.clear();
  1428. }
  1429. bool ParameterIsCloned(const AnfNodePtr &parameter_node) {
  1430. MS_EXCEPTION_IF_NULL(parameter_node);
  1431. auto cloned_parameter = parameter_node->cast<ParameterPtr>();
  1432. MS_EXCEPTION_IF_NULL(cloned_parameter);
  1433. // find the clone parameter
  1434. if (!cloned_parameter->has_default()) {
  1435. return false;
  1436. }
  1437. auto param_value = cloned_parameter->param_info();
  1438. if (param_value == nullptr) {
  1439. return false;
  1440. }
  1441. bool cloned = param_value->cloned();
  1442. if (!cloned) {
  1443. return false;
  1444. }
  1445. MS_LOG(INFO) << "The parameter: " << cloned_parameter->name() << " is cloned";
  1446. return true;
  1447. }
  1448. void SetClonedTensorShapeForOptimizer(const FuncGraphPtr &root) {
  1449. MS_EXCEPTION_IF_NULL(root);
  1450. for (auto &cloned_parameter_node : root->parameters()) {
  1451. MS_EXCEPTION_IF_NULL(cloned_parameter_node);
  1452. auto cloned_parameter = cloned_parameter_node->cast<ParameterPtr>();
  1453. MS_EXCEPTION_IF_NULL(cloned_parameter);
  1454. if (!ParameterIsCloned(cloned_parameter_node)) {
  1455. continue;
  1456. }
  1457. auto param_value = cloned_parameter->param_info();
  1458. if (param_value == nullptr) {
  1459. continue;
  1460. }
  1461. // get the cloned index
  1462. int64_t cloned_index = param_value->cloned_index();
  1463. // find the be cloned parameter
  1464. bool found_be_cloned_parameter = false;
  1465. ParameterPtr cloned_from_parameter = nullptr;
  1466. AnfNodePtr cloned_from_node = nullptr;
  1467. for (auto &be_cloned_parameter_node : root->parameters()) {
  1468. MS_EXCEPTION_IF_NULL(be_cloned_parameter_node);
  1469. auto be_cloned_parameter = be_cloned_parameter_node->cast<ParameterPtr>();
  1470. MS_EXCEPTION_IF_NULL(be_cloned_parameter);
  1471. if (!be_cloned_parameter->has_default()) {
  1472. continue;
  1473. }
  1474. auto param_value_in = be_cloned_parameter->param_info();
  1475. if (param_value_in == nullptr) {
  1476. continue;
  1477. }
  1478. if (!param_value_in->be_cloned()) {
  1479. continue;
  1480. }
  1481. // get the be cloned index
  1482. auto &be_cloned_index = param_value_in->be_cloned_index();
  1483. if (std::find(be_cloned_index.begin(), be_cloned_index.end(), cloned_index) != be_cloned_index.end()) {
  1484. found_be_cloned_parameter = true;
  1485. cloned_from_parameter = be_cloned_parameter;
  1486. cloned_from_node = be_cloned_parameter_node;
  1487. }
  1488. }
  1489. if (found_be_cloned_parameter) {
  1490. // set the shape and tensor layout for cloned parameter
  1491. cloned_parameter->set_user_data<TensorLayout>(cloned_from_parameter->user_data<TensorLayout>());
  1492. MS_EXCEPTION_IF_NULL(cloned_parameter_node->abstract());
  1493. MS_EXCEPTION_IF_NULL(cloned_from_node->abstract());
  1494. auto cloned_abstract = cloned_parameter_node->abstract()->Clone();
  1495. MS_EXCEPTION_IF_NULL(cloned_abstract);
  1496. cloned_abstract->set_shape(cloned_from_node->abstract()->GetShapeTrack());
  1497. cloned_parameter_node->set_abstract(cloned_abstract);
  1498. MS_LOG(INFO) << "The parameter: " << cloned_parameter->name()
  1499. << " is cloned, the be cloned parameter is: " << cloned_from_parameter->name()
  1500. << ", clone index is: " << cloned_index;
  1501. } else {
  1502. MS_LOG(EXCEPTION) << "The parameter: " << cloned_parameter->name() << " is cloned, cloned index is "
  1503. << cloned_index << ", but not found the be cloned parameter";
  1504. }
  1505. }
  1506. }
  1507. void SetVirtualDatasetStrategy(const CNodePtr &node) {
  1508. MS_EXCEPTION_IF_NULL(node);
  1509. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  1510. bool full_batch = ParallelContext::GetInstance()->full_batch();
  1511. PrimitivePtr prim = GetValueNode<PrimitivePtr>(node->input(0));
  1512. MS_EXCEPTION_IF_NULL(prim);
  1513. if (prim->name() == VIRTUAL_DATA_SET) {
  1514. CheckGlobalDeviceManager();
  1515. int64_t dev_num;
  1516. if (full_batch) {
  1517. dev_num = 1;
  1518. } else {
  1519. dev_num = SizeToLong(g_device_manager->stage_device_num());
  1520. }
  1521. auto attrs_temp = prim->attrs();
  1522. std::vector<Shapes> shape_list = ExtractShape(node);
  1523. if (shape_list.empty()) {
  1524. MS_LOG(EXCEPTION) << "Failure:node " << node->ToString() << " failed to extract shape";
  1525. }
  1526. std::vector<ValuePtr> elements;
  1527. for (size_t i = 0; i < shape_list[0].size(); i++) {
  1528. if (shape_list[0][i].empty()) {
  1529. MS_LOG(EXCEPTION) << "shape_list[ " << i << " ].size() is zero";
  1530. }
  1531. Dimensions input_strategy = {dev_num};
  1532. for (size_t j = 1; j < shape_list[0][i].size(); j++) {
  1533. input_strategy.push_back(1);
  1534. }
  1535. elements.push_back(MakeValue(input_strategy));
  1536. }
  1537. ValueTuplePtr strategy = std::make_shared<ValueTuple>(elements);
  1538. attrs_temp[STRATEGY] = strategy;
  1539. (void)prim->SetAttrs(attrs_temp);
  1540. }
  1541. }
  1542. // find previous parallel care node.
  1543. bool FindPreNodes(const AnfNodePtr &node, vector<std::string> *unique_ids) {
  1544. MS_EXCEPTION_IF_NULL(unique_ids);
  1545. // if previous node is a parameter, handle it in the outsize.
  1546. if (node->isa<Parameter>()) {
  1547. return false;
  1548. }
  1549. if (!node->isa<CNode>()) {
  1550. return false;
  1551. }
  1552. CNodePtr cnode = node->cast<CNodePtr>();
  1553. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1554. return false;
  1555. }
  1556. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1557. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1558. if (IsParallelCareNode(cnode) && prim->name() != MAKE_TUPLE && prim->name() != MAKE_LIST) {
  1559. unique_ids->push_back(cnode->UniqueId());
  1560. return true;
  1561. }
  1562. bool find = false;
  1563. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  1564. if (prim->name() == DEPEND && index != 1) {
  1565. continue;
  1566. }
  1567. if (FindPreNodes(cnode->inputs()[index], unique_ids)) {
  1568. find = true;
  1569. continue;
  1570. }
  1571. }
  1572. return find;
  1573. }
  1574. void FindLastNodesUniqueId(const std::vector<AnfNodePtr> &all_nodes, vector<std::string> *unique_ids) {
  1575. MS_EXCEPTION_IF_NULL(unique_ids);
  1576. for (auto &node : all_nodes) {
  1577. auto cnode = node->cast<CNodePtr>();
  1578. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1579. continue;
  1580. }
  1581. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1582. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1583. if (prim->name() == RETURN) {
  1584. if (!FindPreNodes(cnode, unique_ids)) {
  1585. MS_LOG(WARNING) << "cannot find the last parallel care node in eval graph";
  1586. }
  1587. }
  1588. }
  1589. }
  1590. StrategyPtr GenerateBatchParallelStrategy(const OperatorInfoPtr operator_, const PrimitivePtr prim) {
  1591. MS_EXCEPTION_IF_NULL(operator_);
  1592. MS_EXCEPTION_IF_NULL(prim);
  1593. StrategyPtr strategyPtr;
  1594. std::shared_ptr<Strategys> strategy_v_ptr = operator_->GenerateBatchStrategies();
  1595. MS_EXCEPTION_IF_NULL(strategy_v_ptr);
  1596. strategyPtr = NewStrategy(0, *strategy_v_ptr);
  1597. std::vector<ValuePtr> elements;
  1598. for (size_t i = 0; i < strategy_v_ptr->size(); i++) {
  1599. elements.push_back(MakeValue((*strategy_v_ptr)[i]));
  1600. }
  1601. ValueTuplePtr strategy = std::make_shared<ValueTuple>(elements);
  1602. // display the strategy generated by batch parallel
  1603. auto attrs = prim->attrs();
  1604. attrs[GEN_STRATEGY] = strategy;
  1605. (void)prim->SetAttrs(attrs);
  1606. MS_LOG(INFO) << "prim " << prim->name() << " batch parallel strategy is " << attrs[GEN_STRATEGY]->ToString();
  1607. return strategyPtr;
  1608. }
  1609. void SetLastNodeStrategy(const StrategyPtr strategyPtr) {
  1610. auto strategys = strategyPtr->GetInputDim();
  1611. for (size_t i = 0; i < strategys.size(); ++i) {
  1612. for (size_t j = 0; j < strategys[i].size(); ++j) {
  1613. strategys[i][j] = 1;
  1614. }
  1615. }
  1616. strategyPtr->ResetInputs(strategys);
  1617. }
  1618. void ExtractInformation(const std::vector<AnfNodePtr> &all_nodes, bool is_training) {
  1619. // load strategy map from checkpoint
  1620. StrategyMap stra_map;
  1621. if (StrategyCheckpoint::GetInstance().LoadCheckPointOn()) {
  1622. if (StrategyCheckpoint::GetInstance().Load(&stra_map) != SUCCESS) {
  1623. MS_LOG(EXCEPTION) << "Load strategy checkpoint failed";
  1624. }
  1625. }
  1626. vector<std::string> last_forward_node_ids;
  1627. if (!is_training) {
  1628. FindLastNodesUniqueId(all_nodes, &last_forward_node_ids);
  1629. MS_LOG(INFO) << "there are " << last_forward_node_ids.size() << " output nodes in eval/predict";
  1630. }
  1631. for (auto &node : all_nodes) {
  1632. auto cnode = node->cast<CNodePtr>();
  1633. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1634. continue;
  1635. }
  1636. SetVirtualDatasetStrategy(cnode);
  1637. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1638. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1639. if (prim->name() == MAKE_TUPLE || prim->name() == MAKE_LIST) {
  1640. continue;
  1641. }
  1642. auto attrs = prim->attrs();
  1643. MS_LOG(INFO) << "extract information: node: " << node->ToString() << " prim " << prim->name();
  1644. if (IsParallelCareNode(cnode)) {
  1645. std::vector<Shapes> shape_list = ExtractShape(cnode);
  1646. if (shape_list.empty()) {
  1647. MS_LOG(EXCEPTION) << "Failure:node " << node->ToString() << " failed to extract shape";
  1648. }
  1649. OperatorInfoPtr operator_ = OperatorInstance(prim, attrs, shape_list);
  1650. if (operator_ == nullptr) {
  1651. MS_LOG(EXCEPTION) << "Failure:Primitive " << prim->name() << " OperatorInstance failed";
  1652. }
  1653. auto &inputs = cnode->inputs();
  1654. std::vector<ValuePtr> input_value;
  1655. for (size_t index = 1; index < inputs.size(); ++index) {
  1656. if (inputs[index]->isa<ValueNode>()) {
  1657. input_value.push_back(GetValueNode(inputs[index]));
  1658. } else {
  1659. input_value.emplace_back(nullptr);
  1660. }
  1661. }
  1662. StrategyPtr strategyPtr = nullptr;
  1663. (*operator_).set_input_value(input_value);
  1664. (*operator_).set_outputs_dtype(cnode->Type());
  1665. (*operator_).set_cnode(cnode);
  1666. if (prim->name() == RESHAPE) {
  1667. cnode->set_user_data<OperatorInfo>(operator_);
  1668. continue;
  1669. }
  1670. // load strategy checkpoint
  1671. // key of strategy map
  1672. std::string strategy_key_name = "";
  1673. auto param_names = NodeParameterName(cnode);
  1674. if (!param_names.empty()) {
  1675. strategy_key_name = prim->name() + "_" + param_names[0].first;
  1676. }
  1677. bool load_strategy_from_ckpt =
  1678. StrategyCheckpoint::GetInstance().LoadCheckPointOn() && stra_map.find(strategy_key_name) != stra_map.end();
  1679. bool is_last_nodes = std::find(last_forward_node_ids.begin(), last_forward_node_ids.end(), cnode->UniqueId()) !=
  1680. last_forward_node_ids.end();
  1681. bool full_batch = ParallelContext::GetInstance()->full_batch();
  1682. if ((is_last_nodes && !full_batch) || (!StrategyFound(attrs) && !load_strategy_from_ckpt)) {
  1683. MS_LOG(INFO) << "ExtractInformation: the strategy of node " << node->ToString() << " prim " << prim->name()
  1684. << " is empty, using batch parallel";
  1685. strategyPtr = GenerateBatchParallelStrategy(operator_, prim);
  1686. } else if (load_strategy_from_ckpt) {
  1687. strategyPtr = stra_map[strategy_key_name];
  1688. } else {
  1689. strategyPtr = ExtractStrategy(attrs);
  1690. }
  1691. if (strategyPtr != nullptr) {
  1692. if (is_last_nodes && full_batch) {
  1693. SetLastNodeStrategy(strategyPtr);
  1694. }
  1695. if (operator_->Init(strategyPtr) == FAILED) {
  1696. MS_LOG(EXCEPTION) << "Failure:operator " << prim->name() << " init failed";
  1697. }
  1698. cnode->set_user_data<OperatorInfo>(operator_);
  1699. } else {
  1700. MS_LOG(EXCEPTION) << "ERROR:strategy_ptr is nullptr";
  1701. }
  1702. }
  1703. }
  1704. }
  1705. TensorLayout GetInputLayoutFromCNode(const std::pair<AnfNodePtr, int64_t> &node_pair) {
  1706. CNodePtr cnode = node_pair.first->cast<CNodePtr>();
  1707. MS_EXCEPTION_IF_NULL(cnode);
  1708. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1709. MS_EXCEPTION_IF_NULL(distribute_operator);
  1710. int64_t index = node_pair.second;
  1711. if (index > SizeToLong(distribute_operator->inputs_tensor_info().size())) {
  1712. MS_LOG(EXCEPTION) << "The index is out of range, the node_pair.second is " << index - 1 << ", the vector size is "
  1713. << distribute_operator->inputs_tensor_info().size();
  1714. }
  1715. TensorInfo tensorinfo_in = distribute_operator->inputs_tensor_info()[LongToSize(index - 1)];
  1716. TensorLayout tensorlayout_in = tensorinfo_in.tensor_layout();
  1717. return tensorlayout_in;
  1718. }
  1719. // if reshape's output connect to several primitive, return the first layout found
  1720. std::shared_ptr<TensorLayout> FindNextLayout(const CNodePtr &cnode) {
  1721. MS_EXCEPTION_IF_NULL(cnode);
  1722. MS_EXCEPTION_IF_NULL(cnode->func_graph());
  1723. FuncGraphManagerPtr manager = cnode->func_graph()->manager();
  1724. MS_EXCEPTION_IF_NULL(manager);
  1725. AnfNodeIndexSet node_set = manager->node_users()[cnode];
  1726. for (auto &node_pair : node_set) {
  1727. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  1728. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  1729. continue;
  1730. }
  1731. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  1732. MS_EXCEPTION_IF_NULL(prim_anf_node);
  1733. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1734. MS_EXCEPTION_IF_NULL(node_prim);
  1735. MS_LOG(INFO) << "FindNextLayout prim " << node_prim->name();
  1736. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  1737. continue;
  1738. }
  1739. if (IsParallelCareNode(use_apply) && use_apply->has_user_data<OperatorInfo>()) {
  1740. MS_LOG(INFO) << "FindNextLayout success prim " << node_prim->name();
  1741. auto layout = GetInputLayoutFromCNode(node_pair);
  1742. return std::make_shared<TensorLayout>(layout);
  1743. }
  1744. MS_LOG(DEBUG) << "FindNextLayout failed prim " << node_prim->name() << " " << IsParallelCareNode(use_apply)
  1745. << " " << use_apply->has_user_data<OperatorInfo>();
  1746. auto layout_ptr = FindNextLayout(use_apply);
  1747. if (layout_ptr) {
  1748. return layout_ptr;
  1749. }
  1750. }
  1751. MS_LOG(WARNING) << "FindNextLayout return nullptr, if reshape is not the last primitive, there must be some error";
  1752. return nullptr;
  1753. }
  1754. std::shared_ptr<TensorLayout> GetOutputLayoutFromCNode(const CNodePtr &cnode, size_t output_index) {
  1755. MS_EXCEPTION_IF_NULL(cnode);
  1756. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1757. MS_EXCEPTION_IF_NULL(distribute_operator);
  1758. if (distribute_operator->outputs_tensor_info().size() < output_index) {
  1759. MS_LOG(EXCEPTION) << "outputs_tensor_info size is " << distribute_operator->inputs_tensor_info().size()
  1760. << ", must be less than output_index " << output_index;
  1761. }
  1762. TensorInfo tensorinfo_out = distribute_operator->outputs_tensor_info()[output_index];
  1763. TensorLayout tensorlayout_out = tensorinfo_out.tensor_layout();
  1764. return std::make_shared<TensorLayout>(tensorlayout_out);
  1765. }
  1766. std::shared_ptr<TensorLayout> FindPrevParallelCareNodeLayout(const AnfNodePtr &node, size_t output_index) {
  1767. if (!node->isa<CNode>()) {
  1768. return nullptr;
  1769. }
  1770. CNodePtr cnode = node->cast<CNodePtr>();
  1771. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1772. return nullptr;
  1773. }
  1774. if (IsParallelCareNode(cnode) && cnode->has_user_data<OperatorInfo>()) {
  1775. auto layout_ptr = GetOutputLayoutFromCNode(cnode, output_index);
  1776. if (!layout_ptr) {
  1777. MS_LOG(EXCEPTION) << "Failure:GetLayoutFromCNode failed";
  1778. }
  1779. return layout_ptr;
  1780. }
  1781. return nullptr;
  1782. }
  1783. std::shared_ptr<TensorLayout> FindParameterNextLayout(const AnfNodePtr &node) {
  1784. FuncGraphManagerPtr manager = node->func_graph()->manager();
  1785. MS_EXCEPTION_IF_NULL(manager);
  1786. AnfNodeIndexSet node_set = manager->node_users()[node];
  1787. for (auto &node_pair : node_set) {
  1788. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  1789. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  1790. continue;
  1791. }
  1792. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  1793. MS_EXCEPTION_IF_NULL(prim_anf_node);
  1794. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1795. MS_EXCEPTION_IF_NULL(node_prim);
  1796. if ((node_prim->name() == DEPEND && node_pair.second != 1) || node_prim->name() == RESHAPE) {
  1797. continue;
  1798. }
  1799. if (IsParallelCareNode(use_apply) && use_apply->has_user_data<OperatorInfo>()) {
  1800. auto layout = GetInputLayoutFromCNode(node_pair);
  1801. return std::make_shared<TensorLayout>(layout);
  1802. }
  1803. }
  1804. return nullptr;
  1805. }
  1806. std::shared_ptr<TensorLayout> CreateParameterLayout(const AnfNodePtr &node) {
  1807. // Create DataParallel tensor layout for parameter(support WideDeep).
  1808. auto next_layout = FindParameterNextLayout(node);
  1809. if (next_layout != nullptr) {
  1810. return next_layout;
  1811. }
  1812. CheckGlobalDeviceManager();
  1813. int64_t dev_num = g_device_manager->stage_device_num();
  1814. TensorLayout input_tensor_layout;
  1815. // create input_shape
  1816. Shapes inputs_shape = GetNodeShape(node);
  1817. Shape input_shape_array = inputs_shape[0];
  1818. if (input_shape_array.empty()) {
  1819. MS_LOG(EXCEPTION) << "Don't support reshape a scalar parameter.";
  1820. }
  1821. // create tensor_map
  1822. size_t shape_size = input_shape_array.size();
  1823. TensorMap input_tensor_map_array(SizeToLong(shape_size) - 1, -1);
  1824. input_tensor_map_array.insert(input_tensor_map_array.begin(), 0);
  1825. // create dev_matrix
  1826. Shape dev_matrix_array = {dev_num};
  1827. if (input_tensor_layout.InitFromVector(dev_matrix_array, input_tensor_map_array, input_shape_array) != SUCCESS) {
  1828. MS_LOG(EXCEPTION) << "Create tensor layout for parameter failed.";
  1829. }
  1830. return std::make_shared<TensorLayout>(input_tensor_layout);
  1831. }
  1832. RedistributionOpListPtr InferSensRedistribution(const AnfNodePtr &node, const TensorLayout &loss_layout) {
  1833. MS_EXCEPTION_IF_NULL(node);
  1834. TensorRedistribution tensor_redistribution;
  1835. // create stand alone layout:TensorMap:[all -1],dev_matrix:[dev_num].
  1836. CheckGlobalDeviceManager();
  1837. int64_t dev_num = g_device_manager->stage_device_num();
  1838. TensorLayout stand_alone_layout;
  1839. Shapes inputs_shape = GetNodeShape(node);
  1840. if (inputs_shape.empty()) {
  1841. MS_LOG(EXCEPTION) << "InferSensRedistribution failed cause inputs shape is empty.";
  1842. }
  1843. Shape input_shape_array = inputs_shape[0];
  1844. if (input_shape_array.empty()) {
  1845. MS_LOG(INFO) << "No need to redistribution for sens.";
  1846. return nullptr;
  1847. }
  1848. // TensorMap
  1849. TensorMap stand_alone_tensor_map_array(SizeToLong(input_shape_array.size()), -1);
  1850. // Dev_matrix
  1851. Shape dev_matrix_array = {dev_num};
  1852. if (stand_alone_layout.InitFromVector(dev_matrix_array, stand_alone_tensor_map_array, input_shape_array) == FAILED) {
  1853. MS_LOG(EXCEPTION) << "Create tensor layout for Sens failed.";
  1854. }
  1855. // Infer Redistribution op list for stand alone and loss layout.
  1856. RankList dev_list = g_device_manager->GetDeviceListInThisStage();
  1857. if (tensor_redistribution.Init(stand_alone_layout, loss_layout, dev_list) == FAILED) {
  1858. MS_LOG(EXCEPTION) << "Redistribution for Sens init failed.";
  1859. }
  1860. RedistributionOpListPtr sens_redistribution_list = tensor_redistribution.InferTensorRedistributionOperatorList();
  1861. MS_EXCEPTION_IF_NULL(sens_redistribution_list);
  1862. return sens_redistribution_list;
  1863. }
  1864. std::shared_ptr<TensorLayout> FindPrevLayout(const AnfNodePtr &node) {
  1865. if (node->isa<Parameter>()) {
  1866. return CreateParameterLayout(node);
  1867. }
  1868. if (!node->isa<CNode>()) {
  1869. return nullptr;
  1870. }
  1871. CNodePtr cnode = node->cast<CNodePtr>();
  1872. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1873. return nullptr;
  1874. }
  1875. if (IsParallelCareNode(cnode) && cnode->has_user_data<OperatorInfo>()) {
  1876. auto layout_ptr = GetOutputLayoutFromCNode(cnode, 0);
  1877. if (!layout_ptr) {
  1878. MS_LOG(EXCEPTION) << "Failure:GetLayoutFromCNode failed";
  1879. }
  1880. return layout_ptr;
  1881. }
  1882. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1883. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1884. if (prim->name() == TUPLE_GETITEM) {
  1885. auto tuple_index = GetTupleGetItemIndex(cnode);
  1886. auto layout_ptr = FindPrevParallelCareNodeLayout(cnode->input(1), LongToSize(tuple_index));
  1887. if (!layout_ptr) {
  1888. MS_LOG(EXCEPTION)
  1889. << " Failure:FindPrevLayout failed, tuple_getitem before reshape, but there does not exit a parallel care node "
  1890. "before tuple_getitem!";
  1891. }
  1892. return layout_ptr;
  1893. }
  1894. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  1895. if (prim->name() == DEPEND && index != 1) {
  1896. continue;
  1897. }
  1898. auto layout_ptr = FindPrevLayout(cnode->inputs()[index]);
  1899. if (!layout_ptr) {
  1900. continue;
  1901. }
  1902. return layout_ptr;
  1903. }
  1904. MS_LOG(WARNING) << "FindPrevLayout return nullptr, if reshape is not the first primitive, there must be some error";
  1905. return nullptr;
  1906. }
  1907. void ReshapeInit(const std::vector<AnfNodePtr> &all_nodes) {
  1908. for (auto &node : all_nodes) {
  1909. auto cnode = node->cast<CNodePtr>();
  1910. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1911. continue;
  1912. }
  1913. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1914. if (!IsParallelCareNode(cnode) || !cnode->has_user_data<OperatorInfo>()) {
  1915. continue;
  1916. }
  1917. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1918. MS_EXCEPTION_IF_NULL(prim);
  1919. OperatorInfoPtr operator_info = cnode->user_data<OperatorInfo>();
  1920. if (operator_info == nullptr) {
  1921. MS_LOG(EXCEPTION) << "Failure:Primitive " << prim->ToString() << " OperatorInstance is nullptr";
  1922. }
  1923. if (prim->name() != RESHAPE) {
  1924. continue;
  1925. }
  1926. auto attrs = prim->attrs();
  1927. if (StrategyFound(attrs)) {
  1928. MS_LOG(EXCEPTION) << "Setting strategy for Reshape goes for nothing!";
  1929. }
  1930. MS_ASSERT(cnode->inputs().size() == 3);
  1931. auto prev_layout_ptr = FindPrevLayout(cnode->input(1));
  1932. if (prev_layout_ptr) {
  1933. auto reshape_info_ptr = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  1934. reshape_info_ptr->SetInputLayout(*prev_layout_ptr);
  1935. }
  1936. auto next_layout_ptr = FindNextLayout(cnode);
  1937. if (next_layout_ptr) {
  1938. auto reshape_info_ptr = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  1939. reshape_info_ptr->SetOutputLayout(*next_layout_ptr);
  1940. }
  1941. if (operator_info->Init(nullptr) == FAILED) {
  1942. MS_LOG(EXCEPTION) << "Failure:operator " << prim->ToString() << " init failed";
  1943. }
  1944. }
  1945. }
  1946. CNodePtr HandleDependLoss(const CNodePtr &cnode) {
  1947. // Handle return->depend->loss
  1948. auto prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1949. MS_EXCEPTION_IF_NULL(prim);
  1950. if (prim->name() == DEPEND) {
  1951. auto depend_before = cnode->input(1)->cast<CNodePtr>();
  1952. MS_EXCEPTION_IF_NULL(depend_before);
  1953. return HandleDependLoss(depend_before);
  1954. }
  1955. return cnode;
  1956. }
  1957. LossNodeInfo FindLossCNode(const FuncGraphPtr &func_graph) {
  1958. LossNodeInfo loss_node_info;
  1959. MS_EXCEPTION_IF_NULL(func_graph);
  1960. CNodePtr return_node = func_graph->get_return();
  1961. MS_EXCEPTION_IF_NULL(return_node);
  1962. if (return_node->size() < 2) {
  1963. MS_LOG(EXCEPTION) << "Failure: " << return_node->ToString() << " size is smaller than 2";
  1964. }
  1965. AnfNodePtr pre_node = return_node->input(1);
  1966. MS_EXCEPTION_IF_NULL(pre_node);
  1967. auto pre_cnode = pre_node->cast<CNodePtr>();
  1968. if (pre_cnode == nullptr || !IsValueNode<Primitive>(pre_cnode->input(0))) {
  1969. return loss_node_info;
  1970. }
  1971. if (!IsValueNode<Primitive>(pre_cnode->input(0))) {
  1972. MS_LOG(DEBUG) << "pre_cnode:" << pre_cnode->ToString();
  1973. return loss_node_info;
  1974. }
  1975. auto prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  1976. // return -> cast
  1977. if (prim->name() == CAST && !pre_cnode->has_user_data<OperatorInfo>()) {
  1978. pre_cnode = pre_cnode->input(1)->cast<CNodePtr>();
  1979. MS_EXCEPTION_IF_NULL(pre_cnode);
  1980. }
  1981. pre_cnode = HandleDependLoss(pre_cnode);
  1982. auto current_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  1983. // notice: the GetNext op has not input
  1984. if (INVALID_LOSS_OPS.find(current_prim->name()) != INVALID_LOSS_OPS.end()) {
  1985. MS_LOG(INFO) << "The loss is: " << current_prim->name();
  1986. loss_node_info.loss_node = pre_cnode;
  1987. return loss_node_info;
  1988. }
  1989. // size of common cnode is larger than 1
  1990. if (pre_cnode->size() < 2) {
  1991. MS_LOG(EXCEPTION) << pre_cnode->ToString() << " size( " << pre_cnode->inputs().size() << " ) is smaller than 2";
  1992. }
  1993. // return -> tuple_getitem -> loss
  1994. if (current_prim->name() == TUPLE_GETITEM) {
  1995. auto tuple_index = GetTupleGetItemIndex(pre_cnode);
  1996. AnfNodePtr pre_pre_node = pre_cnode->input(1);
  1997. MS_EXCEPTION_IF_NULL(pre_pre_node);
  1998. auto pre_pre_cnode = pre_pre_node->cast<CNodePtr>();
  1999. loss_node_info.has_tuple_getitem = true;
  2000. loss_node_info.dout_index = tuple_index;
  2001. loss_node_info.loss_node = pre_pre_cnode;
  2002. return loss_node_info;
  2003. }
  2004. // return -> make_tuple
  2005. if (current_prim->name() == MAKE_TUPLE) {
  2006. MS_LOG(WARNING) << "The loss have make_tuple, it is not supported";
  2007. return loss_node_info;
  2008. }
  2009. // return -> loss
  2010. loss_node_info.loss_node = pre_cnode;
  2011. MS_LOG(DEBUG) << "The loss name is " << current_prim->name();
  2012. return loss_node_info;
  2013. }
  2014. TensorLayouts GetLossNodeGradOutputLayout(const LossNodeInfo &node_info) {
  2015. TensorLayouts ret;
  2016. auto loss_cnode = node_info.loss_node;
  2017. MS_EXCEPTION_IF_NULL(loss_cnode);
  2018. ValueNodePtr prim_anf_node = loss_cnode->input(0)->cast<ValueNodePtr>();
  2019. MS_EXCEPTION_IF_NULL(prim_anf_node);
  2020. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  2021. MS_EXCEPTION_IF_NULL(prim);
  2022. if (INVALID_LOSS_OPS.find(prim->name()) != INVALID_LOSS_OPS.end()) {
  2023. MS_LOG(WARNING) << "The loss name is: " << prim->name() << ", do nothing for split sens now";
  2024. return ret;
  2025. }
  2026. OperatorInfoPtr operator_info = loss_cnode->user_data<OperatorInfo>();
  2027. MS_EXCEPTION_IF_NULL(operator_info);
  2028. TensorInfo loss_grad_tensor_info;
  2029. size_t op_output_size = operator_info->outputs_tensor_info().size();
  2030. MS_LOG(INFO) << "The loss name is " << operator_info->name() << ", the has tuple item is "
  2031. << node_info.has_tuple_getitem << ", the output size is " << op_output_size << ", the dout_index is "
  2032. << node_info.dout_index;
  2033. if ((op_output_size == 0) || (op_output_size <= LongToSize(node_info.dout_index))) {
  2034. MS_LOG(EXCEPTION) << "The index is " << node_info.dout_index << ", but the size of outputs is " << op_output_size;
  2035. }
  2036. if (!node_info.has_tuple_getitem && (op_output_size > 1)) {
  2037. MS_LOG(EXCEPTION) << "Currently, it is not supported that the sens is a tuple.";
  2038. }
  2039. loss_grad_tensor_info = operator_info->outputs_tensor_info()[LongToSize(node_info.dout_index)];
  2040. ret.push_back(loss_grad_tensor_info.tensor_layout());
  2041. return ret;
  2042. }
  2043. void SplitSens(const CNodePtr &grad_sens_node, const TensorLayout &loss_grad_layout) {
  2044. MS_EXCEPTION_IF_NULL(grad_sens_node);
  2045. if (grad_sens_node->size() <= 1) {
  2046. MS_LOG(EXCEPTION) << "The size of grad sens node is smaller than 2";
  2047. }
  2048. AnfNodePtr sens_tensor_node = grad_sens_node->input(1);
  2049. MS_EXCEPTION_IF_NULL(sens_tensor_node);
  2050. Shapes sens_shapes = GetNodeShape(sens_tensor_node);
  2051. if (sens_shapes.size() != 1) {
  2052. MS_LOG(EXCEPTION) << "GetNodeShape for sens_tensor_node, output size is not 1";
  2053. }
  2054. // If the shape of sens tensor is [] or [1], no need to split it.
  2055. Shape sens_shape = sens_shapes[0];
  2056. if (sens_shape.empty() || ((sens_shape.size() == 1) && (sens_shape[0] == 1))) {
  2057. if (sens_tensor_node->isa<Parameter>()) {
  2058. auto sens_tensor_param = sens_tensor_node->cast<ParameterPtr>();
  2059. MS_LOG(DEBUG) << "loss layout " << loss_grad_layout.ToString();
  2060. sens_tensor_param->set_user_data<TensorLayout>(std::make_shared<TensorLayout>(loss_grad_layout));
  2061. }
  2062. MS_LOG(INFO) << "The shape of sens is " << ShapeToString(sens_shape) << ", no need to split sens";
  2063. return;
  2064. }
  2065. auto loss_shape = loss_grad_layout.tensor_shape().array();
  2066. if (loss_shape != sens_shape) {
  2067. MS_LOG(EXCEPTION) << "The shape of sens is not equal to loss output, it is unsupported now. Sens shape is "
  2068. << ShapeToString(sens_shape) << ", loss shape is " << ShapeToString(loss_shape);
  2069. }
  2070. MS_LOG(INFO) << "The shape of sens is " << ShapeToString(sens_shape) << ", split it.";
  2071. if (!IsValueNode<Tensor>(sens_tensor_node)) {
  2072. if (sens_tensor_node->isa<Parameter>()) {
  2073. MS_LOG(DEBUG) << "loss layout " << loss_grad_layout.ToString();
  2074. AbstractBasePtr abstract = sens_tensor_node->abstract();
  2075. MS_EXCEPTION_IF_NULL(abstract);
  2076. auto slice_shape = loss_grad_layout.slice_shape().array();
  2077. std::shared_ptr<abstract::BaseShape> parallel_shape = std::make_shared<abstract::Shape>(slice_shape);
  2078. MS_EXCEPTION_IF_NULL(parallel_shape);
  2079. auto cloned_abstract = abstract->Clone();
  2080. MS_EXCEPTION_IF_NULL(cloned_abstract);
  2081. cloned_abstract->set_shape(parallel_shape);
  2082. sens_tensor_node->set_abstract(cloned_abstract);
  2083. auto sens_tensor_param = sens_tensor_node->cast<ParameterPtr>();
  2084. sens_tensor_param->set_user_data<TensorLayout>(std::make_shared<TensorLayout>(loss_grad_layout));
  2085. return;
  2086. }
  2087. if (sens_tensor_node->isa<CNode>()) {
  2088. auto op_list_ptr = InferSensRedistribution(sens_tensor_node, loss_grad_layout);
  2089. if (op_list_ptr == nullptr) {
  2090. return;
  2091. }
  2092. auto sens_tensor_cnode = sens_tensor_node->cast<CNodePtr>();
  2093. auto func_graph = grad_sens_node->func_graph();
  2094. MS_EXCEPTION_IF_NULL(func_graph);
  2095. InsertRedistribution(op_list_ptr, grad_sens_node, func_graph, 1, sens_tensor_cnode);
  2096. return;
  2097. }
  2098. MS_LOG(EXCEPTION) << "The type of sens node is not Tensor or Parameter or CNode, it is unsupported now.";
  2099. }
  2100. // Use _GetTensorSlice operator to split the sens tensor
  2101. FuncGraphPtr func_graph = grad_sens_node->func_graph(); // only cnode can get the graph
  2102. MS_EXCEPTION_IF_NULL(func_graph);
  2103. Operator op = CreateGetTensorSliceOp(loss_grad_layout);
  2104. InsertGetTensorSliceOp(op, grad_sens_node, func_graph, 1, SPLIT_SENS);
  2105. }
  2106. void InsertForwardOps(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  2107. MS_EXCEPTION_IF_NULL(distribute_operator);
  2108. MS_EXCEPTION_IF_NULL(cnode);
  2109. OperatorVector forward_op = distribute_operator->forward_op();
  2110. if (!forward_op.empty()) {
  2111. MS_LOG(INFO) << "Insert forward op for " << distribute_operator->name();
  2112. ForwardCommunication(forward_op, cnode);
  2113. }
  2114. }
  2115. void StepReplace(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  2116. MS_EXCEPTION_IF_NULL(distribute_operator);
  2117. MS_EXCEPTION_IF_NULL(cnode);
  2118. // StepReplaceOp
  2119. OperatorVector replace_op = distribute_operator->replace_op();
  2120. if (!replace_op.empty()) {
  2121. MS_LOG(INFO) << "StepReplaceOp " << cnode->ToString();
  2122. StepReplaceOp(replace_op, cnode);
  2123. }
  2124. // StepReplaceGraph: after calling StepReplaceGraph, cnode can not be used anymore.
  2125. ReplaceGraphPtr replace_graph = distribute_operator->replace_graph(cnode);
  2126. if (!replace_op.empty() && replace_graph) {
  2127. MS_LOG(EXCEPTION) << "Only one of replace_op or replace_op can be used";
  2128. }
  2129. if (replace_graph) {
  2130. MS_LOG(INFO) << "StepReplaceGraph " << cnode->ToString();
  2131. StepReplaceGraph(replace_graph, cnode);
  2132. }
  2133. }
  2134. void HandleDropoutNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  2135. MS_EXCEPTION_IF_NULL(distribute_operator);
  2136. MS_EXCEPTION_IF_NULL(cnode);
  2137. std::string op_name = distribute_operator->name();
  2138. if (op_name.find(DROPOUT_DO_MASK) == std::string::npos) {
  2139. return;
  2140. }
  2141. DropoutDoMaskInfoPtr dropout_do_mask = std::dynamic_pointer_cast<DropoutDoMaskInfo>(distribute_operator);
  2142. MS_EXCEPTION_IF_NULL(dropout_do_mask);
  2143. std::vector<Operator> replace_op = dropout_do_mask->GetDropoutGenMaskReplaceOp(cnode);
  2144. if (replace_op.empty()) {
  2145. MS_LOG(DEBUG) << "No need to replace dropout_gen_mask";
  2146. return;
  2147. }
  2148. if (cnode->inputs().size() != DROPOUT_DO_MASK_CNODE_INPUT_SIZE) {
  2149. MS_LOG(EXCEPTION) << "The size of drop out do mask cnode's input is not " << DROPOUT_DO_MASK_CNODE_INPUT_SIZE;
  2150. }
  2151. ReplaceOneOp(replace_op[0], cnode->input(DROPOUT_GEN_MASK_INDEX)->cast<CNodePtr>());
  2152. }
  2153. void HandleTileNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  2154. MS_EXCEPTION_IF_NULL(cnode);
  2155. if (cnode->size() < 3 || !IsValueNode<Primitive>(cnode->input(0))) {
  2156. return;
  2157. }
  2158. auto prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  2159. if (prim->name() != TILE) {
  2160. return;
  2161. }
  2162. TileInfoPtr tile = std::dynamic_pointer_cast<TileInfo>(distribute_operator);
  2163. MS_EXCEPTION_IF_NULL(tile);
  2164. tile->UpdateMultiples(cnode);
  2165. }
  2166. void HandleSpecialNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  2167. HandleDropoutNode(distribute_operator, cnode);
  2168. HandleTileNode(distribute_operator, cnode);
  2169. }
  2170. std::set<FuncGraphPtr> FindForwardGraphByRootNodes(const AnfNodeSet &root_all_nodes) {
  2171. // J->CNode->Graph
  2172. std::set<FuncGraphPtr> graph_set;
  2173. for (auto &node : root_all_nodes) {
  2174. MS_EXCEPTION_IF_NULL(node);
  2175. if (!node->isa<CNode>()) {
  2176. continue;
  2177. }
  2178. auto cnode = node->cast<CNodePtr>();
  2179. if ((cnode->size() < 2) || !IsValueNode<Primitive>(cnode->input(0))) {
  2180. continue;
  2181. }
  2182. auto expect_j_prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  2183. if (expect_j_prim->name() != J) {
  2184. continue;
  2185. }
  2186. if (IsValueNode<FuncGraph>(cnode->input(1))) {
  2187. auto graph = GetValueNode<FuncGraphPtr>(cnode->input(1));
  2188. MS_LOG(DEBUG) << "Find the forward graph success";
  2189. graph_set.insert(graph);
  2190. auto manager = graph->manager();
  2191. MS_EXCEPTION_IF_NULL(manager);
  2192. auto graph_used = manager->func_graphs_used_total(graph);
  2193. for (auto &sub_graph : graph_used) {
  2194. graph_set.insert(sub_graph);
  2195. }
  2196. }
  2197. }
  2198. return graph_set;
  2199. }
  2200. void StepSplitSens(const std::pair<CNodePtr, LossNodeInfo> &sens_loss_pair) {
  2201. CNodePtr sens_node = sens_loss_pair.first;
  2202. auto loss_node = sens_loss_pair.second;
  2203. auto loss_grad_layout = GetLossNodeGradOutputLayout(loss_node);
  2204. if (!loss_grad_layout.empty()) {
  2205. SplitSens(sens_node, loss_grad_layout[0]);
  2206. }
  2207. }
  2208. // Sens node satisfies the following conditions: cnode(sens)-->cnode(tuple_getitem)-->cnode-->cnode(J)
  2209. std::vector<std::pair<CNodePtr, LossNodeInfo>> GetSensLossPairs(const FuncGraphPtr &root) {
  2210. MS_EXCEPTION_IF_NULL(root);
  2211. std::vector<std::pair<CNodePtr, LossNodeInfo>> sens_loss_pairs;
  2212. for (auto &node : root->nodes()) {
  2213. if (!node->isa<CNode>()) {
  2214. continue;
  2215. }
  2216. // cnode(sens)-->cnode(tuple_getitem)
  2217. auto sens_cnode = node->cast<CNodePtr>();
  2218. AnfNodePtr expect_tuple_getitem = sens_cnode->input(0);
  2219. MS_EXCEPTION_IF_NULL(expect_tuple_getitem);
  2220. if (!expect_tuple_getitem->isa<CNode>()) {
  2221. continue;
  2222. }
  2223. auto expect_tuple_getitem_cnode = expect_tuple_getitem->cast<CNodePtr>();
  2224. if (!IsSomePrimitive(expect_tuple_getitem_cnode, TUPLE_GETITEM)) {
  2225. continue;
  2226. }
  2227. // cnode(sens)-->cnode(tuple_getitem)-->cnode
  2228. AnfNodePtr expect_anonymous = expect_tuple_getitem_cnode->input(1);
  2229. MS_EXCEPTION_IF_NULL(expect_anonymous);
  2230. if (!expect_anonymous->isa<CNode>()) {
  2231. continue;
  2232. }
  2233. // cnode(sens)-->cnode(tuple_getitem)-->cnode-->cnode(J)
  2234. auto expect_anonymous_cnode = expect_anonymous->cast<CNodePtr>();
  2235. AnfNodePtr expect_j = expect_anonymous_cnode->input(0);
  2236. MS_EXCEPTION_IF_NULL(expect_j);
  2237. if (!expect_j->isa<CNode>()) {
  2238. continue;
  2239. }
  2240. auto expect_j_cnode = expect_j->cast<CNodePtr>();
  2241. if (!IsSomePrimitive(expect_j_cnode, J)) {
  2242. continue;
  2243. }
  2244. if (!IsValueNode<FuncGraph>(expect_j_cnode->input(1))) {
  2245. MS_LOG(EXCEPTION) << "Sens can't find the corresponding graph.";
  2246. }
  2247. auto func_graph = GetValueNode<FuncGraphPtr>(expect_j_cnode->input(1));
  2248. auto loss_node_info = FindLossCNode(func_graph);
  2249. if (loss_node_info.loss_node == nullptr) {
  2250. MS_LOG(WARNING) << "Can not find the loss cnode";
  2251. continue;
  2252. }
  2253. std::pair<CNodePtr, LossNodeInfo> sens_loss_pair = std::make_pair(sens_cnode, loss_node_info);
  2254. sens_loss_pairs.push_back(sens_loss_pair);
  2255. }
  2256. return sens_loss_pairs;
  2257. }
  2258. void ParallelCommunication(const FuncGraphPtr &root, const std::vector<AnfNodePtr> &all_nodes,
  2259. const FuncGraphManagerPtr &manager) {
  2260. MS_EXCEPTION_IF_NULL(root);
  2261. MS_EXCEPTION_IF_NULL(manager);
  2262. TensorRedistribution tensor_redistribution;
  2263. std::vector<std::pair<CNodePtr, LossNodeInfo>> sens_loss_pairs = GetSensLossPairs(root);
  2264. bool has_backward = !sens_loss_pairs.empty();
  2265. // split sens must before inserting the operators.
  2266. for (auto &pair : sens_loss_pairs) {
  2267. // If the shape of grad-sens tensor is not [] or [1], use get tensor slice to handel it.
  2268. // If the type of sens node is not Tensor, it is unsupported now, do nothing default.
  2269. StepSplitSens(pair);
  2270. }
  2271. for (auto &node : all_nodes) {
  2272. MS_EXCEPTION_IF_NULL(node);
  2273. if (node->isa<CNode>()) {
  2274. auto cnode = node->cast<CNodePtr>();
  2275. // the make_tuple is parallel care node, but it may have not operator info
  2276. if (!IsParallelCareNode(cnode) || !cnode->has_user_data<OperatorInfo>()) {
  2277. continue;
  2278. }
  2279. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  2280. MS_EXCEPTION_IF_NULL(distribute_operator);
  2281. // insert forward ops
  2282. InsertForwardOps(distribute_operator, cnode);
  2283. // insert redistribution ops
  2284. StepRedistribution(cnode, distribute_operator, cnode, tensor_redistribution, cnode);
  2285. // insert backward ops
  2286. if (has_backward) {
  2287. BackwardCommunication(distribute_operator, cnode, sens_loss_pairs);
  2288. }
  2289. HandleSpecialNode(distribute_operator, cnode);
  2290. } else if (IsValueNode<Tensor>(node) || IsValueNode<ValueList>(node) || IsValueNode<ValueTuple>(node)) {
  2291. StepSplitTensor(node, manager);
  2292. }
  2293. }
  2294. for (auto &node : all_nodes) {
  2295. MS_EXCEPTION_IF_NULL(node);
  2296. if (node->isa<CNode>()) {
  2297. auto cnode = node->cast<CNodePtr>();
  2298. if (!IsParallelCareNode(cnode) || !cnode->has_user_data<OperatorInfo>()) {
  2299. continue;
  2300. }
  2301. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  2302. MS_EXCEPTION_IF_NULL(distribute_operator);
  2303. // StepReplace
  2304. StepReplace(distribute_operator, cnode);
  2305. }
  2306. }
  2307. }
  2308. namespace {
  2309. void RevertSymbolicKeyInstance(const FuncGraphPtr &root, const AnfNodePtr &node) {
  2310. MS_EXCEPTION_IF_NULL(root);
  2311. MS_EXCEPTION_IF_NULL(node);
  2312. auto symbolic_key = GetValueNode<SymbolicKeyInstancePtr>(node);
  2313. MS_EXCEPTION_IF_NULL(symbolic_key);
  2314. auto all_upstream_node = root->manager()->node_users()[node];
  2315. for (auto &upstream_node : all_upstream_node) {
  2316. FuncGraphPtr fg = upstream_node.first->func_graph();
  2317. if (symbolic_key->node()->isa<Parameter>()) {
  2318. for (auto &param : root->parameters()) {
  2319. if (*param == *symbolic_key->node()) {
  2320. AnfNodePtr reverted_node = root->NewCNode({NewValueNode(prim::kPrimEmbed), param});
  2321. MS_EXCEPTION_IF_NULL(reverted_node);
  2322. MS_LOG(DEBUG) << "before replace " << node->ToString() << " to node " << reverted_node->DebugString();
  2323. (void)fg->manager()->Replace(node, reverted_node);
  2324. MS_LOG(DEBUG) << "revert node " << node->ToString() << " to node " << reverted_node->DebugString();
  2325. }
  2326. }
  2327. }
  2328. }
  2329. }
  2330. } // namespace
  2331. void HandleSymbolicKeyInstance(const FuncGraphPtr &root, const std::vector<AnfNodePtr> &all_nodes) {
  2332. MS_EXCEPTION_IF_NULL(root);
  2333. for (auto &node : all_nodes) {
  2334. // revert back SymbolicKeyInstance to embed() primitive
  2335. if (IsValueNode<SymbolicKeyInstance>(node)) {
  2336. RevertSymbolicKeyInstance(root, node);
  2337. continue;
  2338. }
  2339. }
  2340. }
  2341. std::vector<std::pair<std::string, int64_t>> NodeParameterName(const CNodePtr &node) {
  2342. std::vector<AnfNodePtr> node_inputs{node->inputs()};
  2343. std::vector<std::pair<std::string, int64_t>> param_names;
  2344. for (int64_t i = 0; i < UlongToLong(node_inputs.size()); ++i) {
  2345. auto input = node_inputs[i];
  2346. if (input->isa<Parameter>()) {
  2347. auto input_parameter = input->cast<ParameterPtr>();
  2348. if (input_parameter->has_default() && ParameterRequireGrad(input_parameter)) {
  2349. param_names.push_back({input_parameter->name(), i});
  2350. }
  2351. } else if (input->isa<CNode>()) {
  2352. CNodePtr cnode = input->cast<CNodePtr>();
  2353. if (!IsValueNode<Primitive>(cnode->input(0))) {
  2354. return param_names;
  2355. }
  2356. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  2357. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  2358. if (prim->name() == CAST && cnode->inputs().size() >= 1) {
  2359. auto cast_input = cnode->inputs()[1];
  2360. if (cast_input->isa<Parameter>()) {
  2361. auto cast_input_parameter = cast_input->cast<ParameterPtr>();
  2362. if (cast_input_parameter->has_default() && ParameterRequireGrad(cast_input_parameter)) {
  2363. param_names.push_back({cast_input_parameter->name(), i});
  2364. }
  2365. }
  2366. }
  2367. }
  2368. }
  2369. return param_names;
  2370. }
  2371. void CheckpointStrategy(const std::vector<AnfNodePtr> &all_nodes) {
  2372. StrategyMap stra_map;
  2373. TensorInfoMap tensor_info_map;
  2374. ManualShapeMap manual_shape_map;
  2375. for (auto &node : all_nodes) {
  2376. MS_EXCEPTION_IF_NULL(node);
  2377. auto cnode = node->cast<CNodePtr>();
  2378. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  2379. continue;
  2380. }
  2381. auto param_names = NodeParameterName(cnode);
  2382. if (param_names.empty()) {
  2383. continue;
  2384. }
  2385. string param_name = param_names[0].first;
  2386. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  2387. MS_EXCEPTION_IF_NULL(prim);
  2388. OperatorInfoPtr operator_info = cnode->user_data<OperatorInfo>();
  2389. if (operator_info) {
  2390. if (operator_info->name().find(RESHAPEINFO) != std::string::npos) {
  2391. continue;
  2392. }
  2393. std::vector<TensorInfo> input_tensor_info = operator_info->inputs_tensor_info();
  2394. std::string stratey_key_name = prim->name() + "_" + param_name;
  2395. stra_map[stratey_key_name] = operator_info->strategy();
  2396. for (auto param_name_pair : param_names) {
  2397. if (param_name_pair.second - 1 >= UlongToLong(input_tensor_info.size())) {
  2398. continue;
  2399. }
  2400. tensor_info_map[param_name_pair.first] = input_tensor_info[param_name_pair.second - 1];
  2401. }
  2402. if (operator_info->name().find(EMBEDDING_LOOKUP) != std::string::npos ||
  2403. operator_info->name().find(GATHERV2) != std::string::npos) {
  2404. auto gatherv2_info = std::dynamic_pointer_cast<GatherV2PInfo>(operator_info);
  2405. auto param_split_shapes = gatherv2_info->param_split_shapes();
  2406. auto index_offsets = gatherv2_info->index_offsets();
  2407. if (param_split_shapes.size() != index_offsets.size()) {
  2408. MS_LOG(EXCEPTION) << "In manual split, the param_split_shapes and index_offsets lenght should be same.";
  2409. }
  2410. std::vector<std::pair<int64_t, int64_t>> manual_shape;
  2411. for (int64_t i = 0; i < UlongToLong(param_split_shapes.size()); ++i) {
  2412. manual_shape.push_back({param_split_shapes[i], index_offsets[i]});
  2413. }
  2414. manual_shape_map[param_name] = manual_shape;
  2415. }
  2416. }
  2417. }
  2418. if (StrategyCheckpoint::GetInstance().Save(stra_map, tensor_info_map, &manual_shape_map) != SUCCESS) {
  2419. MS_LOG(EXCEPTION) << "Save strategy checkpoint failed";
  2420. }
  2421. }
  2422. void SetForwardFlag(const std::vector<AnfNodePtr> &all_nodes) {
  2423. for (auto &node : all_nodes) {
  2424. MS_EXCEPTION_IF_NULL(node);
  2425. if (!node->isa<CNode>()) {
  2426. continue;
  2427. }
  2428. auto cnode = node->cast<CNodePtr>();
  2429. if (!IsValueNode<Primitive>(cnode->input(0))) {
  2430. continue;
  2431. }
  2432. // CNode is globally unique.
  2433. MS_LOG(DEBUG) << "Set forward flag " << cnode->DebugString() << ".";
  2434. cnode->set_in_forward_flag(true);
  2435. }
  2436. }
  2437. void SetForwardFlag(const AnfNodeSet &all_nodes) {
  2438. for (auto &node : all_nodes) {
  2439. MS_EXCEPTION_IF_NULL(node);
  2440. if (!node->isa<CNode>()) {
  2441. continue;
  2442. }
  2443. auto cnode = node->cast<CNodePtr>();
  2444. if (!IsValueNode<Primitive>(cnode->input(0))) {
  2445. continue;
  2446. }
  2447. // CNode is globally unique.
  2448. cnode->set_in_forward_flag(true);
  2449. }
  2450. }
  2451. std::set<FuncGraphPtr> ForwardGraph(const FuncGraphPtr &root) {
  2452. MS_EXCEPTION_IF_NULL(root);
  2453. const auto &all_nodes = root->nodes();
  2454. std::set<FuncGraphPtr> graph_set = FindForwardGraphByRootNodes(all_nodes);
  2455. return graph_set;
  2456. }
  2457. std::vector<AnfNodePtr> FindRootForwardCNode(const FuncGraphPtr &graph, const AnfNodeSet &all_nodes) {
  2458. MS_EXCEPTION_IF_NULL(graph);
  2459. std::vector<AnfNodePtr> root_forward_nodes;
  2460. auto loss_cnode = FindLossCNode(graph).loss_node;
  2461. if (loss_cnode == nullptr) {
  2462. MS_LOG(WARNING) << "Can not find the loss cnode";
  2463. return root_forward_nodes;
  2464. }
  2465. auto loss_cnode_id = loss_cnode->UniqueIdThroughCopy();
  2466. for (auto &node : all_nodes) {
  2467. MS_EXCEPTION_IF_NULL(node);
  2468. if (!node->isa<CNode>()) {
  2469. continue;
  2470. }
  2471. auto cnode = node->cast<CNodePtr>();
  2472. auto root_node_id = node->UniqueIdThroughCopy();
  2473. if (loss_cnode_id == root_node_id) {
  2474. root_forward_nodes = DeepLinkedGraphSearch(cnode);
  2475. break;
  2476. }
  2477. }
  2478. return root_forward_nodes;
  2479. }
  2480. void InsertShapeOp(const CNodePtr &node, const AnfNodePtr &pre_node, const FuncGraphPtr &root) {
  2481. // shape op doesn't have params and attrs.
  2482. OperatorParams params;
  2483. OperatorAttrs attrs;
  2484. auto shape_value = GetValueNode(node->input(2))->cast<ValueSequeuePtr>();
  2485. MS_EXCEPTION_IF_NULL(shape_value);
  2486. auto shape = shape_value->value();
  2487. if (shape.empty()) {
  2488. return;
  2489. }
  2490. OperatorArgs args = std::make_pair(attrs, params);
  2491. Operator op = std::make_pair(SHAPE_OP, args);
  2492. InsertNode(op, node, 2, pre_node, root, "shape");
  2493. }
  2494. void HandleRootReshapeAndSaveStrategy(const std::vector<AnfNodePtr> &all_nodes) {
  2495. // If root graph has reshape op. Find the corresponding parameter.
  2496. // Reshape's shape is the shape of the parameter.
  2497. auto executor = pipeline::ExecutorPy::GetInstance();
  2498. for (auto &node : all_nodes) {
  2499. if (!node->isa<CNode>()) {
  2500. continue;
  2501. }
  2502. auto cnode = node->cast<CNodePtr>();
  2503. if (!IsValueNode<Primitive>(cnode->input(0)) || cnode == nullptr) {
  2504. continue;
  2505. }
  2506. if (cnode->in_forward_flag()) {
  2507. // Save strategy in executor
  2508. OperatorInfoPtr op_info = cnode->user_data<OperatorInfo>();
  2509. if (op_info) {
  2510. auto stra_ptr = op_info->strategy();
  2511. if (stra_ptr) {
  2512. auto strategy = stra_ptr->GetInputDim();
  2513. // fullname with scope should be found in step parallel end ir
  2514. executor->SetCNodeStrategy(cnode->fullname_with_scope(), strategy);
  2515. }
  2516. }
  2517. continue;
  2518. }
  2519. auto prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  2520. if (prim->name() != RESHAPE) {
  2521. continue;
  2522. }
  2523. auto root = node->func_graph();
  2524. auto all_dfs_nodes = DeepLinkedGraphSearch(node);
  2525. for (auto r_iter = all_dfs_nodes.rbegin(); r_iter != all_dfs_nodes.rend(); ++r_iter) {
  2526. if ((*r_iter)->isa<Parameter>()) {
  2527. InsertShapeOp(cnode, *r_iter, root);
  2528. break;
  2529. }
  2530. }
  2531. }
  2532. }
  2533. void MarkForwardCNode(const FuncGraphPtr &root) {
  2534. MS_EXCEPTION_IF_NULL(root);
  2535. auto all_nodes = root->nodes();
  2536. auto graph_set = FindForwardGraphByRootNodes(all_nodes);
  2537. if (graph_set.empty()) {
  2538. MS_LOG(INFO) << "Can not find the forward graph, so mark the ops in root graph";
  2539. SetForwardFlag(all_nodes);
  2540. } else {
  2541. for (auto &func_graph : graph_set) {
  2542. MS_LOG(INFO) << "The sub graph size of root is " << root->func_graphs_used().size();
  2543. auto return_node = func_graph->get_return();
  2544. MS_EXCEPTION_IF_NULL(return_node);
  2545. auto all_dfs_nodes = DeepLinkedGraphSearch(return_node);
  2546. SetForwardFlag(all_dfs_nodes);
  2547. auto root_forward_nodes = FindRootForwardCNode(func_graph, all_nodes);
  2548. if (root_forward_nodes.empty()) {
  2549. continue;
  2550. }
  2551. // Mark forward flag for the nodes in root graph.
  2552. SetForwardFlag(root_forward_nodes);
  2553. }
  2554. }
  2555. }
  2556. Status ParallelInit() {
  2557. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  2558. int64_t device_num = ParallelContext::GetInstance()->device_num();
  2559. int64_t global_rank = ParallelContext::GetInstance()->global_rank();
  2560. int32_t split_stage_num = ParallelContext::GetInstance()->pipeline_stage_split_num();
  2561. std::string parallel_mode = ParallelContext::GetInstance()->parallel_mode();
  2562. auto ms_context = MsContext::GetInstance();
  2563. MS_EXCEPTION_IF_NULL(ms_context);
  2564. std::string backend = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  2565. std::string world_group;
  2566. std::string communication_backend;
  2567. if (backend == kAscendDevice || backend == kDavinciDevice) {
  2568. world_group = HCCL_WORLD_GROUP;
  2569. communication_backend = HCCL_BACKEND;
  2570. } else if (backend == kGPUDevice) {
  2571. world_group = NCCL_WORLD_GROUP;
  2572. communication_backend = NCCL_BACKEND;
  2573. } else {
  2574. MS_LOG(ERROR) << "Invalid communication backend: " << backend;
  2575. return FAILED;
  2576. }
  2577. if (split_stage_num <= 0) {
  2578. MS_LOG(ERROR) << "Invalid stage num " << split_stage_num << ", expected a positive stage number";
  2579. return FAILED;
  2580. }
  2581. uint32_t world_rank_size = 0;
  2582. if (!ParallelContext::GetInstance()->device_num_is_set()) {
  2583. if (!CommManager::GetInstance().GetRankSize(world_group, &world_rank_size)) {
  2584. MS_LOG(EXCEPTION) << "Get rank size failed";
  2585. }
  2586. device_num = UintToInt(world_rank_size);
  2587. MS_LOG(INFO) << "Get device num from communication model, the device num is " << device_num;
  2588. }
  2589. uint32_t rank_id = 0;
  2590. if (!ParallelContext::GetInstance()->global_rank_is_set()) {
  2591. if (!CommManager::GetInstance().GetRankID(world_group, &rank_id)) {
  2592. MS_LOG(EXCEPTION) << "Get rank id failed";
  2593. }
  2594. global_rank = UintToInt(rank_id);
  2595. MS_LOG(INFO) << "Get global rank from communication model, the global rank is " << global_rank;
  2596. }
  2597. if ((device_num <= 0) || (device_num > MAX_DEVICE_NUM)) {
  2598. MS_LOG(ERROR) << "Invalid device num " << device_num;
  2599. return FAILED;
  2600. }
  2601. // the device_num maybe get from communication interface
  2602. if (device_num % split_stage_num != 0) {
  2603. MS_LOG(ERROR) << "Device num " << device_num << " can't be divided by stage num " << split_stage_num;
  2604. return FAILED;
  2605. }
  2606. if ((global_rank < 0) || (global_rank >= device_num)) {
  2607. MS_LOG(ERROR) << "Global rank " << global_rank << " is out of range, the device num is " << device_num;
  2608. return FAILED;
  2609. }
  2610. std::vector<int64_t> stages;
  2611. for (int i = 0; i < split_stage_num; i++) {
  2612. stages.push_back(device_num / split_stage_num);
  2613. }
  2614. if ((split_stage_num > 1) && (parallel_mode != SEMI_AUTO_PARALLEL)) {
  2615. MS_LOG(ERROR) << "To enable the pipeline parallel, please set the parallel mode to " << SEMI_AUTO_PARALLEL;
  2616. return FAILED;
  2617. }
  2618. if (!InitDevice(device_num, global_rank, communication_backend, stages)) {
  2619. MS_LOG(ERROR) << "Init device failed";
  2620. return FAILED;
  2621. }
  2622. MS_LOG(INFO) << "The parallel context: dev num: " << device_num << ", global rank: " << global_rank
  2623. << ", backend: " << backend << ", gradients_mean: " << ParallelContext::GetInstance()->gradients_mean()
  2624. << ", gradient_fp32_sync: " << ParallelContext::GetInstance()->gradient_fp32_sync();
  2625. return SUCCESS;
  2626. }
  2627. void HandleForwardMakeTupleAndMakeList(const std::vector<AnfNodePtr> &all_nodes) {
  2628. for (auto &node : all_nodes) {
  2629. if (!AnfNodeIsPrimitive(node, MAKE_TUPLE) && !AnfNodeIsPrimitive(node, MAKE_LIST)) {
  2630. continue;
  2631. }
  2632. auto cnode = node->cast<CNodePtr>();
  2633. MS_EXCEPTION_IF_NULL(cnode);
  2634. if (!cnode->in_forward_flag()) {
  2635. continue;
  2636. }
  2637. FuncGraphManagerPtr manager = cnode->func_graph()->manager();
  2638. MS_EXCEPTION_IF_NULL(manager);
  2639. std::string op_type = AnfNodeIsPrimitive(node, MAKE_TUPLE) ? MAKE_TUPLE : MAKE_LIST;
  2640. auto make_tuple_list_user = manager->node_users()[cnode];
  2641. if (make_tuple_list_user.size() != 1) {
  2642. MS_LOG(EXCEPTION) << "Now the " << op_type << "'s user must be 1, but got " << make_tuple_list_user.size();
  2643. }
  2644. CNodePtr make_tuple_list_next_cnode = make_tuple_list_user.pop().first->cast<CNodePtr>();
  2645. MS_EXCEPTION_IF_NULL(make_tuple_list_next_cnode);
  2646. std::string make_tuple__list_user_prim_name = GetPrimName(make_tuple_list_next_cnode);
  2647. if (!IsParallelCareNode(make_tuple_list_next_cnode)) {
  2648. MS_LOG(INFO) << "The " << op_type << "'s user is " << make_tuple__list_user_prim_name
  2649. << ", no need to set operator info";
  2650. continue;
  2651. }
  2652. if (make_tuple_list_next_cnode->inputs().size() != 2) {
  2653. MS_LOG(EXCEPTION) << "Now the " << op_type << "'s user only support 1 input, but got "
  2654. << make_tuple_list_next_cnode->inputs().size() - 1;
  2655. }
  2656. MS_LOG(INFO) << "Set the " << op_type << "'s operator info, and the op name is " << make_tuple__list_user_prim_name;
  2657. OperatorInfoPtr op_info = GetDistributeOperator(make_tuple_list_next_cnode);
  2658. MS_EXCEPTION_IF_NULL(op_info);
  2659. cnode->set_user_data<OperatorInfo>(op_info);
  2660. }
  2661. }
  2662. RefKeyPair CNodeWithRefKeys(const AnfNodePtr &cnode) {
  2663. MS_EXCEPTION_IF_NULL(cnode);
  2664. std::vector<AnfNodePtr> refkeys;
  2665. if (cnode->isa<CNode>()) {
  2666. auto cnode_ptr = cnode->cast<CNodePtr>();
  2667. auto inputs = cnode_ptr->inputs();
  2668. for (auto &one_input : inputs) {
  2669. if (IsValueNode<RefKey>(one_input)) {
  2670. refkeys.push_back(one_input);
  2671. }
  2672. }
  2673. if (refkeys.size() >= 1) {
  2674. return std::make_pair(cnode, refkeys);
  2675. }
  2676. }
  2677. return {nullptr, refkeys};
  2678. }
  2679. ParameterUsersInfo FindParameterNodeUsers(const AnfNodePtr &node, bool (*IsCareNode)(const CNodePtr &)) {
  2680. // In this case, node is a Parameter
  2681. ParameterUsersInfo parameter_user_info;
  2682. MS_EXCEPTION_IF_NULL(node->func_graph());
  2683. MS_EXCEPTION_IF_NULL(node->func_graph()->manager());
  2684. auto candidate_set = node->func_graph()->manager()->node_users()[node];
  2685. for (auto &candidate : candidate_set) {
  2686. auto candidate_node = candidate.first;
  2687. auto c = candidate_node->cast<CNodePtr>();
  2688. if (c == nullptr || !c->has_user_data<OperatorInfo>()) {
  2689. continue;
  2690. }
  2691. (void)parameter_user_info.second.second.insert(candidate);
  2692. }
  2693. parameter_user_info.first = node->cast<ParameterPtr>()->name();
  2694. parameter_user_info.second.first = node;
  2695. return parameter_user_info;
  2696. }
  2697. ParameterUsersInfo FindRefKeyNodeUsers(const RefKeyPair &ref_key_pair, bool (*IsCareNode)(const CNodePtr &)) {
  2698. // Dealing with the RefKey case
  2699. ParameterUsersInfo parameter_user_info;
  2700. auto refkeys = ref_key_pair.second;
  2701. auto cnode = ref_key_pair.first;
  2702. auto cnode_ptr = cnode->cast<CNodePtr>();
  2703. if ((cnode_ptr == nullptr) || !IsValueNode<Primitive>(cnode_ptr->input(0)) || !IsCareNode(cnode_ptr)) {
  2704. return parameter_user_info;
  2705. }
  2706. if (refkeys.size() > 1) {
  2707. MS_LOG(EXCEPTION) << "CNode: " << cnode->fullname_with_scope() << "'s inputs have more than 1 RefKeys";
  2708. }
  2709. MS_EXCEPTION_IF_NULL(cnode->func_graph());
  2710. auto cnode_func_graph = cnode->func_graph();
  2711. MS_EXCEPTION_IF_NULL(cnode->func_graph()->manager());
  2712. // Find the RefKey being used
  2713. auto candidate_set_by_refkey = cnode_func_graph->manager()->node_users()[refkeys[0]];
  2714. for (auto &candidate : candidate_set_by_refkey) {
  2715. auto candidate_node = candidate.first;
  2716. auto c = candidate_node->cast<CNodePtr>();
  2717. if ((c == nullptr) || !IsValueNode<Primitive>(c->input(0)) || !IsCareNode(c)) {
  2718. continue;
  2719. }
  2720. parameter_user_info.second.second.add(candidate);
  2721. }
  2722. // Find the corresponding Parameter being used
  2723. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(refkeys[0], cnode_func_graph);
  2724. if (parameters.size() != 1) {
  2725. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  2726. }
  2727. parameter_user_info.first = parameters[0]->cast<ParameterPtr>()->name();
  2728. parameter_user_info.second.first = parameters[0];
  2729. auto candidate_set_by_para = cnode_func_graph->manager()->node_users()[parameters[0]];
  2730. for (auto &candidate : candidate_set_by_para) {
  2731. auto candidate_node = candidate.first;
  2732. auto c = candidate_node->cast<CNodePtr>();
  2733. if ((c == nullptr) || !IsValueNode<Primitive>(c->input(0)) || !IsCareNode(c)) {
  2734. continue;
  2735. }
  2736. (void)parameter_user_info.second.second.insert(candidate);
  2737. }
  2738. return parameter_user_info;
  2739. }
  2740. ParameterUsersInfo FindParameterUsers(const AnfNodePtr &node, bool (*IsCareNode)(const CNodePtr &)) {
  2741. ParameterUsersInfo parameter_users_info;
  2742. auto cnode_with_refkeys = CNodeWithRefKeys(node);
  2743. if (cnode_with_refkeys.first != nullptr) {
  2744. // the node is a ref key node
  2745. return FindRefKeyNodeUsers(cnode_with_refkeys, IsCareNode);
  2746. } else if (node->isa<Parameter>()) {
  2747. // the node is a parameter node
  2748. return FindParameterNodeUsers(node, IsCareNode);
  2749. }
  2750. return parameter_users_info;
  2751. }
  2752. Shape ParameterSliceShape(const std::pair<AnfNodePtr, int64_t> &param_info) {
  2753. auto user_cnode = param_info.first->cast<CNodePtr>();
  2754. MS_EXCEPTION_IF_NULL(user_cnode);
  2755. auto user_input_index = param_info.second;
  2756. OperatorInfoPtr op_info = user_cnode->user_data<OperatorInfo>();
  2757. MS_EXCEPTION_IF_NULL(op_info);
  2758. size_t input_tensor_info_size = op_info->inputs_tensor_info().size();
  2759. if (SizeToLong(input_tensor_info_size) <= user_input_index - 1) {
  2760. MS_LOG(EXCEPTION) << op_info->name() << ": the size of inputs tensor info is " << input_tensor_info_size
  2761. << ", but the index is " << user_input_index - 1;
  2762. }
  2763. TensorInfo tensor_info = op_info->inputs_tensor_info()[user_input_index - 1];
  2764. MS_LOG(DEBUG) << "The op name is " << op_info->name() << ", the parameter index is " << user_input_index - 1
  2765. << ", the slice shape is " << ShapeToString(tensor_info.slice_shape()) << ", the origin shape is "
  2766. << ShapeToString(tensor_info.shape());
  2767. return tensor_info.slice_shape();
  2768. }
  2769. void CheckParameterSplit(const std::vector<AnfNodePtr> &all_nodes) {
  2770. for (auto &node : all_nodes) {
  2771. ParameterUsersInfo parameter_users_info = FindParameterUsers(node, IsParallelCareNode);
  2772. auto users_set = parameter_users_info.second.second;
  2773. if (users_set.size() <= 1) {
  2774. continue;
  2775. }
  2776. auto parameter_name = parameter_users_info.first;
  2777. MS_LOG(INFO) << "The parameter: " << parameter_name << " has " << users_set.size() << " users";
  2778. auto first_user = users_set.pop();
  2779. Shape first_user_slice_shape = ParameterSliceShape(first_user);
  2780. for (auto &user : users_set) {
  2781. Shape user_slice_shape = ParameterSliceShape(user);
  2782. if (first_user_slice_shape != user_slice_shape) {
  2783. MS_LOG(EXCEPTION) << "The parameter: " << parameter_name
  2784. << " has multiple users, but the split strategies are different";
  2785. }
  2786. }
  2787. }
  2788. }
  2789. bool IsUsedParameter(const FuncGraphPtr &graph, const AnfNodePtr &parameter) {
  2790. MS_EXCEPTION_IF_NULL(graph);
  2791. MS_EXCEPTION_IF_NULL(parameter);
  2792. auto manager = graph->manager();
  2793. auto node_users = manager->node_users()[parameter];
  2794. if (node_users.empty()) {
  2795. return false;
  2796. }
  2797. for (auto node_user : node_users) {
  2798. auto use_node = node_user.first->cast<CNodePtr>();
  2799. if (IsValueNode<FuncGraph>(use_node->input(0))) {
  2800. auto graph_sub = GetValueNode<FuncGraphPtr>(use_node->input(0));
  2801. auto parameters = graph_sub->parameters();
  2802. auto parameter_sub = parameters[node_user.second - 1];
  2803. return IsUsedParameter(graph_sub, parameter_sub);
  2804. }
  2805. if (use_node->input(0)->isa<CNode>()) {
  2806. auto cnode = use_node->input(0)->cast<CNodePtr>();
  2807. if (!IsSomePrimitive(cnode, J) || !IsValueNode<FuncGraph>(cnode->input(1))) {
  2808. return true;
  2809. }
  2810. auto graph_sub = GetValueNode<FuncGraphPtr>(cnode->input(1));
  2811. auto parameters = graph_sub->parameters();
  2812. auto parameter_sub = parameters[node_user.second - 1];
  2813. return IsUsedParameter(graph_sub, parameter_sub);
  2814. }
  2815. return true;
  2816. }
  2817. return true;
  2818. }
  2819. static void HandleNoUsedParameter(const FuncGraphPtr &root) {
  2820. MS_EXCEPTION_IF_NULL(root);
  2821. bool full_batch = ParallelContext::GetInstance()->full_batch();
  2822. if (full_batch) {
  2823. return;
  2824. }
  2825. auto dev_num = g_device_manager->stage_device_num();
  2826. auto parameters = root->parameters();
  2827. for (auto &parameter : parameters) {
  2828. if (IsUsedParameter(root, parameter)) {
  2829. continue;
  2830. }
  2831. auto parameter_shape = GetNodeShape(parameter);
  2832. if (parameter_shape.empty()) {
  2833. continue;
  2834. }
  2835. Shape slice_shape = parameter_shape[0];
  2836. if (slice_shape.empty()) {
  2837. continue;
  2838. }
  2839. slice_shape[0] = slice_shape[0] / dev_num;
  2840. auto slice_shape_ptr = std::make_shared<abstract::Shape>(slice_shape);
  2841. auto abstract = parameter->abstract();
  2842. MS_EXCEPTION_IF_NULL(abstract);
  2843. auto abstract_cloned = abstract->Clone();
  2844. MS_EXCEPTION_IF_NULL(abstract_cloned);
  2845. abstract_cloned->set_shape(slice_shape_ptr);
  2846. parameter->set_abstract(abstract_cloned);
  2847. }
  2848. }
  2849. bool StepParallel(const FuncGraphPtr &root, const opt::OptimizerPtr &optimizer) {
  2850. MS_EXCEPTION_IF_NULL(root);
  2851. MS_EXCEPTION_IF_NULL(optimizer);
  2852. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  2853. std::string parallel_mode = ParallelContext::GetInstance()->parallel_mode();
  2854. // assume no change to graph
  2855. bool changes = false;
  2856. // control whether use model_parallel mode
  2857. if (!root->has_flag(AUTO_PARALLEL) || ((parallel_mode != AUTO_PARALLEL) && (parallel_mode != SEMI_AUTO_PARALLEL)) ||
  2858. (root->has_flag(SEMI_AUTO_PARALLEL_RUN_ONCE_ONLY))) {
  2859. if (!root->has_flag(CHECK_SET_STRATEGY_VALID_ONCE_ONLY)) {
  2860. if (HasStrategy(root)) {
  2861. MS_LOG(INFO) << "Strategies ignored in " << parallel_mode
  2862. << ", set_strategy() only valid in [semi_]auto_parallel.";
  2863. }
  2864. root->set_flag(CHECK_SET_STRATEGY_VALID_ONCE_ONLY, true);
  2865. }
  2866. return changes;
  2867. }
  2868. struct timeval start_time, end_time;
  2869. (void)gettimeofday(&start_time, nullptr);
  2870. MS_LOG(INFO) << "Now entering step parallel";
  2871. DumpGraph(root, std::string(STEP_PARALLEL_BEGIN));
  2872. pipeline::ResourceBasePtr res = optimizer->resource();
  2873. MS_EXCEPTION_IF_NULL(res);
  2874. FuncGraphManagerPtr manager = res->manager();
  2875. MS_EXCEPTION_IF_NULL(manager);
  2876. AnfNodePtr ret = root->get_return();
  2877. MS_EXCEPTION_IF_NULL(ret);
  2878. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  2879. std::reverse(all_nodes.begin(), all_nodes.end());
  2880. if (parallel_mode != AUTO_PARALLEL) {
  2881. TOTAL_OPS = 0;
  2882. if (ParallelInit() != SUCCESS) {
  2883. MS_LOG(EXCEPTION) << "Parallel init failed";
  2884. }
  2885. // mark the forward cnodes, parallel only care these nodes
  2886. MarkForwardCNode(root);
  2887. if (FindCommunicationOp(all_nodes)) {
  2888. MS_LOG(EXCEPTION) << "The graph contain communication op";
  2889. }
  2890. // extract shape and strategy, set operator_info
  2891. ExtractInformation(all_nodes, root->has_flag(TRAINING));
  2892. ReshapeInit(all_nodes);
  2893. }
  2894. HandleRootReshapeAndSaveStrategy(all_nodes);
  2895. HandleForwardMakeTupleAndMakeList(all_nodes);
  2896. // if the input or parameter has multiple users, check whether its split strategies are consistent.
  2897. CheckParameterSplit(all_nodes);
  2898. // save strategy as checkpoint for multi-train
  2899. if (StrategyCheckpoint::GetInstance().SaveCheckPointOn()) {
  2900. CheckpointStrategy(all_nodes);
  2901. }
  2902. HandleSymbolicKeyInstance(root, all_nodes);
  2903. // cover Parallel shape
  2904. CoverSliceShape(root);
  2905. // handle input is not used
  2906. HandleNoUsedParameter(root);
  2907. // set the shape for optimizer's clone tensor
  2908. SetClonedTensorShapeForOptimizer(root);
  2909. // ForwardCommunication BackwardCommunication TensorRedistribution
  2910. ParallelCommunication(root, all_nodes, manager);
  2911. DumpGraph(root, std::string(STEP_PARALLEL_END));
  2912. // step parallel only run once
  2913. root->set_flag(SEMI_AUTO_PARALLEL_RUN_ONCE_ONLY, true);
  2914. res->results()[pipeline::kStepParallelGraph] = root;
  2915. // in auto parallel mode, no need to check if stategies set
  2916. root->set_flag(CHECK_SET_STRATEGY_VALID_ONCE_ONLY, true);
  2917. (void)gettimeofday(&end_time, nullptr);
  2918. uint64_t time = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec);
  2919. time += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec);
  2920. MS_LOG(INFO) << "Now leaving step parallel, used time: " << time << " us";
  2921. return changes;
  2922. }
  2923. // Needed by rec_parser
  2924. std::vector<std::string> ExtractInputsTensorName(const CNodePtr &node) {
  2925. std::vector<std::string> name_inputs;
  2926. std::vector<AnfNodePtr> all_inputs = node->inputs();
  2927. std::vector<AnfNodePtr> node_inputs{all_inputs.begin() + 1, all_inputs.end()};
  2928. std::string node_id = node->UniqueId();
  2929. name_inputs.push_back(node_id);
  2930. for (auto &input : node_inputs) {
  2931. std::string name = input->UniqueId();
  2932. name_inputs.push_back(name);
  2933. }
  2934. return name_inputs;
  2935. }
  2936. } // namespace parallel
  2937. } // namespace mindspore