You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

davinci_model.cc 207 kB

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

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