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.

convert.cc 64 kB

6 years ago
6 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  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 "transform/graph_ir/convert.h"
  17. #include <inttypes.h>
  18. #include <algorithm>
  19. #include <stack>
  20. #include "utils/utils.h"
  21. #include "frontend/operator/ops.h"
  22. #include "utils/log_adapter.h"
  23. #include "ir/graph_utils.h"
  24. #include "utils/symbolic.h"
  25. #include "utils/config_manager.h"
  26. #include "utils/convert_utils.h"
  27. #include "utils/ms_context.h"
  28. #include "transform/graph_ir/op_adapter_map.h"
  29. #include "ops/state_ops.h"
  30. #include "ops/array_ops.h"
  31. #include "ops/elewise_calculation_ops.h"
  32. #include "ops/math_ops.h"
  33. #ifdef ENABLE_GE
  34. #include "ops/save_ops.h"
  35. #endif
  36. namespace mindspore {
  37. namespace transform {
  38. using std::endl;
  39. using ge::Operator;
  40. using mindspore::kAnyValue;
  41. using std::make_shared;
  42. using std::shared_ptr;
  43. using std::string;
  44. using std::vector;
  45. using Variable = ge::op::Variable;
  46. using Constant = ge::op::Constant;
  47. using Assign = ge::op::Assign;
  48. using Data = ge::op::Data;
  49. // ---------------implement of DfGraphConvertor-------------
  50. PrimType GetCNodeFuncType(const CNodePtr cnode) {
  51. if (cnode->inputs().empty()) {
  52. return kPrimTypeUnknown;
  53. }
  54. AnfNodePtr valuenode = cnode->input(0);
  55. if (IsValueNode<Primitive>(valuenode)) {
  56. // check whether the valuenode is primitive
  57. return GetValueNode<PrimitivePtr>(valuenode)->prim_type();
  58. }
  59. return kPrimTypeUnknown;
  60. }
  61. bool IsCaseNode(const CNodePtr node) {
  62. if (!node->inputs().empty() && node->input(0)->isa<CNode>() &&
  63. GetCNodeFuncName(node->input(0)->cast<CNodePtr>()) == "switch_layer") {
  64. return true;
  65. }
  66. return false;
  67. }
  68. std::string GetCNodeTargetFuncName(const CNodePtr cnode) {
  69. if (IsCaseNode(cnode)) {
  70. return string(kNameCase);
  71. }
  72. auto name = GetCNodeFuncName(cnode);
  73. if (name == "switch_layer") {
  74. name = "";
  75. }
  76. return name;
  77. }
  78. OpAdapterPtr DfGraphConvertor::FindAdapter(const AnfNodePtr node, bool train) {
  79. if (node->isa<CNode>()) {
  80. auto cnode = node->cast<CNodePtr>();
  81. std::string name = kNameCustomOp;
  82. if (!IsCustomCNode(cnode)) {
  83. name = GetCNodeTargetFuncName(cnode);
  84. }
  85. auto it_adpt = OpAdapterMap::get().find(name);
  86. if (it_adpt != OpAdapterMap::get().end()) {
  87. return it_adpt->second->Get(train);
  88. }
  89. MS_LOG(EXCEPTION) << "Can't find OpAdapter for " << name;
  90. }
  91. if (node->isa<ValueNode>()) {
  92. return OpAdapterMap::get()[kNameConst]->Get(train);
  93. }
  94. if (node->isa<Parameter>()) {
  95. return OpAdapterMap::get()[kNameParam]->Get(train);
  96. }
  97. return OpAdapterPtr(nullptr);
  98. }
  99. void DfGraphConvertor::InitLoopVar(std::vector<ge::Operator> *init_input) {
  100. if (this->training_) {
  101. GeTensorDesc desc(GeShape(), ge::FORMAT_NCHW, ge::DT_INT64);
  102. auto var_iter_num = std::make_shared<Variable>("npu_runconfig/iterations_per_loop");
  103. auto var_loop_cond = std::make_shared<Variable>("npu_runconfig/loop_cond");
  104. auto var_one = std::make_shared<Variable>("npu_runconfig/one");
  105. auto var_zero = std::make_shared<Variable>("npu_runconfig/zero");
  106. (void)var_iter_num->update_output_desc_y(desc);
  107. (void)var_loop_cond->update_output_desc_y(desc);
  108. (void)var_one->update_output_desc_y(desc);
  109. (void)var_zero->update_output_desc_y(desc);
  110. vars_["npu_runconfig/iterations_per_loop"] = var_iter_num;
  111. vars_["npu_runconfig/loop_cond"] = var_loop_cond;
  112. vars_["npu_runconfig/one"] = var_one;
  113. vars_["npu_runconfig/zero"] = var_zero;
  114. int64_t value = 0;
  115. auto const_iter_num = std::make_shared<Constant>("const/npu_runconfig/iterations_per_loop");
  116. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  117. value = ConfigManager::GetInstance().iter_num();
  118. } else {
  119. MS_LOG(INFO) << "Run with normal(non-sink) mode, the iterator number will always be 1";
  120. value = 1;
  121. ConfigManager::GetInstance().set_iter_num(value);
  122. }
  123. value -= 1; // iteration start from 0, the max iteration number for n loop should be n-1
  124. (void)const_iter_num->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  125. auto const_loop_cond = std::make_shared<Constant>("const/npu_runconfig/loop_cond");
  126. value = 0;
  127. (void)const_loop_cond->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  128. auto const_one = std::make_shared<Constant>("const/npu_runconfig/one");
  129. value = 1;
  130. (void)const_one->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  131. auto const_zero = std::make_shared<Constant>("const/npu_runconfig/zero");
  132. value = 0;
  133. (void)const_zero->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  134. (void)const_iter_num->update_output_desc_y(desc);
  135. (void)const_loop_cond->update_output_desc_y(desc);
  136. (void)const_one->update_output_desc_y(desc);
  137. (void)const_zero->update_output_desc_y(desc);
  138. auto assign_iter_num = std::make_shared<Assign>("assign/npu_runconfig/iterations_per_loop");
  139. (void)assign_iter_num->set_input_ref(*var_iter_num).set_input_value(*const_iter_num);
  140. auto assign_loop_cond = std::make_shared<Assign>("assign/npu_runconfig/loop_cond");
  141. (void)assign_loop_cond->set_input_ref(*var_loop_cond).set_input_value(*const_loop_cond);
  142. auto assign_one = std::make_shared<Assign>("assign/npu_runconfig/one");
  143. (void)assign_one->set_input_ref(*var_one).set_input_value(*const_one);
  144. auto assign_zero = std::make_shared<Assign>("assign/npu_runconfig/zero");
  145. (void)assign_zero->set_input_ref(*var_zero).set_input_value(*const_zero);
  146. init_input->push_back(*var_iter_num);
  147. init_input->push_back(*var_loop_cond);
  148. init_input->push_back(*var_one);
  149. init_input->push_back(*var_zero);
  150. init_ops_.push_back(var_iter_num);
  151. init_ops_.push_back(var_loop_cond);
  152. init_ops_.push_back(var_one);
  153. init_ops_.push_back(var_zero);
  154. init_ops_.push_back(const_iter_num);
  155. init_ops_.push_back(const_loop_cond);
  156. init_ops_.push_back(const_one);
  157. init_ops_.push_back(const_zero);
  158. init_ops_.push_back(assign_iter_num);
  159. init_ops_.push_back(assign_loop_cond);
  160. init_ops_.push_back(assign_one);
  161. init_ops_.push_back(assign_zero);
  162. }
  163. }
  164. OpAdapterPtr DfGraphConvertor::FindAdapter(const std::string &name, bool train) {
  165. auto it = OpAdapterMap::get().find(name);
  166. if (it != OpAdapterMap::get().end()) {
  167. return it->second->Get(train);
  168. }
  169. MS_LOG(EXCEPTION) << "Can't find OpAdapter for " << name;
  170. }
  171. void DfGraphConvertor::DrawParamInitSubGraph(const std::string &name, const AnfNodePtr &it) {
  172. // draw init subgraph
  173. init_sout_ << "op_assign" << it.get() << "[label=<";
  174. init_sout_ << "<table border='1' cellborder='1'>" << endl;
  175. init_sout_ << "<tr>";
  176. init_sout_ << "<td port='1'>resource</td>";
  177. init_sout_ << "<td port='2'>value</td>";
  178. init_sout_ << "</tr>" << endl;
  179. init_sout_ << "<tr><td colspan=\"2\">"
  180. << "\"assign_" << name << "\"</td></tr>" << endl;
  181. init_sout_ << "</table>> shape=plaintext]" << endl;
  182. init_sout_ << "param" << it.get() << "[shape=octagon, label=\"" << name << "\"]" << endl;
  183. init_sout_ << "const" << it.get() << "[label= \"" << name << "_const"
  184. << "\" shape=ellipse]" << endl;
  185. init_sout_ << "param" << it.get() << "->"
  186. << "op_assign" << it.get() << ":1" << endl;
  187. init_sout_ << "const" << it.get() << "->"
  188. << "op_assign" << it.get() << ":2" << endl;
  189. }
  190. void DfGraphConvertor::SetupParamInitSubGraph(const TensorOrderMap &tensors, std::vector<ge::Operator> *init_input) {
  191. DfGraphPtr init_graph = std::make_shared<DfGraph>("init");
  192. std::vector<AnfNodePtr> nodes = TopoSort(anf_graph_->get_return());
  193. for (auto &it : nodes) {
  194. if (it->isa<ValueNode>()) {
  195. if (IsValueNode<SymbolicKeyInstance>(it)) {
  196. auto symbolic = GetValueNode<SymbolicKeyInstancePtr>(it);
  197. auto name = std::static_pointer_cast<Parameter>(symbolic->node())->name();
  198. auto iter = vars_.find(name); // get correspoding varaible op
  199. if (iter != vars_.end()) {
  200. op_cache_[it.get()] = iter->second;
  201. // #ifdef DRAW_GE_GRAPH
  202. compute_sout_ << op_draw_name_[params_[name].get()] << " -> " << op_draw_name_[it.get()]
  203. << "[style=\"dotted\"]" << endl;
  204. // #endif
  205. }
  206. } else if (IsValueNode<RefKey>(it)) {
  207. auto refkey = GetValueNode<RefKeyPtr>(it);
  208. auto name = refkey->tag();
  209. auto iter = vars_.find(name); // get correspoding varaible op
  210. if (iter != vars_.end()) {
  211. op_cache_[it.get()] = iter->second;
  212. compute_sout_ << op_draw_name_[params_[name].get()] << " -> " << op_draw_name_[it.get()]
  213. << "[style=\"dotted\"]" << endl;
  214. }
  215. }
  216. }
  217. }
  218. for (auto &it : tensors) {
  219. if (vars_.find(it.first) == vars_.end()) {
  220. MS_LOG(WARNING) << "Init parameter " << it.first << " didn't appear in graph.";
  221. vars_[it.first] = nullptr;
  222. }
  223. }
  224. // set up init sub graph
  225. if (init_input->size()) {
  226. // init sub graph needs no input
  227. MS_LOG(INFO) << "Build data init subgraph.";
  228. (void)init_graph->SetInputs(*init_input);
  229. this->init_graph_ = init_graph;
  230. } else {
  231. this->init_graph_ = nullptr;
  232. }
  233. }
  234. void DfGraphConvertor::MakeDatasetHandler(const std::string &name, const size_t &input_idx, const AnfNodePtr &it) {
  235. MS_LOG(INFO) << "The " << name << " is the " << input_idx << "(st/nd/th) input";
  236. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  237. auto getnext_idx = static_cast<int64_t>(input_idx);
  238. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  239. if (!param.input_indexes().empty() && input_idx <= param.input_indexes().size()) {
  240. getnext_idx = param.input_indexes()[input_idx] - 1; // input_idx start from 0.
  241. MS_LOG(INFO) << "remap input_index:" << input_idx << " to getnext_index:" << getnext_idx << ".";
  242. }
  243. // use iterator_getnext op with output_name instead of data op in BuildGraph.
  244. out_handle_cache_[it.get()] = OutHandler(dataset_iter_getnext_, "y" + std::to_string(getnext_idx));
  245. }
  246. }
  247. void DfGraphConvertor::SetupBroadcast(const std::shared_ptr<HcomBroadcast> &broadcast,
  248. const std::vector<GeTensorDesc> &broadcast_desc,
  249. const DfGraphPtr &broadcast_graph, std::vector<ge::Operator> broadcast_input) {
  250. MS_LOG(INFO) << "build broadcast subgraph";
  251. if (broadcast_desc.size() != broadcast_input.size()) {
  252. MS_LOG(EXCEPTION) << "Desc number of BroadCast is not equal to number of Input";
  253. }
  254. (void)broadcast->create_dynamic_input_x(static_cast<unsigned int>(broadcast_input.size()));
  255. (void)broadcast->create_dynamic_output_y(static_cast<unsigned int>(broadcast_desc.size()));
  256. for (unsigned int i = 0; i < broadcast_input.size(); i++) {
  257. (void)broadcast->set_dynamic_input_x(i, broadcast_input[i]);
  258. (void)broadcast->update_dynamic_output_desc_y(i, broadcast_desc[i]);
  259. }
  260. (void)broadcast_graph->SetInputs(broadcast_input);
  261. this->broadcast_graph_ = broadcast_graph;
  262. }
  263. void DfGraphConvertor::InitParamWithData(const TensorOrderMap &tensors) {
  264. int index = 0;
  265. std::vector<Operator> init_input;
  266. for (auto it : tensors) {
  267. std::string name = it.first;
  268. auto node_itor = params_.find(name);
  269. // if name not in params_, create a node in graph
  270. if (node_itor == params_.end()) {
  271. MS_LOG(WARNING) << name << " is not in params, and create a new node.";
  272. ParameterPtr param = std::make_shared<Parameter>(nullptr);
  273. name = name + "_temp";
  274. param->set_name(name);
  275. (void)ConvertParameter(param);
  276. node_itor = params_.find(name);
  277. }
  278. auto node = node_itor->second;
  279. auto op_itor = op_cache_.find(node.get());
  280. if (op_itor == op_cache_.end()) {
  281. MS_LOG(EXCEPTION) << "Can not find op for node " << node->ToString() << ".";
  282. }
  283. auto adpt = FindAdapter(kNameParam, training_);
  284. if (adpt == nullptr) continue;
  285. auto param_op = adpt->generate(name + "_data");
  286. MS_LOG(INFO) << "Add parameter " << name << " as input, index " << index << ".";
  287. if (!training_) {
  288. auto adpt_const = FindAdapter(kNameConst, training_);
  289. if (adpt_const == nullptr) continue;
  290. auto const_op = adpt_const->generate(name + "_const");
  291. (void)adpt_const->setAttr(const_op, "value", it.second);
  292. auto const_op_desc = TransformUtil::GetGeTensorDesc(it.second->shape_c(), it.second->data_type(), kOpFormat_NCHW);
  293. if (const_op_desc == nullptr) {
  294. MS_LOG(ERROR) << "Create variable " << name << " ouptut descriptor failed!";
  295. continue;
  296. }
  297. (void)std::static_pointer_cast<Constant>(const_op)->update_output_desc_y(*const_op_desc);
  298. vars_[name] = const_op;
  299. op_itor->second = const_op;
  300. continue;
  301. }
  302. // create tensor descriptor for output descriptor
  303. auto desc = TransformUtil::GetGeTensorDesc(it.second->shape_c(), it.second->data_type(), kOpFormat_NCHW);
  304. if (desc == nullptr) {
  305. MS_LOG(ERROR) << "Create variable " << name << " ouptut descriptor failed!";
  306. continue;
  307. }
  308. // we need three variable ops for each graph with same name
  309. // build init subgraph
  310. if (it.second->is_init() == 0) {
  311. (void)std::static_pointer_cast<Data>(param_op)->set_attr_index(index++);
  312. auto init_var = std::make_shared<Variable>(name);
  313. auto assign_op = std::make_shared<Assign>("assign_" + name);
  314. (void)init_var->update_output_desc_y(*desc);
  315. (void)assign_op->set_input_ref(*init_var).set_input_value(*param_op);
  316. init_input.push_back(*init_var);
  317. init_ops_.push_back(param_op);
  318. init_ops_.push_back(assign_op);
  319. init_ops_.push_back(init_var);
  320. }
  321. auto variable = std::make_shared<Variable>(name);
  322. (void)variable->update_output_desc_y(*desc);
  323. // do not use read variable while variable sink
  324. MS_LOG(DEBUG) << "InitParam, op_name = " << name << ", var = " << variable->GetName() << ".";
  325. op_itor->second = variable; // replace parameter with variable
  326. vars_[name] = variable; // prevent the variable operator from being freed
  327. DrawParamInitSubGraph(name, node);
  328. }
  329. InitLoopVar(&init_input);
  330. SetupParamInitSubGraph(tensors, &init_input);
  331. }
  332. // convert all parameter need initialize to variable
  333. DfGraphConvertor &DfGraphConvertor::InitParam(const TensorOrderMap &tensors) {
  334. size_t input_idx = 0;
  335. if (error_ != 0) {
  336. return *this;
  337. }
  338. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  339. error_ = INVALID_ARGUMENT;
  340. MS_LOG(ERROR) << "Invalid AnfGraph in InitParam.";
  341. return *this;
  342. }
  343. // Processing input with MakeDatasetHandler
  344. for (auto &it : anf_graph_->parameters()) {
  345. auto op_itor = op_cache_.find(it.get()); // converted node
  346. if (it->isa<Parameter>() && op_itor != op_cache_.end()) {
  347. string name = std::static_pointer_cast<Parameter>(it)->name();
  348. auto tensor_itor = tensors.find(name); // in init value map
  349. if (tensor_itor == tensors.end()) {
  350. DfGraphConvertor::MakeDatasetHandler(name, input_idx, it);
  351. input_idx++;
  352. }
  353. }
  354. }
  355. InitParamWithData(tensors);
  356. init_sout_ << "}" << endl;
  357. return *this;
  358. }
  359. #if (defined ENABLE_GE)
  360. void DfGraphConvertor::BuildSaveCheckpointGraph() {
  361. std::vector<Operator> graph_inputs;
  362. ge::op::Save save_op("save_parms");
  363. int save_op_is_active = 0;
  364. size_t index = 0;
  365. string name;
  366. int32_t count_size = std::count_if(vars_.begin(), vars_.end(), [](const std::pair<std::string, OperatorPtr> &it) {
  367. return (it.second == nullptr || it.first.find("/") != std::string::npos);
  368. });
  369. (void)save_op.create_dynamic_input_tensors(vars_.size() - static_cast<size_t>(count_size));
  370. // for each "parameter" in anf graph excluding "input"
  371. for (const auto &it : vars_) {
  372. name = it.first;
  373. if (it.second == nullptr || name.find("/") != std::string::npos) continue;
  374. Variable variable(name);
  375. (void)variable.update_output_desc_y(it.second->GetOutputDesc(0));
  376. (void)save_op.set_dynamic_input_tensors(index++, variable);
  377. graph_inputs.push_back(variable);
  378. if (save_op_is_active == 0) {
  379. checkpoint_sout_ << "op_save" << &save_op << "[label=<";
  380. checkpoint_sout_ << "<table border='1' cellborder='1'>" << endl;
  381. checkpoint_sout_ << "<tr><td port='1'>tensor</td></tr>" << endl;
  382. checkpoint_sout_ << "<tr><td colspan=\"1\">"
  383. << "\"saveop"
  384. << "\"</td></tr>" << endl;
  385. checkpoint_sout_ << "</table>> shape=plaintext]" << endl;
  386. }
  387. checkpoint_sout_ << "param" << it.second << "[shape=octagon, label=\"" << name << "\"]" << endl;
  388. checkpoint_sout_ << "param" << it.second << "->"
  389. << "op_save" << &save_op << ":1" << endl;
  390. save_op_is_active = 1;
  391. }
  392. if (save_op_is_active) {
  393. std::vector<Operator> graph_output;
  394. graph_output.emplace_back(save_op);
  395. DfGraphPtr checkpoint_graph = std::make_shared<DfGraph>("checkpoint");
  396. (void)checkpoint_graph->SetInputs(graph_inputs);
  397. (void)checkpoint_graph->SetOutputs(graph_output);
  398. this->save_ckp_graph_ = checkpoint_graph;
  399. } else {
  400. this->save_ckp_graph_ = nullptr;
  401. }
  402. checkpoint_sout_ << "}" << endl;
  403. return;
  404. }
  405. #endif
  406. DfGraphConvertor &DfGraphConvertor::GenerateBroadcastGraph(const TensorOrderMap &tensors) {
  407. if (error_ != 0) {
  408. return *this;
  409. }
  410. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  411. error_ = INVALID_ARGUMENT;
  412. MS_LOG(ERROR) << "Invalid AnfGraph in generate broadcast graph";
  413. return *this;
  414. }
  415. DfGraphPtr broadcast_graph = std::make_shared<DfGraph>("broadcast");
  416. // collect the operators create for broadcast sub graph, in order to avoid auto release
  417. std::vector<Operator> broadcast_input;
  418. std::vector<GeTensorDesc> broadcast_desc;
  419. auto broadcast = std::make_shared<HcomBroadcast>("broadcast_parameter");
  420. (void)broadcast->set_attr_root_rank(0);
  421. (void)broadcast->set_attr_group("hccl_world_group");
  422. broadcast_ops_.push_back(broadcast);
  423. // find every parameter, build broadcast subgraph (or initialize the parameter with constant)
  424. for (auto &it : anf_graph_->parameters()) {
  425. auto op_itor = op_cache_.find(it.get()); // converted node
  426. if (it->isa<Parameter>() && op_itor != op_cache_.end()) {
  427. string name = std::static_pointer_cast<Parameter>(it)->name();
  428. auto tensor_itor = tensors.find(name); // in init tensor map
  429. if (tensor_itor != tensors.end()) {
  430. auto tensor = tensor_itor->second;
  431. auto shape_ge = tensor->shape_c();
  432. // create tensor descriptor for output descriptor
  433. auto desc = TransformUtil::GetGeTensorDesc(shape_ge, tensor->data_type(), kOpFormat_NCHW);
  434. if (desc == nullptr) {
  435. MS_LOG(ERROR) << "Create variable " << name << " ouptut descriptor failed!";
  436. continue;
  437. }
  438. // build broadcast subgraph
  439. if (distribute_) {
  440. auto broadcast_var = std::make_shared<Variable>(name);
  441. (void)broadcast_var->update_output_desc_y(*desc);
  442. broadcast_input.push_back(*broadcast_var);
  443. broadcast_desc.push_back(*desc);
  444. broadcast_ops_.push_back(broadcast_var);
  445. }
  446. }
  447. }
  448. }
  449. // set up broadcast sub graph
  450. if (!broadcast_input.empty()) {
  451. DfGraphConvertor::SetupBroadcast(broadcast, broadcast_desc, broadcast_graph, broadcast_input);
  452. } else {
  453. this->broadcast_graph_ = nullptr;
  454. }
  455. return *this;
  456. }
  457. DfGraphConvertor &DfGraphConvertor::GenerateCheckpointGraph() {
  458. if (error_ != 0) {
  459. MS_LOG(ERROR) << "Generate checkpoint graph failed, found error code " << error_ << ".";
  460. return *this;
  461. }
  462. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  463. error_ = INVALID_ARGUMENT;
  464. MS_LOG(ERROR) << "Invalid AnfGraph in GenerateCheckpointGraph";
  465. return *this;
  466. }
  467. #if (defined ENABLE_GE)
  468. BuildSaveCheckpointGraph();
  469. // Restoring from checkpoint file is done by pyfront, not in graph now.
  470. #endif
  471. return *this;
  472. }
  473. DfGraphConvertor &DfGraphConvertor::ConvertAllNode() {
  474. if (error_ != 0) {
  475. return *this;
  476. }
  477. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  478. MS_LOG(ERROR) << "Invalid AnfGraph";
  479. error_ = FAILED;
  480. return *this;
  481. }
  482. compute_sout_.clear();
  483. compute_sout_ << "digraph {" << endl;
  484. init_sout_.clear();
  485. init_sout_ << "digraph {" << endl;
  486. checkpoint_sout_.clear();
  487. checkpoint_sout_ << "digraph {" << endl;
  488. restore_checkpoint_sout_.clear();
  489. restore_checkpoint_sout_ << "digraph {" << endl;
  490. // Convert all anf node to Operator
  491. MS_LOG(DEBUG) << "convert all node";
  492. std::vector<AnfNodePtr> nodes = TopoSort(anf_graph_->get_return());
  493. for (auto &it : nodes) {
  494. (void)Convert(it);
  495. if (this->error_ != 0) {
  496. MS_LOG(ERROR) << "failed to convert node: " << it->DebugString() << ".";
  497. }
  498. }
  499. // Create dataset iterator and iterator_getnext node
  500. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  501. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  502. MS_LOG(INFO) << "Dataset param is " << param.ToString() << ".";
  503. // GetNext
  504. auto iter_getnext_op = make_shared<ge::op::GetNext>("get_next_tmp");
  505. (void)iter_getnext_op->set_attr_output_types(param.ge_types());
  506. (void)iter_getnext_op->set_attr_output_shapes(param.shapes());
  507. (void)iter_getnext_op->set_attr_channel_name(param.queue_name());
  508. // save iter_getnext_op for later use
  509. dataset_iter_getnext_ = iter_getnext_op;
  510. }
  511. // return the data flow graph
  512. return *this;
  513. }
  514. void DfGraphConvertor::TraceOutputFromTupleGetItem(const AnfNodePtr &anf_out) {
  515. auto it = out_handle_cache_.find(anf_out.get());
  516. if (it != out_handle_cache_.end()) {
  517. OutHandler handle = it->second;
  518. auto op = handle.op;
  519. if (op != nullptr) {
  520. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType() << ", out_name: " << handle.out;
  521. graph_outputs_.emplace_back(std::make_pair(*op, handle.out));
  522. } else {
  523. MS_LOG(EXCEPTION) << "tuple_getitem: " << anf_out->fullname_with_scope() << " is not converted";
  524. }
  525. } else {
  526. // invalid tuple_getitem e.g. tuple_getitem(tuple_getitem())/tuple_getitem(depend())/tuple_getitem(make_tuple())
  527. MS_LOG(WARNING) << "Invalid tuple_getitem: " << anf_out->fullname_with_scope();
  528. }
  529. }
  530. void DfGraphConvertor::TraceOutput(const AnfNodePtr node) {
  531. AnfNodePtr anf_out = node;
  532. AnfNodePtr pre_node = nullptr;
  533. // Trace value node
  534. if (node->isa<ValueNode>()) {
  535. auto op = Convert(anf_out);
  536. if (op != nullptr) {
  537. graph_outputs_.emplace_back(std::make_pair(*op, ""));
  538. AddGraphConstInput(op);
  539. }
  540. return;
  541. }
  542. // Trace Parameter node
  543. TraceOutputFromParameter(anf_out);
  544. // Then trace cnode
  545. if (!node->isa<CNode>()) {
  546. return;
  547. }
  548. // trace tuple_getitem
  549. while (anf_out->isa<CNode>() && IsPrimitiveCNode(anf_out, prim::kPrimTupleGetItem)) {
  550. pre_node = anf_out;
  551. anf_out = anf_out->cast<CNodePtr>()->input(1);
  552. }
  553. // trace every element of make_tuple
  554. auto c = anf_out->cast<CNodePtr>();
  555. std::string name = "";
  556. if (anf_out->isa<CNode>()) {
  557. name = GetCNodeTargetFuncName(c);
  558. }
  559. if (name == "make_tuple") {
  560. for (unsigned int i = 1; i < c->inputs().size(); i++) {
  561. TraceOutput(c->input(i));
  562. }
  563. } else if (name == "Depend") {
  564. if (c->inputs().size() < 3) { // "Depend" primitive have 3 inputs
  565. MS_LOG(EXCEPTION) << "length of inputs is " << c->inputs().size() << ", which is less than 3";
  566. }
  567. TraceOutput(c->input(1));
  568. } else if (name == "tuple_getitem") {
  569. TraceOutputFromTupleGetItem(anf_out);
  570. } else {
  571. // add outputs;
  572. auto op = Convert(anf_out);
  573. std::string index;
  574. if (op != nullptr) {
  575. if ((pre_node != nullptr) && IsPrimitiveCNode(pre_node, prim::kPrimTupleGetItem)) {
  576. auto item = out_handle_cache_.find(pre_node.get());
  577. if (item != out_handle_cache_.end()) {
  578. index = item->second.out;
  579. } else {
  580. MS_LOG(WARNING) << "Can't get operater: " << anf_out->fullname_with_scope() << " 's output item";
  581. }
  582. }
  583. MS_LOG(INFO) << "Add graph output: " << anf_out->fullname_with_scope() << ":" << index;
  584. graph_outputs_.emplace_back(make_pair(*op, index));
  585. }
  586. }
  587. }
  588. void DfGraphConvertor::TraceOutputFromParameter(const AnfNodePtr &anf_out) {
  589. if (anf_out->isa<Parameter>()) {
  590. MS_LOG(INFO) << "Add graph output: " << anf_out->fullname_with_scope();
  591. auto it = out_handle_cache_.find(anf_out.get());
  592. if (it != out_handle_cache_.end()) {
  593. // For dataset graph mode, input parameter is converted to a "iterator_get_next:yn" OutHandler.
  594. OutHandler handle = it->second;
  595. auto op = handle.op;
  596. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType() << ", out_name: " << handle.out;
  597. graph_outputs_.emplace_back(make_pair(*op, handle.out));
  598. } else {
  599. // common parameter case
  600. auto op = Convert(anf_out);
  601. if (op != nullptr) {
  602. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType();
  603. graph_outputs_.emplace_back(std::make_pair(*op, ""));
  604. }
  605. }
  606. }
  607. }
  608. void SetupDatasetIterGetNextNode(const OperatorPtr &op) {
  609. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  610. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  611. size_t output_num = param.ge_types().size();
  612. MS_LOG(INFO) << "Set iterator_getnext op's output num = " << output_num << ".";
  613. // set iterator_getnext op's output num
  614. shared_ptr<ge::op::GetNext> iter_getnext = std::static_pointer_cast<ge::op::GetNext>(op);
  615. (void)iter_getnext->create_dynamic_output_y(static_cast<unsigned int>(output_num));
  616. for (uint32_t i = 0; i < output_num; i++) {
  617. ge::TensorDesc desc(GeShape(param.shapes()[i]), ge::FORMAT_NCHW, (ge::DataType)param.ge_types()[i]);
  618. // we don't SetRealDimCnt here since GE do not use this output's real-dim
  619. (void)iter_getnext->update_dynamic_output_desc_y((i), desc);
  620. }
  621. }
  622. return;
  623. }
  624. void DfGraphConvertor::SetSubgraph(AnfNodePtr node) {
  625. if (!node->isa<CNode>()) {
  626. return;
  627. }
  628. auto cnode = node->cast<CNodePtr>();
  629. if (!IsCaseNode(cnode)) {
  630. return;
  631. }
  632. std::vector<AnfNodePtr> case_inputs;
  633. for (size_t i = 1; i < cnode->inputs().size(); i++) {
  634. case_inputs.emplace_back(cnode->input(i));
  635. }
  636. std::shared_ptr<std::vector<DfGraph>> branches = std::make_shared<std::vector<DfGraph>>();
  637. auto bnode = cnode->input(0)->cast<CNodePtr>()->input(2)->cast<CNodePtr>();
  638. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  639. auto branch_node = bnode->input(i)->cast<CNodePtr>();
  640. for (size_t j = 2; j < branch_node->inputs().size(); j++) {
  641. if (std::find(case_inputs.begin(), case_inputs.end(), branch_node->input(j)) == case_inputs.end()) {
  642. case_inputs.emplace_back(branch_node->input(j));
  643. }
  644. }
  645. }
  646. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  647. ProcessSubgraph(bnode->input(i), case_inputs);
  648. }
  649. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  650. branches->emplace_back(branches_map_[bnode->input(i).get()]);
  651. }
  652. if (op_cache_.find(node.get()) == op_cache_.end()) {
  653. return;
  654. }
  655. OpAdapterPtr adpt = FindAdapter(node, training_);
  656. if (nullptr == adpt) {
  657. MS_LOG(DEBUG) << "Not found adapter";
  658. return;
  659. }
  660. OperatorPtr op = Convert(node);
  661. adpt->setSubgraph(op, 0, branches);
  662. return;
  663. }
  664. void DfGraphConvertor::GetCaseNodeInput(const CNodePtr node, const CNodePtr input_node) {
  665. std::vector<AnfNodePtr> case_inputs;
  666. for (size_t i = 1; i < node->inputs().size(); i++) {
  667. case_inputs.emplace_back(node->input(i));
  668. }
  669. std::shared_ptr<std::vector<DfGraph>> branches = std::make_shared<std::vector<DfGraph>>();
  670. auto bnode = input_node->input(2)->cast<CNodePtr>();
  671. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  672. auto branch_node = bnode->input(i)->cast<CNodePtr>();
  673. for (size_t j = 2; j < branch_node->inputs().size(); j++) {
  674. if (std::find(case_inputs.begin(), case_inputs.end(), branch_node->input(j)) == case_inputs.end()) {
  675. case_inputs.emplace_back(branch_node->input(j));
  676. }
  677. }
  678. }
  679. const size_t case_index = 1;
  680. const size_t make_tuple_index = 2;
  681. AnfNodePtr case_index_iter = input_node->input(case_index);
  682. AnfNodePtr make_tuple_iter = input_node->input(make_tuple_index);
  683. auto make_tuple_node = make_tuple_iter->cast<CNodePtr>();
  684. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  685. for (size_t i = 0; i < case_inputs.size(); i++) {
  686. auto item = case_inputs[i];
  687. auto op = Convert(item);
  688. if (op != nullptr) {
  689. tuple_items->emplace_back(OutHandler(op, ""));
  690. } else if (out_handle_cache_.find(item.get()) != out_handle_cache_.end()) {
  691. tuple_items->push_back(out_handle_cache_[item.get()]);
  692. } else {
  693. MS_LOG(WARNING) << "This anf node is not supported as a case input: " << item->ToString();
  694. continue;
  695. }
  696. }
  697. tuple_out_handle_cache_[make_tuple_node.get()] = tuple_items;
  698. std::shared_ptr<std::vector<AnfNodePtr>> case_input_items = std::make_shared<std::vector<AnfNodePtr>>();
  699. case_input_items->emplace_back(case_index_iter);
  700. case_input_items->emplace_back(make_tuple_iter);
  701. case_input_handle_cache_[node.get()] = case_input_items;
  702. }
  703. DfGraphConvertor &DfGraphConvertor::BuildGraph() {
  704. SetupDatasetIterGetNextNode(dataset_iter_getnext_);
  705. if (error_ != 0) {
  706. return *this;
  707. }
  708. // Case node set input.
  709. std::vector<AnfNodePtr> nodes = ::mindspore::TopoSort(anf_graph_->get_return());
  710. for (auto &it : nodes) {
  711. if (it->isa<CNode>() && IsCaseNode(it->cast<CNodePtr>())) {
  712. auto node = it->cast<CNodePtr>();
  713. auto input_node = node->input(0)->cast<CNodePtr>();
  714. GetCaseNodeInput(node, input_node);
  715. }
  716. }
  717. // update tuple_out_handle_cache_
  718. for (auto it : tuple_out_handle_cache_) {
  719. std::size_t len = it.second->size();
  720. for (std::size_t i = 0; i < len; i++) {
  721. OutHandler handle = (*it.second)[i];
  722. if (handle.op) {
  723. string name = handle.op->GetName();
  724. if (vars_.count(name)) {
  725. OperatorPtr new_op = vars_[name];
  726. if (new_op != nullptr) {
  727. MS_LOG(INFO) << "update tuple_out_handle_cache_ " << name;
  728. (*it.second)[i] = OutHandler(new_op, handle.out);
  729. }
  730. }
  731. }
  732. }
  733. }
  734. // set up dependices
  735. MS_LOG(DEBUG) << "set up dependices";
  736. nodes = ::mindspore::TopoSort(anf_graph_->get_return());
  737. for (auto &it : nodes) {
  738. SetNodeInput(it);
  739. SetOpControlInput(it);
  740. SetSubgraph(it);
  741. UpdateOpDesc(it);
  742. }
  743. if (error_ == 0) {
  744. df_graph_ = make_shared<DfGraph>(anf_graph_->ToString());
  745. } else {
  746. return *this;
  747. }
  748. // set graph input according to the order from anf graph
  749. std::vector<Operator> inputs;
  750. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  751. inputs.push_back(*dataset_iter_getnext_);
  752. } else {
  753. auto params = anf_graph_->parameters();
  754. if (use_inputs_) {
  755. params = inputs_;
  756. auto anf_params = anf_graph_->parameters();
  757. for (size_t i = 0; i < params.size(); i++) {
  758. for (size_t j = 0; j < anf_params.size(); j++) {
  759. if (params[i]->ToString() == anf_params[j]->ToString()) {
  760. params[i] = anf_params[j];
  761. }
  762. }
  763. }
  764. }
  765. int index = 0;
  766. for (auto &it : params) {
  767. auto name = std::static_pointer_cast<Parameter>(it)->name();
  768. // the parameters which has not been converted to var
  769. if (vars_.find(name) == vars_.end()) {
  770. auto op = Convert(it);
  771. MS_EXCEPTION_IF_NULL(op);
  772. MS_LOG(INFO) << "add not var input " << it->ToString() << ", index " << index;
  773. if (op == nullptr) {
  774. MS_LOG(ERROR) << "Convert graph failed!";
  775. return *this;
  776. }
  777. UpdateDataOpDesc(it, op);
  778. MS_LOG(INFO) << "add input " << it->ToString() << ", index " << index;
  779. (void)std::static_pointer_cast<Data>(op)->set_attr_index(index++);
  780. inputs.push_back(*op);
  781. } else if (vars_[name] != nullptr) {
  782. MS_LOG(INFO) << "add var input " << it->ToString();
  783. auto op = Convert(it);
  784. MS_EXCEPTION_IF_NULL(op);
  785. inputs.push_back(*op);
  786. }
  787. }
  788. }
  789. MS_LOG(DEBUG) << "trace output";
  790. graph_outputs_.clear();
  791. TraceOutput(anf_graph_->get_return()->input(1));
  792. // Add const nodes as graph input for some operator work with constant
  793. MS_LOG(INFO) << "graph const input size: " << graph_const_inputs_.size();
  794. std::transform(graph_const_inputs_.begin(), graph_const_inputs_.end(), std::back_inserter(inputs),
  795. [](OperatorPtr x) { return *x; });
  796. MS_LOG(INFO) << "set graph input num: " << inputs.size();
  797. (void)df_graph_->SetInputs(inputs);
  798. // set graph output
  799. // set the value of finale return apply node as the output of dataflow graph
  800. MS_LOG(DEBUG) << "set output";
  801. MS_LOG(INFO) << "set graph output num: " << graph_outputs_.size();
  802. (void)df_graph_->SetOutputs(graph_outputs_);
  803. compute_sout_ << "}" << endl;
  804. // For the graph(e.g. eval_subgraph) whose IterNum is 1, donot set NeedIteration flag.
  805. if (ConfigManager::GetInstance().iter_num() > 1) {
  806. df_graph_->SetNeedIteration(true);
  807. }
  808. return *this;
  809. }
  810. void DfGraphConvertor::UpdateDataOpDesc(const AnfNodePtr &it, const OperatorPtr &op) const {
  811. auto node = std::static_pointer_cast<AnfNode>(it);
  812. if (node == nullptr) {
  813. MS_LOG(ERROR) << "Update data op descriptor failed! Invalid node.";
  814. return;
  815. }
  816. auto normal_shape_ptr = dyn_cast<abstract::Shape>(node->Shape());
  817. std::vector<int64_t> shape;
  818. if (normal_shape_ptr == nullptr) {
  819. MS_LOG(INFO) << "Invalid shape to update data op descriptor.";
  820. return;
  821. }
  822. shape = normal_shape_ptr->shape();
  823. if (node->Type() == nullptr) {
  824. MS_LOG(INFO) << "Invalid type to update data op descriptor.";
  825. return;
  826. }
  827. TypeId me_type = node->Type()->type_id();
  828. if (kObjectTypeTensorType == me_type) {
  829. me_type = dyn_cast<TensorType>(node->Type())->element()->type_id();
  830. }
  831. std::ostringstream buf;
  832. buf << "[" << shape << "]";
  833. MS_LOG(INFO) << "input shape is " << buf.str() << ", type is " << me_type;
  834. auto desc = TransformUtil::GetGeTensorDesc(shape, me_type, "NCHW");
  835. if (desc == nullptr) {
  836. MS_LOG(ERROR) << "Update data op descriptor failed! TensorDesc is null.";
  837. } else {
  838. (void)std::static_pointer_cast<Data>(op)->update_input_desc_x(*desc);
  839. (void)std::static_pointer_cast<Data>(op)->update_output_desc_y(*desc);
  840. }
  841. }
  842. DfGraphPtr DfGraphConvertor::GetComputeGraph() { return df_graph_; }
  843. DfGraphPtr DfGraphConvertor::GetInitGraph() { return init_graph_; }
  844. DfGraphPtr DfGraphConvertor::GetSaveCheckpointGraph() { return save_ckp_graph_; }
  845. DfGraphPtr DfGraphConvertor::GetBroadcastGraph() { return broadcast_graph_; }
  846. void DfGraphConvertor::SetOpControlInput(const AnfNodePtr node) {
  847. if (control_depend_cache_.find(node.get()) == control_depend_cache_.end()) {
  848. return;
  849. }
  850. std::vector<ControlEdge> control_edges = control_depend_cache_[node.get()];
  851. if ((control_edges.empty())) {
  852. MS_LOG(ERROR) << "Get control depend node's src or dest operator failed";
  853. return;
  854. }
  855. for (auto &item : control_edges) {
  856. (void)item.dest_op->AddControlInput(*item.src_op);
  857. }
  858. }
  859. const std::vector<std::string> trans_var_list = {string(kNameAssign), string(kNameAssignAdd), string(kNameAssignSub)};
  860. void DfGraphConvertor::SetOpInput(const OpAdapterPtr &adpt, const CNodePtr &node) {
  861. OperatorPtr src = Convert(node);
  862. int case_flag = 0;
  863. auto &inputs = node->inputs();
  864. size_t input_size = inputs.size();
  865. if (case_input_handle_cache_.find(node.get()) != case_input_handle_cache_.end()) {
  866. case_flag = 1;
  867. input_size = case_input_handle_cache_[node.get()]->size() + 1;
  868. }
  869. for (size_t i = 1; i < input_size; i++) {
  870. AnfNodePtr pred = nullptr;
  871. if (case_flag != 0) {
  872. pred = case_input_handle_cache_[node.get()]->at(i - 1);
  873. } else {
  874. pred = inputs[i];
  875. }
  876. while (pred->isa<CNode>() && GetCNodeTargetFuncName(pred->cast<CNodePtr>()) == "Depend") {
  877. pred = pred->cast<CNodePtr>()->input(1);
  878. }
  879. // skip the None input
  880. if (IsValueNode<None>(pred)) {
  881. continue;
  882. }
  883. // transform "Const" op to "Variable" op when the next node is "Assign" op.
  884. std::string c_name = GetCNodeTargetFuncName(node);
  885. auto pos = std::find(trans_var_list.begin(), trans_var_list.end(), c_name);
  886. if (!training_ && pos != trans_var_list.end() && pred->isa<Parameter>()) {
  887. std::string name = std::static_pointer_cast<Parameter>(pred)->name();
  888. auto op_itor = op_cache_.find(pred.get());
  889. if (op_itor == op_cache_.end()) {
  890. MS_LOG(EXCEPTION) << "Can not find op for node " << pred->ToString() << ".";
  891. }
  892. if (op_itor->second != nullptr &&
  893. (op_itor->second->GetOpType() == "Constant" || op_itor->second->GetOpType() == "Const") &&
  894. vars_.find(name) != vars_.end()) {
  895. auto variable = std::make_shared<Variable>(name);
  896. auto desc = vars_[name]->GetOutputDesc("y");
  897. (void)variable->update_output_desc_y(desc);
  898. MS_LOG(DEBUG) << "Trans to variable, var = " << variable->GetName() << ".";
  899. op_itor->second = variable; // replace parameter with variable
  900. vars_[name] = variable;
  901. }
  902. }
  903. // find in out_hadnle_cache_ first
  904. auto it = out_handle_cache_.find(pred.get());
  905. if (it != out_handle_cache_.end()) {
  906. int ret = adpt->setInput(src, SizeToInt(i), it->second);
  907. if (ret == 0) {
  908. if (pred->isa<CNode>() && GetCNodeTargetFuncName(pred->cast<CNodePtr>()) == "tuple_getitem") {
  909. compute_sout_ << op_draw_name_[pred->cast<CNodePtr>()->input(1).get()] << " -> " << op_draw_name_[node.get()]
  910. << ":" << i << endl;
  911. } else if (pred->isa<Parameter>()) {
  912. compute_sout_ << op_draw_name_[pred.get()] << " -> " << op_draw_name_[node.get()] << ":" << i << endl;
  913. } else {
  914. // don't draw anything.
  915. MS_LOG(INFO) << "DRAW_GE_GRAPH: Shouldn't have this case.";
  916. }
  917. AddGraphConstInput(it->second.op);
  918. }
  919. } else if (tuple_out_handle_cache_.find(pred.get()) != tuple_out_handle_cache_.end()) {
  920. std::shared_ptr<std::vector<OutHandler>> handler_vec = tuple_out_handle_cache_[pred.get()];
  921. int ret = adpt->setInput(src, SizeToInt(i), handler_vec);
  922. if ((ret == 0) && pred->isa<CNode>() && (pred->cast<CNodePtr>()->inputs().size() == handler_vec->size() + 1)) {
  923. for (unsigned int j = 0; j < handler_vec->size(); j++) {
  924. compute_sout_ << op_draw_name_[pred->cast<CNodePtr>()->input(j + 1).get()] << " -> "
  925. << op_draw_name_[node.get()] << ":" << i << endl;
  926. AddGraphConstInput(handler_vec->at(j).op);
  927. }
  928. } else {
  929. MS_LOG(WARNING) << "Convert tuple node setInput failed : " << node->ToString();
  930. }
  931. } else {
  932. auto op = Convert(pred);
  933. int ret = adpt->setInput(src, SizeToInt(i), op);
  934. if (ret == 0) {
  935. compute_sout_ << op_draw_name_[pred.get()] << " -> " << op_draw_name_[node.get()] << ":" << i << endl;
  936. AddGraphConstInput(op);
  937. }
  938. }
  939. }
  940. }
  941. void DfGraphConvertor::AddGraphConstInput(const OperatorPtr &op) {
  942. if (op->GetOpType() == "Constant" || op->GetOpType() == "Const") {
  943. graph_const_inputs_.push_back(op);
  944. }
  945. }
  946. void DfGraphConvertor::SetNodeInput(const AnfNodePtr node) {
  947. if (!node->isa<CNode>()) {
  948. return;
  949. }
  950. if (op_cache_.find(node.get()) == op_cache_.end()) {
  951. return;
  952. }
  953. auto cnode = node->cast<CNodePtr>();
  954. OpAdapterPtr adpt = FindAdapter(cnode, training_);
  955. if (adpt == nullptr) {
  956. error_ = NOT_FOUND;
  957. return;
  958. }
  959. // get Operator from op_cache_, use adapter to set Inputs
  960. DfGraphConvertor::SetOpInput(adpt, cnode);
  961. }
  962. void DfGraphConvertor::ProcessSubgraph(AnfNodePtr node, const std::vector<AnfNodePtr> &inputs) {
  963. if (!node->isa<CNode>() || GetCNodeFuncName(node->cast<CNodePtr>()) != "Partial") {
  964. return;
  965. }
  966. auto graph_node = node->cast<CNodePtr>()->input(1)->cast<ValueNodePtr>();
  967. FuncGraphPtr anf_graph = graph_node->value()->cast<FuncGraphPtr>();
  968. DfGraphConvertor convertor(anf_graph);
  969. convertor.use_inputs_ = true;
  970. convertor.inputs_ = inputs;
  971. (void)convertor.ConvertAllNode().BuildGraph();
  972. std::string name = graph_node->ToString() + "_ge_graph.dot";
  973. if (MsContext::GetInstance()->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) {
  974. convertor.DrawComputeGraph(name);
  975. }
  976. branches_map_[node.get()] = *(convertor.df_graph_);
  977. }
  978. // Update GE op's shape and type info
  979. void DfGraphConvertor::UpdateOpDesc(const AnfNodePtr node) {
  980. if (nullptr == node || !node->isa<CNode>()) {
  981. return;
  982. }
  983. if (op_cache_.find(node.get()) == op_cache_.end()) {
  984. return;
  985. }
  986. OpAdapterPtr adpt = FindAdapter(node, training_);
  987. if (adpt == nullptr) {
  988. error_ = NOT_FOUND;
  989. return;
  990. }
  991. // get Operator from op_cache_
  992. OperatorPtr op = Convert(node);
  993. adpt->updateOutputDesc(op, node->Shape(), node->Type(), node);
  994. }
  995. OperatorPtr DfGraphConvertor::Convert(const AnfNodePtr node) {
  996. if (node == nullptr) {
  997. MS_LOG(ERROR) << "node is nullptr";
  998. error_ = NOT_FOUND;
  999. return nullptr;
  1000. }
  1001. // find in cache
  1002. if (op_cache_.count(node.get())) {
  1003. return op_cache_[node.get()];
  1004. }
  1005. // do not convert primitive node
  1006. if (IsValueNode<Primitive>(node)) {
  1007. return nullptr;
  1008. }
  1009. // convert a new one
  1010. if (node->isa<CNode>()) {
  1011. return ConvertCNode(node->cast<CNodePtr>());
  1012. }
  1013. if (node->isa<Parameter>()) {
  1014. return ConvertParameter(node);
  1015. }
  1016. if (node->isa<ValueNode>()) {
  1017. return ConvertValueNode(node->cast<ValueNodePtr>());
  1018. }
  1019. MS_LOG(ERROR) << "Invalide AnfNode";
  1020. error_ = INVALID_ARGUMENT;
  1021. return nullptr;
  1022. }
  1023. void DfGraphConvertor::ConvertMakeTuple(const CNodePtr node) {
  1024. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  1025. // convert each tuple item to a OutHandler
  1026. for (size_t i = 1; i < node->inputs().size(); i++) {
  1027. AnfNodePtr item = node->input(i);
  1028. OperatorPtr op = Convert(item);
  1029. if (op != nullptr) {
  1030. tuple_items->emplace_back(OutHandler(op, ""));
  1031. } else if (out_handle_cache_.find(item.get()) != out_handle_cache_.end()) {
  1032. tuple_items->push_back(out_handle_cache_[item.get()]);
  1033. } else {
  1034. MS_LOG(WARNING) << "This anf node is not supported as a tuple item : " << item->ToString();
  1035. return;
  1036. }
  1037. }
  1038. MS_LOG(DEBUG) << "ConvertMakeTuple: " << node.get() << " " << tuple_items->size();
  1039. tuple_out_handle_cache_[node.get()] = tuple_items;
  1040. }
  1041. AnfNodePtr DfGraphConvertor::TraceTupleGetItem(const CNodePtr &node, uint64_t *index) {
  1042. const int TUPLE_GET_ITEM_INDEX = 2;
  1043. if (node->inputs().size() < 3) { // "tuple_getitem" primitive must have 3 inputs
  1044. MS_LOG(EXCEPTION) << "length of inputs of TupleGetItem is less than 3";
  1045. }
  1046. auto index_node = node->inputs()[TUPLE_GET_ITEM_INDEX];
  1047. if (!index_node->isa<ValueNode>()) {
  1048. error_ = INVALID_ARGUMENT;
  1049. MS_LOG(EXCEPTION) << "can't convert get item with non-constant index";
  1050. }
  1051. *index = LongToUlong(GetValue<int64_t>(GetValueNode(index_node)));
  1052. return node->inputs()[1];
  1053. }
  1054. AnfNodePtr DfGraphConvertor::TraceDepend(const CNodePtr &node) {
  1055. auto cnode = node->cast<CNodePtr>();
  1056. if (cnode->inputs().size() < 3) { // "Depend" primitive have 3 inputs
  1057. MS_LOG(EXCEPTION) << "length of inputs of depend is less than 3";
  1058. }
  1059. return cnode->inputs()[1];
  1060. }
  1061. AnfNodePtr DfGraphConvertor::TraceMakeTuple(const CNodePtr &node, uint64_t index) {
  1062. if (index + 1 >= node->inputs().size()) {
  1063. MS_LOG(EXCEPTION) << "length of make_tuple is less than index: " << index;
  1064. }
  1065. return node->inputs()[index + 1];
  1066. }
  1067. OutHandler DfGraphConvertor::GetHandler(const AnfNodePtr &node, const std::stack<uint64_t> &index_stack,
  1068. AnfNode *const draw_index) {
  1069. if (node == nullptr) {
  1070. MS_LOG(ERROR) << "Get nullptr while trace real op";
  1071. return OutHandler(nullptr, "");
  1072. }
  1073. std::ostringstream ss;
  1074. ss << "op" << node.get();
  1075. if (index_stack.empty()) {
  1076. op_draw_name_[draw_index] = ss.str();
  1077. return OutHandler(Convert(node), "");
  1078. } else {
  1079. OpAdapterPtr adpt = FindAdapter(node, training_);
  1080. if (nullptr == adpt) {
  1081. MS_LOG(ERROR) << "Can not get node output as adpt is nullptr!";
  1082. error_ = NOT_FOUND;
  1083. return OutHandler(nullptr, "");
  1084. }
  1085. OperatorPtr op = Convert(node);
  1086. if (op == nullptr) {
  1087. error_ = NOT_FOUND;
  1088. MS_LOG(ERROR) << "Can not convert node for trace real op";
  1089. return OutHandler(nullptr, "");
  1090. }
  1091. op_draw_name_[draw_index] = ss.str();
  1092. return adpt->getOutput(Convert(node), UintToInt(index_stack.top()));
  1093. }
  1094. }
  1095. // get the real operator through maketuple tuple_getitem depend
  1096. OutHandler DfGraphConvertor::TraceRealOp(AnfNodePtr node) {
  1097. bool flag = IsPrimitiveCNode(node, prim::kPrimTupleGetItem) || IsPrimitiveCNode(node, prim::kPrimMakeTuple) ||
  1098. IsPrimitiveCNode(node, prim::kPrimDepend);
  1099. std::stack<uint64_t> index_stack;
  1100. auto draw_index = node.get();
  1101. while (flag) {
  1102. flag = false;
  1103. if (IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  1104. uint64_t index;
  1105. node = TraceTupleGetItem(node->cast<CNodePtr>(), &index);
  1106. index_stack.push(index);
  1107. flag = true;
  1108. } else if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1109. if (index_stack.empty()) {
  1110. MS_LOG(ERROR) << "TraceRealOp find a make_tuple node";
  1111. return OutHandler(nullptr, "");
  1112. } else {
  1113. node = TraceMakeTuple(node->cast<CNodePtr>(), index_stack.top());
  1114. index_stack.pop();
  1115. flag = true;
  1116. }
  1117. } else if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1118. node = TraceDepend(node->cast<CNodePtr>());
  1119. flag = true;
  1120. }
  1121. }
  1122. return GetHandler(node, index_stack, draw_index);
  1123. }
  1124. void DfGraphConvertor::ConvertTupleGetItem(const CNodePtr node) {
  1125. auto handle = TraceRealOp(node);
  1126. if (handle.op == nullptr) {
  1127. MS_LOG(ERROR) << "Failed to trace tuple get item";
  1128. return;
  1129. }
  1130. out_handle_cache_[node.get()] = handle;
  1131. }
  1132. // Get the real op for tuple_getitem through make tuple, or depend
  1133. AnfNodePtr DfGraphConvertor::GetRealOpNode(AnfNodePtr node) {
  1134. const int TUPLE_GET_ITEM_INDEX = 2;
  1135. if (IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  1136. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1137. if (node_inputs.size() != 3) { // "tuple_getitem" primitive must have 3 inputs
  1138. MS_LOG(ERROR) << "tuple get item node not correct!";
  1139. error_ = FAILED;
  1140. return node;
  1141. }
  1142. MS_EXCEPTION_IF_NULL(node_inputs[TUPLE_GET_ITEM_INDEX]);
  1143. if (!node_inputs[TUPLE_GET_ITEM_INDEX]->isa<ValueNode>()) {
  1144. error_ = INVALID_ARGUMENT;
  1145. MS_LOG(EXCEPTION) << "can't convert get item with non-constant index";
  1146. }
  1147. auto value_ptr = GetValueNode(node_inputs[TUPLE_GET_ITEM_INDEX])->cast<Int32ImmPtr>();
  1148. if (value_ptr == nullptr) {
  1149. MS_LOG(ERROR) << "Can not convert get item as value is nullptr!";
  1150. error_ = FAILED;
  1151. return node;
  1152. }
  1153. int64_t index = value_ptr->value();
  1154. // make_tuple apply inputs:make_tuple, [tuple_items,]
  1155. if (IsPrimitiveCNode(node_inputs[1], prim::kPrimMakeTuple)) {
  1156. auto tuple_inputs = node->cast<CNodePtr>()->inputs();
  1157. if (tuple_inputs.size() < IntToSize(index + 1)) {
  1158. MS_LOG(ERROR) << "make tuple input items node not correct! size:" << tuple_inputs.size()
  1159. << ", item index:" << index;
  1160. error_ = FAILED;
  1161. return node;
  1162. }
  1163. return GetRealOpNode(tuple_inputs[IntToSize(index + 1)]);
  1164. }
  1165. return GetRealOpNode(node_inputs[1]);
  1166. }
  1167. // depend apply inputs: depend,output,depended_node
  1168. if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1169. auto depend_inputs = node->cast<CNodePtr>()->inputs();
  1170. if (depend_inputs.size() != 3) { // "Depend" primitive have 3 inputs
  1171. MS_LOG(ERROR) << "depend input items not correct";
  1172. error_ = FAILED;
  1173. return node;
  1174. }
  1175. return GetRealOpNode(depend_inputs[1]);
  1176. }
  1177. return node;
  1178. }
  1179. // convert the anf node to corresponding operator list
  1180. std::vector<OperatorPtr> DfGraphConvertor::ConvertDependNode(const AnfNodePtr node) {
  1181. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1182. std::vector<OperatorPtr> op_lists;
  1183. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1184. for (size_t index = 1; index < node_inputs.size(); index++) {
  1185. auto op = Convert(GetRealOpNode(node_inputs[index]));
  1186. if (op == nullptr) {
  1187. MS_LOG(ERROR) << "Convert control depend node to operator failed";
  1188. error_ = FAILED;
  1189. return std::vector<OperatorPtr>({});
  1190. }
  1191. op_lists.push_back(op);
  1192. }
  1193. return op_lists;
  1194. }
  1195. auto op = Convert(GetRealOpNode(node));
  1196. if (op == nullptr) {
  1197. MS_LOG(ERROR) << "Convert control depend node to operator failed";
  1198. error_ = FAILED;
  1199. return std::vector<OperatorPtr>({});
  1200. }
  1201. return std::vector<OperatorPtr>({op});
  1202. }
  1203. // get the anf node list for depend
  1204. std::vector<AnfNodePtr> DfGraphConvertor::GetDependNodes(const AnfNodePtr &node) {
  1205. std::vector<AnfNodePtr> nodes;
  1206. // for make tuple, should control depend on the tuple items
  1207. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1208. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1209. for (size_t index = 1; index < node_inputs.size(); index++) {
  1210. nodes.push_back(GetRealOpNode(node_inputs[index]));
  1211. }
  1212. return nodes;
  1213. }
  1214. // for parameter ,find the apply that used the parameter as the control depended node
  1215. if (node->isa<Parameter>()) {
  1216. auto uses = node->func_graph()->manager()->node_users()[node];
  1217. for (auto &use : uses) {
  1218. auto use_node = use.first;
  1219. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend))) {
  1220. nodes.push_back(GetRealOpNode(use_node));
  1221. }
  1222. }
  1223. return nodes;
  1224. }
  1225. nodes.push_back(GetRealOpNode(node));
  1226. return nodes;
  1227. }
  1228. void DfGraphConvertor::DrawControlDepend(const AnfNodePtr &src_node, const AnfNodePtr &dest_node) {
  1229. #ifdef DRAW_GE_GRAPH
  1230. auto src_depend_nodes = GetDependNodes(src_node);
  1231. auto dst_depend_nodes = GetDependNodes(dest_node);
  1232. if (src_depend_nodes.size() == 1 && dst_depend_nodes.size() > 1) {
  1233. for (auto &item : dst_depend_nodes) {
  1234. compute_sout_ << op_draw_name_[src_depend_nodes[0].get()] << " -> " << op_draw_name_[item.get()]
  1235. << "[style=\"dotted\"]" << endl;
  1236. }
  1237. } else if (src_depend_nodes.size() > 1 && dst_depend_nodes.size() == 1) {
  1238. for (auto &item : src_depend_nodes) {
  1239. compute_sout_ << op_draw_name_[item.get()] << " -> " << op_draw_name_[dst_depend_nodes[0].get()]
  1240. << "[style=\"dotted\"]" << endl;
  1241. }
  1242. } else if (src_depend_nodes.size() == 1 && dst_depend_nodes.size() == 1) {
  1243. compute_sout_ << op_draw_name_[src_depend_nodes[0].get()] << " -> " << op_draw_name_[dst_depend_nodes[0].get()]
  1244. << "[style=\"dotted\"]" << endl;
  1245. }
  1246. #endif
  1247. }
  1248. void DfGraphConvertor::GetDependOnParameterUse(const CNodePtr &node, const AnfNodePtr &src_node,
  1249. const AnfNodePtr &dest_node,
  1250. const std::shared_ptr<std::vector<OperatorPtr>> &src_ops_list,
  1251. const std::shared_ptr<std::vector<OperatorPtr>> &dst_ops_list) {
  1252. if (src_node->isa<Parameter>()) {
  1253. auto uses = node->func_graph()->manager()->node_users()[src_node];
  1254. for (auto &use : uses) {
  1255. auto use_node = use.first;
  1256. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend)) &&
  1257. (!IsPrimitiveCNode(use_node, prim::kPrimMakeTuple))) {
  1258. auto converted_list = ConvertDependNode(use_node);
  1259. src_ops_list->insert(src_ops_list->end(), converted_list.begin(), converted_list.end());
  1260. }
  1261. }
  1262. }
  1263. if (dest_node->isa<Parameter>()) {
  1264. auto uses = node->func_graph()->manager()->node_users()[dest_node];
  1265. for (auto &use : uses) {
  1266. auto use_node = use.first;
  1267. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend)) &&
  1268. (!IsPrimitiveCNode(use_node, prim::kPrimMakeTuple))) {
  1269. auto converted_list = ConvertDependNode(use_node);
  1270. dst_ops_list->insert(dst_ops_list->end(), converted_list.begin(), converted_list.end());
  1271. }
  1272. }
  1273. }
  1274. }
  1275. bool DfGraphConvertor::GetControlDependList(const CNodePtr &node,
  1276. const std::shared_ptr<std::vector<OperatorPtr>> &src_ops_list,
  1277. const std::shared_ptr<std::vector<OperatorPtr>> &dst_ops_list) {
  1278. const int CONTROL_DEPEND_INDEX = 0;
  1279. const int SRC_NODE_INDEX = 1;
  1280. const int DEST_NODE_INDEX = 2;
  1281. const int DEPEND_MODE_NORMAL_USE = 0;
  1282. const int DEPEND_MODE_ON_PARAMETER_USE = 1;
  1283. auto node_inputs = node->inputs();
  1284. if (node_inputs.size() <= DEST_NODE_INDEX) {
  1285. MS_LOG(WARNING) << "Control depend node input size error";
  1286. return false;
  1287. }
  1288. auto src_node = node_inputs[SRC_NODE_INDEX];
  1289. auto dest_node = node_inputs[DEST_NODE_INDEX];
  1290. if ((src_node == nullptr) || (dest_node == nullptr)) {
  1291. MS_LOG(ERROR) << "Control depend node miss src or dest node";
  1292. error_ = FAILED;
  1293. return false;
  1294. }
  1295. AnfNodePtr fn = node_inputs[CONTROL_DEPEND_INDEX];
  1296. PrimitivePtr prim_ptr = GetValueNode<PrimitivePtr>(fn);
  1297. ValuePtr mode_ptr = prim_ptr->GetAttr("depend_mode");
  1298. int depend_mode = DEPEND_MODE_NORMAL_USE;
  1299. if (mode_ptr != nullptr) {
  1300. auto mode_int = mode_ptr->cast<Int64ImmPtr>();
  1301. MS_EXCEPTION_IF_NULL(mode_int);
  1302. depend_mode = mode_int->value();
  1303. MS_LOG(DEBUG) << "depend_mode = " << depend_mode;
  1304. }
  1305. if (depend_mode == DEPEND_MODE_ON_PARAMETER_USE) {
  1306. GetDependOnParameterUse(node, src_node, dest_node, src_ops_list, dst_ops_list);
  1307. }
  1308. if (src_node->isa<CNode>()) {
  1309. auto converted_list = ConvertDependNode(src_node);
  1310. src_ops_list->insert(src_ops_list->end(), converted_list.begin(), converted_list.end());
  1311. }
  1312. if (dest_node->isa<CNode>()) {
  1313. auto converted_list = ConvertDependNode(dest_node);
  1314. dst_ops_list->insert(dst_ops_list->end(), converted_list.begin(), converted_list.end());
  1315. }
  1316. if (src_ops_list->empty() || dst_ops_list->empty()) {
  1317. MS_LOG(DEBUG) << "Control depend node's src or dest node is not a CNode, ignore it";
  1318. error_ = SUCCESS;
  1319. }
  1320. return true;
  1321. }
  1322. void DfGraphConvertor::ConvertControlDependNode(const CNodePtr node) {
  1323. const int SRC_NODE_INDEX = 1;
  1324. const int DEST_NODE_INDEX = 2;
  1325. if (control_depend_cache_.find(node.get()) != control_depend_cache_.end()) {
  1326. return;
  1327. }
  1328. auto node_inputs = node->inputs();
  1329. if (node_inputs.size() <= DEST_NODE_INDEX) {
  1330. MS_LOG(WARNING) << "Control depend node input size error";
  1331. return;
  1332. }
  1333. auto src_node = node_inputs[SRC_NODE_INDEX];
  1334. auto dest_node = node_inputs[DEST_NODE_INDEX];
  1335. if ((src_node == nullptr) || (dest_node == nullptr)) {
  1336. MS_LOG(ERROR) << "Control depend node miss src or dest node";
  1337. error_ = FAILED;
  1338. return;
  1339. }
  1340. std::shared_ptr<std::vector<OperatorPtr>> src_ops_list = std::make_shared<std::vector<OperatorPtr>>();
  1341. std::shared_ptr<std::vector<OperatorPtr>> dst_ops_list = std::make_shared<std::vector<OperatorPtr>>();
  1342. if (!GetControlDependList(node, src_ops_list, dst_ops_list)) {
  1343. MS_LOG(ERROR) << "Get depend list failed";
  1344. error_ = FAILED;
  1345. return;
  1346. }
  1347. std::vector<ControlEdge> control_edges;
  1348. if (src_ops_list->size() == 1 && dst_ops_list->size() > 1) {
  1349. (void)std::transform(dst_ops_list->begin(), dst_ops_list->end(), std::back_inserter(control_edges),
  1350. [src_ops_list](const OperatorPtr &op) -> ControlEdge {
  1351. return {(*src_ops_list)[0], op};
  1352. });
  1353. } else if (src_ops_list->size() > 1 && dst_ops_list->size() == 1) {
  1354. (void)std::transform(src_ops_list->begin(), src_ops_list->end(), std::back_inserter(control_edges),
  1355. [dst_ops_list](const OperatorPtr &op) -> ControlEdge {
  1356. return {op, (*dst_ops_list)[0]};
  1357. });
  1358. } else if (src_ops_list->size() == 1 && dst_ops_list->size() == 1) {
  1359. control_edges.push_back({(*src_ops_list)[0], (*dst_ops_list)[0]});
  1360. } else if (src_ops_list->empty() || dst_ops_list->empty()) {
  1361. MS_LOG(DEBUG) << "Depend list of src or dst is empty, ignore it";
  1362. } else {
  1363. MS_LOG(ERROR) << "Convert control depend node to operator failed, depend src:" << src_ops_list->size()
  1364. << " -> dst:" << dst_ops_list->size();
  1365. error_ = FAILED;
  1366. return;
  1367. }
  1368. control_depend_cache_[node.get()] = control_edges;
  1369. #ifdef DRAW_GE_GRAPH
  1370. DrawControlDepend(src_node, dest_node);
  1371. #endif
  1372. }
  1373. bool DfGraphConvertor::CheckCNode(const std::string &name, const CNodePtr node) {
  1374. // ignore apply node of return
  1375. if (name == "return" || name == "Depend") {
  1376. return false;
  1377. }
  1378. if (name == "" && GetCNodeFuncName(node) == "switch_layer") {
  1379. return false;
  1380. }
  1381. if (name == "Partial") {
  1382. return false;
  1383. }
  1384. // make_tuple is used for a dynamic_input, convert it to a vector of OutHandlers
  1385. if (name == "make_tuple") {
  1386. ConvertMakeTuple(node);
  1387. return false;
  1388. }
  1389. // As for nodes with multi outputs, convert tuple_getitem to OutHandle
  1390. if (name == "tuple_getitem") {
  1391. ConvertTupleGetItem(node);
  1392. return false;
  1393. }
  1394. if (name == "ControlDepend") {
  1395. ConvertControlDependNode(node);
  1396. return false;
  1397. }
  1398. return true;
  1399. }
  1400. OperatorPtr DfGraphConvertor::ConvertCNode(const CNodePtr node) {
  1401. std::string name = GetCNodeTargetFuncName(node);
  1402. if (!CheckCNode(name, node)) {
  1403. return nullptr;
  1404. }
  1405. // get corresponding OpAdapter
  1406. OpAdapterPtr adpt = FindAdapter(node, training_);
  1407. if (adpt == nullptr) {
  1408. error_ = NOT_FOUND;
  1409. return nullptr;
  1410. }
  1411. // get operator
  1412. OperatorPtr op = nullptr;
  1413. auto it_op = op_cache_.find(node.get());
  1414. if (it_op != op_cache_.end()) {
  1415. op = it_op->second;
  1416. } else {
  1417. op = adpt->generate(node);
  1418. }
  1419. // set attribute for primitive
  1420. (void)adpt->setAttr(op, node);
  1421. // add into cache
  1422. (void)op_cache_.insert(std::make_pair(node.get(), op));
  1423. DrawCNode(node, adpt);
  1424. return op_cache_[node.get()];
  1425. }
  1426. OperatorPtr DfGraphConvertor::ConvertParameter(const AnfNodePtr node) {
  1427. // convert Parameter in ANF to variable in DataFlow
  1428. auto op = FindAdapter(node, training_)->generate(node);
  1429. op_cache_[node.get()] = op;
  1430. // build index for parameter using name
  1431. std::string name = std::static_pointer_cast<Parameter>(node)->name();
  1432. params_[name] = node;
  1433. std::ostringstream ss;
  1434. ss << "op" << node.get();
  1435. op_draw_name_[node.get()] = ss.str();
  1436. compute_sout_ << ss.str() << "[shape=octagon, label=\"" << name << "\"]" << endl;
  1437. return op_cache_[node.get()];
  1438. }
  1439. Status DfGraphConvertor::TryConvertValueNodeToMultiConst(const ValueNodePtr node) {
  1440. MS_EXCEPTION_IF_NULL(node);
  1441. ValuePtr value = node->value();
  1442. MS_EXCEPTION_IF_NULL(value);
  1443. if (!value->isa<ValueList>() && !value->isa<ValueTuple>()) {
  1444. return FAILED;
  1445. }
  1446. auto vec = value->isa<ValueTuple>() ? value->cast<ValueTuplePtr>()->value() : value->cast<ValueListPtr>()->value();
  1447. if (vec.empty()) {
  1448. return FAILED;
  1449. }
  1450. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  1451. for (size_t i = 0; i < vec.size(); i++) {
  1452. MS_EXCEPTION_IF_NULL(vec[i]);
  1453. if (vec[i]->isa<MeTensor>()) {
  1454. GeTensorPtr ge_tensor = transform::TransformUtil::ConvertTensor(vec[i]->cast<MeTensorPtr>(), kOpFormat_NCHW);
  1455. auto const_op = std::make_shared<Constant>(node->fullname_with_scope() + "/const/inputs/" + std::to_string(i));
  1456. (void)const_op->set_attr_value(*ge_tensor);
  1457. (void)const_op->update_output_desc_y(ge_tensor->GetTensorDesc());
  1458. tuple_items->emplace_back(OutHandler(const_op, ""));
  1459. } else {
  1460. return FAILED;
  1461. }
  1462. }
  1463. if (tuple_items->empty()) {
  1464. return FAILED;
  1465. }
  1466. tuple_out_handle_cache_[node.get()] = tuple_items;
  1467. return SUCCESS;
  1468. }
  1469. OperatorPtr DfGraphConvertor::ConvertValueNode(const ValueNodePtr node) {
  1470. // convert valuenode in ANF to Const in DataFlow
  1471. // find paramerte referenced by SymbolicKeyInstance of valuenode
  1472. std::ostringstream ss;
  1473. ss << "op" << node.get();
  1474. op_draw_name_[node.get()] = ss.str();
  1475. compute_sout_ << ss.str() << "[label= \"" << node->value()->ToString() << "\" shape=ellipse]" << endl;
  1476. if (TryConvertValueNodeToMultiConst(node) == SUCCESS) {
  1477. MS_LOG(INFO) << "Convert value node to multi Constant OP success";
  1478. return nullptr;
  1479. }
  1480. OpAdapterPtr adpt = FindAdapter(node, training_);
  1481. if (adpt == nullptr) {
  1482. error_ = NOT_FOUND;
  1483. return nullptr;
  1484. }
  1485. auto op = adpt->generate(node);
  1486. // set const's attrs
  1487. if (adpt->setAttr(op, "value", node->value()) != 0) {
  1488. MS_LOG(WARNING) << "set attr value for const failed";
  1489. }
  1490. #if (defined ENABLE_GE)
  1491. auto const_op = std::static_pointer_cast<Constant>(op);
  1492. if (const_op == nullptr) {
  1493. MS_LOG(ERROR) << "Get Constant operator failed";
  1494. return nullptr;
  1495. }
  1496. auto ge_tensor = const_op->get_attr_value();
  1497. auto ge_desc = ge_tensor.GetTensorDesc();
  1498. (void)const_op->update_output_desc_y(ge_desc);
  1499. #endif
  1500. op_cache_[node.get()] = op;
  1501. return op_cache_[node.get()];
  1502. }
  1503. void DfGraphConvertor::DrawCNode(const CNodePtr node, const OpAdapterPtr adpt) {
  1504. if (nullptr == adpt || nullptr == node) {
  1505. MS_LOG(ERROR) << "Failed to draw apply node as adpt or node is nullptr!";
  1506. return;
  1507. }
  1508. std::ostringstream ss;
  1509. ss << "op" << node.get();
  1510. op_draw_name_[node.get()] = ss.str();
  1511. compute_sout_ << ss.str() << "[label=<";
  1512. compute_sout_ << "<table border='1' cellborder='1'>" << endl;
  1513. auto input_map = adpt->getInputMap();
  1514. auto dyn_input_map = adpt->getDynInputMap();
  1515. if (input_map.size() + dyn_input_map.size() > 0) {
  1516. compute_sout_ << "<tr>";
  1517. for (auto &it : input_map) {
  1518. compute_sout_ << "<td port='" << it.first << "'>" << it.second.name << "</td>";
  1519. }
  1520. for (auto &it : dyn_input_map) {
  1521. compute_sout_ << "<td port='" << it.first << "'>" << it.second.name << "</td>";
  1522. }
  1523. compute_sout_ << "</tr>" << endl;
  1524. }
  1525. compute_sout_ << "<tr><td colspan=\"" << (input_map.size() + dyn_input_map.size()) << "\">\"" << node->ToString()
  1526. << ":" << GetCNodeTargetFuncName(node) << "\"</td></tr>" << endl;
  1527. // print attrs' values
  1528. auto atts = adpt->GetAttrsFromDrawGraph();
  1529. for (auto &it : atts) {
  1530. compute_sout_ << "<tr><td colspan=\"" << (input_map.size() + dyn_input_map.size()) << "\">\"" << it
  1531. << "\"</td></tr>";
  1532. }
  1533. adpt->clearAttrVect();
  1534. compute_sout_ << "</table>> shape=plaintext]" << endl;
  1535. }
  1536. void DfGraphConvertor::RegisterAdapter(const std::string &name, OpAdapterPtr adpt) {
  1537. OpAdapterMap::get()[name] = std::make_shared<OpAdapterDesc>(adpt);
  1538. }
  1539. void DfGraphConvertor::RegisterAdapter(const std::string &name, OpAdapterPtr train_adpt, OpAdapterPtr infer_adpt) {
  1540. OpAdapterMap::get()[name] = std::make_shared<OpAdapterDesc>(train_adpt, infer_adpt);
  1541. }
  1542. } // namespace transform
  1543. } // namespace mindspore