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 123 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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989
  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 "analyzer/analyzer.h"
  34. #include "graph/common/ge_call_wrapper.h"
  35. #include "graph/common/local_context.h"
  36. #include "graph/common/transop_util.h"
  37. #include "graph/debug/ge_attr_define.h"
  38. #include "graph/ge_context.h"
  39. #include "graph/ge_global_options.h"
  40. #include "graph/ge_local_context.h"
  41. #include "graph/manager/graph_mem_allocator.h"
  42. #include "graph/manager/util/rt_context_util.h"
  43. #include "graph/partition/dynamic_shape_partition.h"
  44. #include "graph/passes/enter_pass.h"
  45. #include "graph/partition/stage_partition.h"
  46. #include "graph/passes/addn_pass.h"
  47. #include "graph/passes/bitcast_pass.h"
  48. #include "graph/passes/atomic_addr_clean_pass.h"
  49. #include "graph/passes/attach_stream_label_pass.h"
  50. #include "graph/passes/cast_remove_pass.h"
  51. #include "graph/passes/common_subexpression_elimination_pass.h"
  52. #include "graph/passes/compile_nodes_pass.h"
  53. #include "graph/passes/cond_remove_pass.h"
  54. #include "graph/passes/constant_folding_pass.h"
  55. #include "graph/passes/constant_fuse_same_pass.h"
  56. #include "graph/passes/control_trigger_pass.h"
  57. #include "graph/passes/ctrl_edge_transfer_pass.h"
  58. #include "graph/passes/dimension_adjust_pass.h"
  59. #include "graph/passes/dimension_compute_pass.h"
  60. #include "graph/passes/flow_ctrl_pass.h"
  61. #include "graph/passes/hccl_group_pass.h"
  62. #include "graph/passes/hccl_memcpy_pass.h"
  63. #include "graph/passes/identity_pass.h"
  64. #include "graph/passes/input_output_connection_identify_pass.h"
  65. #include "graph/passes/iterator_op_pass.h"
  66. #include "graph/passes/link_gen_mask_nodes_pass.h"
  67. #include "graph/passes/mark_graph_unknown_status_pass.h"
  68. #include "graph/passes/merge_pass.h"
  69. #include "graph/passes/merge_input_memcpy_pass.h"
  70. #include "graph/passes/merge_to_stream_merge_pass.h"
  71. #include "graph/passes/multi_batch_pass.h"
  72. #include "graph/passes/next_iteration_pass.h"
  73. #include "graph/passes/permute_pass.h"
  74. #include "graph/passes/prune_pass.h"
  75. #include "graph/passes/ref_identity_delete_op_pass.h"
  76. #include "graph/passes/replace_with_empty_const_pass.h"
  77. #include "graph/passes/reshape_recovery_pass.h"
  78. #include "graph/passes/reshape_remove_pass.h"
  79. #include "graph/passes/same_transdata_breadth_fusion_pass.h"
  80. #include "graph/passes/subgraph_pass.h"
  81. #include "graph/passes/switch_data_edges_bypass.h"
  82. #include "graph/passes/switch_dead_branch_elimination.h"
  83. #include "graph/passes/switch_logic_remove_pass.h"
  84. #include "graph/passes/switch_to_stream_switch_pass.h"
  85. #include "graph/passes/transop_breadth_fusion_pass.h"
  86. #include "graph/passes/transop_depth_fusion_pass.h"
  87. #include "graph/passes/transop_nearby_allreduce_fusion_pass.h"
  88. #include "graph/passes/transop_symmetry_elimination_pass.h"
  89. #include "graph/passes/transop_without_reshape_fusion_pass.h"
  90. #include "graph/passes/transpose_transdata_pass.h"
  91. #include "graph/passes/variable_op_pass.h"
  92. #include "graph/passes/variable_prepare_op_pass.h"
  93. #include "graph/passes/variable_ref_delete_op_pass.h"
  94. #include "graph/passes/variable_ref_useless_control_out_delete_pass.h"
  95. #include "graph/passes/end_of_sequence_add_control_pass.h"
  96. #include "graph/passes/subexpression_migration_pass.h"
  97. #include "graph/passes/subgraph_const_migration_pass.h"
  98. #include "graph/passes/unused_args_clean_pass.h"
  99. #include "graph/passes/global_step_insert_pass.h"
  100. #include "graph/utils/tensor_adapter.h"
  101. #include "graph/utils/type_utils.h"
  102. #include "graph/graph_util.h"
  103. #include "graph/types.h"
  104. #include "inc/pass_manager.h"
  105. #include "init/gelib.h"
  106. namespace {
  107. const char *const kSummary = "Summary";
  108. const char *const kSave = "Save";
  109. const char *const kNetOutput = "NetOutput";
  110. const char *const kVariable = "Variable";
  111. const char *const kSend = "Send";
  112. const char *const kRecv = "Recv";
  113. const char *const kCheckPointForGetVar = "CheckPointGraphForGetVar";
  114. const char *const kCheckPointGraph = "checkpoint_graph";
  115. const char *const kVectorEngine = "VectorEngine";
  116. const char *const kAIcoreEngine = "AIcoreEngine";
  117. const char *const kOffOptimize = "off_optimize";
  118. bool IsTailingOptimization() {
  119. string is_tailing_optimization_option;
  120. auto ret = ge::GetContext().GetOption(ge::OPTION_EXEC_ENABLE_TAILING_OPTIMIZATION, is_tailing_optimization_option);
  121. if (ret == ge::GRAPH_SUCCESS) {
  122. GELOGI("Option ge.exec.isTailingOptimization is %s", is_tailing_optimization_option.c_str());
  123. // "1" means it's True from frontend option
  124. return is_tailing_optimization_option == "1";
  125. }
  126. GELOGW("OPTION_EXEC_ENABLE_TAILING_OPTIMIZATION not set, use BFSTopologicalSorting by default.");
  127. return false;
  128. }
  129. } // namespace
  130. namespace ge {
  131. GraphManager::GraphManager()
  132. : thread_run_flag_(false),
  133. graph_run_listener_(nullptr),
  134. init_flag_(false) {
  135. }
  136. Status GraphManager::Initialize(const std::map<string, string> &options) {
  137. if (init_flag_) {
  138. GELOGW("[Initialize] GraphManager already initialized.");
  139. return SUCCESS;
  140. }
  141. // malloc
  142. graph_run_listener_ = MakeShared<GraphModelListener>(sync_run_mutex_, condition_);
  143. if (graph_run_listener_ == nullptr) {
  144. GELOGE(MEMALLOC_FAILED, "Make shared failed");
  145. return MEMALLOC_FAILED;
  146. }
  147. // graph context
  148. graph_context_ = MakeShared<GraphContext>();
  149. if (graph_context_ == nullptr) {
  150. GELOGE(MEMALLOC_FAILED, "Make shared failed.");
  151. return MEMALLOC_FAILED;
  152. }
  153. // parse option parameters
  154. Status ret = ParseOptions(options);
  155. if (ret != SUCCESS) {
  156. GELOGE(ret, "[Initialize] parse options failed.");
  157. return ret;
  158. }
  159. ret = graph_context_->Initialize(options);
  160. if (ret != SUCCESS) {
  161. GELOGE(ret, "[Initialize] GraphContext initialize failed.");
  162. return ret;
  163. }
  164. graph_map_.clear();
  165. cache_helper_map_.clear();
  166. init_flag_ = true;
  167. thread_run_flag_ = true;
  168. prerun_thread_ = std::thread(GraphManager::PreRunThread, this);
  169. run_thread_ = std::thread(GraphManager::RunThread, this);
  170. return SUCCESS;
  171. }
  172. Status GraphManager::Finalize() {
  173. if (!init_flag_) {
  174. GELOGW("GraphManager has not been initialized.");
  175. return SUCCESS;
  176. }
  177. if (graph_executor_.FreeExecuteMemory() != SUCCESS) {
  178. GELOGW("Graph executor FreeExecuteMemory failed, resources may not be released correctly.");
  179. }
  180. StopQueue(this);
  181. if (prerun_thread_.joinable()) {
  182. prerun_thread_.join();
  183. }
  184. if (run_thread_.joinable()) {
  185. run_thread_.join();
  186. }
  187. // check graph whether running or not
  188. Status unload_model_ret = SUCCESS;
  189. Status ret;
  190. rtError_t rt_ret;
  191. for (auto iter = graph_map_.begin(); iter != graph_map_.end(); ++iter) {
  192. GraphNodePtr graph_node = iter->second;
  193. if (graph_node->GetRunFlag()) {
  194. GELOGW("[GraphManager] finalize failed, graphId=%u.", iter->first);
  195. unload_model_ret = GE_GRAPH_GRAPH_IS_RUNNING;
  196. continue;
  197. }
  198. // unload model
  199. auto ge_root_model = graph_node->GetGeRootModel();
  200. if (ge_root_model != nullptr && ge_root_model->GetModelId() != INVALID_MODEL_ID && graph_node->GetLoadFlag()) {
  201. rt_ret = rtSetDevice(GetContext().DeviceId());
  202. if (rt_ret != RT_ERROR_NONE) {
  203. GELOGW("[GraphManager] rtSetDevice failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(), iter->first);
  204. unload_model_ret = FAILED;
  205. continue;
  206. }
  207. ret = GraphLoader::UnloadModel(ge_root_model->GetModelId());
  208. if (ret != SUCCESS) {
  209. GELOGW("[GraphManager] unload model failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(), iter->first);
  210. unload_model_ret = ret;
  211. }
  212. rt_ret = rtDeviceReset(GetContext().DeviceId());
  213. if (rt_ret != RT_ERROR_NONE) {
  214. GELOGW("[GraphManager] rtDeviceReset failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(),
  215. iter->first);
  216. unload_model_ret = FAILED;
  217. continue;
  218. }
  219. }
  220. // clear analyzer saved info(graph level)
  221. auto compute_graph = GraphUtils::GetComputeGraph(*graph_node->GetGraph());
  222. GE_CHECK_NOTNULL(compute_graph);
  223. auto session_id = compute_graph->GetSessionID();
  224. auto graph_id = compute_graph->GetGraphID();
  225. Analyzer::GetInstance()->DestroyGraphJsonObject(session_id, graph_id);
  226. }
  227. graph_map_.clear();
  228. cache_helper_map_.clear();
  229. // graph context
  230. if (graph_context_ != nullptr) {
  231. Status ret_final = graph_context_->Finalize();
  232. if (ret_final != SUCCESS) {
  233. GELOGE(ret_final, "[GraphManager] graph context Finalize failed!");
  234. unload_model_ret = ret_final;
  235. }
  236. }
  237. init_flag_ = false;
  238. return unload_model_ret;
  239. }
  240. Status GraphManager::AddGraph(const GraphId &graph_id, const Graph &graph,
  241. const std::map<std::string, std::string> &options,
  242. const OmgContext &omg_context) {
  243. if (HasGraphNode(graph_id)) {
  244. GELOGE(GE_GRAPH_GRAPH_ALREADY_EXIST, "[GraphManager] graph exists, graph_id = %u.", graph_id);
  245. return GE_GRAPH_GRAPH_ALREADY_EXIST;
  246. }
  247. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  248. if (compute_graph != nullptr) {
  249. compute_graph->SetGraphID(graph_id);
  250. bool graph_has_been_added = false;
  251. if (AttrUtils::GetBool(*compute_graph, ATTR_NAME_GRAPH_HAS_BEEN_ADDED, graph_has_been_added)
  252. && graph_has_been_added) {
  253. GELOGE(GE_GRAPH_GRAPH_ALREADY_EXIST,
  254. "[GraphManager] same graph object can not be added again, graph_id = %u.", graph_id);
  255. return GE_GRAPH_GRAPH_ALREADY_EXIST;
  256. }
  257. (void)AttrUtils::SetBool(*compute_graph, ATTR_NAME_GRAPH_HAS_BEEN_ADDED, true);
  258. } else {
  259. GELOGE(FAILED, "compute graph is null");
  260. return FAILED;
  261. }
  262. std::string session_graph_id;
  263. if (!AttrUtils::GetStr(*compute_graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id) || session_graph_id.empty()) {
  264. session_graph_id = "-1_" + to_string(graph_id);
  265. if (!AttrUtils::SetStr(*compute_graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id)) {
  266. GELOGW("Set attribute of compute graph failed.");
  267. }
  268. for (auto &subgraph : compute_graph->GetAllSubgraphs()) {
  269. (void)AttrUtils::SetStr(*subgraph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id);
  270. }
  271. GELOGW("Get graph session_graph_id attr failed, set session id to default value: [0]");
  272. }
  273. GraphNodePtr graph_node = MakeShared<ge::GraphNode>(graph_id);
  274. if (graph_node == nullptr) {
  275. GELOGE(FAILED, "GraphNode make shared failed");
  276. return FAILED;
  277. }
  278. std::shared_ptr<Graph> graph_ptr = MakeShared<ge::Graph>(graph);
  279. if (graph_ptr == nullptr) {
  280. GELOGE(FAILED, "GraphPtr make shared failed");
  281. return FAILED;
  282. }
  283. graph_node->SetGraph(graph_ptr);
  284. graph_node->SetOptions(options);
  285. AddGraphNode(graph_id, graph_node);
  286. AddLocalOmgContext(graph_id, omg_context);
  287. if (!options_.output_datatype.empty()) {
  288. GetLocalOmgContext().output_type = options_.output_datatype;
  289. }
  290. CompilerStages &stages = GetCompilerStages(graph_id);
  291. stages.preparer.SetOptions(options_);
  292. Status status = stages.optimizer.SetOptions(options_);
  293. if (status != SUCCESS) {
  294. GELOGE(status, "Graph optimizer set options failed.");
  295. return status;
  296. }
  297. stages.builder.SetOptions(options_);
  298. var_acc_ctrl_.AddGraph(graph_id, compute_graph);
  299. GELOGI("[GraphManager] add graph success, graph_id = %u.", graph_id);
  300. return SUCCESS;
  301. }
  302. Status GraphManager::MergeSubGraph(ComputeGraphPtr &compute_graph, const ge::ComputeGraphPtr &original_compute_graph,
  303. GraphId root_graph_id) {
  304. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  305. GraphPartitioner &partitioner = GetCompilerStages(root_graph_id).partitioner;
  306. if (instance_ptr != nullptr && instance_ptr->InitFlag()) {
  307. Status ret = partitioner.MergeAfterSubGraphOptimization(compute_graph, original_compute_graph);
  308. if (ret != SUCCESS) {
  309. GELOGE(ret, "merge end and placeholder after subGraph optimization failed.");
  310. return FAILED;
  311. }
  312. Status ret_topo = compute_graph->TopologicalSorting();
  313. if (ret_topo != SUCCESS) {
  314. GELOGE(ret_topo, "[GraphManager]: TopologicalSorting the merged graph failed.");
  315. return ret_topo;
  316. }
  317. } else {
  318. auto subgraph_list = partitioner.GetSubGraphMap();
  319. if (subgraph_list.find(original_compute_graph) != subgraph_list.end() &&
  320. !subgraph_list[original_compute_graph].empty() && subgraph_list[original_compute_graph][0] != nullptr) {
  321. compute_graph = subgraph_list[original_compute_graph][0]->GetSubGraph();
  322. }
  323. }
  324. return SUCCESS;
  325. }
  326. Status GraphManager::CopySubGraphAndMarkFusion(const ComputeGraphPtr &compute_graph,
  327. Graph2SubGraphInfoList &sub_graph_map,
  328. std::unordered_map<std::string, ComputeGraphPtr> &copy_graphs) {
  329. GE_CHECK_NOTNULL(compute_graph);
  330. vector<ComputeGraphPtr> old_compute_graphs;
  331. const auto &root_subgraph_list = sub_graph_map[compute_graph];
  332. for (const auto &subgraph : root_subgraph_list) {
  333. old_compute_graphs.emplace_back(subgraph->GetSubGraph());
  334. }
  335. for (const auto &function_graph : compute_graph->GetAllSubgraphs()) {
  336. const auto &subgraph_list = sub_graph_map[function_graph];
  337. for (const auto &subgraph : subgraph_list) {
  338. old_compute_graphs.emplace_back(subgraph->GetSubGraph());
  339. }
  340. }
  341. for (const auto &old_compute_graph : old_compute_graphs) {
  342. std::vector<NodePtr> input_nodes;
  343. std::vector<NodePtr> output_nodes;
  344. ComputeGraphPtr new_compute_graph = GraphUtils::CloneGraph(old_compute_graph, "", input_nodes, output_nodes);
  345. if (new_compute_graph == nullptr) {
  346. GELOGE(INTERNAL_ERROR, "Clone graph failed.");
  347. return INTERNAL_ERROR;
  348. }
  349. copy_graphs.emplace(old_compute_graph->GetName(), new_compute_graph);
  350. if (!AttrUtils::SetBool(old_compute_graph, ATTR_NAME_NEED_LX_FUSION, true)) {
  351. GELOGE(INTERNAL_ERROR, "Set attr lx_fusion to graph failed.");
  352. return INTERNAL_ERROR;
  353. }
  354. }
  355. GELOGI("Copy %zu graphs successfully.", copy_graphs.size());
  356. return SUCCESS;
  357. }
  358. Status GraphManager::OptimizeSubGraphWithMultiThreads(ComputeGraphPtr compute_graph,
  359. Graph2SubGraphInfoList &sub_graph_map,
  360. uint64_t session_id) {
  361. GE_CHECK_NOTNULL(compute_graph);
  362. // use default 16 multi thread
  363. const uint32_t thread_num = 16;
  364. ThreadPool executor(thread_num);
  365. std::vector<std::future<Status>> vector_future;
  366. const auto &root_subgraph_list = sub_graph_map[compute_graph];
  367. std::string op_compile_strategy;
  368. (void)AttrUtils::GetStr(compute_graph, ATTR_NAME_OP_COMPILE_STRATEGY, op_compile_strategy);
  369. GELOGI("OptimizeSubGraphWithMultiThreads Process op_compile_strategy:%s", op_compile_strategy.c_str());
  370. for (const auto &subgraph : root_subgraph_list) {
  371. if (!op_compile_strategy.empty()) {
  372. (void) AttrUtils::SetStr(subgraph->GetSubGraph(), ATTR_NAME_OP_COMPILE_STRATEGY, op_compile_strategy);
  373. }
  374. std::future<Status> f = executor.commit(GraphManager::ProcessSubGraphWithMultiThreads, this,
  375. compute_graph->GetGraphID(), subgraph, session_id, GetThreadLocalContext());
  376. if (!f.valid()) {
  377. GELOGE(FAILED, "Future is invalid");
  378. return FAILED;
  379. }
  380. vector_future.emplace_back(std::move(f));
  381. }
  382. for (auto &function_graph : compute_graph->GetAllSubgraphs()) {
  383. auto subgraph_list = sub_graph_map[function_graph];
  384. for (const auto &subgraph : subgraph_list) {
  385. if (!op_compile_strategy.empty()) {
  386. (void) AttrUtils::SetStr(subgraph->GetSubGraph(), ATTR_NAME_OP_COMPILE_STRATEGY, op_compile_strategy);
  387. }
  388. std::future<Status> f = executor.commit(GraphManager::ProcessSubGraphWithMultiThreads, this,
  389. compute_graph->GetGraphID(), subgraph, session_id,
  390. GetThreadLocalContext());
  391. if (!f.valid()) {
  392. GELOGE(FAILED, "Future is invalid");
  393. return FAILED;
  394. }
  395. vector_future.emplace_back(std::move(f));
  396. }
  397. }
  398. GELOGI("All sub graph num is %zu", vector_future.size());
  399. for (size_t i = 0; i < vector_future.size(); ++i) {
  400. Status ret_status = vector_future[i].get();
  401. if (ret_status != SUCCESS) {
  402. GELOGE(ret_status, "subgraph %zu optimize failed", i);
  403. return ret_status;
  404. }
  405. }
  406. return SUCCESS;
  407. }
  408. bool GraphManager::CheckAllFusionOptimizeSuccess(const ComputeGraphPtr &compute_graph,
  409. Graph2SubGraphInfoList &sub_graph_map) {
  410. if (compute_graph == nullptr) {
  411. GELOGE(PARAM_INVALID, "Input param compute_graph is nullptr.");
  412. return false;
  413. }
  414. /// 1. FE will set attr optimize_group with true(false) while lx fusion is success(fail);
  415. /// 2. FE will not set attr optimize_group while fe.ini set l2fusion enable false;
  416. /// 3. Other engine will not set attr optimize_group.
  417. const auto &root_subgraph_list = sub_graph_map[compute_graph];
  418. for (const auto &subgraph : root_subgraph_list) {
  419. bool optimize_group = true;
  420. (void) AttrUtils::GetBool(subgraph->GetSubGraph(), ATTR_NAME_OPTIMIZE_GROUP, optimize_group);
  421. if (!optimize_group) {
  422. GELOGW("Run lx optimize for subgraph:%s failed.", subgraph->GetSubGraph()->GetName().c_str());
  423. return false;
  424. }
  425. }
  426. for (auto &function_graph : compute_graph->GetAllSubgraphs()) {
  427. const auto &subgraph_list = sub_graph_map[function_graph];
  428. for (const auto &subgraph : subgraph_list) {
  429. bool optimize_group = true;
  430. (void) AttrUtils::GetBool(subgraph->GetSubGraph(), ATTR_NAME_OPTIMIZE_GROUP, optimize_group);
  431. if (!optimize_group) {
  432. GELOGW("Run lx optimize for subgraph:%s failed.", subgraph->GetSubGraph()->GetName().c_str());
  433. return false;
  434. }
  435. }
  436. }
  437. GELOGI("All subgraph are optimized successfully, no need to reuse buffer optimize.");
  438. return true;
  439. }
  440. Status GraphManager::ReplaceSubgraphWithOriGraph(const ComputeGraphPtr &compute_graph,
  441. Graph2SubGraphInfoList &sub_graph_map,
  442. std::unordered_map<std::string, ComputeGraphPtr> &copy_graphs) {
  443. GE_CHECK_NOTNULL(compute_graph);
  444. const auto &root_subgraph_list = sub_graph_map[compute_graph];
  445. for (const auto &subgraph : root_subgraph_list) {
  446. auto iter = copy_graphs.find(subgraph->GetSubGraph()->GetName());
  447. if (iter == copy_graphs.end()) {
  448. GELOGE(FAILED, "Can not find subgraph:%s in copy graphs.", subgraph->GetSubGraph()->GetName().c_str());
  449. return FAILED;
  450. }
  451. subgraph->SetSubGraph(iter->second);
  452. }
  453. for (auto &function_graph : compute_graph->GetAllSubgraphs()) {
  454. const auto &subgraph_list = sub_graph_map[function_graph];
  455. for (const auto &subgraph : subgraph_list) {
  456. auto iter = copy_graphs.find(subgraph->GetSubGraph()->GetName());
  457. if (iter == copy_graphs.end()) {
  458. GELOGE(FAILED, "Can not find subgraph:%s in copy graphs.", subgraph->GetSubGraph()->GetName().c_str());
  459. return FAILED;
  460. }
  461. subgraph->SetSubGraph(iter->second);
  462. }
  463. }
  464. GELOGI("All subgraphs are successfully replaced.");
  465. return SUCCESS;
  466. }
  467. Status GraphManager::SetSubgraph(uint64_t session_id, ComputeGraphPtr compute_graph, GraphPartitioner &partitioner) {
  468. GE_CHECK_NOTNULL(compute_graph);
  469. auto sub_graph_map = partitioner.GetSubGraphMap();
  470. std::string buffer_optimize;
  471. graphStatus graph_status = ge::GetContext().GetOption(BUFFER_OPTIMIZE, buffer_optimize);
  472. bool need_lx_fusion = (graph_status == GRAPH_SUCCESS) && (buffer_optimize != kOffOptimize);
  473. if (options_.build_mode.empty() && need_lx_fusion) {
  474. GELOGI("Enter normal mode with buffer_optimize:%s.", buffer_optimize.c_str());
  475. /// 1. Copy subgraph for buffer optimize while lx fusion failed.
  476. /// 2. Set graph with attr "lx_fusion" for fusion optimize.
  477. std::unordered_map<std::string, ComputeGraphPtr> copy_graphs;
  478. GE_TIMESTAMP_START(CopySubGraphAndMarkFusion);
  479. Status ret = CopySubGraphAndMarkFusion(compute_graph, sub_graph_map, copy_graphs);
  480. GE_TIMESTAMP_EVENT_END(CopySubGraphAndMarkFusion, "SetSubgraph:CopySubGraphAndMarkFusion");
  481. if (ret != SUCCESS) {
  482. GELOGE(ret, "CopySubGraphAndMarkFusion failed.");
  483. return ret;
  484. }
  485. // Multiply optimize subgraph with lx fusion
  486. ret = OptimizeSubGraphWithMultiThreads(compute_graph, sub_graph_map, session_id);
  487. if (ret != SUCCESS) {
  488. GELOGE(ret, "Multiply optimize subgraph with lx fusion failed.");
  489. return ret;
  490. }
  491. // Check whether all subgraph lx fusion success
  492. GE_TIMESTAMP_START(CheckAllFusionOptimizeSuccess);
  493. if (CheckAllFusionOptimizeSuccess(compute_graph, sub_graph_map)) {
  494. GE_TIMESTAMP_EVENT_END(CheckAllFusionOptimizeSuccess, "SetSubgraph:CheckAllFusionOptimizeSuccess");
  495. return SUCCESS;
  496. }
  497. // Replace subgraph with original graph for lx buffer
  498. ret = ReplaceSubgraphWithOriGraph(compute_graph, sub_graph_map, copy_graphs);
  499. if (ret != SUCCESS) {
  500. GELOGE(ret, "Replace subgraph with original graph failed.");
  501. return ret;
  502. }
  503. // Multiply optimize subgraph with lx buffer
  504. ret = OptimizeSubGraphWithMultiThreads(compute_graph, sub_graph_map, session_id);
  505. if (ret != SUCCESS) {
  506. GELOGE(ret, "Multiply optimize subgraph with lx buffer failed.");
  507. return ret;
  508. }
  509. } else {
  510. /// Multiply optimize subgraph:
  511. /// 1. run lx buffer while build_mode is normal and buffer_optimize is empty or "off_optimize";
  512. /// 2. run lx fusion or buffer according build_mode and build_step in fe.
  513. GELOGI("Directly optimize subgraph with build mode:%s, and step:%s, buffer_optimize:%s.",
  514. options_.build_mode.c_str(),
  515. options_.build_step.c_str(),
  516. buffer_optimize.c_str());
  517. Status ret = OptimizeSubGraphWithMultiThreads(compute_graph, sub_graph_map, session_id);
  518. if (ret != SUCCESS) {
  519. GELOGE(ret, "Multiply optimize subgraph with lx buffer");
  520. return ret;
  521. }
  522. }
  523. return SUCCESS;
  524. }
  525. #define GM_RUN_AND_DUMP_PERF(name, func, ...) \
  526. do { \
  527. GE_RUN_PERF(GraphManager, func, __VA_ARGS__); \
  528. GE_DUMP(compute_graph, "PreRunAfter" name); \
  529. GELOGI("Run %s on graph %s(%u) success.", name, compute_graph->GetName().c_str(), graph_node->GetGraphId()); \
  530. } while (0)
  531. Status GraphManager::PreRunOptimizeOriginalGraph(const GraphNodePtr &graph_node, const std::vector<GeTensor> &inputs,
  532. ge::ComputeGraphPtr &compute_graph, uint64_t session_id) {
  533. GE_CHECK_NOTNULL(graph_node);
  534. GE_CHECK_NOTNULL(compute_graph);
  535. CompilerStages &stages = GetCompilerStages(graph_node->GetGraphId());
  536. GM_RUN_AND_DUMP_PERF("OptimizeGraphPrepare", stages.optimizer.OptimizeOriginalGraphForQuantize, compute_graph);
  537. GM_RUN_AND_DUMP_PERF("HandleSummaryOp", stages.optimizer.HandleSummaryOp, compute_graph);
  538. GM_RUN_AND_DUMP_PERF("Prepare", stages.preparer.PrepareDynShape, graph_node->GetGraph(), inputs, compute_graph,
  539. session_id);
  540. GM_RUN_AND_DUMP_PERF("OptimizeOriginalGraph", stages.optimizer.OptimizeOriginalGraph, compute_graph);
  541. GM_RUN_AND_DUMP_PERF("PrepareRunningFormatRefiner", stages.preparer.PrepareRunningFormatRefiner);
  542. GM_RUN_AND_DUMP_PERF("RefineRunningFormat", stages.optimizer.OptimizeOriginalGraphJudgeInsert, compute_graph);
  543. GM_RUN_AND_DUMP_PERF("SubexpressionMigration", SubexpressionMigration, compute_graph);
  544. GE_RUN(GraphManager, stages.preparer.RecordAIPPInfo, compute_graph);
  545. if (IsTailingOptimization()) {
  546. GM_RUN_AND_DUMP_PERF("OptimizeSwitchOp", stages.preparer.SwitchOpOptimize, compute_graph);
  547. }
  548. GM_RUN_AND_DUMP_PERF("Optimize1", OptimizeStage1, compute_graph);
  549. GM_RUN_AND_DUMP_PERF("InferShape2", compute_graph->InferShapeInNeed);
  550. PassManager graph_pass;
  551. GE_CHK_STATUS_RET(graph_pass.AddPass("PreRun::CtrlEdgeTransferPass", new (std::nothrow) CtrlEdgeTransferPass))
  552. GE_CHK_STATUS_RET(graph_pass.Run(compute_graph));
  553. GE_CHK_STATUS_RET(stages.optimizer.IdentifyReference(compute_graph), "Identify reference failed.");
  554. GELOGI("PreRun:PreRunOptimizeOriginalGraph success.");
  555. return SUCCESS;
  556. }
  557. Status GraphManager::PreRunOptimizeSubGraph(const GraphNodePtr &graph_node,
  558. ge::ComputeGraphPtr &compute_graph,
  559. uint64_t session_id) {
  560. GE_CHECK_NOTNULL(graph_node);
  561. GE_CHECK_NOTNULL(compute_graph);
  562. GM_RUN_AND_DUMP_PERF("OptimizeSubgraph", OptimizeSubgraph, graph_node, compute_graph, session_id);
  563. // Dump graph to tuning path
  564. if (options_.build_mode == BUILD_MODE_TUNING && options_.build_step == BUILD_STEP_AFTER_UB_MATCH) {
  565. std::string tuning_path;
  566. (void) GetContext().GetOption(TUNING_PATH, tuning_path);
  567. GELOGI("Dump path:%s.", tuning_path.c_str());
  568. GraphUtils::DumpGEGraph(compute_graph, "", true, tuning_path);
  569. }
  570. GELOGI("PreRun:PreRunOptimizeSubGraph success.");
  571. return SUCCESS;
  572. }
  573. Status GraphManager::PreRunAfterOptimizeSubGraph(const GraphNodePtr &graph_node, ComputeGraphPtr &compute_graph,
  574. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  575. GE_CHECK_NOTNULL(graph_node);
  576. GE_CHECK_NOTNULL(compute_graph);
  577. GM_RUN_AND_DUMP_PERF("Optimize2", OptimizeStage2, compute_graph);
  578. GM_RUN_AND_DUMP_PERF("OptimizeGraphBeforeBuildForRts",
  579. GetCompilerStages(graph_node->GetGraphId()).optimizer.OptimizeGraphBeforeBuildForRts,
  580. compute_graph);
  581. GM_RUN_AND_DUMP_PERF("Build", Build, graph_node, compute_graph, ge_root_model, session_id);
  582. GELOGI("PreRun:PreRunAfterOptimizeSubGraph success.");
  583. return SUCCESS;
  584. }
  585. Status GraphManager::SetRtContext(rtContext_t rt_context, rtCtxMode_t mode, uint64_t session_id, uint32_t graph_id) {
  586. GELOGI("set rt_context, session id: %lu, graph id: %u, mode %d, device id:%u.", session_id, graph_id,
  587. static_cast<int>(mode), ge::GetContext().DeviceId());
  588. rtError_t rt_ret = rtCtxCreate(&rt_context, mode, ge::GetContext().DeviceId());
  589. if (rt_ret != RT_ERROR_NONE) {
  590. GELOGE(FAILED, "Call rt api failed, ret: 0x%X", rt_ret);
  591. return FAILED;
  592. }
  593. rt_ret = rtCtxSetCurrent(rt_context);
  594. if (rt_ret != RT_ERROR_NONE) {
  595. GELOGE(FAILED, "Call rt api failed, ret: 0x%X", rt_ret);
  596. return FAILED;
  597. }
  598. RtContextUtil::GetInstance().AddRtContext(session_id, graph_id, rt_context);
  599. return SUCCESS;
  600. }
  601. Status GraphManager::PreRun(const GraphNodePtr &graph_node, const std::vector<GeTensor> &inputs,
  602. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  603. GE_CHECK_NOTNULL(graph_node);
  604. GE_CHECK_NOTNULL(graph_node->GetGraph());
  605. auto compute_graph = GraphUtils::GetComputeGraph(*graph_node->GetGraph());
  606. GE_CHECK_NOTNULL(compute_graph);
  607. compute_graph->SetSessionID(session_id);
  608. auto analyzer_instance = Analyzer::GetInstance();
  609. GE_CHK_STATUS_RET(analyzer_instance->BuildJsonObject(session_id, compute_graph->GetGraphID()),
  610. "BuildJsonObject Failed")
  611. GEEVENT("PreRun start, graph node size %zu, session id %lu, graph id %u, graph name %s",
  612. compute_graph->GetDirectNodesSize(), session_id, compute_graph->GetGraphID(),
  613. compute_graph->GetName().c_str());
  614. GE_DUMP(compute_graph, "PreRunBegin");
  615. // rtContext_t
  616. Status ret = SetRtContext(rtContext_t(), RT_CTX_GEN_MODE, session_id, compute_graph->GetGraphID());
  617. if (ret != SUCCESS) {
  618. GELOGE(ret, "Set rt context failed.");
  619. return ret;
  620. }
  621. /// 1. BUILD_MODE_TUNING with BUILD_STEP_AFTER_UB_MATCH no need PreRunOptimizeOriginalGraph;
  622. /// 2. BUILD_MODE_TUNING with BUILD_STEP_AFTER_MERGE no need PreRunOptimizeOriginalGraph.
  623. /// 3. BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER_SUB no need PreRunOptimizeOriginalGraph.
  624. bool run_optimize_original_graph = !((options_.build_mode == BUILD_MODE_TUNING) &&
  625. (options_.build_step == BUILD_STEP_AFTER_UB_MATCH ||
  626. options_.build_step == BUILD_STEP_AFTER_MERGE ||
  627. options_.build_step == BUILD_STEP_AFTER_BUILDER_SUB));
  628. if (run_optimize_original_graph) {
  629. Status ret = PreRunOptimizeOriginalGraph(graph_node, inputs, compute_graph, session_id);
  630. if (ret != SUCCESS) {
  631. GELOGE(ret, "Run PreRunOptimizeOriginalGraph failed for graph:%s.", compute_graph->GetName().c_str());
  632. return ret;
  633. }
  634. }
  635. ret = PreRunOptimizeSubGraph(graph_node, compute_graph, session_id);
  636. if (ret != SUCCESS) {
  637. GELOGE(ret, "Run PreRunOptimizeSubGraph failed for graph:%s.", compute_graph->GetName().c_str());
  638. return ret;
  639. }
  640. /// 1. BUILD_MODE_TUNING with BUILD_STEP_BEFORE_UB_MATCH no need PreRunAfterOptimizeSubGraph;
  641. /// 2. BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER no need PreRunAfterOptimizeSubGraph.
  642. /// 3. BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER_SUB no need PreRunAfterOptimizeSubGraph.
  643. bool run_after_optimize_subgraph = !((options_.build_mode == BUILD_MODE_TUNING) &&
  644. (options_.build_step == BUILD_STEP_BEFORE_UB_MATCH ||
  645. options_.build_step == BUILD_STEP_AFTER_BUILDER ||
  646. options_.build_step == BUILD_STEP_AFTER_BUILDER_SUB));
  647. if (run_after_optimize_subgraph) {
  648. Status ret = PreRunAfterOptimizeSubGraph(graph_node, compute_graph, ge_root_model, session_id);
  649. if (ret != SUCCESS) {
  650. GELOGE(ret, "Run PreRunAfterOptimizeSubGraph failed for graph:%s.", compute_graph->GetName().c_str());
  651. return ret;
  652. }
  653. }
  654. // when set incre build, save om model and var manager
  655. GeModelPtr ge_model = nullptr;
  656. auto save_ret = SaveCacheAfterBuild(graph_node->GetGraphId(), compute_graph, ge_model);
  657. if (save_ret != SUCCESS) {
  658. GELOGW("Fail to save cache.");
  659. }
  660. GEEVENT("[GEPERFTRACE] GE PreRun End");
  661. return SUCCESS;
  662. }
  663. Status GraphManager::SubexpressionMigration(ComputeGraphPtr &compute_graph) {
  664. PassManager pass_manager;
  665. GE_CHK_STATUS_RET(pass_manager.AddPass("SubexpressionMigrationPass", new (std::nothrow) SubexpressionMigrationPass));
  666. GE_CHK_STATUS_RET(pass_manager.AddPass("UnusedArgsCleanPass", new (std::nothrow) UnusedArgsCleanPass));
  667. GE_TIMESTAMP_START(SubexpressionMigrationPass);
  668. auto ret = pass_manager.Run(compute_graph);
  669. GE_TIMESTAMP_END(SubexpressionMigrationPass, "GraphManager::SubexpressionMigration");
  670. if (ret != SUCCESS && ret != NOT_CHANGED) {
  671. GELOGE(ret, "Run SubexpressionMigrationPass failed, ret:%u.", ret);
  672. return ret;
  673. }
  674. return SUCCESS;
  675. }
  676. Status GraphManager::StartForRunGraph(const GraphNodePtr &graph_node, const std::vector<GeTensor> &inputs,
  677. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  678. // it will not execute graph prreprocess, optimize, parition, build if the graph has built successful.
  679. Status ret = SUCCESS;
  680. if (IsGraphNeedBuild(graph_node)) {
  681. if (graph_node->GetBuildFlag()) {
  682. GELOGE(PARAM_INVALID,
  683. "The graph %u need to re-build, you should remove it from GE "
  684. "first, then AddGraph again and rebuild it.",
  685. graph_node->GetGraphId());
  686. return PARAM_INVALID;
  687. }
  688. GeModelPtr ge_model = nullptr;
  689. // check need incre build.
  690. ret = IncreBuild(graph_node, ge_model);
  691. if (ret != SUCCESS) {
  692. ret = PreRun(graph_node, inputs, ge_root_model, session_id);
  693. // release rts generate context
  694. RtContextUtil::GetInstance().DestroyRtContexts(session_id, graph_node->GetGraphId());
  695. if (ret != SUCCESS) {
  696. GELOGE(ret, "PreRun Failed.");
  697. return ret;
  698. }
  699. }
  700. if (!graph_node->IsAsync()) {
  701. ret = LoadGraph(ge_root_model, graph_node);
  702. } else {
  703. ret = LoadGraphAsync(ge_root_model, graph_node);
  704. }
  705. if (ret != SUCCESS) {
  706. GELOGE(ret, "LoadGraph Failed.");
  707. return ret;
  708. }
  709. graph_node->SetBuildFlag(true);
  710. var_acc_ctrl_.SetGraphBuildEnd(graph_node->GetGraphId());
  711. } else if (!graph_node->GetLoadFlag()) {
  712. GeRootModelPtr ge_root_model_ptr = graph_node->GetGeRootModel();
  713. if (!graph_node->IsAsync()) {
  714. ret = LoadGraph(ge_root_model_ptr, graph_node);
  715. } else {
  716. ret = LoadGraphAsync(ge_root_model_ptr, graph_node);
  717. }
  718. if (ret != SUCCESS) {
  719. GELOGE(ret, "LoadGraph Failed.");
  720. return ret;
  721. }
  722. }
  723. return ret;
  724. }
  725. Status GraphManager::LoadGraph(const GeRootModelPtr &ge_root_model, const GraphNodePtr &graph_node) {
  726. GELOGI("[LoadGraph] run_graph_flag[%d], graph_id[%u]", options_.run_graph_flag, graph_node->GetGraphId());
  727. if (options_.run_graph_flag && ge_root_model != nullptr) {
  728. // synchronization run graph with model
  729. std::shared_ptr<GraphModelListener> model_listener = GetModelListener();
  730. ModelIdInfo model_id_info;
  731. bool is_unknown_shape = false;
  732. GE_CHK_STATUS_RET(ge_root_model->CheckIsUnknownShape(is_unknown_shape));
  733. if (!is_unknown_shape) {
  734. if (getenv(kEnvGeuseStaticMemory) != nullptr) {
  735. GELOGI("[LoadGraph] GE_USE_STATIC_MEMORY is seted.");
  736. } else {
  737. auto root_graph = ge_root_model->GetRootGraph();
  738. GE_CHECK_NOTNULL(root_graph);
  739. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  740. GeModelPtr ge_model = name_to_model[root_graph->GetName()];
  741. GE_CHK_STATUS_RET(CheckAndReleaseMemory(ge_model, graph_node));
  742. }
  743. }
  744. GE_TIMESTAMP_START(LoadGraph);
  745. Status ret = GraphLoader::LoadModelOnline(model_id_info.model_id, ge_root_model, model_listener);
  746. GE_TIMESTAMP_EVENT_END(LoadGraph, "GraphManager::LoadGraph");
  747. if (ret != SUCCESS) {
  748. GELOGE(ret, "[StartForRunGraph] LoadGraph Failed");
  749. graph_node->SetRunFlag(false);
  750. return ret;
  751. }
  752. graph_node->SetLoadFlag(true);
  753. ge_root_model->SetModelId(model_id_info.model_id);
  754. graph_node->SetGeRootModel(ge_root_model);
  755. }
  756. return SUCCESS;
  757. }
  758. Status GraphManager::LoadFromCache(const GraphNodePtr &graph_node, const ModelCacheHelperPtr &cache_helper,
  759. GeModelPtr &ge_model) {
  760. auto graph_id = graph_node->GetGraphId();
  761. auto ret = cache_helper->LoadOmModelFromCache(ge_model);
  762. if (ret != SUCCESS) {
  763. GELOGW("Fail to load om model from cache.");
  764. if (cache_helper->ClearCache(graph_id) != SUCCESS) {
  765. GELOGW("Fail to clear cache of graph %u.", graph_id);
  766. }
  767. return FAILED;
  768. }
  769. ret = cache_helper->RecoverVarManagerFromCache();
  770. if (ret != SUCCESS) {
  771. GELOGW("Fail to recover VarManager from cache.");
  772. if (cache_helper->ClearCache(graph_id) != SUCCESS) {
  773. GELOGW("Fail to clear cache of graph %u.", graph_id);
  774. }
  775. return FAILED;
  776. }
  777. ComputeGraphPtr compute_graph_in_model = GraphUtils::GetComputeGraph(ge_model->GetGraph());
  778. if (compute_graph_in_model == nullptr) {
  779. GELOGW("Error occurred when get compute graph from om, abandon.");
  780. return FAILED;
  781. } else {
  782. graph_node->SetComputeGraph(compute_graph_in_model);
  783. graph_node->SetGeModel(ge_model);
  784. GELOGI("Load model and graph form cache om file.");
  785. }
  786. return SUCCESS;
  787. }
  788. Status GraphManager::SaveCacheBeforeBuild(uint32_t graph_id, const ModelCacheHelperPtr &cache_helper) {
  789. auto ret = cache_helper->SaveCacheInfoToCache();
  790. if (ret != SUCCESS) {
  791. GELOGW("Fail to save cache info of graph[%d] to cache.", graph_id);
  792. return FAILED;
  793. }
  794. ret = cache_helper->SaveVarManagerToCache(true);
  795. if (ret != SUCCESS) {
  796. GELOGW("Fail to save var manager to cache.");
  797. cache_helper->ClearCache(graph_id);
  798. return FAILED;
  799. }
  800. GELOGI("Cache files have been saved.");
  801. return SUCCESS;
  802. }
  803. Status GraphManager::SaveCacheAfterBuild(uint32_t graph_id, ge::ComputeGraphPtr graph, GeModelPtr &ge_model) {
  804. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  805. if ((instance_ptr == nullptr) || !instance_ptr->InitFlag()) {
  806. GELOGW("GELib not initialized.");
  807. return FAILED;
  808. }
  809. if (instance_ptr->IsIncreBuild()) {
  810. std::lock_guard<std::mutex> lock(member_mutex_);
  811. auto iter = cache_helper_map_.find(graph_id);
  812. if (iter == cache_helper_map_.end()) {
  813. GELOGW("Can not find ModelCacheHelper of graph[%u]", graph_id);
  814. return FAILED;
  815. } else {
  816. ModelCacheHelperPtr cache_helper = iter->second;
  817. auto ret = cache_helper->RefreshComputeGraph(graph);
  818. if (ret != SUCCESS) {
  819. cache_helper->ClearCache(graph_id);
  820. GELOGW("Fail to refresh cache helper's compute graph");
  821. return FAILED;
  822. }
  823. ret = cache_helper->SaveVarManagerToCache(false);
  824. if (ret != SUCCESS) {
  825. cache_helper->ClearCache(graph_id);
  826. GELOGW("Fail to save VarManager to cache");
  827. return FAILED;
  828. }
  829. ret = cache_helper->SaveOmModelToCache(ge_model);
  830. if (ret != SUCCESS) {
  831. cache_helper->ClearCache(graph_id);
  832. GELOGW("Fail to save om model to cache");
  833. return FAILED;
  834. }
  835. }
  836. }
  837. return SUCCESS;
  838. }
  839. Status GraphManager::InnerRunGraph(GraphNodePtr &graph_node, const GraphId &graph_id,
  840. const std::vector<GeTensor> &inputs, std::vector<GeTensor> &outputs) {
  841. Status ret = graph_executor_.SetCondition(&sync_run_mutex_, &condition_, graph_run_listener_);
  842. if (ret != SUCCESS) {
  843. GELOGE(GE_GRAPH_RUNGRAPH_FAILED, "[RunGraph] set condition failed, graph_id = %u.", graph_id);
  844. graph_node->SetRunFlag(false);
  845. return GE_GRAPH_RUNGRAPH_FAILED;
  846. }
  847. if (GetTrainFlag()) {
  848. GE_CHK_STATUS_RET(graph_executor_.SetGraphContext(GetGraphContext()));
  849. graph_executor_.SetTrainFlag(options_.train_graph_flag);
  850. }
  851. ret = graph_executor_.ExecuteGraph(graph_id, graph_node->GetGeRootModel(), inputs, outputs);
  852. graph_node->SetRunFlag(false);
  853. if (ret != SUCCESS) {
  854. GELOGE(ret, "[RunGraph] execute graph failed, graph_id = %u.", graph_id);
  855. return ret;
  856. }
  857. return SUCCESS;
  858. }
  859. Status GraphManager::RunGraph(const GraphId &graph_id, const std::vector<GeTensor> &inputs,
  860. std::vector<GeTensor> &outputs, uint64_t session_id) {
  861. std::lock_guard<std::mutex> lock(run_mutex_);
  862. GELOGI("[RunGraph] start to run graph, graph_id = %u, is_train_graph: %d", graph_id, GetTrainFlag());
  863. if (inputs.empty()) {
  864. GELOGI("[RunGraph] initialize sub graph has no inputs");
  865. }
  866. // find graph
  867. GraphNodePtr graph_node = nullptr;
  868. Status ret = GetGraphNode(graph_id, graph_node);
  869. if (ret != SUCCESS) {
  870. GELOGE(ret, "[RunGraph] graph not exist, graph_id = %u.", graph_id);
  871. return ret;
  872. }
  873. if (graph_node == nullptr) {
  874. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] graph node is NULL, graph_id = %u.", graph_id);
  875. return GE_GRAPH_GRAPH_NODE_NULL;
  876. }
  877. if (graph_node->GetRunFlag()) {
  878. GELOGE(GE_GRAPH_ALREADY_RUNNING, "[RunGraph] graph already running, graph id = %u", graph_id);
  879. return GE_GRAPH_ALREADY_RUNNING;
  880. }
  881. UpdateLocalOmgContext(graph_id);
  882. // set graph's run flag
  883. graph_node->SetRunFlag(true);
  884. ComputeGraphPtr compute_graph_tmp = GraphUtils::GetComputeGraph(*(graph_node->GetGraph()));
  885. GE_IF_BOOL_EXEC(GetTrainFlag(),
  886. GE_IF_BOOL_EXEC(compute_graph_tmp == nullptr,
  887. GELOGE(GE_GRAPH_GRAPH_NODE_NULL,
  888. "[RunGraph] compute_graph_tmp is NULL, graph id = %u.", graph_id);
  889. return GE_GRAPH_GRAPH_NODE_NULL;))
  890. // when set incre build, add cache helper map
  891. AddModelCacheHelperToMap(graph_id, session_id, compute_graph_tmp);
  892. if (options_.local_fmk_op_flag) {
  893. GetCompilerStages(graph_id).optimizer.TranFrameOp(compute_graph_tmp);
  894. }
  895. GeRootModelPtr ge_root_model = nullptr;
  896. ret = StartForRunGraph(graph_node, inputs, ge_root_model, session_id);
  897. if (ret != SUCCESS) {
  898. GELOGE(ret, "[RunGraph] StartForRunGraph failed!");
  899. graph_node->SetRunFlag(false);
  900. return ret;
  901. }
  902. // excute graph
  903. ret = InnerRunGraph(graph_node, graph_id, inputs, outputs);
  904. if (ret != SUCCESS) {
  905. return ret;
  906. }
  907. if (GetTrainFlag()) {
  908. if (compute_graph_tmp->IsSummaryGraph()) {
  909. ret = SummaryHandle(graph_id, outputs);
  910. if (ret != SUCCESS) {
  911. GELOGE(ret, "[RunGraph] SummaryHandle failed!");
  912. }
  913. }
  914. GeRootModelPtr root_model = graph_node->GetGeRootModel();
  915. if (root_model != nullptr) {
  916. GELOGI("Start CheckpointHandle.");
  917. auto checkPointGraph = root_model->GetRootGraph();
  918. if (IsCheckpointGraph(checkPointGraph)) {
  919. ret = CheckpointHandle(graph_id, checkPointGraph, outputs);
  920. if (ret != SUCCESS) {
  921. GELOGE(ret, "[RunGraph] CheckpointHandle failed!");
  922. }
  923. }
  924. }
  925. }
  926. GELOGI("[RunGraph] run graph success, graph_id = %u.", graph_id);
  927. return SUCCESS;
  928. }
  929. Status GraphManager::GenerateInfershapeGraph(GraphId &graph_id) {
  930. GELOGI("[DumpInfershapeJson] start to DumpInfershapeJson graph, graph_id=%u.", graph_id);
  931. // find graph
  932. GraphNodePtr graph_node = nullptr;
  933. Status ret = GetGraphNode(graph_id, graph_node);
  934. if (ret != SUCCESS) {
  935. GELOGE(ret, "[BuildGraph] graph not exist, graph_id = %u.", graph_id);
  936. return ret;
  937. }
  938. if (graph_node == nullptr) {
  939. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[BuildGraph] graph node is NULL, graphId = %u.", graph_id);
  940. return GE_GRAPH_GRAPH_NODE_NULL;
  941. }
  942. UpdateLocalOmgContext(graph_id);
  943. ret = GetCompilerStages(graph_id).preparer.GenerateInfershapeGraph(graph_node->GetGraph());
  944. if (ret != SUCCESS) {
  945. GELOGE(ret, "ATC dump infershape json failed");
  946. return ret;
  947. }
  948. GELOGI("[DumpInfershapeJson] Dump infershape json success, graph_id=%u.", graph_id);
  949. return ret;
  950. }
  951. Status GraphManager::BuildGraphForUnregisteredOp(const GraphId &graph_id, const std::vector<GeTensor> &inputs,
  952. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  953. // find graph
  954. GraphNodePtr graph_node = nullptr;
  955. Status ret = GetGraphNode(graph_id, graph_node);
  956. if (ret != SUCCESS) {
  957. GELOGE(ret, "[BuildGraph] graph not exist, graph_id = %u.", graph_id);
  958. return ret;
  959. }
  960. if (graph_node == nullptr) {
  961. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[BuildGraph] graph node is NULL, graphId = %u.", graph_id);
  962. return GE_GRAPH_GRAPH_NODE_NULL;
  963. }
  964. UpdateLocalOmgContext(graph_id);
  965. auto compute_graph = GraphUtils::GetComputeGraph(*graph_node->GetGraph());
  966. GE_CHECK_NOTNULL(compute_graph);
  967. GM_RUN_AND_DUMP_PERF("Prepare", GetCompilerStages(graph_id).preparer.PrepareDynShape, graph_node->GetGraph(), inputs,
  968. compute_graph, session_id);
  969. for (auto &node : compute_graph->GetAllNodes()) {
  970. OpDescPtr op_desc = node->GetOpDesc();
  971. GE_CHECK_NOTNULL(op_desc);
  972. if (op_desc->HasAttr(ATTR_NAME_UNREGST_OPPATH)) {
  973. vector<ge::NodePtr> node_vec = {node};
  974. auto instance_ptr = ge::GELib::GetInstance();
  975. if (instance_ptr == nullptr || !instance_ptr->InitFlag()) {
  976. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "GE is not initialized");
  977. return GE_CLI_GE_NOT_INITIALIZED;
  978. }
  979. OpsKernelInfoStorePtr kernel_info =
  980. instance_ptr->OpsKernelManagerObj().GetOpsKernelInfoStore(op_desc->GetOpKernelLibName());
  981. if (kernel_info == nullptr) {
  982. GELOGE(FAILED, "Get op kernel info store failed");
  983. return FAILED;
  984. }
  985. ret = kernel_info->CompileOp(node_vec);
  986. if (ret != SUCCESS) {
  987. GELOGE(ret, "Compile op failed, op = %s, graph_id = %u.", op_desc->GetName().c_str(), graph_id);
  988. return ret;
  989. }
  990. }
  991. }
  992. GM_RUN_AND_DUMP_PERF("Build", Build, graph_node, compute_graph, ge_root_model, session_id);
  993. return SUCCESS;
  994. }
  995. Status GraphManager::BuildGraph(const GraphId &graph_id, const std::vector<GeTensor> &inputs,
  996. GeRootModelPtr &ge_root_model, uint64_t session_id, bool async) {
  997. GELOGI("[BuildGraph] start to build graph, graph_id=%u.", graph_id);
  998. if (inputs.empty()) {
  999. GELOGW("[BuildGraph] BuildGraph warning: empty GeTensor inputs");
  1000. }
  1001. // find graph
  1002. GraphNodePtr graph_node = nullptr;
  1003. Status ret = GetGraphNode(graph_id, graph_node);
  1004. if (ret != SUCCESS) {
  1005. GELOGE(ret, "[BuildGraph] graph not exist, graph_id = %u.", graph_id);
  1006. return ret;
  1007. }
  1008. if (graph_node == nullptr) {
  1009. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[BuildGraph] graph node is NULL, graphId = %u.", graph_id);
  1010. return GE_GRAPH_GRAPH_NODE_NULL;
  1011. }
  1012. if (graph_node->GetRunFlag()) {
  1013. GELOGE(GE_GRAPH_ALREADY_RUNNING, "[BuildGraph] graph already running, graph id = %u", graph_node->GetGraphId());
  1014. return GE_GRAPH_ALREADY_RUNNING;
  1015. }
  1016. UpdateLocalOmgContext(graph_id);
  1017. graph_node->SetAsync(async);
  1018. // set graph's run flag
  1019. graph_node->SetRunFlag(true);
  1020. ret = StartForRunGraph(graph_node, inputs, ge_root_model, session_id);
  1021. graph_node->SetRunFlag(false);
  1022. if (ret != SUCCESS) {
  1023. GELOGE(GE_GRAPH_PRERUN_FAILED, "[BuildGraph] StartForRunGraph failed!");
  1024. return GE_GRAPH_PRERUN_FAILED;
  1025. }
  1026. GELOGI("[BuildGraph] build graph success, graph_id=%u.", graph_id);
  1027. return ret;
  1028. }
  1029. ///
  1030. /// @ingroup ge_graph
  1031. /// @brief Save extra attribute to Model
  1032. /// @param [in] model: Model attribues will save to.
  1033. /// @param [in] type: type of OpDesc.
  1034. /// @param [in] attrs: attributes of OpDesc.
  1035. /// @param [in] inputs: inputs tensor.
  1036. /// @param [in] outputs: outputs tensor.
  1037. /// @return: Status
  1038. ///
  1039. Status GraphManager::SaveParams(ge::GeModel &model, const std::string &type, const std::map<string, GeAttrValue> &attrs,
  1040. const std::vector<GeTensor> &inputs, const std::vector<GeTensor> &outputs) {
  1041. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetStr(&model, "ATTR_MODEL_OP_TYPE", type), return FAILED, "Set Op[%s] type fail",
  1042. type.c_str());
  1043. for (const auto &it : attrs) {
  1044. GE_CHK_BOOL_EXEC(model.SetAttr("ATTR_MODEL_" + it.first, it.second) == GRAPH_SUCCESS, return FAILED,
  1045. "Set OpDesc attribute[%s] fail", it.first.c_str());
  1046. }
  1047. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListTensor(&model, "ATTR_MODEL_TENSOR_INPUTS", inputs), return FAILED,
  1048. "Set Inputs tensor list fail");
  1049. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListTensor(&model, "ATTR_MODEL_TENSOR_OUTPUTS", outputs), return FAILED,
  1050. "Set Outputs tensor list fail");
  1051. return SUCCESS;
  1052. }
  1053. void GraphManager::RemoveModelCacheHelper(const GraphId &graph_id) {
  1054. std::lock_guard<std::mutex> lock(member_mutex_);
  1055. auto iter = cache_helper_map_.find(graph_id);
  1056. if (iter != cache_helper_map_.end()) {
  1057. cache_helper_map_.erase(iter);
  1058. } else {
  1059. GELOGW("[GraphManager] cache helper does not exist, graph_id = %u", graph_id);
  1060. }
  1061. }
  1062. bool GraphManager::CheckModelLoad(const GeRootModelPtr &ge_root_model, bool load_flag) {
  1063. return ((ge_root_model != nullptr) && (ge_root_model->GetModelId() != INVALID_MODEL_ID) && load_flag);
  1064. }
  1065. Status GraphManager::RemoveGraph(const GraphId &graph_id) {
  1066. GraphNodePtr graph_node = nullptr;
  1067. Status ret = GetGraphNode(graph_id, graph_node);
  1068. if (ret != SUCCESS) {
  1069. GELOGE(GE_GRAPH_GRAPH_NOT_EXIST, "[GraphManager] Id %u does not exists.", graph_id);
  1070. return GE_GRAPH_GRAPH_NOT_EXIST;
  1071. }
  1072. if ((graph_node == nullptr) || (graph_node->GetRunFlag())) {
  1073. GELOGE(GE_GRAPH_GRAPH_IS_RUNNING, "[GraphManager] Id %u is running, can't be deleted.", graph_id);
  1074. return GE_GRAPH_GRAPH_IS_RUNNING;
  1075. }
  1076. std::lock_guard<std::mutex> lock(unload_model_mutex_);
  1077. Status middle_ret;
  1078. rtError_t rt_ret;
  1079. const std::vector<SubGraphInfoPtr> &all_sub_graph = graph_node->GetAllSubGraph();
  1080. for (size_t i = 0; i < all_sub_graph.size(); ++i) {
  1081. // must free buffer firstly
  1082. middle_ret = all_sub_graph[i]->FreeInOutBuffer();
  1083. if (middle_ret != SUCCESS) {
  1084. GELOGE(middle_ret, "[GraphManager] RemoveGraph free mem failed, graph_id=%u.", graph_id);
  1085. ret = middle_ret;
  1086. }
  1087. if (all_sub_graph[i]->GeModelIsValid() && all_sub_graph[i]->GetModelIdInfo().model_id != INVALID_MODEL_ID) {
  1088. // unload model
  1089. GELOGI("UnloadModel via new ome.");
  1090. rt_ret = rtSetDevice(GetContext().DeviceId());
  1091. if (rt_ret != RT_ERROR_NONE) {
  1092. GELOGE(RT_FAILED, "[GraphManager:] rtSetDevice failed, modelId=%u, graphId=%u.",
  1093. all_sub_graph[i]->GetModelIdInfo().model_id, graph_id);
  1094. ret = FAILED;
  1095. continue;
  1096. }
  1097. middle_ret = GraphLoader::UnloadModel(all_sub_graph[i]->GetModelIdInfo().model_id);
  1098. if (middle_ret != SUCCESS) {
  1099. GELOGE(middle_ret, "[GraphManager:] unload model failed, modelId=%u, graph_id=%u.",
  1100. all_sub_graph[i]->GetModelIdInfo().model_id, graph_id);
  1101. ret = middle_ret;
  1102. }
  1103. rt_ret = rtDeviceReset(GetContext().DeviceId());
  1104. if (rt_ret != RT_ERROR_NONE) {
  1105. GELOGE(RT_FAILED, "[GraphManager:] unload model failed, modelId=%u, graphId=%u.",
  1106. all_sub_graph[i]->GetModelIdInfo().model_id, graph_id);
  1107. ret = FAILED;
  1108. }
  1109. }
  1110. }
  1111. var_acc_ctrl_.RemoveGraph(graph_id);
  1112. RemoveGraphNode(graph_id);
  1113. RemoveModelCacheHelper(graph_id);
  1114. auto ge_root_model = graph_node->GetGeRootModel();
  1115. if (CheckModelLoad(ge_root_model, graph_node->GetLoadFlag())) {
  1116. GELOGI("Unload model %u.", ge_root_model->GetModelId());
  1117. rt_ret = rtSetDevice(GetContext().DeviceId());
  1118. if (rt_ret != RT_ERROR_NONE) {
  1119. GELOGE(RT_FAILED, "[GraphManager:] rtSetDevice failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(),
  1120. graph_id);
  1121. return FAILED;
  1122. }
  1123. middle_ret = GraphLoader::UnloadModel(ge_root_model->GetModelId());
  1124. if (middle_ret != SUCCESS) {
  1125. GELOGE(middle_ret, "[GraphManager:] unload model failed, modelId=%u, graph_id=%u.", ge_root_model->GetModelId(),
  1126. graph_id);
  1127. ret = middle_ret;
  1128. }
  1129. rt_ret = rtDeviceReset(GetContext().DeviceId());
  1130. if (rt_ret != RT_ERROR_NONE) {
  1131. GELOGE(RT_FAILED, "[GraphManager:] rtDeviceReset failed, modelId=%u, graphId=%u.", ge_root_model->GetModelId(),
  1132. graph_id);
  1133. ret = FAILED;
  1134. }
  1135. }
  1136. RemoveCompilerStages(graph_id);
  1137. GE_CHK_STATUS_RET(ret, "[GraphManager:] Remove graph failed, graph_id=%u.", graph_id);
  1138. GELOGI("[GraphManager] remove graph success, graph_id=%u.", graph_id);
  1139. return SUCCESS;
  1140. }
  1141. Status GraphManager::ParseOptions(const std::map<std::string, std::string> &options) {
  1142. Status ret;
  1143. ParseOption(options, "ge.INPUT_NODES_SET_FP16", options_.input_nodes_set_fp16);
  1144. // parse streams max parallel num
  1145. ret = ParseOption(options, STREAM_MAX_PARALLEL_NUM, options_.stream_max_parallel_num);
  1146. if (ret != SUCCESS) {
  1147. GELOGE(GE_GRAPH_OPTIONS_INVALID,
  1148. "parse Key:%s value failed, it must be same format as "
  1149. "DNN_V100:2,DNN_HCCL:3",
  1150. STREAM_MAX_PARALLEL_NUM.c_str());
  1151. return GE_GRAPH_OPTIONS_INVALID;
  1152. }
  1153. // get stream num
  1154. ret = ParseOption(options, STREAM_NUM, options_.stream_num);
  1155. if ((ret != SUCCESS) || (options_.stream_num == 0)) {
  1156. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.stream_num, its value %d is invalid, must be not equal zero.",
  1157. options_.stream_num);
  1158. return GE_GRAPH_OPTIONS_INVALID;
  1159. }
  1160. // get perf level, its value please see enum PerfLevel
  1161. ret = ParseOption(options, PERF_LEVEL, options_.perf_level);
  1162. if ((ret != SUCCESS) || IsPerfLevelInvalid(options_.perf_level)) {
  1163. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.perfLevel, its value %d is invalid, must be enum PerfLevel type.",
  1164. options_.perf_level);
  1165. return GE_GRAPH_OPTIONS_INVALID;
  1166. }
  1167. // get encrypt mode
  1168. ret = ParseOption(options, ENCRYPT_MODE, options_.encrypt_mode);
  1169. if (ret != SUCCESS) {
  1170. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.encryptMode value invalid.");
  1171. return GE_GRAPH_OPTIONS_INVALID;
  1172. }
  1173. // get ek file
  1174. ParseOption(options, EK_FILE, options_.ek_file);
  1175. // get cert file
  1176. ParseOption(options, CERT_FILE, options_.cert_file);
  1177. // get hw key file
  1178. ParseOption(options, HW_KEY_FILE, options_.hw_key_file);
  1179. // get private file
  1180. ParseOption(options, PRIVATE_KEY_FILE, options_.private_key_file);
  1181. // get framework type, its value please see enum FrameworkType
  1182. ret = ParseOption(options, FRAMEWORK_TYPE, options_.framework_type);
  1183. if (ret != SUCCESS) {
  1184. // print error log in ParseOption
  1185. return GE_GRAPH_OPTIONS_INVALID;
  1186. }
  1187. // get calibration info file
  1188. ParseOption(options, CALIBRATION_CONF_FILE, options_.calibration_conf_file);
  1189. // get insert op info file
  1190. ParseOption(options, INSERT_OP_FILE, options_.insert_op_file);
  1191. // get output node name
  1192. ParseOption(options, OUTPUT_NODE_NAME, options_.output_node_name);
  1193. // get function bin path
  1194. ParseOption(options, "ge.func_bin_path", options_.func_bin_path);
  1195. // get core type
  1196. ParseOption(options, CORE_TYPE, options_.core_type);
  1197. // get weight compress flag
  1198. ret = ParseOption(options, COMPRESS_FLAG, options_.compress_flag);
  1199. if (ret != SUCCESS) {
  1200. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.compressFlag value is invalid, must be 0 or 1.");
  1201. return GE_GRAPH_OPTIONS_INVALID;
  1202. }
  1203. // ge.graphType.
  1204. options_.run_graph_flag = true;
  1205. ret = ParseOption(options, RUN_FLAG, options_.run_graph_flag);
  1206. if (ret != SUCCESS) {
  1207. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.runFlag value is invalid, must be 0 or 1.");
  1208. return GE_GRAPH_OPTIONS_INVALID;
  1209. }
  1210. // ge.graphType
  1211. ret = ParseTrainGraphFlag(options_.run_graph_flag, options_.train_graph_flag);
  1212. if (ret != SUCCESS) {
  1213. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.runFlag value is invalid");
  1214. return GE_GRAPH_OPTIONS_INVALID;
  1215. }
  1216. // parse FmkOp
  1217. options_.local_fmk_op_flag = false;
  1218. ret = ParseOption(options, LOCAL_FMKOP_FLAG, options_.local_fmk_op_flag);
  1219. if (ret != SUCCESS) {
  1220. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.localFmkopFlag value is invalid, must be 0 or 1.");
  1221. return GE_GRAPH_OPTIONS_INVALID;
  1222. }
  1223. options_.enable_print_op_pass = true;
  1224. ret = ParseOption(options, ENABLE_PRINT_OP_PASS, options_.enable_print_op_pass);
  1225. options_.is_single_op = false;
  1226. ret = ParseOption(options, SINGLE_OP_FLAG, options_.is_single_op);
  1227. GE_IF_BOOL_EXEC(ret != SUCCESS,
  1228. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.enablePrintOpPass value is invalid, must be 0 or 1.");
  1229. return GE_GRAPH_OPTIONS_INVALID);
  1230. // parse hcom parallel
  1231. options_.hcom_parallel = false;
  1232. ret = ParseOption(options, HCOM_PARALLEL, options_.hcom_parallel);
  1233. if (ret != SUCCESS) {
  1234. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:ge.hcomParallel value is invalid, must be 0 or 1.");
  1235. return GE_GRAPH_OPTIONS_INVALID;
  1236. }
  1237. // net output node dataType
  1238. ParseOption(options, OUTPUT_DATATYPE, options_.output_datatype);
  1239. // Set save_original_model flag (ge.save_original_model)
  1240. ParseOption(options, SAVE_ORIGINAL_MODEL, options_.save_original_model);
  1241. GELOGI("Set save original model flag %s", options_.save_original_model.c_str());
  1242. // Original model file name
  1243. ParseOption(options, ORIGINAL_MODEL_FILE, options_.original_model_file);
  1244. // Set Build model and step
  1245. ParseOption(options, BUILD_MODE, options_.build_mode);
  1246. ParseOption(options, BUILD_STEP, options_.build_step);
  1247. return SUCCESS;
  1248. }
  1249. Status GraphManager::ParseTrainGraphFlag(bool &options, bool &option) {
  1250. std::shared_ptr<GELib> ge_instance_ptr = ge::GELib::GetInstance();
  1251. if (ge_instance_ptr == nullptr) {
  1252. GELOGW("[Initialize] set train_graph_flag_ to 0 when GE is not initialized or finalized.");
  1253. option = false;
  1254. } else if (!ge_instance_ptr->isTrainMode()) {
  1255. option = false;
  1256. } else { // ge_instance_ptr->isTrainMode() is true
  1257. if (!options) {
  1258. GELOGE(GE_GRAPH_OPTIONS_INVALID,
  1259. "Key:ge.runFlag, its value %d is invalid, it must be 1 when GElib::is_train_mode_ flag is 1", options);
  1260. return GE_GRAPH_OPTIONS_INVALID;
  1261. }
  1262. option = true;
  1263. }
  1264. return SUCCESS;
  1265. }
  1266. bool GraphManager::IsPerfLevelInvalid(int32_t perf_level) {
  1267. return ((perf_level != static_cast<int32_t>(GEN_TASK_WITHOUT_L2FUSION)) &&
  1268. (perf_level != static_cast<int32_t>(GEN_TASK_WITHOUT_FUSION)) && (perf_level != -1));
  1269. }
  1270. void GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  1271. std::string &option) {
  1272. auto iter = options.find(key);
  1273. if (iter != options.end()) {
  1274. option = iter->second;
  1275. }
  1276. }
  1277. Status GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  1278. bool &option) {
  1279. auto iter = options.find(key);
  1280. if (iter != options.end()) {
  1281. string flag = iter->second;
  1282. if (flag == "0") {
  1283. option = false;
  1284. } else if (flag == "1") {
  1285. option = true;
  1286. } else {
  1287. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:%s, its value %s is invalid, it must be 0 or 1.", key.c_str(),
  1288. flag.c_str());
  1289. return GE_GRAPH_OPTIONS_INVALID;
  1290. }
  1291. }
  1292. return SUCCESS;
  1293. }
  1294. Status GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  1295. int &option) {
  1296. const int kDecimal = 10;
  1297. char *ptr = nullptr;
  1298. auto iter = options.find(key);
  1299. if (iter != options.end()) {
  1300. option = static_cast<int32_t>(std::strtol(iter->second.c_str(), &ptr, kDecimal));
  1301. if (ptr != nullptr && *ptr != '\0') {
  1302. GELOGE(GE_GRAPH_OPTIONS_INVALID, "Key:%s, its value %s is invalid, must be int32_t type.", key.c_str(),
  1303. iter->second.c_str());
  1304. return GE_GRAPH_OPTIONS_INVALID;
  1305. }
  1306. }
  1307. return SUCCESS;
  1308. }
  1309. void GraphManager::Trim(std::string &str) {
  1310. if (!str.empty()) {
  1311. auto it = str.find_first_not_of(" ");
  1312. if (it != std::string::npos) {
  1313. str.erase(0, it);
  1314. }
  1315. it = str.find_last_not_of(" ");
  1316. if (it != std::string::npos) {
  1317. str.erase(it + 1);
  1318. }
  1319. }
  1320. }
  1321. Status GraphManager::ParseOption(const std::map<std::string, std::string> &options, const std::string &key,
  1322. std::map<std::string, int> &option) {
  1323. auto iter = options.find(key);
  1324. if (iter == options.end()) {
  1325. return SUCCESS;
  1326. }
  1327. GELOGI("Start to parse %s", key.c_str());
  1328. option.clear();
  1329. std::string op_num = iter->second;
  1330. // split string by ','
  1331. std::vector<std::string> split;
  1332. std::istringstream f(op_num);
  1333. std::string str_tmp;
  1334. while (getline(f, str_tmp, ',')) {
  1335. split.push_back(str_tmp);
  1336. }
  1337. for (const std::string &engine_parallel : split) {
  1338. // split engine and num by :
  1339. size_t pos = engine_parallel.find(':');
  1340. if (pos == string::npos) {
  1341. GELOGE(GE_GRAPH_OPTIONS_INVALID,
  1342. "engine and num must be connected by :, "
  1343. "while your input is %s",
  1344. engine_parallel.c_str());
  1345. return GE_GRAPH_OPTIONS_INVALID;
  1346. }
  1347. std::string engine_name = engine_parallel.substr(0, pos);
  1348. std::string parallel_num = engine_parallel.substr(pos + 1);
  1349. Trim(engine_name);
  1350. Trim(parallel_num);
  1351. Status ret = CheckEngineName(engine_name, key, option);
  1352. if (ret != SUCCESS) {
  1353. GELOGE(GE_GRAPH_OPTIONS_INVALID, "check engine name : %s failed, ", engine_name.c_str());
  1354. return GE_GRAPH_OPTIONS_INVALID;
  1355. }
  1356. int num = 0;
  1357. ret = ParseParallelNum(parallel_num, key, num);
  1358. if (ret != SUCCESS) {
  1359. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parse parallel num failed");
  1360. return GE_GRAPH_OPTIONS_INVALID;
  1361. }
  1362. option.insert(std::make_pair(engine_name, num));
  1363. }
  1364. GELOGI("Parse %s successfully", key.c_str());
  1365. return SUCCESS;
  1366. }
  1367. Status GraphManager::CheckEngineName(const std::string &engine_name, const std::string &key,
  1368. const std::map<std::string, int> &option) {
  1369. if (engine_name.empty()) {
  1370. GELOGE(GE_GRAPH_OPTIONS_INVALID, "engine name of %s is empty", key.c_str());
  1371. return GE_GRAPH_OPTIONS_INVALID;
  1372. }
  1373. // judge whether exist in engine list
  1374. if (!GELib::GetInstance()->DNNEngineManagerObj().IsEngineRegistered(engine_name)) {
  1375. GELOGW("engine : %s is not registered in %s", engine_name.c_str(), key.c_str());
  1376. }
  1377. auto it_stream_repeat = option.find(engine_name);
  1378. if (it_stream_repeat != option.end()) {
  1379. GELOGE(GE_GRAPH_OPTIONS_INVALID, "engine : %s of %s is repeated", engine_name.c_str(), key.c_str());
  1380. return GE_GRAPH_OPTIONS_INVALID;
  1381. }
  1382. return SUCCESS;
  1383. }
  1384. Status GraphManager::ParseParallelNum(const std::string &parallel_num, const std::string &key, int &num) {
  1385. if (parallel_num.empty()) {
  1386. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num of %s is empty", key.c_str());
  1387. return GE_GRAPH_OPTIONS_INVALID;
  1388. }
  1389. for (char c : parallel_num) {
  1390. if (!isdigit(c)) {
  1391. GELOGE(GE_GRAPH_OPTIONS_INVALID, "%s input is invalid ", key.c_str());
  1392. return GE_GRAPH_OPTIONS_INVALID;
  1393. }
  1394. }
  1395. try {
  1396. num = std::stoi(parallel_num);
  1397. } catch (std::invalid_argument &) {
  1398. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s is invalid argument", parallel_num.c_str(), key.c_str());
  1399. return GE_GRAPH_OPTIONS_INVALID;
  1400. } catch (std::out_of_range &) {
  1401. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s is out of range", parallel_num.c_str(), key.c_str());
  1402. return GE_GRAPH_OPTIONS_INVALID;
  1403. } catch (...) {
  1404. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s is invalid argument", parallel_num.c_str(), key.c_str());
  1405. return GE_GRAPH_OPTIONS_INVALID;
  1406. }
  1407. if (num < 1) {
  1408. GELOGE(GE_GRAPH_OPTIONS_INVALID, "parallel num : %s of %s must bigger than 0", parallel_num.c_str(), key.c_str());
  1409. return GE_GRAPH_OPTIONS_INVALID;
  1410. }
  1411. return SUCCESS;
  1412. }
  1413. void GraphManager::AddGraphNode(GraphId graph_id, const GraphNodePtr &graph_node) {
  1414. std::lock_guard<std::mutex> lock(member_mutex_);
  1415. graph_map_.emplace(graph_id, graph_node);
  1416. }
  1417. void GraphManager::RemoveGraphNode(GraphId graph_id) {
  1418. std::lock_guard<std::mutex> lock(member_mutex_);
  1419. graph_map_.erase(graph_id);
  1420. }
  1421. bool GraphManager::HasGraphNode(GraphId graph_id) {
  1422. std::lock_guard<std::mutex> lock(member_mutex_);
  1423. return graph_map_.find(graph_id) != graph_map_.end();
  1424. }
  1425. Status GraphManager::GetGraphNode(const GraphId &graph_id, GraphNodePtr &out) {
  1426. std::lock_guard<std::mutex> lock(member_mutex_);
  1427. auto iter = graph_map_.find(graph_id);
  1428. if (iter == graph_map_.end()) {
  1429. out = nullptr;
  1430. GELOGE(GE_GRAPH_GRAPH_NOT_EXIST, "[GraphManager] graph not exist, graph_id= %u.", graph_id);
  1431. return GE_GRAPH_GRAPH_NOT_EXIST;
  1432. }
  1433. out = iter->second;
  1434. return SUCCESS;
  1435. }
  1436. Status GraphManager::GetVariable(const std::string &name, Tensor &val) {
  1437. GeTensorPtr ge_tensor_ptr = TensorAdapter::AsGeTensorPtr(val);
  1438. GE_CHECK_NOTNULL(ge_tensor_ptr);
  1439. return GetGraphContext()->GetVariableTensor(name, *(ge_tensor_ptr.get()));
  1440. }
  1441. Status GraphManager::SummaryHandle(const GraphId &graph_id, std::vector<GeTensor> &outputs) {
  1442. std::vector<GeTensor> without_summary_outputs;
  1443. std::set<int> summary_output_index;
  1444. GELOGI("[GraphManager] SummaryHandle, outputsSize=%zu.", outputs.size());
  1445. const std::map<uint32_t, std::map<string, size_t>> &whole_summary_output_indexes =
  1446. GetCompilerStages(graph_id).optimizer.GetSummaryOutputIndexes();
  1447. if (whole_summary_output_indexes.find(graph_id) == whole_summary_output_indexes.end()) {
  1448. GELOGE(FAILED, "No Summary graph found in map.");
  1449. return FAILED;
  1450. }
  1451. const std::map<string, size_t> &summary_output_indexes = whole_summary_output_indexes.at(graph_id);
  1452. GELOGI("[GraphManager] SummaryHandle, summaryOutputIndexesSize=%zu.", summary_output_indexes.size());
  1453. std::map<string, Tensor> summary_results;
  1454. for (auto iter = summary_output_indexes.begin(); iter != summary_output_indexes.end(); ++iter) {
  1455. GELOGI("[GraphManager] SummaryHandle, summaryName=%s, outputIndex=%zu.", iter->first.c_str(), iter->second);
  1456. summary_results.emplace(iter->first, TensorAdapter::AsTensor(outputs.at(iter->second)));
  1457. summary_output_index.emplace(iter->second);
  1458. }
  1459. // remove summary data from outputs
  1460. if (!summary_output_index.empty()) {
  1461. for (size_t j = 0; j < outputs.size(); ++j) {
  1462. if (summary_output_index.count(j) == 0) {
  1463. without_summary_outputs.emplace_back(outputs.at(j));
  1464. }
  1465. }
  1466. outputs.swap(without_summary_outputs);
  1467. GELOGI("[GraphManager] SummaryHandle, after swap outputsSize=%zu.", outputs.size());
  1468. }
  1469. if (!summary_results.empty()) {
  1470. return PushSummaryData2ME(graph_id, summary_results);
  1471. }
  1472. return SUCCESS;
  1473. }
  1474. Status GraphManager::CheckpointHandle(const GraphId &graph_id, const ComputeGraphPtr &compute_graph,
  1475. const std::vector<GeTensor> &outputs) {
  1476. GELOGI("[GraphManager] CheckpointHandle, outputsSize=%zu.", outputs.size());
  1477. std::vector<InputOutputDescInfo> outputs_desc = graph_executor_.GetOutputsDesc();
  1478. GELOGI("[GraphManager] CheckpointHandle, outputsDescSize=%zu.", outputs_desc.size());
  1479. std::map<string, Tensor> save_results;
  1480. NodePtr netoutput = nullptr;
  1481. for (const auto &node : compute_graph->GetAllNodes()) {
  1482. if (node->GetType() == kNetOutput) {
  1483. netoutput = node;
  1484. break;
  1485. }
  1486. }
  1487. if (netoutput == nullptr) {
  1488. GELOGE(FAILED, "Netoutput is null.");
  1489. return FAILED;
  1490. }
  1491. for (const auto &in : netoutput->GetAllInDataAnchors()) {
  1492. std::string desc_name;
  1493. auto out_anchor = in->GetPeerOutAnchor();
  1494. if (out_anchor == nullptr) {
  1495. GELOGE(FAILED, "out_anchor is null.");
  1496. return FAILED;
  1497. }
  1498. ge::NodePtr peer_node = out_anchor->GetOwnerNode();
  1499. // find the variable node in graph
  1500. while (peer_node != nullptr && peer_node->GetType() != kVariable) {
  1501. if (peer_node->GetAllInDataAnchors().size() != 1) {
  1502. GELOGE(FAILED, "More than one prior nodes of peer_node %s in checkpoint Graph.", peer_node->GetName().c_str());
  1503. return FAILED;
  1504. }
  1505. auto peer_node_in = peer_node->GetAllInDataAnchors().at(0);
  1506. auto peer_node_out_anchor = peer_node_in->GetPeerOutAnchor();
  1507. if (peer_node_out_anchor != nullptr) {
  1508. peer_node = peer_node_out_anchor->GetOwnerNode();
  1509. if (peer_node->GetType() == kVariable) {
  1510. break;
  1511. }
  1512. }
  1513. }
  1514. if (peer_node == nullptr) {
  1515. GELOGE(FAILED, "No variable op found in one branch, checkpoint graph illegal.");
  1516. return FAILED;
  1517. }
  1518. desc_name = peer_node->GetName();
  1519. GELOGI("[GraphManager] CheckpointHandle, descName=%s.", desc_name.c_str());
  1520. if (in->GetIdx() >= static_cast<int>(outputs.size())) {
  1521. GELOGE(FAILED, "variable index out of range.");
  1522. return FAILED;
  1523. }
  1524. save_results.emplace(desc_name, TensorAdapter::AsTensor(outputs.at(in->GetIdx())));
  1525. }
  1526. if (!save_results.empty()) {
  1527. return PushSaveData2ME(graph_id, save_results);
  1528. }
  1529. return SUCCESS;
  1530. }
  1531. Status GraphManager::RegisterCallBackFunc(
  1532. const std::string &key,
  1533. const std::function<Status(uint32_t, const std::map<std::string, ge::Tensor> &)> &callback) {
  1534. std::lock_guard<std::mutex> lock(member_mutex_);
  1535. GELOGI("[GraphManager] RegisterCallBackFunc, key=%s.", key.c_str());
  1536. me_callback_map_[key] = callback;
  1537. return SUCCESS;
  1538. }
  1539. Status GraphManager::PushSummaryData2ME(const GraphId &graph_id,
  1540. const std::map<std::string, ge::Tensor> &summary_data) {
  1541. std::lock_guard<std::mutex> lock(member_mutex_);
  1542. GELOGI("[GraphManager] PushSummaryData2ME, dataSize=%zu.", summary_data.size());
  1543. auto itr = me_callback_map_.find(kSummary);
  1544. if (itr == me_callback_map_.end()) {
  1545. GELOGE(FAILED, "[GraphManager] PushSummaryData2ME failed, not found summary callback.");
  1546. return FAILED;
  1547. }
  1548. return itr->second(graph_id, summary_data);
  1549. }
  1550. Status GraphManager::PushSaveData2ME(const GraphId &graph_id, const std::map<std::string, ge::Tensor> &save_data) {
  1551. std::lock_guard<std::mutex> lock(member_mutex_);
  1552. GELOGI("[GraphManager] PushSaveData2ME, dataSize=%zu.", save_data.size());
  1553. auto itr = me_callback_map_.find(kSave);
  1554. if (itr == me_callback_map_.end()) {
  1555. GELOGE(FAILED, "[GraphManager] PushSaveData2ME failed, not found checkpoint callback.");
  1556. return FAILED;
  1557. }
  1558. return itr->second(graph_id, save_data);
  1559. }
  1560. bool GraphManager::CheckNetOutputForCheckpointGraph(NodePtr &node) {
  1561. size_t in_data_anchor_size = node->GetAllInDataAnchors().size();
  1562. for (size_t i = 0; i < in_data_anchor_size; ++i) {
  1563. auto in = node->GetInDataAnchor(i);
  1564. if (in == nullptr) {
  1565. return false;
  1566. }
  1567. auto peerin = in->GetPeerOutAnchor();
  1568. GE_IF_BOOL_EXEC(peerin == nullptr, return false);
  1569. if (peerin->GetOwnerNode()->GetType() != kVariable && (!TransOpUtil::IsTransOp(peerin->GetOwnerNode()))) {
  1570. return false;
  1571. }
  1572. }
  1573. return true;
  1574. }
  1575. bool GraphManager::CheckVariableForCheckpointGraph(NodePtr &node) {
  1576. if (node->GetOpDesc()->HasAttr(kCheckPointForGetVar)) {
  1577. return false;
  1578. }
  1579. auto out = node->GetOutDataAnchor(0);
  1580. if (out == nullptr) {
  1581. GELOGE(GE_GRAPH_PARAM_NULLPTR, "out is nullptr.");
  1582. return false;
  1583. }
  1584. auto peer_out = out->GetPeerInDataAnchors();
  1585. for (size_t i = 0; i < peer_out.size(); ++i) {
  1586. if (peer_out.at(i)->GetOwnerNode()->GetType() != kNetOutput &&
  1587. (!TransOpUtil::IsTransOp(peer_out.at(i)->GetOwnerNode()))) {
  1588. return false;
  1589. }
  1590. }
  1591. return true;
  1592. }
  1593. bool GraphManager::CheckTransOpForCheckpointGraph(NodePtr &node) {
  1594. for (const auto &out_node : node->GetOutAllNodes()) {
  1595. if ((!TransOpUtil::IsTransOp(out_node)) && (out_node->GetType() != kNetOutput) && (out_node->GetType() != kSend)) {
  1596. return false;
  1597. }
  1598. }
  1599. for (const auto &in_node : node->GetInAllNodes()) {
  1600. if ((!TransOpUtil::IsTransOp(in_node)) && (in_node->GetType() != kVariable) && (in_node->GetType() != kRecv)) {
  1601. return false;
  1602. }
  1603. }
  1604. return true;
  1605. }
  1606. static inline bool CheckConstanOpForCheckpointGraph(NodePtr &node) { return node->GetOutDataNodes().empty(); }
  1607. bool GraphManager::IsCheckpointGraph(ComputeGraphPtr &compute_graph) {
  1608. if (compute_graph == nullptr) {
  1609. GELOGE(GE_GRAPH_PARAM_NULLPTR, "[IsCheckpointGraph] computeGraph is nullptr.");
  1610. return false;
  1611. }
  1612. for (auto &node : compute_graph->GetAllNodes()) {
  1613. OpDescPtr op = node->GetOpDesc();
  1614. GE_RT_FALSE_CHECK_NOTNULL(op);
  1615. if (op->GetType() == kNetOutput) {
  1616. if (!CheckNetOutputForCheckpointGraph(node)) {
  1617. return false;
  1618. }
  1619. } else if (op->GetType() == kVariable) {
  1620. if (!CheckVariableForCheckpointGraph(node)) {
  1621. return false;
  1622. }
  1623. } else if ((TransOpUtil::IsTransOp(node))) {
  1624. if (!CheckTransOpForCheckpointGraph(node)) {
  1625. return false;
  1626. }
  1627. } else if (op->GetType() == CONSTANTOP) {
  1628. if (!CheckConstanOpForCheckpointGraph(node)) {
  1629. return false;
  1630. }
  1631. } else if (op->GetType() != kSend && op->GetType() != kRecv) {
  1632. GELOGI("this node is not allow in checkpoint sub graph, node_type: %s, node_name: %s.", op->GetType().c_str(),
  1633. op->GetName().c_str());
  1634. return false;
  1635. }
  1636. }
  1637. GELOGI("current graph %s is checkpoint sub graph.", compute_graph->GetName().c_str());
  1638. return true;
  1639. }
  1640. bool GraphManager::IsBroadCastOpData(const ge::NodePtr &var_node) {
  1641. for (auto &out_anchor : var_node->GetAllOutDataAnchors()) {
  1642. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  1643. for (auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  1644. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1645. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  1646. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  1647. if (dst_node->GetType() == HCOMBROADCAST || dst_node->GetType() == HVDCALLBACKBROADCAST) {
  1648. return true;
  1649. }
  1650. }
  1651. }
  1652. return false;
  1653. }
  1654. void GraphManager::SetAttrForHcomBroadCastOp(ge::ComputeGraphPtr &compute_graph) {
  1655. // add variable attr for hccl broadcast,need to be removed after variable pass online
  1656. for (const ge::NodePtr &node : compute_graph->GetDirectNode()) {
  1657. if (node->GetOpDesc()->GetType() != ge::VARIABLE) {
  1658. continue;
  1659. }
  1660. if (IsBroadCastOpData(node)) {
  1661. AdjustBroadCastOpData(node);
  1662. }
  1663. if (IsAssignOpData(node)) {
  1664. AdjustAssignOpData(node);
  1665. }
  1666. }
  1667. }
  1668. void GraphManager::AdjustBroadCastOpData(const ge::NodePtr &var_node) {
  1669. if (!ge::AttrUtils::SetStr(var_node->GetOpDesc(), VAR_ATTR_VAR_IS_BROADCAST, "var_is_restore")) {
  1670. GELOGW("set var_is_restore failed");
  1671. }
  1672. }
  1673. bool GraphManager::IsAssignOpData(const ge::NodePtr &var_node) {
  1674. GELOGD("IsAssignOpData var_node %s", var_node->GetName().c_str());
  1675. std::map<std::string, std::set<int>> assign_ops = {{ASSIGN, {0}}};
  1676. ge::NodePtr assign_node = nullptr;
  1677. if (ConfirmUseOpAndIndexByNode(var_node, assign_ops, assign_node)) {
  1678. return true;
  1679. }
  1680. return false;
  1681. }
  1682. void GraphManager::AdjustAssignOpData(const ge::NodePtr &var_node) {
  1683. if (!ge::AttrUtils::SetStr(var_node->GetOpDesc(), VAR_ATTR_VAR_IS_RESTORE, "var_is_restore")) {
  1684. GELOGW("SetStr var_is_restore failed");
  1685. }
  1686. }
  1687. bool GraphManager::ConfirmUseOpAndIndexByAnchor(const ge::InDataAnchorPtr &in_anchor,
  1688. const map<string, std::set<int>> &confirm_ops, ge::NodePtr &use_node) {
  1689. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1690. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  1691. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  1692. ge::OpDescPtr dst_op_desc = dst_node->GetOpDesc();
  1693. GE_RT_FALSE_CHECK_NOTNULL(dst_op_desc);
  1694. const string &dst_type = dst_op_desc->GetType();
  1695. int input_index = in_anchor->GetIdx();
  1696. GELOGD("ConfirmUseOpAndIndex, var name %s, dst_type = %s, input index %d", dst_node->GetName().c_str(),
  1697. dst_type.c_str(), input_index);
  1698. if (confirm_ops.count(dst_type) > 0) {
  1699. if (confirm_ops.at(dst_type).count(input_index) > 0) {
  1700. use_node = dst_node;
  1701. return true;
  1702. }
  1703. }
  1704. return false;
  1705. }
  1706. bool GraphManager::ConfirmUseOpAndIndexByNode(const ge::NodePtr &var_node,
  1707. const map<string, std::set<int>> &confirm_ops, ge::NodePtr &use_node) {
  1708. GE_RT_FALSE_CHECK_NOTNULL(var_node);
  1709. for (auto &out_anchor : var_node->GetAllOutDataAnchors()) {
  1710. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  1711. for (auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  1712. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  1713. if (ConfirmUseOpAndIndexByAnchor(in_anchor, confirm_ops, use_node)) {
  1714. return true;
  1715. }
  1716. }
  1717. }
  1718. return false;
  1719. }
  1720. Status GraphManager::RemoveIsolatedConstInThisGraph(ge::ComputeGraphPtr &compute_graph) {
  1721. for (ge::NodePtr &n : compute_graph->GetDirectNode()) {
  1722. if (n->GetOpDesc() == nullptr) {
  1723. continue;
  1724. }
  1725. if (n->GetOpDesc()->GetType() == CONSTANT || n->GetOpDesc()->GetType() == CONSTANTOP) {
  1726. // reset const type depend on train_flag
  1727. options_.train_graph_flag ? n->GetOpDesc()->SetType(CONSTANTOP) : n->GetOpDesc()->SetType(CONSTANT);
  1728. if (n->GetOutAllNodes().empty() && n->GetInAllNodes().empty()) {
  1729. // it is an isolated constant, just remove it
  1730. if (GraphUtils::RemoveJustNode(compute_graph, n) != GRAPH_SUCCESS) {
  1731. GELOGE(FAILED, "remove constant %s failed.", n->GetName().c_str());
  1732. return FAILED;
  1733. }
  1734. }
  1735. }
  1736. }
  1737. return SUCCESS;
  1738. }
  1739. Status GraphManager::RemoveIsolatedConst(ge::ComputeGraphPtr &compute_graph) {
  1740. GE_CHK_STATUS_RET(RemoveIsolatedConstInThisGraph(compute_graph));
  1741. for (auto &sub_graph : compute_graph->GetAllSubgraphs()) {
  1742. GE_CHK_STATUS_RET(RemoveIsolatedConstInThisGraph(sub_graph));
  1743. }
  1744. return SUCCESS;
  1745. }
  1746. Status GraphManager::OptimizeStage1(ge::ComputeGraphPtr &compute_graph) {
  1747. string options = "default";
  1748. if (GetContext().GetOption("ge.exec.variable_acc", options) != SUCCESS) {
  1749. GELOGI("get ge.exec.variable_acc failed. set default value.");
  1750. }
  1751. PassManager after_merge_passes;
  1752. GE_CHK_STATUS_RET(
  1753. after_merge_passes.AddPass("OptimizeStage1_1::MergeInputMemcpyPass", new (std::nothrow) MergeInputMemcpyPass));
  1754. GE_CHK_STATUS_RET(
  1755. after_merge_passes.AddPass("OptimizeStage1_1::SwitchDataEdgesBypass", new (std::nothrow) SwitchDataEdgesBypass));
  1756. GE_CHK_STATUS_RET(
  1757. after_merge_passes.AddPass("OptimizeStage1_1::ConstantFuseSamePass", new (std::nothrow) ConstantFuseSamePass));
  1758. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::CommonSubexpressionEliminationPass",
  1759. new (std::nothrow) CommonSubexpressionEliminationPass));
  1760. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::PermutePass", new (std::nothrow) PermutePass))
  1761. /*
  1762. * The SameTransdataBreadthFusionPass should be called before VariableOpPass, because of the scene following:
  1763. * node3
  1764. * |
  1765. * transdata1 node2
  1766. * | |
  1767. * cast1 transdata2
  1768. * \ /
  1769. * var
  1770. * the node `transdata1` should be moved to the front of the ndoe `cast1`,
  1771. * to ensure that `transdata1` and `transdata2` can be fusion with `var`.
  1772. * But it is a temp solution, because the `SameTransdataBreadthFusionPass`
  1773. * can only move `TransData` but not `Cast` nodes.
  1774. * So if we exchange Cast and TransData, the fusion mechanism will fail.
  1775. */
  1776. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::SameTransdataBreadthFusionPass",
  1777. new (std::nothrow) SameTransdataBreadthFusionPass))
  1778. GE_IF_BOOL_EXEC(options == "default" || options == "1", GELOGI("turn on variable accelerator");
  1779. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::VariableOpPass",
  1780. new (std::nothrow) VariableOpPass(&var_acc_ctrl_))))
  1781. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::TransOpWithoutReshapeFusionPass",
  1782. new (std::nothrow) TransOpWithoutReshapeFusionPass))
  1783. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage1_1::TransOpBreadthFusionPass",
  1784. new (std::nothrow) TransOpBreadthFusionPass))
  1785. GE_TIMESTAMP_START(after_merge_passes);
  1786. auto ret = after_merge_passes.Run(compute_graph);
  1787. GE_TIMESTAMP_END(after_merge_passes, "GraphManager::OptimizeStage1_1");
  1788. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1789. GELOGE(ret, "Run passes when OptimizeStage1_1 failed, ret:%u.", ret);
  1790. return ret;
  1791. }
  1792. GE_DUMP(compute_graph, "OptimizeStage1_1");
  1793. NamesToPass names_to_passes;
  1794. TransOpNearbyAllreduceFusionPass trans_op_nearby_allreduce_fusion_pass;
  1795. ReshapeRemovePass reshape_remove_pass;
  1796. ConstantFoldingPass constant_folding_pass;
  1797. DimensionAdjustPass dimension_adjust_pass;
  1798. EnterPass enter_pass;
  1799. AddNPass addn_pass;
  1800. SwitchDeadBranchElimination switch_dead_branch_elimination;
  1801. SwitchLogicRemovePass switch_logic_remove_pass;
  1802. MergePass merge_pass;
  1803. CastRemovePass cast_remove_pass;
  1804. TransposeTransDataPass transpose_transdata_pass;
  1805. TransOpSymmetryEliminationPass symmetry_elimination_pass;
  1806. DimensionComputePass dimension_compute_pass;
  1807. names_to_passes.emplace_back("EnterPass", &enter_pass);
  1808. names_to_passes.emplace_back("AddNPass", &addn_pass);
  1809. names_to_passes.emplace_back("SwitchDeadBranchElimination", &switch_dead_branch_elimination);
  1810. names_to_passes.emplace_back("SwitchLogicRemovePass", &switch_logic_remove_pass);
  1811. names_to_passes.emplace_back("MergePass", &merge_pass);
  1812. names_to_passes.emplace_back("CastRemovePass", &cast_remove_pass);
  1813. names_to_passes.emplace_back("TransposeTransDataPass", &transpose_transdata_pass);
  1814. names_to_passes.emplace_back("ReshapeRemovePass", &reshape_remove_pass);
  1815. names_to_passes.emplace_back("TransOpSymmetryEliminationPass", &symmetry_elimination_pass);
  1816. names_to_passes.emplace_back("TransOpNearbyAllreduceFusionPass", &trans_op_nearby_allreduce_fusion_pass);
  1817. names_to_passes.emplace_back("DimensionComputePass", &dimension_compute_pass);
  1818. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1819. names_to_passes.emplace_back("DimensionAdjustPass", &dimension_adjust_pass);
  1820. GE_TIMESTAMP_START(names_to_passes);
  1821. ret = GEPass(compute_graph).Run(names_to_passes);
  1822. GE_TIMESTAMP_END(names_to_passes, "GraphManager::OptimizeStage1_2");
  1823. if (ret != SUCCESS) {
  1824. GELOGE(ret, "Run passes when OptimizeStage1_2 failed, ret:%u.", ret);
  1825. return ret;
  1826. }
  1827. // Calculate Op/Fe constantfolding cost
  1828. uint64_t op_constant_folding_cost = 0;
  1829. for (auto &it : constant_folding_pass.GetOpConstantFoldingPerfStatistic()) {
  1830. op_constant_folding_cost += it.second.second;
  1831. GELOGI("The time cost of %s constant folding is [%lu] micro second, calls is %lu.",
  1832. it.first.c_str(), it.second.second, it.second.first);
  1833. }
  1834. GEEVENT("[GEPERFTRACE] The time cost of extern constant folding is [%lu] micro second.", op_constant_folding_cost);
  1835. for (auto &it : constant_folding_pass.GetGeConstantFoldingPerfStatistic()) {
  1836. op_constant_folding_cost += it.second.second;
  1837. GELOGI("The time cost of %s constant folding is [%lu] micro second, calls is %lu.",
  1838. it.first.c_str(), it.second.second, it.second.first);
  1839. }
  1840. GE_DUMP(compute_graph, "OptimizeStage1_2");
  1841. PassManager graph_pass;
  1842. // the prune pass should between SwitchPass and SwitchToStreamSwitchPass
  1843. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::Migration", new (std::nothrow) SubgraphConstMigrationPass));
  1844. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::ArgsClean", new (std::nothrow) UnusedArgsCleanPass));
  1845. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::PrunePass", new (std::nothrow) PrunePass))
  1846. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::NextIterationPass", new (std::nothrow) NextIterationPass))
  1847. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::ControlTriggerPass", new (std::nothrow) ControlTriggerPass))
  1848. GE_CHK_STATUS_RET(
  1849. graph_pass.AddPass("OptimizeStage1_3::MergeToStreamMergePass", new (std::nothrow) MergeToStreamMergePass))
  1850. GE_CHK_STATUS_RET(
  1851. graph_pass.AddPass("OptimizeStage1_3::SwitchToStreamSwitchPass", new (std::nothrow) SwitchToStreamSwitchPass))
  1852. GE_CHK_STATUS_RET(
  1853. graph_pass.AddPass("OptimizeStage1_3::AttachStreamLabelPass", new (std::nothrow) AttachStreamLabelPass))
  1854. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::MultiBatchPass", new (std::nothrow) MultiBatchPass(true)))
  1855. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::IteratorOpPass", new (std::nothrow) IteratorOpPass))
  1856. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::VariableRefUselessControlOutDeletePass",
  1857. new (std::nothrow) VariableRefUselessControlOutDeletePass))
  1858. GE_CHK_STATUS_RET(graph_pass.AddPass("OptimizeStage1_3::ReshapeRecoveryPass", new (std::nothrow) ReshapeRecoveryPass))
  1859. if (options_.train_graph_flag) {
  1860. // Priority: The GlobalStepInsertPass should work before graph partitioner.
  1861. // Reason: Make sure that the var "global_step" can be partitioned to known sub graph and allocated memory
  1862. GE_CHK_STATUS_RET(
  1863. graph_pass.AddPass("OptimizeStage1_3::GlobalStepInsertPass", new (std::nothrow) GlobalStepInsertPass))
  1864. }
  1865. GE_TIMESTAMP_START(graph_pass);
  1866. ret = graph_pass.Run(compute_graph);
  1867. GE_TIMESTAMP_END(graph_pass, "GraphManager::OptimizeStage1_3");
  1868. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1869. GELOGE(ret, "Run passes when OptimizeStage1_3 failed, ret:%u.", ret);
  1870. return ret;
  1871. }
  1872. NamesToPass identity_remove_pass;
  1873. GE_TIMESTAMP_START(identity_remove_pass);
  1874. IdentityPass identity_force_pass(false); // after SwitchToStreamSwitchPass
  1875. identity_remove_pass.emplace_back("IdentityPass", &identity_force_pass);
  1876. ret = GEPass(compute_graph).Run(identity_remove_pass);
  1877. GE_TIMESTAMP_END(identity_remove_pass, "GraphPrepare::IdentityRemovePass");
  1878. if (ret != SUCCESS) {
  1879. GELOGE(ret, "Run identity remove pass for preprocess failed, ret:%u.", ret);
  1880. return ret;
  1881. }
  1882. return SUCCESS;
  1883. }
  1884. Status GraphManager::OptimizeStage2(ge::ComputeGraphPtr &compute_graph) {
  1885. GELOGI("Start optimize after merge sub graph.");
  1886. PassManager after_merge_passes;
  1887. GE_CHK_STATUS_RET(after_merge_passes.AddPass("OptimizeStage2::AfterMergePasses::LinkGenMaskNodesPass",
  1888. new (std::nothrow)
  1889. LinkGenMaskNodesPass(options_.stream_max_parallel_num)));
  1890. GE_TIMESTAMP_START(after_merge_passes);
  1891. auto ret = after_merge_passes.Run(compute_graph);
  1892. GE_TIMESTAMP_END(after_merge_passes, "OptimizeStage2::AfterMergePasses");
  1893. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1894. GELOGE(ret, "Run passes after merge sub graph failed, ret:%d.", ret);
  1895. return ret;
  1896. }
  1897. SetAttrForHcomBroadCastOp(compute_graph);
  1898. NamesToPass names_to_passes;
  1899. ConstantFoldingPass constant_folding_pass;
  1900. ReshapeRemovePass reshape_remove_pass;
  1901. CondRemovePass condition_remove_pass;
  1902. BitcastPass bitcast_pass;
  1903. names_to_passes.emplace_back("ConstantFoldingPass", &constant_folding_pass);
  1904. names_to_passes.emplace_back("ReshapeRemovePass", &reshape_remove_pass);
  1905. names_to_passes.emplace_back("CondRemovePass", &condition_remove_pass);
  1906. names_to_passes.emplace_back("BitcastPass", &bitcast_pass);
  1907. GE_TIMESTAMP_START(names_to_passes);
  1908. ret = GEPass(compute_graph).Run(names_to_passes);
  1909. GE_TIMESTAMP_END(names_to_passes, "OptimizeStage2::MergedGraphNameToPasses");
  1910. if (ret != SUCCESS) {
  1911. GELOGE(ret, "Run ge_passes optimize for OptimizeAfterMergeSubGraph failed, ret:%d.", ret);
  1912. return ret;
  1913. }
  1914. ret = RemoveIsolatedConst(compute_graph);
  1915. if (ret != SUCCESS) {
  1916. GELOGE(ret, "Remove isolated Constant failed, ret:%d.", ret);
  1917. return ret;
  1918. }
  1919. PassManager pass_for_control_attr_optimize;
  1920. if (options_.train_graph_flag) {
  1921. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::FlowCtrlPass",
  1922. new (std::nothrow) FlowCtrlPass))
  1923. }
  1924. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::MultiBatchPass",
  1925. new (std::nothrow) MultiBatchPass))
  1926. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::RefIdentityDeleteOpPass",
  1927. new (std::nothrow) RefIdentityDeleteOpPass))
  1928. // the value of the attr is the original variable name the ref-variable ref from.
  1929. // The attr will be used when allocating memory,
  1930. // the node marked attr will be output to a variable instead of new-allocated memory.
  1931. // Therefore, ComputeGraph should not delete nodes after `VariableRefDeleteOpPass`
  1932. // to prevent unexpected deletion of nodes marked with attr
  1933. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::VariableRefDeleteOpPass",
  1934. new (std::nothrow) VariableRefDeleteOpPass))
  1935. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::CompileNodesPass",
  1936. new (std::nothrow) CompileNodesPass))
  1937. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass(
  1938. "OptimizeStage2::AfterMergePasses::MarkGraphUnknownStatusPass", new(std::nothrow) MarkGraphUnknownStatusPass))
  1939. GE_CHK_STATUS_RET(
  1940. pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::InputOutputConnectionIdentifyPass",
  1941. new (std::nothrow) InputOutputConnectionIdentifyPass))
  1942. // When the input node to be cleared is after a `Data` node, the atomic-clean-node should not be inserted.
  1943. // So The ComputeGraph should not delete nodes after `AtomicAddrCleanPass`
  1944. // to prevent unexpected deletion of nodes after a `Data` node
  1945. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::AtomicAddrCleanPass",
  1946. new (std::nothrow) AtomicAddrCleanPass))
  1947. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::AfterMergePasses::"
  1948. "EndOfSequenceAddControlPass",
  1949. new (std::nothrow) EndOfSequenceAddControlPass))
  1950. // SubgraphPass solves memory_assign_conflicts by insert MemcpyAsync node, which depends on multi attrs and
  1951. // graph-structure. So try not to add new pass after SubgraphPass.
  1952. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::SubgraphPass",
  1953. new (std::nothrow) SubgraphPass))
  1954. // AttachStreamLabelPass modifies attr without changing structure of compute_graph
  1955. GE_CHK_STATUS_RET(pass_for_control_attr_optimize.AddPass("OptimizeStage2::ControlAttrOptimize::AttachStreamLabelPass",
  1956. new (std::nothrow) AttachStreamLabelPass))
  1957. GE_TIMESTAMP_START(pass_for_control_attr_optimize);
  1958. ret = pass_for_control_attr_optimize.Run(compute_graph);
  1959. GE_TIMESTAMP_END(pass_for_control_attr_optimize, "OptimizeStage2::ControlAttrOptimize");
  1960. if (ret != SUCCESS && ret != NOT_CHANGED) {
  1961. GELOGE(ret, "Run passes when optimize stage 2 failed");
  1962. return ret;
  1963. }
  1964. // After while sub graph handle, mark all node rw type
  1965. auto result = GetCompilerStages(compute_graph->GetGraphID()).optimizer.HandleMemoryRWConflict(compute_graph);
  1966. if (result != SUCCESS) {
  1967. GELOGW(
  1968. "Mark node rw type failed. It will take some effect on memory_assign_conflicts handling."
  1969. "Please pay attention to it.");
  1970. }
  1971. ChangeConstTypeWhenTraining(compute_graph);
  1972. ret = compute_graph->TopologicalSorting();
  1973. if (ret != SUCCESS) {
  1974. GELOGE(ret, "Graph topological sort failed, ret:%d.", ret);
  1975. return ret;
  1976. }
  1977. GELOGI("End optimize after merge sub graph.");
  1978. return SUCCESS;
  1979. }
  1980. void GraphManager::ChangeConstTypeWhenTraining(const ComputeGraphPtr &compute_graph) {
  1981. // The constant for train is CONSTANTOP, and is CONSTANT for inference. They will be unified in future.
  1982. if (options_.train_graph_flag) {
  1983. for (NodePtr &n : compute_graph->GetAllNodes()) {
  1984. // This can ensure that n is not a null pointer
  1985. if (n->GetOpDesc()->GetType() == CONSTANT) {
  1986. n->GetOpDesc()->SetType(CONSTANTOP);
  1987. }
  1988. }
  1989. }
  1990. }
  1991. Status GraphManager::LoadGraphAsync(const GeRootModelPtr &ge_root_model, const GraphNodePtr &graph_node) {
  1992. GELOGI("[LoadGraphAsync] run_graph_flag[%d], graph_id[%u]", options_.run_graph_flag, graph_node->GetGraphId());
  1993. if (options_.run_graph_flag && ge_root_model != nullptr) {
  1994. // synchronization run graph with model
  1995. ModelIdInfo model_id_info;
  1996. bool is_unknown_shape = false;
  1997. GE_CHK_STATUS_RET(ge_root_model->CheckIsUnknownShape(is_unknown_shape));
  1998. if (!is_unknown_shape) {
  1999. if (getenv(kEnvGeuseStaticMemory) != nullptr) {
  2000. GELOGI("[LoadGraphAsync] GE_USE_STATIC_MEMORY is seted.");
  2001. } else {
  2002. auto root_graph = ge_root_model->GetRootGraph();
  2003. GE_CHECK_NOTNULL(root_graph);
  2004. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  2005. GeModelPtr ge_model = name_to_model[root_graph->GetName()];
  2006. GE_CHK_STATUS_RET(CheckAndReleaseMemory(ge_model, graph_node));
  2007. }
  2008. }
  2009. GE_TIMESTAMP_START(LoadGraph);
  2010. GE_CHECK_NOTNULL(graph_node->graph_run_async_listener_);
  2011. Status ret =
  2012. GraphLoader::LoadModelOnline(model_id_info.model_id, ge_root_model, graph_node->graph_run_async_listener_);
  2013. GE_TIMESTAMP_EVENT_END(LoadGraph, "GraphManager::LoadGraphAsync");
  2014. if (ret != SUCCESS) {
  2015. GELOGE(ret, "[LoadGraphAsync] LoadGraphAsync Failed");
  2016. graph_node->SetRunFlag(false);
  2017. return ret;
  2018. }
  2019. graph_node->SetLoadFlag(true);
  2020. ge_root_model->SetModelId(model_id_info.model_id);
  2021. graph_node->SetGeRootModel(ge_root_model);
  2022. }
  2023. return SUCCESS;
  2024. }
  2025. Status GraphManager::CheckAndReleaseMemory(const GeModelPtr &ge_model, const GraphNodePtr &graph_node) {
  2026. GELOGI("CheckAndReleaseMemory graph_id[%u]", graph_node->GetGraphId());
  2027. int64_t value = 0;
  2028. bool ret = ge::AttrUtils::GetInt(ge_model, ATTR_MODEL_MEMORY_SIZE, value);
  2029. int64_t memory_size = ret ? value : 0;
  2030. ret = ge::AttrUtils::GetInt(ge_model, ATTR_MODEL_WEIGHT_SIZE, value);
  2031. int64_t weight_size = ret ? value : 0;
  2032. ret = ge::AttrUtils::GetInt(ge_model, MODEL_ATTR_SESSION_ID, value);
  2033. uint64_t session_id = ret ? value : 0;
  2034. int64_t free_memory = 0;
  2035. Status result = GraphLoader::GetMemoryInfo(free_memory);
  2036. if (result != SUCCESS) {
  2037. return result;
  2038. }
  2039. GELOGI(
  2040. "CheckAndReleaseMemory Graph[%u] need memory_size[%ld], weight_size[%ld],"
  2041. " Device[%u] free_memory_size[%ld]",
  2042. graph_node->GetGraphId(), memory_size, weight_size, GetContext().DeviceId(), free_memory);
  2043. if (ge::CheckInt64AddOverflow(memory_size, weight_size) != SUCCESS) {
  2044. GELOGE(INTERNAL_ERROR, "The sum of Memory size and weight size exceeds INT64_MAX");
  2045. return INTERNAL_ERROR;
  2046. }
  2047. if (free_memory >= (memory_size + weight_size)) {
  2048. return SUCCESS;
  2049. }
  2050. std::lock_guard<std::mutex> lock(unload_model_mutex_);
  2051. std::map<GraphId, GraphNodePtr> graph_map;
  2052. {
  2053. std::lock_guard<std::mutex> lock(member_mutex_);
  2054. graph_map = graph_map_;
  2055. }
  2056. for (auto &it : graph_map) {
  2057. auto graph_id = it.second->GetGraphId();
  2058. auto model = it.second->GetGeRootModel();
  2059. if (model == nullptr) {
  2060. continue;
  2061. }
  2062. auto model_id = model->GetModelId();
  2063. // not loaded,no need unload
  2064. if (!it.second->GetLoadFlag()) {
  2065. GELOGI("CheckAndReleaseMemory graph[%u] has not been loaded.", graph_id);
  2066. continue;
  2067. }
  2068. uint64_t max_memory_size = 0;
  2069. result = GraphLoader::GetMaxUsedMemory(model_id, max_memory_size);
  2070. if (result != SUCCESS) {
  2071. continue;
  2072. }
  2073. GELOGI("CheckAndReleaseMemory try to UnloadGraph[%u], model[%u] which MaxUsedMemory[%lu].", graph_id, model_id,
  2074. max_memory_size);
  2075. rtError_t rt_ret = rtSetDevice(GetContext().DeviceId());
  2076. if (rt_ret != RT_ERROR_NONE) {
  2077. GELOGE(RT_FAILED, "[GraphManager:] rtSetDevice failed, modelId=%u, graphId=%u.", model_id, graph_id);
  2078. continue;
  2079. }
  2080. result = GraphLoader::UnloadModel(model_id);
  2081. if (result != SUCCESS) {
  2082. GELOGW("[GraphManager:] unload model failed, modelId=%u, graphId=%u.", model_id, graph_id);
  2083. }
  2084. result = GraphLoader::DestroyAicpuKernel(session_id, model_id);
  2085. if (result != SUCCESS) {
  2086. GELOGW("[GraphManager:] destroy aicpu kernel failed when dynamic memory, modelId=%u, graphId=%u.", model_id,
  2087. graph_id);
  2088. }
  2089. rt_ret = rtDeviceReset(GetContext().DeviceId());
  2090. if (rt_ret != RT_ERROR_NONE) {
  2091. GELOGE(RT_FAILED, "[GraphManager:] rtDeviceReset failed, modelId=%u, graphId=%u.", model_id, graph_id);
  2092. continue;
  2093. }
  2094. it.second->SetLoadFlag(false);
  2095. GELOGI("CheckAndReleaseMemory UnloadGraph[%u], model[%u] success and set LoadFlag to false.", graph_id, model_id);
  2096. }
  2097. return SUCCESS;
  2098. }
  2099. Status GraphManager::ProcessSubGraphWithMultiThreads(GraphManager *graph_manager, GraphId root_graph_id,
  2100. const SubGraphInfoPtr &sub_graph_info_ptr, uint64_t session_id,
  2101. const GEThreadLocalContext &ge_context) {
  2102. if (sub_graph_info_ptr != nullptr && graph_manager != nullptr) {
  2103. GetContext().SetSessionId(session_id);
  2104. GetThreadLocalContext() = ge_context;
  2105. graph_manager->UpdateLocalOmgContext(root_graph_id);
  2106. ComputeGraphPtr compute_graph_tmp = sub_graph_info_ptr->GetSubGraph();
  2107. const std::string &engine_name = sub_graph_info_ptr->GetEngineName();
  2108. GELOGI("ProcessSubGraphWithMultiThreads start, graph name is %s, engine_name is %s, thread id is %lu",
  2109. compute_graph_tmp != nullptr ? compute_graph_tmp->GetName().c_str() : "", engine_name.c_str(),
  2110. pthread_self());
  2111. GE_DUMP(compute_graph_tmp, "OptimizeSubGraphBefore");
  2112. GE_CHECK_NOTNULL(compute_graph_tmp);
  2113. compute_graph_tmp->SetSessionID(session_id);
  2114. Status ret = graph_manager->GetCompilerStages(root_graph_id).optimizer.OptimizeSubGraph(compute_graph_tmp,
  2115. engine_name);
  2116. if (ret != SUCCESS) {
  2117. GELOGE(ret, "SubGraph optimize Failed %s", engine_name.c_str());
  2118. return ret;
  2119. } else {
  2120. GELOGI("SubGraph optimize success %s", engine_name.c_str());
  2121. }
  2122. GE_DUMP(compute_graph_tmp, "OptimizeSubGraphAfter");
  2123. sub_graph_info_ptr->SetSubGraph(compute_graph_tmp);
  2124. GELOGI("ProcessSubGraphWithMultiThreads end, graph name is %s, engine_name is %s, thread id is %lu",
  2125. compute_graph_tmp != nullptr ? compute_graph_tmp->GetName().c_str() : "", engine_name.c_str(),
  2126. pthread_self());
  2127. } else {
  2128. GELOGE(FAILED, "graph_manager or sub_graph_info_ptr is nullptr");
  2129. return FAILED;
  2130. }
  2131. return SUCCESS;
  2132. }
  2133. // run graph async on session
  2134. Status GraphManager::RunGraphAsync(const GraphId &graph_id, const std::vector<ge::InputTensorInfo> &inputs,
  2135. uint64_t session_id, RunAsyncCallback callback) {
  2136. GELOGI("[GraphManager] Start to run graph async, graph_id=%u, inputsSize=%zu.", graph_id, inputs.size());
  2137. bool ret = prerun_args_q_.Push(PreRunArgs({graph_id, inputs, session_id, GetThreadLocalContext(), callback}));
  2138. if (!ret) {
  2139. GELOGE(FAILED, "[GraphManager] Run graph async failed, graph_id=%u.", graph_id);
  2140. return FAILED;
  2141. }
  2142. GELOGI("[GraphManager] Run graph async success, graph_id=%u.", graph_id);
  2143. return SUCCESS;
  2144. }
  2145. void GraphManager::AddModelCacheHelperToMap(const GraphId &graph_id, uint64_t session_id,
  2146. ComputeGraphPtr &compute_graph) {
  2147. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  2148. if (instance_ptr != nullptr && instance_ptr->IsIncreBuild()) {
  2149. std::lock_guard<std::mutex> lock(member_mutex_);
  2150. auto iter = cache_helper_map_.find(graph_id);
  2151. if (iter == cache_helper_map_.end()) {
  2152. ModelCacheHelperPtr cache_helper = MakeShared<ge::ModelCacheHelper>(session_id, graph_id, compute_graph);
  2153. if (cache_helper != nullptr) {
  2154. cache_helper_map_.emplace(std::make_pair(graph_id, cache_helper));
  2155. } else {
  2156. GELOGW("Cache helper make shared failed, graph_id = %u.", graph_id);
  2157. }
  2158. }
  2159. }
  2160. }
  2161. ModelCacheHelperPtr GraphManager::FindModelCacheHelper(GraphId graph_id) {
  2162. std::lock_guard<std::mutex> lock(member_mutex_);
  2163. auto iter = cache_helper_map_.find(graph_id);
  2164. if (iter != cache_helper_map_.end()) {
  2165. return iter->second;
  2166. }
  2167. return nullptr;
  2168. }
  2169. Status GraphManager::IncreBuild(const GraphNodePtr &graph_node, GeModelPtr &ge_model) {
  2170. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  2171. if (instance_ptr == nullptr || !instance_ptr->IsIncreBuild()) {
  2172. return FAILED;
  2173. }
  2174. const uint32_t graph_id = graph_node->GetGraphId();
  2175. ModelCacheHelperPtr cache_helper = FindModelCacheHelper(graph_id);
  2176. if (cache_helper == nullptr) {
  2177. GELOGW("Can not find ModelCacheHelper of graph[%u]", graph_id);
  2178. return FAILED;
  2179. }
  2180. if (cache_helper->IsModelCacheHit()) {
  2181. GEEVENT("Model cache hit.");
  2182. Status ret = LoadFromCache(graph_node, cache_helper, ge_model);
  2183. if (ret == SUCCESS) {
  2184. return SUCCESS;
  2185. } else {
  2186. GELOGW("Error occurred when load from cache, abandon.");
  2187. }
  2188. } else {
  2189. GEEVENT("Model cache miss.");
  2190. }
  2191. if (SaveCacheBeforeBuild(graph_node->GetGraphId(), cache_helper) != SUCCESS) {
  2192. GELOGW("Error occurred when save cache.");
  2193. }
  2194. return FAILED;
  2195. }
  2196. void GraphManager::ConstructGeInput(std::vector<ge::GeTensor> &ge_inputs, PreRunArgs &args) {
  2197. for (auto const &input : args.input_tensor) {
  2198. std::vector<int64_t> input_dims;
  2199. std::transform(input.dims.begin(), input.dims.end(), std::back_inserter(input_dims),
  2200. [](int64_t x) -> int64_t { return x; });
  2201. GeShape input_shape(input_dims);
  2202. GeTensorDesc input_tensor_desc;
  2203. input_tensor_desc.SetShape(input_shape);
  2204. input_tensor_desc.SetDataType(static_cast<ge::DataType>(input.data_type));
  2205. ge_inputs.emplace_back(input_tensor_desc);
  2206. }
  2207. }
  2208. void GraphManager::PreRunThread(GraphManager *graph_manager) {
  2209. if (prctl(PR_SET_NAME, ("GE_PreRun")) != 0) {
  2210. GELOGW("Set thread name failed.");
  2211. }
  2212. PreRunArgs args;
  2213. while (graph_manager->thread_run_flag_) {
  2214. bool pop_status = graph_manager->prerun_args_q_.Pop(args);
  2215. if (!pop_status) {
  2216. continue;
  2217. }
  2218. GELOGI("A new loop start.");
  2219. GetContext().SetSessionId(args.session_id);
  2220. GetThreadLocalContext() = args.context;
  2221. graph_manager->UpdateLocalOmgContext(args.graph_id);
  2222. std::vector<ge::GeTensor> ge_inputs;
  2223. ConstructGeInput(ge_inputs, args);
  2224. // find graph
  2225. GraphNodePtr graph_node = nullptr;
  2226. Status ret = graph_manager->GetGraphNode(args.graph_id, graph_node);
  2227. if (ret != SUCCESS) {
  2228. ReturnError(graph_manager, args.callback, GE_GRAPH_ALREADY_RUNNING,
  2229. "[RunGraph] graph not exist, graph_id=" + std::to_string(args.graph_id));
  2230. return;
  2231. }
  2232. graph_node->Lock();
  2233. if (graph_node->GetRunFlag()) {
  2234. ReturnError(graph_manager, args.callback, GE_GRAPH_GRAPH_NODE_NULL,
  2235. "[RunGraph] graph already running, graph id=" + std::to_string(args.graph_id));
  2236. graph_node->Unlock();
  2237. return;
  2238. }
  2239. // set graph's run flag
  2240. graph_node->SetRunFlag(true);
  2241. ComputeGraphPtr compute_graph_tmp = GraphUtils::GetComputeGraph(*(graph_node->GetGraph()));
  2242. if (compute_graph_tmp == nullptr) {
  2243. ReturnError(graph_manager, args.callback, GE_GRAPH_GRAPH_NODE_NULL,
  2244. "[RunGraph] compute_graph_tmp is NULL, graph id = %u.");
  2245. graph_node->Unlock();
  2246. return;
  2247. }
  2248. // when set incre build, save cache helper.
  2249. graph_manager->AddModelCacheHelperToMap(args.graph_id, args.session_id, compute_graph_tmp);
  2250. std::vector<GeModelPtr> ge_models;
  2251. if (graph_manager->options_.local_fmk_op_flag) {
  2252. graph_manager->GetCompilerStages(graph_node->GetGraphId()).optimizer.TranFrameOp(compute_graph_tmp);
  2253. }
  2254. // it will not execute graph preprocess, optimize, parition, build if the graph has built successful.
  2255. GELOGI("Start for run graph async.");
  2256. GeRootModelPtr ge_root_model = nullptr;
  2257. if (graph_manager->IsGraphNeedBuild(graph_node)) {
  2258. if (graph_node->GetBuildFlag()) {
  2259. ReturnError(graph_manager, args.callback, PARAM_INVALID,
  2260. "The graph " + std::to_string(graph_node->GetGraphId()) +
  2261. " need to re-build, you should remove it"
  2262. " from GE first, then AddGraph again and rebuild it.");
  2263. graph_node->Unlock();
  2264. return;
  2265. }
  2266. // check need incre build.
  2267. GeModelPtr ge_model = nullptr;
  2268. if (graph_manager->IncreBuild(graph_node, ge_model) != SUCCESS) {
  2269. ret = graph_manager->PreRun(graph_node, ge_inputs, ge_root_model, args.session_id);
  2270. // release rts generate context
  2271. RtContextUtil::GetInstance().DestroyRtContexts(args.session_id, graph_node->GetGraphId());
  2272. if (ret != SUCCESS) {
  2273. graph_node->SetRunFlag(false);
  2274. if (!ge::Analyzer::GetInstance()->IsEnableNetAnalyzeDebug()) {
  2275. ReturnError(graph_manager, args.callback, ret, "PreRun Failed, thread exit..");
  2276. graph_node->Unlock();
  2277. return;
  2278. } else {
  2279. ReturnError(graph_manager, graph_node, args.callback, ret, "PreRun Failed, keep geop continue!");
  2280. graph_node->Unlock();
  2281. continue;
  2282. }
  2283. }
  2284. }
  2285. graph_node->SetBuildFlag(true);
  2286. graph_manager->var_acc_ctrl_.SetGraphBuildEnd(graph_node->GetGraphId());
  2287. } else {
  2288. ge_root_model = graph_node->GetGeRootModel();
  2289. }
  2290. graph_manager->run_args_q_.Push(RunArgs( { graph_node, args.graph_id, args.session_id, args.input_tensor,
  2291. ge_root_model, GetThreadLocalContext(), args.callback }));
  2292. GELOGI("Loop end.");
  2293. }
  2294. }
  2295. void GraphManager::RunThread(GraphManager *graph_manager) {
  2296. if (prctl(PR_SET_NAME, ("GE_Run")) != 0) {
  2297. GELOGW("Set thread name failed.");
  2298. }
  2299. RunArgs args;
  2300. while (graph_manager->thread_run_flag_) {
  2301. bool pop_status = graph_manager->run_args_q_.Pop(args);
  2302. if (!pop_status) {
  2303. continue;
  2304. }
  2305. GELOGI("A new loop start.");
  2306. GetContext().SetSessionId(args.session_id);
  2307. GetThreadLocalContext() = args.context;
  2308. graph_manager->UpdateLocalOmgContext(args.graph_id);
  2309. if (args.graph_node->graph_run_async_listener_ != nullptr) {
  2310. args.graph_node->graph_run_async_listener_->SetCallback(args.callback);
  2311. }
  2312. Status ret;
  2313. if (!args.graph_node->GetLoadFlag()) {
  2314. ret = graph_manager->LoadGraphAsync(args.ge_root_model, args.graph_node);
  2315. if (ret != SUCCESS || args.ge_root_model == nullptr) {
  2316. StopQueue(graph_manager);
  2317. ReturnError(graph_manager, args.callback, ret, "LoadGraphAsync failed, thread exit.");
  2318. args.graph_node->Unlock();
  2319. return;
  2320. }
  2321. args.graph_node->SetLoadFlag(true);
  2322. GELOGI("LoadGraph[%u], model[%u] success and set LoadFlag to true.", args.graph_node->GetGraphId(),
  2323. args.ge_root_model->GetModelId());
  2324. }
  2325. if (graph_manager->GetTrainFlag()) {
  2326. ret = graph_manager->graph_executor_.SetGraphContext(graph_manager->GetGraphContext());
  2327. if (ret != SUCCESS) {
  2328. GELOGW("[GraphManager] SetGraphContext failed, graph_id=%u.", args.graph_id);
  2329. }
  2330. graph_manager->graph_executor_.SetTrainFlag(graph_manager->options_.train_graph_flag);
  2331. }
  2332. ret = graph_manager->graph_executor_.ExecuteGraphAsync(args.graph_id, args.graph_node->GetGeRootModel(),
  2333. args.input_tensor);
  2334. args.graph_node->SetRunFlag(false);
  2335. args.graph_node->Unlock();
  2336. if (ret != SUCCESS) {
  2337. GELOGE(ret, "[GraphManager] Run graph async failed, graph_id=%u.", args.graph_id);
  2338. StopQueue(graph_manager);
  2339. return;
  2340. }
  2341. GELOGI("[GraphManager] Run graph async success, graph_id=%u.", args.graph_id);
  2342. }
  2343. }
  2344. void GraphManager::StopQueue(GraphManager *graph_manager) {
  2345. if (graph_manager == nullptr) {
  2346. return;
  2347. }
  2348. graph_manager->thread_run_flag_.store(false);
  2349. graph_manager->prerun_args_q_.Stop();
  2350. graph_manager->run_args_q_.Stop();
  2351. }
  2352. void GraphManager::ReturnError(GraphManager *graph_manager, RunAsyncCallback callback, Status ret, const string &log) {
  2353. if (graph_manager == nullptr) {
  2354. return;
  2355. }
  2356. StopQueue(graph_manager);
  2357. GELOGE(ret, "%s.", log.c_str());
  2358. std::vector<ge::OutputTensorInfo> outputs;
  2359. callback(ret, outputs);
  2360. }
  2361. void GraphManager::ReturnError(GraphManager *graph_manager, GraphNodePtr &graph_node,
  2362. RunAsyncCallback callback, Status ret, const string &log) {
  2363. std::vector<ge::OutputTensorInfo> outputs;
  2364. auto compute_graph = GraphUtils::GetComputeGraph(*graph_node->GetGraph());
  2365. if (graph_manager == nullptr || compute_graph == nullptr) {
  2366. GELOGE(GRAPH_FAILED, "[Analyze Mode] compute graph is null!");
  2367. callback(GRAPH_FAILED, outputs);
  2368. return;
  2369. }
  2370. for (const auto &node : compute_graph->GetAllNodes()) {
  2371. if (node->GetType() != "NetOutput") {
  2372. continue;
  2373. }
  2374. for (size_t i = 0; i < node->GetAllInDataAnchorsSize(); i++) {
  2375. auto input_desc = node->GetOpDesc()->MutableInputDesc(i);
  2376. ge::OutputTensorInfo tensor;
  2377. tensor.dims = input_desc->GetShape().GetDims();
  2378. tensor.data_type = static_cast<uint32_t>(input_desc->GetDataType());
  2379. int64_t len = 1;
  2380. if (input_desc->GetShape().GetDims() != std::vector<int64_t>({})) {
  2381. len = input_desc->GetShape().GetShapeSize();
  2382. }
  2383. if (len < 0) {
  2384. GELOGE(GRAPH_FAILED, "Analyze Mode does not support GEOP output unknown shape!");
  2385. callback(GRAPH_FAILED, outputs);
  2386. return;
  2387. } else if (len == 0) {
  2388. GELOGI("getted shape size is 0.Do process as empty tensor!");
  2389. len = 1;
  2390. }
  2391. auto size = GetSizeByDataType(input_desc->GetDataType());
  2392. if (size <= 0) {
  2393. GELOGE(PARAM_INVALID, "Failed to get cube size, the data type %s is invalid",
  2394. ge::TypeUtils::DataTypeToSerialString(input_desc->GetDataType()).c_str());
  2395. callback(GRAPH_FAILED, outputs);
  2396. return;
  2397. }
  2398. if (CheckInt64MulOverflow(len, static_cast<int64_t>(size)) != true) {
  2399. GELOGE(MEMALLOC_FAILED, "int64 multiply happens overflow! a:%ld b:%d", len, size);
  2400. callback(GRAPH_FAILED, outputs);
  2401. return;
  2402. }
  2403. tensor.length = len * size;
  2404. tensor.data.reset(new(std::nothrow) uint8_t[tensor.length]);
  2405. // To avoid global step too small and can not stop, totally set a bigger value
  2406. for (int64_t i = 0; i < tensor.length; i++) {
  2407. tensor.data[i] = 0x7F; // here stands for a positive max value
  2408. }
  2409. outputs.emplace_back(std::move(tensor));
  2410. }
  2411. }
  2412. callback(SUCCESS, outputs);
  2413. return;
  2414. }
  2415. bool GraphManager::IsGraphNeedRebuild(uint32_t graph_id) {
  2416. // find graph
  2417. GraphNodePtr graph_node = nullptr;
  2418. Status ret = GetGraphNode(graph_id, graph_node);
  2419. if (ret != SUCCESS) {
  2420. GELOGE(ret, "[RunGraph] graph not exist, graph_id=%u.", graph_id);
  2421. return true;
  2422. }
  2423. if (graph_node == nullptr) {
  2424. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] graph node is NULL, graphId=%u.", graph_id);
  2425. return true;
  2426. }
  2427. return IsGraphNeedBuild(graph_node);
  2428. }
  2429. bool GraphManager::IsGraphNeedBuild(const GraphNodePtr &graph_node) {
  2430. return !graph_node->GetBuildFlag() || var_acc_ctrl_.IsGraphNeedRebuild(graph_node->GetGraphId());
  2431. }
  2432. const map<std::string, std::string> *GraphManager::GetGraphOptions(uint32_t graph_id) {
  2433. GraphNodePtr graph_node = nullptr;
  2434. Status ret = GetGraphNode(graph_id, graph_node);
  2435. if (ret != SUCCESS) {
  2436. GELOGE(ret, "[RunGraph] graph not exist, graph_id=%u.", graph_id);
  2437. return nullptr;
  2438. }
  2439. if (!graph_node) {
  2440. GELOGE(GE_GRAPH_GRAPH_NODE_NULL, "[RunGraph] graph node is NULL, graph_id=%u.", graph_id);
  2441. return nullptr;
  2442. }
  2443. return &(graph_node->GetOptions());
  2444. }
  2445. void GraphManager::SetOptionsRunGraphFlag(bool run_graph_flag) { options_.run_graph_flag = run_graph_flag; }
  2446. Status GraphManager::OptimizeSubgraph(const GraphNodePtr &graph_node, ComputeGraphPtr &compute_graph,
  2447. uint64_t session_id) {
  2448. // graph partition
  2449. // Stage partition, only for root graph
  2450. GE_TIMESTAMP_START(StagePartition);
  2451. StagePartitioner stage_partitioner(compute_graph);
  2452. auto ret = stage_partitioner.Partition();
  2453. if (ret != SUCCESS) {
  2454. GELOGE(ret, "Graph partition by stage Failed");
  2455. return ret;
  2456. }
  2457. GE_TIMESTAMP_EVENT_END(StagePartition, "OptimizeSubgraph::StagePartition");
  2458. // all sub graph list of root graph and sub graph
  2459. GE_TIMESTAMP_START(GraphPartitionDynamicShape);
  2460. DynamicShapePartitioner dynamic_shape_partitioner(compute_graph);
  2461. ret = dynamic_shape_partitioner.Partition();
  2462. if (ret != SUCCESS) {
  2463. GELOGE(ret, "Graph partition by dynamic shape Failed");
  2464. return ret;
  2465. }
  2466. bool dynamic_shape_partitioned = false;
  2467. if (!AttrUtils::GetBool(*compute_graph, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, dynamic_shape_partitioned)) {
  2468. GELOGE(FAILED, "failed get dynamic shape partitioned flag on partitioned graph.");
  2469. return FAILED;
  2470. }
  2471. GE_TIMESTAMP_EVENT_END(GraphPartitionDynamicShape, "OptimizeSubgraph::GraphPartitionDynamicShape");
  2472. GE_TIMESTAMP_START(GraphPartition);
  2473. GraphPartitioner &partitioner = GetCompilerStages(graph_node->GetGraphId()).partitioner;
  2474. ret = partitioner.Partition(compute_graph, GraphPartitioner::kPartitioning);
  2475. if (ret != SUCCESS) {
  2476. GELOGE(ret, "Graph partition Failed");
  2477. return ret;
  2478. }
  2479. GE_TIMESTAMP_EVENT_END(GraphPartition, "OptimizeSubgraph::Partition1");
  2480. GE_TIMESTAMP_START(SetSubgraph);
  2481. ret = SetSubgraph(session_id, compute_graph, partitioner);
  2482. if (ret != SUCCESS) {
  2483. GELOGE(ret, "Graph set subgraph Failed");
  2484. return ret;
  2485. }
  2486. GE_TIMESTAMP_EVENT_END(SetSubgraph, "OptimizeSubgraph::SetSubGraph");
  2487. if ((options_.build_mode == BUILD_MODE_TUNING) &&
  2488. (options_.build_step == BUILD_STEP_BEFORE_UB_MATCH || options_.build_step == BUILD_STEP_AFTER_BUILDER ||
  2489. options_.build_step == BUILD_STEP_AFTER_BUILDER_SUB)) {
  2490. GE_TIMESTAMP_START(ConvertGraphToFile);
  2491. std::string tuning_path;
  2492. (void) GetContext().GetOption(TUNING_PATH, tuning_path);
  2493. Status ret = ConvertGraphToFile(compute_graph, partitioner, tuning_path,
  2494. (options_.build_step == BUILD_STEP_AFTER_BUILDER));
  2495. if (ret != SUCCESS) {
  2496. GELOGE(ret, "Convert graph[%s] to file failed", compute_graph->GetName().c_str());
  2497. return ret;
  2498. }
  2499. GE_TIMESTAMP_EVENT_END(ConvertGraphToFile, "OptimizeSubgraph::ConvertGraphToFile");
  2500. return SUCCESS;
  2501. }
  2502. ComputeGraphPtr merged_compute_graph = nullptr;
  2503. std::vector<ComputeGraphPtr> merged_sub_graph_list;
  2504. GE_TIMESTAMP_START(MergeSubgraph);
  2505. ret = MergeSubGraph(merged_compute_graph, compute_graph, graph_node->GetGraphId());
  2506. if (ret != SUCCESS) {
  2507. GELOGE(ret, "Merge SubGraph Failed");
  2508. return ret;
  2509. }
  2510. GE_CHECK_NOTNULL(merged_compute_graph);
  2511. merged_compute_graph->SetSessionID(session_id);
  2512. merged_compute_graph->SetGraphID(graph_node->GetGraphId());
  2513. merged_compute_graph->SetNeedIteration(compute_graph->GetNeedIteration());
  2514. for (auto &sub_graph : merged_compute_graph->GetAllSubgraphs()) {
  2515. sub_graph->SetSessionID(session_id);
  2516. sub_graph->SetGraphID(graph_node->GetGraphId());
  2517. }
  2518. GE_TIMESTAMP_EVENT_END(MergeSubgraph, "OptimizeSubgraph::MergeSubGraph");
  2519. GE_DUMP(merged_compute_graph, "mergedComputeGraph");
  2520. compute_graph = merged_compute_graph;
  2521. if (!AttrUtils::SetBool(*compute_graph, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, dynamic_shape_partitioned)) {
  2522. GELOGE(FAILED, "failed set dynamic shape partitioned flag on partitioned graph.");
  2523. return FAILED;
  2524. }
  2525. return SUCCESS;
  2526. }
  2527. Status GraphManager::ConvertGraphToFile(ComputeGraphPtr &compute_graph, GraphPartitioner &partitioner, std::string path,
  2528. bool exe_flag) {
  2529. GE_CHECK_NOTNULL(compute_graph);
  2530. GELOGI("compute_graph [%s] path [%s] Enter ConvertGraphToFile.", compute_graph->GetName().c_str(), path.c_str());
  2531. std::vector<ComputeGraphPtr> non_tuning_subgraphs;
  2532. auto input_node_sub_graph_map = partitioner.graph_2_input_subgraph_;
  2533. const auto &input_subgraph_info = input_node_sub_graph_map[compute_graph];
  2534. GE_CHECK_NOTNULL(input_subgraph_info);
  2535. ComputeGraphPtr input_graph_tmp = input_subgraph_info->GetSubGraph();
  2536. non_tuning_subgraphs.push_back(input_graph_tmp);
  2537. auto sub_graph_map = partitioner.GetSubGraphMap();
  2538. const auto &subgraph_infos = sub_graph_map[compute_graph];
  2539. std::vector<ComputeGraphPtr> tuning_subgraphs;
  2540. for (const auto &sub_graph_info_ptr: subgraph_infos) {
  2541. GE_CHECK_NOTNULL(sub_graph_info_ptr);
  2542. ComputeGraphPtr sub_graph_tmp = sub_graph_info_ptr->GetSubGraph();
  2543. // need to tuning
  2544. if (sub_graph_info_ptr->GetEngineName() == kVectorEngine || sub_graph_info_ptr->GetEngineName() == kAIcoreEngine) {
  2545. tuning_subgraphs.push_back(sub_graph_tmp);
  2546. } else {
  2547. non_tuning_subgraphs.push_back(sub_graph_tmp);
  2548. }
  2549. }
  2550. return TuningUtils::ConvertGraphToFile(tuning_subgraphs, non_tuning_subgraphs, exe_flag, path);
  2551. }
  2552. Status GraphManager::Build(const GraphNodePtr &graph_node, ComputeGraphPtr &compute_graph,
  2553. GeRootModelPtr &ge_root_model, uint64_t session_id) {
  2554. // build
  2555. if (compute_graph != nullptr) {
  2556. std::string graph_name = compute_graph->GetName();
  2557. graph_name.append("_");
  2558. graph_name.append(std::to_string(graph_node->GetGraphId()));
  2559. compute_graph->SetName(graph_name);
  2560. }
  2561. std::vector<SubGraphInfoPtr> sub_graph_list;
  2562. auto ret = GetCompilerStages(graph_node->GetGraphId()).builder.Build(compute_graph, sub_graph_list, ge_root_model,
  2563. session_id);
  2564. if (ret != SUCCESS) {
  2565. GELOGE(ret, "SubGraph build Failed.");
  2566. return ret;
  2567. }
  2568. bool is_always_dump = false;
  2569. if (!PropertiesManager::Instance().GetDumpProperties(session_id).GetDumpPath().empty()) {
  2570. is_always_dump = true;
  2571. }
  2572. GraphUtils::DumpGEGraph(compute_graph, "Build", is_always_dump);
  2573. GraphUtils::DumpGEGraphToOnnx(*compute_graph, "Build");
  2574. graph_node->SetGeRootModel(ge_root_model);
  2575. return SUCCESS;
  2576. }
  2577. Status GraphManager::GenCheckPointGraph(const std::map<std::string, GeTensorDesc> &all_variables, Graph &graph) {
  2578. ge::ComputeGraphPtr compute_graph = MakeShared<ComputeGraph>(kCheckPointGraph);
  2579. GE_CHECK_NOTNULL(compute_graph);
  2580. OpDescPtr save_desc = MakeShared<ge::OpDesc>(compute_graph->GetName() + "_" + kSave, kSave);
  2581. GE_CHECK_NOTNULL(save_desc);
  2582. uint32_t save_index = 0;
  2583. for (auto iter = all_variables.begin(); iter != all_variables.end(); ++iter) {
  2584. GE_CHK_GRAPH_STATUS_RET(save_desc->AddInputDesc(save_index, iter->second));
  2585. save_index++;
  2586. }
  2587. NodePtr save_node = compute_graph->AddNode(save_desc);
  2588. uint32_t index = 0;
  2589. for (auto iter = all_variables.begin(); iter != all_variables.end(); ++iter) {
  2590. OpDescPtr var_desc = MakeShared<ge::OpDesc>(iter->first, VARIABLE);
  2591. GE_CHECK_NOTNULL(var_desc);
  2592. if (!AttrUtils::SetBool(var_desc, kCheckPointForGetVar, true)) {
  2593. GELOGW("Set check point graph attr failed.");
  2594. }
  2595. GE_CHK_GRAPH_STATUS_RET(var_desc->AddOutputDesc(iter->second));
  2596. NodePtr var_node = compute_graph->AddNode(var_desc);
  2597. GE_CHK_STATUS(GraphUtils::AddEdge(var_node->GetOutDataAnchor(0), save_node->GetInDataAnchor(index)),
  2598. "Add edge[%s->%s] fail.", var_node->GetName().c_str(), save_node->GetName().c_str());
  2599. index++;
  2600. }
  2601. compute_graph->Dump();
  2602. graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph);
  2603. return SUCCESS;
  2604. }
  2605. Status GraphManager::SaveVariables(const Graph &graph, const std::vector<std::string> &var_names,
  2606. const std::vector<Tensor> &outputs, std::vector<Tensor> &var_values) {
  2607. map<string, Tensor> var_results;
  2608. GE_CHK_STATUS_RET(SaveCheckPointResult(graph, outputs, var_results), "Save check point result failed.");
  2609. if (!var_names.empty()) {
  2610. for (const auto &var_name : var_names) {
  2611. if (var_results.count(var_name) == 0) {
  2612. GELOGE(FAILED, "Fetch var[%s] value failed.", var_name.c_str());
  2613. return FAILED;
  2614. } else {
  2615. auto var_tensor = var_results[var_name].GetTensorDesc();
  2616. var_tensor.SetName(var_name);
  2617. var_results[var_name].SetTensorDesc(var_tensor);
  2618. var_values.emplace_back(var_results[var_name]);
  2619. }
  2620. }
  2621. } else {
  2622. for (auto iter = var_results.begin(); iter != var_results.end(); ++iter) {
  2623. string var_name = iter->first;
  2624. auto var_tensor = iter->second.GetTensorDesc();
  2625. var_tensor.SetName(var_name);
  2626. iter->second.SetTensorDesc(var_tensor);
  2627. var_values.emplace_back(iter->second);
  2628. }
  2629. }
  2630. return SUCCESS;
  2631. }
  2632. Status GraphManager::SaveCheckPointResult(const Graph &graph, const std::vector<Tensor> &outputs,
  2633. map<string, Tensor> &var_results) {
  2634. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  2635. NodePtr netoutput_node = nullptr;
  2636. for (const auto &node : compute_graph->GetAllNodes()) {
  2637. if (node->GetType() == NETOUTPUT) {
  2638. netoutput_node = node;
  2639. break;
  2640. }
  2641. }
  2642. GE_CHECK_NOTNULL(netoutput_node);
  2643. for (const auto &in : netoutput_node->GetAllInDataAnchors()) {
  2644. auto out_anchor = in->GetPeerOutAnchor();
  2645. GE_CHECK_NOTNULL(out_anchor);
  2646. auto peer_node = out_anchor->GetOwnerNode();
  2647. while (peer_node->GetType() != VARIABLE) {
  2648. if (peer_node->GetAllInDataAnchors().size() != 1) {
  2649. GELOGE(FAILED, "peer_node [%s] has more than 1 input in checkpoint Graph.", peer_node->GetName().c_str());
  2650. return FAILED;
  2651. }
  2652. auto peer_node_in_anchor = peer_node->GetAllInDataAnchors().at(0);
  2653. auto peer_node_out_anchor = peer_node_in_anchor->GetPeerOutAnchor();
  2654. if (peer_node_out_anchor != nullptr) {
  2655. peer_node = peer_node_out_anchor->GetOwnerNode();
  2656. if (peer_node->GetType() == VARIABLE) {
  2657. break;
  2658. }
  2659. }
  2660. }
  2661. if (peer_node->GetType() != VARIABLE) {
  2662. GELOGE(FAILED, " peer_node %s is not variable in checkpoint Graph.", peer_node->GetName().c_str());
  2663. return FAILED;
  2664. }
  2665. auto var_name = peer_node->GetName();
  2666. GELOGI("[GraphManager] SaveVariables, varName is %s.", var_name.c_str());
  2667. if (in->GetIdx() >= static_cast<int>(outputs.size())) {
  2668. GELOGE(FAILED, "variable index[%d] out of range[%zu].", in->GetIdx(), outputs.size());
  2669. return FAILED;
  2670. }
  2671. var_results.emplace(var_name, outputs.at(in->GetIdx()));
  2672. }
  2673. return SUCCESS;
  2674. }
  2675. void GraphManager::AddLocalOmgContext(GraphId graph_id, const OmgContext &omg_context) {
  2676. std::lock_guard<std::mutex> lock(member_mutex_);
  2677. omg_contexts_.emplace(graph_id, omg_context);
  2678. SetLocalOmgContext(omg_contexts_[graph_id]);
  2679. }
  2680. void GraphManager::UpdateLocalOmgContext(GraphId graph_id) {
  2681. std::lock_guard<std::mutex> lock(member_mutex_);
  2682. auto iter = omg_contexts_.find(graph_id);
  2683. if (iter != omg_contexts_.end()) {
  2684. SetLocalOmgContext(iter->second);
  2685. } else {
  2686. GELOGW("OmgContext of graph %u not found.", graph_id);
  2687. }
  2688. }
  2689. GraphManager::CompilerStages &GraphManager::GetCompilerStages(GraphId graph_id) {
  2690. std::lock_guard<std::mutex> lock(member_mutex_);
  2691. return compiler_stages_[graph_id];
  2692. }
  2693. void GraphManager::RemoveCompilerStages(GraphId graph_id) {
  2694. std::lock_guard<std::mutex> lock(member_mutex_);
  2695. compiler_stages_.erase(graph_id);
  2696. }
  2697. } // namespace ge

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