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

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