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