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.

anf_ir_utils.cc 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /**
  2. * Copyright 2019-2021 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 "debug/anf_ir_utils.h"
  17. #include <fstream>
  18. #include <map>
  19. #include <memory>
  20. #include <algorithm>
  21. #include <iomanip>
  22. #include "utils/hash_map.h"
  23. #include "ir/graph_utils.h"
  24. #include "utils/symbolic.h"
  25. #include "ir/meta_func_graph.h"
  26. #include "ir/param_info.h"
  27. #include "pybind_api/ir/tensor_py.h"
  28. #include "pipeline/jit/parse/python_adapter.h"
  29. #include "pipeline/jit/parse/resolve.h"
  30. #include "frontend/operator/composite/composite.h"
  31. #include "frontend/operator/composite/map.h"
  32. #include "utils/ordered_map.h"
  33. #include "utils/ordered_set.h"
  34. #include "utils/utils.h"
  35. #include "utils/shape_utils.h"
  36. #include "debug/trace.h"
  37. #include "utils/label.h"
  38. #include "utils/ms_context.h"
  39. #include "frontend/operator/ops.h"
  40. #include "pipeline/jit/base.h"
  41. #include "debug/common.h"
  42. using mindspore::tensor::TensorPy;
  43. namespace mindspore {
  44. std::string GetKernelNodeName(const AnfNodePtr &anf_node) {
  45. std::string kernel_name = anf_node->fullname_with_scope();
  46. if (kernel_name.empty()) {
  47. kernel_name = anf_node->ToString();
  48. }
  49. MS_LOG(DEBUG) << "Full scope kernel name is " << kernel_name << ".";
  50. return kernel_name;
  51. }
  52. // ============================================= MindSpore IR Exporter =============================================
  53. std::string AnfExporter::GetNodeType(const AnfNodePtr &nd) {
  54. ValuePtr tensor_value = nullptr;
  55. auto abstract = nd->abstract();
  56. if (abstract != nullptr && abstract->isa<abstract::AbstractTensor>()) {
  57. tensor_value = abstract->BuildValue();
  58. }
  59. abstract::ShapePtr shape = nd->Shape() == nullptr ? nullptr : dyn_cast<abstract::Shape>(nd->Shape());
  60. TypePtr type = dyn_cast<Type>(nd->Type());
  61. std::ostringstream oss;
  62. if ((shape != nullptr) && (type != nullptr)) {
  63. oss << type->DumpText() << shape->DumpText();
  64. if (tensor_value != nullptr && tensor_value != kAnyValue) {
  65. oss << "(...)";
  66. }
  67. } else if (type != nullptr) {
  68. oss << type->DumpText();
  69. if (tensor_value != nullptr && tensor_value != kAnyValue) {
  70. oss << "(...)";
  71. }
  72. } else {
  73. oss << "Undefined";
  74. }
  75. return oss.str();
  76. }
  77. int AnfExporter::GetParamIndex(const FuncGraphPtr &func_graph, const AnfNodePtr &param, bool throw_excp) {
  78. if (func_graph == nullptr || param == nullptr) {
  79. return -1;
  80. }
  81. FuncGraphPtr fg = func_graph;
  82. while (fg != nullptr) {
  83. if (exported.find(fg) == exported.end()) {
  84. if (!check_integrity_) {
  85. break;
  86. }
  87. MS_LOG(EXCEPTION) << "Can not find func graph '" << fg->DumpText() << "'";
  88. }
  89. auto param_map = exported[fg];
  90. if (param_map.find(param) != param_map.end()) {
  91. return param_map[param];
  92. }
  93. fg = fg->parent();
  94. }
  95. if (throw_excp) {
  96. MS_LOG(EXCEPTION) << "Can not find index for param '" << param->DumpText() << "' for func graph '"
  97. << func_graph->DumpText() << "'";
  98. }
  99. return -1;
  100. }
  101. // Try to find index of parameter for SymbolicKeyInstance from all exported graphs
  102. // NOTICE: Suppose name of all parameters in SymbolicKeyInstance are different
  103. int AnfExporter::GetParamIndexFromExported(const AnfNodePtr &param) {
  104. if (param == nullptr) {
  105. return -1;
  106. }
  107. int ret = -1;
  108. for (const auto &item : exported) {
  109. auto pram_iter = item.second.find(param);
  110. if (pram_iter != item.second.end()) {
  111. return pram_iter->second;
  112. }
  113. }
  114. return ret;
  115. }
  116. std::string AnfExporter::GetValueNodeText(const FuncGraphPtr &fg, const ValueNodePtr &node) {
  117. MS_EXCEPTION_IF_NULL(node);
  118. return GetValueText(fg, node->value());
  119. }
  120. std::string AnfExporter::GetMultitypeFuncGraphText(const prim::MultitypeFuncGraphPtr &mt_func_graph) {
  121. auto py_funcs = mt_func_graph->GetPyFunctions();
  122. if (py_funcs.empty()) {
  123. return "";
  124. }
  125. std::ostringstream oss;
  126. oss << "{";
  127. bool is_first = true;
  128. for (const auto &py_func : py_funcs) {
  129. if (is_first) {
  130. is_first = false;
  131. } else {
  132. oss << ", ";
  133. }
  134. oss << "(";
  135. for (size_t i = 0; i < py_func.first.size(); ++i) {
  136. if (i > 0) {
  137. oss << ", ";
  138. }
  139. oss << py_func.first[i]->DumpText();
  140. }
  141. oss << ")";
  142. }
  143. oss << "}";
  144. return oss.str();
  145. }
  146. inline bool Skip(const MetaFuncGraphPtr &meta_func_graph) {
  147. return meta_func_graph->isa<prim::Tail>() || meta_func_graph->isa<prim::MakeTupleGradient>() ||
  148. meta_func_graph->isa<prim::MakeListGradient>() || meta_func_graph->isa<prim::TupleAdd>() ||
  149. meta_func_graph->isa<prim::TupleSlice>() || meta_func_graph->isa<prim::UnpackCall>() ||
  150. meta_func_graph->isa<prim::ZipOperation>() || meta_func_graph->isa<prim::ListAppend>() ||
  151. meta_func_graph->isa<prim::DoSignatureMetaFuncGraph>();
  152. }
  153. /* inherit relation of MetaFuncGraph
  154. *
  155. * MetaGraph
  156. * ├── MultitypeGraph
  157. * ├── HyperMap
  158. * │ └── HyperMapPy
  159. * ├── Map
  160. * │ └── MapPy
  161. * ├── Tail
  162. * ├── MakeTupleGradient
  163. * ├── MakeListGradient
  164. * ├── GradOperation
  165. * └── TupleAdd
  166. */
  167. std::string AnfExporter::GetMetaFuncGraphText(const MetaFuncGraphPtr &meta_func_graph) {
  168. if (meta_func_graph == nullptr) {
  169. return "";
  170. }
  171. std::ostringstream oss;
  172. oss << meta_func_graph->type_name() << "::" << meta_func_graph->name();
  173. if (meta_func_graph->isa<prim::MultitypeFuncGraph>()) {
  174. prim::MultitypeFuncGraphPtr mt_func_graph = meta_func_graph->cast<prim::MultitypeFuncGraphPtr>();
  175. oss << GetMultitypeFuncGraphText(mt_func_graph);
  176. } else if (meta_func_graph
  177. ->isa<prim::HyperMapPy>()) { // This statement must before 'meta_graph->isa<prim::HyperMap>()'
  178. auto hyper_map = meta_func_graph->cast<prim::HyperMapPyPtr>();
  179. if (hyper_map->GetFnLeaf() != nullptr) {
  180. oss << "{fn_leaf=" << GetMetaFuncGraphText(hyper_map->GetFnLeaf()) << "}";
  181. }
  182. } else if (meta_func_graph->isa<prim::HyperMap>()) {
  183. auto hyper_map = meta_func_graph->cast<prim::HyperMapPtr>();
  184. if (hyper_map->GetFnLeaf() != nullptr) {
  185. oss << "{fn_leaf=" << GetMetaFuncGraphText(hyper_map->GetFnLeaf()) << "}";
  186. }
  187. } else if (meta_func_graph->isa<prim::MapPy>()) { // This statement must before 'meta_graph->isa<prim::Map>()'
  188. auto map = meta_func_graph->cast<prim::MapPyPtr>();
  189. if (map->GetFnLeaf() != nullptr) {
  190. oss << "{fn_leaf=" << GetMetaFuncGraphText(map->GetFnLeaf()) << "}";
  191. }
  192. } else if (meta_func_graph->isa<prim::Map>()) {
  193. auto map = meta_func_graph->cast<prim::MapPtr>();
  194. if (map->GetFnLeaf() != nullptr) {
  195. oss << "{fn_leaf=" << GetMetaFuncGraphText(map->GetFnLeaf()) << "}";
  196. }
  197. } else if (meta_func_graph->isa<prim::GradOperation>()) {
  198. prim::GradOperationPtr grad_op = meta_func_graph->cast<prim::GradOperationPtr>();
  199. oss << "{get_all=" << grad_op->get_all_ << ", get_by_list=" << grad_op->get_by_list_
  200. << ", sens_param=" << grad_op->sens_param_ << "}";
  201. } else if (Skip(meta_func_graph)) {
  202. // Do nothing
  203. } else {
  204. MS_LOG(EXCEPTION) << "Unknown MetaFuncGraph type " << meta_func_graph->type_name();
  205. }
  206. return oss.str();
  207. }
  208. std::string AnfExporter::GetPrimitiveText(const PrimitivePtr &prim) {
  209. std::ostringstream oss;
  210. if (prim == nullptr) {
  211. return oss.str();
  212. }
  213. oss << prim->type_name() << "::" << prim->name();
  214. // Output primitive type
  215. oss << "{prim_type=" << static_cast<int>(prim->prim_type()) << "}";
  216. // Output primitive attributes
  217. oss << prim->GetAttrsText();
  218. if (prim->isa<prim::DoSignaturePrimitive>()) {
  219. auto do_signature = dyn_cast<prim::DoSignaturePrimitive>(prim);
  220. auto &func = do_signature->function();
  221. if (func->isa<Primitive>()) {
  222. auto sig_prim = dyn_cast<Primitive>(func);
  223. oss << sig_prim->GetAttrsText();
  224. }
  225. }
  226. return oss.str();
  227. }
  228. std::string AnfExporter::GetNameSpaceText(const parse::NameSpacePtr &ns) {
  229. std::ostringstream oss;
  230. if (ns == nullptr) {
  231. return oss.str();
  232. }
  233. // Dump related module information in Namespace
  234. oss << ns->type_name() << "::" << ns->module();
  235. return oss.str();
  236. }
  237. std::string AnfExporter::GetSymbolicKeyInstanceText(const FuncGraphPtr &func_graph,
  238. const SymbolicKeyInstancePtr &sym_inst) {
  239. MS_EXCEPTION_IF_NULL(func_graph);
  240. MS_EXCEPTION_IF_NULL(sym_inst);
  241. AnfNodePtr sym_node = sym_inst->node();
  242. MS_EXCEPTION_IF_NULL(sym_node);
  243. std::ostringstream oss;
  244. if (sym_node->isa<Parameter>()) {
  245. int idx = GetParamIndex(func_graph, sym_node, false);
  246. // If can not find SymbolicKeyInstance related parameter from ancestors,
  247. // try to find from all exported graphs
  248. if (idx < 0) {
  249. idx = GetParamIndexFromExported(sym_node);
  250. }
  251. if (idx < 0) {
  252. ParameterPtr p = dyn_cast<Parameter>(sym_node);
  253. if (p == nullptr) {
  254. MS_LOG(EXCEPTION) << "Sym_inst's node could not cast to parameter";
  255. }
  256. MS_LOG(WARNING) << "Can not find SymbolicKeyInstance: " << p->name();
  257. }
  258. oss << "SymInst(%para" << idx << ")";
  259. } else {
  260. MS_LOG(WARNING) << "SymbolicKeyInstance does not embed a parameter: " << sym_node->ToString();
  261. oss << "SymInst(cnode_" << sym_node->ToString() << ")";
  262. }
  263. return oss.str();
  264. }
  265. std::string AnfExporter::GetSequenceText(const FuncGraphPtr &func_graph, const ValuePtr &value) {
  266. std::ostringstream oss;
  267. // Output ValueList, ValueTuple
  268. ValueSequencePtr seq = dyn_cast<ValueSequence>(value);
  269. MS_EXCEPTION_IF_NULL(seq);
  270. MS_EXCEPTION_IF_NULL(value);
  271. bool is_tuple = value->isa<ValueTuple>();
  272. oss << (is_tuple ? "(" : "[");
  273. bool first_flag = true;
  274. for (auto elem : seq->value()) {
  275. if (first_flag) {
  276. first_flag = false;
  277. } else {
  278. oss << ", ";
  279. }
  280. oss << GetValueText(func_graph, elem);
  281. }
  282. oss << (is_tuple ? ")" : "]");
  283. return oss.str();
  284. }
  285. std::string AnfExporter::GetDictText(const FuncGraphPtr &func_graph, const ValuePtr &value) {
  286. std::ostringstream oss;
  287. ValueDictionaryPtr dict = value->cast<ValueDictionaryPtr>();
  288. oss << "{";
  289. bool first_flag = true;
  290. for (const auto &elem : dict->value()) {
  291. if (first_flag) {
  292. first_flag = false;
  293. } else {
  294. oss << ", ";
  295. }
  296. oss << "\"" << elem.first << "\": " << GetValueText(func_graph, elem.second);
  297. }
  298. oss << "}";
  299. return oss.str();
  300. }
  301. std::string AnfExporter::GetOtherValueText(const FuncGraphPtr &, const ValuePtr &value) {
  302. std::ostringstream oss;
  303. if (check_integrity_) {
  304. MS_LOG(EXCEPTION) << "Need to process type: " << value->type_name() << ", dump text: " << value->DumpText();
  305. }
  306. oss << value->type_name() << "[" << value->DumpText() << "]";
  307. return oss.str();
  308. }
  309. static bool CanUseDumpText(const ValuePtr &value) {
  310. return (value->isa<RefKey>() || value->isa<Scalar>() || value->isa<StringImm>() || value->isa<tensor::Tensor>() ||
  311. value->isa<parse::Symbol>() || value->isa<None>() || value->isa<Null>() || value->isa<ValueSlice>() ||
  312. value->isa<Type>() || value->isa<KeywordArg>());
  313. }
  314. std::string AnfExporter::GetValueText(const FuncGraphPtr &func_graph, const ValuePtr &value) {
  315. if (func_graph == nullptr || value == nullptr) {
  316. return "";
  317. }
  318. if (value->isa<Primitive>()) {
  319. return GetPrimitiveText(value->cast<PrimitivePtr>());
  320. }
  321. if (value->isa<MetaFuncGraph>()) {
  322. MetaFuncGraphPtr meta_func_graph = value->cast<MetaFuncGraphPtr>();
  323. return GetMetaFuncGraphText(meta_func_graph);
  324. }
  325. if (value->isa<SymbolicKeyInstance>()) {
  326. return GetSymbolicKeyInstanceText(func_graph, value->cast<SymbolicKeyInstancePtr>());
  327. }
  328. if (value->isa<ValueSequence>()) {
  329. return GetSequenceText(func_graph, value);
  330. }
  331. if (value->isa<ValueDictionary>()) {
  332. return GetDictText(func_graph, value);
  333. }
  334. if (value->isa<parse::NameSpace>()) {
  335. return GetNameSpaceText(value->cast<parse::NameSpacePtr>());
  336. }
  337. if (value->isa<parse::PyObjectWrapper>()) {
  338. return value->type_name();
  339. }
  340. if (CanUseDumpText(value)) {
  341. return value->DumpText();
  342. }
  343. return GetOtherValueText(func_graph, value);
  344. }
  345. // This function is used to output node in CNode's inputs
  346. std::string AnfExporter::GetAnfNodeText(const FuncGraphPtr &func_graph, const AnfNodePtr &node,
  347. const std::map<AnfNodePtr, int> &apply_map) {
  348. std::ostringstream oss;
  349. if (func_graph == nullptr || node == nullptr) {
  350. return oss.str();
  351. }
  352. if (node->isa<CNode>()) {
  353. auto iter = apply_map.find(node);
  354. if (iter == apply_map.end()) {
  355. MS_LOG(EXCEPTION) << "Can not find node '" << node->DumpText() << "' in apply_map";
  356. }
  357. oss << "%" << iter->second;
  358. } else if (node->isa<Parameter>()) {
  359. // Parameter maybe a free variable, so check it in its own funcgraph.
  360. oss << "%para" << GetParamIndex(node->func_graph(), node, check_integrity_);
  361. } else if (IsValueNode<FuncGraph>(node)) {
  362. FuncGraphPtr fg = GetValueNode<FuncGraphPtr>(node);
  363. oss << fg->type_name() << "::fg_" << fg->debug_info()->get_id();
  364. if (!func_graph_set.contains(fg) && exported.find(fg) == exported.end() && export_used_) {
  365. func_graph_set.add(fg);
  366. }
  367. } else if (node->isa<ValueNode>()) {
  368. oss << GetValueNodeText(func_graph, node->cast<ValueNodePtr>());
  369. } else {
  370. MS_LOG(EXCEPTION) << "Unknown node '" << node->DumpText() << "'";
  371. }
  372. return oss.str();
  373. }
  374. void AnfExporter::OutputParameters(std::ofstream &ofs, const std::vector<AnfNodePtr> &parameters,
  375. ParamIndexMap *param_map) {
  376. bool first_flag = true;
  377. for (const AnfNodePtr &param : parameters) {
  378. if (first_flag) {
  379. first_flag = false;
  380. ofs << " ";
  381. } else {
  382. ofs << " , ";
  383. }
  384. (*param_map)[param] = param_index;
  385. std::string type_info = GetNodeType(param);
  386. // Output parameter and type
  387. if (type_info == "Undefined") {
  388. ofs << "%para" << param_index;
  389. } else {
  390. ofs << "%para" << param_index << " : " << type_info;
  391. }
  392. // Output comment
  393. ofs << " # " << param->DumpText() << "\n";
  394. param_index += 1;
  395. }
  396. }
  397. void AnfExporter::OutputStatementComment(std::ofstream &ofs, const CNodePtr &node) {
  398. if (node == nullptr) {
  399. return;
  400. }
  401. // Output type of each input argument
  402. auto &inputs = node->inputs();
  403. if (inputs.size() > 1) {
  404. ofs << " #(";
  405. for (size_t i = 1; i < inputs.size(); ++i) {
  406. if (i != 1) {
  407. ofs << ", ";
  408. }
  409. AnfNodePtr arg = inputs[i];
  410. ofs << GetNodeType(arg);
  411. }
  412. ofs << ")";
  413. }
  414. // Output other comment, map the graph name to original representation(containing unicode character)
  415. std::ostringstream comment;
  416. comment << " #";
  417. bool has_comment = false;
  418. for (size_t i = 0; i < inputs.size(); ++i) {
  419. AnfNodePtr arg = inputs[i];
  420. if (!IsValueNode<FuncGraph>(arg)) {
  421. continue;
  422. }
  423. if (!has_comment) {
  424. has_comment = true;
  425. } else {
  426. comment << ",";
  427. }
  428. FuncGraphPtr fg = GetValueNode<FuncGraphPtr>(arg);
  429. auto func_graph_id = fg->debug_info()->get_id();
  430. comment << " fg_" << func_graph_id << "=" << fg->ToString();
  431. }
  432. if (has_comment) {
  433. ofs << comment.str();
  434. }
  435. ofs << " #scope: " << node->scope()->name();
  436. }
  437. void AnfExporter::OutputCNodeText(std::ofstream &ofs, const CNodePtr &cnode, const FuncGraphPtr &func_graph, int *idx,
  438. std::map<AnfNodePtr, int> *const apply_map) {
  439. auto &inputs = cnode->inputs();
  440. std::string op_text = GetAnfNodeText(func_graph, inputs[0], *apply_map);
  441. std::string fv_text = (cnode->func_graph() != func_graph) ? ("$(" + cnode->func_graph()->ToString() + "):") : "";
  442. // Non-return node
  443. if (cnode != func_graph->get_return()) {
  444. int apply_idx = (*idx)++;
  445. (*apply_map)[cnode] = apply_idx;
  446. std::string type_info = GetNodeType(cnode);
  447. if (type_info == "Undefined") {
  448. ofs << " %" << apply_idx << " = " << fv_text << op_text << "(";
  449. } else {
  450. ofs << " %" << apply_idx << " : " << fv_text << type_info << " = " << op_text << "(";
  451. }
  452. } else {
  453. ofs << " " << fv_text << op_text << "(";
  454. }
  455. for (size_t i = 1; i < inputs.size(); ++i) {
  456. if (i != 1) {
  457. ofs << ", ";
  458. }
  459. AnfNodePtr arg = inputs[i];
  460. ofs << GetAnfNodeText(func_graph, arg, *apply_map);
  461. }
  462. ofs << ")";
  463. }
  464. void AnfExporter::OutputCNode(std::ofstream &ofs, const CNodePtr &cnode, const FuncGraphPtr &func_graph, int *idx,
  465. std::map<AnfNodePtr, int> *const apply_map) {
  466. OutputCNodeText(ofs, cnode, func_graph, idx, apply_map);
  467. // Output comment
  468. OutputStatementComment(ofs, cnode);
  469. ofs << "\n";
  470. }
  471. void AnfExporter::OutputCNodes(std::ofstream &ofs, const std::vector<AnfNodePtr> &nodes, const FuncGraphPtr &func_graph,
  472. const TaggedNodeMap &tagged_cnodes_map) {
  473. if (func_graph == nullptr) {
  474. return;
  475. }
  476. MS_LOG_TRY_CATCH_SCOPE;
  477. int idx = 1;
  478. std::map<AnfNodePtr, int> apply_map;
  479. for (const AnfNodePtr &node : nodes) {
  480. MS_EXCEPTION_IF_NULL(node);
  481. if (!node->isa<CNode>()) {
  482. continue;
  483. }
  484. if (!tagged_cnodes_map.empty()) {
  485. auto iter = tagged_cnodes_map.find(node);
  486. if (iter != tagged_cnodes_map.end()) {
  487. ofs << "\n#------------------------> " << iter->second << "\n";
  488. }
  489. }
  490. auto cnode = node->cast<CNodePtr>();
  491. OutputCNode(ofs, cnode, func_graph, &idx, &apply_map);
  492. if (label_manage::GetGlobalTraceLabelType() == label_manage::TraceLabelType::kWithUniqueId) {
  493. ofs << trace::GetDebugInfo(cnode->debug_info(), " # ", kSourceLineTipDiscard) << "#"
  494. << label_manage::Label(cnode->debug_info()) << "\n";
  495. } else {
  496. ofs << trace::GetDebugInfo(cnode->debug_info(), " # ", kSourceLineTipDiscard) << "#" << cnode->ToString()
  497. << "\n";
  498. }
  499. }
  500. }
  501. void AnfExporter::OutputOrderList(std::ofstream &ofs, const FuncGraphPtr &func_graph) {
  502. auto &order_list = func_graph->order_list();
  503. if (order_list.empty()) {
  504. return;
  505. }
  506. constexpr int width = 4;
  507. ofs << "# order:\n";
  508. int i = 1;
  509. for (auto &node : order_list) {
  510. ofs << '#' << std::setw(width) << i << ": " << node->DebugString() << '\n';
  511. ++i;
  512. }
  513. }
  514. void AnfExporter::ExportOneFuncGraph(std::ofstream &ofs, const FuncGraphPtr &func_graph,
  515. const TaggedNodeMap &tagged_cnodes_map) {
  516. if (func_graph == nullptr) {
  517. return;
  518. }
  519. std::vector<AnfNodePtr> nodes = TopoSort(func_graph->get_return(), SuccIncoming, AlwaysInclude);
  520. std::vector<AnfNodePtr> parameters = func_graph->parameters();
  521. ParamIndexMap param_map;
  522. if (*(func_graph->switch_input())) {
  523. ofs << "switch_input: " << *(func_graph->switch_input()) << "\n";
  524. }
  525. if (*(func_graph->switch_layer_input())) {
  526. ofs << "switch_layer_input: " << *(func_graph->switch_layer_input()) << "\n";
  527. }
  528. ofs << "# [No." << (exported.size() + 1) << "] " << func_graph->DumpText() << "\n";
  529. if (label_manage::GetGlobalTraceLabelType() == label_manage::TraceLabelType::kWithUniqueId) {
  530. ofs << trace::GetDebugInfo(func_graph->debug_info(), "# ", kSourceLineTipDiscard) << "#"
  531. << label_manage::Label(func_graph->debug_info()) << "\n";
  532. } else {
  533. ofs << trace::GetDebugInfo(func_graph->debug_info(), "# ", kSourceLineTipDiscard) << "\n";
  534. }
  535. ofs << "funcgraph fg_" << func_graph->debug_info()->get_id();
  536. // Output name of parent of graph if exists
  537. if (func_graph->parent() != nullptr) {
  538. ofs << "[fg_" << func_graph->parent()->debug_info()->get_id() << "]";
  539. }
  540. ofs << "(\n";
  541. OutputParameters(ofs, parameters, &param_map);
  542. exported[func_graph] = param_map;
  543. ofs << (!parameters.empty() ? " " : "") << ") {\n";
  544. OutputCNodes(ofs, nodes, func_graph, tagged_cnodes_map);
  545. ofs << "}\n";
  546. OutputOrderList(ofs, func_graph);
  547. }
  548. void AnfExporter::ExportFuncGraph(const std::string &filename, const FuncGraphPtr &func_graph) {
  549. if (func_graph == nullptr) {
  550. return;
  551. }
  552. std::ofstream ofs(filename);
  553. if (!ofs.is_open()) {
  554. MS_LOG(ERROR) << "Open file '" << filename << "' failed!" << ErrnoToString(errno);
  555. return;
  556. }
  557. param_index = 1;
  558. TaggedNodeMap tagged_cnodes_map;
  559. func_graph_set.add(func_graph);
  560. while (!func_graph_set.empty()) {
  561. FuncGraphPtr fg = *func_graph_set.begin();
  562. ExportOneFuncGraph(ofs, fg, tagged_cnodes_map);
  563. ofs << "\n\n";
  564. (void)func_graph_set.erase(fg);
  565. }
  566. ofs << "# num of total function graphs: " << exported.size();
  567. ofs.close();
  568. }
  569. #ifdef ENABLE_DUMP_IR
  570. void ExportIR(const std::string &filename, const FuncGraphPtr &func_graph) {
  571. if (func_graph == nullptr) {
  572. return;
  573. }
  574. auto filepath = GetSaveGraphsPathName(Common::AddId(filename, ".dat"));
  575. auto real_filepath = Common::CreatePrefixPath(filepath);
  576. if (!real_filepath.has_value()) {
  577. MS_LOG(ERROR) << "The export ir path: " << filepath << " is not illegal.";
  578. return;
  579. }
  580. ChangeFileMode(real_filepath.value(), S_IWUSR);
  581. AnfExporter exporter;
  582. exporter.ExportFuncGraph(real_filepath.value(), func_graph);
  583. // Set file mode to read only by user
  584. ChangeFileMode(real_filepath.value(), S_IRUSR);
  585. }
  586. #else
  587. void ExportIR(const std::string &, const FuncGraphPtr &) {
  588. static bool already_printed = false;
  589. if (already_printed) {
  590. return;
  591. }
  592. already_printed = true;
  593. MS_LOG(WARNING) << "The functionality of dumping function graph IR is disabled, "
  594. << "please recompile source to enable it. See help of building script.";
  595. }
  596. void ExportIR(const std::string &filename, const std::vector<TaggedGraph> &graphs) {
  597. static bool already_printed = false;
  598. if (already_printed) {
  599. return;
  600. }
  601. already_printed = true;
  602. MS_LOG(WARNING) << "The functionality of dumping function graph IR is disabled, "
  603. << "please recompile source to enable it. See help of building script.";
  604. }
  605. #endif
  606. } // namespace mindspore