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.

davinci_model.cc 172 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
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
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
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
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
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
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
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
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
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206
  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/load/new_model_manager/davinci_model.h"
  17. #include <cce/dnn.h>
  18. #include <dlfcn.h>
  19. #include <graph/utils/node_utils.h>
  20. #include <pthread.h>
  21. #include <sched.h>
  22. #include <sys/prctl.h>
  23. #include <algorithm>
  24. #include <map>
  25. #include <utility>
  26. #include "common/debug/log.h"
  27. #include "common/formats/formats.h"
  28. #include "common/formats/utils/formats_trans_utils.h"
  29. #include "common/math/math_util.h"
  30. #include "common/op/ge_op_utils.h"
  31. #include "common/profiling/profiling_manager.h"
  32. #include "common/properties_manager.h"
  33. #include "common/scope_guard.h"
  34. #include "common/thread_pool.h"
  35. #include "framework/common/debug/ge_log.h"
  36. #include "graph/common/ge_call_wrapper.h"
  37. #include "graph/compute_graph.h"
  38. #include "graph/debug/ge_attr_define.h"
  39. #include "graph/ge_context.h"
  40. #include "graph/graph.h"
  41. #include "graph/load/new_model_manager/cpu_queue_schedule.h"
  42. #include "graph/load/new_model_manager/model_manager.h"
  43. #include "graph/load/new_model_manager/tbe_handle_store.h"
  44. #include "graph/manager/graph_mem_allocator.h"
  45. #include "graph/manager/graph_var_manager.h"
  46. #include "graph/manager/trans_var_data_utils.h"
  47. #include "graph/manager/util/debug.h"
  48. #include "graph/model_serialize.h"
  49. #include "graph/node.h"
  50. #include "graph/utils/graph_utils.h"
  51. #include "graph/utils/type_utils.h"
  52. #include "init/gelib.h"
  53. #include "mmpa/mmpa_api.h"
  54. #include "omm/csa_interact.h"
  55. #include "runtime/base.h"
  56. #include "runtime/dev.h"
  57. #include "runtime/event.h"
  58. #include "runtime/mem.h"
  59. #include "runtime/rt_model.h"
  60. #include "runtime/stream.h"
  61. #include "securec.h"
  62. #include "graph/common/local_context.h"
  63. #include "common/formats/utils/formats_trans_utils.h"
  64. // create std::thread, catch exceptions using try/catch
  65. #define CREATE_STD_THREAD(thread_id, func, args) \
  66. do { \
  67. try { \
  68. thread_id = std::thread(func, args); \
  69. } catch (const std::system_error &e) { \
  70. GELOGE(FAILED, "Caught system_error with code:%d, meaning:%s", e.code().value(), e.what()); \
  71. GELOGE(FAILED, "Thread creat FAIL, Please check the left resource!"); \
  72. return FAILED; \
  73. } \
  74. } while (0)
  75. namespace ge {
  76. namespace {
  77. const uint32_t kDataIndex = 0;
  78. const uint32_t kOutputNum = 1;
  79. const uint32_t kTrueBranchStreamNum = 1;
  80. const uint32_t kGetDynamicDimsCount = 1;
  81. const uint32_t kThreadNum = 16;
  82. const uint32_t kAddrLen = sizeof(void *);
  83. const int kDecimal = 10;
  84. const int kBytes = 8;
  85. const uint32_t kDataMemAlignSizeCompare = 64;
  86. const uint32_t kDumpL1FusionOpMByteSize = 2 * 1024 * 1024;
  87. const uint32_t kDumpFlagOfL1Fusion = 0;
  88. const char *const kDefaultBatchLable = "Batch_default";
  89. const char *const kGetDynamicDimsName = "ascend_mbatch_get_dynamic_dims_node";
  90. inline bool IsDataOp(const std::string &node_type) {
  91. return node_type == DATA_TYPE || node_type == AIPP_DATA_TYPE || node_type == ANN_DATA_TYPE;
  92. }
  93. inline bool IsNoTaskAndDumpNeeded(const OpDescPtr &op_desc) {
  94. bool save_dump_info = false;
  95. (void)ge::AttrUtils::GetBool(op_desc, ATTR_NO_TASK_AND_DUMP_NEEDED, save_dump_info);
  96. return save_dump_info;
  97. }
  98. } // namespace
  99. std::mutex DavinciModel::tvm_bin_mutex_;
  100. DavinciModel::DavinciModel(int32_t priority, const std::shared_ptr<ModelListener> &listener)
  101. : weights_mem_base_(nullptr),
  102. var_mem_base_(nullptr),
  103. mem_base_(nullptr),
  104. is_inner_mem_base_(false),
  105. is_inner_weight_base_(false),
  106. is_inner_p2p_mem_base_(false),
  107. data_inputer_(nullptr),
  108. load_begin_time_(0),
  109. load_end_time_(0),
  110. time_info_(),
  111. dataInputTid(0),
  112. is_model_has_inited_(false),
  113. model_id_(0),
  114. runtime_model_id_(0),
  115. version_(0),
  116. ge_model_(nullptr),
  117. thread_id_(),
  118. listener_(listener),
  119. run_flg_(false),
  120. priority_(priority),
  121. rt_model_handle_(nullptr),
  122. rt_model_stream_(nullptr),
  123. is_inner_model_stream_(false),
  124. is_async_mode_(false),
  125. last_execute_mode_(INITIALIZATION),
  126. session_id_(0),
  127. device_id_(0),
  128. maxDumpOpNum_(0), data_dumper_(runtime_param_),
  129. iterator_count_(0),
  130. is_l1_fusion_enable_(false),
  131. is_first_execute_(true) {
  132. op_list_.clear();
  133. }
  134. DavinciModel::~DavinciModel() {
  135. try {
  136. Status ret = data_dumper_.UnloadDumpInfo();
  137. if (ret != SUCCESS) {
  138. GELOGW("UnloadDumpInfo failed, ret: %u.", ret);
  139. }
  140. for (const auto &op_and_addr : saved_task_addrs_) {
  141. auto addr = op_and_addr.second;
  142. if (addr != nullptr) {
  143. GE_CHK_RT(rtFree(addr));
  144. }
  145. addr = nullptr;
  146. }
  147. saved_task_addrs_.clear();
  148. GE_CHK_STATUS(ModelRunStop());
  149. op_list_.clear();
  150. data_op_list_.clear();
  151. output_op_list_.clear();
  152. tensor_name_to_fixed_addr_size_.clear();
  153. tensor_name_to_peer_output_index_.clear();
  154. GE_DELETE_NEW_SINGLE(data_inputer_);
  155. // check rt ctx is exist. rt api call will cause error log when ctx not exist
  156. rtContext_t ctx = nullptr;
  157. rtError_t rt_ret = rtCtxGetCurrent(&ctx);
  158. if (rt_ret == RT_ERROR_NONE) {
  159. UnbindTaskSinkStream();
  160. for (size_t i = 0; i < label_list_.size(); ++i) {
  161. if (label_list_[i] != nullptr) {
  162. GE_LOGW_IF(rtLabelDestroy(label_list_[i]) != RT_ERROR_NONE, "Destroy label failed, index: %zu", i);
  163. }
  164. }
  165. for (size_t i = 0; i < stream_list_.size(); ++i) {
  166. GE_LOGW_IF(rtStreamDestroy(stream_list_[i]) != RT_ERROR_NONE, "Destroy stream failed, index: %zu", i);
  167. }
  168. for (size_t i = 0; i < event_list_.size(); ++i) {
  169. GE_LOGW_IF(rtEventDestroy(event_list_[i]) != RT_ERROR_NONE, "Destroy event failed, index: %zu", i);
  170. }
  171. FreeWeightsMem();
  172. FreeFeatureMapMem();
  173. FreeP2PMem();
  174. if (l1_fusion_addr_ != nullptr) {
  175. GE_CHK_RT(rtFree(l1_fusion_addr_));
  176. }
  177. if (rt_model_handle_ != nullptr) {
  178. GE_CHK_RT(rtModelDestroy(rt_model_handle_));
  179. rt_model_handle_ = nullptr;
  180. }
  181. }
  182. OpDebugUnRegister();
  183. GELOGI("do ReleaseTask");
  184. ReleaseTask();
  185. CleanTbeHandle();
  186. var_mem_base_ = nullptr;
  187. if (known_node_) {
  188. if (args_ != nullptr) {
  189. GE_CHK_RT(rtFree(args_));
  190. }
  191. total_io_addrs_.clear();
  192. if (fixed_addrs_ != nullptr) {
  193. GE_CHK_RT(rtFree(fixed_addrs_));
  194. }
  195. }
  196. } catch (...) {
  197. GELOGW("DavinciModel::~DavinciModel: clear op_list catch exception.");
  198. }
  199. }
  200. void DavinciModel::UnbindHcomStream() {
  201. if (!all_hccl_stream_list_.empty()) {
  202. for (size_t i = 0; i < all_hccl_stream_list_.size(); i++) {
  203. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, all_hccl_stream_list_[i]) != RT_ERROR_NONE,
  204. "Unbind hccl stream from model failed! Index: %zu", i);
  205. GE_LOGW_IF(rtStreamDestroy(all_hccl_stream_list_[i]) != RT_ERROR_NONE, "Destroy hccl stream for rt_model failed!")
  206. }
  207. }
  208. return;
  209. }
  210. void DavinciModel::ReleaseTask() {
  211. for (const auto &task : cpu_task_list_) {
  212. if (task != nullptr) {
  213. GE_CHK_STATUS(task->Release(), "Release task failed.");
  214. }
  215. }
  216. cpu_task_list_.clear();
  217. for (const auto &task : task_list_) {
  218. if (task != nullptr) {
  219. GE_CHK_STATUS(task->Release(), "Release task failed.");
  220. }
  221. }
  222. }
  223. Status DavinciModel::Assign(const GeModelPtr &ge_model) {
  224. if (ge_model == nullptr) {
  225. GELOGI("can't assign null ge_model");
  226. return FAILED;
  227. }
  228. ge_model_ = ge_model;
  229. return SUCCESS;
  230. }
  231. ///
  232. /// @ingroup ge
  233. /// @brief Reduce memory usage after task sink.
  234. /// @return: void
  235. ///
  236. void DavinciModel::Shrink() {
  237. ge_model_.reset(); // delete object.
  238. op_list_.clear();
  239. }
  240. Status DavinciModel::InitModelMem(void *dev_ptr, size_t mem_size, void *weight_ptr, size_t weight_size) {
  241. if (is_model_has_inited_) {
  242. GELOGE(FAILED, "call InitModelMem more than once .");
  243. return FAILED;
  244. }
  245. is_model_has_inited_ = true;
  246. std::size_t data_size = TotalMemSize();
  247. std::size_t p2p_data_size = P2PMemInfos().at(RT_MEMORY_P2P_DDR).memory_size;
  248. const Buffer &weights = ge_model_->GetWeight();
  249. std::size_t weights_size = weights.GetSize();
  250. GE_CHECK_LE(weights_size, ALLOC_MEMORY_MAX_SIZE);
  251. if ((dev_ptr != nullptr) && (mem_size < TotalMemSize())) {
  252. GELOGE(FAILED, "Invalid mem param: mem_size=%zu totalsize=%zu.", mem_size, TotalMemSize());
  253. return FAILED;
  254. }
  255. if ((weight_ptr != nullptr) && (weight_size < weights_size)) {
  256. GELOGE(FAILED, "Invalid mem param: weight_size=%zu totalsize=%zu.", weight_size, weights_size);
  257. return FAILED;
  258. }
  259. mem_base_ = static_cast<uint8_t *>(dev_ptr);
  260. p2p_mem_base_ = static_cast<uint8_t *>(dev_ptr);
  261. weights_mem_base_ = static_cast<uint8_t *>(dev_ptr);
  262. is_inner_mem_base_ = false;
  263. is_inner_weight_base_ = false;
  264. if (TotalMemSize() && mem_base_ == nullptr) {
  265. mem_base_ = MallocFeatureMapMem(data_size);
  266. if (mem_base_ == nullptr) {
  267. GELOGE(GE_EXEC_ALLOC_FEATURE_MAP_MEM_FAILED, "Alloc feature map memory failed. size: %zu", data_size);
  268. return GE_EXEC_ALLOC_FEATURE_MAP_MEM_FAILED;
  269. }
  270. GEEVENT("[IMAS]InitModelMem graph_%u MallocMemory type[F] memaddr[%p] mem_size[%zu]", runtime_param_.graph_id,
  271. mem_base_, data_size);
  272. weights_mem_base_ = mem_base_;
  273. is_inner_mem_base_ = true;
  274. is_inner_weight_base_ = true;
  275. }
  276. if (p2p_data_size != 0) {
  277. p2p_mem_base_ = MallocP2PMem(p2p_data_size);
  278. if (p2p_mem_base_ == nullptr) {
  279. GELOGE(GE_EXEC_ALLOC_P2P_MEM_FAILED, "Alloc p2p memory failed,size: %zu", p2p_data_size);
  280. return GE_EXEC_ALLOC_P2P_MEM_FAILED;
  281. }
  282. GELOGI("InitModelMem graph_%u MallocMemory type[P] memaddr[%p] mem_size[%zu]", runtime_param_.graph_id,
  283. p2p_mem_base_, p2p_data_size);
  284. is_inner_p2p_mem_base_ = true;
  285. }
  286. if (weights_size != 0) {
  287. weights_mem_base_ = static_cast<uint8_t *>(weight_ptr);
  288. is_inner_weight_base_ = false;
  289. if (weight_ptr == nullptr) {
  290. weights_mem_base_ = MallocWeightsMem(weights_size);
  291. if (weights_mem_base_ == nullptr) {
  292. GELOGE(GE_EXEC_ALLOC_WEIGHT_MEM_FAILED, "Alloc weight memory failed. size: %zu", weights_size);
  293. return GE_EXEC_ALLOC_WEIGHT_MEM_FAILED;
  294. }
  295. is_inner_weight_base_ = true;
  296. }
  297. GELOGI("[IMAS]InitModelMem graph_%u MallocMemory type[W] memaddr[%p] mem_size[%zu]", runtime_param_.graph_id,
  298. weights_mem_base_, weights_size);
  299. GE_CHK_RT_RET(rtMemcpy(weights_mem_base_, weights_size, weights.GetData(), weights_size, RT_MEMCPY_HOST_TO_DEVICE));
  300. GELOGI("copy weights data to device");
  301. }
  302. GE_CHK_STATUS_RET(InitVariableMem(), "Init variable memory failed.");
  303. runtime_param_.mem_base = mem_base_;
  304. runtime_param_.weight_base = weights_mem_base_;
  305. runtime_param_.memory_infos[RT_MEMORY_P2P_DDR].memory_base = p2p_mem_base_;
  306. return SUCCESS;
  307. }
  308. Status DavinciModel::InitVariableMem() {
  309. // malloc variable memory base
  310. var_mem_base_ = VarManager::Instance(session_id_)->GetVarMemoryBase(RT_MEMORY_HBM);
  311. if (TotalVarMemSize() && var_mem_base_ == nullptr) {
  312. Status ret = VarManager::Instance(session_id_)->MallocVarMemory(TotalVarMemSize());
  313. if (ret != SUCCESS) {
  314. GELOGE(ret, "Malloc variable memory failed.");
  315. return ret;
  316. }
  317. var_mem_base_ = VarManager::Instance(session_id_)->GetVarMemoryBase(RT_MEMORY_HBM);
  318. GEEVENT("[IMAS]InitVariableMem graph_%u MallocMemory type[V] memaddr[%p] mem_size[%zu]", runtime_param_.graph_id,
  319. var_mem_base_, TotalVarMemSize());
  320. }
  321. runtime_param_.var_base = var_mem_base_;
  322. return SUCCESS;
  323. }
  324. void DavinciModel::InitRuntimeParams() {
  325. int64_t value = 0;
  326. bool ret;
  327. MemInfo p2p_mem_info;
  328. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_MEMORY_SIZE, value);
  329. runtime_param_.mem_size = ret ? (uint64_t)value : 0;
  330. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_WEIGHT_SIZE, value);
  331. runtime_param_.weight_size = ret ? (uint64_t)value : 0;
  332. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_STREAM_NUM, value);
  333. runtime_param_.stream_num = ret ? (uint32_t)value : 0;
  334. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_EVENT_NUM, value);
  335. runtime_param_.event_num = ret ? (uint32_t)value : 0;
  336. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_LABEL_NUM, value);
  337. runtime_param_.label_num = ret ? (uint32_t)value : 0;
  338. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_BATCH_NUM, value);
  339. runtime_param_.batch_num = ret ? (uint32_t)value : 0;
  340. ret = ge::AttrUtils::GetInt(ge_model_, MODEL_ATTR_TASK_GEN_BASE_ADDR, value);
  341. runtime_param_.logic_mem_base = ret ? (uint64_t)value : 0;
  342. ret = ge::AttrUtils::GetInt(ge_model_, MODEL_ATTR_TASK_GEN_WEIGHT_ADDR, value);
  343. runtime_param_.logic_weight_base = ret ? (uint64_t)value : 0;
  344. ret = ge::AttrUtils::GetInt(ge_model_, ge::MODEL_ATTR_SESSION_ID, value);
  345. runtime_param_.session_id = ret ? (uint64_t)value : 0;
  346. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_TASK_GEN_VAR_ADDR, value);
  347. runtime_param_.logic_var_base = ret ? (uint64_t)value : 0;
  348. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_VAR_SIZE, value);
  349. runtime_param_.var_size = ret ? (uint64_t)value : 0;
  350. session_id_ = runtime_param_.session_id;
  351. ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_P2P_MEMORY_SIZE, value);
  352. p2p_mem_info.memory_size = ret ? (uint64_t)value : 0;
  353. runtime_param_.memory_infos[RT_MEMORY_P2P_DDR] = std::move(p2p_mem_info);
  354. GELOGI(
  355. "InitRuntimeParams(), session_id:%lu, stream_num:%u, event_num:%u, label_num:%u, "
  356. "logic_mem_base:0x%lx, logic_weight_base:0x%lx, logic_var_base:0x%lx, "
  357. "memory_size:%lu, weight_size:%lu, var_size:%lu",
  358. runtime_param_.session_id, runtime_param_.stream_num, runtime_param_.event_num, runtime_param_.label_num,
  359. runtime_param_.logic_mem_base, runtime_param_.logic_weight_base, runtime_param_.logic_var_base,
  360. runtime_param_.mem_size, runtime_param_.weight_size, runtime_param_.var_size);
  361. }
  362. void DavinciModel::CheckHasHcomOp() {
  363. Graph graph = ge_model_->GetGraph();
  364. auto compute_graph = GraphUtils::GetComputeGraph(graph);
  365. if (compute_graph == nullptr) {
  366. return;
  367. }
  368. for (const auto &node : compute_graph->GetAllNodes()) {
  369. OpDescPtr op_desc = node->GetOpDesc();
  370. GE_IF_BOOL_EXEC(op_desc == nullptr, GELOGW("Node OpDesc is nullptr"); continue);
  371. GE_IF_BOOL_EXEC(((op_desc->GetType() == HCOMBROADCAST) || (op_desc->GetType() == HCOMALLGATHER) ||
  372. (op_desc->GetType() == HCOMALLREDUCE) || (op_desc->GetType() == HCOMSEND) ||
  373. (op_desc->GetType() == HCOMRECEIVE) || (op_desc->GetType() == HCOMREDUCESCATTER) ||
  374. (op_desc->GetType() == HVDCALLBACKALLREDUCE) || (op_desc->GetType() == HVDCALLBACKALLGATHER) ||
  375. (op_desc->GetType() == HVDCALLBACKBROADCAST) || (op_desc->GetType() == HVDWAIT)),
  376. uint32_t stream_id = static_cast<uint32_t>(op_desc->GetStreamId());
  377. (void)hcom_streams_.emplace(stream_id); GELOGD("hcom stream: %u.", stream_id); continue);
  378. }
  379. }
  380. ///
  381. /// @ingroup ge
  382. /// @brief Make active stream list and bind to model.
  383. /// @return: 0 for success / others for fail
  384. ///
  385. Status DavinciModel::BindModelStream() {
  386. // Stream not in active_stream_indication_ is active stream.
  387. is_stream_list_bind_ = false;
  388. if ((!input_queue_ids_.empty() || !output_queue_ids_.empty()) || (deploy_type_ == AICPU_DEPLOY_CROSS_THREAD)) {
  389. for (size_t i = 0; i < stream_list_.size(); ++i) {
  390. if (active_stream_indication_.count(i) == 0) {
  391. active_stream_list_.push_back(stream_list_[i]);
  392. active_stream_indication_.insert(i); // deactive all model stream.
  393. }
  394. }
  395. }
  396. for (size_t i = 0; i < stream_list_.size(); ++i) {
  397. if (active_stream_indication_.count(i) > 0) {
  398. GELOGI("rtModelBindStream[%zu]", i);
  399. GE_CHK_RT_RET(rtModelBindStream(rt_model_handle_, stream_list_[i], RT_INVALID_FLAG));
  400. } else {
  401. // bind rt_model_handel to all streams that relates to op
  402. GE_CHK_RT_RET(rtModelBindStream(rt_model_handle_, stream_list_[i], RT_HEAD_STREAM));
  403. }
  404. }
  405. is_stream_list_bind_ = true;
  406. return SUCCESS;
  407. }
  408. Status DavinciModel::DoTaskSink() {
  409. // task sink is supported as model_task_def is set
  410. const auto &model_task_def = ge_model_->GetModelTaskDefPtr();
  411. if (model_task_def == nullptr) {
  412. return SUCCESS;
  413. }
  414. GE_CHK_RT_RET(rtGetAicpuDeploy(&deploy_type_));
  415. GELOGI("do task_sink. AiCpu deploy type is: %x.", deploy_type_);
  416. GE_CHK_STATUS_RET(BindModelStream(), "Bind model stream failed.");
  417. if (known_node_) {
  418. GE_CHK_STATUS_RET(MallocKnownArgs(), "Mallloc known node args failed.");
  419. }
  420. GE_CHK_STATUS_RET(InitTaskInfo(*model_task_def.get()), "InitTaskInfo failed.");
  421. GE_CHK_STATUS_RET(ModelManager::GetInstance()->LaunchCustAicpuSo(), "Launch cust aicpu so failed.");
  422. GE_CHK_STATUS_RET(InitEntryTask(), "InitEntryTask failed.");
  423. GE_CHK_STATUS_RET(DistributeTask(), "Distribute failed.");
  424. GE_CHK_RT_RET(rtModelLoadComplete(rt_model_handle_));
  425. SetCopyOnlyOutput();
  426. return SUCCESS;
  427. }
  428. // set device use aicore(0) or vectorcore(1)
  429. Status DavinciModel::SetTSDevice() {
  430. int64_t value = 0;
  431. bool ret = ge::AttrUtils::GetInt(ge_model_, ATTR_MODEL_CORE_TYPE, value);
  432. uint32_t core_type = ret ? static_cast<uint32_t>(value) : 0;
  433. GELOGI("SetTSDevice: %u", core_type);
  434. rtError_t rt_ret = rtSetTSDevice(core_type);
  435. if (rt_ret != RT_ERROR_NONE) {
  436. GELOGE(RT_FAILED, "SetTSDevice failed, ret: 0x%X", rt_ret);
  437. return RT_ERROR_TO_GE_STATUS(rt_ret);
  438. }
  439. return SUCCESS;
  440. }
  441. Status DavinciModel::OpDebugRegister() {
  442. bool is_op_debug = false;
  443. (void)ge::AttrUtils::GetBool(ge_model_, ATTR_OP_DEBUG_FLAG, is_op_debug);
  444. GELOGD("The value of op_debug in ge_model_ is %d.", is_op_debug);
  445. if (is_op_debug) {
  446. debug_reg_mutex_.lock();
  447. rtError_t rt_ret = rtMalloc(&op_debug_addr_, kOpDebugMemorySize, RT_MEMORY_DDR);
  448. if (rt_ret != RT_ERROR_NONE) {
  449. GELOGE(RT_FAILED, "rtMalloc error, ret: 0x%X", rt_ret);
  450. return RT_ERROR_TO_GE_STATUS(rt_ret);
  451. }
  452. uint64_t debug_addrs_tmp = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(op_debug_addr_));
  453. // For data dump, aicpu needs the pointer to pointer that save the real debug address.
  454. rt_ret = rtMalloc(&p2p_debug_addr_, kDebugP2pSize, RT_MEMORY_HBM);
  455. if (rt_ret != RT_ERROR_NONE) {
  456. GELOGE(RT_FAILED, "rtMalloc error, ret: 0x%X", rt_ret);
  457. return RT_ERROR_TO_GE_STATUS(rt_ret);
  458. }
  459. rt_ret = rtMemcpy(p2p_debug_addr_, sizeof(uint64_t), &debug_addrs_tmp, sizeof(uint64_t), RT_MEMCPY_HOST_TO_DEVICE);
  460. if (rt_ret != RT_ERROR_NONE) {
  461. GELOGE(RT_FAILED, "rtMemcpy to p2p_addr error: 0x%X", rt_ret);
  462. return RT_ERROR_TO_GE_STATUS(rt_ret);
  463. }
  464. uint32_t op_debug_mode = 0;
  465. (void)ge::AttrUtils::GetInt(ge_model_, ATTR_OP_DEBUG_MODE, op_debug_mode);
  466. GELOGD("The value of op_debug_mode in ge_model_ is %u.", op_debug_mode);
  467. uint32_t debug_task_id = 0;
  468. uint32_t debug_stream_id = 0;
  469. rt_ret = rtDebugRegister(rt_model_handle_, op_debug_mode, op_debug_addr_, &debug_stream_id, &debug_task_id);
  470. if (rt_ret != RT_ERROR_NONE) {
  471. GELOGE(RT_FAILED, "rtDebugRegister error, ret: 0x%X", rt_ret);
  472. return RT_ERROR_TO_GE_STATUS(rt_ret);
  473. }
  474. GELOGI("debug_task_id:%d, debug_stream_id:%u", debug_task_id, debug_stream_id);
  475. is_op_debug_reg_ = true;
  476. data_dumper_.SaveOpDebugId(debug_task_id, debug_stream_id, p2p_debug_addr_, is_op_debug);
  477. }
  478. return SUCCESS;
  479. }
  480. void DavinciModel::OpDebugUnRegister() {
  481. GELOGI("OpDebugUnRegister, is_op_debug_reg_ = %d", is_op_debug_reg_);
  482. if (is_op_debug_reg_) {
  483. debug_reg_mutex_.unlock();
  484. rtError_t rt_ret = RT_ERROR_NONE;
  485. if (rt_model_handle_ != nullptr) {
  486. GELOGD("start call debug_unregister.");
  487. rt_ret = rtDebugUnRegister(rt_model_handle_);
  488. if (rt_ret != RT_ERROR_NONE) {
  489. GELOGW("rtDebugUnRegister failed, ret: 0x%X", rt_ret);
  490. }
  491. }
  492. if (op_debug_addr_ != nullptr) {
  493. rt_ret = rtFree(op_debug_addr_);
  494. if (rt_ret != RT_ERROR_NONE) {
  495. GELOGW("rtFree failed, ret: 0x%X", rt_ret);
  496. }
  497. op_debug_addr_ = nullptr;
  498. }
  499. if (p2p_debug_addr_ != nullptr) {
  500. rt_ret = rtFree(p2p_debug_addr_);
  501. if (rt_ret != RT_ERROR_NONE) {
  502. GELOGW("rtFree failed, ret: 0x%X", rt_ret);
  503. }
  504. p2p_debug_addr_ = nullptr;
  505. }
  506. is_op_debug_reg_ = false;
  507. }
  508. return;
  509. }
  510. // initialize op sequence and call initialization function of each op respectively
  511. Status DavinciModel::Init(void *dev_ptr, size_t mem_size, void *weight_ptr, size_t weight_size) {
  512. // validating params
  513. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(priority_ < 0 || priority_ > 7, return PARAM_INVALID,
  514. "Priority must between 0-7, now is %d", priority_);
  515. GE_CHK_BOOL_RET_STATUS(ge_model_ != nullptr, PARAM_INVALID, "GeModel is null.");
  516. Graph graph = ge_model_->GetGraph();
  517. ComputeGraphPtr compute_graph = GraphUtils::GetComputeGraph(graph);
  518. GE_CHK_BOOL_RET_STATUS(compute_graph != nullptr, INTERNAL_ERROR, "Get compute graph is nullptr.");
  519. // Initializing runtime_param_
  520. InitRuntimeParams();
  521. // RTS set aicore or vectorcore
  522. GE_CHK_STATUS_RET(SetTSDevice(), "SetTSDevice failed");
  523. version_ = ge_model_->GetVersion();
  524. name_ = ge_model_->GetName();
  525. (void)ge::AttrUtils::GetBool(ge_model_, ATTR_NAME_SWITCH_FOR_L1_FUSION, is_l1_fusion_enable_);
  526. GELOGD("The value of ge.l1Fusion in ge_model_ is %d.", is_l1_fusion_enable_);
  527. CheckHasHcomOp();
  528. vector<int64_t> huge_stream_list;
  529. (void)ge::AttrUtils::GetListInt(ge_model_, ATTR_MODEL_HUGE_STREAM_LIST, huge_stream_list);
  530. std::set<int64_t> huge_streams(huge_stream_list.begin(), huge_stream_list.end());
  531. for (uint32_t i = 0; i < StreamNum(); i++) {
  532. rtStream_t stream = nullptr;
  533. GE_MAKE_GUARD_RTSTREAM(stream);
  534. uint32_t stream_flags = RT_STREAM_PERSISTENT;
  535. if (huge_streams.find(i) != huge_streams.end()) {
  536. GELOGI("Stream %u is huge stream.", i);
  537. stream_flags |= RT_STREAM_HUGE;
  538. }
  539. if (hcom_streams_.find(i) != hcom_streams_.end()) {
  540. GE_CHK_RT_RET(rtStreamCreateWithFlags(&stream, priority_, stream_flags | RT_STREAM_FORCE_COPY));
  541. } else {
  542. GE_CHK_RT_RET(rtStreamCreateWithFlags(&stream, priority_, stream_flags));
  543. }
  544. GE_DISMISS_GUARD(stream);
  545. stream_list_.push_back(stream);
  546. GELOGD("Stream index:%u, stream:%p.", i, stream);
  547. }
  548. for (uint32_t i = 0; i < EventNum(); i++) {
  549. rtEvent_t rt_event;
  550. GE_CHK_RT_RET(rtEventCreate(&rt_event));
  551. event_list_.push_back(rt_event);
  552. }
  553. label_list_.resize(LabelNum(), nullptr);
  554. // create model_handle to load model
  555. GE_CHK_RT_RET(rtModelCreate(&rt_model_handle_, 0));
  556. GE_CHK_RT_RET(rtModelGetId(rt_model_handle_, &runtime_model_id_));
  557. // inference will use default graph_id 0;
  558. runtime_param_.graph_id = compute_graph->GetGraphID();
  559. // op debug register
  560. GE_CHK_STATUS_RET(OpDebugRegister(), "OpDebugRegister failed");
  561. GE_TIMESTAMP_START(TransAllVarData);
  562. GE_CHK_STATUS_RET(TransAllVarData(compute_graph, runtime_param_.graph_id), "TransAllVarData failed.");
  563. GE_TIMESTAMP_END(TransAllVarData, "GraphLoader::TransAllVarData");
  564. GE_CHK_STATUS_RET(TransVarDataUtils::CopyVarData(compute_graph, session_id_, device_id_), "copy var data failed.");
  565. GE_TIMESTAMP_START(InitModelMem);
  566. GELOGI("Known node is %d", known_node_);
  567. if (!known_node_) {
  568. GE_CHK_STATUS_RET_NOLOG(InitModelMem(dev_ptr, mem_size, weight_ptr, weight_size));
  569. data_inputer_ = new (std::nothrow) DataInputer();
  570. GE_CHK_BOOL_RET_STATUS(data_inputer_ != nullptr, MEMALLOC_FAILED, "data_inputer_ is nullptr.");
  571. }
  572. GE_TIMESTAMP_END(InitModelMem, "GraphLoader::InitModelMem");
  573. for (const ge::NodePtr &node : compute_graph->GetDirectNode()) {
  574. auto op_desc = node->GetOpDesc();
  575. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  576. GE_IF_BOOL_EXEC(op_desc->GetType() != VARIABLE, continue);
  577. GE_IF_BOOL_EXEC(IsBroadCastOpData(node),
  578. (void)ge::AttrUtils::SetStr(op_desc, VAR_ATTR_VAR_IS_BROADCAST, "var_is_restore"););
  579. }
  580. // for profiling
  581. op_name_map_ = compute_graph->GetGraphOpName();
  582. vector<string> op_name;
  583. GE_IF_BOOL_EXEC(ge::AttrUtils::GetListStr(ge_model_, ATTR_MODEL_TASK_INDEX_OP_NAME, op_name),
  584. GELOGI("get str of task_index_op_name"));
  585. if (op_name_map_.empty()) {
  586. for (size_t idx = 0; idx < op_name.size(); idx++) {
  587. op_name_map_[idx] = op_name[idx];
  588. }
  589. GELOGI("Infer profiling: op_name_size(%zu)", op_name.size());
  590. }
  591. GE_CHK_STATUS_RET(InitNodes(compute_graph), "Init nodes failed");
  592. SetDataDumperArgs(compute_graph);
  593. GE_TIMESTAMP_START(DoTaskSink);
  594. auto ret = DoTaskSink();
  595. GE_TIMESTAMP_END(DoTaskSink, "GraphLoader::DoTaskSink");
  596. auto all_dump_model = GetDumpProperties().GetAllDumpModel();
  597. bool findByOmName = all_dump_model.find(om_name_) != all_dump_model.end();
  598. bool findByModelName = all_dump_model.find(name_) != all_dump_model.end();
  599. if (all_dump_model.find(ge::DUMP_ALL_MODEL) != all_dump_model.end() || findByOmName || findByModelName) {
  600. // malloc 2M for dump l1fusion op
  601. GE_CHK_RT_RET(rtMalloc(&l1_fusion_addr_, kDumpL1FusionOpMByteSize, RT_MEMORY_DDR));
  602. // send l1fusion dump addr to rts
  603. GE_CHK_RT_RET(rtDumpAddrSet(rt_model_handle_, l1_fusion_addr_, kDumpL1FusionOpMByteSize, kDumpFlagOfL1Fusion));
  604. }
  605. /// In zero copy model, if a aicpu operator is connected to the first or last layer, before model execution,
  606. /// the aicpu opertor needs to destroy history record, and update operator memory address.
  607. /// The model with specified aicpu operators is only marked here, and destruction is in ModelManager::ExecuteModel().
  608. need_destroy_aicpu_kernel_ = IsAicpuKernelConnectSpecifiedLayer();
  609. (void)ge::AttrUtils::GetListStr(ge_model_, ATTR_MODEL_OUT_NODES_NAME, out_node_name_);
  610. // collect profiling for ge
  611. if (ProfilingManager::Instance().ProfilingModelLoadOn()) {
  612. std::vector<ComputeGraphDescInfo> compute_graph_desc_info;
  613. Status ret1 = GetComputeGraphInfo(compute_graph, compute_graph_desc_info);
  614. if (ret1 != SUCCESS) {
  615. GELOGE(ret1, "GetComputeGraphInfo failed.");
  616. return ret1;
  617. }
  618. ProfilingManager::Instance().ReportProfilingData(GetTaskDescInfo(), compute_graph_desc_info);
  619. GE_CHK_STATUS(SinkModelProfile(), "Sink model profile failed.");
  620. }
  621. Shrink();
  622. GELOGI("Davinci model init success.");
  623. return ret;
  624. }
  625. ///
  626. /// @ingroup ge
  627. /// @brief Travel all nodes and determine if destruction is required.
  628. /// @return bool
  629. ///
  630. bool DavinciModel::IsAicpuKernelConnectSpecifiedLayer() {
  631. Graph graph = ge_model_->GetGraph();
  632. ComputeGraphPtr compute_graph = GraphUtils::GetComputeGraph(graph);
  633. auto all_nodes = compute_graph->GetAllNodes();
  634. for (auto &node : all_nodes) {
  635. GE_IF_BOOL_EXEC(node == nullptr, continue);
  636. OpDescPtr op_desc = node->GetOpDesc();
  637. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  638. int64_t imply_type = -1;
  639. (void)ge::AttrUtils::GetInt(op_desc, ATTR_NAME_IMPLY_TYPE, imply_type);
  640. if (imply_type != static_cast<int64_t>(domi::ImplyType::AI_CPU)) {
  641. continue;
  642. }
  643. GELOGD("Current operator imply type is %ld, name is %s.", imply_type, op_desc->GetName().c_str());
  644. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  645. GE_IF_BOOL_EXEC(in_data_anchor == nullptr, continue);
  646. auto peer_out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  647. GE_IF_BOOL_EXEC(peer_out_data_anchor == nullptr, continue);
  648. auto peer_node = peer_out_data_anchor->GetOwnerNode();
  649. GE_IF_BOOL_EXEC(peer_node == nullptr, continue);
  650. auto peer_op_desc = peer_node->GetOpDesc();
  651. GE_IF_BOOL_EXEC(peer_op_desc == nullptr, continue);
  652. if (IsDataOp(peer_op_desc->GetType())) {
  653. GELOGI("Mark specified aicpu operator connected to data.");
  654. return true;
  655. }
  656. }
  657. for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  658. GE_IF_BOOL_EXEC(out_data_anchor == nullptr, continue);
  659. auto peer_in_data_anchors = out_data_anchor->GetPeerInDataAnchors();
  660. for (auto &peer_in_data_anchor : peer_in_data_anchors) {
  661. GE_IF_BOOL_EXEC(peer_in_data_anchor == nullptr, continue);
  662. auto peer_node = peer_in_data_anchor->GetOwnerNode();
  663. GE_IF_BOOL_EXEC(peer_node == nullptr, continue);
  664. auto peer_op_desc = peer_node->GetOpDesc();
  665. GE_IF_BOOL_EXEC(peer_op_desc == nullptr, continue);
  666. if (peer_op_desc->GetType() == NETOUTPUT) {
  667. GELOGI("Mark specified aicpu operator connected to netoutput.");
  668. return true;
  669. }
  670. }
  671. }
  672. }
  673. return false;
  674. }
  675. Status DavinciModel::UpdateSessionId(uint64_t session_id) {
  676. GE_CHECK_NOTNULL(ge_model_);
  677. if (!AttrUtils::SetInt(ge_model_, MODEL_ATTR_SESSION_ID, static_cast<int64_t>(session_id))) {
  678. GELOGW("Set attr[%s] failed in updating session_id.", MODEL_ATTR_SESSION_ID.c_str());
  679. }
  680. GELOGD("Update session id: %lu.", session_id);
  681. return SUCCESS;
  682. }
  683. ///
  684. /// @ingroup ge
  685. /// @brief Travel all nodes and do some init.
  686. /// @param [in] compute_graph: ComputeGraph to load.
  687. /// @return Status
  688. ///
  689. Status DavinciModel::InitNodes(const ComputeGraphPtr &compute_graph) {
  690. uint32_t data_op_index = 0;
  691. GE_TIMESTAMP_CALLNUM_START(LoadTBEKernelBinToOpDesc);
  692. GE_TIMESTAMP_CALLNUM_START(InitTbeHandle);
  693. typedef Status (DavinciModel::*OpDescCall)(const OpDescPtr &);
  694. static std::map<std::string, OpDescCall> op_desc_handle = {
  695. {VARIABLE, &DavinciModel::InitVariable},
  696. {CONSTANTOP, &DavinciModel::InitConstant},
  697. {STREAMACTIVE, &DavinciModel::InitStreamActive},
  698. {STREAMSWITCH, &DavinciModel::InitStreamSwitch},
  699. {STREAMSWITCHN, &DavinciModel::InitStreamSwitchN},
  700. {LABELSET, &DavinciModel::InitLabelSet},
  701. {CASE, &DavinciModel::InitCase},
  702. };
  703. GE_CHK_STATUS_RET(InitInputOutputForDynamic(compute_graph), "InitInputOutputForDynamic failed.");
  704. map<uint32_t, OpDescPtr> data_by_index;
  705. auto nodes = compute_graph->GetAllNodes();
  706. const CustAICPUKernelStore &aicpu_kernel_store = ge_model_->GetCustAICPUKernelStore();
  707. for (size_t i = 0; i < nodes.size(); i++) {
  708. auto node = nodes.at(i);
  709. auto op_desc = node->GetOpDesc();
  710. if (op_desc == nullptr) {
  711. GELOGE(PARAM_INVALID, "op_desc is null.");
  712. return PARAM_INVALID;
  713. }
  714. op_list_[op_desc->GetId()] = op_desc;
  715. GE_TIMESTAMP_RESTART(LoadTBEKernelBinToOpDesc);
  716. aicpu_kernel_store.LoadCustAICPUKernelBinToOpDesc(op_desc);
  717. GE_TIMESTAMP_ADD(LoadTBEKernelBinToOpDesc);
  718. if (IsDataOp(op_desc->GetType())) {
  719. if (InitDataOp(node, data_op_index, data_by_index) != SUCCESS) {
  720. GELOGE(PARAM_INVALID, "Data init failed, Name: %s", op_desc->GetName().c_str());
  721. return PARAM_INVALID;
  722. }
  723. data_dumper_.SaveDumpInput(node);
  724. continue;
  725. }
  726. if (op_desc->GetType() == NETOUTPUT) {
  727. if (InitNetOutput(node) != SUCCESS) {
  728. GELOGE(PARAM_INVALID, "NetOutput init failed, Name: %s", op_desc->GetName().c_str());
  729. return PARAM_INVALID;
  730. }
  731. continue;
  732. }
  733. auto it = op_desc_handle.find(op_desc->GetType());
  734. if (it != op_desc_handle.end()) {
  735. if ((this->*it->second)(op_desc) != SUCCESS) {
  736. GELOGE(PARAM_INVALID, "NetOutput init failed, Name: %s", op_desc->GetName().c_str());
  737. return PARAM_INVALID;
  738. }
  739. continue;
  740. }
  741. // for dynamic shape with control flow
  742. SetLabelForDynamic(node);
  743. if (IsNoTaskAndDumpNeeded(op_desc)) {
  744. GELOGD("node[%s] without task, and save op_desc and addr for dump", op_desc->GetName().c_str());
  745. const RuntimeParam &rts_param = GetRuntimeParam();
  746. const vector<void *> input_data_addrs = ModelUtils::GetInputDataAddrs(rts_param, op_desc);
  747. const vector<void *> output_data_addrs = ModelUtils::GetOutputDataAddrs(rts_param, op_desc);
  748. const vector<void *> workspace_data_addrs = ModelUtils::GetWorkspaceDataAddrs(rts_param, op_desc);
  749. vector<void *> tensor_device_addrs;
  750. tensor_device_addrs.insert(tensor_device_addrs.end(), input_data_addrs.begin(), input_data_addrs.end());
  751. tensor_device_addrs.insert(tensor_device_addrs.end(), output_data_addrs.begin(), output_data_addrs.end());
  752. tensor_device_addrs.insert(tensor_device_addrs.end(), workspace_data_addrs.begin(), workspace_data_addrs.end());
  753. void *addr = nullptr;
  754. auto size = kAddrLen * tensor_device_addrs.size();
  755. GE_CHK_RT_RET(rtMalloc(&addr, size, RT_MEMORY_HBM));
  756. rtError_t rt_ret = rtMemcpy(addr, size, tensor_device_addrs.data(), size, RT_MEMCPY_HOST_TO_DEVICE);
  757. if (rt_ret != RT_ERROR_NONE) {
  758. GELOGE(RT_FAILED, "rtMemcpy error, ret: 0x%X", rt_ret);
  759. GE_CHK_RT(rtFree(addr));
  760. return RT_ERROR_TO_GE_STATUS(rt_ret);
  761. }
  762. saved_task_addrs_.emplace(op_desc, addr);
  763. }
  764. GE_TIMESTAMP_RESTART(InitTbeHandle);
  765. uint32_t run_mode = static_cast<uint32_t>(domi::ImplyType::INVALID);
  766. if (AttrUtils::GetInt(op_desc, ATTR_NAME_IMPLY_TYPE, run_mode) &&
  767. run_mode == static_cast<uint32_t>(domi::ImplyType::TVM)) {
  768. // Skip no_task operator, such as concat and split.
  769. bool attr_notask = false;
  770. bool get_attr_notask_flag = ge::AttrUtils::GetBool(op_desc, ATTR_NAME_NOTASK, attr_notask);
  771. GE_IF_BOOL_EXEC(get_attr_notask_flag && attr_notask,
  772. GELOGI("Node[name:%s, type:%s] does not generate task, skip initialization.",
  773. op_desc->GetName().c_str(), op_desc->GetType().c_str());
  774. continue;);
  775. Status status = InitTbeHandle(op_desc);
  776. if (status != SUCCESS) {
  777. GELOGE(status, "TBE init failed. %s", op_desc->GetName().c_str());
  778. return status;
  779. }
  780. }
  781. GE_TIMESTAMP_ADD(InitTbeHandle);
  782. }
  783. AdjustDataOpList(data_by_index);
  784. GE_TIMESTAMP_CALLNUM_END(LoadTBEKernelBinToOpDesc, "GraphLoader::LoadTBEKernelBinToOpDesc.");
  785. GE_TIMESTAMP_CALLNUM_END(InitTbeHandle, "GraphLoader::InitTbeHandle.");
  786. return SUCCESS;
  787. }
  788. Status DavinciModel::InitInputOutputForDynamic(const ComputeGraphPtr &compute_graph) {
  789. if (!known_node_) return SUCCESS;
  790. // for dynamic shape
  791. auto direct_nodes = compute_graph->GetDirectNode();
  792. for (size_t i = 0; i < direct_nodes.size(); i++) {
  793. auto node = direct_nodes.at(i);
  794. auto op_desc = node->GetOpDesc();
  795. if (op_desc == nullptr) {
  796. GELOGE(PARAM_INVALID, "op_desc is null.");
  797. return PARAM_INVALID;
  798. }
  799. if (IsDataOp(op_desc->GetType())) {
  800. GELOGD("init data op %s", op_desc->GetName().c_str());
  801. data_op_list_.push_back(op_desc);
  802. }
  803. if (op_desc->GetType() == NETOUTPUT) {
  804. GELOGD("init netouput op %s", op_desc->GetName().c_str());
  805. output_op_list_.push_back(op_desc);
  806. }
  807. }
  808. return SUCCESS;
  809. }
  810. void DavinciModel::SetLabelForDynamic(const NodePtr &node) {
  811. if (known_node_ && node->GetOpDesc()->GetType() == LABELSWITCHBYINDEX) {
  812. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  813. auto peer_out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  814. if (peer_out_data_anchor != nullptr) {
  815. string tensor_name = node->GetName();
  816. auto peer_node = peer_out_data_anchor->GetOwnerNode();
  817. (void)AttrUtils::SetStr(peer_node->GetOpDesc(), ATTR_DYNAMIC_SHAPE_FIXED_ADDR, tensor_name);
  818. (void)AttrUtils::SetInt(peer_node->GetOpDesc(), ATTR_DYNAMIC_SHAPE_FIXED_ADDR_INDEX, 0);
  819. tensor_name_to_peer_output_index_[tensor_name] = 0;
  820. }
  821. }
  822. }
  823. }
  824. /// @ingroup ge
  825. /// @brief Data Op Initialize.
  826. /// @param [in] NodePtr: Data Op.
  827. /// @param [in/out] data_op_index: NetOutput addr size info.
  828. /// @return Status
  829. Status DavinciModel::InitDataOp(const NodePtr &node, uint32_t &data_op_index, map<uint32_t, OpDescPtr> &data_by_index) {
  830. // op_desc Checked by Init: Data, valid.
  831. auto op_desc = node->GetOpDesc();
  832. if (known_node_) {
  833. return SUCCESS;
  834. }
  835. uint32_t parent_index = 0; // Ignore subgraph Data Node.
  836. if (AttrUtils::GetInt(op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  837. GELOGI("Init zero copy by subgraph Data node: %s.", op_desc->GetName().c_str());
  838. return InitInputBatchLabel(node);
  839. }
  840. data_op_list_.push_back(op_desc);
  841. // Make information for copy input data.
  842. const vector<int64_t> output_size_list = ModelUtils::GetOutputSize(op_desc);
  843. const vector<void *> virtual_addr_list = ModelUtils::GetOutputDataAddrs(runtime_param_, op_desc);
  844. const vector<int64_t> output_offset_list = op_desc->GetOutputOffset();
  845. if (output_offset_list.size() != virtual_addr_list.size()) {
  846. GELOGE(PARAM_INVALID, "virtual_addr size:%zu should be equal to offset size:%zu.", virtual_addr_list.size(),
  847. output_offset_list.size());
  848. return PARAM_INVALID;
  849. }
  850. auto data_index = data_op_index;
  851. if (AttrUtils::GetInt(op_desc, ATTR_NAME_INDEX, data_index)) {
  852. GELOGI("ge_train: get new index %u, old %u", data_index, data_op_index);
  853. }
  854. bool fusion_flag = false;
  855. ZeroCopyOffset zero_copy_offset;
  856. Status ret = zero_copy_offset.InitInputDataInfo(output_size_list, virtual_addr_list, op_desc, fusion_flag);
  857. if (ret != SUCCESS) {
  858. GELOGE(PARAM_INVALID, "InitDataInfo of input_info %s failed.", op_desc->GetName().c_str());
  859. return PARAM_INVALID;
  860. }
  861. new_input_data_info_[data_index] = zero_copy_offset;
  862. data_by_index[data_index] = op_desc;
  863. for (size_t index = 0; index < virtual_addr_list.size(); ++index) {
  864. void *addr = virtual_addr_list.at(index);
  865. if (new_input_outside_addrs_.find(addr) != new_input_outside_addrs_.end()) {
  866. continue;
  867. }
  868. zero_copy_offset.SetInputOutsideAddrs(output_offset_list, addr, index, fusion_flag, real_virtual_addrs_);
  869. new_input_outside_addrs_[addr] = zero_copy_offset;
  870. }
  871. GELOGI("SetInputOutsideAddr success.");
  872. data_op_index++;
  873. if (InitInputZeroCopyNodes(node) != SUCCESS) {
  874. GELOGE(PARAM_INVALID, "Input zero copy nodes init failed!");
  875. return PARAM_INVALID;
  876. }
  877. return SUCCESS;
  878. }
  879. ///
  880. /// @ingroup ge
  881. /// @brief Sort Data op list by index.
  882. /// @param [in] data_by_index: map of Data Op.
  883. /// @return
  884. ///
  885. void DavinciModel::AdjustDataOpList(const map<uint32_t, OpDescPtr> &data_by_index) {
  886. if (data_by_index.size() != data_op_list_.size()) {
  887. GELOGW("Data map size: %zu, Data list size: %zu.", data_by_index.size(), data_op_list_.size());
  888. return;
  889. }
  890. data_op_list_.clear();
  891. for (auto &item : data_by_index) {
  892. data_op_list_.emplace_back(item.second);
  893. }
  894. }
  895. ///
  896. /// @ingroup ge
  897. /// @brief input zero copy node Initialize.
  898. /// @param [in] NodePtr: Data Op.
  899. /// @return Status
  900. ///
  901. Status DavinciModel::InitInputZeroCopyNodes(const NodePtr &node) {
  902. auto out_data_anchor = node->GetOutDataAnchor(kDataIndex);
  903. if (out_data_anchor == nullptr) {
  904. GELOGE(FAILED, "Out data anchor is nullptr");
  905. return FAILED;
  906. }
  907. for (auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  908. auto node = peer_in_data_anchor->GetOwnerNode();
  909. auto op_desc = node->GetOpDesc();
  910. if (op_desc == nullptr) {
  911. GELOGE(FAILED, "Op desc is nullptr");
  912. return FAILED;
  913. }
  914. string batch_label;
  915. (void)ge::AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label);
  916. if (batch_label.empty()) {
  917. batch_label = kDefaultBatchLable;
  918. }
  919. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  920. zero_copy_op_id_batch_label_.emplace(pair<int64_t, string>(op_desc->GetId(), batch_label));
  921. GELOGD("Init input zero copy nodes success, op name:%s, op id: %ld, batch label: %s.", op_desc->GetName().c_str(),
  922. op_desc->GetId(), batch_label.c_str());
  923. }
  924. }
  925. return SUCCESS;
  926. }
  927. bool DavinciModel::IsGetNextSinkDynamic(const OpDescPtr &op_desc) {
  928. bool getnext_sink_dynamic = false;
  929. if (ge::AttrUtils::GetBool(op_desc, ATTR_GETNEXT_SINK_DYNMAIC, getnext_sink_dynamic) && getnext_sink_dynamic) {
  930. GELOGI("ATTR_GETNEXT_SINK_DYNMAIC has been set and is true.");
  931. return true;
  932. }
  933. return false;
  934. }
  935. /// @ingroup ge
  936. /// @brief NetOutput Op Initialize.
  937. /// @param [in] NodePtr: NetOutput Op.
  938. /// @return Status
  939. Status DavinciModel::InitNetOutput(const NodePtr &node) {
  940. // node->GetOpDesc Checked by Init: NetOutput, valid.
  941. auto op_desc = node->GetOpDesc();
  942. // excludes the function op sub graph, e.g. case,if
  943. if (known_node_) {
  944. return SUCCESS;
  945. }
  946. ComputeGraphPtr owner_graph = node->GetOwnerComputeGraph();
  947. GE_CHECK_NOTNULL(owner_graph);
  948. if (owner_graph->GetParentGraph() != nullptr) {
  949. GELOGI("Init zero copy by subgraph NetOutput node: %s.", op_desc->GetName().c_str());
  950. op_list_.erase(op_desc->GetId());
  951. return InitOutputBatchLabel(node);
  952. }
  953. output_op_list_.push_back(op_desc);
  954. // Make information for copy output data.
  955. const vector<int64_t> input_size_list = ModelUtils::GetInputSize(op_desc);
  956. const vector<void *> virtual_addr_list = ModelUtils::GetInputDataAddrs(runtime_param_, op_desc);
  957. const vector<int64_t> input_offset_list = op_desc->GetInputOffset();
  958. GE_IF_BOOL_EXEC(input_offset_list.size() != virtual_addr_list.size(),
  959. GELOGE(PARAM_INVALID, "virtual_addr size should be equal to offset size."); return PARAM_INVALID;);
  960. if (input_size_list.empty() && virtual_addr_list.empty()) {
  961. GELOGI("NetOutput[%s] is empty.", op_desc->GetName().c_str());
  962. return SUCCESS;
  963. }
  964. if (input_size_list.empty() || input_size_list.size() != virtual_addr_list.size()) {
  965. GELOGE(PARAM_INVALID, "NetOutput[%s] init failed: Input size is %zu, Input addr is %zu", op_desc->GetName().c_str(),
  966. input_size_list.size(), virtual_addr_list.size());
  967. return PARAM_INVALID;
  968. }
  969. size_t num = new_output_data_info_.size();
  970. bool fusion_flag = false;
  971. size_t input_count = input_size_list.size();
  972. is_getnext_sink_dynamic_ = false;
  973. if (IsGetNextSinkDynamic(op_desc)) {
  974. input_count = input_size_list.size() - kGetDynamicDimsCount;
  975. is_getnext_sink_dynamic_ = true;
  976. }
  977. for (size_t idx = 0; idx < input_count; ++idx) {
  978. ZeroCopyOffset zero_copy_offset;
  979. Status ret = zero_copy_offset.InitOutputDataInfo(input_size_list, virtual_addr_list, op_desc, idx, fusion_flag);
  980. GE_IF_BOOL_EXEC(ret != SUCCESS, GELOGE(PARAM_INVALID, "InitDataInfo of input_info %s failed.",
  981. op_desc->GetName().c_str()); return PARAM_INVALID;);
  982. new_output_data_info_[num + idx] = zero_copy_offset;
  983. void *addr = virtual_addr_list.at(idx);
  984. int64_t input_offset = input_offset_list.at(idx);
  985. vector<void *> tensor_addrs;
  986. zero_copy_offset.SetOutputOutsideAddrs(input_offset, fusion_flag, addr, tensor_addrs);
  987. auto rslt = new_output_outside_addrs_.insert(std::pair<void *, ZeroCopyOffset>(addr, zero_copy_offset));
  988. if (!rslt.second) {
  989. GELOGI("same output_tensor_addr %p to different input_tensor of %s", addr, op_desc->GetName().c_str());
  990. DisableZeroCopy(addr);
  991. }
  992. for (size_t i = 0; i < tensor_addrs.size(); ++i) {
  993. void *real_addr = tensor_addrs.at(i);
  994. DisableZeroCopy(real_addr);
  995. real_virtual_addrs_.insert(real_addr);
  996. }
  997. GELOGI("SetOutputOutsideAddr success.");
  998. }
  999. GE_IF_BOOL_EXEC(InitOutputZeroCopyNodes(node) != SUCCESS,
  1000. GELOGE(PARAM_INVALID, "Output zero copy nodes init failed!"); return PARAM_INVALID;);
  1001. GetAllGearsInfo(node);
  1002. if (is_getnext_sink_dynamic_) {
  1003. GE_IF_BOOL_EXEC(GetGetDynamicDimsNodeInfo(node) != SUCCESS,
  1004. GELOGE(PARAM_INVALID, "Failed to get info of getdynamicdims node."); return PARAM_INVALID;);
  1005. }
  1006. if (is_online_infer_dynamic_) {
  1007. GE_IF_BOOL_EXEC(GetGearAndRealOutSizeInfo(input_count, node) != SUCCESS,
  1008. GELOGE(PARAM_INVALID, "Failed to get gear and real out size info."); return PARAM_INVALID;);
  1009. GE_IF_BOOL_EXEC(GetGearAndRealOutShapeInfo(input_count, op_desc) != SUCCESS,
  1010. GELOGE(PARAM_INVALID, "Failed to get gear and real out shape info."); return PARAM_INVALID;);
  1011. }
  1012. GELOGI("DavinciModel::InitNetoutput success.");
  1013. return SUCCESS;
  1014. }
  1015. void DavinciModel::GetAllGearsInfo(const NodePtr &node) {
  1016. is_online_infer_dynamic_ = false;
  1017. all_gears_info_.clear();
  1018. std::string shapes;
  1019. (void) AttrUtils::GetStr(node->GetOpDesc(), ATTR_ALL_GEARS_INFO, shapes);
  1020. if (!shapes.empty()) {
  1021. is_online_infer_dynamic_ = true;
  1022. std::vector<std::string> shape_strs = ge::StringUtils::Split(shapes, ';');
  1023. for (const auto &shape_str : shape_strs) {
  1024. if (shape_str.empty()) {
  1025. continue;
  1026. }
  1027. std::vector<int64_t> gear_info;
  1028. std::vector<std::string> dims = ge::StringUtils::Split(shape_str, ',');
  1029. for (const auto &dim : dims) {
  1030. if (dim.empty()) {
  1031. continue;
  1032. }
  1033. gear_info.emplace_back(std::strtol(dim.c_str(), nullptr, kDecimal));
  1034. }
  1035. if (!gear_info.empty()) {
  1036. all_gears_info_.emplace_back(gear_info);
  1037. GELOGD("Init all gears info from %s, gaer info is %s.", node->GetName().c_str(),
  1038. formats::JoinToString(gear_info).c_str());
  1039. }
  1040. }
  1041. }
  1042. }
  1043. Status DavinciModel::GetGetDynamicDimsNodeInfo(const NodePtr &node) {
  1044. GE_CHECK_NOTNULL(node->GetOpDesc());
  1045. size_t input_count = node->GetAllInDataAnchors().size();
  1046. GELOGI("input_anchor count of %s is %zu.", node->GetName().c_str(), input_count);
  1047. size_t get_dynamic_dims_index = input_count - kGetDynamicDimsCount;
  1048. auto in_anchor = node->GetAllInDataAnchors().at(get_dynamic_dims_index);
  1049. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  1050. if (peer_out_anchor == nullptr) {
  1051. GELOGE(PARAM_INVALID, "Out anchor of getdynmaicdims node should not be nullptr.");
  1052. return PARAM_INVALID;
  1053. }
  1054. auto peer_node = peer_out_anchor->GetOwnerNode();
  1055. auto op_desc = peer_node->GetOpDesc();
  1056. GE_CHECK_NOTNULL(op_desc);
  1057. if (op_desc->GetName() == kGetDynamicDimsName && op_desc->GetType() == GETDYNAMICDIMS) {
  1058. GELOGD("Start get info of %s.", op_desc->GetName().c_str());
  1059. auto input_addr = ModelUtils::GetInputDataAddrs(runtime_param_, node->GetOpDesc());
  1060. auto input_size = ModelUtils::GetInputSize(node->GetOpDesc());
  1061. if (input_addr.empty() || input_size.empty()) {
  1062. GELOGE(PARAM_INVALID, "Not set output of %s", op_desc->GetName().c_str());
  1063. return PARAM_INVALID;
  1064. }
  1065. auto input_desc = node->GetOpDesc()->GetInputDescPtr(get_dynamic_dims_index);
  1066. GE_CHECK_NOTNULL(input_desc);
  1067. if (input_desc->GetShape().GetDims().empty()) {
  1068. GELOGE(PARAM_INVALID, "Not set output desc shape of %s.", op_desc->GetName().c_str());
  1069. return PARAM_INVALID;
  1070. }
  1071. netoutput_last_input_addr_ = input_addr[get_dynamic_dims_index];
  1072. netoutput_last_input_size_ = input_size[get_dynamic_dims_index];
  1073. shape_of_cur_dynamic_dims_ = input_desc->GetShape().GetDims().at(0);
  1074. GELOGD("Shape of cur dynamic dims is %zu, size is %ld, addr is 0x%X.", shape_of_cur_dynamic_dims_,
  1075. netoutput_last_input_size_,netoutput_last_input_addr_);
  1076. }
  1077. return SUCCESS;
  1078. }
  1079. Status DavinciModel::GetGearAndRealOutSizeInfo(size_t input_count, const NodePtr &node) {
  1080. GELOGD("Start get gear and real output size info of %s, input count is %zu.", node->GetName().c_str(), input_count);
  1081. merge_nodes_gear_and_real_out_size_info_.clear();
  1082. for (size_t idx = 0; idx < input_count; ++idx) {
  1083. auto in_anchor = node->GetAllInDataAnchors().at(idx);
  1084. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  1085. if (peer_out_anchor == nullptr) {
  1086. continue;
  1087. }
  1088. auto peer_node = peer_out_anchor->GetOwnerNode();
  1089. auto op_desc = peer_node->GetOpDesc();
  1090. GE_CHECK_NOTNULL(op_desc);
  1091. if ((peer_node->GetType() == MERGE) && (op_desc->HasAttr(ATTR_INSERT_BY_MBATCH))) {
  1092. if (GetRealOutputSizeOfMerge(idx, peer_node) != SUCCESS) {
  1093. GELOGE(PARAM_INVALID, "Get real output size of %s failed.", peer_node->GetName().c_str());
  1094. return PARAM_INVALID;
  1095. }
  1096. }
  1097. }
  1098. return SUCCESS;
  1099. }
  1100. Status DavinciModel::GetRealOutputSizeOfMerge(size_t input_index, const NodePtr &merge_node) {
  1101. GELOGD("Start get output size of %s, which is %zu input to netoutput.", merge_node->GetName().c_str(), input_index);
  1102. std::map<vector<int64_t>, int64_t> gear_and_real_out_size_info;
  1103. for (auto &in_anchor : merge_node->GetAllInDataAnchors()) {
  1104. auto peer_out_anchor = in_anchor->GetPeerOutAnchor();
  1105. if (peer_out_anchor == nullptr) {
  1106. continue;
  1107. }
  1108. auto in_node = peer_out_anchor->GetOwnerNode();
  1109. GELOGD("Input node of merge is %s.", in_node->GetName().c_str());
  1110. auto op_desc = in_node->GetOpDesc();
  1111. GE_CHECK_NOTNULL(op_desc);
  1112. string batch_label;
  1113. if (AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label)) {
  1114. size_t batch_index = static_cast<size_t>(stoi(batch_label.substr(batch_label.rfind('_') + 1)));
  1115. GELOGD("Batch index of %s is %zu.", op_desc->GetName().c_str(), batch_index);
  1116. if (batch_index > all_gears_info_.size()) {
  1117. GELOGE(PARAM_INVALID, "The value of ATTR_NAME_BATCH_LABEL is invalid.");
  1118. return PARAM_INVALID;
  1119. }
  1120. const vector<int64_t> output_size_list = ModelUtils::GetOutputSize(op_desc);
  1121. int output_index = ge::AnchorUtils::GetIdx(peer_out_anchor);
  1122. auto tensor_desc = op_desc->GetOutputDescPtr(output_index);
  1123. GE_CHECK_NOTNULL(tensor_desc);
  1124. int64_t data_size = 0;
  1125. if (TensorUtils::GetTensorSizeInBytes(*tensor_desc, data_size) != GRAPH_SUCCESS) {
  1126. GELOGE(FAILED, "Get tensor size in bytes failed.");
  1127. return FAILED;
  1128. }
  1129. gear_and_real_out_size_info[all_gears_info_[batch_index]] = data_size;
  1130. GELOGD("Get real gear index is: %zu, gear info is %s, size is %ld, tensor size is %ld",
  1131. batch_index, formats::JoinToString(all_gears_info_[batch_index]).c_str(),
  1132. output_size_list[output_index], data_size);
  1133. }
  1134. }
  1135. merge_nodes_gear_and_real_out_size_info_[input_index] = gear_and_real_out_size_info;
  1136. return SUCCESS;
  1137. }
  1138. Status DavinciModel::GetGearAndRealOutShapeInfo(size_t input_count, const OpDescPtr &op_desc) {
  1139. GELOGD("Start to get dynamic output dims of %s.", op_desc->GetName().c_str());
  1140. merge_nodes_gear_and_real_out_shape_info_.clear();
  1141. std::vector<std::string> dynamic_output_shape_info;
  1142. if (!AttrUtils::GetListStr(op_desc, ATTR_NAME_DYNAMIC_OUTPUT_DIMS, dynamic_output_shape_info)) {
  1143. GELOGD("Can not get dynamic output dims attr");
  1144. return SUCCESS;
  1145. }
  1146. GELOGI("Dynamic output shape info is %s", formats::JoinToString(dynamic_output_shape_info).c_str());
  1147. std::vector<vector<int64_t>> dynamic_output_shape;
  1148. ParseDynamicOutShape(dynamic_output_shape_info, dynamic_output_shape);
  1149. // idx: input_index to netoutput
  1150. for (size_t idx = 0; idx < input_count; ++idx) {
  1151. std::map<vector<int64_t>, vector<int64_t>> gear_and_real_out_shape_info;
  1152. for (auto &it : dynamic_output_shape) {
  1153. auto gear_index = static_cast<size_t>(it[0]);
  1154. if (gear_index > all_gears_info_.size()) {
  1155. GELOGE(PARAM_INVALID, "The value of cur index: %zu is invalid.", static_cast<size_t>(it[0]));
  1156. return PARAM_INVALID;
  1157. }
  1158. if (static_cast<size_t>(it[1]) == idx) {
  1159. vector<int64_t> output_shape;
  1160. for (size_t i = 2; i < it.size(); ++i) {
  1161. output_shape.emplace_back(it[i]);
  1162. }
  1163. gear_and_real_out_shape_info[all_gears_info_[gear_index]] = output_shape;
  1164. GELOGD("Get real gear index is: %zu, gear info is %s, output shape is %s.",
  1165. gear_index, formats::JoinToString(all_gears_info_[gear_index]).c_str(),
  1166. formats::JoinToString(output_shape).c_str());
  1167. }
  1168. }
  1169. merge_nodes_gear_and_real_out_shape_info_[idx] = gear_and_real_out_shape_info;
  1170. }
  1171. return SUCCESS;
  1172. }
  1173. void DavinciModel::ParseDynamicOutShape(const std::vector<std::string> &str_info, std::vector<vector<int64_t>> &vec_info) {
  1174. for (size_t i = 0; i < str_info.size(); ++i) {
  1175. std::vector<int64_t> shape;
  1176. std::vector<std::string> dims = ge::StringUtils::Split(str_info[i], ',');
  1177. for (const auto &dim : dims) {
  1178. if (dim.empty()) {
  1179. continue;
  1180. }
  1181. shape.emplace_back(std::strtol(dim.c_str(), nullptr, kDecimal));
  1182. }
  1183. GELOGI("Shape from attr is %s.", formats::JoinToString(shape).c_str());
  1184. vec_info.emplace_back(shape);
  1185. }
  1186. }
  1187. ///
  1188. /// @ingroup ge
  1189. /// @brief output zero copy node Initialize.
  1190. /// @param [in] NodePtr: netoutput Op.
  1191. /// @return Status
  1192. ///
  1193. Status DavinciModel::InitOutputZeroCopyNodes(const NodePtr &node) {
  1194. set<NodePtr> nodes_need_record;
  1195. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1196. auto peer_out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  1197. if (peer_out_data_anchor == nullptr) {
  1198. continue;
  1199. }
  1200. auto peer_node = peer_out_data_anchor->GetOwnerNode();
  1201. nodes_need_record.emplace(peer_node);
  1202. // Merge node output multiplexed input, upstream nodes need to be considered in multiple batch scenarios
  1203. if (peer_node->GetType() == MERGE) {
  1204. for (const auto &merge_peer_in_data_anchor : peer_node->GetAllInDataAnchors()) {
  1205. auto merge_peer_out_data_anchor = merge_peer_in_data_anchor->GetPeerOutAnchor();
  1206. if (merge_peer_out_data_anchor == nullptr) {
  1207. continue;
  1208. }
  1209. auto merge_peer_node = merge_peer_out_data_anchor->GetOwnerNode();
  1210. nodes_need_record.emplace(merge_peer_node);
  1211. }
  1212. } else {
  1213. for (const auto &other_in_data_anchor : peer_out_data_anchor->GetPeerInDataAnchors()) {
  1214. auto other_in_node = other_in_data_anchor->GetOwnerNode();
  1215. if (other_in_node->GetType() != NETOUTPUT) {
  1216. nodes_need_record.emplace(other_in_node);
  1217. }
  1218. }
  1219. }
  1220. }
  1221. for (const auto &node_need_record : nodes_need_record) {
  1222. auto op_desc = node_need_record->GetOpDesc();
  1223. GE_CHECK_NOTNULL(op_desc);
  1224. string batch_label;
  1225. (void)ge::AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label);
  1226. if (batch_label.empty()) {
  1227. batch_label = kDefaultBatchLable;
  1228. }
  1229. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  1230. zero_copy_op_id_batch_label_.emplace(pair<int64_t, string>(op_desc->GetId(), batch_label));
  1231. GELOGD("Init Output zero copy nodes success, op name:%s, op id: %ld, batch label: %s.",
  1232. op_desc->GetName().c_str(), op_desc->GetId(), batch_label.c_str());
  1233. }
  1234. }
  1235. return SUCCESS;
  1236. }
  1237. ///
  1238. /// @ingroup ge
  1239. /// @brief input zero copy node Initialize.
  1240. /// @param [in] NodePtr: Data Op.
  1241. /// @return Status
  1242. ///
  1243. Status DavinciModel::InitInputBatchLabel(const NodePtr &node) {
  1244. string batch_label;
  1245. if (!AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_BATCH_LABEL, batch_label)) {
  1246. return SUCCESS; // Not Multi-batch.
  1247. }
  1248. const auto &out_data_anchor = node->GetOutDataAnchor(kDataIndex);
  1249. GE_CHECK_NOTNULL(out_data_anchor);
  1250. for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  1251. const auto &node = peer_in_data_anchor->GetOwnerNode();
  1252. const auto &op_desc = node->GetOpDesc();
  1253. GE_CHECK_NOTNULL(op_desc);
  1254. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  1255. zero_copy_op_id_batch_label_[op_desc->GetId()] = batch_label;
  1256. GELOGD("Init input zero copy nodes success, op name: %s, op id: %ld, batch label: %s", op_desc->GetName().c_str(),
  1257. op_desc->GetId(), batch_label.c_str());
  1258. }
  1259. }
  1260. return SUCCESS;
  1261. }
  1262. ///
  1263. /// @ingroup ge
  1264. /// @brief output zero copy node Initialize for Case.
  1265. /// @param [in] NodePtr: netoutput Op.
  1266. /// @return Status
  1267. ///
  1268. Status DavinciModel::InitOutputBatchLabel(const NodePtr &node) {
  1269. string batch_label;
  1270. if (!AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_BATCH_LABEL, batch_label)) {
  1271. return SUCCESS; // Not Multi-batch.
  1272. }
  1273. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1274. const auto &peer_out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  1275. if (peer_out_data_anchor == nullptr) {
  1276. continue;
  1277. }
  1278. const auto &peer_node = peer_out_data_anchor->GetOwnerNode();
  1279. const auto &op_desc = peer_node->GetOpDesc();
  1280. GE_CHECK_NOTNULL(op_desc);
  1281. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  1282. zero_copy_op_id_batch_label_[op_desc->GetId()] = batch_label;
  1283. GELOGD("Init Output zero copy nodes success, op name: %s, op id: %ld, batch label: %s",
  1284. op_desc->GetName().c_str(), op_desc->GetId(), batch_label.c_str());
  1285. }
  1286. }
  1287. return SUCCESS;
  1288. }
  1289. /// @ingroup ge
  1290. /// @brief LabelSet Op Initialize.
  1291. /// @param [in] op_desc: LabelSet Op descriptor.
  1292. /// @return Status
  1293. Status DavinciModel::InitLabelSet(const OpDescPtr &op_desc) {
  1294. uint32_t label_index = 0;
  1295. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_LABEL_SWITCH_INDEX, label_index)) {
  1296. GELOGE(INTERNAL_ERROR, "InitLabelSet: %s attr [%s] not exist.", op_desc->GetName().c_str(),
  1297. ATTR_NAME_LABEL_SWITCH_INDEX.c_str());
  1298. return INTERNAL_ERROR;
  1299. }
  1300. if (label_index >= LabelNum()) {
  1301. GELOGE(INTERNAL_ERROR, "InitLabelSet: label index: %u >= label size: %zu.", label_index, LabelNum());
  1302. return INTERNAL_ERROR;
  1303. }
  1304. if (label_id_indication_.count(label_index) > 0) {
  1305. GELOGE(INTERNAL_ERROR, "InitLabelSet: %s label index: %u already used.", op_desc->GetName().c_str(), label_index);
  1306. return INTERNAL_ERROR;
  1307. }
  1308. rtStream_t stream = nullptr;
  1309. uint32_t stream_id = static_cast<uint32_t>(op_desc->GetStreamId());
  1310. if (stream_list_.size() == 1) {
  1311. stream = stream_list_[0];
  1312. } else if (stream_list_.size() > stream_id) {
  1313. stream = stream_list_[stream_id];
  1314. } else {
  1315. GELOGE(INTERNAL_ERROR, "InitLabelSet: stream index: %u >= stream size: %zu.", stream_id, stream_list_.size());
  1316. return INTERNAL_ERROR;
  1317. }
  1318. rtLabel_t rt_label = nullptr;
  1319. rtError_t rt_error = rtLabelCreateEx(&rt_label, stream);
  1320. if (rt_error != RT_ERROR_NONE || rt_label == nullptr) {
  1321. GELOGE(INTERNAL_ERROR, "InitLabelSet: %s create label failed, error=0x%x.", op_desc->GetName().c_str(), rt_error);
  1322. return INTERNAL_ERROR;
  1323. }
  1324. GELOGI("InitLabelSet: label[%u]=%p stream[%u]=%p.", label_index, rt_label, stream_id, stream);
  1325. label_id_indication_.insert(label_index);
  1326. label_list_[label_index] = rt_label;
  1327. return SUCCESS;
  1328. }
  1329. Status DavinciModel::InitVariable(const OpDescPtr &op_desc) {
  1330. variable_op_list_.push_back(op_desc);
  1331. return SUCCESS;
  1332. }
  1333. /// @ingroup ge
  1334. /// @brief ACL case, Load task list with queue.
  1335. /// @param [in] input_queue_ids: input queue ids from user, nums equal Data Op.
  1336. /// @param [in] output_queue_ids: input queue ids from user, nums equal NetOutput Op.
  1337. /// @return: 0 for success / others for failed
  1338. Status DavinciModel::SetQueIds(const std::vector<uint32_t> &input_queue_ids,
  1339. const std::vector<uint32_t> &output_queue_ids) {
  1340. if (input_queue_ids.empty() && output_queue_ids.empty()) {
  1341. GELOGE(GE_EXEC_MODEL_QUEUE_ID_INVALID, "Param is empty");
  1342. return GE_EXEC_MODEL_QUEUE_ID_INVALID;
  1343. }
  1344. input_queue_ids_ = input_queue_ids;
  1345. output_queue_ids_ = output_queue_ids;
  1346. return SUCCESS;
  1347. }
  1348. ///
  1349. /// @ingroup ge
  1350. /// @brief ACL case, Load task list with queue.
  1351. /// @param [in] input_que_ids: input queue ids from user, nums equal Data Op.
  1352. /// @param [in] output_que_ids: input queue ids from user, nums equal NetOutput Op.
  1353. /// @return: 0 for success / others for failed
  1354. ///
  1355. Status DavinciModel::LoadWithQueue() {
  1356. if (input_queue_ids_.empty() && output_queue_ids_.empty()) {
  1357. return SUCCESS;
  1358. }
  1359. if (input_queue_ids_.size() != new_input_data_info_.size()) {
  1360. GELOGE(GE_EXEC_MODEL_QUEUE_ID_INVALID, "Input queue ids not match model: input_queue=%zu input_data=%zu",
  1361. input_queue_ids_.size(), new_input_data_info_.size());
  1362. return GE_EXEC_MODEL_QUEUE_ID_INVALID;
  1363. }
  1364. if (output_queue_ids_.size() != new_output_data_info_.size()) {
  1365. GELOGE(GE_EXEC_MODEL_QUEUE_ID_INVALID, "Output queue ids not match model: output_queue=%zu output_data=%zu",
  1366. output_queue_ids_.size(), new_output_data_info_.size());
  1367. return GE_EXEC_MODEL_QUEUE_ID_INVALID;
  1368. }
  1369. GE_CHK_STATUS_RET(AddHeadStream(), "Add head stream failed.");
  1370. // Binding input_queue and Data Op.
  1371. GE_CHK_STATUS_RET(BindInputQueue(), "Launch bind input queue failed.");
  1372. GE_CHK_STATUS_RET(CpuTaskModelZeroCopy(input_mbuf_list_, new_input_outside_addrs_), "Launch zero copy failed.");
  1373. // Binding output_queue and NetOutput Op.
  1374. GE_CHK_STATUS_RET(BindOutputQueue(), "Launch bind output queue failed.");
  1375. GE_CHK_STATUS_RET(CpuTaskModelZeroCopy(output_mbuf_list_, new_output_outside_addrs_), "Launch zero copy failed.");
  1376. GE_CHK_STATUS_RET(CpuActiveStream(), "Launch active entry stream failed.");
  1377. GE_CHK_STATUS_RET(CpuWaitEndGraph(), "Launch wait end graph failed.");
  1378. GE_CHK_STATUS_RET(BindEnqueue(), "Launch enqueue failed.");
  1379. GE_CHK_STATUS_RET(CpuModelRepeat(), "Launch model repeat failed.");
  1380. return SUCCESS;
  1381. }
  1382. /// @ingroup ge
  1383. /// @brief queue schedule, Bind input queue to Data output address.
  1384. /// @return: 0 for success / others for failed
  1385. Status DavinciModel::BindInputQueue() {
  1386. // Caller checked: input_queue_ids_.size() == input_size_list_.size() != input_addr_list_.size()
  1387. for (size_t i = 0; i < input_queue_ids_.size(); ++i) {
  1388. auto it = new_input_data_info_.find(i);
  1389. if (it == new_input_data_info_.end()) {
  1390. GELOGE(FAILED, "Input not match: tensor num=%zu, Queue id index=%zu", new_input_data_info_.size(), i);
  1391. return FAILED;
  1392. }
  1393. uint32_t queue_id = input_queue_ids_[i];
  1394. if (it->second.GetDataInfo().empty()) {
  1395. GELOGE(INTERNAL_ERROR, "the %zu input_queue not set data_info.", i);
  1396. return INTERNAL_ERROR;
  1397. }
  1398. uint32_t data_size = static_cast<uint32_t>(it->second.GetDataInfo().at(0).first);
  1399. uintptr_t data_addr = reinterpret_cast<uintptr_t>(it->second.GetDataInfo().at(0).second);
  1400. GELOGI("BindInputToQueue: graph_%u index[%zu] queue id[%u] output addr[0x%lx] output size[%u]",
  1401. runtime_param_.graph_id, i, queue_id, data_addr, data_size);
  1402. rtError_t rt_ret = rtModelBindQueue(rt_model_handle_, queue_id, RT_MODEL_INPUT_QUEUE);
  1403. if (rt_ret != RT_ERROR_NONE) {
  1404. GELOGE(RT_FAILED, "Call rtModelBindQueue failed, ret: 0x%X", rt_ret);
  1405. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1406. }
  1407. if (CpuModelDequeue(queue_id) != SUCCESS) {
  1408. return INTERNAL_ERROR;
  1409. }
  1410. }
  1411. return SUCCESS;
  1412. }
  1413. /// @ingroup ge
  1414. /// @brief definiteness queue schedule, bind input queue to task.
  1415. /// @param [in] queue_id: input queue id from user.
  1416. /// @return: 0 for success / others for failed
  1417. Status DavinciModel::CpuModelDequeue(uint32_t queue_id) {
  1418. GELOGI("Set CpuKernel model dequeue task enter.");
  1419. std::shared_ptr<CpuTaskModelDequeue> dequeue_task = MakeShared<CpuTaskModelDequeue>(rt_entry_stream_);
  1420. if (dequeue_task == nullptr) {
  1421. GELOGE(MEMALLOC_FAILED, "Make CpuTaskModelDequeue task failed.");
  1422. return MEMALLOC_FAILED;
  1423. }
  1424. // Get DataOp Output address and bind to queue.
  1425. uintptr_t in_mbuf = 0;
  1426. Status status = dequeue_task->Init(queue_id, in_mbuf);
  1427. if (status != SUCCESS) {
  1428. return status;
  1429. }
  1430. cpu_task_list_.push_back(dequeue_task);
  1431. input_mbuf_list_.push_back(in_mbuf);
  1432. GELOGI("Set CpuKernel model dequeue task success.");
  1433. return SUCCESS;
  1434. }
  1435. Status DavinciModel::CpuTaskModelZeroCopy(std::vector<uintptr_t> &mbuf_list,
  1436. std::map<const void *, ZeroCopyOffset> &outside_addrs) {
  1437. GELOGI("Set CpuKernel model zero_copy task enter.");
  1438. std::shared_ptr<CpuTaskZeroCopy> zero_copy = MakeShared<CpuTaskZeroCopy>(rt_entry_stream_);
  1439. if (zero_copy == nullptr) {
  1440. GELOGE(MEMALLOC_FAILED, "Make CpuTaskZeroCopy task failed.");
  1441. return MEMALLOC_FAILED;
  1442. }
  1443. // mdc zero_copy not support l2 fusion
  1444. Status status = zero_copy->Init(mbuf_list, outside_addrs);
  1445. if (status != SUCCESS) {
  1446. return status;
  1447. }
  1448. cpu_task_list_.push_back(zero_copy);
  1449. GELOGI("Set CpuKernel model zero_copy task success.");
  1450. return SUCCESS;
  1451. }
  1452. /// @ingroup ge
  1453. /// @brief queue schedule, bind output queue to NetOutput input address.
  1454. /// @return: 0 for success / others for failed
  1455. Status DavinciModel::BindOutputQueue() {
  1456. // Caller checked: input_queue_ids_.size() == input_size_list_.size() != input_addr_list_.size()
  1457. for (size_t i = 0; i < output_queue_ids_.size(); ++i) {
  1458. auto it = new_output_data_info_.find(i);
  1459. if (it == new_output_data_info_.end()) {
  1460. GELOGE(FAILED, "Output not match: tensor num=%zu, Queue id index=%zu", new_output_data_info_.size(), i);
  1461. return FAILED;
  1462. }
  1463. uint32_t queue_id = output_queue_ids_[i];
  1464. if (it->second.GetDataInfo().empty()) {
  1465. GELOGE(INTERNAL_ERROR, "the %zu output_queue not set data_info.", i);
  1466. return INTERNAL_ERROR;
  1467. }
  1468. uint32_t data_size = static_cast<uint32_t>(it->second.GetDataInfo().at(0).first);
  1469. uintptr_t data_addr = reinterpret_cast<uintptr_t>(it->second.GetDataInfo().at(0).second);
  1470. GELOGI("BindOutputToQueue: graph_%u index[%zu] queue id[%u] input addr[0x%lx] input size[%u]",
  1471. runtime_param_.graph_id, i, queue_id, data_addr, data_size);
  1472. rtError_t rt_ret = rtModelBindQueue(rt_model_handle_, queue_id, RT_MODEL_OUTPUT_QUEUE);
  1473. if (rt_ret != RT_ERROR_NONE) {
  1474. GELOGE(RT_FAILED, "Call rtModelBindQueue failed, ret: 0x%X", rt_ret);
  1475. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1476. }
  1477. Status status = CpuModelPrepareOutput(data_addr, data_size);
  1478. if (status != SUCCESS) {
  1479. return status;
  1480. }
  1481. }
  1482. return SUCCESS;
  1483. }
  1484. /// @ingroup ge
  1485. /// @brief definiteness queue schedule, bind output queue to task.
  1486. /// @param [in] addr: NetOutput Op input tensor address.
  1487. /// @param [in] size: NetOutput Op input tensor size.
  1488. /// @return: 0 for success / others for failed
  1489. Status DavinciModel::CpuModelPrepareOutput(uintptr_t addr, uint32_t size) {
  1490. GELOGI("Set CpuKernel model enqueue task enter.");
  1491. if (input_mbuf_list_.empty()) {
  1492. GELOGE(FAILED, "Need input mbuf for fill output mbuf head info.");
  1493. return FAILED;
  1494. }
  1495. std::shared_ptr<CpuTaskPrepareOutput> prepare_output = MakeShared<CpuTaskPrepareOutput>(rt_entry_stream_);
  1496. if (prepare_output == nullptr) {
  1497. GELOGE(MEMALLOC_FAILED, "Make CpuTaskPrepareOutput task failed.");
  1498. return MEMALLOC_FAILED;
  1499. }
  1500. uintptr_t out_mbuf = 0;
  1501. if (prepare_output->Init(addr, size, input_mbuf_list_.back(), out_mbuf) != SUCCESS) {
  1502. return FAILED;
  1503. }
  1504. cpu_task_list_.push_back(prepare_output);
  1505. output_mbuf_list_.push_back(out_mbuf);
  1506. GELOGI("Set CpuKernel model enqueue task success.");
  1507. return SUCCESS;
  1508. }
  1509. ///
  1510. /// @ingroup ge
  1511. /// @brief definiteness queue schedule, active original model stream.
  1512. /// @return: 0 for success / others for failed
  1513. ///
  1514. Status DavinciModel::CpuActiveStream() {
  1515. GELOGI("Set CpuKernel active stream task enter.");
  1516. std::shared_ptr<CpuTaskActiveEntry> active_entry = MakeShared<CpuTaskActiveEntry>(rt_entry_stream_);
  1517. if (active_entry == nullptr) {
  1518. GELOGE(MEMALLOC_FAILED, "Make CpuTaskActiveEntry task failed.");
  1519. return MEMALLOC_FAILED;
  1520. }
  1521. Status status = active_entry->Init(rt_head_stream_);
  1522. if (status != SUCCESS) {
  1523. return status;
  1524. }
  1525. cpu_task_list_.push_back(active_entry);
  1526. GELOGI("Set CpuKernel active stream task success.");
  1527. return SUCCESS;
  1528. }
  1529. /// @ingroup ge
  1530. /// @brief definiteness queue schedule, wait for end graph.
  1531. /// @return: 0 for success / others for failed
  1532. Status DavinciModel::CpuWaitEndGraph() {
  1533. GELOGI("Set CpuKernel wait end graph task enter.");
  1534. std::shared_ptr<CpuTaskWaitEndGraph> wait_endgraph = MakeShared<CpuTaskWaitEndGraph>(rt_entry_stream_);
  1535. if (wait_endgraph == nullptr) {
  1536. GELOGE(MEMALLOC_FAILED, "Make CpuTaskWaitEndGraph task failed.");
  1537. return MEMALLOC_FAILED;
  1538. }
  1539. Status status = wait_endgraph->Init(runtime_model_id_);
  1540. if (status != SUCCESS) {
  1541. return status;
  1542. }
  1543. cpu_task_list_.push_back(wait_endgraph);
  1544. GELOGI("Set CpuKernel wait end graph task success.");
  1545. return SUCCESS;
  1546. }
  1547. Status DavinciModel::BindEnqueue() {
  1548. for (size_t i = 0; i < output_queue_ids_.size(); ++i) {
  1549. auto it = new_output_data_info_.find(i);
  1550. if (it == new_output_data_info_.end()) {
  1551. GELOGE(FAILED, "Output not match: tensor num=%zu, Queue id index=%zu", new_output_data_info_.size(), i);
  1552. return FAILED;
  1553. }
  1554. uint32_t queue_id = output_queue_ids_[i];
  1555. if (CpuModelEnqueue(queue_id, output_mbuf_list_[i]) != SUCCESS) {
  1556. return INTERNAL_ERROR;
  1557. }
  1558. }
  1559. return SUCCESS;
  1560. }
  1561. Status DavinciModel::CpuModelEnqueue(uint32_t queue_id, uintptr_t out_mbuf) {
  1562. GELOGI("Set CpuKernel model enqueue task enter.");
  1563. std::shared_ptr<CpuTaskModelEnqueue> model_enqueue = MakeShared<CpuTaskModelEnqueue>(rt_entry_stream_);
  1564. if (model_enqueue == nullptr) {
  1565. GELOGE(MEMALLOC_FAILED, "Make CpuTaskModelEnqueue task failed.");
  1566. return MEMALLOC_FAILED;
  1567. }
  1568. Status status = model_enqueue->Init(queue_id, out_mbuf);
  1569. if (status != SUCCESS) {
  1570. return status;
  1571. }
  1572. cpu_task_list_.push_back(model_enqueue);
  1573. GELOGI("Set CpuKernel model enqueue task enter.");
  1574. return SUCCESS;
  1575. }
  1576. /// @ingroup ge
  1577. /// @brief definiteness queue schedule, repeat run model.
  1578. /// @return: 0 for success / others for failed
  1579. Status DavinciModel::CpuModelRepeat() {
  1580. GELOGI("Set CpuKernel repeat task enter.");
  1581. std::shared_ptr<CpuTaskModelRepeat> model_repeat = MakeShared<CpuTaskModelRepeat>(rt_entry_stream_);
  1582. if (model_repeat == nullptr) {
  1583. GELOGE(MEMALLOC_FAILED, "Make CpuTaskModelRepeat task failed.");
  1584. return MEMALLOC_FAILED;
  1585. }
  1586. Status status = model_repeat->Init(runtime_model_id_);
  1587. if (status != SUCCESS) {
  1588. return status;
  1589. }
  1590. cpu_task_list_.push_back(model_repeat);
  1591. GELOGI("Set CpuKernel repeat task success.");
  1592. return SUCCESS;
  1593. }
  1594. Status DavinciModel::GetInputOutputDescInfo(vector<InputOutputDescInfo> &input_desc,
  1595. vector<InputOutputDescInfo> &output_desc) {
  1596. if ((data_op_list_.empty()) || (data_op_list_[0]->GetInputsSize()) != 1) {
  1597. GELOGI("data_op_list_ is empty or input_desc size is not 1.");
  1598. } else {
  1599. std::vector<uint32_t> input_formats;
  1600. GE_CHK_STATUS_RET(GetInputDescInfo(input_desc, input_formats), "get input desc info failed.");
  1601. }
  1602. std::vector<uint32_t> outputFormats;
  1603. GE_CHK_STATUS_RET(GetOutputDescInfo(output_desc, outputFormats), "get output desc info failed.");
  1604. return SUCCESS;
  1605. }
  1606. Status DavinciModel::GetInputOutputDescInfo(vector<InputOutputDescInfo> &input_desc,
  1607. vector<InputOutputDescInfo> &output_desc,
  1608. std::vector<uint32_t> &input_formats,
  1609. std::vector<uint32_t> &outputFormats) {
  1610. if ((data_op_list_.empty()) || (data_op_list_[0]->GetInputsSize()) != 1) {
  1611. GELOGE(FAILED, "OP List Pointer is null or input_desc size is not 1!");
  1612. return FAILED;
  1613. }
  1614. GE_CHK_STATUS_RET(GetInputDescInfo(input_desc, input_formats), "get input desc info failed");
  1615. GE_CHK_STATUS_RET(GetOutputDescInfo(output_desc, outputFormats), "get ouput desc info failed");
  1616. return SUCCESS;
  1617. }
  1618. ///
  1619. /// @ingroup ge
  1620. /// @brief Get dynamic batch_info
  1621. /// @param [out] batch_info
  1622. /// @param [out] dynamic_type
  1623. /// @return execute result
  1624. ///
  1625. Status DavinciModel::GetDynamicBatchInfo(std::vector<std::vector<int64_t>> &batch_info, int32_t &dynamic_type) const {
  1626. dynamic_type = dynamic_type_;
  1627. batch_info = batch_info_;
  1628. return SUCCESS;
  1629. }
  1630. ///
  1631. /// @ingroup ge
  1632. /// @brief Get combined dynamic dims info
  1633. /// @param [out] batch_info
  1634. /// @return None
  1635. ///
  1636. void DavinciModel::GetCombinedDynamicDims(std::vector<std::vector<int64_t>> &batch_info) const {
  1637. batch_info.clear();
  1638. batch_info = combined_batch_info_;
  1639. }
  1640. ///
  1641. /// @ingroup ge
  1642. /// @brief Get user designate shape order
  1643. /// @param [out] user_input_shape_order
  1644. /// @return None
  1645. ///
  1646. void DavinciModel::GetUserDesignateShapeOrder(std::vector<std::string> &user_input_shape_order) const {
  1647. user_input_shape_order.clear();
  1648. user_input_shape_order = user_designate_shape_order_;
  1649. }
  1650. ///
  1651. /// @ingroup ge
  1652. /// @brief Get AIPP input info
  1653. /// @param [in] index
  1654. /// @param [out] aipp_info
  1655. /// @return execute result
  1656. ///
  1657. Status DavinciModel::GetAIPPInfo(uint32_t index, AippConfigInfo &aipp_info) {
  1658. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  1659. OpDescPtr data_op = data_op_list_[index];
  1660. if (!data_op->HasAttr(ATTR_NAME_AIPP)) {
  1661. GELOGW("GetAIPPInfo: there is not AIPP related with index %u.", index);
  1662. return GE_AIPP_NOT_EXIST;
  1663. }
  1664. std::unique_ptr<domi::AippOpParams> aipp_params(new (std::nothrow) domi::AippOpParams());
  1665. GE_CHECK_NOTNULL(aipp_params);
  1666. ge::GeAttrValue::NAMED_ATTRS aipp_attr;
  1667. GE_CHK_BOOL_RET_STATUS(AttrUtils::GetNamedAttrs(data_op, ATTR_NAME_AIPP, aipp_attr), GE_AIPP_NOT_EXIST,
  1668. "Data node do not contain param aipp!");
  1669. GE_CHK_STATUS_RET(OpUtils::ConvertAippParams(aipp_attr, aipp_params.get()), "get aipp params failed");
  1670. GELOGI("GetAIPPInfo: node data: %s, type: %s, current index: %u, current node related input rank: %u",
  1671. data_op->GetName().c_str(), data_op->GetType().c_str(), index, aipp_params->related_input_rank());
  1672. GE_CHK_STATUS_RET(AippUtils::ConvertAippParams2AippInfo(aipp_params.get(), aipp_info),
  1673. "convert aipp params to aipp config info failed");
  1674. return SUCCESS;
  1675. }
  1676. Status DavinciModel::GetAippType(uint32_t index, InputAippType &type, size_t &aipp_index) {
  1677. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  1678. // Set default value
  1679. type = DATA_WITHOUT_AIPP;
  1680. aipp_index = 0xFFFFFFFF; // default invalid value
  1681. OpDescPtr data_op = data_op_list_[index];
  1682. GE_CHECK_NOTNULL(data_op);
  1683. if (!data_op->HasAttr(ATTR_DATA_RELATED_AIPP_MODE)) {
  1684. GELOGW("There is no aipp releated info with index %u.", index);
  1685. return SUCCESS;
  1686. }
  1687. std::string data_mode;
  1688. (void)AttrUtils::GetStr(data_op, ATTR_DATA_RELATED_AIPP_MODE, data_mode);
  1689. if (data_mode == "static_aipp") {
  1690. type = DATA_WITH_STATIC_AIPP;
  1691. } else if (data_mode == "dynamic_aipp") {
  1692. type = DATA_WITH_DYNAMIC_AIPP;
  1693. } else if (data_mode == "dynamic_aipp_conf") {
  1694. type = DYNAMIC_AIPP_NODE;
  1695. } else {
  1696. GELOGE(INTERNAL_ERROR, "The info of aipp releated info %s is invalid with index %u.", data_mode.c_str(), index);
  1697. return INTERNAL_ERROR;
  1698. }
  1699. if (type == DATA_WITH_DYNAMIC_AIPP) {
  1700. string releated_name;
  1701. (void)AttrUtils::GetStr(data_op, ATTR_DATA_AIPP_DATA_NAME_MAP, releated_name);
  1702. for (size_t i = 0; i < data_op_list_.size(); ++i) {
  1703. GE_CHECK_NOTNULL(data_op_list_[i]);
  1704. if (data_op_list_[i]->GetName() == releated_name) {
  1705. GELOGI("Find aipp_data [%s] index %zu from index %u", releated_name.c_str(), i, index);
  1706. aipp_index = i;
  1707. }
  1708. }
  1709. if (aipp_index == 0xFFFFFFFF) {
  1710. GELOGE(INTERNAL_ERROR, "Can not find aipp data node from index %u", index);
  1711. return INTERNAL_ERROR;
  1712. }
  1713. }
  1714. return SUCCESS;
  1715. }
  1716. void DavinciModel::SetDynamicSize(const std::vector<uint64_t> &batch_num, int32_t dynamic_type) {
  1717. batch_size_.clear();
  1718. if (batch_num.empty()) {
  1719. GELOGD("User has not set dynammic data");
  1720. }
  1721. for (size_t i = 0; i < batch_num.size(); i++) {
  1722. batch_size_.emplace_back(batch_num[i]);
  1723. }
  1724. dynamic_type_ = dynamic_type;
  1725. }
  1726. void DavinciModel::GetCurShape(std::vector<int64_t> &batch_info, int32_t &dynamic_type) {
  1727. if (batch_size_.empty()) {
  1728. GELOGD("User does not set dynamic size");
  1729. }
  1730. for (size_t i = 0; i < batch_size_.size(); i++) {
  1731. GELOGI("Start to get current shape");
  1732. batch_info.emplace_back(batch_size_[i]);
  1733. }
  1734. dynamic_type = dynamic_type_;
  1735. }
  1736. void DavinciModel::GetModelAttr(std::vector<std::string> &dynamic_output_shape_info) {
  1737. for (auto &op : output_op_list_) {
  1738. if (op->GetType() != NETOUTPUT) {
  1739. continue;
  1740. }
  1741. GELOGI("Start to get dynamic output dims attr");
  1742. if (!AttrUtils::GetListStr(op, ATTR_NAME_DYNAMIC_OUTPUT_DIMS, dynamic_output_shape_info)) {
  1743. GELOGD("Can not get dynamic output dims attr");
  1744. }
  1745. }
  1746. }
  1747. Status DavinciModel::GetInputOutputDescInfoForZeroCopy(vector<InputOutputDescInfo> &input_desc,
  1748. vector<InputOutputDescInfo> &output_desc,
  1749. std::vector<uint32_t> &input_formats,
  1750. std::vector<uint32_t> &outputFormats) {
  1751. if ((data_op_list_.empty()) || (1 != data_op_list_[0]->GetInputsSize())) {
  1752. GELOGE(FAILED, "OP List Pointer is null or input_desc size is not 1!");
  1753. return FAILED;
  1754. }
  1755. GE_CHK_STATUS_RET(GetInputDescInfo(input_desc, input_formats), "get input desc info failed");
  1756. GE_CHK_STATUS_RET(GetOutputDescInfo(output_desc, outputFormats), "get ouput desc info failed");
  1757. GE_CHK_BOOL_RET_STATUS(output_desc.size() == output_memory_size_list_.size(), INTERNAL_ERROR,
  1758. "output_desc size[%zu] not equal output_size_list_[%zu] size!", output_desc.size(),
  1759. output_memory_size_list_.size());
  1760. /// For function zero copy,the momery should be aligned by 512 bytes.
  1761. /// And, because of the cce op limit, size should be lager than the real shape size. The memory should be padded by 32
  1762. /// bytes.
  1763. /// *size equals to ((tensorDesc->dataSize + 2 * 32 - 1) / 32) * 32;
  1764. for (size_t i = 0; i < output_memory_size_list_.size(); i++) {
  1765. output_desc[i].size = output_memory_size_list_[i];
  1766. }
  1767. return SUCCESS;
  1768. }
  1769. void DavinciModel::SetInputDimsInfo(const vector<int64_t> &model_input_dims, Format &format,
  1770. InputOutputDescInfo &input) {
  1771. uint32_t n, c, h, w;
  1772. n = format == FORMAT_NHWC ? NHWC_DIM_N : NCHW_DIM_N;
  1773. c = format == FORMAT_NHWC ? NHWC_DIM_C : NCHW_DIM_C;
  1774. h = format == FORMAT_NHWC ? NHWC_DIM_H : NCHW_DIM_H;
  1775. w = format == FORMAT_NHWC ? NHWC_DIM_W : NCHW_DIM_W;
  1776. if (model_input_dims.size() == static_cast<size_t>(NORMAL_TENSOR_SIZE)) {
  1777. input.shape_info.num = model_input_dims[n];
  1778. input.shape_info.height = model_input_dims[h];
  1779. input.shape_info.width = model_input_dims[w];
  1780. input.shape_info.channel = model_input_dims[c];
  1781. }
  1782. for (size_t k = 0; k < model_input_dims.size(); ++k) {
  1783. input.shape_info.dims.push_back(model_input_dims[k]);
  1784. }
  1785. return;
  1786. }
  1787. void DavinciModel::CreateInputDimsInfo(const OpDescPtr &op_desc, Format format, InputOutputDescInfo &input) {
  1788. if (is_new_model_desc_ && op_desc->HasAttr(ATTR_NAME_INPUT_DIMS)) {
  1789. // When static aipp is set, need to get the model input dims which processed by aipp
  1790. vector<int64_t> model_input_dims;
  1791. (void)AttrUtils::GetListInt(op_desc, ATTR_NAME_INPUT_DIMS, model_input_dims);
  1792. SetInputDimsInfo(model_input_dims, format, input);
  1793. return;
  1794. }
  1795. // judge if this data is linked dynamic aipp first, multiply batch has been considered
  1796. if (op_desc->HasAttr(ATTR_DYNAMIC_AIPP_INPUT_DIMS)) {
  1797. vector<int64_t> dynamic_aipp_input_dims;
  1798. (void)AttrUtils::GetListInt(op_desc, ATTR_DYNAMIC_AIPP_INPUT_DIMS, dynamic_aipp_input_dims);
  1799. SetInputDimsInfo(dynamic_aipp_input_dims, format, input);
  1800. return;
  1801. } else {
  1802. // judge if this data is multiply batch
  1803. if (!op_desc->HasAttr(ATTR_MBATCH_ORIGIN_INPUT_DIMS)) {
  1804. vector<int64_t> input_dims = op_desc->GetInputDescPtr(0)->GetShape().GetDims();
  1805. SetInputDimsInfo(input_dims, format, input);
  1806. return;
  1807. } else {
  1808. vector<int64_t> origin_input_dims;
  1809. (void)AttrUtils::GetListInt(op_desc, ATTR_MBATCH_ORIGIN_INPUT_DIMS, origin_input_dims);
  1810. SetInputDimsInfo(origin_input_dims, format, input);
  1811. return;
  1812. }
  1813. }
  1814. }
  1815. Status DavinciModel::GetInputDescInfo(vector<InputOutputDescInfo> &input_desc, std::vector<uint32_t> &formats) {
  1816. for (size_t index = 0; index < data_op_list_.size(); ++index) {
  1817. InputOutputDescInfo input;
  1818. GE_CHECK_NOTNULL(data_op_list_[index]);
  1819. GE_CHECK_NOTNULL(data_op_list_[index]->GetInputDescPtr(0));
  1820. Format format = data_op_list_[index]->GetInputDescPtr(0)->GetFormat();
  1821. CreateInputDimsInfo(data_op_list_[index], format, input);
  1822. input.data_type = data_op_list_[index]->GetInputDescPtr(0)->GetDataType();
  1823. input.name = data_op_list_[index]->GetName();
  1824. int64_t input_size = 0;
  1825. GE_CHK_STATUS_RET(TensorUtils::GetSize(*data_op_list_[index]->GetInputDescPtr(0), input_size),
  1826. "get input size failed.");
  1827. input.size = input_size;
  1828. formats.push_back(format);
  1829. input_desc.push_back(input);
  1830. }
  1831. // cause GetInputDescInfo called not only once, set is_new_model_desc_ to false after calc the model input dims
  1832. is_new_model_desc_ = false;
  1833. return SUCCESS;
  1834. }
  1835. void DavinciModel::CreateOutput(uint32_t index, OpDescPtr &op_desc, InputOutputDescInfo &output,
  1836. uint32_t &format_result) {
  1837. /// netoutput input tensor desc
  1838. GE_IF_BOOL_EXEC(op_desc->GetInputDescPtr(index) == nullptr, GELOGE(FAILED, "OpDesc GetInputDescPtr is nullptr");
  1839. return );
  1840. Format format = op_desc->GetInputDescPtr(index)->GetFormat();
  1841. GeShape shape = op_desc->GetInputDescPtr(index)->GetShape();
  1842. DataType data_type = op_desc->GetInputDescPtr(index)->GetDataType();
  1843. int64_t dims[] = {1, 1, 1, 1};
  1844. format_result = format;
  1845. if (format == FORMAT_ND) { // for ND tensor
  1846. for (size_t i = 0; i < shape.GetDimNum() && i < (sizeof(dims) / sizeof(dims[0])); i++) {
  1847. dims[i] = shape.GetDim(i);
  1848. }
  1849. } else { // FOR FORMAT_NHWC or FORMAT_NCHW
  1850. dims[0] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_N : NCHW_DIM_N); // 0: first dim
  1851. dims[1] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_C : NCHW_DIM_C); // 1: second dim
  1852. dims[2] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_H : NCHW_DIM_H); // 2: third dim
  1853. dims[3] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_W : NCHW_DIM_W); // 3: forth dim
  1854. }
  1855. output.shape_info.num = dims[0]; // 0: first dim
  1856. output.shape_info.channel = dims[1]; // 1: second dim
  1857. output.shape_info.height = dims[2]; // 2: third dim
  1858. output.shape_info.width = dims[3]; // 3: forth dim
  1859. if (op_desc->GetInputDescPtr(index)->GetFormat() == FORMAT_FRACTAL_Z) { // FraczToHWCK
  1860. int64_t k = shape.GetDim(0); // 0: first dim
  1861. int64_t c = shape.GetDim(1); // 1: second dim
  1862. int64_t h = shape.GetDim(2); // 2: third dim
  1863. int64_t w = shape.GetDim(3); // 3: forth dim
  1864. output.shape_info.dims.push_back(h);
  1865. output.shape_info.dims.push_back(w);
  1866. output.shape_info.dims.push_back(c);
  1867. output.shape_info.dims.push_back(k);
  1868. format_result = FORMAT_HWCN;
  1869. } else {
  1870. for (size_t j = 0; j < shape.GetDimNum(); j++) {
  1871. output.shape_info.dims.push_back(shape.GetDim(j));
  1872. }
  1873. }
  1874. int64_t tensor_size = 0;
  1875. (void)TensorUtils::CalcTensorMemSize(shape, format, data_type, tensor_size); // no need to check value
  1876. output.size = static_cast<uint64_t>(tensor_size);
  1877. output.data_type = op_desc->GetInputDescPtr(index)->GetDataType();
  1878. }
  1879. Status DavinciModel::GetOutputDescInfo(vector<InputOutputDescInfo> &output_desc, std::vector<uint32_t> &formats) {
  1880. GELOGI("Output node size: %zu", output_op_list_.size());
  1881. for (size_t i = 0; i < output_op_list_.size(); i++) {
  1882. auto &op_desc = output_op_list_[i];
  1883. uint32_t out_size = static_cast<uint32_t>(op_desc->GetInputsSize());
  1884. for (uint32_t index = 0; index < out_size; index++) {
  1885. string output_name;
  1886. InputOutputDescInfo output;
  1887. uint32_t format_result;
  1888. CreateOutput(index, op_desc, output, format_result);
  1889. std::vector<std::string> src_name = op_desc->GetSrcName();
  1890. std::vector<int64_t> src_index = op_desc->GetSrcIndex();
  1891. GE_CHK_BOOL_RET_STATUS(src_name.size() > index && src_index.size() > index, INTERNAL_ERROR,
  1892. "construct output_name failed.");
  1893. // forward compatbility, if old om has no out_node_name, need to return output follow origin way
  1894. if (out_size == out_node_name_.size()) {
  1895. // neweast plan, the index will add to name during generate model.
  1896. bool contains_colon = out_node_name_[index].find(":") != std::string::npos;
  1897. output_name =
  1898. contains_colon ? out_node_name_[index] : out_node_name_[index] + ":" + std::to_string(src_index[index]);
  1899. } else {
  1900. output_name = std::string("output_") + std::to_string(index) + "_" + src_name[index] + "_" +
  1901. std::to_string(src_index[index]);
  1902. }
  1903. output.name = output_name;
  1904. output_desc.push_back(output);
  1905. formats.push_back(format_result);
  1906. }
  1907. }
  1908. return SUCCESS;
  1909. }
  1910. ge::Format DavinciModel::GetFormat() {
  1911. if ((data_op_list_.empty()) || data_op_list_[0] == nullptr || data_op_list_[0]->GetInputDescPtr(0) == nullptr) {
  1912. GELOGW("OP List Pointer is null or input_desc size is not 1!");
  1913. return FORMAT_NCHW;
  1914. }
  1915. return data_op_list_[0]->GetInputDescPtr(0)->GetFormat();
  1916. }
  1917. Status DavinciModel::CopyInputData(const InputData &input_data, bool device_data) {
  1918. rtMemcpyKind_t kind = device_data ? RT_MEMCPY_DEVICE_TO_DEVICE : RT_MEMCPY_HOST_TO_DEVICE;
  1919. const std::vector<DataBuffer> &blobs = input_data.blobs;
  1920. for (const auto &data : new_input_data_info_) {
  1921. if (data.first >= blobs.size()) {
  1922. GELOGE(FAILED, "Blobs not match: blobs=%zu, tensor=%zu, index=%u, size=%ld", blobs.size(),
  1923. new_input_data_info_.size(), data.first, data.second.GetDataInfo().at(0).first);
  1924. return FAILED;
  1925. }
  1926. const DataBuffer &data_buf = blobs[data.first];
  1927. if (data_buf.length == 0) {
  1928. GELOGW("No data need to memcpy!");
  1929. return SUCCESS;
  1930. }
  1931. uint64_t data_size = data.second.GetDataSize();
  1932. GE_CHK_BOOL_RET_STATUS(data_size >= data_buf.length, PARAM_INVALID,
  1933. "input data size(%lu) does not match model required size(%lu), ret failed.", data_buf.length,
  1934. data_size);
  1935. void *mem_addr = data.second.GetBasicAddr();
  1936. void *data_buf_addr = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(data_buf.data));
  1937. uint64_t data_buf_length = data_buf.length;
  1938. GELOGI("[IMAS]CopyPlainData memcpy graph_%lu type[F] input[%lu] dst[%p] src[%p] mem_size[%lu] datasize[%lu]",
  1939. runtime_param_.graph_id, data.first, mem_addr, data_buf_addr, data_size, data_buf_length);
  1940. GE_CHK_RT_RET(rtMemcpy(mem_addr, data_size, data_buf_addr, data_buf_length, kind));
  1941. }
  1942. return SUCCESS;
  1943. }
  1944. Status DavinciModel::SyncVarData() {
  1945. GELOGI("Sync var data, model id:%u", model_id_);
  1946. Status ret = SUCCESS;
  1947. OpDescPtr global_step = GetVariableOp(NODE_NAME_GLOBAL_STEP);
  1948. if (global_step != nullptr) {
  1949. auto v_output_size = ModelUtils::GetOutputSize(global_step);
  1950. auto v_output_addr = ModelUtils::GetOutputDataAddrs(runtime_param_, global_step);
  1951. if (v_output_size.empty() || v_output_addr.empty()) {
  1952. GELOGE(PARAM_INVALID, "global step op:%s not set output", global_step->GetName().c_str());
  1953. return PARAM_INVALID;
  1954. }
  1955. std::vector<uint64_t> v_step;
  1956. v_step.push_back(iterator_count_);
  1957. GE_CHK_RT_RET(rtMemcpy(v_output_addr[0], v_output_size[0], v_step.data(), v_step.size() * sizeof(uint64_t),
  1958. RT_MEMCPY_HOST_TO_DEVICE));
  1959. }
  1960. for (auto op_desc : variable_op_list_) {
  1961. ret =
  1962. VarManager::Instance(session_id_)->SyncVarData(runtime_param_.graph_id, op_desc->GetName(), op_desc, mem_base_);
  1963. GE_CHK_BOOL_EXEC(ret == SUCCESS, break, "sync var data ret failed, model id:%u, op name:%s.", model_id_,
  1964. op_desc->GetName().c_str());
  1965. }
  1966. return ret;
  1967. }
  1968. inline int64_t SumSize(const vector<int64_t> &size_list) {
  1969. int64_t sum_size = 0;
  1970. for (const int64_t &size : size_list) {
  1971. sum_size += size;
  1972. }
  1973. return sum_size;
  1974. }
  1975. Status DavinciModel::SinkModelProfile() {
  1976. // profiling plugin must be registered
  1977. Msprof::Engine::Reporter *reporter = PluginImpl::GetPluginReporter();
  1978. GE_IF_BOOL_EXEC(reporter == nullptr, GELOGI("Profiling report is nullptr!"); return SUCCESS);
  1979. GELOGI("Start collect model load profiling data.");
  1980. Msprof::Engine::ReporterData reporter_data{};
  1981. // report model data tag name
  1982. std::string tag_name;
  1983. tag_name.append("model_load_info_").append(std::to_string(this->Id()));
  1984. GE_CHK_BOOL_EXEC(memcpy_s(reporter_data.tag, MSPROF_ENGINE_MAX_TAG_LEN, tag_name.c_str(), tag_name.size()) == EOK,
  1985. return FAILED, "Sink model tag memcpy error.");
  1986. // Model Header
  1987. string name;
  1988. if (!om_name_.empty()) {
  1989. name = om_name_;
  1990. } else {
  1991. name = name_;
  1992. }
  1993. size_t name_len = name.size();
  1994. reporter_data.deviceId = device_id_;
  1995. reporter_data.data = (unsigned char *)&name_len;
  1996. reporter_data.dataLen = sizeof(int32_t);
  1997. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  1998. this->Id());
  1999. reporter_data.data = (unsigned char *)name.c_str();
  2000. reporter_data.dataLen = name.size();
  2001. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2002. this->Id());
  2003. uint32_t model_id = this->Id();
  2004. reporter_data.data = (unsigned char *)&model_id;
  2005. reporter_data.dataLen = sizeof(uint32_t);
  2006. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2007. this->Id());
  2008. // Load Start/End Time
  2009. int64_t start_time = this->GetLoadBeginTime();
  2010. reporter_data.data = (unsigned char *)&start_time;
  2011. reporter_data.dataLen = sizeof(int64_t);
  2012. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2013. this->Id());
  2014. int64_t end_time = this->GetLoadEndTime();
  2015. reporter_data.data = (unsigned char *)&end_time;
  2016. reporter_data.dataLen = sizeof(int64_t);
  2017. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2018. this->Id());
  2019. int32_t task_num = task_list_.size();
  2020. std::multimap<uint32_t, uint32_t> op_id_map;
  2021. std::set<uint32_t> task_id_set;
  2022. for (int32_t i = 0; i < task_num; i++) {
  2023. auto task = task_list_[i];
  2024. GE_CHECK_NOTNULL(task);
  2025. auto fusion_op_info = task->GetFusionOpInfo();
  2026. // when type is RT_MODEL_TASK_KERNEL, ctx is not null
  2027. if (fusion_op_info != nullptr) {
  2028. uint32_t op_num = fusion_op_info->original_op_names.size();
  2029. uint32_t task_id = task->GetTaskID();
  2030. if (op_num > 0) {
  2031. GELOGI("task.id = %u, opNum = %u", task_id, op_num);
  2032. op_id_map.insert(std::make_pair(fusion_op_info->op_index, task_id));
  2033. }
  2034. }
  2035. }
  2036. struct memoryInfo {
  2037. int64_t input_size;
  2038. int64_t output_size;
  2039. int64_t weight_size;
  2040. int64_t workspace_size;
  2041. int64_t total_size;
  2042. memoryInfo() : input_size(0), output_size(0), weight_size(0), workspace_size(0), total_size(0) {}
  2043. };
  2044. using CIT = std::multimap<uint32_t, uint32_t>::const_iterator;
  2045. using Range = std::pair<CIT, CIT>;
  2046. for (int32_t i = 0; i < task_num; i++) {
  2047. auto task = task_list_[i];
  2048. GE_CHECK_NOTNULL(task);
  2049. auto fusion_op_info = task->GetFusionOpInfo();
  2050. if (fusion_op_info != nullptr && fusion_op_info->original_op_names.size() > 0) {
  2051. uint32_t task_id = task->GetTaskID();
  2052. uint32_t op_num = fusion_op_info->original_op_names.size();
  2053. uint32_t task_count = 0;
  2054. if (task_id_set.count(task_id) != 0) {
  2055. continue;
  2056. }
  2057. uint32_t op_id = fusion_op_info->op_index;
  2058. Range range = op_id_map.equal_range(op_id);
  2059. for (CIT range_idx = range.first; range_idx != range.second; ++range_idx) {
  2060. task_count++;
  2061. uint32_t task_id = range_idx->second;
  2062. task_id_set.insert(task_id);
  2063. }
  2064. // op name after fusion
  2065. string fusion_op_name = fusion_op_info->op_name;
  2066. int32_t fusion_op_name_len = fusion_op_name.size() == 0 ? 1 : fusion_op_name.size();
  2067. reporter_data.data = (unsigned char *)&fusion_op_name_len;
  2068. reporter_data.dataLen = sizeof(int32_t);
  2069. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2070. this->Id());
  2071. reporter_data.data = (unsigned char *)fusion_op_name.c_str();
  2072. reporter_data.dataLen = fusion_op_name_len;
  2073. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2074. this->Id());
  2075. // original op name before fusion
  2076. reporter_data.data = (unsigned char *)&op_num;
  2077. reporter_data.dataLen = sizeof(int32_t);
  2078. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2079. this->Id());
  2080. for (uint32_t k = 0; k < op_num; k++) {
  2081. std::string op_name = fusion_op_info->original_op_names[k];
  2082. int32_t op_name_len = op_name.size() == 0 ? 1 : op_name.size();
  2083. reporter_data.data = (unsigned char *)&op_name_len;
  2084. reporter_data.dataLen = sizeof(int32_t);
  2085. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2086. this->Id());
  2087. reporter_data.data = (unsigned char *)op_name.c_str();
  2088. reporter_data.dataLen = op_name_len;
  2089. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2090. this->Id());
  2091. }
  2092. // stream id info
  2093. uint32_t streamId = task->GetStreamId();
  2094. reporter_data.data = (unsigned char *)&streamId;
  2095. reporter_data.dataLen = sizeof(int32_t);
  2096. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2097. this->Id());
  2098. // memory info
  2099. struct memoryInfo memory_info;
  2100. uint32_t op_index = fusion_op_info->op_index;
  2101. auto iter = op_list_.find(op_index);
  2102. GE_CHK_BOOL_EXEC(iter != op_list_.end(), return FAILED, "index is out of range, index: %u", op_index);
  2103. auto op_desc = iter->second;
  2104. memory_info.input_size = SumSize(ModelUtils::GetInputSize(op_desc));
  2105. memory_info.output_size = SumSize(ModelUtils::GetOutputSize(op_desc));
  2106. memory_info.workspace_size = SumSize(ModelUtils::GetWorkspaceSize(op_desc));
  2107. memory_info.weight_size = SumSize(ModelUtils::GetWeightSize(op_desc));
  2108. memory_info.total_size =
  2109. memory_info.weight_size + memory_info.input_size + memory_info.output_size + memory_info.workspace_size;
  2110. reporter_data.data = (unsigned char *)&memory_info;
  2111. reporter_data.dataLen = sizeof(struct memoryInfo);
  2112. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2113. this->Id());
  2114. // task info
  2115. reporter_data.data = (unsigned char *)&task_count;
  2116. reporter_data.dataLen = sizeof(uint32_t);
  2117. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2118. this->Id());
  2119. Range task_range = op_id_map.equal_range(op_id);
  2120. for (CIT idx = task_range.first; idx != task_range.second; ++idx) {
  2121. uint32_t task_id = idx->second;
  2122. reporter_data.data = (unsigned char *)&task_id;
  2123. reporter_data.dataLen = sizeof(uint32_t);
  2124. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2125. this->Id());
  2126. }
  2127. }
  2128. }
  2129. return SUCCESS;
  2130. }
  2131. Status DavinciModel::SinkTimeProfile(const InputData &current_data) {
  2132. // profiling plugin must be registered
  2133. Msprof::Engine::Reporter *reporter = PluginImpl::GetPluginReporter();
  2134. GE_IF_BOOL_EXEC(reporter == nullptr, GELOGI("Profiling report is nullptr!"); return SUCCESS);
  2135. Msprof::Engine::ReporterData reporter_data{};
  2136. // report model data tag name
  2137. std::string tag_name;
  2138. tag_name.append("model_time_info_")
  2139. .append(std::to_string(this->Id()))
  2140. .append("_")
  2141. .append(std::to_string(current_data.index));
  2142. GE_CHK_BOOL_EXEC(memcpy_s(reporter_data.tag, MSPROF_ENGINE_MAX_TAG_LEN, tag_name.c_str(), tag_name.size()) == EOK,
  2143. return FAILED, "Sink model tag memcpy error.");
  2144. // device id
  2145. reporter_data.deviceId = device_id_;
  2146. // Model Header
  2147. string name;
  2148. if (!om_name_.empty()) {
  2149. name = om_name_;
  2150. } else {
  2151. name = name_;
  2152. }
  2153. size_t name_len = name.size();
  2154. reporter_data.data = (unsigned char *)&name_len;
  2155. reporter_data.dataLen = sizeof(int32_t);
  2156. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2157. this->Id());
  2158. reporter_data.data = (unsigned char *)name.c_str();
  2159. reporter_data.dataLen = name.size();
  2160. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2161. this->Id());
  2162. // request id
  2163. uint64_t request_id = current_data.request_id;
  2164. reporter_data.data = (unsigned char *)&request_id;
  2165. reporter_data.dataLen = sizeof(uint32_t);
  2166. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED,
  2167. "Reporter data fail, model id:%u, data index:%u.", this->Id(), current_data.index);
  2168. // thread id
  2169. int32_t thread_id = GetDataInputTid();
  2170. reporter_data.data = (unsigned char *)&thread_id;
  2171. reporter_data.dataLen = sizeof(int32_t);
  2172. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED,
  2173. "Reporter data fail, model id:%u, data index:%u.", this->Id(), current_data.index);
  2174. // time info
  2175. time_info_.modelId = this->Id();
  2176. reporter_data.data = (unsigned char *)&time_info_;
  2177. reporter_data.dataLen = sizeof(struct timeInfo);
  2178. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED,
  2179. "Reporter data fail, model id:%u, data index:%u.", this->Id(), current_data.index);
  2180. return SUCCESS;
  2181. }
  2182. void DavinciModel::SetProfileTime(ModelProcStage stage, int64_t endTime) {
  2183. int64_t time = endTime;
  2184. if (time == 0) {
  2185. mmTimespec timespec = mmGetTickCount();
  2186. time = timespec.tv_sec * 1000 * 1000 * 1000 + timespec.tv_nsec; // 1000 ^ 3 converts second to nanosecond
  2187. }
  2188. switch (stage) {
  2189. case MODEL_LOAD_START:
  2190. load_begin_time_ = time;
  2191. break;
  2192. case MODEL_LOAD_END:
  2193. load_end_time_ = time;
  2194. break;
  2195. case MODEL_PRE_PROC_START:
  2196. time_info_.processBeginTime = time;
  2197. break;
  2198. case MODEL_PRE_PROC_END:
  2199. time_info_.processEndTime = time;
  2200. break;
  2201. case MODEL_INFER_START:
  2202. time_info_.inferenceBeginTime = time;
  2203. break;
  2204. case MODEL_INFER_END:
  2205. time_info_.inferenceEndTime = time;
  2206. break;
  2207. case MODEL_AFTER_PROC_START:
  2208. time_info_.dumpBeginTime = time;
  2209. break;
  2210. case MODEL_AFTER_PROC_END:
  2211. time_info_.dumpEndTime = time;
  2212. break;
  2213. default:
  2214. break;
  2215. }
  2216. return;
  2217. }
  2218. ///
  2219. /// @ingroup ge
  2220. /// @brief send Output Op result to upper layer
  2221. /// @already malloced in ModelLoad, no need to malloc again
  2222. /// @param [in] data_id: the index of output_data
  2223. /// @param [in/out] output_data: real user output_data
  2224. /// @param [in] kind: the kind of rtMemcpy
  2225. /// @return Status result
  2226. /// @author
  2227. ///
  2228. Status DavinciModel::CopyOutputData(uint32_t data_id, OutputData &output_data, rtMemcpyKind_t kind) {
  2229. if (output_op_list_.empty()) {
  2230. Status ret = SyncVarData();
  2231. return ret;
  2232. }
  2233. output_data.index = data_id;
  2234. output_data.model_id = model_id_;
  2235. if (output_data.blobs.size() != new_output_data_info_.size()) {
  2236. GELOGE(FAILED, "Output data buffer num=%zu not equal model data num=%zu", output_data.blobs.size(),
  2237. new_output_data_info_.size());
  2238. return FAILED;
  2239. }
  2240. std::vector<DataBuffer> &blobs = output_data.blobs;
  2241. size_t idx = 0;
  2242. for (const auto &output : new_output_data_info_) {
  2243. if (output.first >= blobs.size()) {
  2244. GELOGE(FAILED, "Blobs not match: blobs=%zu, tensor=%zu, index=%u, size=%ld", blobs.size(),
  2245. new_input_data_info_.size(), output.first, output.second.GetDataInfo().at(0).first);
  2246. return FAILED;
  2247. }
  2248. if ((kind == RT_MEMCPY_DEVICE_TO_DEVICE) && (copy_only_addrs_.count(output.second.GetBasicAddr()) == 0)) {
  2249. continue; // Skip: Feed by zero copy.
  2250. }
  2251. DataBuffer &buffer = blobs[output.first];
  2252. uint64_t mem_size = static_cast<uint64_t>(output.second.GetDataSize());
  2253. if ((buffer.length == 0) || (mem_size == 0)) {
  2254. GELOGI("Length of data is zero, No need copy. output tensor index=%u", output.first);
  2255. continue;
  2256. }
  2257. if (is_dynamic_) {
  2258. GELOGI("No need to check output data size.");
  2259. } else if (buffer.length < mem_size) {
  2260. GELOGE(FAILED, "Tensor data size=%lu, buffer size=%u", mem_size, buffer.length);
  2261. return FAILED;
  2262. } else if (buffer.length > mem_size) {
  2263. GELOGW("Tensor data size=%lu, buffer size=%u", mem_size, buffer.length);
  2264. }
  2265. int64_t data_size = output.second.GetDataSize();
  2266. if (is_online_infer_dynamic_) {
  2267. auto gear_and_real_out_size_info = merge_nodes_gear_and_real_out_size_info_[idx];
  2268. data_size = gear_and_real_out_size_info[cur_dynamic_dims_];
  2269. }
  2270. uint64_t buffer_length = buffer.length;
  2271. void *buffer_addr = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(buffer.data));
  2272. GELOGI("[IMAS]CopyPlainData memcpy graph_%u type[F] output[%u] memaddr[%p] mem_size[%ld] datasize[%u]",
  2273. runtime_param_.graph_id, output.first, output.second.GetBasicAddr(), data_size, buffer_length);
  2274. GE_CHK_RT_RET(rtMemcpy(buffer_addr, buffer_length, output.second.GetBasicAddr(), data_size, kind));
  2275. idx++;
  2276. }
  2277. return SUCCESS;
  2278. }
  2279. Status DavinciModel::GenOutputTensorInfo(const OpDescPtr &op_desc, uint32_t data_index, OutputData *output_data,
  2280. std::vector<ge::OutputTensorInfo> &outputs) {
  2281. GE_CHECK_NOTNULL(op_desc);
  2282. GE_CHECK_NOTNULL(output_data);
  2283. if (output_data->blobs.size() > data_index) {
  2284. GELOGI("No need to generate output tensor info, model id:%u", model_id_);
  2285. return SUCCESS;
  2286. }
  2287. std::vector<int64_t> out_buffer_size_vec;
  2288. std::vector<std::vector<int64_t>> shape_info_vec;
  2289. size_t input_num = op_desc->GetInputsSize();
  2290. if (is_getnext_sink_dynamic_) {
  2291. input_num = input_num - kGetDynamicDimsCount;
  2292. }
  2293. for (size_t i = 0; i < input_num; ++i) {
  2294. int64_t size = 0;
  2295. auto input_desc = op_desc->GetInputDescPtr(i);
  2296. GE_CHECK_NOTNULL(input_desc);
  2297. auto ret = TensorUtils::GetTensorSizeInBytes(*input_desc, size);
  2298. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS,
  2299. GELOGE(ret, "Get size from TensorDesc failed, op:%s, input id:%zu", op_desc->GetName().c_str(), i);
  2300. return ret);
  2301. std::vector<int64_t> output_shape = input_desc->GetShape().GetDims();
  2302. if (is_online_infer_dynamic_) {
  2303. auto gear_and_real_out_size_info = merge_nodes_gear_and_real_out_size_info_[i];
  2304. size = gear_and_real_out_size_info[cur_dynamic_dims_];
  2305. auto gear_and_real_out_shape_info = merge_nodes_gear_and_real_out_shape_info_[i];
  2306. output_shape = gear_and_real_out_shape_info[cur_dynamic_dims_];
  2307. is_dynamic_ = true;
  2308. }
  2309. GELOGI("Output size is %ld, output shape is %s.", size, formats::JoinToString(output_shape).c_str());
  2310. out_buffer_size_vec.push_back(size);
  2311. shape_info_vec.push_back(output_shape);
  2312. }
  2313. GELOGI("Output blobs size:%zu, data index:%u, model id:%u", out_buffer_size_vec.size(), data_index, model_id_);
  2314. for (size_t i = 0; i < out_buffer_size_vec.size(); ++i) {
  2315. std::unique_ptr<uint8_t[]> data_buf(new (std::nothrow) uint8_t[out_buffer_size_vec[i]]);
  2316. if (data_buf == nullptr) {
  2317. GELOGE(GE_GRAPH_MALLOC_FAILED, "Malloc buffer failed.");
  2318. return GE_GRAPH_MALLOC_FAILED;
  2319. }
  2320. output_data->blobs.push_back({data_buf.get(), static_cast<uint64_t>(out_buffer_size_vec[i]), false});
  2321. ge::OutputTensorInfo output;
  2322. output.dims = shape_info_vec[i];
  2323. output.data = std::move(data_buf);
  2324. output.length = out_buffer_size_vec[i];
  2325. outputs.emplace_back(std::move(output));
  2326. GELOGD("Output index:%zu, output dims is %s, data length:%lu.", i,
  2327. formats::JoinToString(output.dims).c_str(), output.length);
  2328. }
  2329. return SUCCESS;
  2330. }
  2331. ///
  2332. /// @ingroup ge
  2333. /// @brief send Output Op result to upper layer
  2334. /// @already malloced in ModelLoad, no need to malloc again
  2335. /// @param [in] data_id: the index of output_data
  2336. /// @param [in] rslt_flg: result flag
  2337. /// @param [in] seq_end_flag: sequence end flag
  2338. /// @param [out] output_data: real user output_data
  2339. /// @return Status result
  2340. /// @author
  2341. ///
  2342. Status DavinciModel::ReturnResult(uint32_t data_id, const bool rslt_flg, const bool seq_end_flag,
  2343. OutputData *output_data) {
  2344. GE_CHK_BOOL_EXEC(listener_ != nullptr, return PARAM_INVALID, "listener_ is null.");
  2345. std::vector<ge::OutputTensorInfo> outputs;
  2346. // return result is not required
  2347. if (!rslt_flg && !seq_end_flag) {
  2348. GELOGW("Compute failed, model id: %u", model_id_);
  2349. auto model_manager = ModelManager::GetInstance();
  2350. GE_CHECK_NOTNULL(model_manager);
  2351. auto exception_infos = model_manager->GetExceptionInfos();
  2352. if (exception_infos.size() > 0) {
  2353. GE_CHK_STATUS_RET(data_dumper_.DumpExceptionInfo(exception_infos), "Dump exception info failed");
  2354. } else {
  2355. GELOGI("Exception info is null");
  2356. }
  2357. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, INTERNAL_ERROR, outputs), "OnComputeDone failed.");
  2358. return INTERNAL_ERROR;
  2359. }
  2360. if (output_op_list_.empty()) {
  2361. GELOGW("Output tensor list is empty, model id: %u", model_id_);
  2362. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, INTERNAL_ERROR, outputs), "OnComputeDone failed.");
  2363. return INTERNAL_ERROR;
  2364. }
  2365. GE_CHECK_NOTNULL(output_data);
  2366. // index of data in output_data
  2367. uint32_t data_index = 0;
  2368. output_data->index = data_id;
  2369. output_data->model_id = model_id_;
  2370. is_getnext_sink_dynamic_ = false;
  2371. // copy output data from op to designated position
  2372. for (auto &op_desc : output_op_list_) {
  2373. if (IsGetNextSinkDynamic(op_desc)) {
  2374. GELOGD("Reinit cur dynamic dims when getnext sink dynamic.");
  2375. is_getnext_sink_dynamic_ = true;
  2376. cur_dynamic_dims_.clear();
  2377. cur_dynamic_dims_.resize(shape_of_cur_dynamic_dims_);
  2378. GE_CHK_RT_RET(rtMemcpy(cur_dynamic_dims_.data(), shape_of_cur_dynamic_dims_ * sizeof(int64_t),
  2379. netoutput_last_input_addr_, netoutput_last_input_size_, RT_MEMCPY_DEVICE_TO_HOST));
  2380. }
  2381. GELOGD("Cur dynamic dims is %s.", formats::JoinToString(cur_dynamic_dims_).c_str());
  2382. if (GenOutputTensorInfo(op_desc, data_index, output_data, outputs) != SUCCESS) {
  2383. return INTERNAL_ERROR;
  2384. }
  2385. data_index += op_desc->GetInputsSize();
  2386. }
  2387. if (CopyOutputData(data_id, *output_data, RT_MEMCPY_DEVICE_TO_HOST) != SUCCESS) {
  2388. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, INTERNAL_ERROR, outputs), "OnComputeDone failed");
  2389. return INTERNAL_ERROR;
  2390. }
  2391. if (seq_end_flag) {
  2392. GELOGW("End of sequence, model id: %u", model_id_);
  2393. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, END_OF_SEQUENCE, outputs), "OnCompute Done failed.");
  2394. return END_OF_SEQUENCE;
  2395. }
  2396. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, SUCCESS, outputs), "OnComputeDone failed");
  2397. return SUCCESS;
  2398. }
  2399. ///
  2400. /// @ingroup ge
  2401. /// @brief return not output to upper layer for cloud case
  2402. /// @param [in] data_id
  2403. /// @return Status result
  2404. ///
  2405. Status DavinciModel::ReturnNoOutput(uint32_t data_id) {
  2406. GELOGI("ReturnNoOutput model id:%u", model_id_);
  2407. for (auto op_desc : variable_op_list_) {
  2408. Status ret = VarManager::Instance(session_id_)
  2409. ->SyncBroadCastData2Var(runtime_param_.graph_id, op_desc->GetName(), op_desc, mem_base_);
  2410. GE_CHK_BOOL_EXEC(ret == SUCCESS, break, "sync var data ret failed, model id:%u, op name:%s.", model_id_,
  2411. op_desc->GetName().c_str());
  2412. }
  2413. GE_CHK_BOOL_EXEC(listener_ != nullptr, return PARAM_INVALID, "listener_ is null!");
  2414. std::vector<ge::OutputTensorInfo> outputs;
  2415. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, SUCCESS, outputs), "OnComputeDone failed.");
  2416. return SUCCESS;
  2417. }
  2418. void *DavinciModel::Run(DavinciModel *model) {
  2419. GE_CHK_BOOL_EXEC(model != nullptr,
  2420. CsaInteract::GetInstance().WriteErrorCode(FAILED, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2421. return nullptr, "model_pointer is null!")
  2422. bool seq_end_flag = false;
  2423. uint32_t model_id = model->Id();
  2424. uint32_t device_id = model->GetDeviceId();
  2425. GELOGI("Model Run thread start, model_id:%u.", model_id);
  2426. rtError_t rt_ret = rtSetDevice(static_cast<int32_t>(device_id));
  2427. if (rt_ret != RT_ERROR_NONE) {
  2428. GELOGE(FAILED, "Model run rtsetdevice failed.");
  2429. return nullptr;
  2430. }
  2431. // DeviceReset before thread run finished!
  2432. GE_MAKE_GUARD(not_used_var, [&] { GE_CHK_RT(rtDeviceReset(device_id)); });
  2433. while (model->RunFlag()) {
  2434. bool rslt_flg = true;
  2435. if (model->GetDataInputer() == nullptr) {
  2436. GELOGW("Data inputer is nullptr.");
  2437. CsaInteract::GetInstance().StoreInternalErrorCode(FAILED, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2438. break;
  2439. }
  2440. std::shared_ptr<InputDataWrapper> data_wrapper;
  2441. Status ret = model->GetDataInputer()->Pop(data_wrapper);
  2442. if (data_wrapper == nullptr || ret != SUCCESS) {
  2443. GELOGI("data_wrapper is null!");
  2444. continue;
  2445. }
  2446. GELOGI("Getting the input data, model_id:%u", model_id);
  2447. GE_IF_BOOL_EXEC(!model->RunFlag(), break);
  2448. InputData current_data = data_wrapper->GetInput();
  2449. GELOGI("Model thread Run begin, model id:%u, data index:%u.", model_id, current_data.index);
  2450. if (model->is_online_infer_dynamic_ && !model->is_getnext_sink_dynamic_) {
  2451. model->cur_dynamic_dims_.clear();
  2452. auto shape_data_buffer_data = current_data.blobs.back().data;
  2453. auto shape_data_buffer_length = current_data.blobs.back().length;
  2454. model->cur_dynamic_dims_.assign(reinterpret_cast<int64_t *>(shape_data_buffer_data),
  2455. reinterpret_cast<int64_t *>(shape_data_buffer_data) +
  2456. shape_data_buffer_length / sizeof(int64_t));
  2457. GELOGD("Data: cur dynamic dims is %s", formats::JoinToString(model->cur_dynamic_dims_).c_str());
  2458. }
  2459. GE_TIMESTAMP_START(Model_SyncVarData);
  2460. ret = model->SyncVarData();
  2461. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  2462. ret != SUCCESS, (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2463. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2464. continue, "Copy input data to model failed."); // [No need to check value]
  2465. GE_IF_BOOL_EXEC(model->is_first_execute_, GE_TIMESTAMP_EVENT_END(Model_SyncVarData, "Model Run SyncVarData"));
  2466. GELOGI("Copy input data, model id:%u", model_id);
  2467. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(),
  2468. model->SetProfileTime(MODEL_PRE_PROC_START));
  2469. ret = model->CopyInputData(current_data, false);
  2470. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  2471. ret != SUCCESS, (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2472. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2473. continue, "Copy input data to model failed."); // [No need to check value]
  2474. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), model->SetProfileTime(MODEL_PRE_PROC_END));
  2475. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), model->SetProfileTime(MODEL_INFER_START));
  2476. if (ProfilingManager::Instance().ProfilingOpTraceOn()) {
  2477. GELOGI("GetOpTraceIterNum:%d", ProfilingManager::Instance().GetOpTraceIterNum());
  2478. for (int32_t i = 0; i < ProfilingManager::Instance().GetOpTraceIterNum(); i++) {
  2479. if (!ProfilingManager::Instance().ProfilingLoadFlag()) {
  2480. vector<int32_t> prof_device_id_vec = ProfilingManager::Instance().GetProfilingDeviceId();
  2481. for (size_t j = 0; j < prof_device_id_vec.size(); ++j) {
  2482. // just profiling, no need to check value
  2483. (void)ProfilingManager::Instance().StartProfiling(i, prof_device_id_vec[j]);
  2484. }
  2485. }
  2486. GELOGI("rtModelExecute start.");
  2487. rt_ret = rtModelExecute(model->rt_model_handle_, model->rt_model_stream_, 0);
  2488. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, rslt_flg = false;
  2489. (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2490. continue); // [No need to check value]
  2491. GELOGI("rtModelExecute end");
  2492. GELOGI("rtStreamSynchronize start.");
  2493. rt_ret = rtStreamSynchronize(model->rt_model_stream_);
  2494. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, rslt_flg = false;
  2495. (void)model->ReturnResult(current_data.index, false, seq_end_flag, data_wrapper->GetOutput());
  2496. continue); // [No need to check value]
  2497. GELOGI("rtStreamSynchronize end.");
  2498. (void)ProfilingManager::Instance().StopProfiling(); // just profiling, no need to check value
  2499. }
  2500. } else {
  2501. GE_TIMESTAMP_START(rtModelExecute);
  2502. GELOGI("rtModelExecute start.");
  2503. rt_ret = rtModelExecute(model->rt_model_handle_, model->rt_model_stream_, 0);
  2504. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, rslt_flg = false;
  2505. (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2506. CsaInteract::GetInstance().WriteErrorCode(rt_ret, ERROR_MODULE_RUNTIME, JOBSUBSTATE_GRAPH_EXEC);
  2507. continue);
  2508. GELOGI("rtModelExecute end");
  2509. GE_IF_BOOL_EXEC(model->is_first_execute_, GE_TIMESTAMP_EVENT_END(rtModelExecute, "GraphExcute::rtModelExecute"));
  2510. GE_TIMESTAMP_START(rtStreamSynchronize);
  2511. GELOGI("rtStreamSynchronize start.");
  2512. rt_ret = rtStreamSynchronize(model->rt_model_stream_);
  2513. if (rt_ret == RT_ERROR_END_OF_SEQUENCE) {
  2514. seq_end_flag = true;
  2515. }
  2516. GE_IF_BOOL_EXEC(
  2517. rt_ret != RT_ERROR_NONE, rslt_flg = false; GELOGI("seq_end_flg: %d", seq_end_flag);
  2518. (void)model->ReturnResult(current_data.index, false, seq_end_flag,
  2519. data_wrapper->GetOutput()); // [No need to check value]
  2520. CsaInteract::GetInstance().StoreInternalErrorCode(rt_ret, ERROR_MODULE_RUNTIME, JOBSUBSTATE_GRAPH_EXEC);
  2521. continue);
  2522. GELOGI("rtStreamSynchronize end.");
  2523. GE_IF_BOOL_EXEC(model->is_first_execute_,
  2524. GE_TIMESTAMP_EVENT_END(rtStreamSynchronize, "GraphExcute::Wait for rtStreamSynchronize"));
  2525. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), model->SetProfileTime(MODEL_INFER_END));
  2526. }
  2527. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(),
  2528. model->SetProfileTime(MODEL_AFTER_PROC_START));
  2529. GE_TIMESTAMP_START(ReturnResult3);
  2530. // copy output data from device to host
  2531. GE_IF_BOOL_EXEC(!model->output_op_list_.empty(),
  2532. (void)model->ReturnResult(current_data.index, rslt_flg, false, data_wrapper->GetOutput()))
  2533. // copy output data from device to host for variable graph
  2534. GE_IF_BOOL_EXEC(model->output_op_list_.empty(), (void)model->ReturnNoOutput(current_data.index));
  2535. GE_IF_BOOL_EXEC(model->is_first_execute_,
  2536. GE_TIMESTAMP_EVENT_END(ReturnResult3, "GraphExcute::CopyDataFromDeviceToHost"));
  2537. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(),
  2538. model->SetProfileTime(MODEL_AFTER_PROC_END));
  2539. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), (void)model->SinkTimeProfile(current_data));
  2540. model->iterator_count_++;
  2541. model->is_first_execute_ = false;
  2542. GELOGI("run iterator count is %lu", model->iterator_count_);
  2543. }
  2544. CsaInteract::GetInstance().WriteInternalErrorCode();
  2545. GELOGI("Model run end, model id:%u", model->model_id_);
  2546. return nullptr;
  2547. }
  2548. ///
  2549. /// @ingroup ge
  2550. /// @brief call API provided by data inputer to destroy thread
  2551. /// @param [in] no
  2552. /// @return Status Destroy result
  2553. /// @author
  2554. ///
  2555. Status DavinciModel::DestroyThread() {
  2556. GE_CHK_BOOL_RET_STATUS(data_inputer_ != nullptr, INTERNAL_ERROR, "data_inputer_ is nullptr.");
  2557. run_flg_ = false;
  2558. data_inputer_->Stop();
  2559. if (thread_id_.joinable()) {
  2560. thread_id_.join();
  2561. }
  2562. return SUCCESS;
  2563. }
  2564. ///
  2565. /// @ingroup ge
  2566. /// @brief create model std::thread,
  2567. /// @brief start to execute Model
  2568. /// @param [in] no
  2569. /// @return Status create model thread and execute result
  2570. /// @author
  2571. ///
  2572. Status DavinciModel::ModelRunStart() {
  2573. GE_CHK_BOOL_RET_STATUS(data_inputer_ != nullptr, INTERNAL_ERROR, "data_inputer_ is nullptr.");
  2574. LockRunFlg();
  2575. GE_MAKE_GUARD(tmp_lock, [&] { UnlockRunFlg(); });
  2576. GE_CHK_BOOL_RET_STATUS(!run_flg_, INTERNAL_ERROR, "Model already started.");
  2577. run_flg_ = true;
  2578. // create stream instance which rt_model_handel is running on
  2579. GE_CHK_RT_RET(rtStreamCreate(&rt_model_stream_, priority_));
  2580. is_inner_model_stream_ = true;
  2581. string opt = "0";
  2582. (void)ge::GetContext().GetOption(OPTION_GE_MAX_DUMP_OP_NUM, opt); // option may not be set up, no need to check value
  2583. int64_t maxDumpOpNum = std::strtol(opt.c_str(), nullptr, kDecimal);
  2584. maxDumpOpNum_ = maxDumpOpNum;
  2585. CREATE_STD_THREAD(thread_id_, DavinciModel::Run, this);
  2586. GELOGI("model tread create success, model id:%u.", model_id_);
  2587. return SUCCESS;
  2588. }
  2589. ///
  2590. /// @ingroup ge
  2591. /// @brief call API provided by data inputer and destroy model Thread
  2592. /// @param [in] no
  2593. /// @return Status Destroy result
  2594. /// @author
  2595. ///
  2596. Status DavinciModel::ModelRunStop() {
  2597. LockRunFlg();
  2598. GE_MAKE_GUARD(tmp_lock, [&] { UnlockRunFlg(); });
  2599. GE_IF_BOOL_EXEC(!run_flg_, return SUCCESS);
  2600. GE_CHK_STATUS_RET(DestroyThread(), "DestoyThead failed.");
  2601. return SUCCESS;
  2602. }
  2603. void DavinciModel::UnbindTaskSinkStream() {
  2604. // unbinding hcom stream
  2605. UnbindHcomStream();
  2606. if (is_stream_list_bind_) {
  2607. for (size_t i = 0; i < stream_list_.size(); i++) {
  2608. // unbind rt_model_handle and streams
  2609. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, stream_list_[i]) != RT_ERROR_NONE,
  2610. "Unbind stream from model failed! Index: %zu", i);
  2611. }
  2612. }
  2613. if (is_inner_model_stream_) {
  2614. if (!input_queue_ids_.empty() || !output_queue_ids_.empty()) {
  2615. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, rt_model_stream_) != RT_ERROR_NONE, "Unbind stream failed!");
  2616. }
  2617. // destroy stream that is bound with rt_model
  2618. GE_LOGW_IF(rtStreamDestroy(rt_model_stream_) != RT_ERROR_NONE, "Destroy stream for rt_model failed.")
  2619. }
  2620. if (is_pure_head_stream_ && rt_head_stream_ != nullptr) {
  2621. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, rt_head_stream_) != RT_ERROR_NONE, "Unbind stream failed!");
  2622. GE_LOGW_IF(rtStreamDestroy(rt_head_stream_) != RT_ERROR_NONE, "Destroy stream for rt_model failed.");
  2623. rt_head_stream_ = nullptr;
  2624. }
  2625. if (rt_entry_stream_ != nullptr) {
  2626. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, rt_entry_stream_) != RT_ERROR_NONE, "Unbind stream failed!");
  2627. GE_LOGW_IF(rtStreamDestroy(rt_entry_stream_) != RT_ERROR_NONE, "Destroy stream for rt_model failed.");
  2628. rt_entry_stream_ = nullptr;
  2629. }
  2630. }
  2631. Status DavinciModel::CreateKnownZeroCopyMap(const vector<void *> &inputs, const vector<void *> &outputs) {
  2632. GELOGI("DavinciModel::CreateKnownZeroCopyMap in.");
  2633. if (inputs.size() > data_op_list_.size()) {
  2634. GELOGE(FAILED, "input data addr %u should less than input op number %u.", inputs.size(), data_op_list_.size());
  2635. return FAILED;
  2636. }
  2637. // remove zero copy addr in last iteration
  2638. knonw_input_data_info_.clear();
  2639. knonw_output_data_info_.clear();
  2640. for (size_t i = 0; i < inputs.size(); ++i) {
  2641. const vector<void *> addr_list = ModelUtils::GetOutputDataAddrs(runtime_param_, data_op_list_[i]);
  2642. knonw_input_data_info_[addr_list[kDataIndex]] = inputs[i];
  2643. GELOGI("DavinciModel::CreateKnownZeroCopyMap input %d,v addr %p,p addr %p .", i, addr_list[kDataIndex], inputs[i]);
  2644. }
  2645. if (output_op_list_.size() < kOutputNum) {
  2646. GELOGW("output op num in graph is %u.", output_op_list_.size());
  2647. return SUCCESS;
  2648. }
  2649. const vector<void *> addr_list = ModelUtils::GetInputDataAddrs(runtime_param_, output_op_list_[kDataIndex]);
  2650. for (size_t i = 0; i < addr_list.size() && i < outputs.size(); ++i) {
  2651. knonw_output_data_info_[addr_list[i]] = outputs[i];
  2652. GELOGI("DavinciModel::CreateKnownZeroCopyMap output %d,v addr %p,p addr %p .", i, addr_list[i], outputs[i]);
  2653. }
  2654. GELOGI("DavinciModel::CreateKnownZeroCopyMap success.");
  2655. return SUCCESS;
  2656. }
  2657. Status DavinciModel::UpdateKnownZeroCopyAddr() {
  2658. for (size_t i = 0; i < total_io_addrs_.size(); ++i) {
  2659. auto it_in = knonw_input_data_info_.find(total_io_addrs_[i]);
  2660. if (it_in != knonw_input_data_info_.end()) {
  2661. GELOGI("DavinciModel::UpdateKnownZeroCopyAddr input %d,v addr %p,p addr %p .", i, total_io_addrs_[i],
  2662. knonw_input_data_info_.at(total_io_addrs_[i]));
  2663. total_io_addrs_[i] = knonw_input_data_info_.at(total_io_addrs_[i]);
  2664. }
  2665. auto it_out = knonw_output_data_info_.find(total_io_addrs_[i]);
  2666. if (it_out != knonw_output_data_info_.end()) {
  2667. GELOGI("DavinciModel::UpdateKnownZeroCopyAddr output %d,v addr %p,p addr %p .", i, total_io_addrs_[i],
  2668. knonw_output_data_info_.at(total_io_addrs_[i]));
  2669. total_io_addrs_[i] = knonw_output_data_info_.at(total_io_addrs_[i]);
  2670. }
  2671. }
  2672. GELOGI("DavinciModel::UpdateKnownZeroCopyAddr success.");
  2673. return SUCCESS;
  2674. }
  2675. Status DavinciModel::UpdateKnownNodeArgs(const vector<void *> &inputs, const vector<void *> &outputs) {
  2676. GELOGI("DavinciModel::UpdateKnownNodeArgs in");
  2677. GE_CHK_STATUS_RET(CreateKnownZeroCopyMap(inputs, outputs),
  2678. "DavinciModel::UpdateKnownNodeArgs create map for input/output zero copy.");
  2679. if (!base_addr_not_changed_) {
  2680. total_io_addrs_.clear();
  2681. orig_total_io_addrs_.clear();
  2682. for (size_t task_index = 0; task_index < task_list_.size(); ++task_index) {
  2683. auto &task = task_list_[task_index];
  2684. if (task != nullptr) {
  2685. Status ret = task->UpdateArgs();
  2686. if (ret != SUCCESS) {
  2687. GELOGE(FAILED, "task %d created by davinci model is nullptr.", task_index);
  2688. return FAILED;
  2689. }
  2690. }
  2691. }
  2692. // cache latest iterator io addr
  2693. orig_total_io_addrs_ = total_io_addrs_;
  2694. } else {
  2695. total_io_addrs_ = orig_total_io_addrs_;
  2696. }
  2697. GE_CHK_STATUS_RET(UpdateKnownZeroCopyAddr(), "DavinciModel::UpdateKnownZeroCopyAddr failed.");
  2698. if (total_args_size_ == 0) {
  2699. GELOGW("DavinciModel::UpdateKnownNodeArgs device args %p, dst size %u, pass rtMemcpy.", args_, total_args_size_);
  2700. } else {
  2701. uint32_t total_addr_size = total_io_addrs_.size() * sizeof(uint64_t);
  2702. GELOGI("DavinciModel::UpdateKnownNodeArgs device args %p, dst size %u, src size %u", args_, total_args_size_,
  2703. total_addr_size);
  2704. Status rt_ret =
  2705. rtMemcpy(args_, total_args_size_, total_io_addrs_.data(), total_addr_size, RT_MEMCPY_HOST_TO_DEVICE);
  2706. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(rt_ret, "rtMemcpy error, ret: Ox%X", rt_ret); return FAILED;)
  2707. }
  2708. GELOGI("DavinciModel::UpdateKnownNodeArgs success");
  2709. return SUCCESS;
  2710. }
  2711. Status DavinciModel::InitTaskInfo(domi::ModelTaskDef &model_task_def) {
  2712. GELOGI("InitTaskInfo in, task size %zu", model_task_def.task().size());
  2713. task_list_.resize(model_task_def.task_size());
  2714. for (int i = 0; i < model_task_def.task_size(); ++i) {
  2715. // dynamic shape will create task_list_ before
  2716. const domi::TaskDef &task = model_task_def.task(i);
  2717. if (this->task_list_[i] == nullptr) {
  2718. task_list_[i] = TaskInfoFactory::Instance().Create(static_cast<rtModelTaskType_t>(task.type()));
  2719. }
  2720. GE_CHECK_NOTNULL(task_list_[i]);
  2721. Status ret = task_list_[i]->Init(task, this);
  2722. if (ret != SUCCESS) {
  2723. GELOGE(ret, "Task index %d init failed.", i);
  2724. return ret;
  2725. }
  2726. }
  2727. GELOGI("InitTaskInfo out");
  2728. return SUCCESS;
  2729. }
  2730. Status DavinciModel::MallocKnownArgs() {
  2731. GELOGI("DavinciModel::MallocKnownArgs in");
  2732. const auto &model_task_def = ge_model_->GetModelTaskDefPtr();
  2733. if (model_task_def->task_size() == 0) {
  2734. GELOGW("DavinciModel::MallocKnownArgs davincimodel has no task info.");
  2735. return SUCCESS;
  2736. }
  2737. task_list_.resize(model_task_def->task_size());
  2738. for (int32_t i = 0; i < model_task_def->task_size(); ++i) {
  2739. const domi::TaskDef &taskdef = model_task_def->task(i);
  2740. task_list_[i] = TaskInfoFactory::Instance().Create(static_cast<rtModelTaskType_t>(taskdef.type()));
  2741. GE_CHECK_NOTNULL(task_list_[i]);
  2742. Status ret = task_list_[i]->CalculateArgs(taskdef, this);
  2743. if (ret != SUCCESS) {
  2744. GELOGE(ret, "TaskInfo CalculateArgs failed.");
  2745. return ret;
  2746. }
  2747. }
  2748. // malloc args memory
  2749. if (total_args_size_ == 0) {
  2750. GELOGW("DavinciModel::MallocKnownArgs total_args_size_ equals to zero.");
  2751. return SUCCESS;
  2752. }
  2753. rtError_t rt_ret = rtMalloc(&args_, total_args_size_, RT_MEMORY_HBM);
  2754. if (rt_ret != RT_ERROR_NONE) {
  2755. GELOGE(RT_FAILED, "Call rtMalloc failed, ret: 0x%X", rt_ret);
  2756. return RT_ERROR_TO_GE_STATUS(rt_ret);
  2757. }
  2758. // malloc fixed addr memory, eg: rts op
  2759. if (total_fixed_addr_size_ != 0) {
  2760. GELOGI("Begin to allocate fixed addr.");
  2761. rt_ret = rtMalloc(&fixed_addrs_, total_fixed_addr_size_, RT_MEMORY_HBM);
  2762. if (rt_ret != RT_ERROR_NONE) {
  2763. GELOGE(RT_FAILED, "Call rtMalloc failed, ret: 0x%X", rt_ret);
  2764. return RT_ERROR_TO_GE_STATUS(rt_ret);
  2765. }
  2766. }
  2767. GELOGI("DavinciModel::MallocKnownArgs success, total args size %u. total fixed addr size %ld", total_args_size_,
  2768. total_fixed_addr_size_);
  2769. return SUCCESS;
  2770. }
  2771. Status DavinciModel::DistributeTask() {
  2772. GELOGI("do Distribute.");
  2773. for (auto &task : cpu_task_list_) {
  2774. if (task == nullptr) {
  2775. GELOGW("task is null");
  2776. continue;
  2777. }
  2778. GE_CHK_STATUS_RET(task->Distribute());
  2779. }
  2780. task_desc_info_.clear();
  2781. bool flag = GetL1FusionEnableOption();
  2782. char *skt_enable_env = std::getenv("SKT_ENABLE");
  2783. int64_t env_flag = (skt_enable_env != nullptr) ? std::strtol(skt_enable_env, nullptr, kDecimal) : 0;
  2784. if (env_flag != 0) {
  2785. flag = true;
  2786. }
  2787. const auto &model_task_def = ge_model_->GetModelTaskDefPtr();
  2788. GELOGI("there are %zu task need to save.", task_list_.size());
  2789. for (size_t task_index = 0; task_index < task_list_.size(); ++task_index) {
  2790. auto &task = task_list_.at(task_index);
  2791. GE_CHK_STATUS_RET(task->Distribute(), "Task[%zu] distribute fail", task_index);
  2792. // for data dump
  2793. auto op_index = std::max(model_task_def->task(task_index).kernel().context().op_index(),
  2794. model_task_def->task(task_index).kernel_ex().op_index());
  2795. OpDescPtr op = GetOpByIndex(op_index);
  2796. GE_CHECK_NOTNULL(op);
  2797. SaveDumpOpInfo(runtime_param_, op, task->GetTaskID(), task->GetStreamId());
  2798. if (reinterpret_cast<void *>(task->GetDumpArgs()) != nullptr) {
  2799. bool call_dump = GetDumpProperties().IsLayerNeedDump(name_, om_name_, op->GetName()) && task->CallSaveDumpInfo();
  2800. if (call_dump || is_op_debug_reg_) {
  2801. SaveDumpTask(task->GetTaskID(), task->GetStreamId(), op, task->GetDumpArgs());
  2802. }
  2803. }
  2804. // get op_name by task_index
  2805. if (task->GetCtx() != nullptr) {
  2806. auto iter = op_name_map_.find(task_index);
  2807. if (iter == op_name_map_.end()) {
  2808. continue;
  2809. }
  2810. // else task index is found in op_name_map_
  2811. TaskDescInfo task_desc_info;
  2812. string op_name = op_name_map_[task_index];
  2813. if (!om_name_.empty()) {
  2814. task_desc_info.model_name = om_name_;
  2815. } else {
  2816. task_desc_info.model_name = name_;
  2817. }
  2818. task_desc_info.op_name = op_name;
  2819. task_desc_info.block_dim = model_task_def->task(task_index).kernel().block_dim();
  2820. task_desc_info.task_id = task->GetTaskID();
  2821. task_desc_info.stream_id = task->GetStreamId();
  2822. task_desc_info_.emplace_back(task_desc_info);
  2823. if (flag) {
  2824. if (task->GetSktTaskID() != 0xFFFFFFFF) {
  2825. TaskDescInfo task_desc_info;
  2826. string op_name = "super_kernel_" + to_string(task_index);
  2827. task_desc_info.op_name = op_name;
  2828. task_desc_info.task_id = task->GetSktTaskID();
  2829. task_desc_info_.emplace_back(task_desc_info);
  2830. }
  2831. }
  2832. }
  2833. }
  2834. // launch dump kernel to aicpu
  2835. GE_CHK_STATUS_RET(data_dumper_.LoadDumpInfo(), "Load dump info failed.");
  2836. return SUCCESS;
  2837. }
  2838. void DavinciModel::SetEndGraphId(uint32_t task_id, uint32_t stream_id) {
  2839. auto all_dump_model = GetDumpProperties().GetAllDumpModel();
  2840. bool findByOmName = all_dump_model.find(om_name_) != all_dump_model.end();
  2841. bool findByModelName = all_dump_model.find(name_) != all_dump_model.end();
  2842. if (all_dump_model.find(ge::DUMP_ALL_MODEL) != all_dump_model.end() || findByOmName || findByModelName) {
  2843. GELOGI("start save end_graph_info to dumper, task_id is %u, stream_id is %u", task_id, stream_id);
  2844. data_dumper_.SaveEndGraphId(task_id, stream_id);
  2845. }
  2846. }
  2847. ///
  2848. /// @ingroup ge
  2849. /// @brief Set copy only for No task feed NetOutput address.
  2850. /// @return None.
  2851. ///
  2852. void DavinciModel::SetCopyOnlyOutput() {
  2853. for (const auto &output_outside_addrs : new_output_outside_addrs_) {
  2854. ZeroCopyOffset output_outside = output_outside_addrs.second;
  2855. for (uint32_t out_count = 0; out_count < output_outside.GetAddrCount(); ++out_count) {
  2856. auto &addrs_mapping_list = output_outside.GetOutsideAddrs();
  2857. std::map<const void *, std::vector<void *>> virtual_args_addrs = addrs_mapping_list[out_count];
  2858. for (const auto &virtual_args_addr : virtual_args_addrs) {
  2859. const auto &args_addrs = virtual_args_addr.second;
  2860. if (args_addrs.empty()) { // No task feed Output addr, Need copy directly.
  2861. GELOGI("[ZCPY] just copy %p to netoutput.", virtual_args_addr.first);
  2862. copy_only_addrs_.insert(virtual_args_addr.first);
  2863. }
  2864. }
  2865. }
  2866. }
  2867. }
  2868. ///
  2869. /// @ingroup ge
  2870. /// @brief Set disabled input zero copy addr.
  2871. /// @param [in] const void *addr: address of task
  2872. /// @return None.
  2873. ///
  2874. void DavinciModel::DisableZeroCopy(const void *addr) {
  2875. if (real_virtual_addrs_.find(addr) == real_virtual_addrs_.end()) {
  2876. return;
  2877. }
  2878. // Data link to RTS Op directly.
  2879. std::lock_guard<std::mutex> lock(outside_addrs_mutex_);
  2880. GELOGI("[ZCPY] disable zero copy of %p.", addr);
  2881. copy_only_addrs_.insert(addr);
  2882. }
  2883. ///
  2884. /// @ingroup ge
  2885. /// @brief Save outside address used info for ZeroCopy.
  2886. /// @param [in] const OpDescPtr &op_desc: current op desc
  2887. /// @param [in] const std::vector<void *> &outside_addrs: address of task
  2888. /// @param [in] const void *info: task args
  2889. /// @param [in] const char *args: task args
  2890. /// @param [in] size_t size: size of task args
  2891. /// @param [in] size_t offset: offset of task args
  2892. /// @return None.
  2893. ///
  2894. void DavinciModel::SetZeroCopyAddr(const OpDescPtr &op_desc, const std::vector<void *> &outside_addrs, const void *info,
  2895. void *args, size_t size, size_t offset) {
  2896. // Internal call has ensured that op_desc is not nullptr
  2897. GELOGD("[ZCPY] SetZeroCopyAddr for %s.", op_desc->GetName().c_str());
  2898. size_t nums = outside_addrs.size();
  2899. ZeroCopyTask zero_copy_task(op_desc->GetName(), static_cast<uint8_t *>(args), size);
  2900. for (size_t i = 0; i < nums; ++i) {
  2901. std::lock_guard<std::mutex> lock(outside_addrs_mutex_);
  2902. for (auto &input_outside_addrs : new_input_outside_addrs_) {
  2903. ZeroCopyOffset &input_outside = input_outside_addrs.second;
  2904. bool ret = input_outside.SetOutsideAddrsValue(zero_copy_task, outside_addrs[i], args, offset + i * kAddrLen);
  2905. if (ret) {
  2906. void *args_val = static_cast<uint8_t *>(args) + offset + i * kAddrLen;
  2907. SetBatchLabelAddr(op_desc, reinterpret_cast<uintptr_t>(args_val));
  2908. }
  2909. }
  2910. for (auto &output_outside_addrs : new_output_outside_addrs_) {
  2911. ZeroCopyOffset &output_outside = output_outside_addrs.second;
  2912. bool ret = output_outside.SetOutsideAddrsValue(zero_copy_task, outside_addrs[i], args, offset + i * kAddrLen);
  2913. if (ret) {
  2914. void *args_val = static_cast<uint8_t *>(args) + offset + i * kAddrLen;
  2915. SetBatchLabelAddr(op_desc, reinterpret_cast<uintptr_t>(args_val));
  2916. }
  2917. }
  2918. }
  2919. auto it = zero_copy_op_id_batch_label_.find(op_desc->GetId());
  2920. if (it == zero_copy_op_id_batch_label_.end()) {
  2921. zero_copy_task.SetBatchLabel(kDefaultBatchLable);
  2922. } else {
  2923. zero_copy_task.SetBatchLabel(it->second);
  2924. }
  2925. std::lock_guard<std::mutex> lock(outside_addrs_mutex_);
  2926. if (zero_copy_task.IsTaskArgsSet()) {
  2927. zero_copy_task.SetOriginalArgs(info, offset + nums * kAddrLen);
  2928. zero_copy_tasks_.emplace_back(zero_copy_task);
  2929. }
  2930. }
  2931. void DavinciModel::SetBatchLabelAddr(const OpDescPtr &op_desc, uintptr_t addr) {
  2932. // Establish a mapping between batch label and zero copy address for multi-batch scenes
  2933. auto it = zero_copy_op_id_batch_label_.find(op_desc->GetId());
  2934. if (it == zero_copy_op_id_batch_label_.end()) {
  2935. return;
  2936. }
  2937. const string &batch_label = it->second;
  2938. auto iter = zero_copy_batch_label_addrs_.find(batch_label);
  2939. if (iter != zero_copy_batch_label_addrs_.end()) {
  2940. iter->second.insert(addr);
  2941. GELOGD("[ZCPY] Set zero copy batch label and addrs success, batch label: %s, op name:%s.", batch_label.c_str(),
  2942. op_desc->GetName().c_str());
  2943. } else {
  2944. set<uintptr_t> addrs = {addr};
  2945. zero_copy_batch_label_addrs_.emplace(pair<string, set<uintptr_t>>(batch_label, addrs));
  2946. GELOGD("[ZCPY] New added zero copy batch label and addrs success, batch label: %s, op name:%s.",
  2947. batch_label.c_str(), op_desc->GetName().c_str());
  2948. }
  2949. }
  2950. ///
  2951. /// @ingroup ge
  2952. /// @brief Copy Check input size and model op size.
  2953. /// @param [in] const int64_t &input_size: input size.
  2954. /// @param [in] const int64_t &op_size: model op size.
  2955. /// @param [in] is_dynamic: dynamic batch input flag.
  2956. /// @return true if success
  2957. ///
  2958. bool DavinciModel::CheckInputAndModelSize(const int64_t &input_size, const int64_t &op_size, bool is_dynamic) {
  2959. if (is_dynamic) { // dynamic is max size.
  2960. GELOGI("No need to check input and model size.");
  2961. return true;
  2962. }
  2963. if (input_size > op_size) {
  2964. GELOGW(
  2965. "Input size [%u] is bigger than om size need [%u], "
  2966. "MAY cause inference result ERROR, please check model input",
  2967. input_size, op_size);
  2968. }
  2969. bool is_dynamic_aipp = false;
  2970. for (const auto &op_desc : data_op_list_) {
  2971. if (op_desc->GetType() == AIPP_DATA_TYPE) {
  2972. GELOGI("This is dynamic aipp model.");
  2973. is_dynamic_aipp = true;
  2974. break;
  2975. }
  2976. }
  2977. if (is_dynamic_aipp) {
  2978. GELOGI("This is dynamic aipp model, no need to judge smaller input size");
  2979. return true;
  2980. }
  2981. // Judge overflow first
  2982. if (input_size > (INT64_MAX - kDataMemAlignSizeCompare)) {
  2983. GELOGI("The Input size [%ld] is smaller than model size [%ld] and is in the range of 64 bytes", input_size,
  2984. op_size);
  2985. return true;
  2986. }
  2987. // The input and model input size can not be exactly equal because user input is not definite.
  2988. if ((input_size + kDataMemAlignSizeCompare) < op_size) {
  2989. GELOGE(FAILED, "Input size [%ld] can not be smaller than op size [%ld] after 64-byte alignment", input_size,
  2990. op_size);
  2991. return false;
  2992. }
  2993. return true;
  2994. }
  2995. ///
  2996. /// @ingroup ge
  2997. /// @brief Copy Inputs and Outputs addr to model for direct use.
  2998. /// @param [in] const InputData &input_data: model input data.
  2999. /// @param [in] OutputData &output_data: model output data.
  3000. /// @param [in] bool is_dynamic_input: whether is dynamic input, true: is dynamic input; false: not is dynamic input
  3001. /// @return SUCCESS handle successfully / PARAM_INVALID for failed
  3002. ///
  3003. Status DavinciModel::CopyModelData(const InputData &input_data, OutputData &output_data, bool is_dynamic) {
  3004. if (UpdateIoTaskArgs(new_input_data_info_, true, input_data.blobs, is_dynamic, input_data.batch_label) != SUCCESS) {
  3005. GELOGE(PARAM_INVALID, "[ZCPY] Update input data to model failed.");
  3006. return PARAM_INVALID;
  3007. }
  3008. if (UpdateIoTaskArgs(new_output_data_info_, false, output_data.blobs, is_dynamic, input_data.batch_label) !=
  3009. SUCCESS) {
  3010. GELOGE(PARAM_INVALID, "[ZCPY] Update output data to model failed.");
  3011. return PARAM_INVALID;
  3012. }
  3013. for (ZeroCopyTask &task : zero_copy_tasks_) {
  3014. GE_CHK_STATUS_RET(task.DistributeParam(is_async_mode_, rt_model_stream_), "[ZCPY] Update args failed.");
  3015. }
  3016. output_data.index = input_data.index;
  3017. output_data.model_id = model_id_;
  3018. return SUCCESS;
  3019. }
  3020. ///
  3021. /// @ingroup ge
  3022. /// @brief Copy Data addr to model for direct use.
  3023. /// @param [in] data_info: model memory addr/size map { data_index, { tensor_size, tensor_addr } }.
  3024. /// @param [in] is_input: input data or output data
  3025. /// @param [in] blobs: user input/output data list.
  3026. /// @param [in] is_dynamic: whether is dynamic input, true: is dynamic input; false: not is dynamic input
  3027. /// @param [in] batch_label: batch label for multi-batch scenes
  3028. /// @return SUCCESS handle successfully / others handle failed
  3029. ///
  3030. Status DavinciModel::UpdateIoTaskArgs(const std::map<uint32_t, ZeroCopyOffset> &data_info, bool is_input,
  3031. const vector<DataBuffer> &blobs, bool is_dynamic, const string &batch_label) {
  3032. string input_or_output = "input";
  3033. is_input ? input_or_output = "input" : input_or_output = "output";
  3034. if (blobs.size() != data_info.size()) {
  3035. GELOGE(FAILED, "Verify %s data num failed: model requires %zu, but user actually feeds %zu",
  3036. input_or_output.c_str(), data_info.size(), blobs.size());
  3037. return FAILED;
  3038. }
  3039. for (const auto &data : data_info) {
  3040. if (data.first >= blobs.size()) { // check data index.
  3041. GELOGE(FAILED, "Verify %s data num failed: can not find No.%zu data, because user only feeds %zu",
  3042. input_or_output.c_str(), data.first, blobs.size());
  3043. return FAILED;
  3044. }
  3045. const DataBuffer &buffer = blobs[data.first]; // index of data.
  3046. if (buffer.data == nullptr) {
  3047. GELOGE(FAILED, "data_buf.data is nullptr, index=%u", data.first);
  3048. return FAILED;
  3049. }
  3050. if (!CheckInputAndModelSize(buffer.length, data.second.GetDataSize(), is_dynamic)) {
  3051. GELOGE(FAILED, "Check input size and model size failed");
  3052. return FAILED;
  3053. }
  3054. void *basic_addr = data.second.GetBasicAddr();
  3055. uint64_t data_size = data.second.GetDataSize();
  3056. if (copy_only_addrs_.count(basic_addr) > 0) {
  3057. if (is_input) {
  3058. GELOGI("[IMAS] Find addr %p need direct copy from user malloc input %p", basic_addr, buffer.data);
  3059. if (rtMemcpy(basic_addr, data_size, buffer.data, buffer.length, RT_MEMCPY_DEVICE_TO_DEVICE) != RT_ERROR_NONE) {
  3060. GELOGE(FAILED, "Non-zero copy data node copy failed");
  3061. return FAILED;
  3062. }
  3063. }
  3064. GELOGI("No need to exeucte zero copy task because this addr %p need direct copy.", basic_addr);
  3065. continue;
  3066. }
  3067. for (size_t count = 0; count < data.second.GetDataCount(); ++count) {
  3068. int64_t size = data.second.GetDataInfo().at(count).first;
  3069. void *addr = data.second.GetDataInfo().at(count).second;
  3070. void *buffer_addr = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(buffer.data) +
  3071. data.second.GetRelativeOffset().at(count));
  3072. GELOGI("[ZCPY] Copy %s blobs_index %u, virtual_addr: %p, size: %ld, user_data_addr: %p", input_or_output.c_str(),
  3073. data.first, addr, size, buffer_addr);
  3074. // For input data, just copy for rts task.
  3075. for (ZeroCopyTask &task : zero_copy_tasks_) {
  3076. if (task.GetBatchLabel() != kDefaultBatchLable && task.GetBatchLabel() != batch_label) {
  3077. continue;
  3078. }
  3079. uintptr_t addr_val = reinterpret_cast<uintptr_t>(addr);
  3080. if (task.UpdateTaskParam(addr_val, buffer_addr, zero_copy_batch_label_addrs_, batch_label) != SUCCESS) {
  3081. return FAILED;
  3082. }
  3083. }
  3084. }
  3085. }
  3086. return SUCCESS;
  3087. }
  3088. ///
  3089. /// @ingroup ge
  3090. /// @brief get unique identification for op when load two or more models
  3091. /// @param [in] const OpDescPtr: current op.
  3092. /// @param [in] string identification: unique identification for current op.
  3093. /// @return SUCCESS handle successfully / others handle failed
  3094. ///
  3095. void DavinciModel::GetUniqueId(const OpDescPtr &op_desc, std::string &unique_identification) {
  3096. std::string session_graph_id;
  3097. GE_IF_BOOL_EXEC(AttrUtils::GetStr(*op_desc, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id),
  3098. GELOGD("Get original type of session_graph_id."));
  3099. if (session_graph_id.empty()) {
  3100. return;
  3101. } else if (session_graph_id.find("-1") != string::npos) {
  3102. unique_identification = session_graph_id + "_" + to_string(model_id_);
  3103. } else {
  3104. unique_identification = session_graph_id;
  3105. }
  3106. }
  3107. ///
  3108. /// @ingroup ge
  3109. /// @brief For TVM Op, avoid Addr Reuse.
  3110. /// @return void*
  3111. ///
  3112. const char *DavinciModel::GetRegisterStub(const string &binfile, const string &session_graph_id) {
  3113. string binfile_key;
  3114. if (session_graph_id.empty()) {
  3115. binfile_key = binfile;
  3116. } else {
  3117. binfile_key = session_graph_id + "_" + binfile;
  3118. }
  3119. auto it = tvm_bin_kernel_.find(binfile_key);
  3120. if (it != tvm_bin_kernel_.end()) {
  3121. return it->c_str();
  3122. } else {
  3123. it = tvm_bin_kernel_.insert(tvm_bin_kernel_.end(), binfile_key);
  3124. return it->c_str();
  3125. }
  3126. }
  3127. ///
  3128. /// @ingroup ge
  3129. /// @brief Constant Op Init.
  3130. /// @return Status
  3131. ///
  3132. Status DavinciModel::InitConstant(const OpDescPtr &op_desc) {
  3133. auto v_weights = ModelUtils::GetWeights(op_desc);
  3134. auto v_output_size = ModelUtils::GetOutputSize(op_desc);
  3135. auto v_output_addr = ModelUtils::GetOutputDataAddrs(runtime_param_, op_desc);
  3136. GE_IF_BOOL_EXEC(v_weights.empty() || v_output_size.empty() || v_output_addr.empty(),
  3137. GELOGE(PARAM_INVALID, "const op:%s not set output", op_desc->GetName().c_str());
  3138. return PARAM_INVALID;);
  3139. GeTensor *tensor = const_cast<GeTensor *>(v_weights[0].get());
  3140. GE_IF_BOOL_EXEC(static_cast<size_t>(v_output_size[0]) < tensor->GetData().size(),
  3141. GELOGE(PARAM_INVALID, "output size:%u less than weight data size:%zu", v_output_size[0],
  3142. tensor->GetData().size());
  3143. return PARAM_INVALID;);
  3144. GE_IF_BOOL_EXEC(tensor->GetData().size() == 0, GELOGW("const op:%s has no weight data.", op_desc->GetName().c_str());
  3145. return SUCCESS;);
  3146. auto desc = tensor->GetTensorDesc();
  3147. if (desc.GetDataType() == DT_STRING) {
  3148. GeShape tensor_shape = desc.GetShape();
  3149. /// if tensor is a scaler, it's shape size if zero, according ge_tensor.cc.
  3150. /// the logic of GetShapeSize is wrong, the scaler tensor's GetShapeSize is zero
  3151. /// and that of unknown shape is zero too.
  3152. /// unknown shape will not appear here, so we can use zero judge a tensor is scaler or not
  3153. int64_t elem_num = tensor_shape.GetShapeSize();
  3154. if (elem_num == 0 && tensor_shape.GetDims().size() == 0) {
  3155. elem_num = 1;
  3156. }
  3157. uint64_t *buff = reinterpret_cast<uint64_t *>(tensor->MutableData().data());
  3158. GE_CHK_BOOL_RET_STATUS(ge::CheckInt64Uint32MulOverflow(elem_num, kBytes) == SUCCESS, FAILED,
  3159. "Shape size is invalid");
  3160. uint64_t offset = static_cast<uint64_t>(elem_num * kBytes);
  3161. uint64_t hbm_raw_data_base_addr =
  3162. reinterpret_cast<uint64_t>(reinterpret_cast<uintptr_t>(v_output_addr[0])) + offset;
  3163. for (int64_t i = elem_num - 1; i >= 0; --i) {
  3164. buff[i] = hbm_raw_data_base_addr + (buff[i] - buff[0]);
  3165. }
  3166. }
  3167. GELOGI("[IMAS]InitConstant memcpy graph_%u type[V] name[%s] output[%d] memaddr[%p] mem_size[%u] datasize[%zu]",
  3168. runtime_param_.graph_id, op_desc->GetName().c_str(), 0, v_output_addr[0], v_output_size[0],
  3169. tensor->GetData().size());
  3170. GE_CHK_RT_RET(rtMemcpy(v_output_addr[0], v_output_size[0], tensor->GetData().data(), tensor->GetData().size(),
  3171. RT_MEMCPY_HOST_TO_DEVICE));
  3172. return SUCCESS;
  3173. }
  3174. ///
  3175. /// @ingroup ge
  3176. /// @brief TVM Op Init.
  3177. /// @return Status
  3178. ///
  3179. Status DavinciModel::InitTbeHandle(const OpDescPtr &op_desc) {
  3180. auto kernel = ge_model_->GetTBEKernelStore().FindKernel(op_desc->GetName());
  3181. auto tbe_kernel = (kernel != nullptr) ? kernel : op_desc->TryGetExtAttr(OP_EXTATTR_NAME_TBE_KERNEL, TBEKernelPtr());
  3182. if (tbe_kernel == nullptr) {
  3183. GELOGE(INTERNAL_ERROR, "TBE: %s can't find tvm bin file!", op_desc->GetName().c_str());
  3184. return INTERNAL_ERROR;
  3185. }
  3186. std::string session_graph_model_id;
  3187. GetUniqueId(op_desc, session_graph_model_id);
  3188. const char *bin_file_key = GetRegisterStub(op_desc->GetName(), session_graph_model_id); // from set, always valid.
  3189. TBEHandleStore &kernel_store = TBEHandleStore::GetInstance();
  3190. std::lock_guard<std::mutex> lock(tvm_bin_mutex_);
  3191. if (rtQueryFunctionRegistered(bin_file_key) != RT_ERROR_NONE) {
  3192. void *bin_handle = nullptr;
  3193. if (!kernel_store.FindTBEHandle(bin_file_key, bin_handle)) {
  3194. GELOGI("TBE: can't find the kernel_name[%s] in HandleMap", bin_file_key);
  3195. rtDevBinary_t binary;
  3196. std::string json_string;
  3197. GE_IF_BOOL_EXEC(AttrUtils::GetStr(op_desc, TVM_ATTR_NAME_MAGIC, json_string),
  3198. GELOGI("Get original type of session_graph_id."));
  3199. if (json_string == "RT_DEV_BINARY_MAGIC_ELF_AICPU") {
  3200. binary.magic = RT_DEV_BINARY_MAGIC_ELF_AICPU;
  3201. } else if (json_string == "RT_DEV_BINARY_MAGIC_ELF") {
  3202. binary.magic = RT_DEV_BINARY_MAGIC_ELF;
  3203. } else if (json_string == "RT_DEV_BINARY_MAGIC_ELF_AIVEC") {
  3204. binary.magic = RT_DEV_BINARY_MAGIC_ELF_AIVEC;
  3205. } else {
  3206. GELOGE(PARAM_INVALID, "TBE: Invalid parameter magic number! json: %s", json_string.c_str());
  3207. return PARAM_INVALID;
  3208. }
  3209. binary.version = 0;
  3210. binary.data = tbe_kernel->GetBinData();
  3211. binary.length = tbe_kernel->GetBinDataSize();
  3212. GELOGI("TBE: binary.length: %lu", binary.length);
  3213. GE_CHK_RT_RET(rtDevBinaryRegister(&binary, &bin_handle));
  3214. std::string meta_data;
  3215. GE_IF_BOOL_EXEC(AttrUtils::GetStr(op_desc, TVM_ATTR_NAME_METADATA, meta_data),
  3216. GELOGI("Get original type of json_string"));
  3217. GELOGI("TBE: meta data: %s", meta_data.empty() ? "null" : meta_data.c_str());
  3218. GE_IF_BOOL_EXEC(!meta_data.empty(), GE_CHK_RT_RET(rtMetadataRegister(bin_handle, meta_data.c_str())));
  3219. kernel_store.StoreTBEHandle(bin_file_key, bin_handle, tbe_kernel);
  3220. } else {
  3221. GELOGI("TBE: find the kernel_name[%s] in HandleMap", bin_file_key);
  3222. kernel_store.ReferTBEHandle(bin_file_key);
  3223. }
  3224. std::string kernel_name;
  3225. GE_IF_BOOL_EXEC(AttrUtils::GetStr(op_desc, op_desc->GetName() + "_kernelname", kernel_name),
  3226. GELOGI("Get original type of kernel_name"));
  3227. GELOGI("TBE: binfile_key=%s, kernel_name=%s", bin_file_key, kernel_name.c_str());
  3228. GE_CHK_RT_RET(rtFunctionRegister(bin_handle, bin_file_key, bin_file_key, kernel_name.c_str(), 0));
  3229. used_tbe_handle_map_[bin_file_key] = 1; // Init used num to 1.
  3230. return SUCCESS;
  3231. }
  3232. // Kernel registed, Increase used num in store.
  3233. StoreTbeHandle(bin_file_key);
  3234. return SUCCESS;
  3235. }
  3236. void DavinciModel::StoreTbeHandle(const std::string &handle_key) {
  3237. // Online mode FE may call rtFunctionRegister.
  3238. TBEHandleStore &kernel_store = TBEHandleStore::GetInstance();
  3239. auto it = used_tbe_handle_map_.find(handle_key);
  3240. if (it != used_tbe_handle_map_.end()) {
  3241. // GE registered, increase reference.
  3242. kernel_store.ReferTBEHandle(handle_key);
  3243. it->second++;
  3244. return;
  3245. }
  3246. void *bin_handle = nullptr;
  3247. if (kernel_store.FindTBEHandle(handle_key, bin_handle)) {
  3248. // GE registered, increase reference.
  3249. used_tbe_handle_map_[handle_key] = 1; // Init used num to 1.
  3250. kernel_store.ReferTBEHandle(handle_key);
  3251. }
  3252. }
  3253. void DavinciModel::CleanTbeHandle() {
  3254. TBEHandleStore &kernel_store = TBEHandleStore::GetInstance();
  3255. kernel_store.EraseTBEHandle(used_tbe_handle_map_);
  3256. used_tbe_handle_map_.clear();
  3257. tvm_bin_kernel_.clear();
  3258. }
  3259. ///
  3260. /// @ingroup ge
  3261. /// @brief insert active_stream_indication_
  3262. /// @return Status
  3263. ///
  3264. Status DavinciModel::InitStreamActive(const OpDescPtr &op_desc) {
  3265. if (op_desc->HasAttr(ATTR_NAME_SWITCH_BRANCH_NODE_LABEL)) {
  3266. std::vector<uint32_t> active_stream_list;
  3267. GE_CHK_BOOL_EXEC(AttrUtils::GetListInt(op_desc, ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list),
  3268. return INTERNAL_ERROR, "StreamActiveOp get attr ACTIVE_STREAM failed.");
  3269. for (size_t j = 0; j < active_stream_list.size(); ++j) {
  3270. active_stream_indication_.insert(active_stream_list[j]);
  3271. GELOGI("flowctrl_op_index_map node:%s, active_stream_id=%u.", op_desc->GetName().c_str(), active_stream_list[j]);
  3272. }
  3273. }
  3274. return SUCCESS;
  3275. }
  3276. Status DavinciModel::InitStreamSwitch(const OpDescPtr &op_desc) {
  3277. std::vector<uint32_t> active_stream_list;
  3278. GE_LOGI_IF(!ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list),
  3279. "GetInt ACTIVE_STREAM_LIST failed.");
  3280. if (active_stream_list.size() != kTrueBranchStreamNum) {
  3281. GELOGE(INTERNAL_ERROR, "Stream num of switch true branch must be %u.", kTrueBranchStreamNum);
  3282. return INTERNAL_ERROR;
  3283. }
  3284. uint32_t true_stream_id = active_stream_list.front();
  3285. active_stream_indication_.insert(true_stream_id);
  3286. GELOGI("flowctrl_op_index_map node:%s, true_stream_id=%u.", op_desc->GetName().c_str(), true_stream_id);
  3287. return SUCCESS;
  3288. }
  3289. Status DavinciModel::InitStreamSwitchN(const OpDescPtr &op_desc) {
  3290. std::vector<uint32_t> active_stream_list;
  3291. if (!AttrUtils::GetListInt(op_desc, ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list)) {
  3292. GELOGE(INTERNAL_ERROR, "StreamSwitchNOp get attr ACTIVE_STREAM failed.");
  3293. return INTERNAL_ERROR;
  3294. }
  3295. for (size_t j = 0; j < active_stream_list.size(); ++j) {
  3296. active_stream_indication_.insert(active_stream_list[j]);
  3297. GELOGI("StreamSwitchNOp node:%s, active_stream_id=%u.", op_desc->GetName().c_str(), active_stream_list[j]);
  3298. }
  3299. uint32_t batch_num = 0;
  3300. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_BATCH_NUM, batch_num)) {
  3301. GELOGE(FAILED, "Failed to get attr ATTR_NAME_BATCH_NUM, StreamSwitchN: %s.", op_desc->GetName().c_str());
  3302. return FAILED;
  3303. }
  3304. return SetDynamicBatchInfo(op_desc, batch_num);
  3305. }
  3306. Status DavinciModel::SetDynamicBatchInfo(const OpDescPtr &op_desc, uint32_t batch_num) {
  3307. batch_info_.clear();
  3308. combined_batch_info_.clear();
  3309. (void)AttrUtils::GetInt(op_desc, ATTR_DYNAMIC_TYPE, dynamic_type_);
  3310. (void)AttrUtils::GetListStr(op_desc, ATTR_USER_DESIGNEATE_SHAPE_ORDER, user_designate_shape_order_);
  3311. for (uint32_t i = 0; i < batch_num; ++i) {
  3312. std::vector<int64_t> batch_shape;
  3313. const std::string attr_name = ATTR_NAME_PRED_VALUE + "_" + std::to_string(i);
  3314. if (!AttrUtils::GetListInt(op_desc, attr_name, batch_shape)) {
  3315. GELOGE(FAILED, "Get attr ATTR_NAME_PRED_VALUE failed, Node: %s", op_desc->GetName().c_str());
  3316. batch_info_.clear();
  3317. return FAILED;
  3318. }
  3319. batch_info_.emplace_back(batch_shape);
  3320. batch_shape.clear();
  3321. const string attr_combined_batch = ATTR_NAME_COMBINED_BATCH + "_" + std::to_string(i);
  3322. if (AttrUtils::GetListInt(op_desc, attr_combined_batch, batch_shape)) {
  3323. combined_batch_info_.emplace_back(batch_shape);
  3324. }
  3325. }
  3326. return SUCCESS;
  3327. }
  3328. Status DavinciModel::InitCase(const OpDescPtr &op_desc) {
  3329. uint32_t batch_num = 0;
  3330. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_BATCH_NUM, batch_num)) {
  3331. GELOGI("Not multi-batch Node: %s", op_desc->GetName().c_str());
  3332. return SUCCESS;
  3333. }
  3334. return SetDynamicBatchInfo(op_desc, batch_num);
  3335. }
  3336. bool DavinciModel::IsBroadCastOpData(const ge::NodePtr &var_node) {
  3337. for (auto out_anchor : var_node->GetAllOutDataAnchors()) {
  3338. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  3339. for (auto in_anchor : out_anchor->GetPeerInDataAnchors()) {
  3340. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  3341. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  3342. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  3343. if (dst_node->GetType() == HCOMBROADCAST || dst_node->GetType() == HVDCALLBACKBROADCAST) {
  3344. return true;
  3345. }
  3346. }
  3347. }
  3348. return false;
  3349. }
  3350. ///
  3351. /// @ingroup ge
  3352. /// @brief Init model stream for NN model.
  3353. /// @param [in] stream user input model stream.
  3354. /// @return Status
  3355. ///
  3356. Status DavinciModel::InitModelStream(rtStream_t stream) {
  3357. ExecuteMode curr_mode = is_async_mode_ ? ASYNCHRONIZATION : SYNCHRONIZATION;
  3358. GE_CHK_BOOL_RET_STATUS((curr_mode == last_execute_mode_) || (last_execute_mode_ == INITIALIZATION), INTERNAL_ERROR,
  3359. "NnExecute not support mix execute.");
  3360. last_execute_mode_ = curr_mode;
  3361. // asynchronize mode, use user input stream.
  3362. if (is_async_mode_) {
  3363. rt_model_stream_ = stream;
  3364. is_inner_model_stream_ = false;
  3365. return SUCCESS;
  3366. }
  3367. // synchronize mode, use forbidden stream.
  3368. if (stream != nullptr) {
  3369. if ((rt_model_stream_ != nullptr) && is_inner_model_stream_) {
  3370. GE_LOGW_IF(rtStreamDestroy(rt_model_stream_) != RT_ERROR_NONE, "Destroy rt_stream failed!");
  3371. }
  3372. rt_model_stream_ = stream;
  3373. is_inner_model_stream_ = false;
  3374. return SUCCESS;
  3375. }
  3376. if (rt_model_stream_ == nullptr) {
  3377. GE_CHK_RT_RET(rtStreamCreateWithFlags(&rt_model_stream_, priority_, RT_STREAM_FORBIDDEN_DEFAULT));
  3378. is_inner_model_stream_ = true;
  3379. }
  3380. return SUCCESS;
  3381. }
  3382. ///
  3383. /// @ingroup ge
  3384. /// @brief ACL case, do not start new thread, return execute result.
  3385. /// @param [in] stream execute model stream.
  3386. /// @param [in] async_mode is asynchronize mode.
  3387. /// @param [in] input_data model input data.
  3388. /// @param [out] output_data model output data.
  3389. ///
  3390. Status DavinciModel::NnExecute(rtStream_t stream, bool async_mode, const InputData &input_data,
  3391. OutputData &output_data) {
  3392. is_async_mode_ = async_mode;
  3393. GELOGI("Model Run begin, model id:%u, data index:%u, flag:%d.", model_id_, input_data.index, is_async_mode_);
  3394. GE_CHK_STATUS_RET(InitModelStream(stream), "Init model stream failed.");
  3395. is_dynamic_ = input_data.is_dynamic_batch;
  3396. if (!is_dynamic_) {
  3397. zero_copy_batch_label_addrs_.clear();
  3398. }
  3399. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_PRE_PROC_START));
  3400. Status ret = CopyModelData(input_data, output_data, is_dynamic_);
  3401. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Copy input data to model failed. model id: %u",
  3402. model_id_);
  3403. GELOGI("current_data.index=%u", input_data.index);
  3404. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_PRE_PROC_END));
  3405. if (!task_list_.empty()) {
  3406. GELOGD("rtModelExecute do");
  3407. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_INFER_START));
  3408. rtError_t rt_ret = rtModelExecute(rt_model_handle_, rt_model_stream_, 0);
  3409. GE_CHK_RT_EXEC(rt_ret, return RT_ERROR_TO_GE_STATUS(rt_ret));
  3410. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_INFER_END));
  3411. GELOGI("rtModelExecute end");
  3412. }
  3413. if (!is_async_mode_) {
  3414. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_AFTER_PROC_START));
  3415. ret = CopyOutputData(input_data.index, output_data, RT_MEMCPY_DEVICE_TO_DEVICE);
  3416. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Copy Output data to user failed.");
  3417. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_AFTER_PROC_END));
  3418. }
  3419. // report model time data
  3420. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), (void)SinkTimeProfile(input_data));
  3421. GELOGI("Model run end, model id:%u", model_id_);
  3422. return SUCCESS;
  3423. }
  3424. // Add active entry stream for special env.
  3425. Status DavinciModel::AddHeadStream() {
  3426. if (active_stream_list_.empty()) {
  3427. GELOGE(INTERNAL_ERROR, "Active stream is empty, stream list size: %zu, stream indication size: %zu.",
  3428. stream_list_.size(), active_stream_indication_.size());
  3429. return INTERNAL_ERROR;
  3430. }
  3431. if (active_stream_list_.size() == 1) {
  3432. GELOGI("Just one active stream, take as head stream.");
  3433. rt_head_stream_ = active_stream_list_[0];
  3434. is_pure_head_stream_ = false;
  3435. } else {
  3436. // Create stream which rt_model_handel running on, this is S0, TS stream.
  3437. GELOGI("Multiple active stream: %zu, create head stream.", active_stream_list_.size());
  3438. GE_CHK_RT_RET(rtStreamCreateWithFlags(&rt_head_stream_, priority_, RT_STREAM_PERSISTENT));
  3439. GE_CHK_RT_RET(rtModelBindStream(rt_model_handle_, rt_head_stream_, RT_INVALID_FLAG)); // Not active.
  3440. is_pure_head_stream_ = true;
  3441. for (auto s : active_stream_list_) {
  3442. std::shared_ptr<CpuTaskActiveEntry> active_entry = MakeShared<CpuTaskActiveEntry>(rt_head_stream_);
  3443. if (active_entry == nullptr) {
  3444. GELOGE(MEMALLOC_FAILED, "Make CpuTaskActiveEntry task failed.");
  3445. return MEMALLOC_FAILED;
  3446. }
  3447. Status status = active_entry->Init(s);
  3448. if (status != SUCCESS) {
  3449. return status;
  3450. }
  3451. cpu_task_list_.emplace_back(active_entry);
  3452. }
  3453. }
  3454. // Create entry stream active head stream. AICPU stream.
  3455. GE_CHK_RT_RET(rtStreamCreateWithFlags(&rt_entry_stream_, priority_, RT_STREAM_AICPU));
  3456. GE_CHK_RT_RET(rtModelBindStream(rt_model_handle_, rt_entry_stream_, RT_HEAD_STREAM));
  3457. return SUCCESS;
  3458. }
  3459. Status DavinciModel::InitEntryTask() {
  3460. if (deploy_type_ == AICPU_DEPLOY_CROSS_THREAD) {
  3461. GE_CHK_STATUS_RET(AddHeadStream(), "Add head stream failed.");
  3462. return CpuActiveStream();
  3463. } else {
  3464. return LoadWithQueue();
  3465. }
  3466. }
  3467. uint8_t *DavinciModel::MallocFeatureMapMem(size_t data_size) {
  3468. uint8_t *mem_base = nullptr;
  3469. const string purpose("feature map,used for op input and output.");
  3470. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3471. data_size = static_cast<size_t>(VarManager::Instance(session_id_)->GetGraphMemoryMaxSize());
  3472. string memory_key = std::to_string(0) + "_f";
  3473. mem_base = MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, memory_key, data_size, GetDeviceId());
  3474. } else {
  3475. mem_base = MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, data_size, GetDeviceId());
  3476. }
  3477. if (mem_base != nullptr) {
  3478. GE_CHK_RT(rtMemset(mem_base, data_size, 0U, data_size));
  3479. }
  3480. return mem_base;
  3481. }
  3482. uint8_t *DavinciModel::MallocP2PMem(size_t p2p_data_size) {
  3483. uint8_t *p2p_mem_base = nullptr;
  3484. const string purpose("p2p memory, used for some op related to hcom");
  3485. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3486. string p2p_memory_key = std::to_string(0) + "_p";
  3487. p2p_mem_base =
  3488. MemManager::Instance(RT_MEMORY_P2P_DDR)->MallocMemory(purpose, p2p_memory_key, p2p_data_size, GetDeviceId());
  3489. } else {
  3490. p2p_mem_base = MemManager::Instance(RT_MEMORY_P2P_DDR)->MallocMemory(purpose, p2p_data_size, GetDeviceId());
  3491. }
  3492. return p2p_mem_base;
  3493. }
  3494. uint8_t *DavinciModel::MallocWeightsMem(size_t weights_size) {
  3495. uint8_t *weights_mem_base = nullptr;
  3496. const string purpose("weights memory in inference network.");
  3497. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3498. string weight_memory_key = std::to_string(0) + "_w";
  3499. weights_mem_base =
  3500. MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, weight_memory_key, weights_size, GetDeviceId());
  3501. } else {
  3502. weights_mem_base = MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, weights_size, GetDeviceId());
  3503. }
  3504. return weights_mem_base;
  3505. }
  3506. void DavinciModel::FreeFeatureMapMem() {
  3507. if (std::getenv(kEnvGeuseStaticMemory) != nullptr && is_inner_mem_base_) {
  3508. string weight_memory_key = std::to_string(0) + "_f";
  3509. if (MemManager::Instance(RT_MEMORY_HBM)->GetMemoryAddr(weight_memory_key) != nullptr) {
  3510. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(weight_memory_key, GetDeviceId()),
  3511. "failed to free weight memory");
  3512. }
  3513. mem_base_ = nullptr;
  3514. } else {
  3515. GE_IF_BOOL_EXEC(mem_base_ != nullptr && is_inner_mem_base_,
  3516. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(mem_base_, GetDeviceId()),
  3517. "failed to free feature_map memory");
  3518. mem_base_ = nullptr);
  3519. }
  3520. }
  3521. void DavinciModel::FreeP2PMem() {
  3522. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3523. std::string p2p_memory_key = std::to_string(0) + "_p";
  3524. if (MemManager::Instance(RT_MEMORY_P2P_DDR)->GetMemoryAddr(p2p_memory_key) != nullptr) {
  3525. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_P2P_DDR)->FreeMemory(p2p_memory_key, GetDeviceId()),
  3526. "failed to free p2p memory");
  3527. }
  3528. p2p_mem_base_ = nullptr;
  3529. } else {
  3530. GE_IF_BOOL_EXEC(p2p_mem_base_ != nullptr && is_inner_mem_base_,
  3531. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_P2P_DDR)->FreeMemory(p2p_mem_base_, GetDeviceId()),
  3532. "failed to free p2p memory");
  3533. p2p_mem_base_ = nullptr);
  3534. }
  3535. }
  3536. void DavinciModel::FreeWeightsMem() {
  3537. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3538. string memory_key = std::to_string(0) + "_w";
  3539. if (MemManager::Instance(RT_MEMORY_HBM)->GetMemoryAddr(memory_key) != nullptr) {
  3540. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(memory_key, GetDeviceId()),
  3541. "failed to free feature_map memory");
  3542. }
  3543. weights_mem_base_ = nullptr;
  3544. } else {
  3545. GE_IF_BOOL_EXEC(weights_mem_base_ != nullptr && weights_mem_base_ != mem_base_ && is_inner_weight_base_,
  3546. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(weights_mem_base_, GetDeviceId()),
  3547. "failed to free weight memory");
  3548. weights_mem_base_ = nullptr);
  3549. }
  3550. }
  3551. Status DavinciModel::TransAllVarData(ComputeGraphPtr &graph, uint32_t graph_id) {
  3552. GELOGI("TransAllVarData start: session_id:%lu, graph_id: %u.", session_id_, graph_id);
  3553. rtContext_t ctx = nullptr;
  3554. rtError_t rt_ret = rtCtxGetCurrent(&ctx);
  3555. if (rt_ret != RT_ERROR_NONE) {
  3556. GELOGE(RT_FAILED, "Failed to get current context, error_code is: 0x%X.", rt_ret);
  3557. return RT_ERROR_TO_GE_STATUS(rt_ret);
  3558. }
  3559. std::vector<NodePtr> variable_node_list;
  3560. for (ge::NodePtr &node : graph->GetDirectNode()) {
  3561. if (node == nullptr) {
  3562. continue;
  3563. }
  3564. if (node->GetType() != VARIABLE) {
  3565. continue;
  3566. }
  3567. variable_node_list.emplace_back(node);
  3568. }
  3569. GE_CHK_STATUS_RET_NOLOG(
  3570. TransVarDataUtils::TransAllVarData(variable_node_list, session_id_, ctx, graph_id, kThreadNum));
  3571. GELOGI("TransAllVarData success.");
  3572. return SUCCESS;
  3573. }
  3574. void DavinciModel::SetDataDumperArgs(const ComputeGraphPtr &compute_graph) {
  3575. GELOGI("set data dumper args, name: %s, id: %u.", name_.c_str(), model_id_);
  3576. data_dumper_.SetModelName(name_);
  3577. data_dumper_.SetModelId(model_id_);
  3578. data_dumper_.SetOmName(om_name_);
  3579. data_dumper_.SetComputeGraph(compute_graph);
  3580. data_dumper_.SetRefInfo(saved_task_addrs_);
  3581. data_dumper_.SetL1FusionAddr(l1_fusion_addr_);
  3582. int32_t device_id = 0;
  3583. rtError_t rt_ret = rtGetDevice(&device_id);
  3584. if (rt_ret != RT_ERROR_NONE || device_id < 0) {
  3585. GELOGE(RT_FAILED, "Call rtGetDevice failed, ret = 0x%X, device_id = %d.", rt_ret, device_id);
  3586. return;
  3587. }
  3588. data_dumper_.SetDeviceId(device_id);
  3589. // set loop count addr
  3590. auto get_var_addr = [](const OpDescPtr &op, const RuntimeParam &runtime_param) -> void * {
  3591. if (op != nullptr) {
  3592. auto v_output_size = ModelUtils::GetOutputSize(op);
  3593. auto v_output_addr = ModelUtils::GetOutputDataAddrs(runtime_param, op);
  3594. if (v_output_size.empty() || v_output_addr.empty()) {
  3595. return nullptr;
  3596. }
  3597. return v_output_addr[0];
  3598. }
  3599. GELOGW("op is null.");
  3600. return nullptr;
  3601. };
  3602. data_dumper_.SetLoopAddr(get_var_addr(GetVariableOp(NODE_NAME_GLOBAL_STEP), runtime_param_),
  3603. get_var_addr(GetVariableOp(NODE_NAME_FLOWCTRL_LOOP_PER_ITER), runtime_param_),
  3604. get_var_addr(GetVariableOp(NODE_NAME_FLOWCTRL_LOOP_COND), runtime_param_));
  3605. GELOGI("SetDataDumperArgs end.");
  3606. }
  3607. uint32_t DavinciModel::GetFlowctrlIndex(uint32_t op_index) {
  3608. std::lock_guard<std::mutex> lock(flowctrl_op_index_internal_map_mutex_);
  3609. return (++flowctrl_op_index_internal_map_[op_index]) - 1;
  3610. }
  3611. void DavinciModel::PushHcclStream(rtStream_t value) {
  3612. std::lock_guard<std::mutex> lock(all_hccl_stream_list_mutex_);
  3613. all_hccl_stream_list_.push_back(value);
  3614. }
  3615. void DavinciModel::SaveHcclFollowStream(int64_t main_stream_id, rtStream_t stream) {
  3616. std::lock_guard<std::mutex> lock(capacity_of_stream_mutex_);
  3617. main_follow_stream_mapping_[main_stream_id].emplace_back(stream);
  3618. }
  3619. Status DavinciModel::GetComputeGraphInfo(const ComputeGraphPtr &graph, vector<ComputeGraphDescInfo> &graph_desc_info) {
  3620. GELOGI("GetComputeGraphInfo start.");
  3621. for (auto &node : graph->GetAllNodes()) {
  3622. ComputeGraphDescInfo compute_graph_info;
  3623. auto op_desc = node->GetOpDesc();
  3624. if (op_desc == nullptr) {
  3625. GELOGE(PARAM_INVALID, "op_desc is nullptr.");
  3626. return PARAM_INVALID;
  3627. }
  3628. auto op_mode = static_cast<uint32_t>(domi::ImplyType::INVALID);
  3629. if (AttrUtils::GetInt(op_desc, ATTR_NAME_IMPLY_TYPE, op_mode) &&
  3630. op_mode == static_cast<uint32_t>(domi::ImplyType::TVM)) {
  3631. if (!om_name_.empty()) {
  3632. compute_graph_info.model_name = om_name_;
  3633. } else {
  3634. compute_graph_info.model_name = name_;
  3635. }
  3636. compute_graph_info.op_name = op_desc->GetName();
  3637. compute_graph_info.op_type = op_desc->GetType();
  3638. for (size_t i = 0; i < op_desc->GetAllInputsSize(); ++i) {
  3639. GeTensorDescPtr input_desc = op_desc->MutableInputDesc(i);
  3640. if (input_desc == nullptr) {
  3641. continue;
  3642. }
  3643. compute_graph_info.input_format.emplace_back(input_desc->GetFormat());
  3644. compute_graph_info.input_shape.emplace_back(input_desc->GetShape().GetDims());
  3645. compute_graph_info.input_data_type.emplace_back(input_desc->GetDataType());
  3646. }
  3647. for (size_t j = 0; j < op_desc->GetOutputsSize(); ++j) {
  3648. GeTensorDesc output_desc = op_desc->GetOutputDesc(j);
  3649. compute_graph_info.output_format.emplace_back(output_desc.GetFormat());
  3650. compute_graph_info.output_shape.emplace_back(output_desc.GetShape().GetDims());
  3651. compute_graph_info.output_data_type.emplace_back(output_desc.GetDataType());
  3652. }
  3653. graph_desc_info.emplace_back(compute_graph_info);
  3654. }
  3655. }
  3656. GELOGI("GetComputeGraphInfo end.");
  3657. return SUCCESS;
  3658. }
  3659. void DavinciModel::SetTotalFixedAddrsSize(string tensor_name, int64_t fix_addr_size) {
  3660. if (tensor_name_to_fixed_addr_size_.find(tensor_name) == tensor_name_to_fixed_addr_size_.end()) {
  3661. tensor_name_to_fixed_addr_size_[tensor_name] = total_fixed_addr_size_;
  3662. total_fixed_addr_size_ += fix_addr_size;
  3663. }
  3664. }
  3665. Status DavinciModel::GetOrigInputInfo(uint32_t index, OriginInputInfo &orig_input_info) {
  3666. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  3667. OpDescPtr data_op = data_op_list_[index];
  3668. if (!data_op->HasAttr(ATTR_NAME_AIPP_INPUTS) || !data_op->HasAttr(ATTR_NAME_AIPP_OUTPUTS)) {
  3669. GELOGE(GE_AIPP_NOT_EXIST, "GetOrigInputInfo: there is not AIPP related with index %u.", index);
  3670. return GE_AIPP_NOT_EXIST;
  3671. }
  3672. vector<std::string> inputs;
  3673. if (AttrUtils::GetListStr(data_op, ATTR_NAME_AIPP_INPUTS, inputs) && !inputs.empty()) {
  3674. std::string input = inputs[kAippOriginInputIndex];
  3675. GELOGI("GetOrigInputInfo: origin input str: %s", input.c_str());
  3676. std::vector<std::string> infos = ge::StringUtils::Split(input, ':');
  3677. if (infos.size() != kAippInfoNum) {
  3678. GELOGW("origin input str is invalid.");
  3679. }
  3680. orig_input_info.format = TypeUtils::SerialStringToFormat(infos[kAippInfoFormat]);
  3681. orig_input_info.data_type = TypeUtils::SerialStringToDataType(infos[kAippInfoDataType]);
  3682. orig_input_info.dim_num = std::strtol(infos[kAippInfoDimNum].c_str(), nullptr, kDecimal);
  3683. }
  3684. return SUCCESS;
  3685. }
  3686. void DavinciModel::ParseAIPPInfo(std::string in_out_info, InputOutputDims &dims_info) {
  3687. GELOGI("ParseAIPPInfo: origin str: %s", in_out_info.c_str());
  3688. std::vector<std::string> infos = ge::StringUtils::Split(in_out_info, ':');
  3689. if (infos.size() != kAippInfoNum) {
  3690. GELOGW("origin input str is invalid.");
  3691. }
  3692. dims_info.name = infos[kAippInfoTensorName];
  3693. dims_info.size = std::strtol(infos[kAippInfoTensorSize].c_str(), nullptr, kDecimal);
  3694. dims_info.dim_num = std::strtol(infos[kAippInfoDimNum].c_str(), nullptr, kDecimal);
  3695. std::vector<std::string> dims = ge::StringUtils::Split(infos[kAippInfoShape], ',');
  3696. for (const auto &dim : dims) {
  3697. if (dim.empty()) {
  3698. continue;
  3699. }
  3700. dims_info.dims.emplace_back(std::strtol(dim.c_str(), nullptr, kDecimal));
  3701. }
  3702. }
  3703. Status DavinciModel::GetAllAippInputOutputDims(uint32_t index, std::vector<InputOutputDims> &input_dims,
  3704. std::vector<InputOutputDims> &output_dims) {
  3705. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  3706. OpDescPtr data_op = data_op_list_[index];
  3707. if (!data_op->HasAttr(ATTR_NAME_AIPP_INPUTS) || !data_op->HasAttr(ATTR_NAME_AIPP_OUTPUTS)) {
  3708. GELOGE(GE_AIPP_NOT_EXIST, "GetAllAippInputOutputDims: there is not AIPP related with index %u.", index);
  3709. return GE_AIPP_NOT_EXIST;
  3710. }
  3711. vector<std::string> inputs;
  3712. if (AttrUtils::GetListStr(data_op, ATTR_NAME_AIPP_INPUTS, inputs) && !inputs.empty()) {
  3713. GELOGI("GetAllAippInputOutputDims: Data: %s has %u related aippInfo.", data_op->GetName().c_str(), inputs.size());
  3714. for (auto it : inputs) {
  3715. InputOutputDims input_info;
  3716. ParseAIPPInfo(it, input_info);
  3717. input_dims.emplace_back(input_info);
  3718. GELOGD("GetAllAippInputOutputDims Aipp origin input dims info: %s", it.c_str());
  3719. ConstGeTensorDescPtr data_input_desc = data_op->GetInputDescPtr(kDataIndex);
  3720. int64_t data_input_size;
  3721. (void)TensorUtils::GetSize(*(data_op->GetInputDescPtr(kDataIndex)), data_input_size);
  3722. GELOGD(
  3723. "GetAllAippInputOutputDims related Data[%d]: tensor_name is %s, dim_num is %u, tensor_size: %zu, format: "
  3724. "%s, data_type: %s, shape: %s .",
  3725. index, data_op->GetName().c_str(), data_input_desc->GetShape().GetDimNum(), data_input_size,
  3726. TypeUtils::FormatToSerialString(data_input_desc->GetFormat()).c_str(),
  3727. TypeUtils::DataTypeToSerialString(data_input_desc->GetDataType()).c_str(),
  3728. formats::JoinToString(data_input_desc->GetShape().GetDims()).c_str());
  3729. }
  3730. }
  3731. vector<std::string> outputs;
  3732. if (AttrUtils::GetListStr(data_op, ATTR_NAME_AIPP_OUTPUTS, outputs) && !outputs.empty()) {
  3733. for (auto it : outputs) {
  3734. InputOutputDims output_info;
  3735. ParseAIPPInfo(it, output_info);
  3736. output_dims.emplace_back(output_info);
  3737. GELOGD("GetAllAippInputOutputDims Aipp output dims info: %s", it.c_str());
  3738. }
  3739. }
  3740. return SUCCESS;
  3741. }
  3742. int64_t DavinciModel::GetFixedAddrsSize(string tensor_name) {
  3743. if (tensor_name_to_fixed_addr_size_.find(tensor_name) != tensor_name_to_fixed_addr_size_.end()) {
  3744. return tensor_name_to_fixed_addr_size_[tensor_name];
  3745. } else {
  3746. return total_fixed_addr_size_;
  3747. }
  3748. }
  3749. } // namespace ge

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