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