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

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