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

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