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 207 kB

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

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