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 150 kB

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

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