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

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