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

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