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