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

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