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

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