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

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378
  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 "ir/tensor.h"
  27. #include "ir/param_value.h"
  28. #include "frontend/operator/ops.h"
  29. #include "frontend/optimizer/optimizer.h"
  30. #include "frontend/parallel/auto_parallel/graph_costmodel.h"
  31. #include "frontend/parallel/context.h"
  32. #include "frontend/parallel/device_manager.h"
  33. #include "frontend/parallel/dynamic_creator.h"
  34. #include "frontend/parallel/graph_util/generate_graph.h"
  35. #include "frontend/parallel/graph_util/graph_info.h"
  36. #include "frontend/parallel/graph_util/node_info.h"
  37. #include "frontend/parallel/node_check.h"
  38. #include "frontend/parallel/ops_info/matmul_info.h"
  39. #include "frontend/parallel/strategy_checkpoint/parallel_strategy_checkpoint.h"
  40. #include "utils/comm_manager.h"
  41. #include "utils/symbolic.h"
  42. #include "pipeline/jit/static_analysis/prim.h"
  43. using mindspore::tensor::Tensor;
  44. namespace mindspore {
  45. namespace parallel {
  46. static const std::set<std::string> COMMUNICATION_OPS = {ALL_REDUCE, ALL_GATHER, ALL_TO_ALL, REDUCE_SCATTER};
  47. static const std::set<std::string> INVALID_LOSS_OPS = {GET_NEXT, VIRTUALLOSS};
  48. // g_RefMap, for CNode B input i is a RefKey[Parameter C],
  49. // it will be one item in map with key: C, and value: (B, i)
  50. static std::map<AnfNodePtr, std::pair<AnfNodePtr, int>> g_RefMap;
  51. void SetCommunicationOpGroupLabel(std::vector<AnfNodePtr> new_node_input) {
  52. if (new_node_input.empty()) {
  53. return;
  54. }
  55. ValueNodePtr prim_anf_node = new_node_input[0]->cast<ValueNodePtr>();
  56. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  57. MS_EXCEPTION_IF_NULL(prim);
  58. auto attrs = prim->attrs();
  59. auto iter = attrs.find(GROUP);
  60. if (iter != attrs.end()) {
  61. auto value = iter->second;
  62. MS_EXCEPTION_IF_NULL(value);
  63. if (value->isa<StringImm>()) {
  64. std::string hash_name = value->cast<StringImmPtr>()->value();
  65. MS_EXCEPTION_IF_NULL(g_device_manager);
  66. std::string rank_list_name = g_device_manager->FindRankListNameByHashName(hash_name);
  67. (void)prim->AddAttr(GROUP_RANKS, MakeValue(rank_list_name));
  68. }
  69. }
  70. }
  71. std::vector<AnfNodePtr> CreateInput(const Operator &op, const AnfNodePtr &node, const std::string &instance_name) {
  72. MS_EXCEPTION_IF_NULL(node);
  73. OperatorArgs arg_forward = op.second;
  74. ValuePtr pyop_instance = CreatOpInstance(arg_forward.first, op.first, instance_name);
  75. MS_EXCEPTION_IF_NULL(pyop_instance);
  76. OperatorParams params = arg_forward.second;
  77. std::vector<AnfNodePtr> new_node_input = {NewValueNode(pyop_instance), node};
  78. if (!params.empty()) {
  79. for (auto &param : params) {
  80. AnfNodePtr val = NewValueNode(param.first.second);
  81. MS_EXCEPTION_IF_NULL(val);
  82. int32_t position = param.second;
  83. (void)new_node_input.insert(new_node_input.begin() + position, val);
  84. }
  85. }
  86. // if the op have 'group' attr, set the rank list name for the op
  87. SetCommunicationOpGroupLabel(new_node_input);
  88. return new_node_input;
  89. }
  90. void InsertNode(const Operator &op, const CNodePtr &node, size_t index, const AnfNodePtr &pre_node,
  91. const FuncGraphPtr &func_graph, const std::string &instance_name) {
  92. // insert new node before the node
  93. FuncGraphManagerPtr manager = func_graph->manager();
  94. MS_EXCEPTION_IF_NULL(manager);
  95. ScopePtr scope = node->scope();
  96. MS_EXCEPTION_IF_NULL(scope);
  97. std::vector<AnfNodePtr> node_input = CreateInput(op, pre_node, instance_name);
  98. CNodePtr new_node = func_graph->NewCNode(node_input);
  99. MS_EXCEPTION_IF_NULL(new_node);
  100. if (instance_name.find(SPLIT_SENS) == std::string::npos) {
  101. new_node->set_in_forward_flag(true); // mark forward flag
  102. }
  103. auto new_node_value = node_input[0]->cast<ValueNodePtr>();
  104. MS_EXCEPTION_IF_NULL(new_node_value);
  105. PrimitivePtr new_node_prim = new_node_value->value()->cast<PrimitivePtr>();
  106. new_node_prim->set_instance_name(instance_name);
  107. new_node_prim->set_attr("keep_value_node_input", MakeValue(true));
  108. new_node->set_scope(scope);
  109. node_input[0]->set_scope(scope);
  110. manager->SetEdge(node, SizeToInt(index), new_node);
  111. }
  112. std::string CreateInstanceName(const CNodePtr &node, size_t index) {
  113. MS_EXCEPTION_IF_NULL(node);
  114. if (!IsValueNode<Primitive>(node->input(0))) {
  115. MS_LOG(EXCEPTION) << "CreateInstanceName: " << node->ToString() << " doesn't have primitive";
  116. }
  117. std::string name_base = node->fullname_with_scope();
  118. std::string name = name_base + "_" + std::to_string(index);
  119. std::string instance_name = HashInstanceName(name);
  120. return instance_name;
  121. }
  122. void ForwardCommunication(OperatorVector forward_op, const CNodePtr &node) {
  123. MS_EXCEPTION_IF_NULL(node);
  124. // step1:get graph manager distribute_operator
  125. FuncGraphPtr func_graph = node->func_graph();
  126. MS_EXCEPTION_IF_NULL(func_graph);
  127. FuncGraphManagerPtr manager = func_graph->manager();
  128. MS_EXCEPTION_IF_NULL(manager);
  129. auto uses_set = manager->node_users()[node];
  130. CNodePtr node_to_insert = node;
  131. for (auto &uses_pair : uses_set) {
  132. auto uses_cnode = uses_pair.first->cast<CNodePtr>();
  133. MS_EXCEPTION_IF_NULL(uses_cnode);
  134. if (!IsValueNode<Primitive>(uses_cnode->input(0))) {
  135. break;
  136. }
  137. PrimitivePtr value_node_prim = GetValueNode<PrimitivePtr>(uses_cnode->input(0));
  138. MS_EXCEPTION_IF_NULL(value_node_prim);
  139. if (value_node_prim->name() == TUPLE_GETITEM) {
  140. if (uses_set.size() > 1) {
  141. MS_LOG(EXCEPTION) << "Now only support one output, but got " << uses_set.size();
  142. }
  143. node_to_insert = uses_cnode;
  144. }
  145. }
  146. MS_EXCEPTION_IF_NULL(node_to_insert);
  147. std::reverse(forward_op.begin(), forward_op.end());
  148. // step2:traverse op_list and insert node
  149. for (size_t index = 0; index < forward_op.size(); ++index) {
  150. std::string instance_name_base = FORWARD_OP;
  151. std::string instance_name = instance_name_base + "_" + CreateInstanceName(node, index);
  152. std::vector<AnfNodePtr> forward_input = CreateInput(forward_op[index], node_to_insert, instance_name);
  153. CNodePtr forward_node = func_graph->NewCNode(forward_input); // using NewCNode to creat anfnode
  154. MS_EXCEPTION_IF_NULL(forward_node);
  155. ScopePtr scope = node->scope();
  156. MS_EXCEPTION_IF_NULL(scope);
  157. forward_node->set_scope(scope);
  158. forward_node->set_in_forward_flag(true);
  159. forward_input[0]->set_scope(scope);
  160. (void)manager->Replace(node_to_insert, forward_node); // using Replace function to insert node
  161. }
  162. }
  163. CNodePtr InsertMakeTuple(const AnfNodePtr &prev, uint32_t num, const FuncGraphPtr &func_graph) {
  164. MS_EXCEPTION_IF_NULL(prev);
  165. MS_EXCEPTION_IF_NULL(func_graph);
  166. std::vector<AnfNodePtr> make_tuple_inputs;
  167. make_tuple_inputs.push_back(NewValueNode(prim::kPrimMakeTuple));
  168. for (uint32_t i = 0; i < num; i++) {
  169. std::vector<AnfNodePtr> tuple_get_item_inputs{NewValueNode(prim::kPrimTupleGetItem), prev,
  170. CreatInt32Imm(UintToInt(i))};
  171. auto tuple_get_item = func_graph->NewCNode(tuple_get_item_inputs);
  172. MS_EXCEPTION_IF_NULL(tuple_get_item);
  173. make_tuple_inputs.push_back(tuple_get_item);
  174. }
  175. auto make_tuple = func_graph->NewCNode(make_tuple_inputs);
  176. MS_EXCEPTION_IF_NULL(make_tuple);
  177. FuncGraphManagerPtr manager = func_graph->manager();
  178. MS_EXCEPTION_IF_NULL(manager);
  179. (void)manager->Replace(prev, make_tuple);
  180. return make_tuple;
  181. }
  182. void InsertRedistribution(const RedistributionOpListPtr &redistribution_oplist_ptr, const CNodePtr &node,
  183. const FuncGraphPtr &func_graph, int pos, const CNodePtr &pre_node) {
  184. MS_EXCEPTION_IF_NULL(node);
  185. MS_EXCEPTION_IF_NULL(pre_node);
  186. MS_EXCEPTION_IF_NULL(func_graph);
  187. FuncGraphManagerPtr manager = func_graph->manager();
  188. MS_EXCEPTION_IF_NULL(manager);
  189. if ((redistribution_oplist_ptr->first).size() != (redistribution_oplist_ptr->second).size()) {
  190. MS_LOG(EXCEPTION) << "size of OperatorVector and OutPutInfoVector must be the same!";
  191. }
  192. for (size_t index = 0; index < (redistribution_oplist_ptr->first).size(); ++index) {
  193. if (pos >= SizeToInt(node->inputs().size())) {
  194. MS_LOG(EXCEPTION) << "InsertRedistribution:pos can't be larger than node's inputs'size";
  195. }
  196. // Creat new node
  197. AnfNodePtr target_node = node->input(IntToSize(pos));
  198. MS_EXCEPTION_IF_NULL(target_node);
  199. // Creat instance_name
  200. auto op = (redistribution_oplist_ptr->first)[index];
  201. std::string op_name = (redistribution_oplist_ptr->first)[index].first;
  202. std::string instance_name_base = REDISTRIBUTION_OP;
  203. std::string instance_name = instance_name_base + "_" + CreateInstanceName(pre_node, index) + op_name;
  204. InsertNode(op, node, IntToSize(pos), target_node, func_graph, instance_name);
  205. if ((redistribution_oplist_ptr->second)[index].first) {
  206. target_node = node->input(IntToSize(pos));
  207. MS_EXCEPTION_IF_NULL(target_node);
  208. (void)InsertMakeTuple(target_node, (redistribution_oplist_ptr->second)[index].second, func_graph);
  209. }
  210. }
  211. }
  212. void InsertGetTensorSliceOp(const Operator &op, const CNodePtr &node, const FuncGraphPtr &func_graph, int pos,
  213. const std::string &instance_name) {
  214. if (func_graph == nullptr) {
  215. MS_LOG(EXCEPTION) << "InsertGetTensorSliceOp: the graph is null, the instance name is " << instance_name;
  216. }
  217. FuncGraphManagerPtr manager = func_graph->manager();
  218. MS_EXCEPTION_IF_NULL(manager);
  219. if (pos >= SizeToInt(node->inputs().size())) {
  220. MS_LOG(EXCEPTION) << "InsertGetTensorSliceOp: pos can't be larger than node's inputs'size, the instance name is "
  221. << instance_name;
  222. }
  223. // Creat new node
  224. AnfNodePtr pre_node = node->input(IntToSize(pos));
  225. MS_EXCEPTION_IF_NULL(pre_node);
  226. InsertNode(op, node, IntToSize(pos), pre_node, func_graph, instance_name);
  227. }
  228. TensorLayout GetTensorInLayout(const CNodePtr &middle_node, const PrimitivePtr &middle_prim,
  229. const OperatorInfoPtr &distribute_operator) {
  230. TensorInfo tensorinfo_in;
  231. if (middle_prim->name() == TUPLE_GETITEM) {
  232. auto value_node = middle_node->input(2)->cast<ValueNodePtr>();
  233. MS_EXCEPTION_IF_NULL(value_node);
  234. size_t index_s = IntToSize(GetValue<int>(value_node->value()));
  235. if (index_s >= distribute_operator->outputs_tensor_info().size()) {
  236. MS_LOG(EXCEPTION) << "The index out of range, index: " << index_s
  237. << ", vector size: " << distribute_operator->outputs_tensor_info().size();
  238. }
  239. tensorinfo_in = distribute_operator->outputs_tensor_info()[index_s];
  240. } else {
  241. if (distribute_operator->outputs_tensor_info().empty()) {
  242. MS_LOG(EXCEPTION) << "The outputs tensor info is empty";
  243. }
  244. tensorinfo_in = distribute_operator->outputs_tensor_info()[0];
  245. }
  246. return tensorinfo_in.tensor_layout();
  247. }
  248. OperatorInfoPtr GetDistributeOperator(const CNodePtr &node) {
  249. MS_EXCEPTION_IF_NULL(node);
  250. if (!IsParallelCareNode(node)) {
  251. return nullptr;
  252. }
  253. OperatorInfoPtr distribute_operator = node->GetUserData<OperatorInfo>();
  254. if (distribute_operator == nullptr) {
  255. MS_LOG(EXCEPTION) << "GetDistributeOperator:distribute_operator is nullptr";
  256. }
  257. return distribute_operator;
  258. }
  259. void Redistribution(const std::pair<AnfNodePtr, int> &node_pair, const OperatorInfoPtr &distribute_operator,
  260. const CNodePtr &middle_node, int index, TensorRedistribution tensor_redistribution,
  261. const CNodePtr &pre_node) {
  262. FuncGraphPtr func_graph = middle_node->func_graph();
  263. if (func_graph == nullptr) {
  264. MS_LOG(EXCEPTION) << "Redistribution:get graph failed";
  265. }
  266. CNodePtr next_node = node_pair.first->cast<CNodePtr>();
  267. MS_EXCEPTION_IF_NULL(next_node);
  268. auto middle_value = middle_node->input(0)->cast<ValueNodePtr>();
  269. MS_EXCEPTION_IF_NULL(middle_value);
  270. PrimitivePtr middle_prim = middle_value->value()->cast<PrimitivePtr>();
  271. MS_EXCEPTION_IF_NULL(middle_prim);
  272. OperatorInfoPtr next_distribute_operator = GetDistributeOperator(next_node);
  273. if (next_distribute_operator == nullptr) {
  274. MS_LOG(EXCEPTION) << "Failure: " << next_node->ToString() << " GetDistributeOperator failed";
  275. }
  276. RankList dev_list = distribute_operator->global_device_list();
  277. std::string next_prim_name = GetValueNode<PrimitivePtr>(next_node->input(0))->name();
  278. MS_LOG(DEBUG) << "Redistribution: middle_prim " << middle_prim->name() << " next_prim " << next_prim_name;
  279. MS_LOG(DEBUG) << "Redistribution: middle_node " << middle_node->ToString() << " next_node " << next_node->ToString();
  280. // extract tensor layout in and out
  281. if (distribute_operator->outputs_tensor_info().empty()) {
  282. MS_LOG(WARNING) << "pre_node's tensorinfo_in is empty, operator name is " << distribute_operator->name();
  283. return;
  284. }
  285. if (IntToSize(index - 1) >= next_distribute_operator->inputs_tensor_info().size()) {
  286. MS_LOG(WARNING) << "The index is out of range, the index is " << index - 1 << ", the vector size is "
  287. << next_distribute_operator->inputs_tensor_info().size() << "next operator name is "
  288. << next_distribute_operator->name();
  289. return;
  290. }
  291. TensorInfo tensorinfo_out = next_distribute_operator->inputs_tensor_info()[IntToSize(index - 1)];
  292. TensorLayout tensorlayout_out = tensorinfo_out.tensor_layout();
  293. TensorLayout tensorlayout_in = GetTensorInLayout(middle_node, middle_prim, distribute_operator);
  294. if (tensorlayout_in.skip_redistribution() || tensorlayout_out.skip_redistribution()) {
  295. MS_LOG(INFO) << "skip the reshape redistribution, operator name is" << distribute_operator->name()
  296. << "next distribute operator, operator name is" << next_distribute_operator->name();
  297. return;
  298. }
  299. if (tensor_redistribution.Init(tensorlayout_in, tensorlayout_out, dev_list) == FAILED) {
  300. MS_LOG(ERROR) << "Redistribution: middle_prim " << middle_prim->name() << " next_prim : " << next_prim_name;
  301. MS_LOG(ERROR) << "Redistribution: middle_node " << middle_node->ToString() << " next_node "
  302. << next_node->ToString();
  303. DumpGraph(func_graph, "redistribution_error");
  304. MS_LOG(EXCEPTION) << "Failure:tensor_redistribution init failed";
  305. }
  306. RedistributionOpListPtr redistribution_oplist_ptr = tensor_redistribution.InferTensorRedistributionOperatorList();
  307. if (redistribution_oplist_ptr == nullptr) {
  308. MS_LOG(EXCEPTION) << "Failure:InferTensorRedistribution failed";
  309. }
  310. MS_LOG(DEBUG) << "Redistribution size " << redistribution_oplist_ptr->first.size();
  311. if (!redistribution_oplist_ptr->first.empty()) {
  312. // insert node before next node
  313. InsertRedistribution(redistribution_oplist_ptr, next_node, func_graph, node_pair.second, pre_node);
  314. }
  315. }
  316. bool StrategyFound(std::unordered_map<std::string, ValuePtr> attrs) {
  317. auto iter = attrs.find(STRATEGY);
  318. return !((iter == attrs.end()) || (iter->second->type_name() == NONE));
  319. }
  320. bool HasStrategy(const FuncGraphPtr &root) {
  321. AnfNodePtr ret = root->get_return();
  322. MS_EXCEPTION_IF_NULL(ret);
  323. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  324. for (auto &node : all_nodes) {
  325. auto cnode = node->cast<CNodePtr>();
  326. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  327. continue;
  328. }
  329. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  330. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  331. auto attrs = prim->attrs();
  332. if (StrategyFound(attrs)) {
  333. return true;
  334. }
  335. }
  336. return false;
  337. }
  338. bool IsCommunicationOp(const PrimitivePtr &prim) {
  339. MS_EXCEPTION_IF_NULL(prim);
  340. return (COMMUNICATION_OPS.find(prim->name()) != COMMUNICATION_OPS.end());
  341. }
  342. bool FindCommunicationOp(const std::vector<AnfNodePtr> &all_nodes) {
  343. for (auto &node : all_nodes) {
  344. MS_EXCEPTION_IF_NULL(node);
  345. if (!node->isa<CNode>()) {
  346. continue;
  347. }
  348. auto cnode = node->cast<CNodePtr>();
  349. if (!IsValueNode<Primitive>(cnode->input(0))) {
  350. continue;
  351. }
  352. ValueNodePtr prim_value_node = cnode->input(0)->cast<ValueNodePtr>();
  353. MS_EXCEPTION_IF_NULL(prim_value_node);
  354. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_value_node);
  355. MS_EXCEPTION_IF_NULL(prim);
  356. if (IsCommunicationOp(prim) && cnode->in_forward_flag()) {
  357. MS_EXCEPTION_IF_NULL(prim_value_node->scope());
  358. MS_LOG(INFO) << "The graph contain communication op: " << prim->name() << ", scope name is "
  359. << prim_value_node->scope()->name();
  360. return true;
  361. }
  362. }
  363. return false;
  364. }
  365. bool IsParallelCareNode(const CNodePtr &cnode) {
  366. MS_EXCEPTION_IF_NULL(cnode);
  367. ValueNodePtr prim_node = cnode->input(0)->cast<ValueNodePtr>();
  368. if (prim_node == nullptr) {
  369. return false;
  370. }
  371. PrimitivePtr prim = prim_node->value()->cast<PrimitivePtr>();
  372. if (prim == nullptr) {
  373. return false;
  374. }
  375. if (IsInBlackList(prim)) {
  376. MS_LOG(INFO) << "Parallel don't care node: " << prim->name();
  377. return false;
  378. }
  379. // get_next is not in the forward graph, we need mark the get_next as the forward node
  380. if (prim->name() == GET_NEXT) {
  381. return true;
  382. }
  383. if ((prim->name() == CAST) && !cnode->HasUserData<OperatorInfo>()) {
  384. return false;
  385. }
  386. return cnode->in_forward_flag();
  387. }
  388. void StepRedistribution(const CNodePtr &node, const OperatorInfoPtr &distribute_operator, const CNodePtr &insert_node,
  389. const TensorRedistribution &tensor_redistribution, const CNodePtr &pre_node) {
  390. MS_EXCEPTION_IF_NULL(node->func_graph());
  391. FuncGraphManagerPtr manager = node->func_graph()->manager();
  392. MS_EXCEPTION_IF_NULL(manager);
  393. AnfNodeIndexSet node_set = manager->node_users()[node];
  394. CNodePtr insert_node_new;
  395. if (IsValueNode<Primitive>(node->input(0))) {
  396. auto current_value = node->input(0)->cast<ValueNodePtr>();
  397. MS_EXCEPTION_IF_NULL(current_value);
  398. PrimitivePtr current_prim = current_value->value()->cast<PrimitivePtr>();
  399. MS_EXCEPTION_IF_NULL(current_prim);
  400. insert_node_new = ((current_prim->name() == TUPLE_GETITEM) ? node : insert_node);
  401. } else {
  402. insert_node_new = insert_node;
  403. }
  404. MS_EXCEPTION_IF_NULL(insert_node_new);
  405. for (auto &node_pair : node_set) {
  406. CNodePtr use_cnode = node_pair.first->cast<CNodePtr>();
  407. MS_EXCEPTION_IF_NULL(use_cnode);
  408. if (!IsValueNode<Primitive>(use_cnode->input(0))) {
  409. StepRedistribution(use_cnode, distribute_operator, insert_node_new, tensor_redistribution, pre_node);
  410. } else {
  411. ValueNodePtr prim_anf_node = use_cnode->input(0)->cast<ValueNodePtr>();
  412. MS_EXCEPTION_IF_NULL(prim_anf_node);
  413. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  414. MS_EXCEPTION_IF_NULL(node_prim);
  415. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  416. continue;
  417. }
  418. if (IsParallelCareNode(use_cnode) && use_cnode->HasUserData<OperatorInfo>()) {
  419. Redistribution(node_pair, distribute_operator, insert_node_new, node_pair.second, tensor_redistribution,
  420. pre_node);
  421. } else {
  422. StepRedistribution(use_cnode, distribute_operator, insert_node_new, tensor_redistribution, pre_node);
  423. }
  424. }
  425. }
  426. }
  427. void SplitTensor(const AnfNodePtr &node, const CNodePtr &next_node, int index) {
  428. MS_EXCEPTION_IF_NULL(node);
  429. MS_EXCEPTION_IF_NULL(next_node);
  430. OperatorInfoPtr op_info = next_node->GetUserData<OperatorInfo>();
  431. MS_EXCEPTION_IF_NULL(op_info);
  432. // If the shape of tensor is [] or [1], no need to split it.
  433. Shapes shapes = GetNodeShape(node);
  434. if (shapes.size() != 1) {
  435. MS_LOG(EXCEPTION) << "Split tensor for " << op_info->name()
  436. << ": GetNodeShape for tensor_node, output size is not 1";
  437. }
  438. Shape shape = shapes[0];
  439. std::string shape_str = ShapeToString(shape);
  440. if (shape.empty() || ((shape.size() == 1) && (shape[0] == 1))) {
  441. MS_LOG(INFO) << "Split tensor for " << op_info->name() << ": The shape is " << shape_str
  442. << ", no need to split it.";
  443. return;
  444. }
  445. MS_LOG(INFO) << "Split tensor for " << op_info->name() << ": The shape of tensor is " << shape_str;
  446. // extract tensor layout
  447. if (IntToSize(index - 1) >= op_info->inputs_tensor_info().size()) {
  448. MS_LOG(EXCEPTION) << "The index is out of range, index is " << index - 1 << ", vector size is "
  449. << op_info->inputs_tensor_info().size();
  450. }
  451. TensorInfo tensor_info = op_info->inputs_tensor_info()[IntToSize(index - 1)];
  452. TensorLayout tensor_layout = tensor_info.tensor_layout();
  453. // Use _GetTensorSlice operator to split the tensor
  454. FuncGraphPtr func_graph = next_node->func_graph(); // only cnode can get the graph
  455. MS_EXCEPTION_IF_NULL(func_graph);
  456. Operator op = CreateGetTensorSliceOp(tensor_layout);
  457. InsertGetTensorSliceOp(op, next_node, func_graph, index, SPLIT_TENSOR);
  458. if (!op_info->sub_ops().empty()) {
  459. auto sub_ops = op_info->sub_ops();
  460. for (size_t i = 0; i < sub_ops.size(); i++) {
  461. if (!sub_ops.at(i).empty()) {
  462. InsertGetTensorSliceOp(sub_ops.at(i).at(0), next_node, func_graph, index, SUB);
  463. }
  464. }
  465. }
  466. }
  467. void StepSplitTensor(const AnfNodePtr &node, const FuncGraphManagerPtr &manager) {
  468. MS_EXCEPTION_IF_NULL(node);
  469. MS_EXCEPTION_IF_NULL(manager);
  470. AnfNodeIndexSet node_set = manager->node_users()[node];
  471. for (auto &node_pair : node_set) {
  472. CNodePtr use_cnode = node_pair.first->cast<CNodePtr>();
  473. if (use_cnode == nullptr || !IsValueNode<Primitive>(use_cnode->input(0))) {
  474. continue;
  475. }
  476. ValueNodePtr prim_anf_node = use_cnode->input(0)->cast<ValueNodePtr>();
  477. MS_EXCEPTION_IF_NULL(prim_anf_node);
  478. PrimitivePtr use_cnode_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  479. MS_EXCEPTION_IF_NULL(use_cnode_prim);
  480. if (use_cnode_prim->name() == DEPEND && node_pair.second != 1) {
  481. continue;
  482. }
  483. if (IsParallelCareNode(use_cnode)) {
  484. SplitTensor(node, use_cnode, node_pair.second);
  485. }
  486. }
  487. }
  488. std::vector<AnfNodePtr> ReplaceOpInput(const Operator &replace_op, const std::string &instance_name,
  489. const CNodePtr &node) {
  490. OperatorArgs arg_replace_op = replace_op.second;
  491. ValuePtr pyop_instance = CreatOpInstance(arg_replace_op.first, replace_op.first, instance_name);
  492. if (pyop_instance == nullptr) {
  493. MS_LOG(EXCEPTION) << "Failure: " << replace_op.first << " CreatOpInstance failed";
  494. }
  495. OperatorParams params = arg_replace_op.second;
  496. if (node->inputs().size() < 2) {
  497. // GetNext operator dose not has input
  498. if (node->inputs().size() == 1) {
  499. return {NewValueNode(pyop_instance)};
  500. }
  501. MS_LOG(EXCEPTION) << "Failure: " << node->ToString() << " size is smaller than 2";
  502. }
  503. std::vector<AnfNodePtr> replace_input = {NewValueNode(pyop_instance), node->input(1)};
  504. auto prim = GetValueNode<PrimitivePtr>(node->input(0));
  505. if (prim->name() == EMBEDDING_LOOKUP) {
  506. replace_input = {NewValueNode(pyop_instance), node->input(1), node->input(2)};
  507. }
  508. if (!params.empty()) {
  509. Param param_first = *(params.begin());
  510. int32_t first_position = param_first.second;
  511. if (first_position == 1) {
  512. replace_input.pop_back();
  513. }
  514. for (auto &param : params) {
  515. AnfNodePtr val = NewValueNode(param.first.second);
  516. if (val == nullptr) {
  517. MS_LOG(EXCEPTION) << "Failure:val is nullptr";
  518. }
  519. int32_t position = param.second;
  520. (void)replace_input.insert(replace_input.begin() + position, val);
  521. }
  522. }
  523. return replace_input;
  524. }
  525. void ReplaceOneOp(const Operator &replace_op, const CNodePtr &node) {
  526. FuncGraphPtr func_graph = node->func_graph();
  527. MS_EXCEPTION_IF_NULL(func_graph);
  528. FuncGraphManagerPtr manager = func_graph->manager();
  529. if (manager == nullptr) {
  530. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  531. }
  532. std::string instance_name = CreateInstanceName(node, 0);
  533. std::vector<AnfNodePtr> replace_input;
  534. replace_input = ReplaceOpInput(replace_op, instance_name, node);
  535. CNodePtr replace_node = func_graph->NewCNode(replace_input);
  536. MS_EXCEPTION_IF_NULL(replace_node);
  537. ScopePtr scope = node->scope();
  538. MS_EXCEPTION_IF_NULL(scope);
  539. replace_node->set_scope(scope);
  540. replace_node->set_in_forward_flag(true);
  541. replace_input[0]->set_scope(scope);
  542. (void)manager->Replace(node, replace_node);
  543. }
  544. void StepReplaceOp(OperatorVector replace_op, const CNodePtr &node) {
  545. // step1:get graph manager distribute_operator
  546. OperatorInfoPtr distribute_operator = node->GetUserData<OperatorInfo>();
  547. if (distribute_operator == nullptr) {
  548. MS_LOG(EXCEPTION) << "Failure:AddNode error since distribute_operator is nullptr";
  549. }
  550. FuncGraphPtr func_graph = node->func_graph();
  551. MS_EXCEPTION_IF_NULL(func_graph);
  552. FuncGraphManagerPtr manager = func_graph->manager();
  553. if (manager == nullptr) {
  554. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  555. }
  556. // step2:traverse op_list and insert node
  557. std::reverse(replace_op.begin(), replace_op.end());
  558. auto replace_op_info = distribute_operator->replace_op_info();
  559. std::reverse(replace_op_info.begin(), replace_op_info.end());
  560. if (!replace_op_info.empty() && replace_op_info.size() != replace_op.size()) {
  561. MS_LOG(EXCEPTION) << "replace_op_info is not empty and size not equal to replace_op!";
  562. }
  563. bool replace_op_info_flag = !replace_op_info.empty();
  564. for (size_t index = 0; index < replace_op.size(); ++index) {
  565. std::string instance_name = CreateInstanceName(node, index);
  566. std::vector<AnfNodePtr> replace_input;
  567. if (index != replace_op.size() - 1) {
  568. replace_input = CreateInput(replace_op[index], node, instance_name);
  569. } else {
  570. replace_input = ReplaceOpInput(replace_op[index], instance_name, node);
  571. }
  572. CNodePtr replace_node = func_graph->NewCNode(replace_input);
  573. MS_EXCEPTION_IF_NULL(replace_node);
  574. ScopePtr scope = node->scope();
  575. MS_EXCEPTION_IF_NULL(scope);
  576. replace_node->set_scope(scope);
  577. PrimitivePtr prim = GetValueNode<PrimitivePtr>(replace_node->input(0));
  578. if (prim->name() == EMBEDDING_LOOKUP) {
  579. auto attrs = prim->attrs();
  580. attrs[TARGET] = MakeValue(CPU);
  581. (void)prim->SetAttrs(attrs);
  582. }
  583. if (index == replace_op.size() - 1) {
  584. replace_node->SetUserData<OperatorInfo>(node->GetUserData<OperatorInfo>());
  585. }
  586. replace_node->set_in_forward_flag(true);
  587. replace_input[0]->set_scope(scope);
  588. if (replace_op_info_flag && replace_op_info[index].first) {
  589. auto new_cnode = InsertMakeTuple(replace_node, replace_op_info[index].second, func_graph);
  590. (void)manager->Replace(node, new_cnode); // using Replace function to insert node
  591. } else {
  592. (void)manager->Replace(node, replace_node); // using Replace function to insert node
  593. }
  594. }
  595. MS_LOG(INFO) << "Insert ReplaceOp success for " << distribute_operator->name();
  596. }
  597. bool IsSomePrimitive(const CNodePtr &cnode, const std::string &name) {
  598. ValueNodePtr anf_node = cnode->input(0)->cast<ValueNodePtr>();
  599. MS_EXCEPTION_IF_NULL(anf_node);
  600. PrimitivePtr prim = anf_node->value()->cast<PrimitivePtr>();
  601. return (prim->name() == name);
  602. }
  603. void StepReplaceGraph(const ReplaceGraphPtr &replace_graph, const CNodePtr &node) {
  604. MS_EXCEPTION_IF_NULL(replace_graph);
  605. MS_EXCEPTION_IF_NULL(node);
  606. MS_EXCEPTION_IF_NULL(replace_graph->second);
  607. FuncGraphPtr func_graph = node->func_graph();
  608. MS_EXCEPTION_IF_NULL(func_graph);
  609. FuncGraphManagerPtr manager = func_graph->manager();
  610. if (manager == nullptr) {
  611. MS_LOG(EXCEPTION) << "Failure:AddNode error since manager is nullptr";
  612. }
  613. for (auto &replace_input : replace_graph->first) {
  614. auto pre_node = node->input(IntToSize(replace_input.second));
  615. manager->SetEdge(replace_input.first, 1, pre_node);
  616. }
  617. // "(void)manager->Replace(replace_graph->first, pre_node);" can not be called
  618. auto replace_output = replace_graph->second;
  619. MS_EXCEPTION_IF_NULL(replace_output);
  620. (void)manager->Replace(node, replace_output);
  621. }
  622. int32_t GetTupleGetItemIndex(const CNodePtr &cnode) {
  623. MS_EXCEPTION_IF_NULL(cnode);
  624. if (cnode->inputs().size() != 3) {
  625. MS_LOG(EXCEPTION) << cnode->ToString() << " size( " << cnode->inputs().size() << " ) is not 3";
  626. }
  627. if (!cnode->input(2)->isa<ValueNode>()) {
  628. MS_LOG(EXCEPTION) << "The index of tuple getitem is not a value node";
  629. }
  630. ValuePtr tuple_index_value = GetValueNode(cnode->input(2));
  631. MS_EXCEPTION_IF_NULL(tuple_index_value);
  632. if (!tuple_index_value->isa<Int32Imm>()) {
  633. MS_LOG(EXCEPTION) << "The index of tuple getitem is not int32";
  634. }
  635. return tuple_index_value->cast<Int32ImmPtr>()->value();
  636. }
  637. // Judge whether the node is a loss, and if there are multiple outputs,
  638. // get which output is a grad according to the tuple getitem.
  639. // Currently, it is not supported that the sens is a tuple.
  640. LossNodeInfo GetLossNodeInfo(const AnfNodePtr &loss_node) {
  641. MS_EXCEPTION_IF_NULL(loss_node);
  642. FuncGraphPtr sub_graph = loss_node->func_graph();
  643. MS_EXCEPTION_IF_NULL(sub_graph);
  644. CNodePtr return_node = sub_graph->get_return();
  645. MS_EXCEPTION_IF_NULL(return_node);
  646. if (return_node->inputs().size() < 2) {
  647. MS_LOG(EXCEPTION) << "Failure: " << return_node->ToString() << " size is smaller than 2";
  648. }
  649. AnfNodePtr pre_node = return_node->input(1);
  650. MS_EXCEPTION_IF_NULL(pre_node);
  651. LossNodeInfo node_info;
  652. // return -> cast
  653. auto pre_cnode = pre_node->cast<CNodePtr>();
  654. MS_EXCEPTION_IF_NULL(pre_cnode);
  655. auto pre_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  656. if (pre_prim->name() == CAST && !pre_cnode->HasUserData<OperatorInfo>()) {
  657. pre_node = pre_cnode->input(1);
  658. }
  659. // return -> loss
  660. if (pre_node == loss_node) {
  661. node_info.has_tuple_getitem = false;
  662. node_info.dout_index = 0;
  663. return node_info;
  664. }
  665. // return -> tuple_getitem -> loss
  666. auto cnode = pre_node->cast<CNodePtr>();
  667. MS_EXCEPTION_IF_NULL(cnode);
  668. auto current_value = cnode->input(0)->cast<ValueNodePtr>();
  669. MS_EXCEPTION_IF_NULL(current_value);
  670. PrimitivePtr current_prim = current_value->value()->cast<PrimitivePtr>();
  671. MS_EXCEPTION_IF_NULL(current_prim);
  672. // size of common cnode is larger than 1
  673. if (cnode->inputs().size() < 2) {
  674. MS_LOG(EXCEPTION) << cnode->ToString() << " size( " << cnode->inputs().size() << " ) is smaller than 2";
  675. }
  676. if ((current_prim->name() == TUPLE_GETITEM) && (cnode->input(1) == loss_node)) {
  677. // size of tuple_getitem cnode is 3
  678. auto tuple_index = GetTupleGetItemIndex(cnode);
  679. node_info.has_tuple_getitem = true;
  680. node_info.dout_index = tuple_index;
  681. return node_info;
  682. }
  683. MS_LOG(EXCEPTION) << "Invalid loss";
  684. }
  685. void InsertVirtualDivOp(const VirtualDivOp &virtual_div_op, const CNodePtr &node) {
  686. MS_EXCEPTION_IF_NULL(node);
  687. size_t node_size = node->inputs().size();
  688. FuncGraphPtr func_graph = node->func_graph();
  689. MS_EXCEPTION_IF_NULL(func_graph);
  690. FuncGraphManagerPtr manager = func_graph->manager();
  691. MS_EXCEPTION_IF_NULL(manager);
  692. for (size_t index = 1; index < node_size; ++index) {
  693. AnfNodePtr input = node->input(index);
  694. MS_EXCEPTION_IF_NULL(input);
  695. if (!input->isa<CNode>() && !input->isa<Parameter>()) { // if it is not a tensor, continue
  696. MS_LOG(INFO) << "insert div op: the index " << index << " is not tensor, skip";
  697. continue;
  698. }
  699. for (size_t pos = 0; pos < virtual_div_op.size(); ++pos) {
  700. std::string instance_name = CreateInstanceName(node, pos);
  701. InsertNode(virtual_div_op[pos], node, index, node->input(index), func_graph, instance_name);
  702. }
  703. MS_LOG(INFO) << "insert div op for input index " << index << " of node";
  704. }
  705. }
  706. std::pair<AnfNodePtr, bool> FindParameter(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  707. if (!node->isa<Parameter>() && !node->isa<CNode>() && !node->isa<ValueNode>()) {
  708. return std::make_pair(nullptr, false);
  709. } else if (node->isa<Parameter>()) {
  710. return std::make_pair(node, false);
  711. } else if (node->isa<ValueNode>()) {
  712. if (IsValueNode<RefKey>(node)) {
  713. std::vector<AnfNodePtr> param_v = FindParameterByRefKeyNode(node, func_graph);
  714. if (param_v.size() != 1) {
  715. MS_LOG(EXCEPTION) << "FindParameterByRefKeyNode failed, return vector size must be 1, real is "
  716. << param_v.size();
  717. }
  718. return std::make_pair(node, true);
  719. }
  720. return std::make_pair(nullptr, false);
  721. } else {
  722. CNodePtr cnode = node->cast<CNodePtr>();
  723. MS_EXCEPTION_IF_NULL(cnode);
  724. if (!IsValueNode<Primitive>(cnode->input(0))) {
  725. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  726. if (!FindParameter(cnode->input(index), func_graph).first) {
  727. continue;
  728. }
  729. return FindParameter(cnode->input(index), func_graph);
  730. }
  731. } else {
  732. if (IsParallelCareNode(cnode)) {
  733. return std::make_pair(nullptr, false);
  734. } else {
  735. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  736. MS_EXCEPTION_IF_NULL(prim_anf_node);
  737. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  738. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  739. MS_EXCEPTION_IF_NULL(prim);
  740. if (prim->name() == DEPEND && index != 1) {
  741. continue;
  742. }
  743. if (!FindParameter(cnode->input(index), func_graph).first) {
  744. continue;
  745. }
  746. return FindParameter(cnode->input(index), func_graph);
  747. }
  748. }
  749. }
  750. }
  751. return std::make_pair(nullptr, false);
  752. }
  753. std::pair<bool, CNodePtr> FindCNode(const AnfNodePtr &anode, const std::string &name, const FuncGraphPtr &func_graph) {
  754. MS_EXCEPTION_IF_NULL(anode);
  755. MS_EXCEPTION_IF_NULL(anode->func_graph());
  756. FuncGraphManagerPtr manager = anode->func_graph()->manager();
  757. MS_EXCEPTION_IF_NULL(manager);
  758. AnfNodeIndexSet node_set = manager->node_users()[anode];
  759. bool result = false;
  760. CNodePtr cnode_return = nullptr;
  761. for (auto &node_pair : node_set) {
  762. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  763. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  764. continue;
  765. }
  766. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  767. MS_EXCEPTION_IF_NULL(prim_anf_node);
  768. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  769. MS_EXCEPTION_IF_NULL(node_prim);
  770. if (node_prim->name() == name && node_pair.second == 1) {
  771. if (use_apply->func_graph() == func_graph) {
  772. result = true;
  773. cnode_return = use_apply;
  774. MS_LOG(INFO) << "Find Primitive " << name << " in the same func_graph";
  775. continue;
  776. }
  777. MS_LOG(INFO) << "Find Primitive " << name << " in different func_graph";
  778. }
  779. }
  780. return std::make_pair(result, cnode_return);
  781. }
  782. bool IsCastBeforMirror(const CNodePtr &node, size_t index) {
  783. // only if cast_before_mirror is true, pre node is cast and type is not float32 return true
  784. if (!ParallelContext::GetInstance()->cast_before_mirror()) {
  785. return false;
  786. }
  787. auto pre_node = node->input(index);
  788. MS_EXCEPTION_IF_NULL(pre_node);
  789. auto cnode = pre_node->cast<CNodePtr>();
  790. if (cnode == nullptr || !IsValueNode<Primitive>(cnode->input(0))) {
  791. return false;
  792. }
  793. auto pre_value_node = cnode->input(0)->cast<ValueNodePtr>();
  794. MS_EXCEPTION_IF_NULL(pre_value_node);
  795. auto pre_prim = pre_value_node->value()->cast<PrimitivePtr>();
  796. MS_EXCEPTION_IF_NULL(pre_prim);
  797. if (pre_prim->name() != CAST) {
  798. return false;
  799. }
  800. auto node_type = pre_node->Type();
  801. MS_EXCEPTION_IF_NULL(node_type);
  802. if (!node_type->isa<mindspore::TensorType>()) {
  803. MS_LOG(EXCEPTION) << "Unknown type.";
  804. }
  805. auto input_element_type = node_type->cast<mindspore::TensorTypePtr>()->element();
  806. MS_EXCEPTION_IF_NULL(input_element_type);
  807. auto type_id = input_element_type->type_id();
  808. return (type_id != kNumberTypeFloat32);
  809. }
  810. void InsertMirrorOps(const MirrorOps &mirror_ops, const CNodePtr &node) {
  811. MS_EXCEPTION_IF_NULL(node);
  812. size_t node_size = node->inputs().size();
  813. FuncGraphPtr func_graph = node->func_graph();
  814. MS_EXCEPTION_IF_NULL(func_graph);
  815. FuncGraphManagerPtr manager = func_graph->manager();
  816. MS_EXCEPTION_IF_NULL(manager);
  817. if (mirror_ops.size() != node_size - 1) {
  818. MS_LOG(EXCEPTION) << "Failure:Mirrorops's size is wrong! mirror_ops size is " << mirror_ops.size()
  819. << ", node_size is " << node_size;
  820. }
  821. for (size_t index = 1; index < node_size; ++index) {
  822. OperatorVector backward_op = mirror_ops[index - 1];
  823. if (backward_op.empty()) {
  824. continue;
  825. }
  826. std::pair<AnfNodePtr, bool> param_node_pair = FindParameter(node->input(index), func_graph);
  827. if (!param_node_pair.first) {
  828. continue;
  829. }
  830. // not a RefKey
  831. if (!param_node_pair.second) {
  832. auto next_cnode = FindCNode(param_node_pair.first, MIRROR_OPERATOR, func_graph);
  833. // if there is already a MirrorOp in the same graph, use MirrorOp CNode as a input instead
  834. if (next_cnode.first) {
  835. MS_EXCEPTION_IF_NULL(next_cnode.second);
  836. manager->SetEdge(node, SizeToInt(index), next_cnode.second);
  837. continue;
  838. }
  839. }
  840. // if the parameter found is a RefKey, or no MirrorOp is found in the same graph, insert a new MirrorOp
  841. // only one MirrorOp in backward_op
  842. if (backward_op.size() != 1) {
  843. MS_LOG(EXCEPTION) << "backward_op size must be 1, real is " << backward_op.size();
  844. }
  845. std::string instance_name = MIRROR_OP;
  846. if (IsCastBeforMirror(node, index)) {
  847. for (auto &op : backward_op) {
  848. // insert new node before the node
  849. CNodePtr cnode = node->input(index)->cast<CNodePtr>();
  850. MS_EXCEPTION_IF_NULL(cnode);
  851. AnfNodePtr pre_node = cnode->input(1);
  852. InsertNode(op, cnode, size_t(1), pre_node, func_graph, instance_name);
  853. }
  854. } else {
  855. for (auto &op : backward_op) {
  856. AnfNodePtr pre_node = node->input(index);
  857. InsertNode(op, node, index, pre_node, func_graph, instance_name);
  858. }
  859. }
  860. }
  861. }
  862. void BackwardCommunication(const OperatorInfoPtr &distribute_operator, const CNodePtr &node,
  863. const std::vector<std::pair<CNodePtr, CNodePtr>> &sens_loss_pairs) {
  864. MS_EXCEPTION_IF_NULL(distribute_operator);
  865. MS_EXCEPTION_IF_NULL(node);
  866. bool is_loss_cnode =
  867. std::any_of(sens_loss_pairs.begin(), sens_loss_pairs.end(),
  868. [node](const std::pair<CNodePtr, CNodePtr> &element) { return element.second == node; });
  869. MirrorOps mirror_ops = distribute_operator->mirror_ops();
  870. VirtualDivOp virtual_div_op = distribute_operator->virtual_div_op();
  871. // insert mirror op
  872. if (!mirror_ops.empty()) {
  873. MS_LOG(INFO) << "insert mirror op for " << distribute_operator->name();
  874. InsertMirrorOps(mirror_ops, node);
  875. }
  876. // insert virtual div op
  877. if (!virtual_div_op.empty() && is_loss_cnode) {
  878. MS_LOG(INFO) << "insert virtual div op for " << distribute_operator->name();
  879. InsertVirtualDivOp(virtual_div_op, node);
  880. }
  881. }
  882. std::string GetDisOpName(const std::string &prim_name) {
  883. std::string op_name = prim_name;
  884. if (!prim_name.empty() && (prim_name[0] == '_')) {
  885. op_name = prim_name.substr(1);
  886. }
  887. return op_name + "Info";
  888. }
  889. OperatorInfoPtr OperatorInstanceByName(const std::string &name, const PrimitiveAttrs &attrs,
  890. const std::vector<Shapes> &shape_list) {
  891. if (shape_list.size() != 2) {
  892. MS_LOG(ERROR) << "The size of shape list is not 2";
  893. return nullptr;
  894. }
  895. if (name.length() == 0) {
  896. MS_LOG(EXCEPTION) << "Length of name is zero!";
  897. }
  898. std::string distribute_opname = GetDisOpName(name);
  899. if (name == GATHERV2) {
  900. distribute_opname = name + "PInfo";
  901. auto data_parallel_iter = attrs.find(DATA_PARALLEL);
  902. if (data_parallel_iter != attrs.end()) {
  903. MS_EXCEPTION_IF_NULL(data_parallel_iter->second);
  904. if (!data_parallel_iter->second->isa<BoolImm>()) {
  905. MS_LOG(EXCEPTION) << ": data_parallel flag's type is not a bool.";
  906. }
  907. bool data_parallel = data_parallel_iter->second->cast<BoolImmPtr>()->value();
  908. if (data_parallel) {
  909. distribute_opname = name + "Info";
  910. }
  911. }
  912. }
  913. OperatorInfoPtr operator_ =
  914. (OperatorInfoPtr)DynCreator::Instance().Creat(distribute_opname, shape_list[0], shape_list[1], attrs, TOTAL_OPS);
  915. if (operator_ == nullptr) {
  916. MS_LOG(INFO) << "Creat " << name << " failed";
  917. return nullptr;
  918. }
  919. std::string origin_name = operator_->name();
  920. operator_->set_name(origin_name + std::to_string(TOTAL_OPS));
  921. MS_LOG(INFO) << "Successfully created operator " << origin_name;
  922. ++TOTAL_OPS;
  923. return operator_;
  924. }
  925. OperatorInfoPtr OperatorInstance(const PrimitivePtr &prim, const PrimitiveAttrs &attrs,
  926. const std::vector<Shapes> &shape_list) {
  927. MS_EXCEPTION_IF_NULL(prim);
  928. OperatorInfoPtr operator_ = OperatorInstanceByName(prim->name(), attrs, shape_list);
  929. if (operator_ == nullptr) {
  930. MS_LOG(INFO) << "Creat " << prim->name() << " failed, use batch parallel";
  931. operator_ = OperatorInstanceByName(BATCH_PARALLEL, attrs, shape_list);
  932. MS_EXCEPTION_IF_NULL(operator_);
  933. }
  934. return operator_;
  935. }
  936. OperatorInfoPtr NewOperatorInstance(const PrimitivePtr &prim, const PrimitiveAttrs &attrs,
  937. std::vector<Shapes> shape_list) {
  938. OperatorInfoPtr operator_ = OperatorInstance(prim, attrs, shape_list);
  939. for (size_t i = 0; i < shape_list[0].size(); ++i) {
  940. MS_LOG(INFO) << "No: " << i << " input's shape: " << ShapeToString(shape_list[0][i]);
  941. }
  942. return operator_;
  943. }
  944. StrategyPtr ExtractStrategy(std::unordered_map<std::string, ValuePtr> attrs) {
  945. ValueTuplePtr var = attrs[STRATEGY]->cast<ValueTuplePtr>();
  946. StrategyPtr strategyPtr;
  947. MS_LOG(INFO) << "Extract information: strategy " << attrs[STRATEGY]->ToString();
  948. if (var == nullptr) {
  949. MS_LOG(EXCEPTION) << "Strategy value is nullptr";
  950. }
  951. if (var->size() > 0) {
  952. std::vector<ValuePtr> elements = var->value();
  953. std::vector<Dimensions> strategy;
  954. for (uint32_t index = 0; index < elements.size(); ++index) {
  955. Dimensions dim;
  956. if (elements[index]->isa<ValueSequeue>()) {
  957. ValueTuplePtr value_tuple = elements[index]->cast<ValueTuplePtr>();
  958. std::vector<ValuePtr> value_vector = value_tuple->value();
  959. (void)std::transform(value_vector.begin(), value_vector.end(), std::back_inserter(dim),
  960. [](const ValuePtr &value) { return static_cast<int32_t>(GetValue<int>(value)); });
  961. strategy.push_back(dim);
  962. } else {
  963. MS_LOG(EXCEPTION) << "Failure:Strategy's format is wrong! Need ValueSequeue";
  964. }
  965. }
  966. if (strategy.empty()) {
  967. MS_LOG(EXCEPTION) << "ExtractStrategy:failed to extract strategy";
  968. }
  969. strategyPtr = NewStrategy(0, strategy);
  970. }
  971. return strategyPtr;
  972. }
  973. Shapes GetNodeShape(const AnfNodePtr &node) {
  974. MS_EXCEPTION_IF_NULL(node);
  975. Shapes shapes;
  976. BaseShapePtr base_shape_ptr = node->Shape();
  977. if (node->isa<CNode>()) {
  978. auto cnode = node->cast<CNodePtr>();
  979. if (IsValueNode<Primitive>(cnode->input(0))) {
  980. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  981. MS_EXCEPTION_IF_NULL(prim);
  982. if (prim->name() == MAKEREF) {
  983. AnfNodePtr ref_node = cnode->input(1);
  984. auto func_graph = cnode->func_graph();
  985. MS_EXCEPTION_IF_NULL(ref_node);
  986. MS_EXCEPTION_IF_NULL(func_graph);
  987. return GetRefKeyNodeShape(ref_node, func_graph);
  988. }
  989. }
  990. if (cnode->input(0)->isa<CNode>()) {
  991. if (cnode->inputs().size() < 2) {
  992. MS_LOG(EXCEPTION) << "GetNodeShape: " << node->ToString() << " size is samller than 2";
  993. }
  994. base_shape_ptr = cnode->input(1)->Shape();
  995. }
  996. }
  997. if (base_shape_ptr == nullptr) {
  998. MS_LOG(EXCEPTION) << "GetNodeShape: " << node->ToString() << " shape_ptr is nullptr, full name is "
  999. << node->fullname_with_scope();
  1000. }
  1001. auto tuple_shape_ptr = dyn_cast<abstract::TupleShape>(base_shape_ptr);
  1002. if (tuple_shape_ptr != nullptr) {
  1003. auto tuple_shape = tuple_shape_ptr->shape();
  1004. for (auto &shape : tuple_shape) {
  1005. auto each_shape = dyn_cast<abstract::Shape>(shape);
  1006. MS_EXCEPTION_IF_NULL(each_shape);
  1007. shapes.push_back(each_shape->shape());
  1008. }
  1009. } else {
  1010. auto shape_ptr = dyn_cast<abstract::Shape>(base_shape_ptr);
  1011. MS_EXCEPTION_IF_NULL(shape_ptr);
  1012. shapes.push_back(shape_ptr->shape());
  1013. }
  1014. return shapes;
  1015. }
  1016. std::vector<AnfNodePtr> FindParameterByRefKeyNode(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  1017. MS_EXCEPTION_IF_NULL(node);
  1018. MS_EXCEPTION_IF_NULL(func_graph);
  1019. std::vector<AnfNodePtr> parameters;
  1020. if (!IsValueNode<RefKey>(node)) {
  1021. MS_LOG(ERROR) << "The node is not a ref key";
  1022. return parameters;
  1023. }
  1024. auto ref_key = GetValueNode<RefKeyPtr>(node);
  1025. MS_EXCEPTION_IF_NULL(ref_key);
  1026. auto name = ref_key->tag();
  1027. auto manager = func_graph->manager();
  1028. MS_EXCEPTION_IF_NULL(manager);
  1029. auto roots = manager->roots();
  1030. if (roots.size() != 1) {
  1031. MS_LOG(ERROR) << "The size of roots ( " << roots.size() << " ) is not 1";
  1032. return parameters;
  1033. }
  1034. FuncGraphPtr root_g = roots.back();
  1035. MS_EXCEPTION_IF_NULL(root_g);
  1036. for (auto &param_node : root_g->parameters()) {
  1037. auto param = param_node->cast<ParameterPtr>();
  1038. if (param && (name == param->name())) {
  1039. parameters.push_back(param_node);
  1040. MS_LOG(INFO) << "The name of ref key is: " << name;
  1041. return parameters;
  1042. }
  1043. }
  1044. MS_LOG(ERROR) << "The name of ref key is: " << name << ", but have not found the parameter";
  1045. return parameters;
  1046. }
  1047. Shapes GetRefKeyNodeShape(const AnfNodePtr &node, const FuncGraphPtr &func_graph) {
  1048. MS_EXCEPTION_IF_NULL(node);
  1049. MS_EXCEPTION_IF_NULL(func_graph);
  1050. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(node, func_graph);
  1051. if (parameters.size() != 1) {
  1052. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  1053. }
  1054. Shapes input_shapes;
  1055. input_shapes = GetNodeShape(parameters[0]);
  1056. if (input_shapes.size() != 1) {
  1057. MS_LOG(EXCEPTION) << "Get input shape failed";
  1058. }
  1059. MS_LOG(INFO) << "The parameter shape is " << ShapeToString(input_shapes[0]);
  1060. return input_shapes;
  1061. }
  1062. std::vector<Shapes> ExtractShape(const CNodePtr &node) {
  1063. MS_EXCEPTION_IF_NULL(node);
  1064. Shapes shape_inputs, shape_outputs;
  1065. std::vector<Shapes> shape_all;
  1066. std::vector<AnfNodePtr> all_inputs = node->inputs();
  1067. std::vector<AnfNodePtr> node_inputs{all_inputs.begin() + 1, all_inputs.end()};
  1068. size_t inputs_size = all_inputs.size();
  1069. for (size_t i = 1; i < inputs_size; ++i) {
  1070. Shapes input_shapes;
  1071. AnfNodePtr input = all_inputs[i];
  1072. if (IsValueNode<RefKey>(input)) {
  1073. auto func_graph = node->func_graph();
  1074. MS_EXCEPTION_IF_NULL(func_graph);
  1075. std::vector<AnfNodePtr> parameters = FindParameterByRefKeyNode(input, func_graph);
  1076. if (parameters.size() != 1) {
  1077. MS_LOG(EXCEPTION) << "Find parameter by ref key node failed";
  1078. }
  1079. std::pair<AnfNodePtr, int> node_pair = std::make_pair(node, SizeToInt(i));
  1080. g_RefMap[parameters[0]] = node_pair;
  1081. input_shapes = GetRefKeyNodeShape(input, func_graph);
  1082. } else if (IsValueNode<Tensor>(input) || input->isa<CNode>() || input->isa<Parameter>()) {
  1083. input_shapes = GetNodeShape(input);
  1084. } else {
  1085. continue;
  1086. }
  1087. if (input_shapes.size() != 1) {
  1088. MS_LOG(EXCEPTION) << "ExtractShape:Get input shape failed";
  1089. }
  1090. shape_inputs.push_back(input_shapes[0]);
  1091. }
  1092. shape_all.push_back(shape_inputs);
  1093. // extract out shape
  1094. shape_outputs = GetNodeShape(node);
  1095. shape_all.push_back(shape_outputs);
  1096. return shape_all;
  1097. }
  1098. std::pair<AnfNodePtr, int> FindParallelCareNode(const AnfNodePtr &node) {
  1099. MS_EXCEPTION_IF_NULL(node);
  1100. FuncGraphPtr func_graph = node->func_graph();
  1101. MS_EXCEPTION_IF_NULL(func_graph);
  1102. FuncGraphManagerPtr manager = func_graph->manager();
  1103. MS_EXCEPTION_IF_NULL(manager);
  1104. AnfNodeIndexSet node_set = manager->node_users()[node];
  1105. for (auto &node_pair : node_set) {
  1106. CNodePtr cnode = node_pair.first->cast<CNodePtr>();
  1107. MS_EXCEPTION_IF_NULL(cnode);
  1108. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1109. continue;
  1110. }
  1111. ValueNodePtr prim_node_anf = cnode->input(0)->cast<ValueNodePtr>();
  1112. MS_EXCEPTION_IF_NULL(prim_node_anf);
  1113. PrimitivePtr node_prim = prim_node_anf->value()->cast<PrimitivePtr>();
  1114. MS_EXCEPTION_IF_NULL(node_prim);
  1115. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  1116. continue;
  1117. }
  1118. if (IsParallelCareNode(cnode) && cnode->HasUserData<OperatorInfo>()) {
  1119. return node_pair;
  1120. } else if (FindParallelCareNode(node_pair.first).first != nullptr) {
  1121. return FindParallelCareNode(node_pair.first);
  1122. }
  1123. }
  1124. return std::make_pair(nullptr, 0);
  1125. }
  1126. std::pair<AnfNodePtr, int> FindSubGraph(const FuncGraphPtr &graph, const AnfNodePtr &parameter) {
  1127. MS_EXCEPTION_IF_NULL(graph);
  1128. MS_EXCEPTION_IF_NULL(parameter);
  1129. FuncGraphManagerPtr manager = graph->manager();
  1130. MS_EXCEPTION_IF_NULL(manager);
  1131. std::pair<AnfNodePtr, int> prim_anf_node_pair = FindParallelCareNode(parameter);
  1132. if (prim_anf_node_pair.first != nullptr) {
  1133. return prim_anf_node_pair;
  1134. } else {
  1135. AnfNodeIndexSet param_sub_set = manager->node_users()[parameter];
  1136. for (auto &param_pair : param_sub_set) {
  1137. CNodePtr graph_cnode = param_pair.first->cast<CNodePtr>();
  1138. if ((graph_cnode == nullptr) || !graph_cnode->input(0)->isa<CNode>()) {
  1139. continue;
  1140. }
  1141. CNodePtr graph_cnode_inp0 = graph_cnode->input(0)->cast<CNodePtr>();
  1142. if (!IsValueNode<FuncGraph>(graph_cnode_inp0->input(1))) {
  1143. continue;
  1144. }
  1145. FuncGraphPtr graph_sub = GetValueNode<FuncGraphPtr>(graph_cnode_inp0->input(1));
  1146. auto parameters = graph_sub->parameters();
  1147. if (IntToSize(param_pair.second - 1) >= parameters.size()) {
  1148. MS_LOG(EXCEPTION) << "The index is out of range, index is " << param_pair.second - 1 << ", vector size is "
  1149. << parameters.size();
  1150. }
  1151. std::pair<AnfNodePtr, int> res = FindSubGraph(graph_sub, parameters[IntToSize(param_pair.second - 1)]);
  1152. if (res.first != nullptr) {
  1153. return res;
  1154. }
  1155. }
  1156. }
  1157. return std::make_pair(nullptr, 0);
  1158. }
  1159. void SetParallelShape(const AnfNodePtr &parameter, const std::pair<AnfNodePtr, int> &res) {
  1160. MS_EXCEPTION_IF_NULL(parameter);
  1161. AbstractBasePtr abstract = parameter->abstract();
  1162. MS_EXCEPTION_IF_NULL(abstract);
  1163. MS_LOG(DEBUG) << "SetParallelShape " << parameter->ToString() << " shape " << parameter->Shape()->ToString();
  1164. CNodePtr cnode = res.first->cast<CNodePtr>();
  1165. MS_EXCEPTION_IF_NULL(cnode);
  1166. OperatorInfoPtr distribute_operator = cnode->GetUserData<OperatorInfo>();
  1167. if (distribute_operator == nullptr) {
  1168. MS_LOG(EXCEPTION) << "Failure:node " << cnode->ToString() << " 's OperatorInfoPtr is nullptr";
  1169. }
  1170. if (IntToSize(res.second - 1) >= distribute_operator->inputs_tensor_info().size()) {
  1171. MS_LOG(EXCEPTION) << "The index is out of range, index is " << res.second - 1 << ", vector size is "
  1172. << distribute_operator->inputs_tensor_info().size();
  1173. }
  1174. TensorInfo tensorinfo_in = distribute_operator->inputs_tensor_info()[IntToSize(res.second - 1)];
  1175. Shape slice_shape = tensorinfo_in.slice_shape();
  1176. MS_LOG(DEBUG) << "SetParallelShape slice_shape " << parameter->ToString() << " shape "
  1177. << MakeValue(slice_shape)->ToString();
  1178. std::shared_ptr<abstract::BaseShape> parallel_shape = std::make_shared<abstract::Shape>(slice_shape);
  1179. MS_EXCEPTION_IF_NULL(parallel_shape);
  1180. // Don't modify it in-place as the pointer of this AbstractValue may used as cache key in StaticAnalysis.
  1181. auto cloned_abstract = abstract->Clone();
  1182. MS_EXCEPTION_IF_NULL(cloned_abstract);
  1183. cloned_abstract->set_shape(parallel_shape);
  1184. parameter->set_abstract(cloned_abstract);
  1185. TensorLayout tensor_layout = tensorinfo_in.tensor_layout();
  1186. ParameterPtr parameter_ptr = parameter->cast<ParameterPtr>();
  1187. MS_EXCEPTION_IF_NULL(parameter_ptr);
  1188. parameter_ptr->SetUserData<TensorLayout>(std::make_shared<TensorLayout>(tensor_layout));
  1189. }
  1190. void CoverSliceShape(const FuncGraphPtr &root) {
  1191. MS_EXCEPTION_IF_NULL(root);
  1192. auto parameters = root->parameters();
  1193. for (auto &parameter : parameters) {
  1194. MS_EXCEPTION_IF_NULL(parameter->Shape());
  1195. auto iter = g_RefMap.find(parameter);
  1196. if (iter != g_RefMap.end()) {
  1197. SetParallelShape(parameter, g_RefMap[parameter]);
  1198. continue;
  1199. }
  1200. std::pair<AnfNodePtr, int> res = FindSubGraph(root, parameter);
  1201. if (res.first == nullptr) {
  1202. MS_LOG(INFO) << "Parameter " << parameter->ToString() << " don't need to set parallel shape";
  1203. } else {
  1204. SetParallelShape(parameter, res);
  1205. MS_LOG(DEBUG) << "Parameter " << parameter->ToString() << " shape " << parameter->Shape()->ToString();
  1206. }
  1207. }
  1208. g_RefMap.clear();
  1209. }
  1210. bool ParameterIsCloned(const FuncGraphPtr &root, const AnfNodePtr &parameter_node) {
  1211. MS_EXCEPTION_IF_NULL(root);
  1212. MS_EXCEPTION_IF_NULL(parameter_node);
  1213. FuncGraphManagerPtr manager = root->manager();
  1214. MS_EXCEPTION_IF_NULL(manager);
  1215. auto cloned_parameter = parameter_node->cast<ParameterPtr>();
  1216. MS_EXCEPTION_IF_NULL(cloned_parameter);
  1217. // find the clone parameter
  1218. if (!cloned_parameter->has_default()) {
  1219. return false;
  1220. }
  1221. bool cloned = cloned_parameter->default_param()->cloned();
  1222. if (!cloned) {
  1223. return false;
  1224. }
  1225. MS_LOG(INFO) << "The parameter: " << cloned_parameter->name() << " is cloned";
  1226. return true;
  1227. }
  1228. void SetClonedTensorShapeForOptimizer(const FuncGraphPtr &root) {
  1229. MS_EXCEPTION_IF_NULL(root);
  1230. for (auto &cloned_parameter_node : root->parameters()) {
  1231. MS_EXCEPTION_IF_NULL(cloned_parameter_node);
  1232. auto cloned_parameter = cloned_parameter_node->cast<ParameterPtr>();
  1233. MS_EXCEPTION_IF_NULL(cloned_parameter);
  1234. if (!ParameterIsCloned(root, cloned_parameter_node)) {
  1235. continue;
  1236. }
  1237. // get the cloned index
  1238. int32_t cloned_index = cloned_parameter->default_param()->cloned_index();
  1239. // find the be cloned parameter
  1240. bool found_be_cloned_parameter = false;
  1241. ParameterPtr cloned_from_parameter = nullptr;
  1242. AnfNodePtr cloned_from_node = nullptr;
  1243. for (auto &be_cloned_parameter_node : root->parameters()) {
  1244. MS_EXCEPTION_IF_NULL(be_cloned_parameter_node);
  1245. auto be_cloned_parameter = be_cloned_parameter_node->cast<ParameterPtr>();
  1246. MS_EXCEPTION_IF_NULL(be_cloned_parameter);
  1247. if (!be_cloned_parameter->has_default()) {
  1248. continue;
  1249. }
  1250. const auto &param_value_cloned = be_cloned_parameter->default_param();
  1251. if (!param_value_cloned->be_cloned()) {
  1252. continue;
  1253. }
  1254. // get the be cloned index
  1255. auto &be_cloned_index = param_value_cloned->be_cloned_index();
  1256. if (std::find(be_cloned_index.begin(), be_cloned_index.end(), cloned_index) != be_cloned_index.end()) {
  1257. found_be_cloned_parameter = true;
  1258. cloned_from_parameter = be_cloned_parameter;
  1259. cloned_from_node = be_cloned_parameter_node;
  1260. }
  1261. }
  1262. if (found_be_cloned_parameter) {
  1263. // set the shape and tensor layout for cloned parameter
  1264. cloned_parameter->SetUserData<TensorLayout>(cloned_from_parameter->GetUserData<TensorLayout>());
  1265. MS_EXCEPTION_IF_NULL(cloned_parameter_node->abstract());
  1266. MS_EXCEPTION_IF_NULL(cloned_from_node->abstract());
  1267. auto cloned_abstract = cloned_parameter_node->abstract()->Clone();
  1268. MS_EXCEPTION_IF_NULL(cloned_abstract);
  1269. cloned_abstract->set_shape(cloned_from_node->abstract()->GetShapeTrack());
  1270. cloned_parameter_node->set_abstract(cloned_abstract);
  1271. MS_LOG(INFO) << "The parameter: " << cloned_parameter->name()
  1272. << " is cloned, the be cloned parameter is: " << cloned_from_parameter->name()
  1273. << ", clone index is: " << cloned_index;
  1274. } else {
  1275. MS_LOG(EXCEPTION) << "The parameter: " << cloned_parameter->name() << " is cloned, cloned index is "
  1276. << cloned_index << ", but not found the be cloned parameter";
  1277. }
  1278. }
  1279. std::string env = common::GetEnv("SLICE_ENV");
  1280. if (!env.empty()) {
  1281. MS_LOG(INFO) << "Slice tensors shape will be configured from env:" << env;
  1282. }
  1283. }
  1284. void SetVirtualDatasetStrategy(const CNodePtr &node) {
  1285. MS_EXCEPTION_IF_NULL(node);
  1286. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  1287. bool full_batch = ParallelContext::GetInstance()->full_batch();
  1288. PrimitivePtr prim = GetValueNode<PrimitivePtr>(node->input(0));
  1289. MS_EXCEPTION_IF_NULL(prim);
  1290. if (prim->name() == VIRTUAL_DATA_SET) {
  1291. CheckGlobalDeviceManager();
  1292. int32_t dev_num;
  1293. if (full_batch) {
  1294. dev_num = 1;
  1295. } else {
  1296. dev_num = SizeToInt(g_device_manager->GetDeviceListByStageId(0).size());
  1297. }
  1298. auto attrs_temp = prim->attrs();
  1299. std::vector<Shapes> shape_list = ExtractShape(node);
  1300. if (shape_list.empty()) {
  1301. MS_LOG(EXCEPTION) << "Failure:node " << node->ToString() << " failed to extract shape";
  1302. }
  1303. std::vector<ValuePtr> elements;
  1304. for (size_t i = 0; i < shape_list[0].size(); i++) {
  1305. if (shape_list[0][i].empty()) {
  1306. MS_LOG(EXCEPTION) << "shape_list[ " << i << " ].size() is zero";
  1307. }
  1308. std::vector<int32_t> input_strategy = {dev_num};
  1309. for (size_t j = 1; j < shape_list[0][i].size(); j++) {
  1310. input_strategy.push_back(1);
  1311. }
  1312. elements.push_back(MakeValue(input_strategy));
  1313. }
  1314. ValueTuplePtr strategy = std::make_shared<ValueTuple>(elements);
  1315. attrs_temp[STRATEGY] = strategy;
  1316. (void)prim->SetAttrs(attrs_temp);
  1317. }
  1318. }
  1319. void ExtractInformation(const std::vector<AnfNodePtr> &all_nodes) {
  1320. // load strategy map from checkpoint
  1321. StrategyMap stra_map;
  1322. if (StrategyCheckpoint::GetInstance().LoadCheckPointOn()) {
  1323. if (StrategyCheckpoint::GetInstance().Load(&stra_map) != SUCCESS) {
  1324. MS_LOG(EXCEPTION) << "Load strategy checkpoint failed";
  1325. }
  1326. }
  1327. for (auto &node : all_nodes) {
  1328. auto cnode = node->cast<CNodePtr>();
  1329. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1330. continue;
  1331. }
  1332. SetVirtualDatasetStrategy(cnode);
  1333. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1334. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1335. auto attrs = prim->attrs();
  1336. MS_LOG(INFO) << "extract information: node: " << node->ToString() << " prim " << prim->name();
  1337. if (IsParallelCareNode(cnode)) {
  1338. std::vector<Shapes> shape_list = ExtractShape(cnode);
  1339. if (shape_list.empty()) {
  1340. MS_LOG(EXCEPTION) << "Failure:node " << node->ToString() << " failed to extract shape";
  1341. }
  1342. OperatorInfoPtr operator_ = OperatorInstance(prim, attrs, shape_list);
  1343. if (operator_ == nullptr) {
  1344. MS_LOG(EXCEPTION) << "Failure:Primitive " << prim->name() << " OperatorInstance failed";
  1345. }
  1346. auto &inputs = cnode->inputs();
  1347. std::vector<ValuePtr> input_value;
  1348. for (size_t index = 1; index < inputs.size(); ++index) {
  1349. if (inputs[index]->isa<ValueNode>()) {
  1350. input_value.push_back(GetValueNode(inputs[index]));
  1351. } else {
  1352. input_value.emplace_back(nullptr);
  1353. }
  1354. }
  1355. StrategyPtr strategyPtr = nullptr;
  1356. (*operator_).set_input_value(input_value);
  1357. (*operator_).set_outputs_dtype(cnode->Type());
  1358. (*operator_).set_cnode(cnode);
  1359. if (prim->name() == RESHAPE) {
  1360. cnode->SetUserData<OperatorInfo>(operator_);
  1361. continue;
  1362. }
  1363. // load strategy checkpoint
  1364. // key of strategy map
  1365. std::string strategy_key_name = NodeParameterName(cnode);
  1366. bool load_strategy_from_ckpt =
  1367. StrategyCheckpoint::GetInstance().LoadCheckPointOn() && stra_map.find(strategy_key_name) != stra_map.end();
  1368. if (!StrategyFound(attrs) && !load_strategy_from_ckpt) {
  1369. MS_LOG(INFO) << "ExtractInformation: the strategy of node " << node->ToString() << " prim " << prim->name()
  1370. << " is empty, using batch parallel";
  1371. std::shared_ptr<std::vector<Dimensions>> strategy_v_ptr = operator_->GenerateBatchStrategies();
  1372. if (strategy_v_ptr == nullptr) {
  1373. MS_LOG(EXCEPTION) << "Failure:Generate batch parallel strategy failed";
  1374. }
  1375. std::vector<ValuePtr> elements;
  1376. for (size_t i = 0; i < strategy_v_ptr->size(); i++) {
  1377. elements.push_back(MakeValue((*strategy_v_ptr)[i]));
  1378. }
  1379. ValueTuplePtr strategy = std::make_shared<ValueTuple>(elements);
  1380. // display the strategy generated by batch parallel
  1381. attrs[GEN_STRATEGY] = strategy;
  1382. (void)prim->SetAttrs(attrs);
  1383. MS_LOG(INFO) << "node " << node->ToString() << " prim " << prim->name() << " batch parallel strategy is "
  1384. << attrs[GEN_STRATEGY]->ToString();
  1385. strategyPtr = NewStrategy(0, *strategy_v_ptr);
  1386. } else if (load_strategy_from_ckpt) {
  1387. strategyPtr = stra_map[strategy_key_name];
  1388. } else {
  1389. strategyPtr = ExtractStrategy(attrs);
  1390. }
  1391. if (strategyPtr != nullptr) {
  1392. if (operator_->Init(strategyPtr) == FAILED) {
  1393. MS_LOG(EXCEPTION) << "Failure:operator " << prim->name() << " init failed";
  1394. }
  1395. cnode->SetUserData<OperatorInfo>(operator_);
  1396. } else {
  1397. MS_LOG(EXCEPTION) << "ERROR:strategy_ptr is nullptr";
  1398. }
  1399. }
  1400. }
  1401. }
  1402. TensorLayout GetInputLayoutFromCNode(const std::pair<AnfNodePtr, int> &node_pair) {
  1403. CNodePtr cnode = node_pair.first->cast<CNodePtr>();
  1404. MS_EXCEPTION_IF_NULL(cnode);
  1405. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1406. MS_EXCEPTION_IF_NULL(distribute_operator);
  1407. int index = node_pair.second;
  1408. if (index > SizeToInt(distribute_operator->inputs_tensor_info().size())) {
  1409. MS_LOG(EXCEPTION) << "The index is out of range, the node_pair.second is " << index - 1 << ", the vector size is "
  1410. << distribute_operator->inputs_tensor_info().size();
  1411. }
  1412. TensorInfo tensorinfo_in = distribute_operator->inputs_tensor_info()[IntToSize(index - 1)];
  1413. TensorLayout tensorlayout_in = tensorinfo_in.tensor_layout();
  1414. return tensorlayout_in;
  1415. }
  1416. // if reshape's output connect to several primitive, return the first layout found
  1417. std::shared_ptr<TensorLayout> FindNextLayout(const CNodePtr &cnode) {
  1418. MS_EXCEPTION_IF_NULL(cnode);
  1419. MS_EXCEPTION_IF_NULL(cnode->func_graph());
  1420. FuncGraphManagerPtr manager = cnode->func_graph()->manager();
  1421. MS_EXCEPTION_IF_NULL(manager);
  1422. AnfNodeIndexSet node_set = manager->node_users()[cnode];
  1423. for (auto &node_pair : node_set) {
  1424. CNodePtr use_apply = node_pair.first->cast<CNodePtr>();
  1425. if (use_apply == nullptr || !IsValueNode<Primitive>(use_apply->input(0))) {
  1426. continue;
  1427. }
  1428. ValueNodePtr prim_anf_node = use_apply->input(0)->cast<ValueNodePtr>();
  1429. MS_EXCEPTION_IF_NULL(prim_anf_node);
  1430. PrimitivePtr node_prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1431. MS_EXCEPTION_IF_NULL(node_prim);
  1432. MS_LOG(INFO) << "FindNextLayout prim " << node_prim->name();
  1433. if (node_prim->name() == DEPEND && node_pair.second != 1) {
  1434. continue;
  1435. }
  1436. if (IsParallelCareNode(use_apply) && use_apply->HasUserData<OperatorInfo>()) {
  1437. MS_LOG(INFO) << "FindNextLayout success prim " << node_prim->name();
  1438. auto layout = GetInputLayoutFromCNode(node_pair);
  1439. return std::make_shared<TensorLayout>(layout);
  1440. }
  1441. MS_LOG(DEBUG) << "FindNextLayout failed prim " << node_prim->name() << " " << IsParallelCareNode(use_apply)
  1442. << " " << use_apply->HasUserData<OperatorInfo>();
  1443. auto layout_ptr = FindNextLayout(use_apply);
  1444. if (layout_ptr) {
  1445. return layout_ptr;
  1446. }
  1447. }
  1448. MS_LOG(WARNING) << "FindNextLayout return nullptr, if reshape is not the last primitive, there must be some error";
  1449. return nullptr;
  1450. }
  1451. std::shared_ptr<TensorLayout> GetOutputLayoutFromCNode(const CNodePtr &cnode, size_t output_index) {
  1452. MS_EXCEPTION_IF_NULL(cnode);
  1453. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1454. MS_EXCEPTION_IF_NULL(distribute_operator);
  1455. if (distribute_operator->outputs_tensor_info().size() < output_index) {
  1456. MS_LOG(EXCEPTION) << "outputs_tensor_info size is " << distribute_operator->inputs_tensor_info().size()
  1457. << ", must be less than output_index " << output_index;
  1458. }
  1459. TensorInfo tensorinfo_out = distribute_operator->outputs_tensor_info()[output_index];
  1460. TensorLayout tensorlayout_out = tensorinfo_out.tensor_layout();
  1461. return std::make_shared<TensorLayout>(tensorlayout_out);
  1462. }
  1463. std::shared_ptr<TensorLayout> FindPrevParallelCareNodeLayout(const AnfNodePtr &node, size_t output_index) {
  1464. if (!node->isa<CNode>()) {
  1465. return nullptr;
  1466. }
  1467. CNodePtr cnode = node->cast<CNodePtr>();
  1468. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1469. return nullptr;
  1470. }
  1471. if (IsParallelCareNode(cnode) && cnode->HasUserData<OperatorInfo>()) {
  1472. auto layout_ptr = GetOutputLayoutFromCNode(cnode, output_index);
  1473. if (!layout_ptr) {
  1474. MS_LOG(EXCEPTION) << "Failure:GetLayoutFromCNode failed";
  1475. }
  1476. return layout_ptr;
  1477. }
  1478. return nullptr;
  1479. }
  1480. std::shared_ptr<TensorLayout> CreateParameterLayout(const AnfNodePtr &node) {
  1481. // Create DataParallel tensor layout for parameter(support WideDeep).
  1482. CheckGlobalDeviceManager();
  1483. int32_t dev_num = SizeToInt(g_device_manager->GetDeviceListByStageId(0).size());
  1484. TensorLayout input_tensor_layout;
  1485. // create input_shape
  1486. Shapes inputs_shape = GetNodeShape(node);
  1487. Shape input_shape_array = inputs_shape[0];
  1488. if (input_shape_array.empty()) {
  1489. MS_LOG(EXCEPTION) << "Don't support reshape a scalar parameter.";
  1490. }
  1491. // create tensor_map
  1492. size_t shape_size = input_shape_array.size();
  1493. TensorMap input_tensor_map_array(SizeToInt(shape_size) - 1, -1);
  1494. input_tensor_map_array.insert(input_tensor_map_array.begin(), 0);
  1495. // create dev_matrix
  1496. Shape dev_matrix_array = {dev_num};
  1497. if (input_tensor_layout.InitFromVector(dev_matrix_array, input_tensor_map_array, input_shape_array) != SUCCESS) {
  1498. MS_LOG(EXCEPTION) << "Create tensor layout for parameter failed.";
  1499. }
  1500. return std::make_shared<TensorLayout>(input_tensor_layout);
  1501. }
  1502. std::shared_ptr<TensorLayout> FindPrevLayout(const AnfNodePtr &node) {
  1503. if (node->isa<Parameter>()) {
  1504. return CreateParameterLayout(node);
  1505. }
  1506. if (!node->isa<CNode>()) {
  1507. return nullptr;
  1508. }
  1509. CNodePtr cnode = node->cast<CNodePtr>();
  1510. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1511. return nullptr;
  1512. }
  1513. if (IsParallelCareNode(cnode) && cnode->HasUserData<OperatorInfo>()) {
  1514. auto layout_ptr = GetOutputLayoutFromCNode(cnode, 0);
  1515. if (!layout_ptr) {
  1516. MS_LOG(EXCEPTION) << "Failure:GetLayoutFromCNode failed";
  1517. }
  1518. return layout_ptr;
  1519. }
  1520. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1521. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1522. if (prim->name() == TUPLE_GETITEM) {
  1523. auto tuple_index = GetTupleGetItemIndex(cnode);
  1524. auto layout_ptr = FindPrevParallelCareNodeLayout(cnode->input(1), IntToSize(tuple_index));
  1525. if (!layout_ptr) {
  1526. MS_LOG(EXCEPTION)
  1527. << " Failure:FindPrevLayout failed, tuple_getitem before reshape, but there does not exit a parallel care node "
  1528. "before tuple_getitem!";
  1529. }
  1530. return layout_ptr;
  1531. }
  1532. for (size_t index = 0; index < cnode->inputs().size(); ++index) {
  1533. if (prim->name() == DEPEND && index != 1) {
  1534. continue;
  1535. }
  1536. auto layout_ptr = FindPrevLayout(cnode->inputs()[index]);
  1537. if (!layout_ptr) {
  1538. continue;
  1539. }
  1540. return layout_ptr;
  1541. }
  1542. MS_LOG(WARNING) << "FindPrevLayout return nullptr, if reshape is not the first primitive, there must be some error";
  1543. return nullptr;
  1544. }
  1545. void ReshapeInit(const std::vector<AnfNodePtr> &all_nodes) {
  1546. for (auto &node : all_nodes) {
  1547. auto cnode = node->cast<CNodePtr>();
  1548. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1549. continue;
  1550. }
  1551. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  1552. if (!IsParallelCareNode(cnode) || !cnode->HasUserData<OperatorInfo>()) {
  1553. continue;
  1554. }
  1555. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  1556. MS_EXCEPTION_IF_NULL(prim);
  1557. OperatorInfoPtr operator_info = cnode->GetUserData<OperatorInfo>();
  1558. if (operator_info == nullptr) {
  1559. MS_LOG(EXCEPTION) << "Failure:Primitive " << prim->ToString() << " OperatorInstance is nullptr";
  1560. }
  1561. if (prim->name() != RESHAPE) {
  1562. continue;
  1563. }
  1564. auto attrs = prim->attrs();
  1565. if (StrategyFound(attrs)) {
  1566. MS_LOG(EXCEPTION) << "Setting strategy for Reshape goes for nothing!";
  1567. }
  1568. MS_ASSERT(cnode->inputs().size() == 3);
  1569. auto prev_layout_ptr = FindPrevLayout(cnode->input(1));
  1570. if (prev_layout_ptr) {
  1571. auto reshape_info_ptr = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  1572. reshape_info_ptr->SetInputLayout(*prev_layout_ptr);
  1573. }
  1574. auto next_layout_ptr = FindNextLayout(cnode);
  1575. if (next_layout_ptr) {
  1576. auto reshape_info_ptr = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  1577. reshape_info_ptr->SetOutputLayout(*next_layout_ptr);
  1578. }
  1579. if (operator_info->Init(nullptr) == FAILED) {
  1580. MS_LOG(EXCEPTION) << "Failure:operator " << prim->ToString() << " init failed";
  1581. }
  1582. }
  1583. }
  1584. CNodePtr FindLossCNode(const FuncGraphPtr &func_graph) {
  1585. MS_EXCEPTION_IF_NULL(func_graph);
  1586. CNodePtr return_node = func_graph->get_return();
  1587. MS_EXCEPTION_IF_NULL(return_node);
  1588. if (return_node->size() < 2) {
  1589. MS_LOG(EXCEPTION) << "Failure: " << return_node->ToString() << " size is smaller than 2";
  1590. }
  1591. AnfNodePtr pre_node = return_node->input(1);
  1592. MS_EXCEPTION_IF_NULL(pre_node);
  1593. auto pre_cnode = pre_node->cast<CNodePtr>();
  1594. if (pre_cnode == nullptr) {
  1595. return nullptr;
  1596. }
  1597. auto current_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  1598. // return -> cast
  1599. if (current_prim->name() == CAST && !pre_cnode->HasUserData<OperatorInfo>()) {
  1600. pre_cnode = pre_cnode->input(1)->cast<CNodePtr>();
  1601. MS_EXCEPTION_IF_NULL(pre_cnode);
  1602. current_prim = GetValueNode<PrimitivePtr>(pre_cnode->input(0));
  1603. }
  1604. // notice: the GetNext op has not input
  1605. if (INVALID_LOSS_OPS.find(current_prim->name()) != INVALID_LOSS_OPS.end()) {
  1606. MS_LOG(INFO) << "The loss is: " << current_prim->name();
  1607. return pre_cnode;
  1608. }
  1609. // size of common cnode is larger than 1
  1610. if (pre_cnode->size() < 2) {
  1611. MS_LOG(EXCEPTION) << pre_cnode->ToString() << " size( " << pre_cnode->inputs().size() << " ) is smaller than 2";
  1612. }
  1613. // return -> tuple_getitem -> loss
  1614. if (current_prim->name() == TUPLE_GETITEM) {
  1615. AnfNodePtr pre_pre_node = pre_cnode->input(1);
  1616. MS_EXCEPTION_IF_NULL(pre_pre_node);
  1617. auto pre_pre_cnode = pre_pre_node->cast<CNodePtr>();
  1618. auto value = pre_pre_cnode->input(0)->cast<ValueNodePtr>();
  1619. MS_EXCEPTION_IF_NULL(value);
  1620. PrimitivePtr prim = value->value()->cast<PrimitivePtr>();
  1621. MS_EXCEPTION_IF_NULL(prim);
  1622. MS_LOG(DEBUG) << "The loss name is " << prim->name();
  1623. return pre_pre_cnode;
  1624. }
  1625. // return -> make_tuple
  1626. if (current_prim->name() == MAKE_TUPLE) {
  1627. MS_LOG(EXCEPTION) << "The loss have make_tuple, it is not supported";
  1628. }
  1629. // return -> loss
  1630. MS_LOG(DEBUG) << "The loss name is " << current_prim->name();
  1631. return pre_cnode;
  1632. }
  1633. TensorLayouts GetLossNodeGradOutputLayout(const CNodePtr &loss_cnode) {
  1634. TensorLayouts ret;
  1635. MS_EXCEPTION_IF_NULL(loss_cnode);
  1636. AnfNodePtr node = loss_cnode->cast<AnfNodePtr>();
  1637. MS_EXCEPTION_IF_NULL(node);
  1638. LossNodeInfo node_info = GetLossNodeInfo(node);
  1639. ValueNodePtr prim_anf_node = loss_cnode->input(0)->cast<ValueNodePtr>();
  1640. MS_EXCEPTION_IF_NULL(prim_anf_node);
  1641. PrimitivePtr prim = prim_anf_node->value()->cast<PrimitivePtr>();
  1642. MS_EXCEPTION_IF_NULL(prim);
  1643. if (INVALID_LOSS_OPS.find(prim->name()) != INVALID_LOSS_OPS.end()) {
  1644. MS_LOG(WARNING) << "The loss name is: " << prim->name() << ", do nothing for split sens now";
  1645. return ret;
  1646. }
  1647. OperatorInfoPtr operator_info = loss_cnode->GetUserData<OperatorInfo>();
  1648. MS_EXCEPTION_IF_NULL(operator_info);
  1649. TensorInfo loss_grad_tensor_info;
  1650. size_t op_output_size = operator_info->outputs_tensor_info().size();
  1651. MS_LOG(INFO) << "The loss name is " << operator_info->name() << ", the has tuple item is "
  1652. << node_info.has_tuple_getitem << ", the output size is " << op_output_size << ", the dout_index is "
  1653. << node_info.dout_index;
  1654. if ((op_output_size == 0) || (op_output_size <= IntToSize(node_info.dout_index))) {
  1655. MS_LOG(EXCEPTION) << "The index is " << node_info.dout_index << ", but the size of outputs is " << op_output_size;
  1656. }
  1657. if (!node_info.has_tuple_getitem && (op_output_size > 1)) {
  1658. MS_LOG(EXCEPTION) << "Currently, it is not supported that the sens is a tuple.";
  1659. }
  1660. loss_grad_tensor_info = operator_info->outputs_tensor_info()[IntToSize(node_info.dout_index)];
  1661. ret.push_back(loss_grad_tensor_info.tensor_layout());
  1662. return ret;
  1663. }
  1664. void SplitSens(const CNodePtr &grad_sens_node, const TensorLayout &loss_grad_layout) {
  1665. MS_EXCEPTION_IF_NULL(grad_sens_node);
  1666. if (grad_sens_node->size() <= 1) {
  1667. MS_LOG(EXCEPTION) << "The size of grad sens node is smaller than 2";
  1668. }
  1669. AnfNodePtr sens_tensor_node = grad_sens_node->input(1);
  1670. MS_EXCEPTION_IF_NULL(sens_tensor_node);
  1671. Shapes sens_shapes = GetNodeShape(sens_tensor_node);
  1672. if (sens_shapes.size() != 1) {
  1673. MS_LOG(EXCEPTION) << "GetNodeShape for sens_tensor_node, output size is not 1";
  1674. }
  1675. // If the shape of sens tensor is [] or [1], no need to split it.
  1676. Shape sens_shape = sens_shapes[0];
  1677. if (sens_shape.empty() || ((sens_shape.size() == 1) && (sens_shape[0] == 1))) {
  1678. if (sens_tensor_node->isa<Parameter>()) {
  1679. auto sens_tensor_param = sens_tensor_node->cast<ParameterPtr>();
  1680. MS_LOG(DEBUG) << "loss layout " << loss_grad_layout.ToString();
  1681. sens_tensor_param->SetUserData<TensorLayout>(std::make_shared<TensorLayout>(loss_grad_layout));
  1682. }
  1683. MS_LOG(INFO) << "The shape of sens is " << ShapeToString(sens_shape) << ", no need to split sens";
  1684. return;
  1685. }
  1686. auto loss_shape = loss_grad_layout.tensor_shape().array();
  1687. if (loss_shape != sens_shape) {
  1688. MS_LOG(EXCEPTION) << "The shape of sens is not equal to loss output, it is unsupported now. Sens shape is "
  1689. << ShapeToString(sens_shape) << ", loss shape is " << ShapeToString(loss_shape);
  1690. }
  1691. MS_LOG(INFO) << "The shape of sens is " << ShapeToString(sens_shape) << ", split it.";
  1692. if (!IsValueNode<Tensor>(sens_tensor_node)) {
  1693. if (sens_tensor_node->isa<Parameter>()) {
  1694. MS_LOG(DEBUG) << "loss layout " << loss_grad_layout.ToString();
  1695. AbstractBasePtr abstract = sens_tensor_node->abstract();
  1696. MS_EXCEPTION_IF_NULL(abstract);
  1697. auto slice_shape = loss_grad_layout.slice_shape().array();
  1698. std::shared_ptr<abstract::BaseShape> parallel_shape = std::make_shared<abstract::Shape>(slice_shape);
  1699. MS_EXCEPTION_IF_NULL(parallel_shape);
  1700. auto cloned_abstract = abstract->Clone();
  1701. MS_EXCEPTION_IF_NULL(cloned_abstract);
  1702. cloned_abstract->set_shape(parallel_shape);
  1703. sens_tensor_node->set_abstract(cloned_abstract);
  1704. auto sens_tensor_param = sens_tensor_node->cast<ParameterPtr>();
  1705. sens_tensor_param->SetUserData<TensorLayout>(std::make_shared<TensorLayout>(loss_grad_layout));
  1706. return;
  1707. }
  1708. MS_LOG(EXCEPTION) << "The type of sens node is not Tensor or Parameter, it is unsupported now.";
  1709. }
  1710. // Use _GetTensorSlice operator to split the sens tensor
  1711. FuncGraphPtr func_graph = grad_sens_node->func_graph(); // only cnode can get the graph
  1712. MS_EXCEPTION_IF_NULL(func_graph);
  1713. Operator op = CreateGetTensorSliceOp(loss_grad_layout);
  1714. InsertGetTensorSliceOp(op, grad_sens_node, func_graph, 1, SPLIT_SENS);
  1715. }
  1716. void InsertForwardOps(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1717. MS_EXCEPTION_IF_NULL(distribute_operator);
  1718. MS_EXCEPTION_IF_NULL(cnode);
  1719. OperatorVector forward_op = distribute_operator->forward_op();
  1720. if (!forward_op.empty()) {
  1721. MS_LOG(INFO) << "Insert forward op for " << distribute_operator->name();
  1722. ForwardCommunication(forward_op, cnode);
  1723. }
  1724. }
  1725. void StepReplace(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1726. MS_EXCEPTION_IF_NULL(distribute_operator);
  1727. MS_EXCEPTION_IF_NULL(cnode);
  1728. // StepReplaceOp
  1729. OperatorVector replace_op = distribute_operator->replace_op();
  1730. if (!replace_op.empty()) {
  1731. MS_LOG(INFO) << "StepReplaceOp " << cnode->ToString();
  1732. StepReplaceOp(replace_op, cnode);
  1733. }
  1734. // StepReplaceGraph: after calling StepReplaceGraph, cnode can not be used anymore.
  1735. ReplaceGraphPtr replace_graph = distribute_operator->replace_graph(cnode);
  1736. if (!replace_op.empty() && replace_graph) {
  1737. MS_LOG(EXCEPTION) << "Only one of replace_op or replace_op can be used";
  1738. }
  1739. if (replace_graph) {
  1740. MS_LOG(INFO) << "StepReplaceGraph " << cnode->ToString();
  1741. StepReplaceGraph(replace_graph, cnode);
  1742. }
  1743. }
  1744. void HandleDropoutNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1745. MS_EXCEPTION_IF_NULL(distribute_operator);
  1746. MS_EXCEPTION_IF_NULL(cnode);
  1747. std::string op_name = distribute_operator->name();
  1748. if (op_name.find(DROPOUT_DO_MASK) == std::string::npos) {
  1749. return;
  1750. }
  1751. DropoutDoMaskInfoPtr dropout_do_mask = std::dynamic_pointer_cast<DropoutDoMaskInfo>(distribute_operator);
  1752. MS_EXCEPTION_IF_NULL(dropout_do_mask);
  1753. std::vector<Operator> replace_op = dropout_do_mask->GetDropoutGenMaskReplaceOp(cnode);
  1754. if (replace_op.empty()) {
  1755. MS_LOG(DEBUG) << "No need to replace dropout_gen_mask";
  1756. return;
  1757. }
  1758. if (cnode->inputs().size() != DROPOUT_DO_MASK_CNODE_INPUT_SIZE) {
  1759. MS_LOG(EXCEPTION) << "The size of drop out do mask cnode's input is not " << DROPOUT_DO_MASK_CNODE_INPUT_SIZE;
  1760. }
  1761. ReplaceOneOp(replace_op[0], cnode->input(DROPOUT_GEN_MASK_INDEX)->cast<CNodePtr>());
  1762. }
  1763. void HandleSpecialNode(const OperatorInfoPtr &distribute_operator, const CNodePtr &cnode) {
  1764. HandleDropoutNode(distribute_operator, cnode);
  1765. }
  1766. std::set<FuncGraphPtr> FindForwardGraphByRootNodes(const AnfNodeSet &root_all_nodes) {
  1767. // J->CNode->Graph
  1768. std::set<FuncGraphPtr> graph_set;
  1769. for (auto &node : root_all_nodes) {
  1770. MS_EXCEPTION_IF_NULL(node);
  1771. if (!node->isa<CNode>()) {
  1772. continue;
  1773. }
  1774. auto cnode = node->cast<CNodePtr>();
  1775. if ((cnode->size() < 2) || !IsValueNode<Primitive>(cnode->input(0))) {
  1776. continue;
  1777. }
  1778. auto expect_j_prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1779. if (expect_j_prim->name() != J) {
  1780. continue;
  1781. }
  1782. if (IsValueNode<FuncGraph>(cnode->input(1))) {
  1783. auto graph = GetValueNode<FuncGraphPtr>(cnode->input(1));
  1784. MS_LOG(DEBUG) << "Find the forward graph success";
  1785. graph_set.insert(graph);
  1786. }
  1787. }
  1788. return graph_set;
  1789. }
  1790. void StepSplitSens(const std::pair<CNodePtr, CNodePtr> &sens_loss_pair) {
  1791. CNodePtr sens_node = sens_loss_pair.first;
  1792. CNodePtr loss_node = sens_loss_pair.second;
  1793. auto loss_grad_layout = GetLossNodeGradOutputLayout(loss_node);
  1794. if (!loss_grad_layout.empty()) {
  1795. SplitSens(sens_node, loss_grad_layout[0]);
  1796. }
  1797. }
  1798. // Sens node satisfies the following conditions: cnode(sens)-->cnode(tuple_getitem)-->cnode-->cnode(J)
  1799. std::vector<std::pair<CNodePtr, CNodePtr>> GetSensLossPairs(const FuncGraphPtr &root) {
  1800. MS_EXCEPTION_IF_NULL(root);
  1801. std::vector<std::pair<CNodePtr, CNodePtr>> sens_loss_pairs;
  1802. for (auto &node : root->nodes()) {
  1803. if (!node->isa<CNode>()) {
  1804. continue;
  1805. }
  1806. // cnode(sens)-->cnode(tuple_getitem)
  1807. auto sens_cnode = node->cast<CNodePtr>();
  1808. AnfNodePtr expect_tuple_getitem = sens_cnode->input(0);
  1809. MS_EXCEPTION_IF_NULL(expect_tuple_getitem);
  1810. if (!expect_tuple_getitem->isa<CNode>()) {
  1811. continue;
  1812. }
  1813. auto expect_tuple_getitem_cnode = expect_tuple_getitem->cast<CNodePtr>();
  1814. if (!IsSomePrimitive(expect_tuple_getitem_cnode, TUPLE_GETITEM)) {
  1815. continue;
  1816. }
  1817. // cnode(sens)-->cnode(tuple_getitem)-->cnode
  1818. AnfNodePtr expect_anonymous = expect_tuple_getitem_cnode->input(1);
  1819. MS_EXCEPTION_IF_NULL(expect_anonymous);
  1820. if (!expect_anonymous->isa<CNode>()) {
  1821. continue;
  1822. }
  1823. // cnode(sens)-->cnode(tuple_getitem)-->cnode-->cnode(J)
  1824. auto expect_anonymous_cnode = expect_anonymous->cast<CNodePtr>();
  1825. AnfNodePtr expect_j = expect_anonymous_cnode->input(0);
  1826. MS_EXCEPTION_IF_NULL(expect_j);
  1827. if (!expect_j->isa<CNode>()) {
  1828. continue;
  1829. }
  1830. auto expect_j_cnode = expect_j->cast<CNodePtr>();
  1831. if (!IsSomePrimitive(expect_j_cnode, J)) {
  1832. continue;
  1833. }
  1834. if (!IsValueNode<FuncGraph>(expect_j_cnode->input(1))) {
  1835. MS_LOG(EXCEPTION) << "Sens can't find the corresponding graph.";
  1836. }
  1837. auto func_graph = GetValueNode<FuncGraphPtr>(expect_j_cnode->input(1));
  1838. auto loss_cnode = FindLossCNode(func_graph);
  1839. if (loss_cnode == nullptr) {
  1840. MS_LOG(WARNING) << "Can not find the loss cnode";
  1841. continue;
  1842. }
  1843. std::pair<CNodePtr, CNodePtr> sens_loss_pair = std::make_pair(sens_cnode, loss_cnode);
  1844. sens_loss_pairs.push_back(sens_loss_pair);
  1845. }
  1846. return sens_loss_pairs;
  1847. }
  1848. void ParallelCommunication(const FuncGraphPtr &root, const std::vector<AnfNodePtr> &all_nodes,
  1849. const FuncGraphManagerPtr &manager) {
  1850. MS_EXCEPTION_IF_NULL(root);
  1851. MS_EXCEPTION_IF_NULL(manager);
  1852. TensorRedistribution tensor_redistribution;
  1853. std::vector<std::pair<CNodePtr, CNodePtr>> sens_loss_pairs = GetSensLossPairs(root);
  1854. bool has_backward = !sens_loss_pairs.empty();
  1855. // split sens must before inserting the operators.
  1856. for (auto &pair : sens_loss_pairs) {
  1857. // If the shape of grad-sens tensor is not [] or [1], use get tensor slice to handel it.
  1858. // If the type of sens node is not Tensor, it is unsupported now, do nothing default.
  1859. StepSplitSens(pair);
  1860. }
  1861. for (auto &node : all_nodes) {
  1862. MS_EXCEPTION_IF_NULL(node);
  1863. if (node->isa<CNode>()) {
  1864. auto cnode = node->cast<CNodePtr>();
  1865. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1866. continue;
  1867. }
  1868. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1869. if (distribute_operator == nullptr) {
  1870. continue;
  1871. }
  1872. // insert forward ops
  1873. InsertForwardOps(distribute_operator, cnode);
  1874. // insert redistribution ops
  1875. StepRedistribution(cnode, distribute_operator, cnode, tensor_redistribution, cnode);
  1876. // insert backward ops
  1877. if (has_backward) {
  1878. BackwardCommunication(distribute_operator, cnode, sens_loss_pairs);
  1879. }
  1880. HandleSpecialNode(distribute_operator, cnode);
  1881. } else if (IsValueNode<Tensor>(node)) {
  1882. StepSplitTensor(node, manager);
  1883. }
  1884. }
  1885. for (auto &node : all_nodes) {
  1886. MS_EXCEPTION_IF_NULL(node);
  1887. if (node->isa<CNode>()) {
  1888. auto cnode = node->cast<CNodePtr>();
  1889. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1890. continue;
  1891. }
  1892. OperatorInfoPtr distribute_operator = GetDistributeOperator(cnode);
  1893. if (distribute_operator == nullptr) {
  1894. continue;
  1895. }
  1896. // StepReplace
  1897. StepReplace(distribute_operator, cnode);
  1898. }
  1899. }
  1900. }
  1901. namespace {
  1902. void RevertSymbolicKeyInstance(const FuncGraphPtr &root, const AnfNodePtr &node) {
  1903. MS_EXCEPTION_IF_NULL(root);
  1904. MS_EXCEPTION_IF_NULL(node);
  1905. auto symbolic_key = GetValueNode<SymbolicKeyInstancePtr>(node);
  1906. MS_EXCEPTION_IF_NULL(symbolic_key);
  1907. auto all_upstream_node = root->manager()->node_users()[node];
  1908. for (auto &upstream_node : all_upstream_node) {
  1909. FuncGraphPtr fg = upstream_node.first->func_graph();
  1910. if (symbolic_key->node()->isa<Parameter>()) {
  1911. for (auto &param : root->parameters()) {
  1912. if (*param == *symbolic_key->node()) {
  1913. AnfNodePtr reverted_node = root->NewCNode({NewValueNode(prim::kPrimEmbed), param});
  1914. MS_EXCEPTION_IF_NULL(reverted_node);
  1915. MS_LOG(DEBUG) << "before replace " << node->ToString() << " to node " << reverted_node->DebugString();
  1916. (void)fg->manager()->Replace(node, reverted_node);
  1917. MS_LOG(DEBUG) << "revert node " << node->ToString() << " to node " << reverted_node->DebugString();
  1918. }
  1919. }
  1920. }
  1921. }
  1922. }
  1923. } // namespace
  1924. void HandleSymbolicKeyInstance(const FuncGraphPtr &root, const std::vector<AnfNodePtr> &all_nodes) {
  1925. MS_EXCEPTION_IF_NULL(root);
  1926. for (auto &node : all_nodes) {
  1927. // revert back SymbolicKeyInstance to embed() primitive
  1928. if (IsValueNode<SymbolicKeyInstance>(node)) {
  1929. RevertSymbolicKeyInstance(root, node);
  1930. continue;
  1931. }
  1932. }
  1933. }
  1934. std::string NodeParameterName(const CNodePtr &node) {
  1935. std::vector<AnfNodePtr> node_inputs{node->inputs()};
  1936. for (auto input : node_inputs) {
  1937. if (input->isa<Parameter>()) {
  1938. auto input_parameter = input->cast<ParameterPtr>();
  1939. if (input_parameter->has_default()) {
  1940. const auto &param_value = input_parameter->default_param();
  1941. if (param_value->requires_grad()) {
  1942. return param_value->name();
  1943. }
  1944. }
  1945. }
  1946. }
  1947. return "";
  1948. }
  1949. void CheckpointStrategy(const FuncGraphPtr &func_graph) {
  1950. MS_EXCEPTION_IF_NULL(func_graph);
  1951. MS_LOG(DEBUG) << "Save strategy to checkpoint begin";
  1952. StrategyMap stra_map;
  1953. auto ret = func_graph->get_return();
  1954. auto all_nodes = DeepScopedGraphSearch(ret);
  1955. for (auto &node : all_nodes) {
  1956. MS_EXCEPTION_IF_NULL(node);
  1957. auto cnode = node->cast<CNodePtr>();
  1958. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  1959. continue;
  1960. }
  1961. std::string param_name = NodeParameterName(cnode);
  1962. if (param_name.empty()) {
  1963. continue;
  1964. }
  1965. PrimitivePtr prim = GetValueNode<PrimitivePtr>(cnode->input(0));
  1966. MS_EXCEPTION_IF_NULL(prim);
  1967. OperatorInfoPtr operator_info = cnode->GetUserData<OperatorInfo>();
  1968. if (operator_info) {
  1969. if (operator_info->name().find(RESHAPEINFO) != std::string::npos) {
  1970. continue;
  1971. }
  1972. StrategyPtr strategyPtr = operator_info->strategy();
  1973. MS_EXCEPTION_IF_NULL(node->scope());
  1974. stra_map[param_name] = strategyPtr;
  1975. }
  1976. }
  1977. if (StrategyCheckpoint::GetInstance().Save(stra_map) != SUCCESS) {
  1978. MS_LOG(EXCEPTION) << "Save strategy checkpoint failed";
  1979. }
  1980. }
  1981. void SetForwardFlag(const std::vector<AnfNodePtr> &all_nodes) {
  1982. for (auto &node : all_nodes) {
  1983. MS_EXCEPTION_IF_NULL(node);
  1984. if (!node->isa<CNode>()) {
  1985. continue;
  1986. }
  1987. auto cnode = node->cast<CNodePtr>();
  1988. if (!IsValueNode<Primitive>(cnode->input(0))) {
  1989. continue;
  1990. }
  1991. // CNode is globally unique.
  1992. MS_LOG(DEBUG) << "Set forward flag " << cnode->DebugString() << ".";
  1993. cnode->set_in_forward_flag(true);
  1994. }
  1995. }
  1996. void SetForwardFlag(const AnfNodeSet &all_nodes) {
  1997. for (auto &node : all_nodes) {
  1998. MS_EXCEPTION_IF_NULL(node);
  1999. if (!node->isa<CNode>()) {
  2000. continue;
  2001. }
  2002. auto cnode = node->cast<CNodePtr>();
  2003. if (!IsValueNode<Primitive>(cnode->input(0))) {
  2004. continue;
  2005. }
  2006. // CNode is globally unique.
  2007. cnode->set_in_forward_flag(true);
  2008. }
  2009. }
  2010. std::set<FuncGraphPtr> ForwardGraph(const FuncGraphPtr &root) {
  2011. MS_EXCEPTION_IF_NULL(root);
  2012. const auto &all_nodes = root->nodes();
  2013. std::set<FuncGraphPtr> graph_set = FindForwardGraphByRootNodes(all_nodes);
  2014. return graph_set;
  2015. }
  2016. std::vector<AnfNodePtr> FindRootForwardCNode(const FuncGraphPtr &graph, const AnfNodeSet &all_nodes) {
  2017. MS_EXCEPTION_IF_NULL(graph);
  2018. std::vector<AnfNodePtr> root_forward_nodes;
  2019. auto loss_cnode = FindLossCNode(graph);
  2020. if (loss_cnode == nullptr) {
  2021. MS_LOG(WARNING) << "Can not find the loss cnode";
  2022. return root_forward_nodes;
  2023. }
  2024. auto loss_cnode_id = loss_cnode->UniqueIdThroughCopy();
  2025. for (auto &node : all_nodes) {
  2026. MS_EXCEPTION_IF_NULL(node);
  2027. if (!node->isa<CNode>()) {
  2028. continue;
  2029. }
  2030. auto cnode = node->cast<CNodePtr>();
  2031. auto root_node_id = node->UniqueIdThroughCopy();
  2032. if (loss_cnode_id == root_node_id) {
  2033. root_forward_nodes = DeepLinkedGraphSearch(cnode);
  2034. break;
  2035. }
  2036. }
  2037. return root_forward_nodes;
  2038. }
  2039. void MarkForwardCNode(const FuncGraphPtr &root) {
  2040. MS_EXCEPTION_IF_NULL(root);
  2041. auto all_nodes = root->nodes();
  2042. std::set<FuncGraphPtr> graph_set = FindForwardGraphByRootNodes(all_nodes);
  2043. if (graph_set.empty()) {
  2044. MS_LOG(INFO) << "Can not find the forward graph, so mark the ops in root graph";
  2045. SetForwardFlag(all_nodes);
  2046. } else {
  2047. for (auto &func_graph : graph_set) {
  2048. MS_LOG(INFO) << "The sub graph size of root is " << root->func_graphs_used().size();
  2049. auto return_node = func_graph->get_return();
  2050. MS_EXCEPTION_IF_NULL(return_node);
  2051. auto all_dfs_nodes = DeepLinkedGraphSearch(return_node);
  2052. SetForwardFlag(all_dfs_nodes);
  2053. auto root_forward_nodes = FindRootForwardCNode(func_graph, all_nodes);
  2054. if (root_forward_nodes.empty()) {
  2055. continue;
  2056. }
  2057. // Mark forward flag for the nodes in root graph.
  2058. SetForwardFlag(root_forward_nodes);
  2059. }
  2060. }
  2061. }
  2062. Status ParallelInit() {
  2063. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  2064. int32_t device_num = ParallelContext::GetInstance()->device_num();
  2065. int32_t global_rank = ParallelContext::GetInstance()->global_rank();
  2066. std::string backend = ParallelContext::GetInstance()->communication_backend();
  2067. std::string world_group;
  2068. if (backend == HCCL_BACKEND) {
  2069. world_group = HCCL_WORLD_GROUP;
  2070. } else if (backend == NCCL_BACKEND) {
  2071. world_group = NCCL_WORLD_GROUP;
  2072. } else {
  2073. MS_LOG(EXCEPTION) << "Invalid communication backend: " << backend;
  2074. }
  2075. uint32_t world_rank_size = 0;
  2076. if (!ParallelContext::GetInstance()->device_num_is_set()) {
  2077. if (!CommManager::GetInstance().GetRankSize(world_group, &world_rank_size)) {
  2078. MS_LOG(EXCEPTION) << "Get rank size failed";
  2079. }
  2080. device_num = UintToInt(world_rank_size);
  2081. MS_LOG(INFO) << "Get device num from communication model, the device num is " << device_num;
  2082. }
  2083. uint32_t rank_id = 0;
  2084. if (!ParallelContext::GetInstance()->global_rank_is_set()) {
  2085. if (!CommManager::GetInstance().GetRankID(world_group, &rank_id)) {
  2086. MS_LOG(EXCEPTION) << "Get rank id failed";
  2087. }
  2088. global_rank = UintToInt(rank_id);
  2089. MS_LOG(INFO) << "Get global rank from communication model, the global rank is " << global_rank;
  2090. }
  2091. if (!InitDevice(device_num, global_rank, backend)) {
  2092. MS_LOG(ERROR) << "Init device failed";
  2093. return FAILED;
  2094. }
  2095. MS_LOG(INFO) << "The parallel context: dev num: " << device_num << ", global rank: " << global_rank
  2096. << ", backend: " << backend << ", mirror_mean: " << ParallelContext::GetInstance()->mirror_mean()
  2097. << ", cast_before_mirror: " << ParallelContext::GetInstance()->cast_before_mirror();
  2098. return SUCCESS;
  2099. }
  2100. bool StepParallel(const FuncGraphPtr &root, const opt::OptimizerPtr &optimizer) {
  2101. MS_EXCEPTION_IF_NULL(root);
  2102. MS_EXCEPTION_IF_NULL(optimizer);
  2103. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  2104. std::string parallel_mode = ParallelContext::GetInstance()->parallel_mode();
  2105. // assume no change to graph
  2106. bool changes = false;
  2107. // control whether use model_parallel mode
  2108. if (!root->has_flag(AUTO_PARALLEL) || ((parallel_mode != AUTO_PARALLEL) && (parallel_mode != SEMI_AUTO_PARALLEL)) ||
  2109. (root->has_flag(SEMI_AUTO_PARALLEL_RUN_ONCE_ONLY))) {
  2110. if (!root->has_flag(CHECK_SET_STRATEGY_VALID_ONCE_ONLY)) {
  2111. if (HasStrategy(root)) {
  2112. MS_LOG(INFO) << "Strategies ignored in " << parallel_mode
  2113. << ", set_strategy() only valid in [semi_]auto_parallel.";
  2114. }
  2115. root->set_flag(CHECK_SET_STRATEGY_VALID_ONCE_ONLY, true);
  2116. }
  2117. return changes;
  2118. }
  2119. struct timeval start_time, end_time;
  2120. (void)gettimeofday(&start_time, nullptr);
  2121. MS_LOG(INFO) << "Now entering step parallel";
  2122. DumpGraph(root, std::string(STEP_PARALLEL_BEGIN));
  2123. pipeline::ResourceBasePtr res = optimizer->resource();
  2124. MS_EXCEPTION_IF_NULL(res);
  2125. FuncGraphManagerPtr manager = res->manager();
  2126. MS_EXCEPTION_IF_NULL(manager);
  2127. AnfNodePtr ret = root->get_return();
  2128. MS_EXCEPTION_IF_NULL(ret);
  2129. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  2130. std::reverse(all_nodes.begin(), all_nodes.end());
  2131. if (parallel_mode != AUTO_PARALLEL) {
  2132. TOTAL_OPS = 0;
  2133. if (ParallelInit() != SUCCESS) {
  2134. MS_LOG(EXCEPTION) << "Parallel init failed";
  2135. }
  2136. // mark the forward cnodes, parallel only care these nodes
  2137. MarkForwardCNode(root);
  2138. if (FindCommunicationOp(all_nodes)) {
  2139. MS_LOG(EXCEPTION) << "The graph contain communication op";
  2140. }
  2141. // extract shape and strategy, set operator_info
  2142. ExtractInformation(all_nodes);
  2143. ReshapeInit(all_nodes);
  2144. }
  2145. // save strategy as checkpoint for multi-train
  2146. if (StrategyCheckpoint::GetInstance().SaveCheckPointOn()) {
  2147. CheckpointStrategy(root);
  2148. }
  2149. HandleSymbolicKeyInstance(root, all_nodes);
  2150. // cover Parallel shape
  2151. CoverSliceShape(root);
  2152. // set the shape for optimizer's clone tensor
  2153. SetClonedTensorShapeForOptimizer(root);
  2154. // ForwardCommunication BackwardCommunication TensorRedistribution
  2155. ParallelCommunication(root, all_nodes, manager);
  2156. DumpGraph(root, std::string(STEP_PARALLEL_END));
  2157. // step parallel only run once
  2158. root->set_flag(SEMI_AUTO_PARALLEL_RUN_ONCE_ONLY, true);
  2159. res->results()[pipeline::kStepParallelGraph] = root;
  2160. // in auto parallel mode, no need to check if stategies set
  2161. root->set_flag(CHECK_SET_STRATEGY_VALID_ONCE_ONLY, true);
  2162. (void)gettimeofday(&end_time, nullptr);
  2163. uint64_t time = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec);
  2164. time += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec);
  2165. MS_LOG(INFO) << "Now leaving step parallel, used time: " << time << " us";
  2166. return changes;
  2167. }
  2168. // Needed by rec_parser
  2169. std::vector<std::string> ExtractInputsTensorName(const CNodePtr &node) {
  2170. std::vector<std::string> name_inputs;
  2171. std::vector<AnfNodePtr> all_inputs = node->inputs();
  2172. std::vector<AnfNodePtr> node_inputs{all_inputs.begin() + 1, all_inputs.end()};
  2173. std::string node_id = node->UniqueId();
  2174. name_inputs.push_back(node_id);
  2175. for (auto &input : node_inputs) {
  2176. std::string name = input->UniqueId();
  2177. name_inputs.push_back(name);
  2178. }
  2179. return name_inputs;
  2180. }
  2181. } // namespace parallel
  2182. } // namespace mindspore