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

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