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

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