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

5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323
  1. /**
  2. * Copyright 2019-2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "debug/anf_ir_utils.h"
  17. #include <fstream>
  18. #include <map>
  19. #include <memory>
  20. #include <unordered_map>
  21. #include <unordered_set>
  22. #include <algorithm>
  23. #include "ir/graph_utils.h"
  24. #include "utils/symbolic.h"
  25. #include "ir/meta_func_graph.h"
  26. #include "ir/param_value.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 "debug/trace.h"
  36. #include "utils/label.h"
  37. #include "utils/ms_context.h"
  38. #include "frontend/operator/ops.h"
  39. using mindspore::tensor::TensorPy;
  40. namespace mindspore {
  41. // max number of elements in sequence
  42. const int NUM_MAX_SEQUENCE_ELEMS = 0x00FFFFFF;
  43. // ============================================== MindSpore IR Common ==============================================
  44. // get MindSpore Intermediate Representation Path
  45. std::string GetMsIrPath(void) {
  46. std::string path;
  47. const char *path_ptr = getenv("MS_IR_PATH");
  48. if (path_ptr != nullptr) {
  49. path = path_ptr;
  50. char real_path[PATH_MAX] = {0};
  51. #if defined(_WIN32) || defined(_WIN64)
  52. if (path.size() > PATH_MAX || _fullpath(real_path, path.c_str(), PATH_MAX) == nullptr) {
  53. MS_LOG(EXCEPTION) << "MS IR Path error, " << path_ptr;
  54. }
  55. #else
  56. if (path.size() > PATH_MAX || nullptr == realpath(path.c_str(), real_path)) {
  57. MS_LOG(EXCEPTION) << "MS IR path error, " << path_ptr;
  58. }
  59. #endif
  60. path = real_path;
  61. }
  62. return path;
  63. }
  64. std::string dump_obj(const py::object &obj, const std::string &path) {
  65. py::module mod = parse::python_adapter::GetPyModule(parse::PYTHON_MOD_PARSE_MODULE);
  66. py::object name = parse::python_adapter::CallPyModFn(mod, "dump_obj", obj, py::str(path));
  67. return py::str(name);
  68. }
  69. py::object load_obj(const std::string &path) {
  70. py::module mod = parse::python_adapter::GetPyModule(parse::PYTHON_MOD_PARSE_MODULE);
  71. py::object obj = parse::python_adapter::CallPyModFn(mod, "load_obj", py::str(path));
  72. return obj;
  73. }
  74. // ============================================= MindSpore IR Exporter =============================================
  75. std::string AnfExporter::GetNodeType(const AnfNodePtr &nd) {
  76. abstract::ShapePtr shape = nd->Shape() == nullptr ? nullptr : dyn_cast<abstract::Shape>(nd->Shape());
  77. TypePtr type = dyn_cast<Type>(nd->Type());
  78. std::ostringstream oss;
  79. if ((nullptr != shape) && (nullptr != type)) {
  80. oss << type->DumpText() << shape->DumpText();
  81. } else if (nullptr != type) {
  82. oss << type->DumpText();
  83. } else {
  84. oss << "Undefined";
  85. }
  86. return oss.str();
  87. }
  88. std::string AnfExporter::DumpObject(const py::object &obj, const std::string &category) const {
  89. std::string pkl_path = GetMsIrPath();
  90. // if not specified env 'MS_IR_PATH', do not create any files
  91. if (pkl_path.empty() || (getenv("MS_IR_FILE") != nullptr)) {
  92. return "null";
  93. }
  94. std::string file_prefix = id_ + "." + category;
  95. std::string file_name = dump_obj(obj, pkl_path + "/" + file_prefix);
  96. return file_prefix + file_name;
  97. }
  98. int AnfExporter::GetParamIndex(const FuncGraphPtr &func_graph, const AnfNodePtr &param, bool throw_excp) {
  99. if (func_graph == nullptr || param == nullptr) {
  100. return -1;
  101. }
  102. FuncGraphPtr fg = func_graph;
  103. while (fg != nullptr) {
  104. if (exported.find(fg) == exported.end()) {
  105. if (!check_integrity_) {
  106. break;
  107. }
  108. MS_LOG(EXCEPTION) << "Can not find func graph '" << fg->DumpText() << "." << fg->debug_info()->get_id() << "'";
  109. }
  110. auto param_map = exported[fg];
  111. if (param_map.find(param) != param_map.end()) {
  112. return param_map[param];
  113. }
  114. fg = fg->parent();
  115. }
  116. if (throw_excp) {
  117. MS_LOG(EXCEPTION) << "Can not find index for param '" << param->DumpText() << "' for func graph '"
  118. << func_graph->DumpText() << "." << func_graph->debug_info()->get_id() << "'";
  119. }
  120. return -1;
  121. }
  122. // try to find index of parameter for SymbolicKeyInstance from all exported graphs
  123. // NOTICE: Suppose name of all parameters in SymbolicKeyInstance are different
  124. int AnfExporter::GetParamIndexFromExported(const AnfNodePtr &param) {
  125. if (param == nullptr) {
  126. return -1;
  127. }
  128. int ret = -1;
  129. for (const auto &item : exported) {
  130. auto pram_iter = item.second.find(param);
  131. if (pram_iter != item.second.end()) {
  132. return pram_iter->second;
  133. }
  134. }
  135. return ret;
  136. }
  137. std::string AnfExporter::GetValueNodeText(const FuncGraphPtr &fg, const ValueNodePtr &node) {
  138. MS_EXCEPTION_IF_NULL(node);
  139. return GetValueText(fg, node->value());
  140. }
  141. std::string AnfExporter::GetMultitypeFuncGraphText(const prim::MultitypeFuncGraphPtr &mt_func_graph) {
  142. auto py_funcs = mt_func_graph->GetPyFunctions();
  143. if (py_funcs.empty()) {
  144. return "";
  145. }
  146. std::ostringstream oss;
  147. oss << "{";
  148. bool is_first = true;
  149. for (const auto &py_func : py_funcs) {
  150. if (is_first) {
  151. is_first = false;
  152. } else {
  153. oss << ", ";
  154. }
  155. oss << "(";
  156. for (size_t i = 0; i < py_func.first.size(); ++i) {
  157. if (i > 0) {
  158. oss << ", ";
  159. }
  160. oss << py_func.first[i]->DumpText();
  161. }
  162. oss << ")";
  163. // dump Python Function object
  164. oss << "@" << DumpObject(py_func.second, "F");
  165. }
  166. oss << "}";
  167. return oss.str();
  168. }
  169. /* inherit relation of MetaFuncGraph
  170. *
  171. * MetaGraph
  172. * ├── MultitypeGraph
  173. * ├── HyperMap
  174. * │ └── HyperMapPy
  175. * ├── Map
  176. * │ └── MapPy
  177. * ├── Tail
  178. * ├── MakeTupleGradient
  179. * ├── MakeListGradient
  180. * ├── GradOperation
  181. * └── TupleAdd
  182. */
  183. std::string AnfExporter::GetMetaFuncGraphText(const MetaFuncGraphPtr &meta_func_graph) {
  184. if (meta_func_graph == nullptr) {
  185. return "";
  186. }
  187. std::ostringstream oss;
  188. oss << meta_func_graph->type_name() << "::" << meta_func_graph->name();
  189. if (meta_func_graph->isa<prim::MultitypeFuncGraph>()) {
  190. prim::MultitypeFuncGraphPtr mt_func_graph = meta_func_graph->cast<prim::MultitypeFuncGraphPtr>();
  191. oss << GetMultitypeFuncGraphText(mt_func_graph);
  192. } else if (meta_func_graph
  193. ->isa<prim::HyperMapPy>()) { // this statement must before 'meta_graph->isa<prim::HyperMap>()'
  194. auto hyper_map = meta_func_graph->cast<prim::HyperMapPyPtr>();
  195. if (hyper_map->GetFnLeaf() != nullptr) {
  196. oss << "{fn_leaf=" << GetMetaFuncGraphText(hyper_map->GetFnLeaf()) << "}";
  197. }
  198. } else if (meta_func_graph->isa<prim::HyperMap>()) {
  199. auto hyper_map = meta_func_graph->cast<prim::HyperMapPtr>();
  200. if (hyper_map->GetFnLeaf() != nullptr) {
  201. oss << "{fn_leaf=" << GetMetaFuncGraphText(hyper_map->GetFnLeaf()) << "}";
  202. }
  203. } else if (meta_func_graph->isa<prim::MapPy>()) { // this statement must before 'meta_graph->isa<prim::Map>()'
  204. auto map = meta_func_graph->cast<prim::MapPyPtr>();
  205. if (map->GetFnLeaf() != nullptr) {
  206. oss << "{fn_leaf=" << GetMetaFuncGraphText(map->GetFnLeaf()) << "}";
  207. }
  208. } else if (meta_func_graph->isa<prim::Map>()) {
  209. auto map = meta_func_graph->cast<prim::MapPtr>();
  210. if (map->GetFnLeaf() != nullptr) {
  211. oss << "{fn_leaf=" << GetMetaFuncGraphText(map->GetFnLeaf()) << "}";
  212. }
  213. } else if (meta_func_graph->isa<prim::GradOperation>()) {
  214. prim::GradOperationPtr grad_op = meta_func_graph->cast<prim::GradOperationPtr>();
  215. oss << "{get_all=" << grad_op->get_all_ << ", get_by_list=" << grad_op->get_by_list_
  216. << ", sens_param=" << grad_op->sens_param_ << "}";
  217. } else if (meta_func_graph->isa<prim::Tail>()) {
  218. // do nothing
  219. } else if (meta_func_graph->isa<prim::MakeTupleGradient>()) {
  220. // do nothing
  221. } else if (meta_func_graph->isa<prim::MakeListGradient>()) {
  222. // do nothing
  223. } else if (meta_func_graph->isa<prim::TupleAdd>()) {
  224. // do nothing
  225. } else if (meta_func_graph->isa<prim::TupleSlice>()) {
  226. // do nothing
  227. } else if (meta_func_graph->isa<prim::UnpackCall>()) {
  228. // do nothing
  229. } else if (meta_func_graph->isa<prim::ZipOperation>()) {
  230. // do nothing
  231. } else if (meta_func_graph->isa<prim::ListAppend>()) {
  232. // do nothing
  233. } else if (meta_func_graph->isa<prim::DoSignatureMetaFuncGraph>()) {
  234. // do nothing
  235. } else {
  236. MS_LOG(EXCEPTION) << "Unknown MetaFuncGraph type " << meta_func_graph->type_name();
  237. }
  238. return oss.str();
  239. }
  240. std::string AnfExporter::GetPrimitiveText(const PrimitivePtr &prim) {
  241. std::ostringstream oss;
  242. if (prim == nullptr) {
  243. return oss.str();
  244. }
  245. oss << prim->type_name() << "::" << prim->name();
  246. // need to serialize internal python function of PrimitivePy and record its prim_type
  247. if (prim->isa<PrimitivePy>()) {
  248. PrimitivePyPtr primpy = prim->cast<PrimitivePyPtr>();
  249. // dump related function in PrimitivePy
  250. oss << "@" << DumpObject(primpy->GetPyObj(), "P");
  251. // output primitive type
  252. oss << "{prim_type=" << static_cast<int>(prim->prim_type()) << "}";
  253. }
  254. // output primitive attributes
  255. oss << prim->GetAttrsText();
  256. if (prim->isa<prim::DoSignaturePrimitive>()) {
  257. auto do_signature = dyn_cast<prim::DoSignaturePrimitive>(prim);
  258. auto &func = do_signature->function();
  259. if (func->isa<Primitive>()) {
  260. auto sig_prim = dyn_cast<Primitive>(func);
  261. oss << sig_prim->GetAttrsText();
  262. }
  263. }
  264. return oss.str();
  265. }
  266. std::string AnfExporter::GetNameSpaceText(const parse::NameSpacePtr &ns) {
  267. std::ostringstream oss;
  268. if (ns == nullptr) {
  269. return oss.str();
  270. }
  271. // dump related module information in Namespace
  272. oss << ns->type_name() << "::" << ns->module() << "@" << DumpObject(ns->obj(), "N");
  273. return oss.str();
  274. }
  275. std::string AnfExporter::GetSymbolicKeyInstanceText(const FuncGraphPtr &func_graph,
  276. const SymbolicKeyInstancePtr &sym_inst) {
  277. MS_EXCEPTION_IF_NULL(func_graph);
  278. MS_EXCEPTION_IF_NULL(sym_inst);
  279. AnfNodePtr sym_node = sym_inst->node();
  280. MS_EXCEPTION_IF_NULL(sym_node);
  281. std::ostringstream oss;
  282. if (sym_node->isa<Parameter>()) {
  283. int idx = GetParamIndex(func_graph, sym_node, false);
  284. // if can not find SymbolicKeyInstance related parameter from ancestors,
  285. // try to find from all exported graphs
  286. if (idx < 0) {
  287. idx = GetParamIndexFromExported(sym_node);
  288. }
  289. if (idx < 0) {
  290. ParameterPtr p = dyn_cast<Parameter>(sym_node);
  291. if (p == nullptr) {
  292. MS_LOG(EXCEPTION) << "Sym_inst's node could not cast to parameter";
  293. }
  294. MS_LOG(WARNING) << "Can not find SymbolicKeyInstance: " << p->name();
  295. }
  296. oss << "SymInst(%para" << idx << ")";
  297. } else {
  298. MS_LOG(WARNING) << "SymbolicKeyInstance does not embed a parameter: " << sym_node->ToString();
  299. oss << "SymInst(cnode_" << sym_node->ToString() << ")";
  300. }
  301. return oss.str();
  302. }
  303. std::string AnfExporter::GetSequenceText(const FuncGraphPtr &func_graph, const ValuePtr &value) {
  304. std::ostringstream oss;
  305. // output ValueList, ValueTuple
  306. ValueSequeuePtr seq = dyn_cast<ValueSequeue>(value);
  307. MS_EXCEPTION_IF_NULL(seq);
  308. MS_EXCEPTION_IF_NULL(value);
  309. bool is_tuple = value->isa<ValueTuple>();
  310. oss << (is_tuple ? "(" : "[");
  311. bool first_flag = true;
  312. for (auto elem : seq->value()) {
  313. if (first_flag) {
  314. first_flag = false;
  315. } else {
  316. oss << ", ";
  317. }
  318. oss << GetValueText(func_graph, elem);
  319. }
  320. oss << (is_tuple ? ")" : "]");
  321. return oss.str();
  322. }
  323. std::string AnfExporter::GetDictText(const FuncGraphPtr &func_graph, const ValuePtr &value) {
  324. std::ostringstream oss;
  325. ValueDictionaryPtr dict = value->cast<ValueDictionaryPtr>();
  326. oss << "{";
  327. bool first_flag = true;
  328. for (const auto &elem : dict->value()) {
  329. if (first_flag) {
  330. first_flag = false;
  331. } else {
  332. oss << ", ";
  333. }
  334. oss << "\"" << elem.first << "\": " << GetValueText(func_graph, elem.second);
  335. }
  336. oss << "}";
  337. return oss.str();
  338. }
  339. std::string AnfExporter::GetOtherValueText(const FuncGraphPtr &, const ValuePtr &value) {
  340. std::ostringstream oss;
  341. if (check_integrity_) {
  342. MS_LOG(EXCEPTION) << "Need to process type: " << value->type_name() << ", dump text: " << value->DumpText();
  343. }
  344. oss << value->type_name() << "[" << value->DumpText() << "]";
  345. return oss.str();
  346. }
  347. std::string AnfExporter::GetValueText(const FuncGraphPtr &func_graph, const ValuePtr &value) {
  348. std::ostringstream oss;
  349. bool is_null_ptr = (func_graph == nullptr || value == nullptr);
  350. if (is_null_ptr) {
  351. return oss.str();
  352. }
  353. if (value->isa<Primitive>()) {
  354. oss << GetPrimitiveText(value->cast<PrimitivePtr>());
  355. } else if (value->isa<MetaFuncGraph>()) {
  356. MetaFuncGraphPtr meta_func_graph = value->cast<MetaFuncGraphPtr>();
  357. oss << GetMetaFuncGraphText(meta_func_graph);
  358. } else if (value->isa<SymbolicKeyInstance>()) {
  359. oss << GetSymbolicKeyInstanceText(func_graph, value->cast<SymbolicKeyInstancePtr>());
  360. } else if (value->isa<RefKey>()) {
  361. oss << value->DumpText();
  362. } else if (value->isa<Scalar>() || value->isa<StringImm>()) {
  363. oss << value->DumpText();
  364. } else if (value->isa<tensor::Tensor>()) {
  365. auto tensor_ptr = dyn_cast<tensor::Tensor>(value);
  366. oss << value->DumpText() << "@" << DumpObject(TensorPy::AsNumpy(*tensor_ptr), "T");
  367. } else if (value->isa<parse::Symbol>() || value->isa<None>() || value->isa<Null>()) {
  368. oss << value->DumpText();
  369. } else if (value->isa<ValueSequeue>()) {
  370. oss << GetSequenceText(func_graph, value);
  371. } else if (value->isa<ValueDictionary>()) {
  372. oss << GetDictText(func_graph, value);
  373. } else if (value->isa<ValueSlice>()) {
  374. ValueSlicePtr slice = value->cast<ValueSlicePtr>();
  375. oss << slice->DumpText();
  376. } else if (value->isa<Type>()) {
  377. oss << value->DumpText();
  378. } else if (value->isa<parse::NameSpace>()) {
  379. oss << GetNameSpaceText(value->cast<parse::NameSpacePtr>());
  380. } else if (value->isa<parse::PyObjectWrapper>()) {
  381. oss << value->type_name();
  382. } else if (value->isa<KeywordArg>()) {
  383. KeywordArgPtr keyword_arg = value->cast<KeywordArgPtr>();
  384. oss << keyword_arg->DumpText();
  385. } else {
  386. return GetOtherValueText(func_graph, value);
  387. }
  388. return oss.str();
  389. }
  390. // this function is used to output node in CNode's inputs
  391. std::string AnfExporter::GetAnfNodeText(const FuncGraphPtr &func_graph, const AnfNodePtr &node,
  392. const std::map<AnfNodePtr, int> &apply_map) {
  393. std::ostringstream oss;
  394. if (func_graph == nullptr || node == nullptr) {
  395. return oss.str();
  396. }
  397. if (node->isa<CNode>()) {
  398. auto iter = apply_map.find(node);
  399. if (iter == apply_map.end()) {
  400. MS_LOG(EXCEPTION) << "Can not find node '" << node->DumpText() << "' in apply_map";
  401. }
  402. oss << "%" << iter->second;
  403. } else if (node->isa<Parameter>()) {
  404. oss << "%para" << GetParamIndex(func_graph, node, check_integrity_);
  405. } else if (IsValueNode<FuncGraph>(node)) {
  406. FuncGraphPtr fg = GetValueNode<FuncGraphPtr>(node);
  407. oss << fg->type_name() << "::fg_" << fg->debug_info()->get_id();
  408. if (!func_graph_set.contains(fg) && exported.find(fg) == exported.end() && export_used_) {
  409. func_graph_set.add(fg);
  410. }
  411. } else if (node->isa<ValueNode>()) {
  412. oss << GetValueNodeText(func_graph, node->cast<ValueNodePtr>());
  413. } else {
  414. MS_LOG(EXCEPTION) << "Unknown node '" << node->DumpText() << "'";
  415. }
  416. return oss.str();
  417. }
  418. void AnfExporter::OutputParameters(std::ofstream &ofs, const std::vector<AnfNodePtr> &parameters,
  419. OrderedMap<AnfNodePtr, int, ParamPtrHasher, ParamPtrEqual> *param_map) {
  420. bool first_flag = true;
  421. for (const AnfNodePtr &param : parameters) {
  422. if (first_flag) {
  423. first_flag = false;
  424. ofs << " ";
  425. } else {
  426. ofs << " , ";
  427. }
  428. (*param_map)[param] = param_index;
  429. std::string type_info = GetNodeType(param);
  430. // output parameter and type
  431. if (type_info == "Undefined") {
  432. ofs << "%para" << param_index;
  433. } else {
  434. ofs << "%para" << param_index << " : " << type_info;
  435. }
  436. // dump Default value of parameter if exists
  437. const ParameterPtr param_ptr = dyn_cast<Parameter>(param);
  438. if (param_ptr == nullptr) {
  439. MS_LOG(EXCEPTION) << "Param could not cast to parameter";
  440. }
  441. if (param_ptr->has_default()) {
  442. auto param_value = param_ptr->default_param();
  443. ofs << " = @" << DumpObject(py::cast(param_value), "D");
  444. }
  445. // output comment
  446. ofs << " # " << param->DumpText() << "\n";
  447. param_index += 1;
  448. }
  449. }
  450. void AnfExporter::OutputStatementComment(std::ofstream &ofs, const CNodePtr &node) {
  451. if (node == nullptr) {
  452. return;
  453. }
  454. // output type of each input argument
  455. auto &inputs = node->inputs();
  456. if (inputs.size() > 1) {
  457. ofs << " #(";
  458. for (size_t i = 1; i < inputs.size(); ++i) {
  459. if (i != 1) {
  460. ofs << ", ";
  461. }
  462. AnfNodePtr arg = inputs[i];
  463. ofs << GetNodeType(arg);
  464. }
  465. ofs << ")";
  466. }
  467. // output other comment, map the graph name to original representation(containing unicode character)
  468. std::ostringstream comment;
  469. comment << " #";
  470. bool has_comment = false;
  471. for (size_t i = 0; i < inputs.size(); ++i) {
  472. AnfNodePtr arg = inputs[i];
  473. if (!IsValueNode<FuncGraph>(arg)) {
  474. continue;
  475. }
  476. if (!has_comment) {
  477. has_comment = true;
  478. } else {
  479. comment << ",";
  480. }
  481. FuncGraphPtr fg = GetValueNode<FuncGraphPtr>(arg);
  482. std::string func_graph_id = fg->debug_info()->get_id();
  483. comment << " fg_" << func_graph_id << "=" << fg->ToString() << "." << func_graph_id;
  484. }
  485. if (has_comment) {
  486. ofs << comment.str();
  487. }
  488. ofs << " #scope: " << node->scope()->name();
  489. }
  490. void AnfExporter::OutputCNodes(std::ofstream &ofs, const std::vector<AnfNodePtr> &nodes,
  491. const FuncGraphPtr &func_graph) {
  492. if (func_graph == nullptr) {
  493. return;
  494. }
  495. int idx = 1;
  496. std::map<AnfNodePtr, int> apply_map;
  497. for (const AnfNodePtr &node : nodes) {
  498. MS_EXCEPTION_IF_NULL(node);
  499. if (!node->isa<CNode>()) {
  500. continue;
  501. }
  502. auto iter = tagged_cnodes_.find(node);
  503. if (iter != tagged_cnodes_.end()) {
  504. ofs << "\n#------------------------> " << iter->second << "\n";
  505. }
  506. auto cnode = node->cast<CNodePtr>();
  507. auto &inputs = cnode->inputs();
  508. std::string op_text = GetAnfNodeText(func_graph, inputs[0], apply_map);
  509. // non-return node
  510. if (node != func_graph->get_return()) {
  511. int apply_idx = idx++;
  512. apply_map[node] = apply_idx;
  513. std::string type_info = GetNodeType(node);
  514. if (type_info == "Undefined") {
  515. ofs << " %" << apply_idx << " = " << op_text << "(";
  516. } else {
  517. ofs << " %" << apply_idx << " : " << type_info << " = " << op_text << "(";
  518. }
  519. } else {
  520. ofs << " " << op_text << "(";
  521. }
  522. for (size_t i = 1; i < inputs.size(); ++i) {
  523. if (i != 1) {
  524. ofs << ", ";
  525. }
  526. AnfNodePtr arg = inputs[i];
  527. ofs << GetAnfNodeText(func_graph, arg, apply_map);
  528. }
  529. ofs << ")";
  530. // output comment
  531. OutputStatementComment(ofs, cnode);
  532. ofs << "\n";
  533. if (label_manage::GetGlobalTraceLabelType() == label_manage::TraceLabelType::kWithUniqueId) {
  534. ofs << trace::GetDebugInfo(cnode->debug_info(), " # ", kSourceLineTipDiscard) << "#"
  535. << label_manage::Label(cnode->debug_info()) << "\n";
  536. } else {
  537. ofs << trace::GetDebugInfo(cnode->debug_info(), " # ", kSourceLineTipDiscard) << "\n";
  538. }
  539. }
  540. }
  541. void AnfExporter::ExportOneFuncGraph(std::ofstream &ofs, const FuncGraphPtr &func_graph) {
  542. if (func_graph == nullptr) {
  543. return;
  544. }
  545. std::vector<AnfNodePtr> nodes = TopoSort(func_graph->get_return(), SuccIncoming, AlwaysInclude);
  546. std::vector<AnfNodePtr> parameters = func_graph->parameters();
  547. OrderedMap<AnfNodePtr, int, ParamPtrHasher, ParamPtrEqual> param_map;
  548. if (*(func_graph->switch_layer_input())) {
  549. ofs << "switch_layer_input: " << *(func_graph->switch_layer_input()) << "\n";
  550. }
  551. ofs << "# [No." << (exported.size() + 1) << "] " << func_graph->DumpText() << "."
  552. << func_graph->debug_info()->get_id() << "\n";
  553. if (label_manage::GetGlobalTraceLabelType() == label_manage::TraceLabelType::kWithUniqueId) {
  554. ofs << trace::GetDebugInfo(func_graph->debug_info(), "# ", kSourceLineTipDiscard) << "#"
  555. << label_manage::Label(func_graph->debug_info()) << "\n";
  556. } else {
  557. ofs << trace::GetDebugInfo(func_graph->debug_info(), "# ", kSourceLineTipDiscard) << "\n";
  558. }
  559. ofs << "funcgraph fg_" << func_graph->debug_info()->get_id();
  560. // output name of parent of graph if exists
  561. if (func_graph->parent() != nullptr) {
  562. ofs << "[fg_" << func_graph->parent()->debug_info()->get_id() << "]";
  563. }
  564. ofs << "(\n";
  565. OutputParameters(ofs, parameters, &param_map);
  566. exported[func_graph] = param_map;
  567. ofs << (!parameters.empty() ? " " : "") << ") {\n";
  568. OutputCNodes(ofs, nodes, func_graph);
  569. ofs << "}\n";
  570. }
  571. void AnfExporter::ExportFuncGraph(const std::string &filename, const FuncGraphPtr &func_graph) {
  572. if (func_graph == nullptr) {
  573. return;
  574. }
  575. std::ofstream ofs(filename);
  576. if (!ofs.is_open()) {
  577. MS_LOG(ERROR) << "Open file '" << filename << "' failed!";
  578. return;
  579. }
  580. param_index = 1;
  581. func_graph_set.add(func_graph);
  582. while (!func_graph_set.empty()) {
  583. FuncGraphPtr fg = *func_graph_set.begin();
  584. ExportOneFuncGraph(ofs, fg);
  585. ofs << "\n\n";
  586. (void)func_graph_set.erase(fg);
  587. }
  588. ofs << "# num of total function graphs: " << exported.size();
  589. ofs.close();
  590. }
  591. void AnfExporter::ExportFuncGraph(const std::string &filename, const std::vector<TaggedGraph> &graphs) {
  592. if (graphs.empty()) {
  593. return;
  594. }
  595. std::ofstream ofs(filename);
  596. if (!ofs.is_open()) {
  597. MS_LOG(ERROR) << "Open file '" << filename << "' failed!";
  598. return;
  599. }
  600. param_index = 1;
  601. for (const auto &tagged_graph : graphs) {
  602. tagged_cnodes_ = tagged_graph.second;
  603. ExportOneFuncGraph(ofs, tagged_graph.first);
  604. tagged_cnodes_.clear();
  605. ofs << "\n\n";
  606. }
  607. ofs << "# num of total function graphs: " << graphs.size();
  608. ofs.close();
  609. }
  610. #ifdef ENABLE_DUMP_IR
  611. void ExportIR(const std::string &filename, const std::string &id, const FuncGraphPtr &func_graph) {
  612. if (func_graph == nullptr) {
  613. return;
  614. }
  615. AnfExporter exporter(id);
  616. ChangeFileMode(filename, S_IRWXU);
  617. exporter.ExportFuncGraph(filename, func_graph);
  618. // set file mode to read only by user
  619. ChangeFileMode(filename, S_IRUSR);
  620. }
  621. void ExportIR(const std::string &filename, const std::vector<TaggedGraph> &graphs) {
  622. AnfExporter exporter("", false);
  623. ChangeFileMode(filename, S_IRWXU);
  624. exporter.ExportFuncGraph(filename, graphs);
  625. // set file mode to read only by user
  626. ChangeFileMode(filename, S_IRUSR);
  627. }
  628. #else
  629. void ExportIR(const std::string &, const std::string &, const FuncGraphPtr &) {
  630. static bool already_printed = false;
  631. if (already_printed) {
  632. return;
  633. }
  634. already_printed = true;
  635. MS_LOG(WARNING) << "The functionality of dumping function graph IR is disabled, "
  636. << "please recompile source to enable it. See help of building script.";
  637. }
  638. void ExportIR(const std::string &filename, const std::vector<TaggedGraph> &graphs) {
  639. static bool already_printed = false;
  640. if (already_printed) {
  641. return;
  642. }
  643. already_printed = true;
  644. MS_LOG(WARNING) << "The functionality of dumping function graph IR is disabled, "
  645. << "please recompile source to enable it. See help of building script.";
  646. }
  647. #endif
  648. // ============================================= MindSpore IR Importer =============================================
  649. enum Token : int {
  650. TOK_INVALID = 0, // invalid token
  651. TOK_LPARENTHESIS, // ( left parenthesis
  652. TOK_RPARENTHESIS, // ) right parenthesis
  653. TOK_LBRACKET, // [ left bracket
  654. TOK_RBRACKET, // ] right bracket
  655. TOK_LBRACE, // { left brace
  656. TOK_RBRACE, // } right brace
  657. TOK_COMMA, // , comma
  658. TOK_EQUALITY, // = equality
  659. TOK_COLON, // : colon
  660. TOK_STAR, // * star
  661. TOK_VARIABLE, // variable
  662. TOK_AT_FILE, // @filename
  663. TOK_PARAMETER, // parameter
  664. TOK_IDENTIFIER, // identifier
  665. TOK_FUNCGRAPH, // keyword 'funcgraph'
  666. TOK_RETURN, // id prim::return
  667. TOK_STRING, // string
  668. TOK_NUMBER, // number
  669. TOK_COMMENT, // comment
  670. TOK_EOL, // end of line
  671. TOK_EOF, // end of file
  672. TOK_ERROR // file read error
  673. };
  674. std::map<Token, const char *> token_text = {
  675. {TOK_INVALID, "invalid"}, // invalid token
  676. {TOK_LPARENTHESIS, "("}, // ( left parenthesis
  677. {TOK_RPARENTHESIS, ")"}, // ) right parenthesis
  678. {TOK_LBRACKET, "["}, // [ left bracket
  679. {TOK_RBRACKET, "]"}, // ] right bracket
  680. {TOK_LBRACE, "{"}, // { left brace
  681. {TOK_RBRACE, "}"}, // } right brace
  682. {TOK_COMMA, ","}, // , comma
  683. {TOK_EQUALITY, "="}, // = equality
  684. {TOK_COLON, ":"}, // : colon
  685. {TOK_STAR, "*"}, // * start
  686. {TOK_VARIABLE, nullptr}, // variable
  687. {TOK_AT_FILE, nullptr}, // @file
  688. {TOK_PARAMETER, nullptr}, // parameter
  689. {TOK_IDENTIFIER, nullptr}, // identifier
  690. {TOK_FUNCGRAPH, "funcgraph"}, // keyword 'funcgraph'
  691. {TOK_RETURN, nullptr}, // id prim::return
  692. {TOK_STRING, nullptr}, // string
  693. {TOK_NUMBER, nullptr}, // number
  694. {TOK_COMMENT, nullptr}, // comment
  695. {TOK_EOL, "\n"}, // end of line
  696. {TOK_EOF, ""}, // end of file
  697. {TOK_ERROR, "error"} // file read error
  698. };
  699. class Lexer {
  700. public:
  701. // filename is checked in ImportIR;
  702. explicit Lexer(const char *filename) : fin(filename) {}
  703. ~Lexer() {
  704. try {
  705. if (fin.is_open()) {
  706. fin.close();
  707. }
  708. } catch (const std::exception &e) {
  709. MS_LOG(ERROR) << "Exception when closing file";
  710. } catch (...) {
  711. std::string exName(abi::__cxa_current_exception_type()->name());
  712. MS_LOG(ERROR) << "Error occurred when closing file. Exception name: " << exName;
  713. }
  714. }
  715. bool IsSingleCharToken(char ch, Token *token_ptr) {
  716. // clang-format off
  717. std::unordered_map<char, Token> char_to_token = {
  718. {'(', TOK_LPARENTHESIS},
  719. {')', TOK_RPARENTHESIS},
  720. {'[', TOK_LBRACKET},
  721. {']', TOK_RBRACKET},
  722. {'{', TOK_LBRACE},
  723. {'}', TOK_RBRACE},
  724. {',', TOK_COMMA},
  725. {'=', TOK_EQUALITY},
  726. {':', TOK_COLON},
  727. {'*', TOK_STAR}};
  728. // clang-format on
  729. auto iter = char_to_token.find(ch);
  730. if (iter == char_to_token.end()) {
  731. return false;
  732. }
  733. if (token_ptr != nullptr) {
  734. *token_ptr = iter->second;
  735. }
  736. return true;
  737. }
  738. Token GetNextToken() {
  739. #ifdef DEBUG
  740. Token token = GetNextTokenInner();
  741. const char *str = token_text[token];
  742. std::string text = (str == nullptr ? GetTokenText() : str);
  743. MS_LOG(DEBUG) << "------Parse token] " << text;
  744. return token;
  745. }
  746. Token GetNextTokenInner() {
  747. #endif
  748. tok_idx = 0;
  749. Token tok = TOK_ERROR;
  750. char ch = SkipTabAndSpace();
  751. if (ch == CODE_EOF) {
  752. return TOK_EOF;
  753. } else if (ch == CODE_ERROR) {
  754. return TOK_ERROR;
  755. } else if (IsSingleCharToken(ch, &tok)) {
  756. return tok;
  757. } else if (ch == '\r') {
  758. char c = GetChar();
  759. if (c == '\n') {
  760. line_++;
  761. return TOK_EOL;
  762. }
  763. UnGetChar(c);
  764. line_++;
  765. return TOK_EOL;
  766. } else if (ch == '\n') {
  767. line_++;
  768. return TOK_EOL;
  769. } else if (ch == '#') {
  770. return ParseComment(ch);
  771. } else if (ch == '"') {
  772. return ParseString();
  773. } else if (ch == '%') {
  774. return ParseVariableOrParameter(ch);
  775. } else if (ch == '@') {
  776. return ParseAtFile();
  777. } else if (IsDigit(ch) || ch == '-') {
  778. return ParseNumber(ch);
  779. } else if (IsAlpha(ch) || ch == '_') {
  780. return ParseIdentifier(ch);
  781. } else {
  782. return TOK_ERROR;
  783. }
  784. }
  785. Token SkipWhiteToken() {
  786. Token tok = GetNextToken();
  787. while (tok == TOK_EOL || tok == TOK_COMMENT) {
  788. tok = GetNextToken();
  789. }
  790. return tok;
  791. }
  792. std::string GetTokenText() const { return std::string(tok_buf); }
  793. int GetLineNo() const { return line_; }
  794. private:
  795. Token ParseComment(char ch) {
  796. char c = GetChar();
  797. while (c != '\r' && c != '\n' && c != CODE_EOF) {
  798. c = GetChar();
  799. }
  800. if (ch != CODE_EOF) {
  801. UnGetChar(c);
  802. }
  803. tok_buf[0] = '#';
  804. tok_buf[1] = '\0';
  805. return TOK_COMMENT;
  806. }
  807. Token ParseString() {
  808. tok_idx = 0;
  809. char c = GetChar();
  810. while (c != '"') {
  811. if (tok_idx >= BUF_SIZE) {
  812. MS_LOG(EXCEPTION) << "Length of token which is " << tok_idx << " exceeds " << BUF_SIZE;
  813. }
  814. if (c == '\r' || c == '\n') {
  815. MS_LOG(EXCEPTION) << "Literal newline characters are not allowed within the quote at line " << line_;
  816. }
  817. if (c == CODE_EOF) {
  818. MS_LOG(EXCEPTION) << "Encounter EOF within the quote at line " << line_;
  819. }
  820. tok_buf[tok_idx++] = c;
  821. c = GetChar();
  822. }
  823. tok_buf[tok_idx] = '\0';
  824. return TOK_STRING;
  825. }
  826. Token ParseVariableOrParameter(char ch) {
  827. tok_idx = 0;
  828. tok_buf[tok_idx++] = ch;
  829. char c = GetChar();
  830. while (IsAlphaNumeric(c)) {
  831. if (tok_idx >= BUF_SIZE) {
  832. MS_LOG(EXCEPTION) << "Length of token which is " << tok_idx << " exceeds " << BUF_SIZE;
  833. }
  834. tok_buf[tok_idx++] = c;
  835. c = GetChar();
  836. }
  837. tok_buf[tok_idx] = '\0';
  838. UnGetChar(c);
  839. // judge parameter: %para[0-9]+
  840. tok_buf[tok_idx] = '\0';
  841. std::string param_key = "%para";
  842. if (strncmp(tok_buf, param_key.c_str(), param_key.size()) == 0) {
  843. if (tok_idx <= param_key.size()) {
  844. return TOK_ERROR;
  845. }
  846. for (auto i = static_cast<unsigned>(param_key.size()); i < tok_idx; ++i) {
  847. if (!IsDigit(tok_buf[i])) {
  848. return TOK_ERROR;
  849. }
  850. }
  851. return TOK_PARAMETER;
  852. }
  853. // judge local variable: %[0-9]+
  854. if (tok_idx == 1) {
  855. return TOK_ERROR;
  856. }
  857. for (unsigned i = 1; i < tok_idx; ++i) {
  858. if (!IsDigit(tok_buf[i])) {
  859. return TOK_ERROR;
  860. }
  861. }
  862. return TOK_VARIABLE;
  863. }
  864. Token ParseAtFile() {
  865. tok_idx = 0;
  866. char c = GetChar();
  867. while (IsAlphaNumeric(c) || c == '_' || c == '.') {
  868. if (tok_idx >= BUF_SIZE) {
  869. MS_LOG(EXCEPTION) << "Length of token which is " << tok_idx << " exceeds " << BUF_SIZE;
  870. }
  871. tok_buf[tok_idx++] = c;
  872. c = GetChar();
  873. }
  874. tok_buf[tok_idx] = '\0';
  875. UnGetChar(c);
  876. if (tok_idx == 0) {
  877. return TOK_ERROR;
  878. }
  879. return TOK_AT_FILE;
  880. }
  881. Token ParseNumber(char ch) {
  882. tok_buf[tok_idx++] = ch;
  883. char c = GetChar();
  884. // parse number, e.g. 10, 15.6, 1e-5
  885. while (IsDigit(c) || c == '.' || c == 'e' || c == '-') {
  886. if (tok_idx >= BUF_SIZE) {
  887. MS_LOG(EXCEPTION) << "Length of token which is " << tok_idx << " exceeds " << BUF_SIZE;
  888. }
  889. tok_buf[tok_idx++] = c;
  890. c = GetChar();
  891. }
  892. UnGetChar(c);
  893. tok_buf[tok_idx] = '\0';
  894. return TOK_NUMBER;
  895. }
  896. Token ParseIdentifier(char ch) {
  897. tok_idx = 0;
  898. tok_buf[tok_idx++] = ch;
  899. char c = GetChar();
  900. while (IsAlphaNumeric(c) || c == '.' || c == ':' || c == '_') {
  901. if (tok_idx >= BUF_SIZE) {
  902. MS_LOG(EXCEPTION) << "Length of token which is " << tok_idx << " exceeds " << BUF_SIZE;
  903. }
  904. tok_buf[tok_idx++] = c;
  905. c = GetChar();
  906. }
  907. UnGetChar(c);
  908. tok_buf[tok_idx] = '\0';
  909. if (strcmp(tok_buf, "funcgraph") == 0) {
  910. return TOK_FUNCGRAPH;
  911. }
  912. if (strcmp(tok_buf, "Primitive::return") == 0) {
  913. return TOK_RETURN;
  914. }
  915. return TOK_IDENTIFIER;
  916. }
  917. // Suppose the file only contain ASCII character
  918. char GetChar() {
  919. if (ungot_char != UNGOT_CHAR) {
  920. char ch = ungot_char;
  921. ungot_char = UNGOT_CHAR;
  922. return ch;
  923. }
  924. if (idx >= cnt) {
  925. if (fin.eof()) {
  926. return CODE_EOF;
  927. }
  928. cnt = fin.read(buffer, BUF_SIZE).gcount();
  929. if ((fin.bad() || fin.fail()) && !fin.eof()) {
  930. MS_LOG(EXCEPTION) << "Read file error!";
  931. }
  932. idx = 0;
  933. }
  934. return buffer[idx++];
  935. }
  936. void UnGetChar(char ch) {
  937. if (ungot_char == UNGOT_CHAR) {
  938. ungot_char = ch;
  939. }
  940. }
  941. static bool IsTabOrSpace(char ch) { return ch == ' ' || ch == '\t'; }
  942. static bool IsDigit(char ch) { return ch >= '0' && ch <= '9'; }
  943. static bool IsAlpha(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); }
  944. static bool IsAlphaNumeric(char ch) { return IsDigit(ch) || IsAlpha(ch); }
  945. // skip whitespace(including comment) to read a valid character
  946. char SkipTabAndSpace() {
  947. char ch = GetChar();
  948. while (IsTabOrSpace(ch)) {
  949. ch = GetChar();
  950. }
  951. return ch;
  952. }
  953. std::ifstream fin;
  954. static const unsigned BUF_SIZE = 4096; // lexer buffer size
  955. char buffer[BUF_SIZE + 1] = {0}; // buffer for holding text read from text
  956. std::streamsize cnt = 0; // number of valid characters in the buffer
  957. unsigned idx = 0; // index of next char the lexer to read from
  958. char tok_buf[BUF_SIZE + 1] = {0}; // token buffer
  959. unsigned tok_idx = 0; // token buffer index
  960. char ungot_char = UNGOT_CHAR; // store ungot char
  961. static const int CODE_EOF = -1; // return code of GetChar
  962. static const int CODE_ERROR = -2; // read file error
  963. static const char UNGOT_CHAR = -3; // value of ungot char
  964. int line_ = 1; // current line number
  965. };
  966. const unsigned Lexer::BUF_SIZE;
  967. class IrParser {
  968. public:
  969. explicit IrParser(const char *filename) : lexer_(filename) {}
  970. ~IrParser() {}
  971. py::object LoadObject(const std::string &file_name) const {
  972. std::string pkl_path = GetMsIrPath();
  973. py::object default_obj = load_obj(pkl_path + "/" + file_name);
  974. return default_obj;
  975. }
  976. void ParseFile() {
  977. FuncGraphPtr func_graph = ParseFuncGraph();
  978. while (func_graph != nullptr) {
  979. func_graphs_.push_back(func_graph);
  980. func_graph = ParseFuncGraph();
  981. }
  982. if (error_flag_) {
  983. MS_LOG(EXCEPTION) << "Parse Error at line: " << lexer_.GetLineNo();
  984. }
  985. MS_LOG(INFO) << "Total graphs: " << func_graphs_.size();
  986. }
  987. Token ParseParent(FuncGraphPtr *const parent_ptr) {
  988. if (lexer_.GetNextToken() != TOK_IDENTIFIER) {
  989. return TOK_ERROR;
  990. }
  991. std::string parent_name = lexer_.GetTokenText();
  992. // NOTICE: require definition of parent graph must before child graph
  993. auto iter = func_graphs_map_.find(parent_name);
  994. if (iter == func_graphs_map_.end()) {
  995. MS_LOG(EXCEPTION) << "Can not find definition of parent func graph '" << parent_name << "' at line "
  996. << lexer_.GetLineNo();
  997. }
  998. if (parent_ptr != nullptr) {
  999. *parent_ptr = iter->second;
  1000. }
  1001. if (lexer_.GetNextToken() != TOK_RBRACKET) {
  1002. return TOK_ERROR;
  1003. }
  1004. return lexer_.GetNextToken();
  1005. }
  1006. FuncGraphPtr ParseFuncGraph() {
  1007. cnodes_.clear();
  1008. Token tok = lexer_.SkipWhiteToken();
  1009. if (tok != TOK_FUNCGRAPH) {
  1010. error_flag_ = tok != TOK_EOF;
  1011. return nullptr;
  1012. }
  1013. if (lexer_.GetNextToken() != TOK_IDENTIFIER) {
  1014. error_flag_ = true;
  1015. return nullptr;
  1016. }
  1017. std::string func_graph_name = lexer_.GetTokenText();
  1018. if (func_graphs_map_.find(func_graph_name) == func_graphs_map_.end()) {
  1019. func_graphs_map_[func_graph_name] = std::make_shared<FuncGraph>();
  1020. }
  1021. FuncGraphPtr func_graph = func_graphs_map_[func_graph_name];
  1022. MS_EXCEPTION_IF_NULL(func_graph);
  1023. MS_EXCEPTION_IF_NULL(func_graph->debug_info());
  1024. func_graph->debug_info()->set_name(func_graph_name); // for debugging
  1025. FuncGraphPtr parent = nullptr;
  1026. tok = lexer_.GetNextToken();
  1027. if (tok == TOK_LBRACKET) {
  1028. tok = ParseParent(&parent);
  1029. if (parent != nullptr) {
  1030. parents_map_[func_graph] = parent;
  1031. }
  1032. }
  1033. if (tok != TOK_LPARENTHESIS) {
  1034. error_flag_ = true;
  1035. return nullptr;
  1036. }
  1037. if (ParseParameters(func_graph) == nullptr) {
  1038. error_flag_ = true;
  1039. return nullptr;
  1040. }
  1041. if (lexer_.SkipWhiteToken() != TOK_LBRACE) {
  1042. error_flag_ = true;
  1043. return nullptr;
  1044. }
  1045. // parse statements
  1046. if (ParseStatements(func_graph) == nullptr) {
  1047. error_flag_ = true;
  1048. return nullptr;
  1049. }
  1050. func_graphs_map_[func_graph_name] = func_graph;
  1051. return func_graph;
  1052. }
  1053. FuncGraphPtr ParseStatements(const FuncGraphPtr &func_graph) {
  1054. Token tok = lexer_.SkipWhiteToken();
  1055. while (tok == TOK_VARIABLE) {
  1056. if (ParseStatement(func_graph) == nullptr) {
  1057. return nullptr;
  1058. }
  1059. tok = lexer_.SkipWhiteToken();
  1060. }
  1061. if (tok == TOK_RETURN) {
  1062. return ParseReturn(func_graph);
  1063. }
  1064. return nullptr;
  1065. }
  1066. FuncGraphPtr ParseStatement(FuncGraphPtr func_graph) {
  1067. std::string var_name = lexer_.GetTokenText();
  1068. Token tok = lexer_.GetNextToken();
  1069. AbstractBasePtr type = nullptr;
  1070. if (tok == TOK_COLON) {
  1071. tok = ParseType(func_graph, &type);
  1072. }
  1073. if (tok != TOK_EQUALITY) {
  1074. return nullptr;
  1075. }
  1076. std::vector<AnfNodePtr> inputs;
  1077. AnfNodePtr node = nullptr;
  1078. ValuePtr val = nullptr;
  1079. tok = ParseItem(func_graph, &node, &val);
  1080. if (tok != TOK_LPARENTHESIS) {
  1081. return nullptr;
  1082. }
  1083. inputs.push_back(node);
  1084. int lineno = lexer_.GetLineNo();
  1085. if (ParseArguments(func_graph, &inputs) == nullptr) {
  1086. return nullptr;
  1087. }
  1088. tok = lexer_.GetNextToken();
  1089. if (tok == TOK_COMMENT) {
  1090. tok = lexer_.GetNextToken();
  1091. }
  1092. if (tok != TOK_EOL) {
  1093. return nullptr;
  1094. }
  1095. MS_EXCEPTION_IF_NULL(func_graph);
  1096. cnodes_[var_name] = func_graph->NewCNode(inputs);
  1097. MS_EXCEPTION_IF_NULL(cnodes_[var_name]);
  1098. cnodes_[var_name]->set_debug_info(std::make_shared<NodeDebugInfo>(var_name + "@" + std::to_string(lineno)));
  1099. return func_graph;
  1100. }
  1101. FuncGraphPtr ParseReturn(FuncGraphPtr func_graph) {
  1102. if (lexer_.GetNextToken() != TOK_LPARENTHESIS) {
  1103. return nullptr;
  1104. }
  1105. AnfNodePtr input1 = nullptr;
  1106. ValuePtr value = nullptr;
  1107. Token tok = ParseItem(func_graph, &input1, &value, lexer_.GetNextToken());
  1108. int lineno = lexer_.GetLineNo();
  1109. if (tok != TOK_RPARENTHESIS) {
  1110. return nullptr;
  1111. }
  1112. tok = lexer_.GetNextToken();
  1113. if (tok == TOK_COMMENT) {
  1114. tok = lexer_.GetNextToken();
  1115. }
  1116. if (tok != TOK_EOL) {
  1117. return nullptr;
  1118. }
  1119. if (lexer_.SkipWhiteToken() != TOK_RBRACE) {
  1120. return nullptr;
  1121. }
  1122. PrimitivePtr prim = std::make_shared<Primitive>("return");
  1123. ValueNodePtr input0 = std::make_shared<ValueNode>(prim);
  1124. std::vector<AnfNodePtr> inputs;
  1125. inputs.push_back(input0);
  1126. inputs.push_back(input1);
  1127. MS_EXCEPTION_IF_NULL(func_graph);
  1128. CNodePtr ret = func_graph->NewCNode(inputs);
  1129. MS_EXCEPTION_IF_NULL(ret);
  1130. ret->set_debug_info(std::make_shared<NodeDebugInfo>(std::string("ret@") + std::to_string(lineno)));
  1131. func_graph->set_return(ret);
  1132. return func_graph;
  1133. }
  1134. void SetBasicType(TypePtr *ptr, const TypePtr &dtype) const {
  1135. if (ptr == nullptr) {
  1136. return;
  1137. }
  1138. *ptr = dtype;
  1139. }
  1140. void SetTupleType(TypePtr *ptr) {
  1141. if (ptr == nullptr) {
  1142. return;
  1143. }
  1144. *ptr = std::make_shared<Tuple>();
  1145. }
  1146. void SetTupleType(TypePtr *ptr, const TypePtrList &elems) {
  1147. if (ptr == nullptr) {
  1148. return;
  1149. }
  1150. *ptr = std::make_shared<Tuple>(elems);
  1151. }
  1152. void SetArrayType(TypePtr *const ptr, const TypePtr &elem_type, const std::vector<int> &) {
  1153. if (ptr == nullptr) {
  1154. return;
  1155. }
  1156. *ptr = std::make_shared<TensorType>(elem_type);
  1157. }
  1158. void SetListType(TypePtr *ptr) {
  1159. if (ptr == nullptr) {
  1160. return;
  1161. }
  1162. *ptr = std::make_shared<List>();
  1163. }
  1164. void SetListType(TypePtr *ptr, const TypePtrList &elems) {
  1165. if (ptr == nullptr) {
  1166. return;
  1167. }
  1168. *ptr = std::make_shared<List>(elems);
  1169. }
  1170. void SetJTaggedType(TypePtr *ptr, const TypePtr &elem) {
  1171. if (ptr == nullptr) {
  1172. return;
  1173. }
  1174. *ptr = std::make_shared<JTagged>(elem);
  1175. }
  1176. void SetBasicType(AbstractBasePtr *ptr, const TypePtr &dtype) const {
  1177. if (ptr == nullptr) {
  1178. return;
  1179. }
  1180. *ptr = std::make_shared<abstract::AbstractScalar>(dtype);
  1181. }
  1182. // void SetBasicType(AbstractBasePtr *ptr, const SymbolicKeyTypePtr& dtype) {}
  1183. void SetBasicType(AbstractBasePtr *const ptr, const TypeNonePtr &) const {
  1184. if (ptr == nullptr) {
  1185. return;
  1186. }
  1187. *ptr = std::make_shared<abstract::AbstractNone>();
  1188. }
  1189. void SetBasicType(AbstractBasePtr *, const FunctionPtr &) const {}
  1190. void SetBasicType(AbstractBasePtr *, const TensorTypePtr &) const {}
  1191. void SetTupleType(AbstractBasePtr *const ptr, const AbstractBasePtrList &elems) {
  1192. if (ptr == nullptr) {
  1193. return;
  1194. }
  1195. // if one of elems is nullptr, just return
  1196. if (std::any_of(std::begin(elems), std::end(elems), [](const AbstractBasePtr &elem) { return elem == nullptr; })) {
  1197. return;
  1198. }
  1199. *ptr = std::make_shared<abstract::AbstractTuple>(elems);
  1200. }
  1201. void SetArrayType(AbstractBasePtr *const ptr, const TypePtr &elem_type, const std::vector<int> &shape) {
  1202. if (ptr == nullptr) {
  1203. return;
  1204. }
  1205. *ptr = std::make_shared<abstract::AbstractTensor>(elem_type, shape);
  1206. }
  1207. void SetListType(AbstractBasePtr *const ptr, const AbstractBasePtrList &elems) {
  1208. if (ptr == nullptr) {
  1209. return;
  1210. }
  1211. if (std::any_of(std::begin(elems), std::end(elems), [](const AbstractBasePtr &elem) { return elem == nullptr; })) {
  1212. return;
  1213. }
  1214. *ptr = std::make_shared<abstract::AbstractList>(elems);
  1215. }
  1216. void SetJTaggedType(AbstractBasePtr *const ptr, const AbstractBasePtr &elem) {
  1217. if (ptr == nullptr) {
  1218. return;
  1219. }
  1220. *ptr = std::make_shared<abstract::AbstractJTagged>(elem);
  1221. }
  1222. template <typename T>
  1223. Token ParseTypeVector(const FuncGraphPtr &func_graph, Token tok, const std::string &type, T *const ptr = nullptr) {
  1224. if (tok != TOK_LBRACKET) {
  1225. MS_LOG(EXCEPTION) << "Illegal case, , wrong token start symbol.";
  1226. return tok;
  1227. }
  1228. bool first_flag = true;
  1229. std::vector<T> elems;
  1230. do {
  1231. tok = lexer_.GetNextToken();
  1232. if (first_flag) {
  1233. if (tok == TOK_RBRACKET) {
  1234. return lexer_.GetNextToken();
  1235. }
  1236. first_flag = false;
  1237. }
  1238. T elem = nullptr;
  1239. tok = ParseOneType(func_graph, tok, &elem);
  1240. elems.push_back(elem);
  1241. if (tok == TOK_STAR) {
  1242. if (lexer_.GetNextToken() != TOK_NUMBER) {
  1243. return TOK_ERROR;
  1244. }
  1245. int num_elems = StringToScalar<int>(lexer_.GetTokenText());
  1246. if (num_elems < 1 || num_elems > NUM_MAX_SEQUENCE_ELEMS) {
  1247. MS_LOG(EXCEPTION) << "Number of elements " << num_elems << " is out of range [1, " << NUM_MAX_SEQUENCE_ELEMS
  1248. << "]";
  1249. }
  1250. for (int i = 0; i < num_elems - 1; ++i) {
  1251. elems.push_back(elem);
  1252. }
  1253. tok = lexer_.GetNextToken();
  1254. }
  1255. } while (tok == TOK_COMMA);
  1256. if (tok != TOK_RBRACKET) {
  1257. return TOK_ERROR;
  1258. }
  1259. if (type == "Tuple") {
  1260. SetTupleType(ptr, elems);
  1261. } else if (type == "List") {
  1262. SetListType(ptr, elems);
  1263. } else {
  1264. MS_LOG(EXCEPTION) << "This method does not support " << type << " parse.";
  1265. }
  1266. return lexer_.GetNextToken();
  1267. }
  1268. template <typename T>
  1269. Token ParseTypeArray(const FuncGraphPtr &func_graph, Token tok, T *const ptr = nullptr) {
  1270. if (tok != TOK_LPARENTHESIS) {
  1271. if (ptr != nullptr) {
  1272. SetBasicType(ptr, std::make_shared<TensorType>());
  1273. }
  1274. return tok;
  1275. }
  1276. // process Array element type
  1277. TypePtr elem_type = nullptr;
  1278. std::vector<int> shape;
  1279. tok = ParseOneType(func_graph, lexer_.GetNextToken(), &elem_type);
  1280. if (tok != TOK_RPARENTHESIS) {
  1281. return TOK_ERROR;
  1282. }
  1283. tok = lexer_.GetNextToken();
  1284. if (tok != TOK_LBRACKET) {
  1285. // NOTICE: if shape.size == 0, is this ok?
  1286. SetArrayType(ptr, elem_type, shape);
  1287. return tok;
  1288. }
  1289. // process Array shape
  1290. do {
  1291. tok = lexer_.GetNextToken();
  1292. // case: Array(I32)[]
  1293. if (tok != TOK_NUMBER) {
  1294. break;
  1295. }
  1296. shape.push_back(StringToScalar<int>(lexer_.GetTokenText()));
  1297. tok = lexer_.GetNextToken();
  1298. } while (tok == TOK_COMMA);
  1299. if (tok != TOK_RBRACKET) {
  1300. return TOK_ERROR;
  1301. }
  1302. SetArrayType(ptr, elem_type, shape);
  1303. return lexer_.GetNextToken();
  1304. }
  1305. bool IsNumberType(const std::string &type, TypeId *typeid_ptr) {
  1306. // clang-format off
  1307. static std::unordered_map<std::string, TypeId> basic_types = {
  1308. {"Bool", kNumberTypeBool},
  1309. {"I8", kNumberTypeInt8},
  1310. {"I16", kNumberTypeInt16},
  1311. {"I32", kNumberTypeInt32},
  1312. {"I64", kNumberTypeInt64},
  1313. {"U8", kNumberTypeUInt8},
  1314. {"U16", kNumberTypeUInt16},
  1315. {"U32", kNumberTypeUInt32},
  1316. {"U64", kNumberTypeUInt64},
  1317. {"F16", kNumberTypeFloat16},
  1318. {"F32", kNumberTypeFloat32},
  1319. {"F64", kNumberTypeFloat64},
  1320. {"Int", kNumberTypeInt},
  1321. {"UInt", kNumberTypeUInt},
  1322. {"Float", kNumberTypeFloat},
  1323. {"Number", kObjectTypeNumber}};
  1324. // clang-format on
  1325. auto iter = basic_types.find(type);
  1326. if (iter == basic_types.end()) {
  1327. return false;
  1328. }
  1329. if (typeid_ptr != nullptr) {
  1330. *typeid_ptr = iter->second;
  1331. }
  1332. return true;
  1333. }
  1334. template <typename T>
  1335. void ParseNumberType(const std::string &type, TypeId typeId, T *const ptr = nullptr) {
  1336. TypePtr dtype = nullptr;
  1337. std::unordered_map<int, TypePtr> type_map = {
  1338. {static_cast<int>(kNumberTypeBool), std::make_shared<Bool>()}, // Bool
  1339. {static_cast<int>(kNumberTypeInt8), std::make_shared<Int>(8)}, // Int8
  1340. {static_cast<int>(kNumberTypeInt16), std::make_shared<Int>(16)}, // Int16
  1341. {static_cast<int>(kNumberTypeInt32), std::make_shared<Int>(32)}, // Int32
  1342. {static_cast<int>(kNumberTypeInt64), std::make_shared<Int>(64)}, // Int64
  1343. {static_cast<int>(kNumberTypeUInt8), std::make_shared<UInt>(8)}, // UInt8
  1344. {static_cast<int>(kNumberTypeUInt16), std::make_shared<UInt>(16)}, // UInt16
  1345. {static_cast<int>(kNumberTypeUInt32), std::make_shared<UInt>(32)}, // UInt32
  1346. {static_cast<int>(kNumberTypeUInt64), std::make_shared<UInt>(64)}, // UInt64
  1347. {static_cast<int>(kNumberTypeFloat16), std::make_shared<Float>(16)}, // Float16
  1348. {static_cast<int>(kNumberTypeFloat32), std::make_shared<Float>(32)}, // Float32
  1349. {static_cast<int>(kNumberTypeFloat64), std::make_shared<Float>(64)}, // Float64
  1350. {static_cast<int>(kNumberTypeInt), std::make_shared<Int>()}, // Int
  1351. {static_cast<int>(kNumberTypeUInt), std::make_shared<UInt>()}, // UInt
  1352. {static_cast<int>(kNumberTypeFloat), std::make_shared<Float>()}, // Float
  1353. {static_cast<int>(kObjectTypeNumber), std::make_shared<Number>()}, // Number
  1354. };
  1355. auto iter = type_map.find(static_cast<int>(typeId));
  1356. if (iter != type_map.end()) {
  1357. dtype = iter->second;
  1358. } else {
  1359. MS_LOG(EXCEPTION) << "Unknown number type " << type;
  1360. }
  1361. SetBasicType(ptr, dtype);
  1362. }
  1363. template <typename T>
  1364. Token ParseTrivalType(const std::string &type, T *const ptr = nullptr) {
  1365. if (type == "NoneType") {
  1366. SetBasicType(ptr, std::make_shared<TypeNone>());
  1367. return lexer_.GetNextToken();
  1368. } else if (type == "ProblemType") {
  1369. SetBasicType(ptr, std::make_shared<Problem>());
  1370. return lexer_.GetNextToken();
  1371. } else if (type == "ExternalType") {
  1372. SetBasicType(ptr, std::make_shared<External>());
  1373. return lexer_.GetNextToken();
  1374. } else if (type == "AnythingType") {
  1375. SetBasicType(ptr, kAnyType);
  1376. return lexer_.GetNextToken();
  1377. } else if (type == "TypeType") {
  1378. SetBasicType(ptr, std::make_shared<TypeType>());
  1379. return lexer_.GetNextToken();
  1380. } else {
  1381. MS_LOG(EXCEPTION) << "Unknown type error at line " << lexer_.GetLineNo();
  1382. }
  1383. }
  1384. template <typename T>
  1385. Token ParseOneType(const FuncGraphPtr &func_graph, Token tok, T *const ptr = nullptr) {
  1386. if (tok != TOK_IDENTIFIER) {
  1387. return TOK_ERROR;
  1388. }
  1389. std::string type = lexer_.GetTokenText();
  1390. TypeId typeId = kTypeUnknown;
  1391. if (IsNumberType(type, &typeId)) {
  1392. ParseNumberType(type, typeId, ptr);
  1393. return lexer_.GetNextToken();
  1394. } else if (type == "Tuple") {
  1395. return ParseTypeVector(func_graph, lexer_.GetNextToken(), type, ptr);
  1396. } else if (type == "Tensor") {
  1397. return ParseTypeArray(func_graph, lexer_.GetNextToken(), ptr);
  1398. } else if (type == "List") {
  1399. return ParseTypeVector(func_graph, lexer_.GetNextToken(), type, ptr);
  1400. } else if (type == "Func") {
  1401. tok = lexer_.GetNextToken();
  1402. if (tok != TOK_LBRACKET) {
  1403. SetBasicType(ptr, std::make_shared<Function>());
  1404. return tok;
  1405. }
  1406. MS_LOG(EXCEPTION) << "Need to process function parameter types at line " << lexer_.GetLineNo();
  1407. } else if (type == "JT") {
  1408. tok = lexer_.GetNextToken();
  1409. if (tok != TOK_LBRACKET) {
  1410. return tok;
  1411. }
  1412. T elem = nullptr;
  1413. tok = ParseOneType(func_graph, lexer_.GetNextToken(), &elem);
  1414. SetJTaggedType(ptr, elem);
  1415. if (tok != TOK_RBRACKET) {
  1416. return TOK_ERROR;
  1417. }
  1418. return lexer_.GetNextToken();
  1419. } else if (type == "SymType") {
  1420. SetBasicType(ptr, std::make_shared<SymbolicKeyType>());
  1421. return lexer_.GetNextToken();
  1422. } else if (type == "EnvType") {
  1423. SetBasicType(ptr, std::make_shared<EnvType>());
  1424. return lexer_.GetNextToken();
  1425. } else if (Match(type, "Cls.")) {
  1426. MS_LOG(EXCEPTION) << "Need to do class type at line " << lexer_.GetLineNo();
  1427. } else {
  1428. return ParseTrivalType(type, ptr);
  1429. }
  1430. }
  1431. Token ParseType(const FuncGraphPtr &func_graph, AbstractBasePtr *const abstract = nullptr) {
  1432. return ParseOneType(func_graph, lexer_.GetNextToken(), abstract);
  1433. }
  1434. Token ParseAttributes(const FuncGraphPtr &func_graph, const PrimitivePtr &prim) {
  1435. Token tok = ParseAttribute(func_graph, prim);
  1436. while (tok == TOK_COMMA) {
  1437. tok = ParseAttribute(func_graph, prim);
  1438. }
  1439. if (tok != TOK_RBRACKET) {
  1440. return TOK_ERROR;
  1441. }
  1442. return lexer_.GetNextToken();
  1443. }
  1444. Token ParseAttribute(const FuncGraphPtr &func_graph, const PrimitivePtr &prim) {
  1445. Token tok = lexer_.GetNextToken();
  1446. if (tok != TOK_IDENTIFIER) {
  1447. return TOK_ERROR;
  1448. }
  1449. std::string attr_name = lexer_.GetTokenText();
  1450. if (lexer_.GetNextToken() != TOK_EQUALITY) {
  1451. return TOK_ERROR;
  1452. }
  1453. ValuePtr value = nullptr;
  1454. tok = ParseValue(func_graph, lexer_.GetNextToken(), &value);
  1455. if (prim != nullptr) {
  1456. prim->set_attr(attr_name, value);
  1457. } else {
  1458. MS_LOG(EXCEPTION) << "Non primitive obj has attributes";
  1459. }
  1460. return tok;
  1461. }
  1462. FuncGraphPtr ParseParameters(FuncGraphPtr func_graph) {
  1463. Token tok = lexer_.SkipWhiteToken();
  1464. while (tok == TOK_PARAMETER) {
  1465. ParameterPtr param = std::make_shared<Parameter>(func_graph);
  1466. param->set_name(lexer_.GetTokenText());
  1467. param_nodes_[lexer_.GetTokenText()] = param;
  1468. int lineno = lexer_.GetLineNo();
  1469. param->set_debug_info(std::make_shared<NodeDebugInfo>(lexer_.GetTokenText() + "@" + std::to_string(lineno)));
  1470. func_graph->add_parameter(param);
  1471. tok = lexer_.GetNextToken();
  1472. // parse type
  1473. if (tok == TOK_COLON) {
  1474. AbstractBasePtr type = nullptr;
  1475. tok = ParseType(func_graph, &type);
  1476. }
  1477. // parse default value
  1478. if (tok == TOK_EQUALITY) {
  1479. if (lexer_.GetNextToken() != TOK_AT_FILE) {
  1480. MS_LOG(EXCEPTION) << "Expect @file at line " << lexer_.GetLineNo();
  1481. }
  1482. // load parameter default value from serialized file
  1483. py::object default_obj = LoadObject(lexer_.GetTokenText());
  1484. auto param_value_new = py::cast<tensor::TensorPtr>(default_obj);
  1485. param->set_default_param(param_value_new);
  1486. tok = lexer_.GetNextToken();
  1487. }
  1488. if (tok == TOK_COMMENT || tok == TOK_EOL) {
  1489. tok = lexer_.SkipWhiteToken();
  1490. }
  1491. Token next = tok;
  1492. if (next == TOK_RPARENTHESIS) {
  1493. return func_graph;
  1494. } else if (next == TOK_COMMA) {
  1495. tok = lexer_.SkipWhiteToken();
  1496. } else {
  1497. return nullptr;
  1498. }
  1499. }
  1500. return tok == TOK_RPARENTHESIS ? func_graph : nullptr;
  1501. }
  1502. FuncGraphPtr ParseArguments(FuncGraphPtr func_graph, std::vector<AnfNodePtr> *const inputs_ptr) {
  1503. Token tok = ParseArgument(func_graph, inputs_ptr);
  1504. while (tok == TOK_COMMA) {
  1505. tok = ParseArgument(func_graph, inputs_ptr);
  1506. }
  1507. if (tok != TOK_RPARENTHESIS) {
  1508. return nullptr;
  1509. }
  1510. return func_graph;
  1511. }
  1512. AnfNodePtr FindParameter(FuncGraphPtr func_graph, const std::string &param_name) {
  1513. while (func_graph != nullptr) {
  1514. for (auto &ptr : func_graph->parameters()) {
  1515. MS_EXCEPTION_IF_NULL(ptr);
  1516. ParameterPtr param = ptr->cast<ParameterPtr>();
  1517. MS_EXCEPTION_IF_NULL(param);
  1518. if (param->name() == param_name) {
  1519. return ptr;
  1520. }
  1521. }
  1522. auto iter = parents_map_.find(func_graph);
  1523. if (iter == parents_map_.end()) {
  1524. break;
  1525. }
  1526. func_graph = iter->second;
  1527. }
  1528. return nullptr;
  1529. }
  1530. bool Match(const std::string &str, const std::string &pattern) const {
  1531. return strncmp(str.c_str(), pattern.c_str(), pattern.length()) == 0;
  1532. }
  1533. template <typename T, typename V>
  1534. Token ParseScalar(ValuePtr *const val_ptr) {
  1535. if (lexer_.GetNextToken() != TOK_NUMBER) {
  1536. return TOK_ERROR;
  1537. }
  1538. std::stringstream ss;
  1539. ss << lexer_.GetTokenText();
  1540. if (lexer_.GetNextToken() != TOK_RPARENTHESIS) {
  1541. return TOK_ERROR;
  1542. }
  1543. V val;
  1544. ss >> val;
  1545. *val_ptr = std::make_shared<T>(val);
  1546. return lexer_.GetNextToken();
  1547. }
  1548. template <typename VT, typename V, typename T>
  1549. Token ParseScalar(ValuePtr *const val_ptr, Token tok) {
  1550. if (tok != TOK_LPARENTHESIS) {
  1551. *val_ptr = std::make_shared<T>();
  1552. return tok;
  1553. }
  1554. return ParseScalar<VT, V>(val_ptr);
  1555. }
  1556. template <typename VT, typename V, typename T, const unsigned nbits>
  1557. Token ParseScalar(ValuePtr *const val_ptr, Token tok) {
  1558. if (tok != TOK_LPARENTHESIS) {
  1559. *val_ptr = std::make_shared<T>(nbits);
  1560. return tok;
  1561. }
  1562. return ParseScalar<VT, V>(val_ptr);
  1563. }
  1564. template <typename T>
  1565. T StringToScalar(const std::string &text) {
  1566. std::stringstream ss;
  1567. T value;
  1568. ss << text;
  1569. ss >> value;
  1570. return value;
  1571. }
  1572. Token ParseTensor(ValuePtr *const val_ptr) {
  1573. // parse type
  1574. TypeId type;
  1575. if (lexer_.GetNextToken() != TOK_LPARENTHESIS) {
  1576. return TOK_ERROR;
  1577. }
  1578. if (lexer_.GetNextToken() != TOK_NUMBER) {
  1579. return TOK_ERROR;
  1580. }
  1581. type = static_cast<TypeId>(StringToScalar<int>(lexer_.GetTokenText()));
  1582. if (lexer_.GetNextToken() != TOK_RPARENTHESIS) {
  1583. return TOK_ERROR;
  1584. }
  1585. // parse shape
  1586. std::vector<int> shape;
  1587. Token tok = lexer_.GetNextToken();
  1588. if (tok != TOK_LBRACKET) {
  1589. return TOK_ERROR;
  1590. }
  1591. do {
  1592. tok = lexer_.GetNextToken();
  1593. // consider case: Tensor(23)[]
  1594. if (tok != TOK_NUMBER) {
  1595. break;
  1596. }
  1597. shape.push_back(StringToScalar<int>(lexer_.GetTokenText()));
  1598. tok = lexer_.GetNextToken();
  1599. } while (tok == TOK_COMMA);
  1600. if (tok != TOK_RBRACKET) {
  1601. return TOK_ERROR;
  1602. }
  1603. if (lexer_.GetNextToken() != TOK_AT_FILE) {
  1604. return TOK_ERROR;
  1605. }
  1606. py::object tensor_obj = LoadObject(lexer_.GetTokenText());
  1607. py::array tensor_data = py::cast<py::array>(tensor_obj);
  1608. if (tensor_data == nullptr) {
  1609. return TOK_ERROR;
  1610. }
  1611. *val_ptr = TensorPy::MakeTensor(tensor_data, TypeIdToType(type));
  1612. return lexer_.GetNextToken();
  1613. }
  1614. Token ParsePrimType(Token tok, PrimType *prim_type_ptr) {
  1615. if (tok != TOK_LBRACE) {
  1616. return tok;
  1617. }
  1618. if (lexer_.GetNextToken() != TOK_IDENTIFIER) {
  1619. return TOK_ERROR;
  1620. }
  1621. if (lexer_.GetTokenText() != "prim_type") {
  1622. return TOK_ERROR;
  1623. }
  1624. if (lexer_.GetNextToken() != TOK_EQUALITY) {
  1625. return TOK_ERROR;
  1626. }
  1627. if (lexer_.GetNextToken() != TOK_NUMBER) {
  1628. return TOK_ERROR;
  1629. }
  1630. int val = 0;
  1631. std::stringstream ss;
  1632. ss << lexer_.GetTokenText();
  1633. ss >> val;
  1634. *prim_type_ptr = PrimType(val);
  1635. if (lexer_.GetNextToken() != TOK_RBRACE) {
  1636. return TOK_ERROR;
  1637. }
  1638. return lexer_.GetNextToken();
  1639. }
  1640. Token ParseMultitypeFuncGraphItem(const prim::MultitypeFuncGraphPtr &mt_func_graph, Token tok) {
  1641. if (tok != TOK_LPARENTHESIS) {
  1642. return TOK_ERROR;
  1643. }
  1644. TypePtrList type_list;
  1645. do {
  1646. TypePtr type = nullptr;
  1647. tok = ParseOneType(nullptr, lexer_.GetNextToken(), &type);
  1648. type_list.push_back(type);
  1649. } while (tok == TOK_COMMA);
  1650. if (tok != TOK_RPARENTHESIS) {
  1651. return TOK_ERROR;
  1652. }
  1653. if (lexer_.GetNextToken() != TOK_AT_FILE) {
  1654. return TOK_ERROR;
  1655. }
  1656. // load Python function from serialized file
  1657. py::object py_func = LoadObject(lexer_.GetTokenText());
  1658. MS_EXCEPTION_IF_NULL(mt_func_graph);
  1659. mt_func_graph->Register(type_list, py::function(py_func));
  1660. return lexer_.GetNextToken();
  1661. }
  1662. Token ParseMultitypeFuncGraph(const prim::MultitypeFuncGraphPtr &mt_func_graph, Token tok) {
  1663. if (tok != TOK_LBRACE) {
  1664. return tok;
  1665. }
  1666. do {
  1667. tok = ParseMultitypeFuncGraphItem(mt_func_graph, lexer_.GetNextToken());
  1668. } while (tok == TOK_COMMA);
  1669. if (tok != TOK_RBRACE) {
  1670. return TOK_ERROR;
  1671. }
  1672. return lexer_.GetNextToken();
  1673. }
  1674. Token ParseBoolValue(const std::string &key, bool *val_ptr) {
  1675. if (lexer_.GetNextToken() != TOK_IDENTIFIER || lexer_.GetTokenText() != key) {
  1676. return TOK_ERROR;
  1677. }
  1678. if (lexer_.GetNextToken() != TOK_EQUALITY) {
  1679. return TOK_ERROR;
  1680. }
  1681. if (lexer_.GetNextToken() != TOK_NUMBER) {
  1682. return TOK_ERROR;
  1683. }
  1684. bool value = false;
  1685. {
  1686. std::stringstream ss;
  1687. ss << lexer_.GetTokenText();
  1688. ss >> value;
  1689. }
  1690. if (val_ptr != nullptr) {
  1691. *val_ptr = value;
  1692. }
  1693. return lexer_.GetNextToken();
  1694. }
  1695. Token ParseValueGradOperation(const std::string &name, ValuePtr *const val_ptr) {
  1696. if (lexer_.GetNextToken() != TOK_LBRACE) {
  1697. return TOK_ERROR;
  1698. }
  1699. // get_all=0, get_by_list=1, sens_param=1
  1700. bool get_all = false;
  1701. Token tok = ParseBoolValue("get_all", &get_all);
  1702. if (tok != TOK_COMMA) {
  1703. return TOK_ERROR;
  1704. }
  1705. bool get_by_list = false;
  1706. tok = ParseBoolValue("get_by_list", &get_by_list);
  1707. if (tok != TOK_COMMA) {
  1708. return TOK_ERROR;
  1709. }
  1710. bool sens_param = false;
  1711. tok = ParseBoolValue("sens_param", &sens_param);
  1712. if (tok != TOK_RBRACE) {
  1713. return TOK_ERROR;
  1714. }
  1715. *val_ptr = std::make_shared<prim::GradOperation>(name, get_all, get_by_list, sens_param);
  1716. return lexer_.GetNextToken();
  1717. }
  1718. Token ParseSymbolicKeyInstance(const FuncGraphPtr &func_graph, AnfNodePtr *const node_ptr = nullptr) {
  1719. if (lexer_.GetNextToken() != TOK_LPARENTHESIS) {
  1720. return TOK_ERROR;
  1721. }
  1722. if (lexer_.GetNextToken() != TOK_PARAMETER) {
  1723. return TOK_ERROR;
  1724. }
  1725. std::string param_name = lexer_.GetTokenText();
  1726. if (lexer_.GetNextToken() != TOK_RPARENTHESIS) {
  1727. return TOK_ERROR;
  1728. }
  1729. auto iter = param_nodes_.find(param_name);
  1730. if (iter == param_nodes_.end()) {
  1731. MS_LOG(EXCEPTION) << "Can not find param '" << param_name << "' for SymbolicKeyInstance at line "
  1732. << lexer_.GetLineNo();
  1733. }
  1734. PrimitivePtr embed = std::make_shared<Primitive>("embed");
  1735. std::vector<AnfNodePtr> inputs;
  1736. inputs.push_back(std::make_shared<ValueNode>(embed));
  1737. inputs.push_back(iter->second);
  1738. if (node_ptr != nullptr) {
  1739. MS_EXCEPTION_IF_NULL(func_graph);
  1740. *node_ptr = func_graph->NewCNode(inputs);
  1741. } else {
  1742. MS_LOG(EXCEPTION) << "Not processed SymbolicKeyInstance '" << param_name << "' at line " << lexer_.GetLineNo()
  1743. << ".";
  1744. }
  1745. return lexer_.GetNextToken();
  1746. }
  1747. Token ParsePrimitivePy(const FuncGraphPtr &func_graph, const std::string &id, ValuePtr *const val_ptr) {
  1748. if (lexer_.GetNextToken() != TOK_AT_FILE) {
  1749. return TOK_ERROR;
  1750. }
  1751. // restore python function of PrimitivePy from serialized file
  1752. py::object py_obj = LoadObject(lexer_.GetTokenText());
  1753. PrimitivePyPtr ptr = nullptr;
  1754. if (py::hasattr(py_obj, "__setattr_flag__") && py::hasattr(py_obj, "_clone")) {
  1755. auto clone_fn = py_obj.attr("_clone");
  1756. py::object new_obj = clone_fn();
  1757. ptr = new_obj.cast<PrimitivePyPtr>();
  1758. if (ptr == nullptr) {
  1759. MS_LOG(EXCEPTION) << "Cast to type 'PrimitivePyPtr' error";
  1760. }
  1761. } else {
  1762. auto len = strlen("PrimitivePy::");
  1763. if (id.size() < len) {
  1764. return TOK_ERROR;
  1765. }
  1766. ptr = std::make_shared<PrimitivePy>(id.substr(len), py_obj);
  1767. }
  1768. *val_ptr = ptr;
  1769. PrimType prim_type = kPrimTypeUnknown;
  1770. Token next = ParsePrimType(lexer_.GetNextToken(), &prim_type);
  1771. if (prim_type != kPrimTypeUnknown) {
  1772. ptr->set_prim_type(prim_type);
  1773. }
  1774. if (next != TOK_LBRACKET) {
  1775. return next;
  1776. }
  1777. // parse attributes
  1778. next = ParseAttributes(func_graph, ptr);
  1779. return next;
  1780. }
  1781. Token ParseValueGraphAndNamespace(const std::string &id, ValuePtr *const val_ptr) {
  1782. if (Match(id, "MultitypeFuncGraph::")) {
  1783. std::string name = id.substr(strlen("MultitypeFuncGraph::"));
  1784. auto mt_func_graph = std::make_shared<prim::MultitypeFuncGraph>(name);
  1785. *val_ptr = mt_func_graph;
  1786. Token next = ParseMultitypeFuncGraph(mt_func_graph, lexer_.GetNextToken());
  1787. return next;
  1788. } else if (Match(id, "HyperMapPy::")) {
  1789. *val_ptr = std::make_shared<prim::HyperMapPy>();
  1790. Token next = lexer_.GetNextToken();
  1791. // process case: fn_leaf is not null
  1792. if (next == TOK_LBRACE) {
  1793. MS_LOG(EXCEPTION) << "Need to process fn_leaf at line " << lexer_.GetLineNo();
  1794. }
  1795. return next;
  1796. } else if (Match(id, "FuncGraph::")) {
  1797. std::string func_graph_name = id.substr(strlen("FuncGraph::"));
  1798. // if the graph does not exist, create a null graph, then fill the graph when encounter the definition
  1799. // of the graph
  1800. if (func_graphs_map_.find(func_graph_name) == func_graphs_map_.end()) {
  1801. func_graphs_map_[func_graph_name] = std::make_shared<FuncGraph>();
  1802. }
  1803. *val_ptr = func_graphs_map_[func_graph_name];
  1804. return lexer_.GetNextToken();
  1805. } else if (Match(id, "NameSpace::")) {
  1806. std::string module_name = id.substr(strlen("NameSpace::"));
  1807. if (lexer_.GetNextToken() != TOK_AT_FILE) {
  1808. MS_LOG(ERROR) << "Expect TOK_AT_FILE at line " << lexer_.GetLineNo();
  1809. return TOK_ERROR;
  1810. }
  1811. // load Python module information from serialized file
  1812. py::object py_obj = LoadObject(lexer_.GetTokenText());
  1813. *val_ptr = std::make_shared<parse::NameSpace>(module_name, py_obj);
  1814. return lexer_.GetNextToken();
  1815. } else {
  1816. MS_LOG(EXCEPTION) << "Unknown id " << id << " at line " << lexer_.GetLineNo();
  1817. }
  1818. }
  1819. Token ParseValueBasic(const FuncGraphPtr &func_graph, const std::string &id, ValuePtr *const val_ptr,
  1820. AnfNodePtr *const node_ptr = nullptr) {
  1821. if (id == "None") {
  1822. *val_ptr = std::make_shared<None>();
  1823. return lexer_.GetNextToken();
  1824. } else if (id == "Bool") {
  1825. return ParseScalar<BoolImm, bool, Bool>(val_ptr, lexer_.GetNextToken());
  1826. } else if (id == "I8") {
  1827. return ParseScalar<Int8Imm, int8_t, Int, 8>(val_ptr, lexer_.GetNextToken());
  1828. } else if (id == "I16") {
  1829. return ParseScalar<Int16Imm, int16_t, Int, 16>(val_ptr, lexer_.GetNextToken());
  1830. } else if (id == "I32") {
  1831. return ParseScalar<Int32Imm, int32_t, Int, 32>(val_ptr, lexer_.GetNextToken());
  1832. } else if (id == "I64") {
  1833. return ParseScalar<Int64Imm, int64_t, Int, 64>(val_ptr, lexer_.GetNextToken());
  1834. } else if (id == "U8") {
  1835. return ParseScalar<UInt8Imm, uint8_t, UInt, 8>(val_ptr, lexer_.GetNextToken());
  1836. } else if (id == "U16") {
  1837. return ParseScalar<UInt16Imm, uint16_t, UInt, 16>(val_ptr, lexer_.GetNextToken());
  1838. } else if (id == "U32") {
  1839. return ParseScalar<UInt32Imm, uint32_t, UInt, 32>(val_ptr, lexer_.GetNextToken());
  1840. } else if (id == "U64") {
  1841. return ParseScalar<UInt64Imm, uint64_t, UInt, 64>(val_ptr, lexer_.GetNextToken());
  1842. } else if (id == "F16") {
  1843. // Notice: Since there is no basic data type for storing fp16, just use float instead
  1844. return ParseScalar<FP32Imm, float, Float, 16>(val_ptr, lexer_.GetNextToken());
  1845. } else if (id == "F32") {
  1846. return ParseScalar<FP32Imm, float, Float, 32>(val_ptr, lexer_.GetNextToken());
  1847. } else if (id == "F64") {
  1848. return ParseScalar<FP64Imm, double, Float, 64>(val_ptr, lexer_.GetNextToken());
  1849. } else if (id == "Tensor") {
  1850. return ParseTensor(val_ptr);
  1851. } else if (id == "SymInst") {
  1852. return ParseSymbolicKeyInstance(func_graph, node_ptr);
  1853. } else if (id == "Array") {
  1854. TypePtr type = nullptr;
  1855. Token ret = ParseTypeArray(func_graph, lexer_.GetNextToken(), &type);
  1856. *val_ptr = type;
  1857. return ret;
  1858. } else if (Match(id, "PrimitivePy::")) {
  1859. return ParsePrimitivePy(func_graph, id, val_ptr);
  1860. } else if (Match(id, "Primitive::")) {
  1861. *val_ptr = std::make_shared<Primitive>(id.substr(strlen("Primitive::")));
  1862. return lexer_.GetNextToken();
  1863. } else if (Match(id, "GradOperation::")) {
  1864. return ParseValueGradOperation(id.substr(strlen("GradOperation::")), val_ptr);
  1865. } else {
  1866. return ParseValueGraphAndNamespace(id, val_ptr);
  1867. }
  1868. }
  1869. Token SetListOrTupleValue(const FuncGraphPtr &func_graph, Token left_tok, Token next, bool node_is_valid,
  1870. const std::vector<ValuePtr> &elems, const std::vector<AnfNodePtr> &nodes,
  1871. ValuePtr *const val_ptr, AnfNodePtr *node_ptr) {
  1872. if (left_tok == TOK_LPARENTHESIS && next == TOK_RPARENTHESIS) {
  1873. if (node_is_valid && node_ptr != nullptr) {
  1874. MS_EXCEPTION_IF_NULL(func_graph);
  1875. *node_ptr = func_graph->NewCNode(nodes);
  1876. } else {
  1877. *val_ptr = std::make_shared<ValueTuple>(elems);
  1878. }
  1879. return lexer_.GetNextToken();
  1880. } else if (left_tok == TOK_LBRACKET && next == TOK_RBRACKET) {
  1881. if (node_is_valid && node_ptr != nullptr) {
  1882. MS_LOG(EXCEPTION) << "Encounter valid node in value list";
  1883. }
  1884. *val_ptr = std::make_shared<ValueList>(elems);
  1885. return lexer_.GetNextToken();
  1886. } else {
  1887. return TOK_ERROR;
  1888. }
  1889. }
  1890. Token ParseListOrTupleValue(const FuncGraphPtr &func_graph, Token tok, ValuePtr *const val_ptr,
  1891. AnfNodePtr *node_ptr = nullptr) {
  1892. Token left_tok = tok;
  1893. std::vector<ValuePtr> elems;
  1894. std::vector<AnfNodePtr> nodes;
  1895. nodes.push_back(std::make_shared<ValueNode>(std::make_shared<Primitive>("make_tuple")));
  1896. ValuePtr elem = nullptr;
  1897. AnfNodePtr node = nullptr;
  1898. bool node_is_valid = false;
  1899. bool first_flag = true;
  1900. Token next = TOK_ERROR;
  1901. do {
  1902. next = lexer_.GetNextToken();
  1903. if (first_flag) {
  1904. first_flag = false;
  1905. // case (), zero elements
  1906. if ((left_tok == TOK_LPARENTHESIS && next == TOK_RPARENTHESIS) ||
  1907. (left_tok == TOK_LBRACKET && next == TOK_RBRACKET)) {
  1908. if (left_tok == TOK_LPARENTHESIS) {
  1909. *val_ptr = std::make_shared<ValueTuple>(elems);
  1910. } else {
  1911. *val_ptr = std::make_shared<ValueList>(elems);
  1912. }
  1913. return lexer_.GetNextToken();
  1914. }
  1915. }
  1916. node = nullptr;
  1917. next = ParseValue(func_graph, next, &elem, &node);
  1918. elems.push_back(elem);
  1919. if (node != nullptr) {
  1920. nodes.push_back(node);
  1921. node_is_valid = true;
  1922. } else {
  1923. nodes.push_back(std::make_shared<ValueNode>(elem));
  1924. }
  1925. } while (next == TOK_COMMA);
  1926. return SetListOrTupleValue(func_graph, left_tok, next, node_is_valid, elems, nodes, val_ptr, node_ptr);
  1927. }
  1928. Token ParseValue(const FuncGraphPtr &func_graph, Token tok, ValuePtr *const val_ptr, AnfNodePtr *node_ptr = nullptr) {
  1929. // tuple or list
  1930. if (tok == TOK_LPARENTHESIS || tok == TOK_LBRACKET) {
  1931. return ParseListOrTupleValue(func_graph, tok, val_ptr, node_ptr);
  1932. } else if (tok == TOK_IDENTIFIER) {
  1933. return ParseValueBasic(func_graph, lexer_.GetTokenText(), val_ptr, node_ptr);
  1934. } else if (tok == TOK_STRING) {
  1935. *val_ptr = std::make_shared<StringImm>(lexer_.GetTokenText());
  1936. return lexer_.GetNextToken();
  1937. }
  1938. MS_LOG(ERROR) << "Parse error!";
  1939. return TOK_ERROR;
  1940. }
  1941. Token ParseItem(const FuncGraphPtr &func_graph, AnfNodePtr *node_ptr, ValuePtr *const val_ptr,
  1942. Token tok = TOK_INVALID) {
  1943. if (tok == TOK_INVALID) {
  1944. tok = lexer_.GetNextToken();
  1945. }
  1946. if (tok == TOK_VARIABLE) {
  1947. auto iter = cnodes_.find(lexer_.GetTokenText());
  1948. if (iter == cnodes_.end()) {
  1949. MS_LOG(EXCEPTION) << "Can not find definition of '" << lexer_.GetTokenText() << "'";
  1950. }
  1951. *node_ptr = iter->second;
  1952. } else if (tok == TOK_PARAMETER) {
  1953. AnfNodePtr param = FindParameter(func_graph, lexer_.GetTokenText());
  1954. if (param == nullptr) {
  1955. MS_LOG(EXCEPTION) << "Can not find definition of '" << lexer_.GetTokenText() << "' at line "
  1956. << lexer_.GetLineNo();
  1957. }
  1958. *node_ptr = param;
  1959. } else if (tok == TOK_IDENTIFIER || tok == TOK_LPARENTHESIS || tok == TOK_STRING) {
  1960. ValuePtr value;
  1961. AnfNodePtr node;
  1962. tok = ParseValue(func_graph, tok, &value, &node);
  1963. if (tok == TOK_ERROR) {
  1964. MS_LOG(ERROR) << "Parse value error!";
  1965. return tok;
  1966. }
  1967. if (node == nullptr) {
  1968. *val_ptr = value;
  1969. *node_ptr = std::make_shared<ValueNode>(value);
  1970. } else {
  1971. *node_ptr = node;
  1972. }
  1973. return tok;
  1974. } else {
  1975. MS_LOG(EXCEPTION) << "tok_type = " << tok;
  1976. }
  1977. return lexer_.GetNextToken();
  1978. }
  1979. Token ParseArgument(const FuncGraphPtr &func_graph, std::vector<AnfNodePtr> *const inputs_ptr) {
  1980. Token tok = lexer_.GetNextToken();
  1981. if (tok == TOK_RPARENTHESIS) {
  1982. return tok;
  1983. }
  1984. AnfNodePtr node = nullptr;
  1985. ValuePtr value = nullptr;
  1986. tok = ParseItem(func_graph, &node, &value, tok);
  1987. if (tok != TOK_ERROR) {
  1988. MS_EXCEPTION_IF_NULL(inputs_ptr);
  1989. inputs_ptr->push_back(node);
  1990. }
  1991. return tok;
  1992. }
  1993. const std::vector<FuncGraphPtr> &GetFuncGraphs() const { return func_graphs_; }
  1994. private:
  1995. Lexer lexer_;
  1996. std::vector<FuncGraphPtr> func_graphs_;
  1997. bool error_flag_ = false;
  1998. // store all parsed graphs
  1999. std::map<std::string, FuncGraphPtr> func_graphs_map_;
  2000. // map from child to parent, consider adding a 'parent' field in class Graph
  2001. std::map<FuncGraphPtr, FuncGraphPtr> parents_map_;
  2002. // map for buffering cnodes when parsing a graph
  2003. std::map<std::string, CNodePtr> cnodes_;
  2004. std::map<std::string, ParameterPtr> param_nodes_; // map parameter name to parameter
  2005. };
  2006. std::vector<FuncGraphPtr> ImportIR(const std::string &filename) {
  2007. IrParser parser(filename.c_str());
  2008. parser.ParseFile();
  2009. return parser.GetFuncGraphs();
  2010. }
  2011. #ifdef ENABLE_DUMP_IR
  2012. void DumpIRProto(const FuncGraphPtr &func_graph, const std::string &suffix) {
  2013. if (func_graph == nullptr) {
  2014. MS_LOG(ERROR) << "Func graph is nullptr";
  2015. return;
  2016. }
  2017. auto ms_context = MsContext::GetInstance();
  2018. if (ms_context == nullptr) {
  2019. MS_LOG(ERROR) << "ms_context is nullptr";
  2020. return;
  2021. }
  2022. auto save_graphs_path = ms_context->save_graphs_path();
  2023. if (save_graphs_path.empty()) {
  2024. save_graphs_path = ".";
  2025. }
  2026. std::string file_path = save_graphs_path + "/" + "ms_output_" + suffix + ".pb";
  2027. if (file_path.size() > PATH_MAX) {
  2028. MS_LOG(ERROR) << "File path " << file_path << " is too long.";
  2029. return;
  2030. }
  2031. char real_path[PATH_MAX] = {0};
  2032. char *real_path_ret = nullptr;
  2033. #if defined(_WIN32) || defined(_WIN64)
  2034. real_path_ret = _fullpath(real_path, file_path.c_str(), PATH_MAX);
  2035. #else
  2036. real_path_ret = realpath(file_path.c_str(), real_path);
  2037. #endif
  2038. if (nullptr == real_path_ret) {
  2039. MS_LOG(DEBUG) << "dir " << file_path << " does not exit.";
  2040. } else {
  2041. std::string path_string = real_path;
  2042. if (chmod(common::SafeCStr(path_string), S_IRUSR | S_IWUSR) == -1) {
  2043. MS_LOG(ERROR) << "Modify file:" << real_path << " to rw fail.";
  2044. return;
  2045. }
  2046. }
  2047. // write to pb file
  2048. std::ofstream ofs(real_path);
  2049. if (!ofs.is_open()) {
  2050. MS_LOG(ERROR) << "Open file '" << real_path << "' failed!";
  2051. return;
  2052. }
  2053. ofs << GetFuncGraphProtoString(func_graph);
  2054. ofs.close();
  2055. // set file mode to read only by user
  2056. ChangeFileMode(file_path, S_IRUSR);
  2057. }
  2058. #else
  2059. void DumpIRProto(const FuncGraphPtr &, const std::string &) {
  2060. static bool already_printed = false;
  2061. if (already_printed) {
  2062. return;
  2063. }
  2064. already_printed = true;
  2065. MS_LOG(WARNING) << "The functionality of dumping function graph IR in protobuf format is disabled, "
  2066. << "please recompile source to enable it. See help of building script.";
  2067. }
  2068. #endif
  2069. } // namespace mindspore