You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

step_parallel.cc 130 kB

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