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

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