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

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