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

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