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

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