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

davinci_model.cc 204 kB

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

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