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

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