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.

graph_manager.cc 96 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384
  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 "graph/manager/graph_manager.h"
  17. #include <pthread.h>
  18. #include <algorithm>
  19. #include <future>
  20. #include <set>
  21. #include <sstream>
  22. #include <string>
  23. #include <thread>
  24. #include <utility>
  25. #include "common/ge/ge_util.h"
  26. #include "common/math/math_util.h"
  27. #include "common/thread_pool.h"
  28. #include "common/util.h"
  29. #include "external/graph/types.h"
  30. #include "framework/common/debug/ge_log.h"
  31. #include "framework/common/ge_inner_error_codes.h"
  32. #include "framework/common/ge_types.h"
  33. #include "graph/common/ge_call_wrapper.h"
  34. #include "graph/common/transop_util.h"
  35. #include "graph/debug/ge_attr_define.h"
  36. #include "graph/ge_context.h"
  37. #include "graph/ge_global_options.h"
  38. #include "graph/ge_local_context.h"
  39. #include "graph/manager/graph_mem_allocator.h"
  40. #include "graph/manager/util/rt_context_util.h"
  41. #include "graph/partition/dynamic_shape_partition.h"
  42. #include "graph/passes/addn_pass.h"
  43. #include "graph/passes/atomic_addr_clean_pass.h"
  44. #include "graph/passes/cast_remove_pass.h"
  45. #include "graph/passes/common_subexpression_elimination_pass.h"
  46. #include "graph/passes/compile_nodes_pass.h"
  47. #include "graph/passes/cond_remove_pass.h"
  48. #include "graph/passes/constant_folding_pass.h"
  49. #include "graph/passes/constant_fuse_same_pass.h"
  50. #include "graph/passes/control_trigger_pass.h"
  51. #include "graph/passes/ctrl_edge_transfer_pass.h"
  52. #include "graph/passes/dimension_adjust_pass.h"
  53. #include "graph/passes/dimension_compute_pass.h"
  54. #include "graph/passes/flow_ctrl_pass.h"
  55. #include "graph/passes/hccl_group_pass.h"
  56. #include "graph/passes/hccl_memcpy_pass.h"
  57. #include "graph/passes/identify_reference_pass.h"
  58. #include "graph/passes/identity_pass.h"
  59. #include "graph/passes/iterator_op_pass.h"
  60. #include "graph/passes/link_gen_mask_nodes_pass.h"
  61. #include "graph/passes/merge_pass.h"
  62. #include "graph/passes/multi_batch_pass.h"
  63. #include "graph/passes/next_iteration_pass.h"
  64. #include "graph/passes/permute_pass.h"
  65. #include "graph/passes/prune_pass.h"
  66. #include "graph/passes/replace_with_empty_const_pass.h"
  67. #include "graph/passes/reshape_recovery_pass.h"
  68. #include "graph/passes/reshape_remove_pass.h"
  69. #include "graph/passes/same_transdata_breadth_fusion_pass.h"
  70. #include "graph/passes/subgraph_pass.h"
  71. #include "graph/passes/switch_data_edges_bypass.h"
  72. #include "graph/passes/switch_dead_branch_elimination.h"
  73. #include "graph/passes/switch_logic_remove_pass.h"
  74. #include "graph/passes/switch_op_pass.h"
  75. #include "graph/passes/transop_breadth_fusion_pass.h"
  76. #include "graph/passes/transop_depth_fusion_pass.h"
  77. #include "graph/passes/transop_nearby_allreduce_fusion_pass.h"
  78. #include "graph/passes/transop_symmetry_elimination_pass.h"
  79. #include "graph/passes/transop_without_reshape_fusion_pass.h"
  80. #include "graph/passes/transpose_transdata_pass.h"
  81. #include "graph/passes/variable_op_pass.h"
  82. #include "graph/passes/variable_prepare_op_pass.h"
  83. #include "graph/passes/variable_ref_delete_op_pass.h"
  84. #include "graph/passes/variable_ref_useless_control_out_delete_pass.h"
  85. #include "graph/utils/tensor_adapter.h"
  86. #include "inc/pass_manager.h"
  87. #include "init/gelib.h"
  88. namespace {
  89. const char *const kSummary = "Summary";
  90. const char *const kSave = "Save";
  91. const char *const kNetOutput = "NetOutput";
  92. const char *const kVariable = "Variable";
  93. const char *const kSend = "Send";
  94. const char *const kRecv = "Recv";
  95. bool IsTailingOptimization() {
  96. string is_tailing_optimization_option;
  97. auto ret = ge::GetContext().GetOption(ge::OPTION_EXEC_ENABLE_TAILING_OPTIMIZATION, is_tailing_optimization_option);
  98. if (ret == ge::GRAPH_SUCCESS) {
  99. GELOGI("Option ge.exec.isTailingOptimization is %s", is_tailing_optimization_option.c_str());
  100. // "1" means it's True from frontend option
  101. return is_tailing_optimization_option == "1";
  102. }
  103. GELOGW("OPTION_EXEC_ENABLE_TAILING_OPTIMIZATION not set, use BFSTopologicalSorting by default.");
  104. return false;
  105. }
  106. } // namespace
  107. namespace ge {
  108. GraphManager::GraphManager() : thread_run_flag_(false), graph_run_listener_(nullptr), init_flag_(false) {}
  109. Status GraphManager::Initialize(const std::map<string, string> &options) {
  110. if (init_flag_) {
  111. GELOGW("[Initialize] GraphManager already initialized.");
  112. return SUCCESS;
  113. }
  114. // malloc
  115. graph_run_listener_ = MakeShared<GraphModelListener>(sync_run_mutex_, condition_);
  116. if (graph_run_listener_ == nullptr) {
  117. GELOGE(MEMALLOC_FAILED, "Make shared failed");
  118. return MEMALLOC_FAILED;
  119. }
  120. // graph context
  121. graph_context_ = MakeShared<GraphContext>();
  122. if (graph_context_ == nullptr) {
  123. GELOGE(MEMALLOC_FAILED, "Make shared failed.");
  124. return MEMALLOC_FAILED;
  125. }
  126. // parse option parameters
  127. Status ret = ParseOptions(options);
  128. if (ret != SUCCESS) {
  129. GELOGE(ret, "[Initialize] parse options failed.");
  130. return ret;
  131. }
  132. graph_builder_.SetOptions(options_);
  133. ret = graph_optimize_.SetOptions(options_);
  134. if (ret != SUCCESS) {
  135. GELOGE(ret, "[Initialize] Graph optimize initialize failed.");
  136. return ret;
  137. }
  138. graph_preparer_.SetOptions(options_);
  139. ret = graph_context_->Initialize(options);
  140. if (ret != SUCCESS) {
  141. GELOGE(ret, "[Initialize] GraphContext initialize failed.");
  142. return ret;
  143. }
  144. graph_map_.clear();
  145. cache_helper_map_.clear();
  146. init_flag_ = true;
  147. thread_run_flag_ = true;
  148. prerun_thread_ = std::thread(GraphManager::PreRunThread, this);
  149. run_thread_ = std::thread(GraphManager::RunThread, this);
  150. return SUCCESS;
  151. }
  152. Status GraphManager::Finalize() {
  153. if (!init_flag_) {
  154. GELOGW("GraphManager has not been initialized.");
  155. return SUCCESS;
  156. }
  157. if (graph_executor_.FreeExecuteMemory() != SUCCESS) {
  158. GELOGW("Graph executor FreeExecuteMemory failed, resources may not be released correctly.");
  159. }
  160. StopQueue(this);
  161. if (prerun_thread_.joinable()) {
  162. prerun_thread_.join();
  163. }
  164. if (run_thread_.joinable()) {
  165. run_thread_.join();
  166. }
  167. // check graph whether running or not
  168. Status unload_model_ret = SUCCESS;
  169. Status ret;
  170. rtError_t rt_ret;
  171. for (auto iter = graph_map_.begin(); iter != graph_map_.end(); ++iter) {
  172. GraphNodePtr graph_node = iter->second;
  173. if (graph_node->GetRunFlag()) {
  174. GELOGW("[GraphManager] finalize failed, graphId=%u.", iter->first);
  175. unload_model_ret = GE_GRAPH_GRAPH_IS_RUNNING;
  176. continue;
  177. }
  178. // unload model
  179. auto ge_root_model = graph_node->GetGeRootModel();
  180. if (ge_root_model != nullptr && ge_root_model->GetModelId() != INVALID_MODEL_ID && graph_node->GetLoadFlag()) {
  181. rt_ret = rtSetDevice(GetContext().DeviceId());
  182. if (rt_ret != RT_ERROR_NONE) {
  183. GELOGW("[GraphManager] rtSetDevice failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(), iter->first);
  184. unload_model_ret = FAILED;
  185. continue;
  186. }
  187. ret = GraphLoader::UnloadModel(ge_root_model->GetModelId());
  188. if (ret != SUCCESS) {
  189. GELOGW("[GraphManager] unload model failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(), iter->first);
  190. unload_model_ret = ret;
  191. }
  192. rt_ret = rtDeviceReset(GetContext().DeviceId());
  193. if (rt_ret != RT_ERROR_NONE) {
  194. GELOGW("[GraphManager] rtDeviceReset failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(),
  195. iter->first);
  196. unload_model_ret = FAILED;
  197. continue;
  198. }
  199. }
  200. }
  201. graph_map_.clear();
  202. cache_helper_map_.clear();
  203. // graph context
  204. if (graph_context_ != nullptr) {
  205. Status ret_final = graph_context_->Finalize();
  206. if (ret_final != SUCCESS) {
  207. GELOGE(ret_final, "[GraphManager] graph context Finalize failed!");
  208. unload_model_ret = ret_final;
  209. }
  210. }
  211. init_flag_ = false;
  212. return unload_model_ret;
  213. }
  214. Status GraphManager::AddGraph(const GraphId &graph_id, const Graph &graph,
  215. const std::map<std::string, std::string> &options) {
  216. if (graph_map_.find(graph_id) != graph_map_.end()) {
  217. GELOGE(GE_GRAPH_GRAPH_ALREADY_EXIST, "[GraphManager] graph exists, graph_id = %u.", graph_id);
  218. return GE_GRAPH_GRAPH_ALREADY_EXIST;
  219. }
  220. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  221. if (compute_graph != nullptr) {
  222. compute_graph->SetGraphID(graph_id);
  223. } else {
  224. GELOGE(FAILED, "compute graph is null");
  225. return FAILED;
  226. }
  227. std::string session_graph_id;
  228. if (!AttrUtils::GetStr(*compute_graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id) || session_graph_id.empty()) {
  229. session_graph_id = "-1_" + to_string(graph_id);
  230. if (!AttrUtils::SetStr(*compute_graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id)) {
  231. GELOGW("Set attribute of compute graph failed.");
  232. }
  233. for (auto &subgraph : compute_graph->GetAllSubgraphs()) {
  234. (void)AttrUtils::SetStr(*subgraph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id);
  235. }
  236. GELOGW("Get graph session_graph_id attr failed, set session id to default value: [0]");
  237. }
  238. GraphNodePtr graph_node = MakeShared<ge::GraphNode>(graph_id);
  239. if (graph_node == nullptr) {
  240. GELOGE(FAILED, "GraphNode make shared failed");
  241. return FAILED;
  242. }
  243. std::shared_ptr<Graph> graph_ptr = MakeShared<ge::Graph>(graph);
  244. if (graph_ptr == nullptr) {
  245. GELOGE(FAILED, "GraphPtr make shared failed");
  246. return FAILED;
  247. }
  248. graph_node->SetGraph(graph_ptr);
  249. graph_node->SetOptions(options);
  250. graph_map_.insert(std::make_pair(graph_id, graph_node));
  251. GELOGI("[GraphManager] add graph success, graph_id = %u.", graph_id);
  252. var_acc_ctrl_.AddGraph(graph_id, compute_graph);
  253. return SUCCESS;
  254. }
  255. Status GraphManager::MergeSubGraph(ComputeGraphPtr &compute_graph, const ge::ComputeGraphPtr &original_compute_graph) {
  256. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  257. if (instance_ptr != nullptr && instance_ptr->InitFlag()) {
  258. Status ret = graph_partitioner_.MergeAfterSubGraphOptimization(compute_graph, original_compute_graph);
  259. if (ret != SUCCESS) {
  260. GELOGE(ret, "merge end and placeholder after subGraph optimization failed.");
  261. return FAILED;
  262. }
  263. Status ret_topo = compute_graph->TopologicalSorting();
  264. if (ret_topo != SUCCESS) {
  265. GELOGE(ret_topo, "[GraphManager]: TopologicalSorting the merged graph failed.");
  266. return ret_topo;
  267. }
  268. } else {
  269. auto subgraph_list = graph_partitioner_.GetSubGraphMap();
  270. if (subgraph_list.find(original_compute_graph) != subgraph_list.end() &&
  271. !subgraph_list[original_compute_graph].empty() && subgraph_list[original_compute_graph][0] != nullptr) {
  272. compute_graph = subgraph_list[original_compute_graph][0]->GetSubGraph();
  273. }
  274. }
  275. return SUCCESS;
  276. }
  277. Status GraphManager::SetSubgraph(uint64_t session_id, ComputeGraphPtr compute_graph) {
  278. // use default 16 multi thread
  279. const uint32_t thread_num = 16;
  280. ThreadPool executor(thread_num);
  281. auto sub_graph_map = graph_partitioner_.GetSubGraphMap();
  282. std::vector<std::future<Status>> vector_future;
  283. const auto &root_subgraph_list = sub_graph_map[compute_graph];
  284. for (const auto &subgraph : root_subgraph_list) {
  285. std::future<Status> f = executor.commit(GraphManager::ProcessSubGraphWithMultiThreads, this, subgraph, session_id,
  286. GetThreadLocalContext());
  287. if (!f.valid()) {
  288. GELOGE(FAILED, "Future is invalid");
  289. return FAILED;
  290. }
  291. vector_future.emplace_back(std::move(f));
  292. }
  293. for (auto &function_graph : compute_graph->GetAllSubgraphs()) {
  294. auto subgraph_list = sub_graph_map[function_graph];
  295. for (const auto &subgraph : subgraph_list) {
  296. std::future<Status> f = executor.commit(GraphManager::ProcessSubGraphWithMultiThreads, this, subgraph, session_id,
  297. GetThreadLocalContext());
  298. if (!f.valid()) {
  299. GELOGE(FAILED, "Future is invalid");
  300. return FAILED;
  301. }
  302. vector_future.emplace_back(std::move(f));
  303. }
  304. }
  305. GELOGI("All sub graph num is %zu", vector_future.size());
  306. for (size_t i = 0; i < vector_future.size(); ++i) {
  307. Status ret_status = vector_future[i].get();
  308. if (ret_status != SUCCESS) {
  309. GELOGE(ret_status, "subgraph %zu optimize failed", i);
  310. return ret_status;
  311. }
  312. }
  313. return SUCCESS;
  314. }
  315. #define GM_RUN_AND_DUMP(name, func, ...) \
  316. do { \
  317. GE_RUN(GraphManager, func, __VA_ARGS__); \
  318. GE_DUMP(compute_graph, "PreRunAfter" name); \
  319. GELOGI("Run %s on graph %s(%u) success.", name, compute_graph->GetName().c_str(), graph_node->GetGraphId()); \
  320. } while (0)
  321. Status GraphManager::PreRun(const GraphNodePtr &graph_node, const std::vector<GeTensor> &inputs,
  322. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  323. GE_CHECK_NOTNULL(graph_node);
  324. GE_CHECK_NOTNULL(graph_node->GetGraph());
  325. auto compute_graph = GraphUtils::GetComputeGraph(*graph_node->GetGraph());
  326. GE_CHECK_NOTNULL(compute_graph);
  327. GEEVENT("PreRun start, graph node size %zu, session id %lu, graph id %u, graph name %s",
  328. compute_graph->GetDirectNodesSize(), session_id, compute_graph->GetGraphID(),
  329. compute_graph->GetName().c_str());
  330. GE_DUMP(compute_graph, "PreRunBegin");
  331. GM_RUN_AND_DUMP("OptimizeGraphPrepare", graph_optimize_.OptimizeOriginalGraphForQuantize, compute_graph);
  332. GM_RUN_AND_DUMP("HandleSummaryOp", graph_optimize_.HandleSummaryOp, compute_graph);
  333. GM_RUN_AND_DUMP("Prepare", graph_preparer_.PrepareDynShape, graph_node->GetGraph(), inputs, compute_graph,
  334. session_id);
  335. GM_RUN_AND_DUMP("OptimizeOriginalGraph", graph_optimize_.OptimizeOriginalGraph, compute_graph);
  336. GM_RUN_AND_DUMP("PrepareRunningFormatRefiner", graph_preparer_.PrepareRunningFormatRefiner);
  337. GM_RUN_AND_DUMP("RefineRunningFormat", graph_optimize_.OptimizeOriginalGraphJudgeInsert, compute_graph);
  338. GE_RUN(GraphManager, graph_preparer_.RecordAIPPInfo, compute_graph);
  339. if (IsTailingOptimization()) {
  340. GM_RUN_AND_DUMP("OptimizeSwitchOp", graph_preparer_.SwitchOpOptimize, compute_graph);
  341. }
  342. GM_RUN_AND_DUMP("Optimize1", OptimizeStage1, compute_graph);
  343. GM_RUN_AND_DUMP("InferShape2", compute_graph->InferShapeInNeed);
  344. const char *unknown_shape_skip = std::getenv("EXPERIMENTAL_DYNAMIC_PARTITION");
  345. if (unknown_shape_skip != nullptr) {
  346. PassManager graph_pass;
  347. GE_CHK_STATUS_RET(graph_pass.AddPass("PreRun::CtrlEdgeTransferPass", new (std::nothrow) CtrlEdgeTransferPass))
  348. GE_CHK_STATUS_RET(graph_pass.Run(compute_graph));
  349. }
  350. GM_RUN_AND_DUMP("OptimizeSubgraph", OptimizeSubgraph, graph_node, compute_graph, session_id);
  351. GM_RUN_AND_DUMP("Optimize2", OptimizeStage2, compute_graph);
  352. GM_RUN_AND_DUMP("Build", Build, graph_node, compute_graph, ge_root_model, session_id);
  353. // when set incre build, save om model and var manager
  354. GeModelPtr ge_model = nullptr;
  355. auto save_ret = SaveCacheAfterBuild(graph_node->GetGraphId(), compute_graph, ge_model);
  356. if (save_ret != SUCCESS) {
  357. GELOGW("Fail to save cache.");
  358. }
  359. GEEVENT("[GEPERFTRACE] GE PreRun End");
  360. return SUCCESS;
  361. }
  362. #undef RUN_AND_DUMP
  363. Status GraphManager::StartForRunGraph(const GraphNodePtr &graph_node, const std::vector<GeTensor> &inputs,
  364. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  365. // it will not execute graph prreprocess, optimize, parition, build if the graph has built successful.
  366. Status ret = SUCCESS;
  367. if (IsGraphNeedBuild(graph_node)) {
  368. if (graph_node->GetBuildFlag()) {
  369. GELOGE(PARAM_INVALID,
  370. "The graph %u need to re-build, you should remove it from GE "
  371. "first, then AddGraph again and rebuild it.",
  372. graph_node->GetGraphId());
  373. return PARAM_INVALID;
  374. }
  375. GeModelPtr ge_model = nullptr;
  376. // check need incre build.
  377. ret = IncreBuild(graph_node, ge_model);
  378. if (ret != SUCCESS) {
  379. ret = PreRun(graph_node, inputs, ge_root_model, session_id);
  380. // release rts generate context
  381. RtContextUtil::GetInstance().DestroyrtContexts();
  382. if (ret != SUCCESS) {
  383. GELOGE(ret, "PreRun Failed.");
  384. return ret;
  385. }
  386. }
  387. if (!graph_node->IsAsync()) {
  388. ret = LoadGraph(ge_root_model, graph_node);
  389. } else {
  390. ret = LoadGraphAsync(ge_root_model, graph_node);
  391. }
  392. if (ret != SUCCESS) {
  393. GELOGE(ret, "LoadGraph Failed.");
  394. return ret;
  395. }
  396. graph_node->SetBuildFlag(true);
  397. var_acc_ctrl_.SetGraphBuildEnd(graph_node->GetGraphId());
  398. } else if (!graph_node->GetLoadFlag()) {
  399. GeRootModelPtr ge_root_model_ptr = graph_node->GetGeRootModel();
  400. if (!graph_node->IsAsync()) {
  401. ret = LoadGraph(ge_root_model_ptr, graph_node);
  402. } else {
  403. ret = LoadGraphAsync(ge_root_model_ptr, graph_node);
  404. }
  405. if (ret != SUCCESS) {
  406. GELOGE(ret, "LoadGraph Failed.");
  407. return ret;
  408. }
  409. }
  410. return ret;
  411. }
  412. Status GraphManager::LoadGraph(const GeRootModelPtr &ge_root_model, const GraphNodePtr &graph_node) {
  413. GELOGI("[LoadGraph] run_graph_flag[%d], graph_id[%u]", options_.run_graph_flag, graph_node->GetGraphId());
  414. if (options_.run_graph_flag && ge_root_model != nullptr) {
  415. // synchronization run graph with model
  416. std::shared_ptr<GraphModelListener> model_listener = GetModelListener();
  417. ModelIdInfo model_id_info;
  418. bool is_unknown_shape = false;
  419. GE_CHK_STATUS_RET(ge_root_model->CheckIsUnknownShape(is_unknown_shape));
  420. if (!is_unknown_shape) {
  421. if (getenv(kEnvGeuseStaticMemory) != nullptr) {
  422. GELOGI("[LoadGraph] GE_USE_STATIC_MEMORY is seted.");
  423. } else {
  424. auto root_graph = ge_root_model->GetRootGraph();
  425. GE_CHECK_NOTNULL(root_graph);
  426. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  427. GeModelPtr ge_model = name_to_model[root_graph->GetName()];
  428. GE_CHK_STATUS_RET(CheckAndReleaseMemory(ge_model, graph_node));
  429. }
  430. }
  431. GE_TIMESTAMP_START(LoadGraph);
  432. Status ret = GraphLoader::LoadModelOnline(model_id_info.model_id, ge_root_model, model_listener);
  433. GE_TIMESTAMP_END(LoadGraph, "GraphManager::LoadGraph");
  434. if (ret != SUCCESS) {
  435. GELOGE(ret, "[StartForRunGraph] LoadGraph Failed");
  436. graph_node->SetRunFlag(false);
  437. return ret;
  438. }
  439. graph_node->SetLoadFlag(true);
  440. ge_root_model->SetModelId(model_id_info.model_id);
  441. graph_node->SetGeRootModel(ge_root_model);
  442. }
  443. return SUCCESS;
  444. }
  445. Status GraphManager::LoadFromCache(const GraphNodePtr &graph_node, const ModelCacheHelperPtr &cache_helper,
  446. GeModelPtr &ge_model) {
  447. auto graph_id = graph_node->GetGraphId();
  448. auto ret = cache_helper->LoadOmModelFromCache(ge_model);
  449. if (ret != SUCCESS) {
  450. GELOGW("Fail to load om model from cache.");
  451. if (cache_helper->ClearCache(graph_id) != SUCCESS) {
  452. GELOGW("Fail to clear cache of graph %u.", graph_id);
  453. }
  454. return FAILED;
  455. }
  456. ret = cache_helper->RecoverVarManagerFromCache();
  457. if (ret != SUCCESS) {
  458. GELOGW("Fail to recover VarManager from cache.");
  459. if (cache_helper->ClearCache(graph_id) != SUCCESS) {
  460. GELOGW("Fail to clear cache of graph %u.", graph_id);
  461. }
  462. return FAILED;
  463. }
  464. ComputeGraphPtr compute_graph_in_model = GraphUtils::GetComputeGraph(ge_model->GetGraph());
  465. if (compute_graph_in_model == nullptr) {
  466. GELOGW("Error occurred when get compute graph from om, abandon.");
  467. return FAILED;
  468. } else {
  469. graph_node->SetComputeGraph(compute_graph_in_model);
  470. graph_node->SetGeModel(ge_model);
  471. GELOGI("Load model and graph form cache om file.");
  472. }
  473. return SUCCESS;
  474. }
  475. Status GraphManager::SaveCacheBeforeBuild(uint32_t graph_id, const ModelCacheHelperPtr &cache_helper) {
  476. auto ret = cache_helper->SaveCacheInfoToCache();
  477. if (ret != SUCCESS) {
  478. GELOGW("Fail to save cache info of graph[%d] to cache.", graph_id);
  479. return FAILED;
  480. }
  481. ret = cache_helper->SaveVarManagerToCache(true);
  482. if (ret != SUCCESS) {
  483. GELOGW("Fail to save var manager to cache.");
  484. cache_helper->ClearCache(graph_id);
  485. return FAILED;
  486. }
  487. GELOGI("Cache files have been saved.");
  488. return SUCCESS;
  489. }
  490. Status GraphManager::SaveCacheAfterBuild(uint32_t graph_id, ge::ComputeGraphPtr graph, GeModelPtr &ge_model) {
  491. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  492. if ((instance_ptr == nullptr) || !instance_ptr->InitFlag()) {
  493. GELOGW("GELib not initialized.");
  494. return FAILED;
  495. }
  496. if (instance_ptr->IsIncreBuild()) {
  497. auto iter = cache_helper_map_.find(graph_id);
  498. if (iter == cache_helper_map_.end()) {
  499. GELOGW("Can not find ModelCacheHelper of graph[%u]", graph_id);
  500. return FAILED;
  501. } else {
  502. ModelCacheHelperPtr cache_helper = iter->second;
  503. auto ret = cache_helper->RefreshComputeGraph(graph);
  504. if (ret != SUCCESS) {
  505. cache_helper->ClearCache(graph_id);
  506. GELOGW("Fail to refresh cache helper's compute graph");
  507. return FAILED;
  508. }
  509. ret = cache_helper->SaveVarManagerToCache(false);
  510. if (ret != SUCCESS) {
  511. cache_helper->ClearCache(graph_id);
  512. GELOGW("Fail to save VarManager to cache");
  513. return FAILED;
  514. }
  515. ret = cache_helper->SaveOmModelToCache(ge_model);
  516. if (ret != SUCCESS) {
  517. cache_helper->ClearCache(graph_id);
  518. GELOGW("Fail to save om model to cache");
  519. return FAILED;
  520. }
  521. }
  522. }
  523. return SUCCESS;
  524. }
  525. Status GraphManager::InnerRunGraph(GraphNodePtr &graph_node, const GraphId &graph_id,
  526. const std::vector<GeTensor> &inputs, std::vector<GeTensor> &outputs) {
  527. Status ret = graph_executor_.SetCondition(&sync_run_mutex_, &condition_, graph_run_listener_);
  528. if (ret != SUCCESS) {
  529. GELOGE(GE_GRAPH_RUNGRAPH_FAILED, "[RunGraph] set condition failed, graph_id = %u.", graph_id);
  530. graph_node->SetRunFlag(false);
  531. return GE_GRAPH_RUNGRAPH_FAILED;
  532. }
  533. if (GetTrainFlag()) {
  534. GE_CHK_STATUS_RET(graph_executor_.SetGraphContext(GetGraphContext()));
  535. graph_executor_.SetTrainFlag(options_.train_graph_flag);
  536. }
  537. ret = graph_executor_.ExecuteGraph(graph_id, graph_node->GetGeRootModel(), inputs, outputs);
  538. graph_node->SetRunFlag(false);
  539. if (ret != SUCCESS) {
  540. GELOGE(ret, "[RunGraph] execute graph failed, graph_id = %u.", graph_id);
  541. return ret;
  542. }
  543. return SUCCESS;
  544. }
  545. Status GraphManager::RunGraph(const GraphId &graph_id, const std::vector<GeTensor> &inputs,
  546. std::vector<GeTensor> &outputs, uint64_t session_id) {
  547. std::lock_guard<std::mutex> lock(run_mutex_);
  548. GELOGI("[RunGraph] start to run graph, graph_id = %u, is_train_graph: %d", graph_id, GetTrainFlag());
  549. if (inputs.empty()) {
  550. GELOGI("[RunGraph] initialize sub graph has no inputs");
  551. }
  552. // find graph
  553. GraphNodePtr graph_node = nullptr;
  554. Status ret = GetGraphNode(graph_id, graph_node);
  555. if (ret != SUCCESS) {
  556. GELOGE(ret, "[RunGraph] graph not exist, graph_id = %u.", graph_id);
  557. return ret;
  558. }
  559. if (graph_node == nullptr) {
  560. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] graph node is NULL, graph_id = %u.", graph_id);
  561. return GE_GRAPH_GRAPH_NODE_NULL;
  562. }
  563. if (graph_node->GetRunFlag()) {
  564. GELOGE(GE_GRAPH_ALREADY_RUNNING, "[RunGraph] graph already running, graph id = %u", graph_id);
  565. return GE_GRAPH_ALREADY_RUNNING;
  566. }
  567. // set graph's run flag
  568. graph_node->SetRunFlag(true);
  569. ComputeGraphPtr compute_graph_tmp = GraphUtils::GetComputeGraph(*(graph_node->GetGraph()));
  570. GE_IF_BOOL_EXEC(
  571. GetTrainFlag(),
  572. GE_IF_BOOL_EXEC(compute_graph_tmp == nullptr,
  573. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] compute_graph_tmp is NULL, graph id = %u.", graph_id);
  574. return GE_GRAPH_GRAPH_NODE_NULL;))
  575. // when set incre build, add cache helper map
  576. AddModelCacheHelperToMap(graph_id, session_id, compute_graph_tmp);
  577. if (options_.local_fmk_op_flag) {
  578. graph_optimize_.TranFrameOp(compute_graph_tmp);
  579. }
  580. GeRootModelPtr ge_root_model;
  581. ret = StartForRunGraph(graph_node, inputs, ge_root_model, session_id);
  582. if (ret != SUCCESS) {
  583. GELOGE(ret, "[RunGraph] StartForRunGraph failed!");
  584. graph_node->SetRunFlag(false);
  585. return ret;
  586. }
  587. // excute graph
  588. ret = InnerRunGraph(graph_node, graph_id, inputs, outputs);
  589. if (ret != SUCCESS) {
  590. return ret;
  591. }
  592. if (GetTrainFlag()) {
  593. if (compute_graph_tmp->IsSummaryGraph()) {
  594. ret = SummaryHandle(graph_id, outputs);
  595. if (ret != SUCCESS) {
  596. GELOGE(ret, "[RunGraph] SummaryHandle failed!");
  597. }
  598. }
  599. GeRootModelPtr root_model = graph_node->GetGeRootModel();
  600. if (root_model != nullptr) {
  601. GELOGI("Start CheckpointHandle.");
  602. auto checkPointGraph = root_model->GetRootGraph();
  603. if (IsCheckpointGraph(checkPointGraph)) {
  604. ret = CheckpointHandle(graph_id, checkPointGraph, outputs);
  605. if (ret != SUCCESS) {
  606. GELOGE(ret, "[RunGraph] CheckpointHandle failed!");
  607. }
  608. }
  609. }
  610. }
  611. GELOGI("[RunGraph] run graph success, graph_id = %u.", graph_id);
  612. return SUCCESS;
  613. }
  614. Status GraphManager::GenerateInfershapeGraph(GraphId &graph_id) {
  615. GELOGI("[DumpInfershapeJson] start to DumpInfershapeJson graph, graph_id=%u.", graph_id);
  616. // find graph
  617. GraphNodePtr graph_node = nullptr;
  618. Status ret = GetGraphNode(graph_id, graph_node);
  619. if (ret != SUCCESS) {
  620. GELOGE(ret, "[BuildGraph] graph not exist, graph_id = %u.", graph_id);
  621. return ret;
  622. }
  623. if (graph_node == nullptr) {
  624. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[BuildGraph] graph node is NULL, graphId = %u.", graph_id);
  625. return GE_GRAPH_GRAPH_NODE_NULL;
  626. }
  627. ret = graph_preparer_.GenerateInfershapeGraph(graph_node->GetGraph());
  628. if (ret != SUCCESS) {
  629. GELOGE(ret, "ATC dump infershape json failed");
  630. return ret;
  631. }
  632. GELOGI("[DumpInfershapeJson] Dump infershape json success, graph_id=%u.", graph_id);
  633. return ret;
  634. }
  635. Status GraphManager::BuildGraph(const GraphId &graph_id, const std::vector<GeTensor> &inputs,
  636. GeRootModelPtr &ge_root_model, uint64_t session_id, bool async) {
  637. GELOGI("[BuildGraph] start to build graph, graph_id=%u.", graph_id);
  638. if (inputs.empty()) {
  639. GELOGW("[BuildGraph] BuildGraph warning: empty GeTensor inputs");
  640. }
  641. // find graph
  642. GraphNodePtr graph_node = nullptr;
  643. Status ret = GetGraphNode(graph_id, graph_node);
  644. if (ret != SUCCESS) {
  645. GELOGE(ret, "[BuildGraph] graph not exist, graph_id = %u.", graph_id);
  646. return ret;
  647. }
  648. if (graph_node == nullptr) {
  649. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[BuildGraph] graph node is NULL, graphId = %u.", graph_id);
  650. return GE_GRAPH_GRAPH_NODE_NULL;
  651. }
  652. if (graph_node->GetRunFlag()) {
  653. GELOGE(GE_GRAPH_ALREADY_RUNNING, "[BuildGraph] graph already running, graph id = %u", graph_node->GetGraphId());
  654. return GE_GRAPH_ALREADY_RUNNING;
  655. }
  656. graph_node->SetAsync(async);
  657. // set graph's run flag
  658. graph_node->SetRunFlag(true);
  659. ret = StartForRunGraph(graph_node, inputs, ge_root_model, session_id);
  660. graph_node->SetRunFlag(false);
  661. if (ret != SUCCESS) {
  662. GELOGE(GE_GRAPH_PRERUN_FAILED, "[BuildGraph] StartForRunGraph failed!");
  663. return GE_GRAPH_PRERUN_FAILED;
  664. }
  665. GELOGI("[BuildGraph] build graph success, graph_id=%u.", graph_id);
  666. return ret;
  667. }
  668. ///
  669. /// @ingroup ge_graph
  670. /// @brief Save extra attribute to Model
  671. /// @param [in] model: Model attribues will save to.
  672. /// @param [in] type: type of OpDesc.
  673. /// @param [in] attrs: attributes of OpDesc.
  674. /// @param [in] inputs: inputs tensor.
  675. /// @param [in] outputs: outputs tensor.
  676. /// @return: Status
  677. ///
  678. Status GraphManager::SaveParams(ge::GeModel &model, const std::string &type, const std::map<string, GeAttrValue> &attrs,
  679. const std::vector<GeTensor> &inputs, const std::vector<GeTensor> &outputs) {
  680. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetStr(&model, "ATTR_MODEL_OP_TYPE", type), return FAILED, "Set Op[%s] type fail",
  681. type.c_str());
  682. for (const auto &it : attrs) {
  683. GE_CHK_BOOL_EXEC(model.SetAttr("ATTR_MODEL_" + it.first, it.second) == GRAPH_SUCCESS, return FAILED,
  684. "Set OpDesc attribute[%s] fail", it.first.c_str());
  685. }
  686. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListTensor(&model, "ATTR_MODEL_TENSOR_INPUTS", inputs), return FAILED,
  687. "Set Inputs tensor list fail");
  688. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListTensor(&model, "ATTR_MODEL_TENSOR_OUTPUTS", outputs), return FAILED,
  689. "Set Outputs tensor list fail");
  690. return SUCCESS;
  691. }
  692. void GraphManager::RemoveModelCacheHelper(const GraphId &graph_id) {
  693. auto iter = cache_helper_map_.find(graph_id);
  694. if (iter != cache_helper_map_.end()) {
  695. cache_helper_map_.erase(iter);
  696. } else {
  697. GELOGW("[GraphManager] cache helper does not exist, graph_id = %u", graph_id);
  698. }
  699. }
  700. bool GraphManager::CheckModelLoad(const GeRootModelPtr &ge_root_model, bool load_flag) {
  701. return ((ge_root_model != nullptr) && (ge_root_model->GetModelId() != INVALID_MODEL_ID) && load_flag);
  702. }
  703. Status GraphManager::RemoveGraph(const GraphId &graph_id) {
  704. auto it = graph_map_.find(graph_id);
  705. if (it == graph_map_.end()) {
  706. GELOGE(GE_GRAPH_GRAPH_NOT_EXIST, "[GraphManager] Id %u does not exists.", graph_id);
  707. return GE_GRAPH_GRAPH_NOT_EXIST;
  708. }
  709. GraphNodePtr graph_node = it->second;
  710. if ((graph_node == nullptr) || (graph_node->GetRunFlag())) {
  711. GELOGE(GE_GRAPH_GRAPH_IS_RUNNING, "[GraphManager] Id %u is running, can't be deleted.", graph_id);
  712. return GE_GRAPH_GRAPH_IS_RUNNING;
  713. }
  714. Status ret = SUCCESS;
  715. Status middle_ret;
  716. rtError_t rt_ret;
  717. const std::vector<SubGraphInfoPtr> &all_sub_graph = graph_node->GetAllSubGraph();
  718. for (size_t i = 0; i < all_sub_graph.size(); ++i) {
  719. // must free buffer firstly
  720. middle_ret = all_sub_graph[i]->FreeInOutBuffer();
  721. if (middle_ret != SUCCESS) {
  722. GELOGE(middle_ret, "[GraphManager] RemoveGraph free mem failed, graph_id=%u.", graph_id);
  723. ret = middle_ret;
  724. }
  725. if (all_sub_graph[i]->GeModelIsValid() && all_sub_graph[i]->GetModelIdInfo().model_id != INVALID_MODEL_ID) {
  726. // unload model
  727. GELOGI("UnloadModel via new ome.");
  728. rt_ret = rtSetDevice(GetContext().DeviceId());
  729. if (rt_ret != RT_ERROR_NONE) {
  730. GELOGE(RT_FAILED, "[GraphManager:] rtSetDevice failed, modelId=%u, graphId=%u.",
  731. all_sub_graph[i]->GetModelIdInfo().model_id, graph_id);
  732. ret = FAILED;
  733. continue;
  734. }
  735. middle_ret = GraphLoader::UnloadModel(all_sub_graph[i]->GetModelIdInfo().model_id);
  736. if (middle_ret != SUCCESS) {
  737. GELOGE(middle_ret, "[GraphManager:] unload model failed, modelId=%u, graph_id=%u.",
  738. all_sub_graph[i]->GetModelIdInfo().model_id, graph_id);
  739. ret = middle_ret;
  740. }
  741. rt_ret = rtDeviceReset(GetContext().DeviceId());
  742. if (rt_ret != RT_ERROR_NONE) {
  743. GELOGE(RT_FAILED, "[GraphManager:] unload model failed, modelId=%u, graphId=%u.",
  744. all_sub_graph[i]->GetModelIdInfo().model_id, graph_id);
  745. ret = FAILED;
  746. }
  747. }
  748. }
  749. var_acc_ctrl_.RemoveGraph(graph_id);
  750. graph_map_.erase(it);
  751. RemoveModelCacheHelper(graph_id);
  752. auto ge_root_model = graph_node->GetGeRootModel();
  753. if (CheckModelLoad(ge_root_model, graph_node->GetLoadFlag())) {
  754. GELOGI("Unload model %u.", ge_root_model->GetModelId());
  755. rt_ret = rtSetDevice(GetContext().DeviceId());
  756. if (rt_ret != RT_ERROR_NONE) {
  757. GELOGE(RT_FAILED, "[GraphManager:] rtSetDevice failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(),
  758. graph_id);
  759. return FAILED;
  760. }
  761. middle_ret = GraphLoader::UnloadModel(ge_root_model->GetModelId());
  762. if (middle_ret != SUCCESS) {
  763. GELOGE(middle_ret, "[GraphManager:] unload model failed, modelId=%u, graph_id=%u.", ge_root_model->GetModelId(),
  764. graph_id);
  765. ret = middle_ret;
  766. }
  767. rt_ret = rtDeviceReset(GetContext().DeviceId());
  768. if (rt_ret != RT_ERROR_NONE) {
  769. GELOGE(RT_FAILED, "[GraphManager:] rtDeviceReset failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(),
  770. graph_id);
  771. ret = FAILED;
  772. }
  773. }
  774. GE_CHK_STATUS_RET(ret, "[GraphManager:] Remove graph failed, graph_id=%u.", graph_id);
  775. GELOGI("[GraphManager] remove graph success, graph_id=%u.", graph_id);
  776. return SUCCESS;
  777. }
  778. Status GraphManager::ParseOptions(const std::map<std::string, std::string> &options) {
  779. Status ret;
  780. ParseOption(options, "ge.INPUT_NODES_SET_FP16", options_.input_nodes_set_fp16);
  781. // parse streams max parallel num
  782. ret = ParseOption(options, STREAM_MAX_PARALLEL_NUM, options_.stream_max_parallel_num);
  783. if (ret != SUCCESS) {
  784. GELOGE(GE_GRAPH_OPTIONS_INVALID,
  785. "parse Key:%s value failed, it must be same format as "
  786. "DNN_V100:2,DNN_HCCL:3",
  787. STREAM_MAX_PARALLEL_NUM.c_str());
  788. return GE_GRAPH_OPTIONS_INVALID;
  789. }
  790. // get stream num
  791. ret = ParseOption(options, STREAM_NUM, options_.stream_num);
  792. if ((ret != SUCCESS) || (options_.stream_num == 0)) {
  793. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.stream_num, its value %d is invalid, must be not equal zero.",
  794. options_.stream_num);
  795. return GE_GRAPH_OPTIONS_INVALID;
  796. }
  797. // get perf level, its value please see enum PerfLevel
  798. ret = ParseOption(options, PERF_LEVEL, options_.perf_level);
  799. if ((ret != SUCCESS) || IsPerfLevelInvalid(options_.perf_level)) {
  800. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.perfLevel, its value %d is invalid, must be enum PerfLevel type.",
  801. options_.perf_level);
  802. return GE_GRAPH_OPTIONS_INVALID;
  803. }
  804. // get encrypt mode
  805. ret = ParseOption(options, ENCRYPT_MODE, options_.encrypt_mode);
  806. if (ret != SUCCESS) {
  807. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.encryptMode value invalid.");
  808. return GE_GRAPH_OPTIONS_INVALID;
  809. }
  810. // get ek file
  811. ParseOption(options, EK_FILE, options_.ek_file);
  812. // get cert file
  813. ParseOption(options, CERT_FILE, options_.cert_file);
  814. // get hw key file
  815. ParseOption(options, HW_KEY_FILE, options_.hw_key_file);
  816. // get private file
  817. ParseOption(options, PRIVATE_KEY_FILE, options_.private_key_file);
  818. // get framework type, its value please see enum FrameworkType
  819. ret = ParseOption(options, FRAMEWORK_TYPE, options_.framework_type);
  820. if (ret != SUCCESS) {
  821. // print error log in ParseOption
  822. return GE_GRAPH_OPTIONS_INVALID;
  823. }
  824. // get calibration info file
  825. ParseOption(options, CALIBRATION_CONF_FILE, options_.calibration_conf_file);
  826. // get insert op info file
  827. ParseOption(options, INSERT_OP_FILE, options_.insert_op_file);
  828. // get output node name
  829. ParseOption(options, OUTPUT_NODE_NAME, options_.output_node_name);
  830. // get function bin path
  831. ParseOption(options, "ge.func_bin_path", options_.func_bin_path);
  832. // get core type
  833. ParseOption(options, CORE_TYPE, options_.core_type);
  834. // get weight compress flag
  835. ret = ParseOption(options, COMPRESS_FLAG, options_.compress_flag);
  836. if (ret != SUCCESS) {
  837. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.compressFlag value is invalid, must be 0 or 1.");
  838. return GE_GRAPH_OPTIONS_INVALID;
  839. }
  840. // ge.graphType.
  841. options_.run_graph_flag = true;
  842. ret = ParseOption(options, RUN_FLAG, options_.run_graph_flag);
  843. if (ret != SUCCESS) {
  844. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.runFlag value is invalid, must be 0 or 1.");
  845. return GE_GRAPH_OPTIONS_INVALID;
  846. }
  847. // ge.graphType
  848. ret = ParseTrainGraphFlag(options_.run_graph_flag, options_.train_graph_flag);
  849. if (ret != SUCCESS) {
  850. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.runFlag value is invalid");
  851. return GE_GRAPH_OPTIONS_INVALID;
  852. }
  853. // parse FmkOp
  854. options_.local_fmk_op_flag = false;
  855. ret = ParseOption(options, LOCAL_FMKOP_FLAG, options_.local_fmk_op_flag);
  856. if (ret != SUCCESS) {
  857. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.localFmkopFlag value is invalid, must be 0 or 1.");
  858. return GE_GRAPH_OPTIONS_INVALID;
  859. }
  860. options_.enable_print_op_pass = true;
  861. ret = ParseOption(options, ENABLE_PRINT_OP_PASS, options_.enable_print_op_pass);
  862. options_.is_single_op = false;
  863. ret = ParseOption(options, SINGLE_OP_FLAG, options_.is_single_op);
  864. GE_IF_BOOL_EXEC(ret != SUCCESS,
  865. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.enablePrintOpPass value is invalid, must be 0 or 1.");
  866. return GE_GRAPH_OPTIONS_INVALID);
  867. // parse hcom parallel
  868. options_.hcom_parallel = false;
  869. ret = ParseOption(options, HCOM_PARALLEL, options_.hcom_parallel);
  870. if (ret != SUCCESS) {
  871. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.hcomParallel value is invalid, must be 0 or 1.");
  872. return GE_GRAPH_OPTIONS_INVALID;
  873. }
  874. // net output node dataType
  875. ParseOption(options, OUTPUT_DATATYPE, options_.output_datatype);
  876. if (!options_.output_datatype.empty()) {
  877. domi::GetContext().output_type = options_.output_datatype;
  878. }
  879. // Set save_original_model flag (ge.save_original_model)
  880. ParseOption(options, SAVE_ORIGINAL_MODEL, options_.save_original_model);
  881. GELOGI("Set save original model flag %s", options_.save_original_model.c_str());
  882. // Original model file name
  883. ParseOption(options, ORIGINAL_MODEL_FILE, options_.original_model_file);
  884. return SUCCESS;
  885. }
  886. Status GraphManager::ParseTrainGraphFlag(bool &options, bool &option) {
  887. std::shared_ptr<GELib> ge_instance_ptr = ge::GELib::GetInstance();
  888. if (ge_instance_ptr == nullptr) {
  889. GELOGW("[Initialize] set train_graph_flag_ to 0 when GE is not initialized or finalized.");
  890. option = false;
  891. } else if (!ge_instance_ptr->isTrainMode()) {
  892. option = false;
  893. } else { // ge_instance_ptr->isTrainMode() is true
  894. if (!options) {
  895. GELOGE(GE_GRAPH_OPTIONS_INVALID,
  896. "Key:ge.runFlag, its value %d is invalid, it must be 1 when GElib::is_train_mode_ flag is 1", options);
  897. return GE_GRAPH_OPTIONS_INVALID;
  898. }
  899. option = true;
  900. }
  901. return SUCCESS;
  902. }
  903. bool GraphManager::IsPerfLevelInvalid(int32_t perf_level) {
  904. return ((perf_level != static_cast<int32_t>(GEN_TASK_WITHOUT_L2FUSION)) &&
  905. (perf_level != static_cast<int32_t>(GEN_TASK_WITHOUT_FUSION)) && (perf_level != -1));
  906. }
  907. void GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  908. std::string &option) {
  909. auto iter = options.find(key);
  910. if (iter != options.end()) {
  911. option = iter->second;
  912. }
  913. }
  914. Status GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  915. bool &option) {
  916. auto iter = options.find(key);
  917. if (iter != options.end()) {
  918. string flag = iter->second;
  919. if (flag == "0") {
  920. option = false;
  921. } else if (flag == "1") {
  922. option = true;
  923. } else {
  924. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:%s, its value %s is invalid, it must be 0 or 1.", key.c_str(),
  925. flag.c_str());
  926. return GE_GRAPH_OPTIONS_INVALID;
  927. }
  928. }
  929. return SUCCESS;
  930. }
  931. Status GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  932. int &option) {
  933. const int kDecimal = 10;
  934. char *ptr = nullptr;
  935. auto iter = options.find(key);
  936. if (iter != options.end()) {
  937. option = static_cast<int32_t>(std::strtol(iter->second.c_str(), &ptr, kDecimal));
  938. if (ptr != nullptr && *ptr != '\0') {
  939. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:%s, its value %s is invalid, must be int32_t type.", key.c_str(),
  940. iter->second.c_str());
  941. return GE_GRAPH_OPTIONS_INVALID;
  942. }
  943. }
  944. return SUCCESS;
  945. }
  946. void GraphManager::Trim(std::string &str) {
  947. if (!str.empty()) {
  948. auto it = str.find_first_not_of(" ");
  949. if (it != std::string::npos) {
  950. str.erase(0, it);
  951. }
  952. it = str.find_last_not_of(" ");
  953. if (it != std::string::npos) {
  954. str.erase(it + 1);
  955. }
  956. }
  957. }
  958. Status GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  959. std::map<std::string, int> &option) {
  960. auto iter = options.find(key);
  961. if (iter == options.end()) {
  962. return SUCCESS;
  963. }
  964. GELOGI("Start to parse %s", key.c_str());
  965. option.clear();
  966. std::string op_num = iter->second;
  967. // split string by ','
  968. std::vector<std::string> split;
  969. std::istringstream f(op_num);
  970. std::string str_tmp;
  971. while (getline(f, str_tmp, ',')) {
  972. split.push_back(str_tmp);
  973. }
  974. for (const std::string &engine_parallel : split) {
  975. // split engine and num by :
  976. size_t pos = engine_parallel.find(':');
  977. if (pos == string::npos) {
  978. GELOGE(GE_GRAPH_OPTIONS_INVALID,
  979. "engine and num must be connected by :, "
  980. "while your input is %s",
  981. engine_parallel.c_str());
  982. return GE_GRAPH_OPTIONS_INVALID;
  983. }
  984. std::string engine_name = engine_parallel.substr(0, pos);
  985. std::string parallel_num = engine_parallel.substr(pos + 1);
  986. Trim(engine_name);
  987. Trim(parallel_num);
  988. Status ret = CheckEngineName(engine_name, key, option);
  989. if (ret != SUCCESS) {
  990. GELOGE(GE_GRAPH_OPTIONS_INVALID, "check engine name : %s failed, ", engine_name.c_str());
  991. return GE_GRAPH_OPTIONS_INVALID;
  992. }
  993. int num = 0;
  994. ret = ParseParallelNum(parallel_num, key, num);
  995. if (ret != SUCCESS) {
  996. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parse parallel num failed");
  997. return GE_GRAPH_OPTIONS_INVALID;
  998. }
  999. option.insert(std::make_pair(engine_name, num));
  1000. }
  1001. GELOGI("Parse %s successfully", key.c_str());
  1002. return SUCCESS;
  1003. }
  1004. Status GraphManager::CheckEngineName(const std::string &engine_name, const std::string &key,
  1005. const std::map<std::string, int> &option) {
  1006. if (engine_name.empty()) {
  1007. GELOGE(GE_GRAPH_OPTIONS_INVALID, "engine name of %s is empty", key.c_str());
  1008. return GE_GRAPH_OPTIONS_INVALID;
  1009. }
  1010. // judge whether exist in engine list
  1011. if (!GELib::GetInstance()->DNNEngineManagerObj().IsEngineRegistered(engine_name)) {
  1012. GELOGW("engine : %s is not registered in %s", engine_name.c_str(), key.c_str());
  1013. }
  1014. auto it_stream_repeat = option.find(engine_name);
  1015. if (it_stream_repeat != option.end()) {
  1016. GELOGE(GE_GRAPH_OPTIONS_INVALID, "engine : %s of %s is repeated", engine_name.c_str(), key.c_str());
  1017. return GE_GRAPH_OPTIONS_INVALID;
  1018. }
  1019. return SUCCESS;
  1020. }
  1021. Status GraphManager::ParseParallelNum(const std::string &parallel_num, const std::string &key, int &num) {
  1022. if (parallel_num.empty()) {
  1023. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num of %s is empty", key.c_str());
  1024. return GE_GRAPH_OPTIONS_INVALID;
  1025. }
  1026. for (char c : parallel_num) {
  1027. if (!isdigit(c)) {
  1028. GELOGE(GE_GRAPH_OPTIONS_INVALID, "%s input is invalid ", key.c_str());
  1029. return GE_GRAPH_OPTIONS_INVALID;
  1030. }
  1031. }
  1032. try {
  1033. num = std::stoi(parallel_num);
  1034. } catch (std::invalid_argument &) {
  1035. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s is invalid argument", parallel_num.c_str(), key.c_str());
  1036. return GE_GRAPH_OPTIONS_INVALID;
  1037. } catch (std::out_of_range &) {
  1038. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s is out of range", parallel_num.c_str(), key.c_str());
  1039. return GE_GRAPH_OPTIONS_INVALID;
  1040. } catch (...) {
  1041. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s is invalid argument", parallel_num.c_str(), key.c_str());
  1042. return GE_GRAPH_OPTIONS_INVALID;
  1043. }
  1044. if (num < 1) {
  1045. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s must bigger than 0", parallel_num.c_str(), key.c_str());
  1046. return GE_GRAPH_OPTIONS_INVALID;
  1047. }
  1048. return SUCCESS;
  1049. }
  1050. Status GraphManager::GetGraphNode(const GraphId &graph_id, GraphNodePtr &out) {
  1051. auto iter = graph_map_.find(graph_id);
  1052. if (iter == graph_map_.end()) {
  1053. out = nullptr;
  1054. GELOGE(GE_GRAPH_GRAPH_NOT_EXIST, "[GraphManager] graph not exist, graph_id= %u.", graph_id);
  1055. return GE_GRAPH_GRAPH_NOT_EXIST;
  1056. }
  1057. out = iter->second;
  1058. return SUCCESS;
  1059. }
  1060. Status GraphManager::GetVariable(const std::string &name, Tensor &val) {
  1061. GeTensorPtr ge_tensor_ptr = TensorAdapter::AsGeTensorPtr(val);
  1062. GE_CHECK_NOTNULL(ge_tensor_ptr);
  1063. return GetGraphContext()->GetVariableTensor(name, *(ge_tensor_ptr.get()));
  1064. }
  1065. Status GraphManager::SummaryHandle(const GraphId &graph_id, std::vector<GeTensor> &outputs) {
  1066. std::vector<GeTensor> without_summary_outputs;
  1067. std::set<int> summary_output_index;
  1068. GELOGI("[GraphManager] SummaryHandle, outputsSize=%zu.", outputs.size());
  1069. const std::map<uint32_t, std::map<string, size_t>> &whole_summary_output_indexes =
  1070. graph_optimize_.GetSummaryOutputIndexes();
  1071. if (whole_summary_output_indexes.find(graph_id) == whole_summary_output_indexes.end()) {
  1072. GELOGE(FAILED, "No Summary graph found in map.");
  1073. return FAILED;
  1074. }
  1075. const std::map<string, size_t> &summary_output_indexes = whole_summary_output_indexes.at(graph_id);
  1076. GELOGI("[GraphManager] SummaryHandle, summaryOutputIndexesSize=%zu.", summary_output_indexes.size());
  1077. std::map<string, Tensor> summary_results;
  1078. for (auto iter = summary_output_indexes.begin(); iter != summary_output_indexes.end(); ++iter) {
  1079. GELOGI("[GraphManager] SummaryHandle, summaryName=%s, outputIndex=%zu.", iter->first.c_str(), iter->second);
  1080. summary_results.emplace(iter->first, TensorAdapter::AsTensor(outputs.at(iter->second)));
  1081. summary_output_index.emplace(iter->second);
  1082. }
  1083. // remove summary data from outputs
  1084. if (!summary_output_index.empty()) {
  1085. for (size_t j = 0; j < outputs.size(); ++j) {
  1086. if (summary_output_index.count(j) == 0) {
  1087. without_summary_outputs.emplace_back(outputs.at(j));
  1088. }
  1089. }
  1090. outputs.swap(without_summary_outputs);
  1091. GELOGI("[GraphManager] SummaryHandle, after swap outputsSize=%zu.", outputs.size());
  1092. }
  1093. if (!summary_results.empty()) {
  1094. return PushSummaryData2ME(graph_id, summary_results);
  1095. }
  1096. return SUCCESS;
  1097. }
  1098. Status GraphManager::CheckpointHandle(const GraphId &graph_id, const ComputeGraphPtr &compute_graph,
  1099. const std::vector<GeTensor> &outputs) {
  1100. GELOGI("[GraphManager] CheckpointHandle, outputsSize=%zu.", outputs.size());
  1101. std::vector<InputOutputDescInfo> outputs_desc = graph_executor_.GetOutputsDesc();
  1102. GELOGI("[GraphManager] CheckpointHandle, outputsDescSize=%zu.", outputs_desc.size());
  1103. std::map<string, Tensor> save_results;
  1104. NodePtr netoutput = nullptr;
  1105. for (const auto &node : compute_graph->GetAllNodes()) {
  1106. if (node->GetType() == kNetOutput) {
  1107. netoutput = node;
  1108. break;
  1109. }
  1110. }
  1111. if (netoutput == nullptr) {
  1112. GELOGE(FAILED, "Netoutput is null.");
  1113. return FAILED;
  1114. }
  1115. for (const auto &in : netoutput->GetAllInDataAnchors()) {
  1116. std::string desc_name;
  1117. auto out_anchor = in->GetPeerOutAnchor();
  1118. if (out_anchor == nullptr) {
  1119. GELOGE(FAILED, "out_anchor is null.");
  1120. return FAILED;
  1121. }
  1122. ge::NodePtr peer_node = out_anchor->GetOwnerNode();
  1123. // find the variable node in graph
  1124. while (peer_node != nullptr && peer_node->GetType() != kVariable) {
  1125. if (peer_node->GetAllInDataAnchors().size() != 1) {
  1126. GELOGE(FAILED, "More than one prior nodes of peer_node %s in checkpoint Graph.", peer_node->GetName().c_str());
  1127. return FAILED;
  1128. }
  1129. auto peer_node_in = peer_node->GetAllInDataAnchors().at(0);
  1130. auto peer_node_out_anchor = peer_node_in->GetPeerOutAnchor();
  1131. if (peer_node_out_anchor != nullptr) {
  1132. peer_node = peer_node_out_anchor->GetOwnerNode();
  1133. if (peer_node->GetType() == kVariable) {
  1134. break;
  1135. }
  1136. }
  1137. }
  1138. if (peer_node == nullptr) {
  1139. GELOGE(FAILED, "No variable op found in one branch, checkpoint graph illegal.");
  1140. return FAILED;
  1141. }
  1142. desc_name = peer_node->GetName();
  1143. GELOGI("[GraphManager] CheckpointHandle, descName=%s.", desc_name.c_str());
  1144. if (in->GetIdx() >= static_cast<int>(outputs.size())) {
  1145. GELOGE(FAILED, "variable index out of range.");
  1146. return FAILED;
  1147. }
  1148. save_results.emplace(desc_name, TensorAdapter::AsTensor(outputs.at(in->GetIdx())));
  1149. }
  1150. if (!save_results.empty()) {
  1151. return PushSaveData2ME(graph_id, save_results);
  1152. }
  1153. return SUCCESS;
  1154. }
  1155. Status GraphManager::RegisterCallBackFunc(
  1156. const std::string &key, const std::function<Status(uint32_t, const std::map<std::string, ge::Tensor> &)> &callback) {
  1157. GELOGI("[GraphManager] RegisterCallBackFunc, key=%s.", key.c_str());
  1158. me_callback_map_[key] = callback;
  1159. return SUCCESS;
  1160. }
  1161. Status GraphManager::PushSummaryData2ME(const GraphId &graph_id,
  1162. const std::map<std::string, ge::Tensor> &summary_data) {
  1163. GELOGI("[GraphManager] PushSummaryData2ME, dataSize=%zu.", summary_data.size());
  1164. auto itr = me_callback_map_.find(kSummary);
  1165. if (itr == me_callback_map_.end()) {
  1166. GELOGE(FAILED, "[GraphManager] PushSummaryData2ME failed, not found summary callback.");
  1167. return FAILED;
  1168. }
  1169. return itr->second(graph_id, summary_data);
  1170. }
  1171. Status GraphManager::PushSaveData2ME(const GraphId &graph_id, const std::map<std::string, ge::Tensor> &save_data) {
  1172. GELOGI("[GraphManager] PushSaveData2ME, dataSize=%zu.", save_data.size());
  1173. auto itr = me_callback_map_.find(kSave);
  1174. if (itr == me_callback_map_.end()) {
  1175. GELOGE(FAILED, "[GraphManager] PushSaveData2ME failed, not found checkpoint callback.");
  1176. return FAILED;
  1177. }
  1178. return itr->second(graph_id, save_data);
  1179. }
  1180. bool GraphManager::CheckNetOutputForCheckpointGraph(NodePtr &node) {
  1181. size_t in_data_anchor_size = node->GetAllInDataAnchors().size();
  1182. for (size_t i = 0; i < in_data_anchor_size; ++i) {
  1183. auto in = node->GetInDataAnchor(i);
  1184. if (in == nullptr) {
  1185. return false;
  1186. }
  1187. auto peerin = in->GetPeerOutAnchor();
  1188. GE_IF_BOOL_EXEC(peerin == nullptr, return false);
  1189. if (peerin->GetOwnerNode()->GetType() != kVariable && (!TransOpUtil::IsTransOp(peerin->GetOwnerNode()))) {
  1190. return false;
  1191. }
  1192. }
  1193. return true;
  1194. }
  1195. bool GraphManager::CheckVariableForCheckpointGraph(NodePtr &node) {
  1196. auto out = node->GetOutDataAnchor(0);
  1197. if (out == nullptr) {
  1198. GELOGE(GE_GRAPH_PARAM_NULLPTR, "out is nullptr.");
  1199. return false;
  1200. }
  1201. auto peer_out = out->GetPeerInDataAnchors();
  1202. for (size_t i = 0; i < peer_out.size(); ++i) {
  1203. if (peer_out.at(i)->GetOwnerNode()->GetType() != kNetOutput &&
  1204. (!TransOpUtil::IsTransOp(peer_out.at(i)->GetOwnerNode()))) {
  1205. return false;
  1206. }
  1207. }
  1208. return true;
  1209. }
  1210. bool GraphManager::CheckTransOpForCheckpointGraph(NodePtr &node) {
  1211. for (const auto &out_node : node->GetOutAllNodes()) {
  1212. if ((!TransOpUtil::IsTransOp(out_node)) && (out_node->GetType() != kNetOutput) && (out_node->GetType() != kSend)) {
  1213. return false;
  1214. }
  1215. }
  1216. for (const auto &in_node : node->GetInAllNodes()) {
  1217. if ((!TransOpUtil::IsTransOp(in_node)) && (in_node->GetType() != kVariable) && (in_node->GetType() != kRecv)) {
  1218. return false;
  1219. }
  1220. }
  1221. return true;
  1222. }
  1223. static inline bool CheckConstanOpForCheckpointGraph(NodePtr &node) { return node->GetOutDataNodes().empty(); }
  1224. bool GraphManager::IsCheckpointGraph(ComputeGraphPtr &compute_graph) {
  1225. if (compute_graph == nullptr) {
  1226. GELOGE(GE_GRAPH_PARAM_NULLPTR, "[IsCheckpointGraph] computeGraph is nullptr.");
  1227. return false;
  1228. }
  1229. for (auto &node : compute_graph->GetAllNodes()) {
  1230. OpDescPtr op = node->GetOpDesc();
  1231. GE_RT_FALSE_CHECK_NOTNULL(op);
  1232. if (op->GetType() == kNetOutput) {
  1233. if (!CheckNetOutputForCheckpointGraph(node)) {
  1234. return false;
  1235. }
  1236. } else if (op->GetType() == kVariable) {
  1237. if (!CheckVariableForCheckpointGraph(node)) {
  1238. return false;
  1239. }
  1240. } else if ((TransOpUtil::IsTransOp(node))) {
  1241. if (!CheckTransOpForCheckpointGraph(node)) {
  1242. return false;
  1243. }
  1244. } else if (op->GetType() == CONSTANTOP) {
  1245. if (!CheckConstanOpForCheckpointGraph(node)) {
  1246. return false;
  1247. }
  1248. } else if (op->GetType() != kSend && op->GetType() != kRecv) {
  1249. GELOGI("this node is not allow in checkpoint sub graph, node_type: %s, node_name: %s.", op->GetType().c_str(),
  1250. op->GetName().c_str());
  1251. return false;
  1252. }
  1253. }
  1254. GELOGI("current graph %s is checkpoint sub graph.", compute_graph->GetName().c_str());
  1255. return true;
  1256. }
  1257. bool GraphManager::IsBroadCastOpData(const ge::NodePtr &var_node) {
  1258. for (auto &out_anchor : var_node->GetAllOutDataAnchors()) {
  1259. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  1260. for (auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  1261. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1262. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  1263. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  1264. if (dst_node->GetType() == HCOMBROADCAST || dst_node->GetType() == HVDCALLBACKBROADCAST) {
  1265. return true;
  1266. }
  1267. }
  1268. }
  1269. return false;
  1270. }
  1271. void GraphManager::SetAttrForHcomBroadCastOp(ge::ComputeGraphPtr &compute_graph) {
  1272. // add variable attr for hccl broadcast,need to be removed after variable pass online
  1273. for (const ge::NodePtr &node : compute_graph->GetDirectNode()) {
  1274. if (node->GetOpDesc()->GetType() != ge::VARIABLE) {
  1275. continue;
  1276. }
  1277. if (IsBroadCastOpData(node)) {
  1278. AdjustBroadCastOpData(node);
  1279. }
  1280. if (IsAssignOpData(node)) {
  1281. AdjustAssignOpData(node);
  1282. }
  1283. }
  1284. }
  1285. void GraphManager::AdjustBroadCastOpData(const ge::NodePtr &var_node) {
  1286. if (!ge::AttrUtils::SetStr(var_node->GetOpDesc(), VAR_ATTR_VAR_IS_BROADCAST, "var_is_restore")) {
  1287. GELOGW("set var_is_restore failed");
  1288. }
  1289. }
  1290. bool GraphManager::IsAssignOpData(const ge::NodePtr &var_node) {
  1291. GELOGD("IsAssignOpData var_node %s", var_node->GetName().c_str());
  1292. std::map<std::string, std::set<int>> assign_ops = {{ASSIGN, {0}}};
  1293. ge::NodePtr assign_node = nullptr;
  1294. if (ConfirmUseOpAndIndexByNode(var_node, assign_ops, assign_node)) {
  1295. return true;
  1296. }
  1297. return false;
  1298. }
  1299. void GraphManager::AdjustAssignOpData(const ge::NodePtr &var_node) {
  1300. if (!ge::AttrUtils::SetStr(var_node->GetOpDesc(), VAR_ATTR_VAR_IS_RESTORE, "var_is_restore")) {
  1301. GELOGW("SetStr var_is_restore failed");
  1302. }
  1303. }
  1304. bool GraphManager::ConfirmUseOpAndIndexByAnchor(const ge::InDataAnchorPtr &in_anchor,
  1305. const map<string, std::set<int>> &confirm_ops, ge::NodePtr &use_node) {
  1306. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1307. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  1308. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  1309. ge::OpDescPtr dst_op_desc = dst_node->GetOpDesc();
  1310. GE_RT_FALSE_CHECK_NOTNULL(dst_op_desc);
  1311. const string &dst_type = dst_op_desc->GetType();
  1312. int input_index = in_anchor->GetIdx();
  1313. GELOGD("ConfirmUseOpAndIndex, var name %s, dst_type = %s, input index %d", dst_node->GetName().c_str(),
  1314. dst_type.c_str(), input_index);
  1315. if (confirm_ops.count(dst_type) > 0) {
  1316. if (confirm_ops.at(dst_type).count(input_index) > 0) {
  1317. use_node = dst_node;
  1318. return true;
  1319. }
  1320. }
  1321. return false;
  1322. }
  1323. bool GraphManager::ConfirmUseOpAndIndexByNode(const ge::NodePtr &var_node,
  1324. const map<string, std::set<int>> &confirm_ops, ge::NodePtr &use_node) {
  1325. GE_RT_FALSE_CHECK_NOTNULL(var_node);
  1326. for (auto &out_anchor : var_node->GetAllOutDataAnchors()) {
  1327. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  1328. for (auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  1329. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1330. if (ConfirmUseOpAndIndexByAnchor(in_anchor, confirm_ops, use_node)) {
  1331. return true;
  1332. }
  1333. }
  1334. }
  1335. return false;
  1336. }
  1337. Status GraphManager::RemoveIsolatedConstInThisGraph(ge::ComputeGraphPtr &compute_graph) {
  1338. for (ge::NodePtr &n : compute_graph->GetDirectNode()) {
  1339. if (n->GetOpDesc() == nullptr) {
  1340. continue;
  1341. }
  1342. if (n->GetOpDesc()->GetType() == CONSTANT || n->GetOpDesc()->GetType() == CONSTANTOP) {
  1343. // reset const type depend on train_flag
  1344. options_.train_graph_flag ? n->GetOpDesc()->SetType(CONSTANTOP) : n->GetOpDesc()->SetType(CONSTANT);
  1345. if (n->GetOutAllNodes().empty() && n->GetInAllNodes().empty()) {
  1346. // it is an isolated constant, just remove it
  1347. if (GraphUtils::RemoveJustNode(compute_graph, n) != GRAPH_SUCCESS) {
  1348. GELOGE(FAILED, "remove constant %s failed.", n->GetName().c_str());
  1349. return FAILED;
  1350. }
  1351. }
  1352. }
  1353. }
  1354. return SUCCESS;
  1355. }
  1356. Status GraphManager::RemoveIsolatedConst(ge::ComputeGraphPtr &compute_graph) {
  1357. GE_CHK_STATUS_RET(RemoveIsolatedConstInThisGraph(compute_graph));
  1358. for (auto &sub_graph : compute_graph->GetAllSubgraphs()) {
  1359. GE_CHK_STATUS_RET(RemoveIsolatedConstInThisGraph(sub_graph));
  1360. }
  1361. return SUCCESS;
  1362. }
  1363. Status GraphManager::NewOptimizeAfterMergeSubGraph(ge::ComputeGraphPtr &compute_graph) {
  1364. GELOGD("NewOptimizeAfterMergeSubGraph in");
  1365. GEPass ge_passes(compute_graph);
  1366. NamesToPass names_to_passes;
  1367. ConstantFoldingPass constant_folding_pass;
  1368. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1369. GE_TIMESTAMP_START(names_to_passes);
  1370. auto ret = ge_passes.Run(names_to_passes);
  1371. GE_TIMESTAMP_END(names_to_passes, "GraphManager::ge_passes");
  1372. if (ret != SUCCESS) {
  1373. GELOGE(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1374. return ret;
  1375. }
  1376. ret = RemoveIsolatedConst(compute_graph);
  1377. if (ret != SUCCESS) {
  1378. GELOGE(ret, "Remove isolated Constant failed, ret:%d.", ret);
  1379. return ret;
  1380. }
  1381. PassManager passes;
  1382. GE_CHK_STATUS_RET(passes.AddPass("MultiBatchPass", new (std::nothrow) MultiBatchPass));
  1383. GE_CHK_STATUS_RET(passes.AddPass("CompileNodesPass", new (std::nothrow) CompileNodesPass));
  1384. GE_CHK_STATUS_RET(passes.AddPass("AtomicAddrCleanPass", new (std::nothrow) AtomicAddrCleanPass));
  1385. GE_TIMESTAMP_START(passes);
  1386. ret = passes.Run(compute_graph);
  1387. GE_TIMESTAMP_END(passes, "GraphManager::passes");
  1388. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1389. GELOGE(ret, "Run passes optimize for OptimizeAfterMergeSubGraph failed");
  1390. return ret;
  1391. }
  1392. ret = compute_graph->TopologicalSorting();
  1393. if (ret != SUCCESS) {
  1394. GELOGE(ret, "Graph topological sort failed, ret:%d.", ret);
  1395. return ret;
  1396. }
  1397. return SUCCESS;
  1398. }
  1399. Status GraphManager::OptimizeStage1(ge::ComputeGraphPtr &compute_graph) {
  1400. string options = "default";
  1401. if (GetContext().GetOption("ge.exec.variable_acc", options) != SUCCESS) {
  1402. GELOGI("get ge.exec.variable_acc failed. set default value.");
  1403. }
  1404. PassManager after_merge_passes;
  1405. GE_CHK_STATUS_RET(
  1406. after_merge_passes.AddPass("OptimizeStage1_1::SwitchDataEdgesBypass", new (std::nothrow) SwitchDataEdgesBypass));
  1407. GE_CHK_STATUS_RET(
  1408. after_merge_passes.AddPass("OptimizeStage1_1::ConstantFuseSamePass", new (std::nothrow) ConstantFuseSamePass));
  1409. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::CommonSubexpressionEliminationPass",
  1410. new (std::nothrow) CommonSubexpressionEliminationPass));
  1411. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::PermutePass", new (std::nothrow) PermutePass))
  1412. /*
  1413. * The SameTransdataBreadthFusionPass should be called before VariableOpPass, because of the scene following:
  1414. * node3
  1415. * |
  1416. * transdata1 node2
  1417. * | |
  1418. * cast1 transdata2
  1419. * \ /
  1420. * var
  1421. * the node `transdata1` should be moved to the front of the ndoe `cast1`,
  1422. * to ensure that `transdata1` and `transdata2` can be fusion with `var`.
  1423. * But it is a temp solution, because the `SameTransdataBreadthFusionPass`
  1424. * can only move `TransData` but not `Cast` nodes.
  1425. * So if we exchange Cast and TransData, the fusion mechanism will fail.
  1426. */
  1427. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::SameTransdataBreadthFusionPass",
  1428. new (std::nothrow) SameTransdataBreadthFusionPass))
  1429. GE_IF_BOOL_EXEC(options == "default" || options == "1", GELOGI("turn on variable accelerator");
  1430. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::VariableOpPass",
  1431. new (std::nothrow) VariableOpPass(&var_acc_ctrl_))))
  1432. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::TransOpWithoutReshapeFusionPass",
  1433. new (std::nothrow) TransOpWithoutReshapeFusionPass))
  1434. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::TransOpBreadthFusionPass",
  1435. new (std::nothrow) TransOpBreadthFusionPass))
  1436. GE_TIMESTAMP_START(after_merge_passes);
  1437. auto ret = after_merge_passes.Run(compute_graph);
  1438. GE_TIMESTAMP_END(after_merge_passes, "GraphManager::OptimizeStage1_1");
  1439. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1440. GELOGE(ret, "Run passes when OptimizeStage1_1 failed, ret:%u.", ret);
  1441. return ret;
  1442. }
  1443. GraphUtils::DumpGEGraphToOnnx(*compute_graph, "OptimizeStage1_1");
  1444. NamesToPass names_to_passes;
  1445. TransOpNearbyAllreduceFusionPass trans_op_nearby_allreduce_fusion_pass;
  1446. ReshapeRemovePass reshape_remove_pass;
  1447. ConstantFoldingPass constant_folding_pass;
  1448. DimensionAdjustPass dimension_adjust_pass;
  1449. AddNPass addn_pass;
  1450. SwitchDeadBranchElimination switch_dead_branch_elimination;
  1451. SwitchLogicRemovePass switch_logic_remove_pass;
  1452. MergePass merge_pass;
  1453. IdentifyReferencePass identify_reference_pass;
  1454. CastRemovePass cast_remove_pass;
  1455. TransposeTransDataPass transpose_transdata_pass;
  1456. TransOpSymmetryEliminationPass symmetry_elimination_pass;
  1457. DimensionComputePass dimension_compute_pass;
  1458. names_to_passes.emplace_back("AddNPass", &addn_pass);
  1459. names_to_passes.emplace_back("SwitchDeadBranchElimination", &switch_dead_branch_elimination);
  1460. names_to_passes.emplace_back("SwitchLogicRemovePass", &switch_logic_remove_pass);
  1461. names_to_passes.emplace_back("MergePass", &merge_pass);
  1462. names_to_passes.emplace_back("IdentifyReferencePass", &identify_reference_pass);
  1463. names_to_passes.emplace_back("CastRemovePass", &cast_remove_pass);
  1464. names_to_passes.emplace_back("TransposeTransDataPass", &transpose_transdata_pass);
  1465. names_to_passes.emplace_back("TransOpSymmetryEliminationPass", &symmetry_elimination_pass);
  1466. names_to_passes.emplace_back("TransOpNearbyAllreduceFusionPass", &trans_op_nearby_allreduce_fusion_pass);
  1467. names_to_passes.emplace_back("ReshapeRemovePass", &reshape_remove_pass);
  1468. names_to_passes.emplace_back("DimensionComputePass", &dimension_compute_pass);
  1469. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1470. names_to_passes.emplace_back("DimensionAdjustPass", &dimension_adjust_pass);
  1471. GE_TIMESTAMP_START(names_to_passes);
  1472. ret = GEPass(compute_graph).Run(names_to_passes);
  1473. GE_TIMESTAMP_END(names_to_passes, "GraphManager::OptimizeStage1_2");
  1474. if (ret != SUCCESS) {
  1475. GELOGE(ret, "Run passes when OptimizeStage1_2 failed, ret:%u.", ret);
  1476. return ret;
  1477. }
  1478. GraphUtils::DumpGEGraphToOnnx(*compute_graph, "OptimizeStage1_2");
  1479. PassManager graph_pass;
  1480. // the prune pass should between SwtichPass and SwitchOpPass
  1481. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::PrunePass", new (std::nothrow) PrunePass))
  1482. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::NextIterationPass", new (std::nothrow) NextIterationPass))
  1483. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::ControlTriggerPass", new (std::nothrow) ControlTriggerPass))
  1484. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::SwitchOpPass", new (std::nothrow) SwitchOpPass))
  1485. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::IteratorOpPass", new (std::nothrow) IteratorOpPass))
  1486. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::VariableRefUselessControlOutDeletePass",
  1487. new (std::nothrow) VariableRefUselessControlOutDeletePass))
  1488. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::ReshapeRecoveryPass", new (std::nothrow) ReshapeRecoveryPass))
  1489. GE_TIMESTAMP_START(graph_pass);
  1490. ret = graph_pass.Run(compute_graph);
  1491. GE_TIMESTAMP_END(graph_pass, "GraphManager::OptimizeStage1_3");
  1492. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1493. GELOGE(ret, "Run passes when OptimizeStage1_3 failed, ret:%u.", ret);
  1494. return ret;
  1495. }
  1496. NamesToPass identity_remove_pass;
  1497. GE_TIMESTAMP_START(identity_remove_pass);
  1498. IdentityPass identity_force_pass(true); // after SwitchOpPass
  1499. identity_remove_pass.emplace_back("IdentityPass", &identity_force_pass);
  1500. ret = GEPass(compute_graph).Run(identity_remove_pass);
  1501. GE_TIMESTAMP_END(identity_remove_pass, "GraphPrepare::IdentityRemovePass");
  1502. if (ret != SUCCESS) {
  1503. GELOGE(ret, "Run identity remove pass for preprocess failed, ret:%u.", ret);
  1504. return ret;
  1505. }
  1506. return SUCCESS;
  1507. }
  1508. Status GraphManager::OptimizeStage2(ge::ComputeGraphPtr &compute_graph) {
  1509. GELOGI("Start optimize after merge sub graph.");
  1510. PassManager after_merge_passes;
  1511. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage2::AfterMergePasses::LinkGenMaskNodesPass",
  1512. new (std::nothrow)
  1513. LinkGenMaskNodesPass(options_.stream_max_parallel_num)));
  1514. GE_TIMESTAMP_START(after_merge_passes);
  1515. auto ret = after_merge_passes.Run(compute_graph);
  1516. GE_TIMESTAMP_END(after_merge_passes, "OptimizeStage2::AfterMergePasses");
  1517. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1518. GELOGE(ret, "Run passes after merge sub graph failed, ret:%d.", ret);
  1519. return ret;
  1520. }
  1521. SetAttrForHcomBroadCastOp(compute_graph);
  1522. NamesToPass names_to_passes;
  1523. ConstantFoldingPass constant_folding_pass;
  1524. ReshapeRemovePass reshape_remove_pass;
  1525. CondRemovePass condition_remove_pass;
  1526. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1527. names_to_passes.emplace_back("ReshapeRemovePass", &reshape_remove_pass);
  1528. names_to_passes.emplace_back("CondRemovePass", &condition_remove_pass);
  1529. GE_TIMESTAMP_START(names_to_passes);
  1530. ret = GEPass(compute_graph).Run(names_to_passes);
  1531. GE_TIMESTAMP_END(names_to_passes, "OptimizeStage2::MergedGraphNameToPasses");
  1532. if (ret != SUCCESS) {
  1533. GELOGE(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1534. return ret;
  1535. }
  1536. ret = RemoveIsolatedConst(compute_graph);
  1537. if (ret != SUCCESS) {
  1538. GELOGE(ret, "Remove isolated Constant failed, ret:%d.", ret);
  1539. return ret;
  1540. }
  1541. PassManager pass_for_control_attr_optimize;
  1542. if (options_.train_graph_flag) {
  1543. const char *unknown_shape_skip = std::getenv("EXPERIMENTAL_DYNAMIC_PARTITION");
  1544. if (unknown_shape_skip == nullptr) {
  1545. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::FlowCtrlPass",
  1546. new (std::nothrow) FlowCtrlPass))
  1547. }
  1548. }
  1549. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::MultiBatchPass",
  1550. new (std::nothrow) MultiBatchPass))
  1551. // the value of the attr is the original variable name the ref-variable ref from.
  1552. // The attr will be used when allocating memory,
  1553. // the node marked attr will be output to a variable instead of new-allocated memory.
  1554. // Therefore, ComputeGraph should not delete nodes after `VariableRefDeleteOpPass`
  1555. // to prevent unexpected deletion of nodes marked with attr
  1556. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::VariableRefDeleteOpPass",
  1557. new (std::nothrow) VariableRefDeleteOpPass))
  1558. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::CompileNodesPass",
  1559. new (std::nothrow) CompileNodesPass))
  1560. // When the input node to be cleared is after a `Data` node, the atomic-clean-node should not be inserted.
  1561. // So The ComputeGraph should not delete nodes after `AtomicAddrCleanPass`
  1562. // to prevent unexpected deletion of nodes after a `Data` node
  1563. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::AtomicAddrCleanPass",
  1564. new (std::nothrow) AtomicAddrCleanPass))
  1565. const char *unknown_shape_skip = std::getenv("EXPERIMENTAL_DYNAMIC_PARTITION");
  1566. if (unknown_shape_skip == nullptr) {
  1567. // SubgraphPass solves memory_assign_conflicts by insert MemcpyAsync node, which depends on multi attrs and
  1568. // graph-structure. So try not to add new pass after SubgraphPass.
  1569. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::SubgraphPass",
  1570. new (std::nothrow) SubgraphPass));
  1571. }
  1572. GE_TIMESTAMP_START(pass_for_control_attr_optimize);
  1573. ret = pass_for_control_attr_optimize.Run(compute_graph);
  1574. GE_TIMESTAMP_END(pass_for_control_attr_optimize, "OptimizeStage2::ControlAttrOptimize");
  1575. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1576. GELOGE(ret, "Run passes when optimize stage 2 failed");
  1577. return ret;
  1578. }
  1579. ChangeConstTypeWhenTraining(compute_graph);
  1580. ret = compute_graph->TopologicalSorting();
  1581. if (ret != SUCCESS) {
  1582. GELOGE(ret, "Graph topological sort failed, ret:%d.", ret);
  1583. return ret;
  1584. }
  1585. GELOGI("End optimize after merge sub graph.");
  1586. return SUCCESS;
  1587. }
  1588. void GraphManager::ChangeConstTypeWhenTraining(const ComputeGraphPtr &compute_graph) {
  1589. // The constant for train is CONSTANTOP, and is CONSTANT for inference. They will be unified in future.
  1590. if (options_.train_graph_flag) {
  1591. for (NodePtr &n : compute_graph->GetAllNodes()) {
  1592. // This can ensure that n is not a null pointer
  1593. if (n->GetOpDesc()->GetType() == CONSTANT) {
  1594. n->GetOpDesc()->SetType(CONSTANTOP);
  1595. }
  1596. }
  1597. }
  1598. }
  1599. Status GraphManager::OptimizeAfterMergeSubGraph(ge::ComputeGraphPtr &compute_graph) {
  1600. GELOGI("Start optimize after merge sub graph.");
  1601. GEPass ge_passes_for_shape(compute_graph);
  1602. NamesToPass names_to_passes_for_shape;
  1603. IdentifyReferencePass identify_reference_pass;
  1604. names_to_passes_for_shape.emplace_back("IdentifyReferencePass", &identify_reference_pass);
  1605. CastRemovePass cast_remove_pass;
  1606. names_to_passes_for_shape.emplace_back("CastRemovePass", &cast_remove_pass);
  1607. TransposeTransDataPass transpose_transdata_pass;
  1608. names_to_passes_for_shape.emplace_back("TransposeTransDataPass", &transpose_transdata_pass);
  1609. GE_TIMESTAMP_START(ge_passes_for_shape);
  1610. Status ret = ge_passes_for_shape.Run(names_to_passes_for_shape);
  1611. GE_TIMESTAMP_END(ge_passes_for_shape, "GraphManager::GePassesForShape");
  1612. GE_CHK_STATUS_RET(ret, "Run ge_passes_for_shape optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1613. string options = "default";
  1614. if (GetContext().GetOption("ge.exec.variable_acc", options) != SUCCESS) {
  1615. GELOGI("get ge.exec.variable_acc failed. set default value.");
  1616. }
  1617. PassManager after_merge_passes;
  1618. GE_CHK_STATUS_RET(after_merge_passes.AddPass("PermutePass", new (std::nothrow) PermutePass));
  1619. GE_IF_BOOL_EXEC(options == "default" || options == "1", GELOGI("turn on variable accelerator"); GE_CHK_STATUS_RET(
  1620. after_merge_passes.AddPass("VariableOpPass", new (std::nothrow) VariableOpPass(&var_acc_ctrl_))));
  1621. ret = after_merge_passes.Run(compute_graph);
  1622. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1623. GELOGE(ret, "Run passes after merge sub graph failed, ret:%d.", ret);
  1624. return ret;
  1625. }
  1626. // reshape remove + symmetry_elimination_pass to replace transop depth fusion pass
  1627. GEPass ge_passes_symmetry(compute_graph);
  1628. NamesToPass names_to_passes_for_symmetry;
  1629. ReshapeRemovePass reshape_remove_pass;
  1630. names_to_passes_for_symmetry.emplace_back("ReshapeRemovePass", &reshape_remove_pass);
  1631. TransOpSymmetryEliminationPass symmetry_elimination_pass;
  1632. names_to_passes_for_symmetry.emplace_back("TransOpSymmetryEliminationPass", &symmetry_elimination_pass);
  1633. ret = ge_passes_symmetry.Run(names_to_passes_for_symmetry);
  1634. GE_CHK_STATUS_RET(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1635. PassManager after_merge_fusion_passes;
  1636. GE_CHK_STATUS_RET(after_merge_fusion_passes.AddPass("TransOpWithoutReshapeFusionPass",
  1637. new (std::nothrow) TransOpWithoutReshapeFusionPass));
  1638. GE_CHK_STATUS_RET(
  1639. after_merge_fusion_passes.AddPass("TransOpBreadthFusionPass", new (std::nothrow) TransOpBreadthFusionPass));
  1640. GE_CHK_STATUS_RET(
  1641. after_merge_fusion_passes.AddPass("VariableRefDeleteOpPass", new (std::nothrow) VariableRefDeleteOpPass));
  1642. GE_CHK_STATUS_RET(after_merge_fusion_passes.AddPass("SameTransdataBreadthFusionPass",
  1643. new (std::nothrow) SameTransdataBreadthFusionPass));
  1644. GE_CHK_STATUS_RET(after_merge_fusion_passes.AddPass("AtomicAddrCleanPass", new (std::nothrow) AtomicAddrCleanPass));
  1645. GE_CHK_STATUS_RET(after_merge_fusion_passes.AddPass(
  1646. "LinkGenMaskNodesPass", new (std::nothrow) LinkGenMaskNodesPass(options_.stream_max_parallel_num)));
  1647. GE_TIMESTAMP_START(after_merge_fusion_passes);
  1648. ret = after_merge_fusion_passes.Run(compute_graph);
  1649. GE_TIMESTAMP_END(after_merge_fusion_passes, "GraphManager::AfterMergePasses");
  1650. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1651. GELOGE(ret, "Run passes after merge sub graph failed, ret:%d.", ret);
  1652. return ret;
  1653. }
  1654. // add variable attr for hccl broadcast,need to be removed after variable pass online
  1655. for (const ge::NodePtr &node : compute_graph->GetDirectNode()) {
  1656. if (node->GetOpDesc()->GetType() != VARIABLE) {
  1657. continue;
  1658. }
  1659. if (IsBroadCastOpData(node)) {
  1660. AdjustBroadCastOpData(node);
  1661. }
  1662. if (IsAssignOpData(node)) {
  1663. AdjustAssignOpData(node);
  1664. }
  1665. }
  1666. GEPass ge_passes(compute_graph);
  1667. NamesToPass names_to_passes;
  1668. TransOpNearbyAllreduceFusionPass trans_op_nearby_allreduce_fusion_pass;
  1669. names_to_passes.emplace_back("TransOpNearbyAllreduceFusionPass", &trans_op_nearby_allreduce_fusion_pass);
  1670. names_to_passes_for_shape.emplace_back("ReshapeRemovePass", &reshape_remove_pass);
  1671. ConstantFoldingPass constant_folding_pass;
  1672. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1673. DimensionAdjustPass dimension_adjust_pass;
  1674. names_to_passes.emplace_back("DimensionAdjustPass", &dimension_adjust_pass);
  1675. CondRemovePass condition_remove_pass;
  1676. names_to_passes.emplace_back("CondRemovePass", &condition_remove_pass);
  1677. GE_TIMESTAMP_START(names_to_passes);
  1678. ret = ge_passes.Run(names_to_passes);
  1679. GE_TIMESTAMP_END(names_to_passes, "GraphManager::MergedGraphNameToPasses");
  1680. GE_CHK_STATUS_RET(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1681. ret = RemoveIsolatedConst(compute_graph);
  1682. GE_CHK_STATUS_RET(ret, "Remove isolated Constant failed, ret:%d.", ret);
  1683. PassManager pass_for_optimize;
  1684. GE_CHK_STATUS_RET(pass_for_optimize.AddPass("SubgraphPass", new (std::nothrow) SubgraphPass));
  1685. GE_CHK_STATUS_RET(pass_for_optimize.AddPass("MultiBatchPass", new (std::nothrow) MultiBatchPass));
  1686. GE_CHK_STATUS_RET(pass_for_optimize.AddPass("CompileNodesPass", new (std::nothrow) CompileNodesPass));
  1687. GE_TIMESTAMP_START(pass_for_optimize);
  1688. ret = pass_for_optimize.Run(compute_graph);
  1689. GE_TIMESTAMP_END(pass_for_optimize, "GraphManager::OptimizePass");
  1690. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1691. GELOGE(ret, "Run optimize pass failed");
  1692. return ret;
  1693. }
  1694. ret = compute_graph->TopologicalSorting();
  1695. GE_CHK_STATUS_RET(ret, "Graph topological sort failed, ret:%d.", ret);
  1696. GELOGI("End optimize after merge sub graph.");
  1697. return SUCCESS;
  1698. }
  1699. Status GraphManager::LoadGraphAsync(const GeRootModelPtr &ge_root_model, const GraphNodePtr &graph_node) {
  1700. GELOGI("[LoadGraphAsync] run_graph_flag[%d], graph_id[%u]", options_.run_graph_flag, graph_node->GetGraphId());
  1701. if (options_.run_graph_flag && ge_root_model != nullptr) {
  1702. // synchronization run graph with model
  1703. ModelIdInfo model_id_info;
  1704. bool is_unknown_shape = false;
  1705. GE_CHK_STATUS_RET(ge_root_model->CheckIsUnknownShape(is_unknown_shape));
  1706. if (!is_unknown_shape) {
  1707. if (getenv(kEnvGeuseStaticMemory) != nullptr) {
  1708. GELOGI("[LoadGraphAsync] GE_USE_STATIC_MEMORY is seted.");
  1709. } else {
  1710. auto root_graph = ge_root_model->GetRootGraph();
  1711. GE_CHECK_NOTNULL(root_graph);
  1712. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  1713. GeModelPtr ge_model = name_to_model[root_graph->GetName()];
  1714. GE_CHK_STATUS_RET(CheckAndReleaseMemory(ge_model, graph_node));
  1715. }
  1716. }
  1717. GE_TIMESTAMP_START(LoadGraph);
  1718. GE_CHECK_NOTNULL(graph_node->graph_run_async_listener_);
  1719. Status ret =
  1720. GraphLoader::LoadModelOnline(model_id_info.model_id, ge_root_model, graph_node->graph_run_async_listener_);
  1721. GE_TIMESTAMP_END(LoadGraph, "GraphManager::LoadGraphAsync");
  1722. if (ret != SUCCESS) {
  1723. GELOGE(ret, "[LoadGraphAsync] LoadGraphAsync Failed");
  1724. graph_node->SetRunFlag(false);
  1725. return ret;
  1726. }
  1727. graph_node->SetLoadFlag(true);
  1728. ge_root_model->SetModelId(model_id_info.model_id);
  1729. graph_node->SetGeRootModel(ge_root_model);
  1730. }
  1731. return SUCCESS;
  1732. }
  1733. Status GraphManager::CheckAndReleaseMemory(const GeModelPtr &ge_model, const GraphNodePtr &graph_node) {
  1734. GELOGI("CheckAndReleaseMemory graph_id[%u]", graph_node->GetGraphId());
  1735. int64_t value = 0;
  1736. bool ret = ge::AttrUtils::GetInt(ge_model, ATTR_MODEL_MEMORY_SIZE, value);
  1737. int64_t memory_size = ret ? value : 0;
  1738. ret = ge::AttrUtils::GetInt(ge_model, ATTR_MODEL_WEIGHT_SIZE, value);
  1739. int64_t weight_size = ret ? value : 0;
  1740. ret = ge::AttrUtils::GetInt(ge_model, MODEL_ATTR_SESSION_ID, value);
  1741. uint64_t session_id = ret ? value : 0;
  1742. int64_t free_memory = 0;
  1743. Status result = GraphLoader::GetMemoryInfo(free_memory);
  1744. if (result != SUCCESS) {
  1745. return result;
  1746. }
  1747. GELOGI(
  1748. "CheckAndReleaseMemory Graph[%u] need memory_size[%ld], weight_size[%ld],"
  1749. " Device[%u] free_memory_size[%ld]",
  1750. graph_node->GetGraphId(), memory_size, weight_size, GetContext().DeviceId(), free_memory);
  1751. if (ge::CheckInt64AddOverflow(memory_size, weight_size) != SUCCESS) {
  1752. GELOGE(INTERNAL_ERROR, "The sum of Memory size and weight size exceeds INT64_MAX");
  1753. return INTERNAL_ERROR;
  1754. }
  1755. if (free_memory >= (memory_size + weight_size)) {
  1756. return SUCCESS;
  1757. }
  1758. rtError_t rt_ret;
  1759. for (auto &it : graph_map_) {
  1760. auto graph_id = it.second->GetGraphId();
  1761. auto model = it.second->GetGeRootModel();
  1762. if (model == nullptr) {
  1763. continue;
  1764. }
  1765. auto model_id = model->GetModelId();
  1766. // not loaded,no need unload
  1767. if (!it.second->GetLoadFlag()) {
  1768. GELOGI("CheckAndReleaseMemory graph[%u] has not been loaded.", graph_id);
  1769. continue;
  1770. }
  1771. uint64_t max_memory_size = 0;
  1772. result = GraphLoader::GetMaxUsedMemory(model_id, max_memory_size);
  1773. if (result != SUCCESS) {
  1774. continue;
  1775. }
  1776. GELOGI("CheckAndReleaseMemory try to UnloadGraph[%u], model[%u] which MaxUsedMemory[%lu].", graph_id, model_id,
  1777. max_memory_size);
  1778. rt_ret = rtSetDevice(GetContext().DeviceId());
  1779. if (rt_ret != RT_ERROR_NONE) {
  1780. GELOGE(RT_FAILED, "[GraphManager:] rtSetDevice failed, modelId=%u, graphId=%u.", model_id, graph_id);
  1781. continue;
  1782. }
  1783. result = GraphLoader::UnloadModel(model_id);
  1784. if (result != SUCCESS) {
  1785. GELOGW("[GraphManager:] unload model failed, modelId=%u, graphId=%u.", model_id, graph_id);
  1786. }
  1787. result = GraphLoader::DestroyAicpuKernel(session_id, model_id);
  1788. if (result != SUCCESS) {
  1789. GELOGW("[GraphManager:] destroy aicpu kernel failed when dynamic memory, modelId=%u, graphId=%u.", model_id,
  1790. graph_id);
  1791. }
  1792. rt_ret = rtDeviceReset(GetContext().DeviceId());
  1793. if (rt_ret != RT_ERROR_NONE) {
  1794. GELOGE(RT_FAILED, "[GraphManager:] rtDeviceReset failed, modelId=%u, graphId=%u.", model_id, graph_id);
  1795. continue;
  1796. }
  1797. it.second->SetLoadFlag(false);
  1798. GELOGI("CheckAndReleaseMemory UnloadGraph[%u], model[%u] success and set LoadFlag to false.", graph_id, model_id);
  1799. }
  1800. return SUCCESS;
  1801. }
  1802. Status GraphManager::ProcessSubGraphWithMultiThreads(GraphManager *graph_manager,
  1803. const SubGraphInfoPtr &sub_graph_info_ptr, uint64_t session_id,
  1804. const GEThreadLocalContext &ge_context) {
  1805. Status ret = SUCCESS;
  1806. GetThreadLocalContext() = ge_context;
  1807. if (sub_graph_info_ptr != nullptr && graph_manager != nullptr) {
  1808. ComputeGraphPtr compute_graph_tmp = sub_graph_info_ptr->GetSubGraph();
  1809. const std::string &engine_name = sub_graph_info_ptr->GetEngineName();
  1810. GELOGI("ProcessSubGraphWithMultiThreads start, graph name is %s, engine_name is %s, thread id is %lu",
  1811. compute_graph_tmp != nullptr ? compute_graph_tmp->GetName().c_str() : "", engine_name.c_str(),
  1812. pthread_self());
  1813. GE_DUMP(compute_graph_tmp, "OptimizeSubGraphBefore");
  1814. GE_CHECK_NOTNULL(compute_graph_tmp);
  1815. compute_graph_tmp->SetSessionID(session_id);
  1816. ret = graph_manager->graph_optimize_.OptimizeSubGraph(compute_graph_tmp, engine_name);
  1817. if (ret != SUCCESS) {
  1818. GELOGE(ret, "SubGraph optimize Failed %s", engine_name.c_str());
  1819. return ret;
  1820. } else {
  1821. GELOGI("SubGraph optimize success %s", engine_name.c_str());
  1822. }
  1823. GE_DUMP(compute_graph_tmp, "OptimizeSubGraphAfter");
  1824. sub_graph_info_ptr->SetSubGraph(compute_graph_tmp);
  1825. GELOGI("ProcessSubGraphWithMultiThreads end, graph name is %s, engine_name is %s, thread id is %lu",
  1826. compute_graph_tmp != nullptr ? compute_graph_tmp->GetName().c_str() : "", engine_name.c_str(),
  1827. pthread_self());
  1828. } else {
  1829. GELOGE(ret, "graph_manager or sub_graph_info_ptr is nullptr");
  1830. return FAILED;
  1831. }
  1832. return SUCCESS;
  1833. }
  1834. // run graph async on session
  1835. Status GraphManager::RunGraphAsync(const GraphId &graph_id, const std::vector<ge::InputTensorInfo> &inputs,
  1836. uint64_t session_id, RunAsyncCallback callback) {
  1837. GELOGI("[GraphManager] Start to run graph async, graph_id=%u, inputsSize=%zu.", graph_id, inputs.size());
  1838. bool ret = prerun_args_q_.Push(PreRunArgs({graph_id, inputs, session_id, GetThreadLocalContext(), callback}));
  1839. if (!ret) {
  1840. GELOGE(FAILED, "[GraphManager] Run graph async failed, graph_id=%u.", graph_id);
  1841. return FAILED;
  1842. }
  1843. GELOGI("[GraphManager] Run graph async success, graph_id=%u.", graph_id);
  1844. return SUCCESS;
  1845. }
  1846. void GraphManager::AddModelCacheHelperToMap(const GraphId &graph_id, uint64_t session_id,
  1847. ComputeGraphPtr &compute_graph) {
  1848. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  1849. if (instance_ptr != nullptr && instance_ptr->IsIncreBuild()) {
  1850. auto iter = cache_helper_map_.find(graph_id);
  1851. if (iter == cache_helper_map_.end()) {
  1852. ModelCacheHelperPtr cache_helper = MakeShared<ge::ModelCacheHelper>(session_id, graph_id, compute_graph);
  1853. if (cache_helper != nullptr) {
  1854. cache_helper_map_.emplace(std::make_pair(graph_id, cache_helper));
  1855. } else {
  1856. GELOGW("Cache helper make shared failed, graph_id = %u.", graph_id);
  1857. }
  1858. }
  1859. }
  1860. }
  1861. Status GraphManager::IncreBuild(const GraphNodePtr &graph_node, GeModelPtr &ge_model) {
  1862. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  1863. if (instance_ptr == nullptr || !instance_ptr->IsIncreBuild()) {
  1864. return FAILED;
  1865. }
  1866. const uint32_t graph_id = graph_node->GetGraphId();
  1867. auto iter = cache_helper_map_.find(graph_id);
  1868. if (iter == cache_helper_map_.end()) {
  1869. GELOGW("Can not find ModelCacheHelper of graph[%u]", graph_id);
  1870. return FAILED;
  1871. }
  1872. ModelCacheHelperPtr cache_helper = iter->second;
  1873. if (cache_helper->IsModelCacheHit()) {
  1874. GEEVENT("Model cache hit.");
  1875. Status ret = LoadFromCache(graph_node, cache_helper, ge_model);
  1876. if (ret == SUCCESS) {
  1877. return SUCCESS;
  1878. } else {
  1879. GELOGW("Error occurred when load from cache, abandon.");
  1880. }
  1881. } else {
  1882. GEEVENT("Model cache miss.");
  1883. }
  1884. if (SaveCacheBeforeBuild(graph_node->GetGraphId(), cache_helper) != SUCCESS) {
  1885. GELOGW("Error occurred when save cache.");
  1886. }
  1887. return FAILED;
  1888. }
  1889. void GraphManager::PreRunThread(GraphManager *graph_manager) {
  1890. if (prctl(PR_SET_NAME, ("GE_PreRun")) != 0) {
  1891. GELOGW("Set thread name failed.");
  1892. }
  1893. PreRunArgs args;
  1894. while (graph_manager->thread_run_flag_) {
  1895. bool pop_status = graph_manager->prerun_args_q_.Pop(args);
  1896. if (!pop_status) {
  1897. continue;
  1898. }
  1899. GetThreadLocalContext() = args.context;
  1900. GELOGI("A new loop start.");
  1901. std::vector<ge::GeTensor> ge_inputs;
  1902. for (auto const &input : args.input_tensor) {
  1903. std::vector<int64_t> input_dims;
  1904. std::transform(input.dims.begin(), input.dims.end(), std::back_inserter(input_dims),
  1905. [](int64_t x) -> int64_t { return x; });
  1906. GeShape input_shape(input_dims);
  1907. GeTensorDesc input_tensor_desc;
  1908. input_tensor_desc.SetShape(input_shape);
  1909. input_tensor_desc.SetDataType(static_cast<ge::DataType>(input.data_type));
  1910. ge_inputs.emplace_back(input_tensor_desc);
  1911. }
  1912. // find graph
  1913. GraphNodePtr graph_node = nullptr;
  1914. Status ret = graph_manager->GetGraphNode(args.graph_id, graph_node);
  1915. if (ret != SUCCESS) {
  1916. ReturnError(graph_manager, args.callback, GE_GRAPH_ALREADY_RUNNING,
  1917. "[RunGraph] graph not exist, graph_id=" + std::to_string(args.graph_id));
  1918. return;
  1919. }
  1920. graph_node->Lock();
  1921. if (graph_node->GetRunFlag()) {
  1922. ReturnError(graph_manager, args.callback, GE_GRAPH_GRAPH_NODE_NULL,
  1923. "[RunGraph] graph already running, graph id=" + std::to_string(args.graph_id));
  1924. graph_node->Unlock();
  1925. return;
  1926. }
  1927. // set graph's run flag
  1928. graph_node->SetRunFlag(true);
  1929. ComputeGraphPtr compute_graph_tmp = GraphUtils::GetComputeGraph(*(graph_node->GetGraph()));
  1930. if (graph_manager->GetTrainFlag()) {
  1931. if (compute_graph_tmp == nullptr) {
  1932. ReturnError(graph_manager, args.callback, GE_GRAPH_GRAPH_NODE_NULL,
  1933. "[RunGraph] compute_graph_tmp is NULL, graph id = %u.");
  1934. graph_node->Unlock();
  1935. return;
  1936. }
  1937. }
  1938. // when set incre build, save cache helper.
  1939. graph_manager->AddModelCacheHelperToMap(args.graph_id, args.session_id, compute_graph_tmp);
  1940. std::vector<GeModelPtr> ge_models;
  1941. if (graph_manager->options_.local_fmk_op_flag) {
  1942. graph_manager->graph_optimize_.TranFrameOp(compute_graph_tmp);
  1943. }
  1944. // it will not execute graph preprocess, optimize, parition, build if the graph has built successful.
  1945. GELOGI("Start for run graph async.");
  1946. GeRootModelPtr ge_root_model = nullptr;
  1947. if (graph_manager->IsGraphNeedBuild(graph_node)) {
  1948. if (graph_node->GetBuildFlag()) {
  1949. ReturnError(graph_manager, args.callback, PARAM_INVALID,
  1950. "The graph " + std::to_string(graph_node->GetGraphId()) +
  1951. " need to re-build, you should remove it"
  1952. " from GE first, then AddGraph again and rebuild it.");
  1953. graph_node->Unlock();
  1954. return;
  1955. }
  1956. // check need incre build.
  1957. GeModelPtr ge_model = nullptr;
  1958. if (graph_manager->IncreBuild(graph_node, ge_model) != SUCCESS) {
  1959. ret = graph_manager->PreRun(graph_node, ge_inputs, ge_root_model, args.session_id);
  1960. // release rts generate context
  1961. RtContextUtil::GetInstance().DestroyrtContexts();
  1962. if (ret != SUCCESS) {
  1963. graph_node->SetRunFlag(false);
  1964. ReturnError(graph_manager, args.callback, ret, "PreRun Failed, thread exit..");
  1965. graph_node->Unlock();
  1966. return;
  1967. }
  1968. }
  1969. graph_node->SetBuildFlag(true);
  1970. graph_manager->var_acc_ctrl_.SetGraphBuildEnd(graph_node->GetGraphId());
  1971. } else {
  1972. ge_root_model = graph_node->GetGeRootModel();
  1973. }
  1974. graph_manager->run_args_q_.Push(
  1975. RunArgs({graph_node, args.graph_id, args.input_tensor, ge_root_model, GetThreadLocalContext(), args.callback}));
  1976. GELOGI("Loop end.");
  1977. }
  1978. }
  1979. void GraphManager::RunThread(GraphManager *graph_manager) {
  1980. if (prctl(PR_SET_NAME, ("GE_Run")) != 0) {
  1981. GELOGW("Set thread name failed.");
  1982. }
  1983. RunArgs args;
  1984. while (graph_manager->thread_run_flag_) {
  1985. bool pop_status = graph_manager->run_args_q_.Pop(args);
  1986. if (!pop_status) {
  1987. continue;
  1988. }
  1989. GELOGI("A new loop start.");
  1990. GetThreadLocalContext() = args.context;
  1991. if (args.graph_node->graph_run_async_listener_ != nullptr) {
  1992. args.graph_node->graph_run_async_listener_->SetCallback(args.callback);
  1993. }
  1994. Status ret;
  1995. if (!args.graph_node->GetLoadFlag()) {
  1996. ret = graph_manager->LoadGraphAsync(args.ge_root_model, args.graph_node);
  1997. if (ret != SUCCESS || args.ge_root_model == nullptr) {
  1998. StopQueue(graph_manager);
  1999. ReturnError(graph_manager, args.callback, ret, "LoadGraphAsync failed, thread exit.");
  2000. args.graph_node->Unlock();
  2001. return;
  2002. }
  2003. args.graph_node->SetLoadFlag(true);
  2004. GELOGI("LoadGraph[%u], model[%u] success and set LoadFlag to true.", args.graph_node->GetGraphId(),
  2005. args.ge_root_model->GetModelId());
  2006. }
  2007. if (graph_manager->GetTrainFlag()) {
  2008. ret = graph_manager->graph_executor_.SetGraphContext(graph_manager->GetGraphContext());
  2009. if (ret != SUCCESS) {
  2010. GELOGW("[GraphManager] SetGraphContext failed, graph_id=%u.", args.graph_id);
  2011. }
  2012. graph_manager->graph_executor_.SetTrainFlag(graph_manager->options_.train_graph_flag);
  2013. }
  2014. ret = graph_manager->graph_executor_.ExecuteGraphAsync(args.graph_id, args.graph_node->GetGeRootModel(),
  2015. args.input_tensor);
  2016. args.graph_node->SetRunFlag(false);
  2017. args.graph_node->Unlock();
  2018. if (ret != SUCCESS) {
  2019. GELOGE(ret, "[GraphManager] Run graph async failed, graph_id=%u.", args.graph_id);
  2020. StopQueue(graph_manager);
  2021. return;
  2022. }
  2023. GELOGI("[GraphManager] Run graph async success, graph_id=%u.", args.graph_id);
  2024. }
  2025. }
  2026. void GraphManager::StopQueue(GraphManager *graph_manager) {
  2027. if (graph_manager == nullptr) {
  2028. return;
  2029. }
  2030. graph_manager->thread_run_flag_.store(false);
  2031. graph_manager->prerun_args_q_.Stop();
  2032. graph_manager->run_args_q_.Stop();
  2033. }
  2034. void GraphManager::ReturnError(GraphManager *graph_manager, RunAsyncCallback callback, Status ret, const string &log) {
  2035. if (graph_manager == nullptr) {
  2036. return;
  2037. }
  2038. GELOGE(ret, "%s.", log.c_str());
  2039. StopQueue(graph_manager);
  2040. std::vector<ge::OutputTensorInfo> outputs;
  2041. callback(ret, outputs);
  2042. }
  2043. bool GraphManager::IsGraphNeedRebuild(uint32_t graph_id) {
  2044. // find graph
  2045. GraphNodePtr graph_node = nullptr;
  2046. Status ret = GetGraphNode(graph_id, graph_node);
  2047. if (ret != SUCCESS) {
  2048. GELOGE(ret, "[RunGraph] graph not exist, graph_id=%u.", graph_id);
  2049. return true;
  2050. }
  2051. if (graph_node == nullptr) {
  2052. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] graph node is NULL, graphId=%u.", graph_id);
  2053. return true;
  2054. }
  2055. return IsGraphNeedBuild(graph_node);
  2056. }
  2057. bool GraphManager::IsGraphNeedBuild(const GraphNodePtr &graph_node) {
  2058. return !graph_node->GetBuildFlag() || var_acc_ctrl_.IsGraphNeedRebuild(graph_node->GetGraphId());
  2059. }
  2060. const map<std::string, std::string> *GraphManager::GetGraphOptions(uint32_t graph_id) {
  2061. GraphNodePtr graph_node = nullptr;
  2062. Status ret = GetGraphNode(graph_id, graph_node);
  2063. if (ret != SUCCESS) {
  2064. GELOGE(ret, "[RunGraph] graph not exist, graph_id=%u.", graph_id);
  2065. return nullptr;
  2066. }
  2067. if (!graph_node) {
  2068. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] graph node is NULL, graph_id=%u.", graph_id);
  2069. return nullptr;
  2070. }
  2071. return &(graph_node->GetOptions());
  2072. }
  2073. void GraphManager::SetOptionsRunGraphFlag(bool run_graph_flag) { options_.run_graph_flag = run_graph_flag; }
  2074. Status GraphManager::OptimizeSubgraph(const GraphNodePtr &graph_node, ComputeGraphPtr &compute_graph,
  2075. uint64_t session_id) {
  2076. // graph partition
  2077. // all sub graph list of root graph and sub graph
  2078. GE_TIMESTAMP_START(GraphPartitionDynamicShape);
  2079. DynamicShapePartitioner dynamic_shape_partitioner(compute_graph);
  2080. auto ret = dynamic_shape_partitioner.Partition();
  2081. if (ret != SUCCESS) {
  2082. GELOGE(ret, "Graph partition by dynamic shape Failed");
  2083. return ret;
  2084. }
  2085. bool dynamic_shape_partitioned = false;
  2086. if (!AttrUtils::GetBool(*compute_graph, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, dynamic_shape_partitioned)) {
  2087. GELOGE(FAILED, "failed get dynamic shape partitioned flag on partitioned graph.");
  2088. return FAILED;
  2089. }
  2090. GE_TIMESTAMP_END(GraphPartitionDynamicShape, "OptimizeSubgraph::GraphPartitionDynamicShape");
  2091. GE_TIMESTAMP_START(GraphPartition);
  2092. ret = graph_partitioner_.Partition(compute_graph, GraphPartitioner::kPartitioning);
  2093. if (ret != SUCCESS) {
  2094. GELOGE(ret, "Graph partition Failed");
  2095. return ret;
  2096. }
  2097. GE_TIMESTAMP_END(GraphPartition, "OptimizeSubgraph::Partition1");
  2098. GE_TIMESTAMP_START(SetSubgraph);
  2099. ret = SetSubgraph(session_id, compute_graph);
  2100. if (ret != SUCCESS) {
  2101. GELOGE(ret, "Graph set subgraph Failed");
  2102. return ret;
  2103. }
  2104. GE_TIMESTAMP_END(SetSubgraph, "OptimizeSubgraph::SetSubGraph");
  2105. ComputeGraphPtr merged_compute_graph = nullptr;
  2106. std::vector<ComputeGraphPtr> merged_sub_graph_list;
  2107. GE_TIMESTAMP_START(MergeSubgraph);
  2108. ret = MergeSubGraph(merged_compute_graph, compute_graph);
  2109. if (ret != SUCCESS) {
  2110. GELOGE(ret, "Merge SubGraph Failed");
  2111. return ret;
  2112. }
  2113. GE_CHECK_NOTNULL(merged_compute_graph);
  2114. merged_compute_graph->SetSessionID(session_id);
  2115. merged_compute_graph->SetGraphID(graph_node->GetGraphId());
  2116. merged_compute_graph->SetNeedIteration(compute_graph->GetNeedIteration());
  2117. for (auto &sub_graph : merged_compute_graph->GetAllSubgraphs()) {
  2118. sub_graph->SetSessionID(session_id);
  2119. sub_graph->SetGraphID(graph_node->GetGraphId());
  2120. }
  2121. GE_TIMESTAMP_END(MergeSubgraph, "OptimizeSubgraph::MergeSubGraph");
  2122. GE_DUMP(merged_compute_graph, "mergedComputeGraph");
  2123. compute_graph = merged_compute_graph;
  2124. if (!AttrUtils::SetBool(*compute_graph, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, dynamic_shape_partitioned)) {
  2125. GELOGE(FAILED, "failed set dynamic shape partitioned flag on partitioned graph.");
  2126. return FAILED;
  2127. }
  2128. return SUCCESS;
  2129. }
  2130. Status GraphManager::Build(const GraphNodePtr &graph_node, ComputeGraphPtr &compute_graph,
  2131. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  2132. // build
  2133. if (compute_graph != nullptr) {
  2134. std::string graph_name = compute_graph->GetName();
  2135. graph_name.append("_");
  2136. graph_name.append(std::to_string(graph_node->GetGraphId()));
  2137. compute_graph->SetName(graph_name);
  2138. }
  2139. std::vector<SubGraphInfoPtr> sub_graph_list;
  2140. auto ret = graph_builder_.Build(compute_graph, sub_graph_list, ge_root_model, session_id);
  2141. if (ret != SUCCESS) {
  2142. GELOGE(ret, "SubGraph build Failed.");
  2143. return ret;
  2144. }
  2145. bool is_always_dump = false;
  2146. PropertiesManager &properties_manager = PropertiesManager::Instance();
  2147. if (!properties_manager.GetDumpOutputPath().empty()) {
  2148. is_always_dump = true;
  2149. }
  2150. GraphUtils::DumpGEGraph(compute_graph, "Build", is_always_dump);
  2151. GraphUtils::DumpGEGraphToOnnx(*compute_graph, "Build");
  2152. graph_node->SetGeRootModel(ge_root_model);
  2153. return SUCCESS;
  2154. }
  2155. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示