You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

anf_ir_utils.cc 73 kB

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