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

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