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

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