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

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