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

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