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
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
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 %p.", 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,
  1183. std::vector<vector<int64_t>> &vec_info) {
  1184. for (size_t i = 0; i < str_info.size(); ++i) {
  1185. std::vector<int64_t> shape;
  1186. std::vector<std::string> dims = ge::StringUtils::Split(str_info[i], ',');
  1187. for (const auto &dim : dims) {
  1188. if (dim.empty()) {
  1189. continue;
  1190. }
  1191. shape.emplace_back(std::strtol(dim.c_str(), nullptr, kDecimal));
  1192. }
  1193. GELOGI("Shape from attr is %s.", formats::JoinToString(shape).c_str());
  1194. vec_info.emplace_back(shape);
  1195. }
  1196. }
  1197. ///
  1198. /// @ingroup ge
  1199. /// @brief output zero copy node Initialize.
  1200. /// @param [in] NodePtr: netoutput Op.
  1201. /// @return Status
  1202. ///
  1203. Status DavinciModel::InitOutputZeroCopyNodes(const NodePtr &node) {
  1204. set<NodePtr> nodes_need_record;
  1205. for (auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1206. auto peer_out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  1207. if (peer_out_data_anchor == nullptr) {
  1208. continue;
  1209. }
  1210. auto peer_node = peer_out_data_anchor->GetOwnerNode();
  1211. nodes_need_record.emplace(peer_node);
  1212. // Merge node output multiplexed input, upstream nodes need to be considered in multiple batch scenarios
  1213. if (peer_node->GetType() == MERGE) {
  1214. for (const auto &merge_peer_in_data_anchor : peer_node->GetAllInDataAnchors()) {
  1215. auto merge_peer_out_data_anchor = merge_peer_in_data_anchor->GetPeerOutAnchor();
  1216. if (merge_peer_out_data_anchor == nullptr) {
  1217. continue;
  1218. }
  1219. auto merge_peer_node = merge_peer_out_data_anchor->GetOwnerNode();
  1220. nodes_need_record.emplace(merge_peer_node);
  1221. }
  1222. } else {
  1223. for (const auto &other_in_data_anchor : peer_out_data_anchor->GetPeerInDataAnchors()) {
  1224. auto other_in_node = other_in_data_anchor->GetOwnerNode();
  1225. if (other_in_node->GetType() != NETOUTPUT) {
  1226. nodes_need_record.emplace(other_in_node);
  1227. }
  1228. }
  1229. }
  1230. }
  1231. for (const auto &node_need_record : nodes_need_record) {
  1232. auto op_desc = node_need_record->GetOpDesc();
  1233. GE_CHECK_NOTNULL(op_desc);
  1234. string batch_label;
  1235. (void)ge::AttrUtils::GetStr(op_desc, ATTR_NAME_BATCH_LABEL, batch_label);
  1236. if (batch_label.empty()) {
  1237. batch_label = kDefaultBatchLable;
  1238. }
  1239. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  1240. zero_copy_op_id_batch_label_.emplace(pair<int64_t, string>(op_desc->GetId(), batch_label));
  1241. GELOGD("Init Output zero copy nodes success, op name:%s, op id: %ld, batch label: %s.",
  1242. op_desc->GetName().c_str(), op_desc->GetId(), batch_label.c_str());
  1243. }
  1244. }
  1245. return SUCCESS;
  1246. }
  1247. ///
  1248. /// @ingroup ge
  1249. /// @brief input zero copy node Initialize.
  1250. /// @param [in] NodePtr: Data Op.
  1251. /// @return Status
  1252. ///
  1253. Status DavinciModel::InitInputBatchLabel(const NodePtr &node) {
  1254. string batch_label;
  1255. if (!AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_BATCH_LABEL, batch_label)) {
  1256. return SUCCESS; // Not Multi-batch.
  1257. }
  1258. const auto &out_data_anchor = node->GetOutDataAnchor(kDataIndex);
  1259. GE_CHECK_NOTNULL(out_data_anchor);
  1260. for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  1261. const auto &node = peer_in_data_anchor->GetOwnerNode();
  1262. const auto &op_desc = node->GetOpDesc();
  1263. GE_CHECK_NOTNULL(op_desc);
  1264. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  1265. zero_copy_op_id_batch_label_[op_desc->GetId()] = batch_label;
  1266. GELOGD("Init input zero copy nodes success, op name: %s, op id: %ld, batch label: %s", op_desc->GetName().c_str(),
  1267. op_desc->GetId(), batch_label.c_str());
  1268. }
  1269. }
  1270. return SUCCESS;
  1271. }
  1272. ///
  1273. /// @ingroup ge
  1274. /// @brief output zero copy node Initialize for Case.
  1275. /// @param [in] NodePtr: netoutput Op.
  1276. /// @return Status
  1277. ///
  1278. Status DavinciModel::InitOutputBatchLabel(const NodePtr &node) {
  1279. string batch_label;
  1280. if (!AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_BATCH_LABEL, batch_label)) {
  1281. return SUCCESS; // Not Multi-batch.
  1282. }
  1283. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  1284. const auto &peer_out_data_anchor = in_data_anchor->GetPeerOutAnchor();
  1285. if (peer_out_data_anchor == nullptr) {
  1286. continue;
  1287. }
  1288. const auto &peer_node = peer_out_data_anchor->GetOwnerNode();
  1289. const auto &op_desc = peer_node->GetOpDesc();
  1290. GE_CHECK_NOTNULL(op_desc);
  1291. if (zero_copy_op_id_batch_label_.find(op_desc->GetId()) == zero_copy_op_id_batch_label_.end()) {
  1292. zero_copy_op_id_batch_label_[op_desc->GetId()] = batch_label;
  1293. GELOGD("Init Output zero copy nodes success, op name: %s, op id: %ld, batch label: %s",
  1294. op_desc->GetName().c_str(), op_desc->GetId(), batch_label.c_str());
  1295. }
  1296. }
  1297. return SUCCESS;
  1298. }
  1299. /// @ingroup ge
  1300. /// @brief LabelSet Op Initialize.
  1301. /// @param [in] op_desc: LabelSet Op descriptor.
  1302. /// @return Status
  1303. Status DavinciModel::InitLabelSet(const OpDescPtr &op_desc) {
  1304. uint32_t label_index = 0;
  1305. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_LABEL_SWITCH_INDEX, label_index)) {
  1306. GELOGE(INTERNAL_ERROR, "InitLabelSet: %s attr [%s] not exist.", op_desc->GetName().c_str(),
  1307. ATTR_NAME_LABEL_SWITCH_INDEX.c_str());
  1308. return INTERNAL_ERROR;
  1309. }
  1310. if (label_index >= LabelNum()) {
  1311. GELOGE(INTERNAL_ERROR, "InitLabelSet: label index: %u >= label size: %zu.", label_index, LabelNum());
  1312. return INTERNAL_ERROR;
  1313. }
  1314. if (label_id_indication_.count(label_index) > 0) {
  1315. GELOGE(INTERNAL_ERROR, "InitLabelSet: %s label index: %u already used.", op_desc->GetName().c_str(), label_index);
  1316. return INTERNAL_ERROR;
  1317. }
  1318. rtStream_t stream = nullptr;
  1319. uint32_t stream_id = static_cast<uint32_t>(op_desc->GetStreamId());
  1320. if (stream_list_.size() == 1) {
  1321. stream = stream_list_[0];
  1322. } else if (stream_list_.size() > stream_id) {
  1323. stream = stream_list_[stream_id];
  1324. } else {
  1325. GELOGE(INTERNAL_ERROR, "InitLabelSet: stream index: %u >= stream size: %zu.", stream_id, stream_list_.size());
  1326. return INTERNAL_ERROR;
  1327. }
  1328. rtLabel_t rt_label = nullptr;
  1329. rtError_t rt_error = rtLabelCreateEx(&rt_label, stream);
  1330. if (rt_error != RT_ERROR_NONE || rt_label == nullptr) {
  1331. GELOGE(INTERNAL_ERROR, "InitLabelSet: %s create label failed, error=0x%x.", op_desc->GetName().c_str(), rt_error);
  1332. return INTERNAL_ERROR;
  1333. }
  1334. GELOGI("InitLabelSet: label[%u]=%p stream[%u]=%p.", label_index, rt_label, stream_id, stream);
  1335. label_id_indication_.insert(label_index);
  1336. label_list_[label_index] = rt_label;
  1337. return SUCCESS;
  1338. }
  1339. Status DavinciModel::InitVariable(const OpDescPtr &op_desc) {
  1340. variable_op_list_.push_back(op_desc);
  1341. return SUCCESS;
  1342. }
  1343. /// @ingroup ge
  1344. /// @brief ACL case, Load task list with queue.
  1345. /// @param [in] input_queue_ids: input queue ids from user, nums equal Data Op.
  1346. /// @param [in] output_queue_ids: input queue ids from user, nums equal NetOutput Op.
  1347. /// @return: 0 for success / others for failed
  1348. Status DavinciModel::SetQueIds(const std::vector<uint32_t> &input_queue_ids,
  1349. const std::vector<uint32_t> &output_queue_ids) {
  1350. if (input_queue_ids.empty() && output_queue_ids.empty()) {
  1351. GELOGE(GE_EXEC_MODEL_QUEUE_ID_INVALID, "Param is empty");
  1352. return GE_EXEC_MODEL_QUEUE_ID_INVALID;
  1353. }
  1354. input_queue_ids_ = input_queue_ids;
  1355. output_queue_ids_ = output_queue_ids;
  1356. return SUCCESS;
  1357. }
  1358. ///
  1359. /// @ingroup ge
  1360. /// @brief ACL case, Load task list with queue.
  1361. /// @param [in] input_que_ids: input queue ids from user, nums equal Data Op.
  1362. /// @param [in] output_que_ids: input queue ids from user, nums equal NetOutput Op.
  1363. /// @return: 0 for success / others for failed
  1364. ///
  1365. Status DavinciModel::LoadWithQueue() {
  1366. if (input_queue_ids_.empty() && output_queue_ids_.empty()) {
  1367. return SUCCESS;
  1368. }
  1369. if (input_queue_ids_.size() != new_input_data_info_.size()) {
  1370. GELOGE(GE_EXEC_MODEL_QUEUE_ID_INVALID, "Input queue ids not match model: input_queue=%zu input_data=%zu",
  1371. input_queue_ids_.size(), new_input_data_info_.size());
  1372. return GE_EXEC_MODEL_QUEUE_ID_INVALID;
  1373. }
  1374. if (output_queue_ids_.size() != new_output_data_info_.size()) {
  1375. GELOGE(GE_EXEC_MODEL_QUEUE_ID_INVALID, "Output queue ids not match model: output_queue=%zu output_data=%zu",
  1376. output_queue_ids_.size(), new_output_data_info_.size());
  1377. return GE_EXEC_MODEL_QUEUE_ID_INVALID;
  1378. }
  1379. GE_CHK_STATUS_RET(AddHeadStream(), "Add head stream failed.");
  1380. // Binding input_queue and Data Op.
  1381. GE_CHK_STATUS_RET(BindInputQueue(), "Launch bind input queue failed.");
  1382. GE_CHK_STATUS_RET(CpuTaskModelZeroCopy(input_mbuf_list_, new_input_outside_addrs_), "Launch zero copy failed.");
  1383. // Binding output_queue and NetOutput Op.
  1384. GE_CHK_STATUS_RET(BindOutputQueue(), "Launch bind output queue failed.");
  1385. GE_CHK_STATUS_RET(CpuTaskModelZeroCopy(output_mbuf_list_, new_output_outside_addrs_), "Launch zero copy failed.");
  1386. GE_CHK_STATUS_RET(CpuActiveStream(), "Launch active entry stream failed.");
  1387. GE_CHK_STATUS_RET(CpuWaitEndGraph(), "Launch wait end graph failed.");
  1388. GE_CHK_STATUS_RET(BindEnqueue(), "Launch enqueue failed.");
  1389. GE_CHK_STATUS_RET(CpuModelRepeat(), "Launch model repeat failed.");
  1390. return SUCCESS;
  1391. }
  1392. /// @ingroup ge
  1393. /// @brief queue schedule, Bind input queue to Data output address.
  1394. /// @return: 0 for success / others for failed
  1395. Status DavinciModel::BindInputQueue() {
  1396. // Caller checked: input_queue_ids_.size() == input_size_list_.size() != input_addr_list_.size()
  1397. for (size_t i = 0; i < input_queue_ids_.size(); ++i) {
  1398. auto it = new_input_data_info_.find(i);
  1399. if (it == new_input_data_info_.end()) {
  1400. GELOGE(FAILED, "Input not match: tensor num=%zu, Queue id index=%zu", new_input_data_info_.size(), i);
  1401. return FAILED;
  1402. }
  1403. uint32_t queue_id = input_queue_ids_[i];
  1404. if (it->second.GetDataInfo().empty()) {
  1405. GELOGE(INTERNAL_ERROR, "the %zu input_queue not set data_info.", i);
  1406. return INTERNAL_ERROR;
  1407. }
  1408. uint32_t data_size = static_cast<uint32_t>(it->second.GetDataInfo().at(0).first);
  1409. uintptr_t data_addr = reinterpret_cast<uintptr_t>(it->second.GetDataInfo().at(0).second);
  1410. GELOGI("BindInputToQueue: graph_%u index[%zu] queue id[%u] output addr[0x%lx] output size[%u]",
  1411. runtime_param_.graph_id, i, queue_id, data_addr, data_size);
  1412. rtError_t rt_ret = rtModelBindQueue(rt_model_handle_, queue_id, RT_MODEL_INPUT_QUEUE);
  1413. if (rt_ret != RT_ERROR_NONE) {
  1414. GELOGE(RT_FAILED, "Call rtModelBindQueue failed, ret: 0x%X", rt_ret);
  1415. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1416. }
  1417. if (CpuModelDequeue(queue_id) != SUCCESS) {
  1418. return INTERNAL_ERROR;
  1419. }
  1420. }
  1421. return SUCCESS;
  1422. }
  1423. /// @ingroup ge
  1424. /// @brief definiteness queue schedule, bind input queue to task.
  1425. /// @param [in] queue_id: input queue id from user.
  1426. /// @return: 0 for success / others for failed
  1427. Status DavinciModel::CpuModelDequeue(uint32_t queue_id) {
  1428. GELOGI("Set CpuKernel model dequeue task enter.");
  1429. std::shared_ptr<CpuTaskModelDequeue> dequeue_task = MakeShared<CpuTaskModelDequeue>(rt_entry_stream_);
  1430. if (dequeue_task == nullptr) {
  1431. GELOGE(MEMALLOC_FAILED, "Make CpuTaskModelDequeue task failed.");
  1432. return MEMALLOC_FAILED;
  1433. }
  1434. // Get DataOp Output address and bind to queue.
  1435. uintptr_t in_mbuf = 0;
  1436. Status status = dequeue_task->Init(queue_id, in_mbuf);
  1437. if (status != SUCCESS) {
  1438. return status;
  1439. }
  1440. cpu_task_list_.push_back(dequeue_task);
  1441. input_mbuf_list_.push_back(in_mbuf);
  1442. GELOGI("Set CpuKernel model dequeue task success.");
  1443. return SUCCESS;
  1444. }
  1445. Status DavinciModel::CpuTaskModelZeroCopy(std::vector<uintptr_t> &mbuf_list,
  1446. std::map<const void *, ZeroCopyOffset> &outside_addrs) {
  1447. GELOGI("Set CpuKernel model zero_copy task enter.");
  1448. std::shared_ptr<CpuTaskZeroCopy> zero_copy = MakeShared<CpuTaskZeroCopy>(rt_entry_stream_);
  1449. if (zero_copy == nullptr) {
  1450. GELOGE(MEMALLOC_FAILED, "Make CpuTaskZeroCopy task failed.");
  1451. return MEMALLOC_FAILED;
  1452. }
  1453. // mdc zero_copy not support l2 fusion
  1454. Status status = zero_copy->Init(mbuf_list, outside_addrs);
  1455. if (status != SUCCESS) {
  1456. return status;
  1457. }
  1458. cpu_task_list_.push_back(zero_copy);
  1459. GELOGI("Set CpuKernel model zero_copy task success.");
  1460. return SUCCESS;
  1461. }
  1462. /// @ingroup ge
  1463. /// @brief queue schedule, bind output queue to NetOutput input address.
  1464. /// @return: 0 for success / others for failed
  1465. Status DavinciModel::BindOutputQueue() {
  1466. // Caller checked: input_queue_ids_.size() == input_size_list_.size() != input_addr_list_.size()
  1467. for (size_t i = 0; i < output_queue_ids_.size(); ++i) {
  1468. auto it = new_output_data_info_.find(i);
  1469. if (it == new_output_data_info_.end()) {
  1470. GELOGE(FAILED, "Output not match: tensor num=%zu, Queue id index=%zu", new_output_data_info_.size(), i);
  1471. return FAILED;
  1472. }
  1473. uint32_t queue_id = output_queue_ids_[i];
  1474. if (it->second.GetDataInfo().empty()) {
  1475. GELOGE(INTERNAL_ERROR, "the %zu output_queue not set data_info.", i);
  1476. return INTERNAL_ERROR;
  1477. }
  1478. uint32_t data_size = static_cast<uint32_t>(it->second.GetDataInfo().at(0).first);
  1479. uintptr_t data_addr = reinterpret_cast<uintptr_t>(it->second.GetDataInfo().at(0).second);
  1480. GELOGI("BindOutputToQueue: graph_%u index[%zu] queue id[%u] input addr[0x%lx] input size[%u]",
  1481. runtime_param_.graph_id, i, queue_id, data_addr, data_size);
  1482. rtError_t rt_ret = rtModelBindQueue(rt_model_handle_, queue_id, RT_MODEL_OUTPUT_QUEUE);
  1483. if (rt_ret != RT_ERROR_NONE) {
  1484. GELOGE(RT_FAILED, "Call rtModelBindQueue failed, ret: 0x%X", rt_ret);
  1485. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1486. }
  1487. Status status = CpuModelPrepareOutput(data_addr, data_size);
  1488. if (status != SUCCESS) {
  1489. return status;
  1490. }
  1491. }
  1492. return SUCCESS;
  1493. }
  1494. /// @ingroup ge
  1495. /// @brief definiteness queue schedule, bind output queue to task.
  1496. /// @param [in] addr: NetOutput Op input tensor address.
  1497. /// @param [in] size: NetOutput Op input tensor size.
  1498. /// @return: 0 for success / others for failed
  1499. Status DavinciModel::CpuModelPrepareOutput(uintptr_t addr, uint32_t size) {
  1500. GELOGI("Set CpuKernel model enqueue task enter.");
  1501. if (input_mbuf_list_.empty()) {
  1502. GELOGE(FAILED, "Need input mbuf for fill output mbuf head info.");
  1503. return FAILED;
  1504. }
  1505. std::shared_ptr<CpuTaskPrepareOutput> prepare_output = MakeShared<CpuTaskPrepareOutput>(rt_entry_stream_);
  1506. if (prepare_output == nullptr) {
  1507. GELOGE(MEMALLOC_FAILED, "Make CpuTaskPrepareOutput task failed.");
  1508. return MEMALLOC_FAILED;
  1509. }
  1510. uintptr_t out_mbuf = 0;
  1511. if (prepare_output->Init(addr, size, input_mbuf_list_.back(), out_mbuf) != SUCCESS) {
  1512. return FAILED;
  1513. }
  1514. cpu_task_list_.push_back(prepare_output);
  1515. output_mbuf_list_.push_back(out_mbuf);
  1516. GELOGI("Set CpuKernel model enqueue task success.");
  1517. return SUCCESS;
  1518. }
  1519. ///
  1520. /// @ingroup ge
  1521. /// @brief definiteness queue schedule, active original model stream.
  1522. /// @return: 0 for success / others for failed
  1523. ///
  1524. Status DavinciModel::CpuActiveStream() {
  1525. GELOGI("Set CpuKernel active stream task enter.");
  1526. std::shared_ptr<CpuTaskActiveEntry> active_entry = MakeShared<CpuTaskActiveEntry>(rt_entry_stream_);
  1527. if (active_entry == nullptr) {
  1528. GELOGE(MEMALLOC_FAILED, "Make CpuTaskActiveEntry task failed.");
  1529. return MEMALLOC_FAILED;
  1530. }
  1531. Status status = active_entry->Init(rt_head_stream_);
  1532. if (status != SUCCESS) {
  1533. return status;
  1534. }
  1535. cpu_task_list_.push_back(active_entry);
  1536. GELOGI("Set CpuKernel active stream task success.");
  1537. return SUCCESS;
  1538. }
  1539. /// @ingroup ge
  1540. /// @brief definiteness queue schedule, wait for end graph.
  1541. /// @return: 0 for success / others for failed
  1542. Status DavinciModel::CpuWaitEndGraph() {
  1543. GELOGI("Set CpuKernel wait end graph task enter.");
  1544. std::shared_ptr<CpuTaskWaitEndGraph> wait_endgraph = MakeShared<CpuTaskWaitEndGraph>(rt_entry_stream_);
  1545. if (wait_endgraph == nullptr) {
  1546. GELOGE(MEMALLOC_FAILED, "Make CpuTaskWaitEndGraph task failed.");
  1547. return MEMALLOC_FAILED;
  1548. }
  1549. Status status = wait_endgraph->Init(runtime_model_id_);
  1550. if (status != SUCCESS) {
  1551. return status;
  1552. }
  1553. cpu_task_list_.push_back(wait_endgraph);
  1554. GELOGI("Set CpuKernel wait end graph task success.");
  1555. return SUCCESS;
  1556. }
  1557. Status DavinciModel::BindEnqueue() {
  1558. for (size_t i = 0; i < output_queue_ids_.size(); ++i) {
  1559. auto it = new_output_data_info_.find(i);
  1560. if (it == new_output_data_info_.end()) {
  1561. GELOGE(FAILED, "Output not match: tensor num=%zu, Queue id index=%zu", new_output_data_info_.size(), i);
  1562. return FAILED;
  1563. }
  1564. uint32_t queue_id = output_queue_ids_[i];
  1565. if (CpuModelEnqueue(queue_id, output_mbuf_list_[i]) != SUCCESS) {
  1566. return INTERNAL_ERROR;
  1567. }
  1568. }
  1569. return SUCCESS;
  1570. }
  1571. Status DavinciModel::CpuModelEnqueue(uint32_t queue_id, uintptr_t out_mbuf) {
  1572. GELOGI("Set CpuKernel model enqueue task enter.");
  1573. std::shared_ptr<CpuTaskModelEnqueue> model_enqueue = MakeShared<CpuTaskModelEnqueue>(rt_entry_stream_);
  1574. if (model_enqueue == nullptr) {
  1575. GELOGE(MEMALLOC_FAILED, "Make CpuTaskModelEnqueue task failed.");
  1576. return MEMALLOC_FAILED;
  1577. }
  1578. Status status = model_enqueue->Init(queue_id, out_mbuf);
  1579. if (status != SUCCESS) {
  1580. return status;
  1581. }
  1582. cpu_task_list_.push_back(model_enqueue);
  1583. GELOGI("Set CpuKernel model enqueue task enter.");
  1584. return SUCCESS;
  1585. }
  1586. /// @ingroup ge
  1587. /// @brief definiteness queue schedule, repeat run model.
  1588. /// @return: 0 for success / others for failed
  1589. Status DavinciModel::CpuModelRepeat() {
  1590. GELOGI("Set CpuKernel repeat task enter.");
  1591. std::shared_ptr<CpuTaskModelRepeat> model_repeat = MakeShared<CpuTaskModelRepeat>(rt_entry_stream_);
  1592. if (model_repeat == nullptr) {
  1593. GELOGE(MEMALLOC_FAILED, "Make CpuTaskModelRepeat task failed.");
  1594. return MEMALLOC_FAILED;
  1595. }
  1596. Status status = model_repeat->Init(runtime_model_id_);
  1597. if (status != SUCCESS) {
  1598. return status;
  1599. }
  1600. cpu_task_list_.push_back(model_repeat);
  1601. GELOGI("Set CpuKernel repeat task success.");
  1602. return SUCCESS;
  1603. }
  1604. Status DavinciModel::GetInputOutputDescInfo(vector<InputOutputDescInfo> &input_desc,
  1605. vector<InputOutputDescInfo> &output_desc) {
  1606. if ((data_op_list_.empty()) || (data_op_list_[0]->GetInputsSize()) != 1) {
  1607. GELOGI("data_op_list_ is empty or input_desc size is not 1.");
  1608. } else {
  1609. std::vector<uint32_t> input_formats;
  1610. GE_CHK_STATUS_RET(GetInputDescInfo(input_desc, input_formats), "get input desc info failed.");
  1611. }
  1612. std::vector<uint32_t> outputFormats;
  1613. GE_CHK_STATUS_RET(GetOutputDescInfo(output_desc, outputFormats), "get output desc info failed.");
  1614. return SUCCESS;
  1615. }
  1616. Status DavinciModel::GetInputOutputDescInfo(vector<InputOutputDescInfo> &input_desc,
  1617. vector<InputOutputDescInfo> &output_desc,
  1618. std::vector<uint32_t> &input_formats,
  1619. std::vector<uint32_t> &outputFormats) {
  1620. if ((data_op_list_.empty()) || (data_op_list_[0]->GetInputsSize()) != 1) {
  1621. GELOGE(FAILED, "OP List Pointer is null or input_desc size is not 1!");
  1622. return FAILED;
  1623. }
  1624. GE_CHK_STATUS_RET(GetInputDescInfo(input_desc, input_formats), "get input desc info failed");
  1625. GE_CHK_STATUS_RET(GetOutputDescInfo(output_desc, outputFormats), "get ouput desc info failed");
  1626. return SUCCESS;
  1627. }
  1628. ///
  1629. /// @ingroup ge
  1630. /// @brief Get dynamic batch_info
  1631. /// @param [out] batch_info
  1632. /// @param [out] dynamic_type
  1633. /// @return execute result
  1634. ///
  1635. Status DavinciModel::GetDynamicBatchInfo(std::vector<std::vector<int64_t>> &batch_info, int32_t &dynamic_type) const {
  1636. dynamic_type = dynamic_type_;
  1637. batch_info = batch_info_;
  1638. return SUCCESS;
  1639. }
  1640. ///
  1641. /// @ingroup ge
  1642. /// @brief Get combined dynamic dims info
  1643. /// @param [out] batch_info
  1644. /// @return None
  1645. ///
  1646. void DavinciModel::GetCombinedDynamicDims(std::vector<std::vector<int64_t>> &batch_info) const {
  1647. batch_info.clear();
  1648. batch_info = combined_batch_info_;
  1649. }
  1650. ///
  1651. /// @ingroup ge
  1652. /// @brief Get user designate shape order
  1653. /// @param [out] user_input_shape_order
  1654. /// @return None
  1655. ///
  1656. void DavinciModel::GetUserDesignateShapeOrder(std::vector<std::string> &user_input_shape_order) const {
  1657. user_input_shape_order.clear();
  1658. user_input_shape_order = user_designate_shape_order_;
  1659. }
  1660. ///
  1661. /// @ingroup ge
  1662. /// @brief Get AIPP input info
  1663. /// @param [in] index
  1664. /// @param [out] aipp_info
  1665. /// @return execute result
  1666. ///
  1667. Status DavinciModel::GetAIPPInfo(uint32_t index, AippConfigInfo &aipp_info) {
  1668. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  1669. OpDescPtr data_op = data_op_list_[index];
  1670. if (!data_op->HasAttr(ATTR_NAME_AIPP)) {
  1671. GELOGW("GetAIPPInfo: there is not AIPP related with index %u.", index);
  1672. return GE_AIPP_NOT_EXIST;
  1673. }
  1674. std::unique_ptr<domi::AippOpParams> aipp_params(new (std::nothrow) domi::AippOpParams());
  1675. GE_CHECK_NOTNULL(aipp_params);
  1676. ge::GeAttrValue::NAMED_ATTRS aipp_attr;
  1677. GE_CHK_BOOL_RET_STATUS(AttrUtils::GetNamedAttrs(data_op, ATTR_NAME_AIPP, aipp_attr), GE_AIPP_NOT_EXIST,
  1678. "Data node do not contain param aipp!");
  1679. GE_CHK_STATUS_RET(OpUtils::ConvertAippParams(aipp_attr, aipp_params.get()), "get aipp params failed");
  1680. GELOGI("GetAIPPInfo: node data: %s, type: %s, current index: %u, current node related input rank: %u",
  1681. data_op->GetName().c_str(), data_op->GetType().c_str(), index, aipp_params->related_input_rank());
  1682. GE_CHK_STATUS_RET(AippUtils::ConvertAippParams2AippInfo(aipp_params.get(), aipp_info),
  1683. "convert aipp params to aipp config info failed");
  1684. return SUCCESS;
  1685. }
  1686. Status DavinciModel::GetAippType(uint32_t index, InputAippType &type, size_t &aipp_index) {
  1687. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  1688. // Set default value
  1689. type = DATA_WITHOUT_AIPP;
  1690. aipp_index = 0xFFFFFFFF; // default invalid value
  1691. OpDescPtr data_op = data_op_list_[index];
  1692. GE_CHECK_NOTNULL(data_op);
  1693. if (!data_op->HasAttr(ATTR_DATA_RELATED_AIPP_MODE)) {
  1694. GELOGW("There is no aipp releated info with index %u.", index);
  1695. return SUCCESS;
  1696. }
  1697. std::string data_mode;
  1698. (void)AttrUtils::GetStr(data_op, ATTR_DATA_RELATED_AIPP_MODE, data_mode);
  1699. if (data_mode == "static_aipp") {
  1700. type = DATA_WITH_STATIC_AIPP;
  1701. } else if (data_mode == "dynamic_aipp") {
  1702. type = DATA_WITH_DYNAMIC_AIPP;
  1703. } else if (data_mode == "dynamic_aipp_conf") {
  1704. type = DYNAMIC_AIPP_NODE;
  1705. } else {
  1706. GELOGE(INTERNAL_ERROR, "The info of aipp releated info %s is invalid with index %u.", data_mode.c_str(), index);
  1707. return INTERNAL_ERROR;
  1708. }
  1709. if (type == DATA_WITH_DYNAMIC_AIPP) {
  1710. string releated_name;
  1711. (void)AttrUtils::GetStr(data_op, ATTR_DATA_AIPP_DATA_NAME_MAP, releated_name);
  1712. for (size_t i = 0; i < data_op_list_.size(); ++i) {
  1713. GE_CHECK_NOTNULL(data_op_list_[i]);
  1714. if (data_op_list_[i]->GetName() == releated_name) {
  1715. GELOGI("Find aipp_data [%s] index %zu from index %u", releated_name.c_str(), i, index);
  1716. aipp_index = i;
  1717. }
  1718. }
  1719. if (aipp_index == 0xFFFFFFFF) {
  1720. GELOGE(INTERNAL_ERROR, "Can not find aipp data node from index %u", index);
  1721. return INTERNAL_ERROR;
  1722. }
  1723. }
  1724. return SUCCESS;
  1725. }
  1726. void DavinciModel::SetDynamicSize(const std::vector<uint64_t> &batch_num, int32_t dynamic_type) {
  1727. batch_size_.clear();
  1728. if (batch_num.empty()) {
  1729. GELOGD("User has not set dynammic data");
  1730. }
  1731. for (size_t i = 0; i < batch_num.size(); i++) {
  1732. batch_size_.emplace_back(batch_num[i]);
  1733. }
  1734. dynamic_type_ = dynamic_type;
  1735. }
  1736. void DavinciModel::GetCurShape(std::vector<int64_t> &batch_info, int32_t &dynamic_type) {
  1737. if (batch_size_.empty()) {
  1738. GELOGD("User does not set dynamic size");
  1739. }
  1740. for (size_t i = 0; i < batch_size_.size(); i++) {
  1741. GELOGI("Start to get current shape");
  1742. batch_info.emplace_back(batch_size_[i]);
  1743. }
  1744. dynamic_type = dynamic_type_;
  1745. }
  1746. void DavinciModel::GetModelAttr(std::vector<std::string> &dynamic_output_shape_info) {
  1747. for (auto &op : output_op_list_) {
  1748. if (op->GetType() != NETOUTPUT) {
  1749. continue;
  1750. }
  1751. GELOGI("Start to get dynamic output dims attr");
  1752. if (!AttrUtils::GetListStr(op, ATTR_NAME_DYNAMIC_OUTPUT_DIMS, dynamic_output_shape_info)) {
  1753. GELOGD("Can not get dynamic output dims attr");
  1754. }
  1755. }
  1756. }
  1757. Status DavinciModel::GetInputOutputDescInfoForZeroCopy(vector<InputOutputDescInfo> &input_desc,
  1758. vector<InputOutputDescInfo> &output_desc,
  1759. std::vector<uint32_t> &input_formats,
  1760. std::vector<uint32_t> &outputFormats) {
  1761. if ((data_op_list_.empty()) || (1 != data_op_list_[0]->GetInputsSize())) {
  1762. GELOGE(FAILED, "OP List Pointer is null or input_desc size is not 1!");
  1763. return FAILED;
  1764. }
  1765. GE_CHK_STATUS_RET(GetInputDescInfo(input_desc, input_formats), "get input desc info failed");
  1766. GE_CHK_STATUS_RET(GetOutputDescInfo(output_desc, outputFormats), "get ouput desc info failed");
  1767. GE_CHK_BOOL_RET_STATUS(output_desc.size() == output_memory_size_list_.size(), INTERNAL_ERROR,
  1768. "output_desc size[%zu] not equal output_size_list_[%zu] size!", output_desc.size(),
  1769. output_memory_size_list_.size());
  1770. /// For function zero copy,the momery should be aligned by 512 bytes.
  1771. /// And, because of the cce op limit, size should be lager than the real shape size. The memory should be padded by 32
  1772. /// bytes.
  1773. /// *size equals to ((tensorDesc->dataSize + 2 * 32 - 1) / 32) * 32;
  1774. for (size_t i = 0; i < output_memory_size_list_.size(); i++) {
  1775. output_desc[i].size = output_memory_size_list_[i];
  1776. }
  1777. return SUCCESS;
  1778. }
  1779. void DavinciModel::SetInputDimsInfo(const vector<int64_t> &model_input_dims, Format &format,
  1780. InputOutputDescInfo &input) {
  1781. uint32_t n, c, h, w;
  1782. n = format == FORMAT_NHWC ? NHWC_DIM_N : NCHW_DIM_N;
  1783. c = format == FORMAT_NHWC ? NHWC_DIM_C : NCHW_DIM_C;
  1784. h = format == FORMAT_NHWC ? NHWC_DIM_H : NCHW_DIM_H;
  1785. w = format == FORMAT_NHWC ? NHWC_DIM_W : NCHW_DIM_W;
  1786. if (model_input_dims.size() == static_cast<size_t>(NORMAL_TENSOR_SIZE)) {
  1787. input.shape_info.num = model_input_dims[n];
  1788. input.shape_info.height = model_input_dims[h];
  1789. input.shape_info.width = model_input_dims[w];
  1790. input.shape_info.channel = model_input_dims[c];
  1791. }
  1792. for (size_t k = 0; k < model_input_dims.size(); ++k) {
  1793. input.shape_info.dims.push_back(model_input_dims[k]);
  1794. }
  1795. return;
  1796. }
  1797. void DavinciModel::CreateInputDimsInfo(const OpDescPtr &op_desc, Format format, InputOutputDescInfo &input) {
  1798. if (is_new_model_desc_ && op_desc->HasAttr(ATTR_NAME_INPUT_DIMS)) {
  1799. // When static aipp is set, need to get the model input dims which processed by aipp
  1800. vector<int64_t> model_input_dims;
  1801. (void)AttrUtils::GetListInt(op_desc, ATTR_NAME_INPUT_DIMS, model_input_dims);
  1802. SetInputDimsInfo(model_input_dims, format, input);
  1803. return;
  1804. }
  1805. // judge if this data is linked dynamic aipp first, multiply batch has been considered
  1806. if (op_desc->HasAttr(ATTR_DYNAMIC_AIPP_INPUT_DIMS)) {
  1807. vector<int64_t> dynamic_aipp_input_dims;
  1808. (void)AttrUtils::GetListInt(op_desc, ATTR_DYNAMIC_AIPP_INPUT_DIMS, dynamic_aipp_input_dims);
  1809. SetInputDimsInfo(dynamic_aipp_input_dims, format, input);
  1810. return;
  1811. } else {
  1812. // judge if this data is multiply batch
  1813. if (!op_desc->HasAttr(ATTR_MBATCH_ORIGIN_INPUT_DIMS)) {
  1814. vector<int64_t> input_dims = op_desc->GetInputDescPtr(0)->GetShape().GetDims();
  1815. SetInputDimsInfo(input_dims, format, input);
  1816. return;
  1817. } else {
  1818. vector<int64_t> origin_input_dims;
  1819. (void)AttrUtils::GetListInt(op_desc, ATTR_MBATCH_ORIGIN_INPUT_DIMS, origin_input_dims);
  1820. SetInputDimsInfo(origin_input_dims, format, input);
  1821. return;
  1822. }
  1823. }
  1824. }
  1825. Status DavinciModel::GetInputDescInfo(vector<InputOutputDescInfo> &input_desc, std::vector<uint32_t> &formats) {
  1826. for (size_t index = 0; index < data_op_list_.size(); ++index) {
  1827. InputOutputDescInfo input;
  1828. GE_CHECK_NOTNULL(data_op_list_[index]);
  1829. GE_CHECK_NOTNULL(data_op_list_[index]->GetInputDescPtr(0));
  1830. Format format = data_op_list_[index]->GetInputDescPtr(0)->GetFormat();
  1831. CreateInputDimsInfo(data_op_list_[index], format, input);
  1832. input.data_type = data_op_list_[index]->GetInputDescPtr(0)->GetDataType();
  1833. input.name = data_op_list_[index]->GetName();
  1834. int64_t input_size = 0;
  1835. GE_CHK_STATUS_RET(TensorUtils::GetSize(*data_op_list_[index]->GetInputDescPtr(0), input_size),
  1836. "get input size failed.");
  1837. input.size = input_size;
  1838. formats.push_back(format);
  1839. input_desc.push_back(input);
  1840. }
  1841. // cause GetInputDescInfo called not only once, set is_new_model_desc_ to false after calc the model input dims
  1842. is_new_model_desc_ = false;
  1843. return SUCCESS;
  1844. }
  1845. void DavinciModel::CreateOutput(uint32_t index, OpDescPtr &op_desc, InputOutputDescInfo &output,
  1846. uint32_t &format_result) {
  1847. /// netoutput input tensor desc
  1848. GE_IF_BOOL_EXEC(op_desc->GetInputDescPtr(index) == nullptr, GELOGE(FAILED, "OpDesc GetInputDescPtr is nullptr");
  1849. return );
  1850. Format format = op_desc->GetInputDescPtr(index)->GetFormat();
  1851. GeShape shape = op_desc->GetInputDescPtr(index)->GetShape();
  1852. DataType data_type = op_desc->GetInputDescPtr(index)->GetDataType();
  1853. int64_t dims[] = {1, 1, 1, 1};
  1854. format_result = format;
  1855. if (format == FORMAT_ND) { // for ND tensor
  1856. for (size_t i = 0; i < shape.GetDimNum() && i < (sizeof(dims) / sizeof(dims[0])); i++) {
  1857. dims[i] = shape.GetDim(i);
  1858. }
  1859. } else { // FOR FORMAT_NHWC or FORMAT_NCHW
  1860. dims[0] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_N : NCHW_DIM_N); // 0: first dim
  1861. dims[1] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_C : NCHW_DIM_C); // 1: second dim
  1862. dims[2] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_H : NCHW_DIM_H); // 2: third dim
  1863. dims[3] = shape.GetDim(format == FORMAT_NHWC ? NHWC_DIM_W : NCHW_DIM_W); // 3: forth dim
  1864. }
  1865. output.shape_info.num = dims[0]; // 0: first dim
  1866. output.shape_info.channel = dims[1]; // 1: second dim
  1867. output.shape_info.height = dims[2]; // 2: third dim
  1868. output.shape_info.width = dims[3]; // 3: forth dim
  1869. if (op_desc->GetInputDescPtr(index)->GetFormat() == FORMAT_FRACTAL_Z) { // FraczToHWCK
  1870. int64_t k = shape.GetDim(0); // 0: first dim
  1871. int64_t c = shape.GetDim(1); // 1: second dim
  1872. int64_t h = shape.GetDim(2); // 2: third dim
  1873. int64_t w = shape.GetDim(3); // 3: forth dim
  1874. output.shape_info.dims.push_back(h);
  1875. output.shape_info.dims.push_back(w);
  1876. output.shape_info.dims.push_back(c);
  1877. output.shape_info.dims.push_back(k);
  1878. format_result = FORMAT_HWCN;
  1879. } else {
  1880. for (size_t j = 0; j < shape.GetDimNum(); j++) {
  1881. output.shape_info.dims.push_back(shape.GetDim(j));
  1882. }
  1883. }
  1884. int64_t tensor_size = 0;
  1885. (void)TensorUtils::CalcTensorMemSize(shape, format, data_type, tensor_size); // no need to check value
  1886. output.size = static_cast<uint64_t>(tensor_size);
  1887. output.data_type = op_desc->GetInputDescPtr(index)->GetDataType();
  1888. }
  1889. Status DavinciModel::GetOutputDescInfo(vector<InputOutputDescInfo> &output_desc, std::vector<uint32_t> &formats) {
  1890. GELOGI("Output node size: %zu", output_op_list_.size());
  1891. for (size_t i = 0; i < output_op_list_.size(); i++) {
  1892. auto &op_desc = output_op_list_[i];
  1893. uint32_t out_size = static_cast<uint32_t>(op_desc->GetInputsSize());
  1894. for (uint32_t index = 0; index < out_size; index++) {
  1895. string output_name;
  1896. InputOutputDescInfo output;
  1897. uint32_t format_result;
  1898. CreateOutput(index, op_desc, output, format_result);
  1899. std::vector<std::string> src_name = op_desc->GetSrcName();
  1900. std::vector<int64_t> src_index = op_desc->GetSrcIndex();
  1901. GE_CHK_BOOL_RET_STATUS(src_name.size() > index && src_index.size() > index, INTERNAL_ERROR,
  1902. "construct output_name failed.");
  1903. // forward compatbility, if old om has no out_node_name, need to return output follow origin way
  1904. if (out_size == out_node_name_.size()) {
  1905. // neweast plan, the index will add to name during generate model.
  1906. bool contains_colon = out_node_name_[index].find(":") != std::string::npos;
  1907. output_name =
  1908. contains_colon ? out_node_name_[index] : out_node_name_[index] + ":" + std::to_string(src_index[index]);
  1909. } else {
  1910. output_name = std::string("output_") + std::to_string(index) + "_" + src_name[index] + "_" +
  1911. std::to_string(src_index[index]);
  1912. }
  1913. output.name = output_name;
  1914. output_desc.push_back(output);
  1915. formats.push_back(format_result);
  1916. }
  1917. }
  1918. return SUCCESS;
  1919. }
  1920. ge::Format DavinciModel::GetFormat() {
  1921. if ((data_op_list_.empty()) || data_op_list_[0] == nullptr || data_op_list_[0]->GetInputDescPtr(0) == nullptr) {
  1922. GELOGW("OP List Pointer is null or input_desc size is not 1!");
  1923. return FORMAT_NCHW;
  1924. }
  1925. return data_op_list_[0]->GetInputDescPtr(0)->GetFormat();
  1926. }
  1927. Status DavinciModel::CopyInputData(const InputData &input_data, bool device_data) {
  1928. rtMemcpyKind_t kind = device_data ? RT_MEMCPY_DEVICE_TO_DEVICE : RT_MEMCPY_HOST_TO_DEVICE;
  1929. const std::vector<DataBuffer> &blobs = input_data.blobs;
  1930. for (const auto &data : new_input_data_info_) {
  1931. if (data.first >= blobs.size()) {
  1932. GELOGE(FAILED, "Blobs not match: blobs=%zu, tensor=%zu, index=%u, size=%ld", blobs.size(),
  1933. new_input_data_info_.size(), data.first, data.second.GetDataInfo().at(0).first);
  1934. return FAILED;
  1935. }
  1936. const DataBuffer &data_buf = blobs[data.first];
  1937. if (data_buf.length == 0) {
  1938. GELOGW("No data need to memcpy!");
  1939. return SUCCESS;
  1940. }
  1941. uint64_t data_size = data.second.GetDataSize();
  1942. GE_CHK_BOOL_RET_STATUS(data_size >= data_buf.length, PARAM_INVALID,
  1943. "input data size(%lu) does not match model required size(%lu), ret failed.", data_buf.length,
  1944. data_size);
  1945. void *mem_addr = data.second.GetBasicAddr();
  1946. void *data_buf_addr = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(data_buf.data));
  1947. uint64_t data_buf_length = data_buf.length;
  1948. GELOGI("[IMAS]CopyPlainData memcpy graph_%lu type[F] input[%lu] dst[%p] src[%p] mem_size[%lu] datasize[%lu]",
  1949. runtime_param_.graph_id, data.first, mem_addr, data_buf_addr, data_size, data_buf_length);
  1950. GE_CHK_RT_RET(rtMemcpy(mem_addr, data_size, data_buf_addr, data_buf_length, kind));
  1951. }
  1952. return SUCCESS;
  1953. }
  1954. Status DavinciModel::SyncVarData() {
  1955. GELOGI("Sync var data, model id:%u", model_id_);
  1956. Status ret = SUCCESS;
  1957. OpDescPtr global_step = GetVariableOp(NODE_NAME_GLOBAL_STEP);
  1958. if (global_step != nullptr) {
  1959. auto v_output_size = ModelUtils::GetOutputSize(global_step);
  1960. auto v_output_addr = ModelUtils::GetOutputDataAddrs(runtime_param_, global_step);
  1961. if (v_output_size.empty() || v_output_addr.empty()) {
  1962. GELOGE(PARAM_INVALID, "global step op:%s not set output", global_step->GetName().c_str());
  1963. return PARAM_INVALID;
  1964. }
  1965. std::vector<uint64_t> v_step;
  1966. v_step.push_back(iterator_count_);
  1967. GE_CHK_RT_RET(rtMemcpy(v_output_addr[0], v_output_size[0], v_step.data(), v_step.size() * sizeof(uint64_t),
  1968. RT_MEMCPY_HOST_TO_DEVICE));
  1969. }
  1970. for (auto op_desc : variable_op_list_) {
  1971. ret =
  1972. VarManager::Instance(session_id_)->SyncVarData(runtime_param_.graph_id, op_desc->GetName(), op_desc, mem_base_);
  1973. GE_CHK_BOOL_EXEC(ret == SUCCESS, break, "sync var data ret failed, model id:%u, op name:%s.", model_id_,
  1974. op_desc->GetName().c_str());
  1975. }
  1976. return ret;
  1977. }
  1978. inline int64_t SumSize(const vector<int64_t> &size_list) {
  1979. int64_t sum_size = 0;
  1980. for (const int64_t &size : size_list) {
  1981. sum_size += size;
  1982. }
  1983. return sum_size;
  1984. }
  1985. Status DavinciModel::SinkModelProfile() {
  1986. // profiling plugin must be registered
  1987. Msprof::Engine::Reporter *reporter = PluginImpl::GetPluginReporter();
  1988. GE_IF_BOOL_EXEC(reporter == nullptr, GELOGI("Profiling report is nullptr!"); return SUCCESS);
  1989. GELOGI("Start collect model load profiling data.");
  1990. Msprof::Engine::ReporterData reporter_data{};
  1991. // report model data tag name
  1992. std::string tag_name;
  1993. tag_name.append("model_load_info_").append(std::to_string(this->Id()));
  1994. GE_CHK_BOOL_EXEC(memcpy_s(reporter_data.tag, MSPROF_ENGINE_MAX_TAG_LEN, tag_name.c_str(), tag_name.size()) == EOK,
  1995. return FAILED, "Sink model tag memcpy error.");
  1996. // Model Header
  1997. string name;
  1998. if (!om_name_.empty()) {
  1999. name = om_name_;
  2000. } else {
  2001. name = name_;
  2002. }
  2003. size_t name_len = name.size();
  2004. reporter_data.deviceId = device_id_;
  2005. reporter_data.data = (unsigned char *)&name_len;
  2006. reporter_data.dataLen = sizeof(int32_t);
  2007. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2008. this->Id());
  2009. reporter_data.data = (unsigned char *)name.c_str();
  2010. reporter_data.dataLen = name.size();
  2011. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2012. this->Id());
  2013. uint32_t model_id = this->Id();
  2014. reporter_data.data = (unsigned char *)&model_id;
  2015. reporter_data.dataLen = sizeof(uint32_t);
  2016. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2017. this->Id());
  2018. // Load Start/End Time
  2019. int64_t start_time = this->GetLoadBeginTime();
  2020. reporter_data.data = (unsigned char *)&start_time;
  2021. reporter_data.dataLen = sizeof(int64_t);
  2022. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2023. this->Id());
  2024. int64_t end_time = this->GetLoadEndTime();
  2025. reporter_data.data = (unsigned char *)&end_time;
  2026. reporter_data.dataLen = sizeof(int64_t);
  2027. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2028. this->Id());
  2029. int32_t task_num = task_list_.size();
  2030. std::multimap<uint32_t, uint32_t> op_id_map;
  2031. std::set<uint32_t> task_id_set;
  2032. for (int32_t i = 0; i < task_num; i++) {
  2033. auto task = task_list_[i];
  2034. GE_CHECK_NOTNULL(task);
  2035. auto fusion_op_info = task->GetFusionOpInfo();
  2036. // when type is RT_MODEL_TASK_KERNEL, ctx is not null
  2037. if (fusion_op_info != nullptr) {
  2038. uint32_t op_num = fusion_op_info->original_op_names.size();
  2039. uint32_t task_id = task->GetTaskID();
  2040. if (op_num > 0) {
  2041. GELOGI("task.id = %u, opNum = %u", task_id, op_num);
  2042. op_id_map.insert(std::make_pair(fusion_op_info->op_index, task_id));
  2043. }
  2044. }
  2045. }
  2046. struct memoryInfo {
  2047. int64_t input_size;
  2048. int64_t output_size;
  2049. int64_t weight_size;
  2050. int64_t workspace_size;
  2051. int64_t total_size;
  2052. memoryInfo() : input_size(0), output_size(0), weight_size(0), workspace_size(0), total_size(0) {}
  2053. };
  2054. using CIT = std::multimap<uint32_t, uint32_t>::const_iterator;
  2055. using Range = std::pair<CIT, CIT>;
  2056. for (int32_t i = 0; i < task_num; i++) {
  2057. auto task = task_list_[i];
  2058. GE_CHECK_NOTNULL(task);
  2059. auto fusion_op_info = task->GetFusionOpInfo();
  2060. if (fusion_op_info != nullptr && fusion_op_info->original_op_names.size() > 0) {
  2061. uint32_t task_id = task->GetTaskID();
  2062. uint32_t op_num = fusion_op_info->original_op_names.size();
  2063. uint32_t task_count = 0;
  2064. if (task_id_set.count(task_id) != 0) {
  2065. continue;
  2066. }
  2067. uint32_t op_id = fusion_op_info->op_index;
  2068. Range range = op_id_map.equal_range(op_id);
  2069. for (CIT range_idx = range.first; range_idx != range.second; ++range_idx) {
  2070. task_count++;
  2071. uint32_t task_id = range_idx->second;
  2072. task_id_set.insert(task_id);
  2073. }
  2074. // op name after fusion
  2075. string fusion_op_name = fusion_op_info->op_name;
  2076. int32_t fusion_op_name_len = fusion_op_name.size() == 0 ? 1 : fusion_op_name.size();
  2077. reporter_data.data = (unsigned char *)&fusion_op_name_len;
  2078. reporter_data.dataLen = sizeof(int32_t);
  2079. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2080. this->Id());
  2081. reporter_data.data = (unsigned char *)fusion_op_name.c_str();
  2082. reporter_data.dataLen = fusion_op_name_len;
  2083. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2084. this->Id());
  2085. // original op name before fusion
  2086. reporter_data.data = (unsigned char *)&op_num;
  2087. reporter_data.dataLen = sizeof(int32_t);
  2088. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2089. this->Id());
  2090. for (uint32_t k = 0; k < op_num; k++) {
  2091. std::string op_name = fusion_op_info->original_op_names[k];
  2092. int32_t op_name_len = op_name.size() == 0 ? 1 : op_name.size();
  2093. reporter_data.data = (unsigned char *)&op_name_len;
  2094. reporter_data.dataLen = sizeof(int32_t);
  2095. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2096. this->Id());
  2097. reporter_data.data = (unsigned char *)op_name.c_str();
  2098. reporter_data.dataLen = op_name_len;
  2099. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2100. this->Id());
  2101. }
  2102. // stream id info
  2103. uint32_t streamId = task->GetStreamId();
  2104. reporter_data.data = (unsigned char *)&streamId;
  2105. reporter_data.dataLen = sizeof(int32_t);
  2106. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2107. this->Id());
  2108. // memory info
  2109. struct memoryInfo memory_info;
  2110. uint32_t op_index = fusion_op_info->op_index;
  2111. auto iter = op_list_.find(op_index);
  2112. GE_CHK_BOOL_EXEC(iter != op_list_.end(), return FAILED, "index is out of range, index: %u", op_index);
  2113. auto op_desc = iter->second;
  2114. memory_info.input_size = SumSize(ModelUtils::GetInputSize(op_desc));
  2115. memory_info.output_size = SumSize(ModelUtils::GetOutputSize(op_desc));
  2116. memory_info.workspace_size = SumSize(ModelUtils::GetWorkspaceSize(op_desc));
  2117. memory_info.weight_size = SumSize(ModelUtils::GetWeightSize(op_desc));
  2118. memory_info.total_size =
  2119. memory_info.weight_size + memory_info.input_size + memory_info.output_size + memory_info.workspace_size;
  2120. reporter_data.data = (unsigned char *)&memory_info;
  2121. reporter_data.dataLen = sizeof(struct memoryInfo);
  2122. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2123. this->Id());
  2124. // task info
  2125. reporter_data.data = (unsigned char *)&task_count;
  2126. reporter_data.dataLen = sizeof(uint32_t);
  2127. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2128. this->Id());
  2129. Range task_range = op_id_map.equal_range(op_id);
  2130. for (CIT idx = task_range.first; idx != task_range.second; ++idx) {
  2131. uint32_t task_id = idx->second;
  2132. reporter_data.data = (unsigned char *)&task_id;
  2133. reporter_data.dataLen = sizeof(uint32_t);
  2134. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2135. this->Id());
  2136. }
  2137. }
  2138. }
  2139. return SUCCESS;
  2140. }
  2141. Status DavinciModel::SinkTimeProfile(const InputData &current_data) {
  2142. // profiling plugin must be registered
  2143. Msprof::Engine::Reporter *reporter = PluginImpl::GetPluginReporter();
  2144. GE_IF_BOOL_EXEC(reporter == nullptr, GELOGI("Profiling report is nullptr!"); return SUCCESS);
  2145. Msprof::Engine::ReporterData reporter_data{};
  2146. // report model data tag name
  2147. std::string tag_name;
  2148. tag_name.append("model_time_info_")
  2149. .append(std::to_string(this->Id()))
  2150. .append("_")
  2151. .append(std::to_string(current_data.index));
  2152. GE_CHK_BOOL_EXEC(memcpy_s(reporter_data.tag, MSPROF_ENGINE_MAX_TAG_LEN, tag_name.c_str(), tag_name.size()) == EOK,
  2153. return FAILED, "Sink model tag memcpy error.");
  2154. // device id
  2155. reporter_data.deviceId = device_id_;
  2156. // Model Header
  2157. string name;
  2158. if (!om_name_.empty()) {
  2159. name = om_name_;
  2160. } else {
  2161. name = name_;
  2162. }
  2163. size_t name_len = name.size();
  2164. reporter_data.data = (unsigned char *)&name_len;
  2165. reporter_data.dataLen = sizeof(int32_t);
  2166. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2167. this->Id());
  2168. reporter_data.data = (unsigned char *)name.c_str();
  2169. reporter_data.dataLen = name.size();
  2170. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED, "Reporter data fail, model id:%u.",
  2171. this->Id());
  2172. // request id
  2173. uint64_t request_id = current_data.request_id;
  2174. reporter_data.data = (unsigned char *)&request_id;
  2175. reporter_data.dataLen = sizeof(uint32_t);
  2176. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED,
  2177. "Reporter data fail, model id:%u, data index:%u.", this->Id(), current_data.index);
  2178. // thread id
  2179. int32_t thread_id = GetDataInputTid();
  2180. reporter_data.data = (unsigned char *)&thread_id;
  2181. reporter_data.dataLen = sizeof(int32_t);
  2182. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED,
  2183. "Reporter data fail, model id:%u, data index:%u.", this->Id(), current_data.index);
  2184. // time info
  2185. time_info_.modelId = this->Id();
  2186. reporter_data.data = (unsigned char *)&time_info_;
  2187. reporter_data.dataLen = sizeof(struct timeInfo);
  2188. GE_CHK_BOOL_EXEC(reporter->Report(&reporter_data) == SUCCESS, return FAILED,
  2189. "Reporter data fail, model id:%u, data index:%u.", this->Id(), current_data.index);
  2190. return SUCCESS;
  2191. }
  2192. void DavinciModel::SetProfileTime(ModelProcStage stage, int64_t endTime) {
  2193. int64_t time = endTime;
  2194. if (time == 0) {
  2195. mmTimespec timespec = mmGetTickCount();
  2196. time = timespec.tv_sec * 1000 * 1000 * 1000 + timespec.tv_nsec; // 1000 ^ 3 converts second to nanosecond
  2197. }
  2198. switch (stage) {
  2199. case MODEL_LOAD_START:
  2200. load_begin_time_ = time;
  2201. break;
  2202. case MODEL_LOAD_END:
  2203. load_end_time_ = time;
  2204. break;
  2205. case MODEL_PRE_PROC_START:
  2206. time_info_.processBeginTime = time;
  2207. break;
  2208. case MODEL_PRE_PROC_END:
  2209. time_info_.processEndTime = time;
  2210. break;
  2211. case MODEL_INFER_START:
  2212. time_info_.inferenceBeginTime = time;
  2213. break;
  2214. case MODEL_INFER_END:
  2215. time_info_.inferenceEndTime = time;
  2216. break;
  2217. case MODEL_AFTER_PROC_START:
  2218. time_info_.dumpBeginTime = time;
  2219. break;
  2220. case MODEL_AFTER_PROC_END:
  2221. time_info_.dumpEndTime = time;
  2222. break;
  2223. default:
  2224. break;
  2225. }
  2226. return;
  2227. }
  2228. ///
  2229. /// @ingroup ge
  2230. /// @brief send Output Op result to upper layer
  2231. /// @already malloced in ModelLoad, no need to malloc again
  2232. /// @param [in] data_id: the index of output_data
  2233. /// @param [in/out] output_data: real user output_data
  2234. /// @param [in] kind: the kind of rtMemcpy
  2235. /// @return Status result
  2236. /// @author
  2237. ///
  2238. Status DavinciModel::CopyOutputData(uint32_t data_id, OutputData &output_data, rtMemcpyKind_t kind) {
  2239. if (output_op_list_.empty()) {
  2240. Status ret = SyncVarData();
  2241. return ret;
  2242. }
  2243. output_data.index = data_id;
  2244. output_data.model_id = model_id_;
  2245. if (output_data.blobs.size() != new_output_data_info_.size()) {
  2246. GELOGE(FAILED, "Output data buffer num=%zu not equal model data num=%zu", output_data.blobs.size(),
  2247. new_output_data_info_.size());
  2248. return FAILED;
  2249. }
  2250. std::vector<DataBuffer> &blobs = output_data.blobs;
  2251. size_t idx = 0;
  2252. for (const auto &output : new_output_data_info_) {
  2253. if (output.first >= blobs.size()) {
  2254. GELOGE(FAILED, "Blobs not match: blobs=%zu, tensor=%zu, index=%u, size=%ld", blobs.size(),
  2255. new_input_data_info_.size(), output.first, output.second.GetDataInfo().at(0).first);
  2256. return FAILED;
  2257. }
  2258. if ((kind == RT_MEMCPY_DEVICE_TO_DEVICE) && (copy_only_addrs_.count(output.second.GetBasicAddr()) == 0)) {
  2259. continue; // Skip: Feed by zero copy.
  2260. }
  2261. DataBuffer &buffer = blobs[output.first];
  2262. uint64_t mem_size = static_cast<uint64_t>(output.second.GetDataSize());
  2263. if ((buffer.length == 0) || (mem_size == 0)) {
  2264. GELOGI("Length of data is zero, No need copy. output tensor index=%u", output.first);
  2265. continue;
  2266. }
  2267. if (is_dynamic_) {
  2268. GELOGI("No need to check output data size.");
  2269. } else if (buffer.length < mem_size) {
  2270. GELOGE(FAILED, "Tensor data size=%lu, buffer size=%u", mem_size, buffer.length);
  2271. return FAILED;
  2272. } else if (buffer.length > mem_size) {
  2273. GELOGW("Tensor data size=%lu, buffer size=%u", mem_size, buffer.length);
  2274. }
  2275. int64_t data_size = output.second.GetDataSize();
  2276. if (is_online_infer_dynamic_) {
  2277. auto gear_and_real_out_size_info = merge_nodes_gear_and_real_out_size_info_[idx];
  2278. data_size = gear_and_real_out_size_info[cur_dynamic_dims_];
  2279. }
  2280. uint64_t buffer_length = buffer.length;
  2281. void *buffer_addr = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(buffer.data));
  2282. GELOGI("[IMAS]CopyPlainData memcpy graph_%u type[F] output[%u] memaddr[%p] mem_size[%ld] datasize[%u]",
  2283. runtime_param_.graph_id, output.first, output.second.GetBasicAddr(), data_size, buffer_length);
  2284. GE_CHK_RT_RET(rtMemcpy(buffer_addr, buffer_length, output.second.GetBasicAddr(), data_size, kind));
  2285. idx++;
  2286. }
  2287. return SUCCESS;
  2288. }
  2289. Status DavinciModel::GenOutputTensorInfo(const OpDescPtr &op_desc, uint32_t data_index, OutputData *output_data,
  2290. std::vector<ge::OutputTensorInfo> &outputs) {
  2291. GE_CHECK_NOTNULL(op_desc);
  2292. GE_CHECK_NOTNULL(output_data);
  2293. if (output_data->blobs.size() > data_index) {
  2294. GELOGI("No need to generate output tensor info, model id:%u", model_id_);
  2295. return SUCCESS;
  2296. }
  2297. std::vector<int64_t> out_buffer_size_vec;
  2298. std::vector<std::vector<int64_t>> shape_info_vec;
  2299. size_t input_num = op_desc->GetInputsSize();
  2300. if (is_getnext_sink_dynamic_) {
  2301. input_num = input_num - kGetDynamicDimsCount;
  2302. }
  2303. for (size_t i = 0; i < input_num; ++i) {
  2304. int64_t size = 0;
  2305. auto input_desc = op_desc->GetInputDescPtr(i);
  2306. GE_CHECK_NOTNULL(input_desc);
  2307. auto ret = TensorUtils::GetTensorSizeInBytes(*input_desc, size);
  2308. GE_IF_BOOL_EXEC(ret != GRAPH_SUCCESS,
  2309. GELOGE(ret, "Get size from TensorDesc failed, op:%s, input id:%zu", op_desc->GetName().c_str(), i);
  2310. return ret);
  2311. std::vector<int64_t> output_shape = input_desc->GetShape().GetDims();
  2312. if (is_online_infer_dynamic_) {
  2313. auto gear_and_real_out_size_info = merge_nodes_gear_and_real_out_size_info_[i];
  2314. size = gear_and_real_out_size_info[cur_dynamic_dims_];
  2315. auto gear_and_real_out_shape_info = merge_nodes_gear_and_real_out_shape_info_[i];
  2316. output_shape = gear_and_real_out_shape_info[cur_dynamic_dims_];
  2317. is_dynamic_ = true;
  2318. }
  2319. GELOGI("Output size is %ld, output shape is %s.", size, formats::JoinToString(output_shape).c_str());
  2320. out_buffer_size_vec.push_back(size);
  2321. shape_info_vec.push_back(output_shape);
  2322. }
  2323. GELOGI("Output blobs size:%zu, data index:%u, model id:%u", out_buffer_size_vec.size(), data_index, model_id_);
  2324. for (size_t i = 0; i < out_buffer_size_vec.size(); ++i) {
  2325. std::unique_ptr<uint8_t[]> data_buf(new (std::nothrow) uint8_t[out_buffer_size_vec[i]]);
  2326. if (data_buf == nullptr) {
  2327. GELOGE(GE_GRAPH_MALLOC_FAILED, "Malloc buffer failed.");
  2328. return GE_GRAPH_MALLOC_FAILED;
  2329. }
  2330. output_data->blobs.push_back({data_buf.get(), static_cast<uint64_t>(out_buffer_size_vec[i]), false});
  2331. ge::OutputTensorInfo output;
  2332. output.dims = shape_info_vec[i];
  2333. output.data = std::move(data_buf);
  2334. output.length = out_buffer_size_vec[i];
  2335. outputs.emplace_back(std::move(output));
  2336. GELOGD("Output index:%zu, output dims is %s, data length:%lu.", i,
  2337. formats::JoinToString(output.dims).c_str(), output.length);
  2338. }
  2339. return SUCCESS;
  2340. }
  2341. ///
  2342. /// @ingroup ge
  2343. /// @brief send Output Op result to upper layer
  2344. /// @already malloced in ModelLoad, no need to malloc again
  2345. /// @param [in] data_id: the index of output_data
  2346. /// @param [in] rslt_flg: result flag
  2347. /// @param [in] seq_end_flag: sequence end flag
  2348. /// @param [out] output_data: real user output_data
  2349. /// @return Status result
  2350. /// @author
  2351. ///
  2352. Status DavinciModel::ReturnResult(uint32_t data_id, const bool rslt_flg, const bool seq_end_flag,
  2353. OutputData *output_data) {
  2354. GE_CHK_BOOL_EXEC(listener_ != nullptr, return PARAM_INVALID, "listener_ is null.");
  2355. std::vector<ge::OutputTensorInfo> outputs;
  2356. // return result is not required
  2357. if (!rslt_flg && !seq_end_flag) {
  2358. GELOGW("Compute failed, model id: %u", model_id_);
  2359. auto model_manager = ModelManager::GetInstance();
  2360. GE_CHECK_NOTNULL(model_manager);
  2361. auto exception_infos = model_manager->GetExceptionInfos();
  2362. if (exception_infos.size() > 0) {
  2363. GE_CHK_STATUS_RET(data_dumper_.DumpExceptionInfo(exception_infos), "Dump exception info failed");
  2364. } else {
  2365. GELOGI("Exception info is null");
  2366. }
  2367. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, INTERNAL_ERROR, outputs), "OnComputeDone failed.");
  2368. return INTERNAL_ERROR;
  2369. }
  2370. if (output_op_list_.empty()) {
  2371. GELOGW("Output tensor list is empty, model id: %u", model_id_);
  2372. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, INTERNAL_ERROR, outputs), "OnComputeDone failed.");
  2373. return INTERNAL_ERROR;
  2374. }
  2375. GE_CHECK_NOTNULL(output_data);
  2376. // index of data in output_data
  2377. uint32_t data_index = 0;
  2378. output_data->index = data_id;
  2379. output_data->model_id = model_id_;
  2380. is_getnext_sink_dynamic_ = false;
  2381. // copy output data from op to designated position
  2382. for (auto &op_desc : output_op_list_) {
  2383. if (IsGetNextSinkDynamic(op_desc)) {
  2384. GELOGD("Reinit cur dynamic dims when getnext sink dynamic.");
  2385. is_getnext_sink_dynamic_ = true;
  2386. cur_dynamic_dims_.clear();
  2387. cur_dynamic_dims_.resize(shape_of_cur_dynamic_dims_);
  2388. GE_CHK_RT_RET(rtMemcpy(cur_dynamic_dims_.data(), shape_of_cur_dynamic_dims_ * sizeof(int64_t),
  2389. netoutput_last_input_addr_, netoutput_last_input_size_, RT_MEMCPY_DEVICE_TO_HOST));
  2390. }
  2391. GELOGD("Cur dynamic dims is %s.", formats::JoinToString(cur_dynamic_dims_).c_str());
  2392. if (GenOutputTensorInfo(op_desc, data_index, output_data, outputs) != SUCCESS) {
  2393. return INTERNAL_ERROR;
  2394. }
  2395. data_index += op_desc->GetInputsSize();
  2396. }
  2397. if (CopyOutputData(data_id, *output_data, RT_MEMCPY_DEVICE_TO_HOST) != SUCCESS) {
  2398. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, INTERNAL_ERROR, outputs), "OnComputeDone failed");
  2399. return INTERNAL_ERROR;
  2400. }
  2401. if (seq_end_flag) {
  2402. GELOGW("End of sequence, model id: %u", model_id_);
  2403. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, END_OF_SEQUENCE, outputs), "OnCompute Done failed.");
  2404. return END_OF_SEQUENCE;
  2405. }
  2406. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, SUCCESS, outputs), "OnComputeDone failed");
  2407. return SUCCESS;
  2408. }
  2409. ///
  2410. /// @ingroup ge
  2411. /// @brief return not output to upper layer for cloud case
  2412. /// @param [in] data_id
  2413. /// @return Status result
  2414. ///
  2415. Status DavinciModel::ReturnNoOutput(uint32_t data_id) {
  2416. GELOGI("ReturnNoOutput model id:%u", model_id_);
  2417. for (auto op_desc : variable_op_list_) {
  2418. Status ret = VarManager::Instance(session_id_)
  2419. ->SyncBroadCastData2Var(runtime_param_.graph_id, op_desc->GetName(), op_desc, mem_base_);
  2420. GE_CHK_BOOL_EXEC(ret == SUCCESS, break, "sync var data ret failed, model id:%u, op name:%s.", model_id_,
  2421. op_desc->GetName().c_str());
  2422. }
  2423. GE_CHK_BOOL_EXEC(listener_ != nullptr, return PARAM_INVALID, "listener_ is null!");
  2424. std::vector<ge::OutputTensorInfo> outputs;
  2425. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_id, SUCCESS, outputs), "OnComputeDone failed.");
  2426. return SUCCESS;
  2427. }
  2428. void *DavinciModel::Run(DavinciModel *model) {
  2429. GE_CHK_BOOL_EXEC(model != nullptr,
  2430. CsaInteract::GetInstance().WriteErrorCode(FAILED, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2431. return nullptr, "model_pointer is null!")
  2432. bool seq_end_flag = false;
  2433. uint32_t model_id = model->Id();
  2434. uint32_t device_id = model->GetDeviceId();
  2435. GELOGI("Model Run thread start, model_id:%u.", model_id);
  2436. rtError_t rt_ret = rtSetDevice(static_cast<int32_t>(device_id));
  2437. if (rt_ret != RT_ERROR_NONE) {
  2438. GELOGE(FAILED, "Model run rtsetdevice failed.");
  2439. return nullptr;
  2440. }
  2441. // DeviceReset before thread run finished!
  2442. GE_MAKE_GUARD(not_used_var, [&] { GE_CHK_RT(rtDeviceReset(device_id)); });
  2443. while (model->RunFlag()) {
  2444. bool rslt_flg = true;
  2445. if (model->GetDataInputer() == nullptr) {
  2446. GELOGW("Data inputer is nullptr.");
  2447. CsaInteract::GetInstance().StoreInternalErrorCode(FAILED, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2448. break;
  2449. }
  2450. std::shared_ptr<InputDataWrapper> data_wrapper;
  2451. Status ret = model->GetDataInputer()->Pop(data_wrapper);
  2452. if (data_wrapper == nullptr || ret != SUCCESS) {
  2453. GELOGI("data_wrapper is null!");
  2454. continue;
  2455. }
  2456. GELOGI("Getting the input data, model_id:%u", model_id);
  2457. GE_IF_BOOL_EXEC(!model->RunFlag(), break);
  2458. InputData current_data = data_wrapper->GetInput();
  2459. GELOGI("Model thread Run begin, model id:%u, data index:%u.", model_id, current_data.index);
  2460. if (model->is_online_infer_dynamic_ && !model->is_getnext_sink_dynamic_) {
  2461. model->cur_dynamic_dims_.clear();
  2462. GE_IF_BOOL_EXEC(current_data.blobs.empty(), break);
  2463. auto shape_data_buffer_data = current_data.blobs.back().data;
  2464. auto shape_data_buffer_length = current_data.blobs.back().length;
  2465. model->cur_dynamic_dims_.assign(reinterpret_cast<int64_t *>(shape_data_buffer_data),
  2466. reinterpret_cast<int64_t *>(shape_data_buffer_data) +
  2467. shape_data_buffer_length / sizeof(int64_t));
  2468. GELOGD("Data: cur dynamic dims is %s", formats::JoinToString(model->cur_dynamic_dims_).c_str());
  2469. }
  2470. GE_TIMESTAMP_START(Model_SyncVarData);
  2471. ret = model->SyncVarData();
  2472. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  2473. ret != SUCCESS, (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2474. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2475. continue, "Copy input data to model failed."); // [No need to check value]
  2476. GE_IF_BOOL_EXEC(model->is_first_execute_, GE_TIMESTAMP_EVENT_END(Model_SyncVarData, "Model Run SyncVarData"));
  2477. GELOGI("Copy input data, model id:%u", model_id);
  2478. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(),
  2479. model->SetProfileTime(MODEL_PRE_PROC_START));
  2480. ret = model->CopyInputData(current_data, false);
  2481. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  2482. ret != SUCCESS, (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2483. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  2484. continue, "Copy input data to model failed."); // [No need to check value]
  2485. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), model->SetProfileTime(MODEL_PRE_PROC_END));
  2486. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), model->SetProfileTime(MODEL_INFER_START));
  2487. if (ProfilingManager::Instance().ProfilingOpTraceOn()) {
  2488. GELOGI("GetOpTraceIterNum:%d", ProfilingManager::Instance().GetOpTraceIterNum());
  2489. for (int32_t i = 0; i < ProfilingManager::Instance().GetOpTraceIterNum(); i++) {
  2490. if (!ProfilingManager::Instance().ProfilingLoadFlag()) {
  2491. vector<int32_t> prof_device_id_vec = ProfilingManager::Instance().GetProfilingDeviceId();
  2492. for (size_t j = 0; j < prof_device_id_vec.size(); ++j) {
  2493. // just profiling, no need to check value
  2494. (void)ProfilingManager::Instance().StartProfiling(i, prof_device_id_vec[j]);
  2495. }
  2496. }
  2497. GELOGI("rtModelExecute start.");
  2498. rt_ret = rtModelExecute(model->rt_model_handle_, model->rt_model_stream_, 0);
  2499. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, rslt_flg = false;
  2500. (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2501. continue); // [No need to check value]
  2502. GELOGI("rtModelExecute end");
  2503. GELOGI("rtStreamSynchronize start.");
  2504. rt_ret = rtStreamSynchronize(model->rt_model_stream_);
  2505. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, rslt_flg = false;
  2506. (void)model->ReturnResult(current_data.index, false, seq_end_flag, data_wrapper->GetOutput());
  2507. continue); // [No need to check value]
  2508. GELOGI("rtStreamSynchronize end.");
  2509. (void)ProfilingManager::Instance().StopProfiling(); // just profiling, no need to check value
  2510. }
  2511. } else {
  2512. GE_TIMESTAMP_START(rtModelExecute);
  2513. GELOGI("rtModelExecute start.");
  2514. rt_ret = rtModelExecute(model->rt_model_handle_, model->rt_model_stream_, 0);
  2515. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, rslt_flg = false;
  2516. (void)model->ReturnResult(current_data.index, false, false, data_wrapper->GetOutput());
  2517. CsaInteract::GetInstance().WriteErrorCode(rt_ret, ERROR_MODULE_RUNTIME, JOBSUBSTATE_GRAPH_EXEC);
  2518. continue);
  2519. GELOGI("rtModelExecute end");
  2520. GE_IF_BOOL_EXEC(model->is_first_execute_, GE_TIMESTAMP_EVENT_END(rtModelExecute, "GraphExcute::rtModelExecute"));
  2521. GE_TIMESTAMP_START(rtStreamSynchronize);
  2522. GELOGI("rtStreamSynchronize start.");
  2523. rt_ret = rtStreamSynchronize(model->rt_model_stream_);
  2524. if (rt_ret == RT_ERROR_END_OF_SEQUENCE) {
  2525. seq_end_flag = true;
  2526. }
  2527. GE_IF_BOOL_EXEC(
  2528. rt_ret != RT_ERROR_NONE, rslt_flg = false; GELOGI("seq_end_flg: %d", seq_end_flag);
  2529. (void)model->ReturnResult(current_data.index, false, seq_end_flag,
  2530. data_wrapper->GetOutput()); // [No need to check value]
  2531. CsaInteract::GetInstance().StoreInternalErrorCode(rt_ret, ERROR_MODULE_RUNTIME, JOBSUBSTATE_GRAPH_EXEC);
  2532. continue);
  2533. GELOGI("rtStreamSynchronize end.");
  2534. GE_IF_BOOL_EXEC(model->is_first_execute_,
  2535. GE_TIMESTAMP_EVENT_END(rtStreamSynchronize, "GraphExcute::Wait for rtStreamSynchronize"));
  2536. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), model->SetProfileTime(MODEL_INFER_END));
  2537. }
  2538. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(),
  2539. model->SetProfileTime(MODEL_AFTER_PROC_START));
  2540. GE_TIMESTAMP_START(ReturnResult3);
  2541. // copy output data from device to host
  2542. GE_IF_BOOL_EXEC(!model->output_op_list_.empty(),
  2543. (void)model->ReturnResult(current_data.index, rslt_flg, false, data_wrapper->GetOutput()))
  2544. // copy output data from device to host for variable graph
  2545. GE_IF_BOOL_EXEC(model->output_op_list_.empty(), (void)model->ReturnNoOutput(current_data.index));
  2546. GE_IF_BOOL_EXEC(model->is_first_execute_,
  2547. GE_TIMESTAMP_EVENT_END(ReturnResult3, "GraphExcute::CopyDataFromDeviceToHost"));
  2548. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(),
  2549. model->SetProfileTime(MODEL_AFTER_PROC_END));
  2550. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), (void)model->SinkTimeProfile(current_data));
  2551. model->iterator_count_++;
  2552. model->is_first_execute_ = false;
  2553. GELOGI("run iterator count is %lu", model->iterator_count_);
  2554. }
  2555. CsaInteract::GetInstance().WriteInternalErrorCode();
  2556. GELOGI("Model run end, model id:%u", model->model_id_);
  2557. return nullptr;
  2558. }
  2559. ///
  2560. /// @ingroup ge
  2561. /// @brief call API provided by data inputer to destroy thread
  2562. /// @param [in] no
  2563. /// @return Status Destroy result
  2564. /// @author
  2565. ///
  2566. Status DavinciModel::DestroyThread() {
  2567. GE_CHK_BOOL_RET_STATUS(data_inputer_ != nullptr, INTERNAL_ERROR, "data_inputer_ is nullptr.");
  2568. run_flg_ = false;
  2569. data_inputer_->Stop();
  2570. if (thread_id_.joinable()) {
  2571. thread_id_.join();
  2572. }
  2573. return SUCCESS;
  2574. }
  2575. ///
  2576. /// @ingroup ge
  2577. /// @brief create model std::thread,
  2578. /// @brief start to execute Model
  2579. /// @param [in] no
  2580. /// @return Status create model thread and execute result
  2581. /// @author
  2582. ///
  2583. Status DavinciModel::ModelRunStart() {
  2584. GE_CHK_BOOL_RET_STATUS(data_inputer_ != nullptr, INTERNAL_ERROR, "data_inputer_ is nullptr.");
  2585. LockRunFlg();
  2586. GE_MAKE_GUARD(tmp_lock, [&] { UnlockRunFlg(); });
  2587. GE_CHK_BOOL_RET_STATUS(!run_flg_, INTERNAL_ERROR, "Model already started.");
  2588. run_flg_ = true;
  2589. // create stream instance which rt_model_handel is running on
  2590. GE_CHK_RT_RET(rtStreamCreate(&rt_model_stream_, priority_));
  2591. is_inner_model_stream_ = true;
  2592. string opt = "0";
  2593. (void)ge::GetContext().GetOption(OPTION_GE_MAX_DUMP_OP_NUM, opt); // option may not be set up, no need to check value
  2594. int64_t maxDumpOpNum = std::strtol(opt.c_str(), nullptr, kDecimal);
  2595. maxDumpOpNum_ = maxDumpOpNum;
  2596. CREATE_STD_THREAD(thread_id_, DavinciModel::Run, this);
  2597. GELOGI("model tread create success, model id:%u.", model_id_);
  2598. return SUCCESS;
  2599. }
  2600. ///
  2601. /// @ingroup ge
  2602. /// @brief call API provided by data inputer and destroy model Thread
  2603. /// @param [in] no
  2604. /// @return Status Destroy result
  2605. /// @author
  2606. ///
  2607. Status DavinciModel::ModelRunStop() {
  2608. LockRunFlg();
  2609. GE_MAKE_GUARD(tmp_lock, [&] { UnlockRunFlg(); });
  2610. GE_IF_BOOL_EXEC(!run_flg_, return SUCCESS);
  2611. GE_CHK_STATUS_RET(DestroyThread(), "DestoyThead failed.");
  2612. return SUCCESS;
  2613. }
  2614. void DavinciModel::UnbindTaskSinkStream() {
  2615. // unbinding hcom stream
  2616. UnbindHcomStream();
  2617. if (is_stream_list_bind_) {
  2618. for (size_t i = 0; i < stream_list_.size(); i++) {
  2619. // unbind rt_model_handle and streams
  2620. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, stream_list_[i]) != RT_ERROR_NONE,
  2621. "Unbind stream from model failed! Index: %zu", i);
  2622. }
  2623. }
  2624. if (is_inner_model_stream_) {
  2625. if (!input_queue_ids_.empty() || !output_queue_ids_.empty()) {
  2626. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, rt_model_stream_) != RT_ERROR_NONE, "Unbind stream failed!");
  2627. }
  2628. // destroy stream that is bound with rt_model
  2629. GE_LOGW_IF(rtStreamDestroy(rt_model_stream_) != RT_ERROR_NONE, "Destroy stream for rt_model failed.")
  2630. }
  2631. if (is_pure_head_stream_ && rt_head_stream_ != nullptr) {
  2632. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, rt_head_stream_) != RT_ERROR_NONE, "Unbind stream failed!");
  2633. GE_LOGW_IF(rtStreamDestroy(rt_head_stream_) != RT_ERROR_NONE, "Destroy stream for rt_model failed.");
  2634. rt_head_stream_ = nullptr;
  2635. }
  2636. if (rt_entry_stream_ != nullptr) {
  2637. GE_LOGW_IF(rtModelUnbindStream(rt_model_handle_, rt_entry_stream_) != RT_ERROR_NONE, "Unbind stream failed!");
  2638. GE_LOGW_IF(rtStreamDestroy(rt_entry_stream_) != RT_ERROR_NONE, "Destroy stream for rt_model failed.");
  2639. rt_entry_stream_ = nullptr;
  2640. }
  2641. }
  2642. Status DavinciModel::CreateKnownZeroCopyMap(const vector<void *> &inputs, const vector<void *> &outputs) {
  2643. GELOGI("DavinciModel::CreateKnownZeroCopyMap in.");
  2644. if (inputs.size() > data_op_list_.size()) {
  2645. GELOGE(FAILED, "input data addr %u should less than input op number %u.", inputs.size(), data_op_list_.size());
  2646. return FAILED;
  2647. }
  2648. // remove zero copy addr in last iteration
  2649. knonw_input_data_info_.clear();
  2650. knonw_output_data_info_.clear();
  2651. for (size_t i = 0; i < inputs.size(); ++i) {
  2652. const vector<void *> addr_list = ModelUtils::GetOutputDataAddrs(runtime_param_, data_op_list_[i]);
  2653. knonw_input_data_info_[addr_list[kDataIndex]] = inputs[i];
  2654. GELOGI("DavinciModel::CreateKnownZeroCopyMap input %d,v addr %p,p addr %p .", i, addr_list[kDataIndex], inputs[i]);
  2655. }
  2656. if (output_op_list_.size() < kOutputNum) {
  2657. GELOGW("output op num in graph is %u.", output_op_list_.size());
  2658. return SUCCESS;
  2659. }
  2660. const vector<void *> addr_list = ModelUtils::GetInputDataAddrs(runtime_param_, output_op_list_[kDataIndex]);
  2661. for (size_t i = 0; i < addr_list.size() && i < outputs.size(); ++i) {
  2662. knonw_output_data_info_[addr_list[i]] = outputs[i];
  2663. GELOGI("DavinciModel::CreateKnownZeroCopyMap output %d,v addr %p,p addr %p .", i, addr_list[i], outputs[i]);
  2664. }
  2665. GELOGI("DavinciModel::CreateKnownZeroCopyMap success.");
  2666. return SUCCESS;
  2667. }
  2668. Status DavinciModel::UpdateKnownZeroCopyAddr() {
  2669. for (size_t i = 0; i < total_io_addrs_.size(); ++i) {
  2670. auto it_in = knonw_input_data_info_.find(total_io_addrs_[i]);
  2671. if (it_in != knonw_input_data_info_.end()) {
  2672. GELOGI("DavinciModel::UpdateKnownZeroCopyAddr input %d,v addr %p,p addr %p .", i, total_io_addrs_[i],
  2673. knonw_input_data_info_.at(total_io_addrs_[i]));
  2674. total_io_addrs_[i] = knonw_input_data_info_.at(total_io_addrs_[i]);
  2675. }
  2676. auto it_out = knonw_output_data_info_.find(total_io_addrs_[i]);
  2677. if (it_out != knonw_output_data_info_.end()) {
  2678. GELOGI("DavinciModel::UpdateKnownZeroCopyAddr output %d,v addr %p,p addr %p .", i, total_io_addrs_[i],
  2679. knonw_output_data_info_.at(total_io_addrs_[i]));
  2680. total_io_addrs_[i] = knonw_output_data_info_.at(total_io_addrs_[i]);
  2681. }
  2682. }
  2683. GELOGI("DavinciModel::UpdateKnownZeroCopyAddr success.");
  2684. return SUCCESS;
  2685. }
  2686. Status DavinciModel::UpdateKnownNodeArgs(const vector<void *> &inputs, const vector<void *> &outputs) {
  2687. GELOGI("DavinciModel::UpdateKnownNodeArgs in");
  2688. GE_CHK_STATUS_RET(CreateKnownZeroCopyMap(inputs, outputs),
  2689. "DavinciModel::UpdateKnownNodeArgs create map for input/output zero copy.");
  2690. if (!base_addr_not_changed_) {
  2691. total_io_addrs_.clear();
  2692. orig_total_io_addrs_.clear();
  2693. for (size_t task_index = 0; task_index < task_list_.size(); ++task_index) {
  2694. auto &task = task_list_[task_index];
  2695. if (task != nullptr) {
  2696. Status ret = task->UpdateArgs();
  2697. if (ret != SUCCESS) {
  2698. GELOGE(FAILED, "task %d created by davinci model is nullptr.", task_index);
  2699. return FAILED;
  2700. }
  2701. }
  2702. }
  2703. // cache latest iterator io addr
  2704. orig_total_io_addrs_ = total_io_addrs_;
  2705. } else {
  2706. total_io_addrs_ = orig_total_io_addrs_;
  2707. }
  2708. GE_CHK_STATUS_RET(UpdateKnownZeroCopyAddr(), "DavinciModel::UpdateKnownZeroCopyAddr failed.");
  2709. if (total_args_size_ == 0) {
  2710. GELOGW("DavinciModel::UpdateKnownNodeArgs device args %p, dst size %u, pass rtMemcpy.", args_, total_args_size_);
  2711. } else {
  2712. uint32_t total_addr_size = total_io_addrs_.size() * sizeof(uint64_t);
  2713. GELOGI("DavinciModel::UpdateKnownNodeArgs device args %p, dst size %u, src size %u", args_, total_args_size_,
  2714. total_addr_size);
  2715. Status rt_ret =
  2716. rtMemcpy(args_, total_args_size_, total_io_addrs_.data(), total_addr_size, RT_MEMCPY_HOST_TO_DEVICE);
  2717. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(rt_ret, "rtMemcpy error, ret: Ox%X", rt_ret); return FAILED;)
  2718. }
  2719. GELOGI("DavinciModel::UpdateKnownNodeArgs success");
  2720. return SUCCESS;
  2721. }
  2722. Status DavinciModel::InitTaskInfo(domi::ModelTaskDef &model_task_def) {
  2723. GELOGI("InitTaskInfo in, task size %zu", model_task_def.task().size());
  2724. task_list_.resize(model_task_def.task_size());
  2725. for (int i = 0; i < model_task_def.task_size(); ++i) {
  2726. // dynamic shape will create task_list_ before
  2727. const domi::TaskDef &task = model_task_def.task(i);
  2728. if (this->task_list_[i] == nullptr) {
  2729. task_list_[i] = TaskInfoFactory::Instance().Create(static_cast<rtModelTaskType_t>(task.type()));
  2730. }
  2731. GE_CHECK_NOTNULL(task_list_[i]);
  2732. Status ret = task_list_[i]->Init(task, this);
  2733. if (ret != SUCCESS) {
  2734. GELOGE(ret, "Task index %d init failed.", i);
  2735. return ret;
  2736. }
  2737. }
  2738. GELOGI("InitTaskInfo out");
  2739. return SUCCESS;
  2740. }
  2741. Status DavinciModel::MallocKnownArgs() {
  2742. GELOGI("DavinciModel::MallocKnownArgs in");
  2743. const auto &model_task_def = ge_model_->GetModelTaskDefPtr();
  2744. if (model_task_def->task_size() == 0) {
  2745. GELOGW("DavinciModel::MallocKnownArgs davincimodel has no task info.");
  2746. return SUCCESS;
  2747. }
  2748. task_list_.resize(model_task_def->task_size());
  2749. for (int32_t i = 0; i < model_task_def->task_size(); ++i) {
  2750. const domi::TaskDef &taskdef = model_task_def->task(i);
  2751. task_list_[i] = TaskInfoFactory::Instance().Create(static_cast<rtModelTaskType_t>(taskdef.type()));
  2752. GE_CHECK_NOTNULL(task_list_[i]);
  2753. Status ret = task_list_[i]->CalculateArgs(taskdef, this);
  2754. if (ret != SUCCESS) {
  2755. GELOGE(ret, "TaskInfo CalculateArgs failed.");
  2756. return ret;
  2757. }
  2758. }
  2759. // malloc args memory
  2760. if (total_args_size_ == 0) {
  2761. GELOGW("DavinciModel::MallocKnownArgs total_args_size_ equals to zero.");
  2762. return SUCCESS;
  2763. }
  2764. rtError_t rt_ret = rtMalloc(&args_, total_args_size_, RT_MEMORY_HBM);
  2765. if (rt_ret != RT_ERROR_NONE) {
  2766. GELOGE(RT_FAILED, "Call rtMalloc failed, ret: 0x%X", rt_ret);
  2767. return RT_ERROR_TO_GE_STATUS(rt_ret);
  2768. }
  2769. // malloc fixed addr memory, eg: rts op
  2770. if (total_fixed_addr_size_ != 0) {
  2771. GELOGI("Begin to allocate fixed addr.");
  2772. rt_ret = rtMalloc(&fixed_addrs_, total_fixed_addr_size_, RT_MEMORY_HBM);
  2773. if (rt_ret != RT_ERROR_NONE) {
  2774. GELOGE(RT_FAILED, "Call rtMalloc failed, ret: 0x%X", rt_ret);
  2775. return RT_ERROR_TO_GE_STATUS(rt_ret);
  2776. }
  2777. }
  2778. GELOGI("DavinciModel::MallocKnownArgs success, total args size %u. total fixed addr size %ld", total_args_size_,
  2779. total_fixed_addr_size_);
  2780. return SUCCESS;
  2781. }
  2782. Status DavinciModel::DistributeTask() {
  2783. GELOGI("do Distribute.");
  2784. for (auto &task : cpu_task_list_) {
  2785. if (task == nullptr) {
  2786. GELOGW("task is null");
  2787. continue;
  2788. }
  2789. GE_CHK_STATUS_RET(task->Distribute());
  2790. }
  2791. task_desc_info_.clear();
  2792. bool flag = GetL1FusionEnableOption();
  2793. char *skt_enable_env = std::getenv("SKT_ENABLE");
  2794. int64_t env_flag = (skt_enable_env != nullptr) ? std::strtol(skt_enable_env, nullptr, kDecimal) : 0;
  2795. if (env_flag != 0) {
  2796. flag = true;
  2797. }
  2798. const auto &model_task_def = ge_model_->GetModelTaskDefPtr();
  2799. GELOGI("there are %zu task need to save.", task_list_.size());
  2800. for (size_t task_index = 0; task_index < task_list_.size(); ++task_index) {
  2801. auto &task = task_list_.at(task_index);
  2802. GE_CHK_STATUS_RET(task->Distribute(), "Task[%zu] distribute fail", task_index);
  2803. // for data dump
  2804. auto op_index = std::max(model_task_def->task(task_index).kernel().context().op_index(),
  2805. model_task_def->task(task_index).kernel_ex().op_index());
  2806. OpDescPtr op = GetOpByIndex(op_index);
  2807. GE_CHECK_NOTNULL(op);
  2808. SaveDumpOpInfo(runtime_param_, op, task->GetTaskID(), task->GetStreamId());
  2809. if (reinterpret_cast<void *>(task->GetDumpArgs()) != nullptr) {
  2810. bool call_dump = GetDumpProperties().IsLayerNeedDump(name_, om_name_, op->GetName()) && task->CallSaveDumpInfo();
  2811. if (call_dump || is_op_debug_reg_) {
  2812. SaveDumpTask(task->GetTaskID(), task->GetStreamId(), op, task->GetDumpArgs());
  2813. }
  2814. }
  2815. // Load task info for profiling
  2816. TaskDescInfo task_desc_info;
  2817. if (!om_name_.empty()) {
  2818. task_desc_info.model_name = om_name_;
  2819. } else {
  2820. task_desc_info.model_name = name_;
  2821. }
  2822. task_desc_info.op_name = op->GetName();
  2823. task_desc_info.block_dim = model_task_def->task(task_index).kernel().block_dim();
  2824. task_desc_info.task_id = task->GetTaskID();
  2825. task_desc_info.stream_id = task->GetStreamId();
  2826. task_desc_info_.emplace_back(task_desc_info);
  2827. if (flag) {
  2828. if (task->GetSktTaskID() != 0xFFFFFFFF) {
  2829. TaskDescInfo task_desc_info;
  2830. string op_name = "super_kernel_" + to_string(task_index);
  2831. task_desc_info.op_name = op_name;
  2832. task_desc_info.task_id = task->GetSktTaskID();
  2833. task_desc_info_.emplace_back(task_desc_info);
  2834. }
  2835. }
  2836. }
  2837. // launch dump kernel to aicpu
  2838. GE_CHK_STATUS_RET(data_dumper_.LoadDumpInfo(), "Load dump info failed.");
  2839. return SUCCESS;
  2840. }
  2841. void DavinciModel::SetEndGraphId(uint32_t task_id, uint32_t stream_id) {
  2842. auto all_dump_model = GetDumpProperties().GetAllDumpModel();
  2843. bool findByOmName = all_dump_model.find(om_name_) != all_dump_model.end();
  2844. bool findByModelName = all_dump_model.find(name_) != all_dump_model.end();
  2845. if (all_dump_model.find(ge::DUMP_ALL_MODEL) != all_dump_model.end() || findByOmName || findByModelName) {
  2846. GELOGI("start save end_graph_info to dumper, task_id is %u, stream_id is %u", task_id, stream_id);
  2847. data_dumper_.SaveEndGraphId(task_id, stream_id);
  2848. }
  2849. }
  2850. ///
  2851. /// @ingroup ge
  2852. /// @brief Set copy only for No task feed NetOutput address.
  2853. /// @return None.
  2854. ///
  2855. void DavinciModel::SetCopyOnlyOutput() {
  2856. for (const auto &output_outside_addrs : new_output_outside_addrs_) {
  2857. ZeroCopyOffset output_outside = output_outside_addrs.second;
  2858. for (uint32_t out_count = 0; out_count < output_outside.GetAddrCount(); ++out_count) {
  2859. auto &addrs_mapping_list = output_outside.GetOutsideAddrs();
  2860. std::map<const void *, std::vector<void *>> virtual_args_addrs = addrs_mapping_list[out_count];
  2861. for (const auto &virtual_args_addr : virtual_args_addrs) {
  2862. const auto &args_addrs = virtual_args_addr.second;
  2863. if (args_addrs.empty()) { // No task feed Output addr, Need copy directly.
  2864. GELOGI("[ZCPY] just copy %p to netoutput.", virtual_args_addr.first);
  2865. copy_only_addrs_.insert(virtual_args_addr.first);
  2866. }
  2867. }
  2868. }
  2869. }
  2870. }
  2871. ///
  2872. /// @ingroup ge
  2873. /// @brief Set disabled input zero copy addr.
  2874. /// @param [in] const void *addr: address of task
  2875. /// @return None.
  2876. ///
  2877. void DavinciModel::DisableZeroCopy(const void *addr) {
  2878. if (real_virtual_addrs_.find(addr) == real_virtual_addrs_.end()) {
  2879. return;
  2880. }
  2881. // Data link to RTS Op directly.
  2882. std::lock_guard<std::mutex> lock(outside_addrs_mutex_);
  2883. GELOGI("[ZCPY] disable zero copy of %p.", addr);
  2884. copy_only_addrs_.insert(addr);
  2885. }
  2886. ///
  2887. /// @ingroup ge
  2888. /// @brief Save outside address used info for ZeroCopy.
  2889. /// @param [in] const OpDescPtr &op_desc: current op desc
  2890. /// @param [in] const std::vector<void *> &outside_addrs: address of task
  2891. /// @param [in] const void *info: task args
  2892. /// @param [in] const char *args: task args
  2893. /// @param [in] size_t size: size of task args
  2894. /// @param [in] size_t offset: offset of task args
  2895. /// @return None.
  2896. ///
  2897. void DavinciModel::SetZeroCopyAddr(const OpDescPtr &op_desc, const std::vector<void *> &outside_addrs, const void *info,
  2898. void *args, size_t size, size_t offset) {
  2899. // Internal call has ensured that op_desc is not nullptr
  2900. GELOGD("[ZCPY] SetZeroCopyAddr for %s.", op_desc->GetName().c_str());
  2901. size_t nums = outside_addrs.size();
  2902. ZeroCopyTask zero_copy_task(op_desc->GetName(), static_cast<uint8_t *>(args), size);
  2903. for (size_t i = 0; i < nums; ++i) {
  2904. std::lock_guard<std::mutex> lock(outside_addrs_mutex_);
  2905. for (auto &input_outside_addrs : new_input_outside_addrs_) {
  2906. ZeroCopyOffset &input_outside = input_outside_addrs.second;
  2907. bool ret = input_outside.SetOutsideAddrsValue(zero_copy_task, outside_addrs[i], args, offset + i * kAddrLen);
  2908. if (ret) {
  2909. void *args_val = static_cast<uint8_t *>(args) + offset + i * kAddrLen;
  2910. SetBatchLabelAddr(op_desc, reinterpret_cast<uintptr_t>(args_val));
  2911. }
  2912. }
  2913. for (auto &output_outside_addrs : new_output_outside_addrs_) {
  2914. ZeroCopyOffset &output_outside = output_outside_addrs.second;
  2915. bool ret = output_outside.SetOutsideAddrsValue(zero_copy_task, outside_addrs[i], args, offset + i * kAddrLen);
  2916. if (ret) {
  2917. void *args_val = static_cast<uint8_t *>(args) + offset + i * kAddrLen;
  2918. SetBatchLabelAddr(op_desc, reinterpret_cast<uintptr_t>(args_val));
  2919. }
  2920. }
  2921. }
  2922. auto it = zero_copy_op_id_batch_label_.find(op_desc->GetId());
  2923. if (it == zero_copy_op_id_batch_label_.end()) {
  2924. zero_copy_task.SetBatchLabel(kDefaultBatchLable);
  2925. } else {
  2926. zero_copy_task.SetBatchLabel(it->second);
  2927. }
  2928. std::lock_guard<std::mutex> lock(outside_addrs_mutex_);
  2929. if (zero_copy_task.IsTaskArgsSet()) {
  2930. zero_copy_task.SetOriginalArgs(info, offset + nums * kAddrLen);
  2931. zero_copy_tasks_.emplace_back(zero_copy_task);
  2932. }
  2933. }
  2934. void DavinciModel::SetBatchLabelAddr(const OpDescPtr &op_desc, uintptr_t addr) {
  2935. // Establish a mapping between batch label and zero copy address for multi-batch scenes
  2936. auto it = zero_copy_op_id_batch_label_.find(op_desc->GetId());
  2937. if (it == zero_copy_op_id_batch_label_.end()) {
  2938. return;
  2939. }
  2940. const string &batch_label = it->second;
  2941. auto iter = zero_copy_batch_label_addrs_.find(batch_label);
  2942. if (iter != zero_copy_batch_label_addrs_.end()) {
  2943. iter->second.insert(addr);
  2944. GELOGD("[ZCPY] Set zero copy batch label and addrs success, batch label: %s, op name:%s.", batch_label.c_str(),
  2945. op_desc->GetName().c_str());
  2946. } else {
  2947. set<uintptr_t> addrs = {addr};
  2948. zero_copy_batch_label_addrs_.emplace(pair<string, set<uintptr_t>>(batch_label, addrs));
  2949. GELOGD("[ZCPY] New added zero copy batch label and addrs success, batch label: %s, op name:%s.",
  2950. batch_label.c_str(), op_desc->GetName().c_str());
  2951. }
  2952. }
  2953. ///
  2954. /// @ingroup ge
  2955. /// @brief Copy Check input size and model op size.
  2956. /// @param [in] const int64_t &input_size: input size.
  2957. /// @param [in] const int64_t &op_size: model op size.
  2958. /// @param [in] is_dynamic: dynamic batch input flag.
  2959. /// @return true if success
  2960. ///
  2961. bool DavinciModel::CheckInputAndModelSize(const int64_t &input_size, const int64_t &op_size, bool is_dynamic) {
  2962. if (is_dynamic) { // dynamic is max size.
  2963. GELOGI("No need to check input and model size.");
  2964. return true;
  2965. }
  2966. if (input_size > op_size) {
  2967. GELOGW(
  2968. "Input size [%u] is bigger than om size need [%u], "
  2969. "MAY cause inference result ERROR, please check model input",
  2970. input_size, op_size);
  2971. }
  2972. bool is_dynamic_aipp = false;
  2973. for (const auto &op_desc : data_op_list_) {
  2974. if (op_desc->GetType() == AIPP_DATA_TYPE) {
  2975. GELOGI("This is dynamic aipp model.");
  2976. is_dynamic_aipp = true;
  2977. break;
  2978. }
  2979. }
  2980. if (is_dynamic_aipp) {
  2981. GELOGI("This is dynamic aipp model, no need to judge smaller input size");
  2982. return true;
  2983. }
  2984. // Judge overflow first
  2985. if (input_size > (INT64_MAX - kDataMemAlignSizeCompare)) {
  2986. GELOGI("The Input size [%ld] is smaller than model size [%ld] and is in the range of 64 bytes", input_size,
  2987. op_size);
  2988. return true;
  2989. }
  2990. // The input and model input size can not be exactly equal because user input is not definite.
  2991. if ((input_size + kDataMemAlignSizeCompare) < op_size) {
  2992. GELOGE(FAILED, "Input size [%ld] can not be smaller than op size [%ld] after 64-byte alignment", input_size,
  2993. op_size);
  2994. return false;
  2995. }
  2996. return true;
  2997. }
  2998. ///
  2999. /// @ingroup ge
  3000. /// @brief Copy Inputs and Outputs addr to model for direct use.
  3001. /// @param [in] const InputData &input_data: model input data.
  3002. /// @param [in] OutputData &output_data: model output data.
  3003. /// @param [in] bool is_dynamic_input: whether is dynamic input, true: is dynamic input; false: not is dynamic input
  3004. /// @return SUCCESS handle successfully / PARAM_INVALID for failed
  3005. ///
  3006. Status DavinciModel::CopyModelData(const InputData &input_data, OutputData &output_data, bool is_dynamic) {
  3007. if (UpdateIoTaskArgs(new_input_data_info_, true, input_data.blobs, is_dynamic, input_data.batch_label) != SUCCESS) {
  3008. GELOGE(PARAM_INVALID, "[ZCPY] Update input data to model failed.");
  3009. return PARAM_INVALID;
  3010. }
  3011. if (UpdateIoTaskArgs(new_output_data_info_, false, output_data.blobs, is_dynamic, input_data.batch_label) !=
  3012. SUCCESS) {
  3013. GELOGE(PARAM_INVALID, "[ZCPY] Update output data to model failed.");
  3014. return PARAM_INVALID;
  3015. }
  3016. for (ZeroCopyTask &task : zero_copy_tasks_) {
  3017. GE_CHK_STATUS_RET(task.DistributeParam(is_async_mode_, rt_model_stream_), "[ZCPY] Update args failed.");
  3018. }
  3019. output_data.index = input_data.index;
  3020. output_data.model_id = model_id_;
  3021. return SUCCESS;
  3022. }
  3023. ///
  3024. /// @ingroup ge
  3025. /// @brief Copy Data addr to model for direct use.
  3026. /// @param [in] data_info: model memory addr/size map { data_index, { tensor_size, tensor_addr } }.
  3027. /// @param [in] is_input: input data or output data
  3028. /// @param [in] blobs: user input/output data list.
  3029. /// @param [in] is_dynamic: whether is dynamic input, true: is dynamic input; false: not is dynamic input
  3030. /// @param [in] batch_label: batch label for multi-batch scenes
  3031. /// @return SUCCESS handle successfully / others handle failed
  3032. ///
  3033. Status DavinciModel::UpdateIoTaskArgs(const std::map<uint32_t, ZeroCopyOffset> &data_info, bool is_input,
  3034. const vector<DataBuffer> &blobs, bool is_dynamic, const string &batch_label) {
  3035. string input_or_output = "input";
  3036. is_input ? input_or_output = "input" : input_or_output = "output";
  3037. if (blobs.size() != data_info.size()) {
  3038. GELOGE(FAILED, "Verify %s data num failed: model requires %zu, but user actually feeds %zu",
  3039. input_or_output.c_str(), data_info.size(), blobs.size());
  3040. return FAILED;
  3041. }
  3042. for (const auto &data : data_info) {
  3043. if (data.first >= blobs.size()) { // check data index.
  3044. GELOGE(FAILED, "Verify %s data num failed: can not find No.%zu data, because user only feeds %zu",
  3045. input_or_output.c_str(), data.first, blobs.size());
  3046. return FAILED;
  3047. }
  3048. const DataBuffer &buffer = blobs[data.first]; // index of data.
  3049. if (buffer.data == nullptr) {
  3050. GELOGE(FAILED, "data_buf.data is nullptr, index=%u", data.first);
  3051. return FAILED;
  3052. }
  3053. if (!CheckInputAndModelSize(buffer.length, data.second.GetDataSize(), is_dynamic)) {
  3054. GELOGE(FAILED, "Check input size and model size failed");
  3055. return FAILED;
  3056. }
  3057. void *basic_addr = data.second.GetBasicAddr();
  3058. uint64_t data_size = data.second.GetDataSize();
  3059. if (copy_only_addrs_.count(basic_addr) > 0) {
  3060. if (is_input) {
  3061. GELOGI("[IMAS] Find addr %p need direct copy from user malloc input %p", basic_addr, buffer.data);
  3062. if (rtMemcpy(basic_addr, data_size, buffer.data, buffer.length, RT_MEMCPY_DEVICE_TO_DEVICE) != RT_ERROR_NONE) {
  3063. GELOGE(FAILED, "Non-zero copy data node copy failed");
  3064. return FAILED;
  3065. }
  3066. }
  3067. GELOGI("No need to exeucte zero copy task because this addr %p need direct copy.", basic_addr);
  3068. continue;
  3069. }
  3070. for (size_t count = 0; count < data.second.GetDataCount(); ++count) {
  3071. int64_t size = data.second.GetDataInfo().at(count).first;
  3072. void *addr = data.second.GetDataInfo().at(count).second;
  3073. void *buffer_addr = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(buffer.data) +
  3074. data.second.GetRelativeOffset().at(count));
  3075. GELOGI("[ZCPY] Copy %s blobs_index %u, virtual_addr: %p, size: %ld, user_data_addr: %p", input_or_output.c_str(),
  3076. data.first, addr, size, buffer_addr);
  3077. // For input data, just copy for rts task.
  3078. for (ZeroCopyTask &task : zero_copy_tasks_) {
  3079. if (task.GetBatchLabel() != kDefaultBatchLable && task.GetBatchLabel() != batch_label) {
  3080. continue;
  3081. }
  3082. uintptr_t addr_val = reinterpret_cast<uintptr_t>(addr);
  3083. if (task.UpdateTaskParam(addr_val, buffer_addr, zero_copy_batch_label_addrs_, batch_label) != SUCCESS) {
  3084. return FAILED;
  3085. }
  3086. }
  3087. }
  3088. }
  3089. return SUCCESS;
  3090. }
  3091. ///
  3092. /// @ingroup ge
  3093. /// @brief get unique identification for op when load two or more models
  3094. /// @param [in] const OpDescPtr: current op.
  3095. /// @param [in] string identification: unique identification for current op.
  3096. /// @return SUCCESS handle successfully / others handle failed
  3097. ///
  3098. void DavinciModel::GetUniqueId(const OpDescPtr &op_desc, std::string &unique_identification) {
  3099. std::string session_graph_id;
  3100. GE_IF_BOOL_EXEC(AttrUtils::GetStr(*op_desc, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id),
  3101. GELOGD("Get original type of session_graph_id."));
  3102. if (session_graph_id.empty()) {
  3103. return;
  3104. } else if (session_graph_id.find("-1") != string::npos) {
  3105. unique_identification = session_graph_id + "_" + to_string(model_id_);
  3106. } else {
  3107. unique_identification = session_graph_id;
  3108. }
  3109. }
  3110. ///
  3111. /// @ingroup ge
  3112. /// @brief For TVM Op, avoid Addr Reuse.
  3113. /// @return void*
  3114. ///
  3115. const char *DavinciModel::GetRegisterStub(const string &binfile, const string &session_graph_id) {
  3116. string binfile_key;
  3117. if (session_graph_id.empty()) {
  3118. binfile_key = binfile;
  3119. } else {
  3120. binfile_key = session_graph_id + "_" + binfile;
  3121. }
  3122. auto it = tvm_bin_kernel_.find(binfile_key);
  3123. if (it != tvm_bin_kernel_.end()) {
  3124. return it->c_str();
  3125. } else {
  3126. it = tvm_bin_kernel_.insert(tvm_bin_kernel_.end(), binfile_key);
  3127. return it->c_str();
  3128. }
  3129. }
  3130. ///
  3131. /// @ingroup ge
  3132. /// @brief Constant Op Init.
  3133. /// @return Status
  3134. ///
  3135. Status DavinciModel::InitConstant(const OpDescPtr &op_desc) {
  3136. auto v_weights = ModelUtils::GetWeights(op_desc);
  3137. auto v_output_size = ModelUtils::GetOutputSize(op_desc);
  3138. auto v_output_addr = ModelUtils::GetOutputDataAddrs(runtime_param_, op_desc);
  3139. GE_IF_BOOL_EXEC(v_weights.empty() || v_output_size.empty() || v_output_addr.empty(),
  3140. GELOGE(PARAM_INVALID, "const op:%s not set output", op_desc->GetName().c_str());
  3141. return PARAM_INVALID;);
  3142. GeTensor *tensor = const_cast<GeTensor *>(v_weights[0].get());
  3143. GE_IF_BOOL_EXEC(static_cast<size_t>(v_output_size[0]) < tensor->GetData().size(),
  3144. GELOGE(PARAM_INVALID, "output size:%u less than weight data size:%zu", v_output_size[0],
  3145. tensor->GetData().size());
  3146. return PARAM_INVALID;);
  3147. GE_IF_BOOL_EXEC(tensor->GetData().size() == 0, GELOGW("const op:%s has no weight data.", op_desc->GetName().c_str());
  3148. return SUCCESS;);
  3149. auto desc = tensor->GetTensorDesc();
  3150. if (desc.GetDataType() == DT_STRING) {
  3151. GeShape tensor_shape = desc.GetShape();
  3152. /// if tensor is a scaler, it's shape size if zero, according ge_tensor.cc.
  3153. /// the logic of GetShapeSize is wrong, the scaler tensor's GetShapeSize is zero
  3154. /// and that of unknown shape is zero too.
  3155. /// unknown shape will not appear here, so we can use zero judge a tensor is scaler or not
  3156. int64_t elem_num = tensor_shape.GetShapeSize();
  3157. if (elem_num == 0 && tensor_shape.GetDims().size() == 0) {
  3158. elem_num = 1;
  3159. }
  3160. uint64_t *buff = reinterpret_cast<uint64_t *>(tensor->MutableData().data());
  3161. GE_CHK_BOOL_RET_STATUS(ge::CheckInt64Uint32MulOverflow(elem_num, kBytes) == SUCCESS, FAILED,
  3162. "Shape size is invalid");
  3163. uint64_t offset = static_cast<uint64_t>(elem_num * kBytes);
  3164. uint64_t hbm_raw_data_base_addr =
  3165. reinterpret_cast<uint64_t>(reinterpret_cast<uintptr_t>(v_output_addr[0])) + offset;
  3166. for (int64_t i = elem_num - 1; i >= 0; --i) {
  3167. buff[i] = hbm_raw_data_base_addr + (buff[i] - buff[0]);
  3168. }
  3169. }
  3170. GELOGI("[IMAS]InitConstant memcpy graph_%u type[V] name[%s] output[%d] memaddr[%p] mem_size[%u] datasize[%zu]",
  3171. runtime_param_.graph_id, op_desc->GetName().c_str(), 0, v_output_addr[0], v_output_size[0],
  3172. tensor->GetData().size());
  3173. GE_CHK_RT_RET(rtMemcpy(v_output_addr[0], v_output_size[0], tensor->GetData().data(), tensor->GetData().size(),
  3174. RT_MEMCPY_HOST_TO_DEVICE));
  3175. return SUCCESS;
  3176. }
  3177. ///
  3178. /// @ingroup ge
  3179. /// @brief TVM Op Init.
  3180. /// @return Status
  3181. ///
  3182. Status DavinciModel::InitTbeHandle(const OpDescPtr &op_desc) {
  3183. auto kernel = ge_model_->GetTBEKernelStore().FindKernel(op_desc->GetName());
  3184. auto tbe_kernel = (kernel != nullptr) ? kernel : op_desc->TryGetExtAttr(OP_EXTATTR_NAME_TBE_KERNEL, TBEKernelPtr());
  3185. if (tbe_kernel == nullptr) {
  3186. GELOGE(INTERNAL_ERROR, "TBE: %s can't find tvm bin file!", op_desc->GetName().c_str());
  3187. return INTERNAL_ERROR;
  3188. }
  3189. std::string session_graph_model_id;
  3190. GetUniqueId(op_desc, session_graph_model_id);
  3191. const char *bin_file_key = GetRegisterStub(op_desc->GetName(), session_graph_model_id); // from set, always valid.
  3192. TBEHandleStore &kernel_store = TBEHandleStore::GetInstance();
  3193. std::lock_guard<std::mutex> lock(tvm_bin_mutex_);
  3194. if (rtQueryFunctionRegistered(bin_file_key) != RT_ERROR_NONE) {
  3195. void *bin_handle = nullptr;
  3196. if (!kernel_store.FindTBEHandle(bin_file_key, bin_handle)) {
  3197. GELOGI("TBE: can't find the kernel_name[%s] in HandleMap", bin_file_key);
  3198. rtDevBinary_t binary;
  3199. std::string json_string;
  3200. GE_IF_BOOL_EXEC(AttrUtils::GetStr(op_desc, TVM_ATTR_NAME_MAGIC, json_string),
  3201. GELOGI("Get original type of session_graph_id."));
  3202. if (json_string == "RT_DEV_BINARY_MAGIC_ELF_AICPU") {
  3203. binary.magic = RT_DEV_BINARY_MAGIC_ELF_AICPU;
  3204. } else if (json_string == "RT_DEV_BINARY_MAGIC_ELF") {
  3205. binary.magic = RT_DEV_BINARY_MAGIC_ELF;
  3206. } else if (json_string == "RT_DEV_BINARY_MAGIC_ELF_AIVEC") {
  3207. binary.magic = RT_DEV_BINARY_MAGIC_ELF_AIVEC;
  3208. } else {
  3209. GELOGE(PARAM_INVALID, "TBE: Invalid parameter magic number! json: %s", json_string.c_str());
  3210. return PARAM_INVALID;
  3211. }
  3212. binary.version = 0;
  3213. binary.data = tbe_kernel->GetBinData();
  3214. binary.length = tbe_kernel->GetBinDataSize();
  3215. GELOGI("TBE: binary.length: %lu", binary.length);
  3216. GE_CHK_RT_RET(rtDevBinaryRegister(&binary, &bin_handle));
  3217. std::string meta_data;
  3218. GE_IF_BOOL_EXEC(AttrUtils::GetStr(op_desc, TVM_ATTR_NAME_METADATA, meta_data),
  3219. GELOGI("Get original type of json_string"));
  3220. GELOGI("TBE: meta data: %s", meta_data.empty() ? "null" : meta_data.c_str());
  3221. GE_IF_BOOL_EXEC(!meta_data.empty(), GE_CHK_RT_RET(rtMetadataRegister(bin_handle, meta_data.c_str())));
  3222. kernel_store.StoreTBEHandle(bin_file_key, bin_handle, tbe_kernel);
  3223. } else {
  3224. GELOGI("TBE: find the kernel_name[%s] in HandleMap", bin_file_key);
  3225. kernel_store.ReferTBEHandle(bin_file_key);
  3226. }
  3227. std::string kernel_name;
  3228. GE_IF_BOOL_EXEC(AttrUtils::GetStr(op_desc, op_desc->GetName() + "_kernelname", kernel_name),
  3229. GELOGI("Get original type of kernel_name"));
  3230. GELOGI("TBE: binfile_key=%s, kernel_name=%s", bin_file_key, kernel_name.c_str());
  3231. GE_CHK_RT_RET(rtFunctionRegister(bin_handle, bin_file_key, bin_file_key, kernel_name.c_str(), 0));
  3232. used_tbe_handle_map_[bin_file_key] = 1; // Init used num to 1.
  3233. return SUCCESS;
  3234. }
  3235. // Kernel registed, Increase used num in store.
  3236. StoreTbeHandle(bin_file_key);
  3237. return SUCCESS;
  3238. }
  3239. void DavinciModel::StoreTbeHandle(const std::string &handle_key) {
  3240. // Online mode FE may call rtFunctionRegister.
  3241. TBEHandleStore &kernel_store = TBEHandleStore::GetInstance();
  3242. auto it = used_tbe_handle_map_.find(handle_key);
  3243. if (it != used_tbe_handle_map_.end()) {
  3244. // GE registered, increase reference.
  3245. kernel_store.ReferTBEHandle(handle_key);
  3246. it->second++;
  3247. return;
  3248. }
  3249. void *bin_handle = nullptr;
  3250. if (kernel_store.FindTBEHandle(handle_key, bin_handle)) {
  3251. // GE registered, increase reference.
  3252. used_tbe_handle_map_[handle_key] = 1; // Init used num to 1.
  3253. kernel_store.ReferTBEHandle(handle_key);
  3254. }
  3255. }
  3256. void DavinciModel::CleanTbeHandle() {
  3257. TBEHandleStore &kernel_store = TBEHandleStore::GetInstance();
  3258. kernel_store.EraseTBEHandle(used_tbe_handle_map_);
  3259. used_tbe_handle_map_.clear();
  3260. tvm_bin_kernel_.clear();
  3261. }
  3262. ///
  3263. /// @ingroup ge
  3264. /// @brief insert active_stream_indication_
  3265. /// @return Status
  3266. ///
  3267. Status DavinciModel::InitStreamActive(const OpDescPtr &op_desc) {
  3268. if (op_desc->HasAttr(ATTR_NAME_SWITCH_BRANCH_NODE_LABEL)) {
  3269. std::vector<uint32_t> active_stream_list;
  3270. GE_CHK_BOOL_EXEC(AttrUtils::GetListInt(op_desc, ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list),
  3271. return INTERNAL_ERROR, "StreamActiveOp get attr ACTIVE_STREAM failed.");
  3272. for (size_t j = 0; j < active_stream_list.size(); ++j) {
  3273. active_stream_indication_.insert(active_stream_list[j]);
  3274. GELOGI("flowctrl_op_index_map node:%s, active_stream_id=%u.", op_desc->GetName().c_str(), active_stream_list[j]);
  3275. }
  3276. }
  3277. return SUCCESS;
  3278. }
  3279. Status DavinciModel::InitStreamSwitch(const OpDescPtr &op_desc) {
  3280. std::vector<uint32_t> active_stream_list;
  3281. GE_LOGI_IF(!ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list),
  3282. "GetInt ACTIVE_STREAM_LIST failed.");
  3283. if (active_stream_list.size() != kTrueBranchStreamNum) {
  3284. GELOGE(INTERNAL_ERROR, "Stream num of switch true branch must be %u.", kTrueBranchStreamNum);
  3285. return INTERNAL_ERROR;
  3286. }
  3287. uint32_t true_stream_id = active_stream_list.front();
  3288. active_stream_indication_.insert(true_stream_id);
  3289. GELOGI("flowctrl_op_index_map node:%s, true_stream_id=%u.", op_desc->GetName().c_str(), true_stream_id);
  3290. return SUCCESS;
  3291. }
  3292. Status DavinciModel::InitStreamSwitchN(const OpDescPtr &op_desc) {
  3293. std::vector<uint32_t> active_stream_list;
  3294. if (!AttrUtils::GetListInt(op_desc, ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list)) {
  3295. GELOGE(INTERNAL_ERROR, "StreamSwitchNOp get attr ACTIVE_STREAM failed.");
  3296. return INTERNAL_ERROR;
  3297. }
  3298. for (size_t j = 0; j < active_stream_list.size(); ++j) {
  3299. active_stream_indication_.insert(active_stream_list[j]);
  3300. GELOGI("StreamSwitchNOp node:%s, active_stream_id=%u.", op_desc->GetName().c_str(), active_stream_list[j]);
  3301. }
  3302. uint32_t batch_num = 0;
  3303. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_BATCH_NUM, batch_num)) {
  3304. GELOGE(FAILED, "Failed to get attr ATTR_NAME_BATCH_NUM, StreamSwitchN: %s.", op_desc->GetName().c_str());
  3305. return FAILED;
  3306. }
  3307. return SetDynamicBatchInfo(op_desc, batch_num);
  3308. }
  3309. Status DavinciModel::SetDynamicBatchInfo(const OpDescPtr &op_desc, uint32_t batch_num) {
  3310. batch_info_.clear();
  3311. combined_batch_info_.clear();
  3312. (void)AttrUtils::GetInt(op_desc, ATTR_DYNAMIC_TYPE, dynamic_type_);
  3313. (void)AttrUtils::GetListStr(op_desc, ATTR_USER_DESIGNEATE_SHAPE_ORDER, user_designate_shape_order_);
  3314. for (uint32_t i = 0; i < batch_num; ++i) {
  3315. std::vector<int64_t> batch_shape;
  3316. const std::string attr_name = ATTR_NAME_PRED_VALUE + "_" + std::to_string(i);
  3317. if (!AttrUtils::GetListInt(op_desc, attr_name, batch_shape)) {
  3318. GELOGE(FAILED, "Get attr ATTR_NAME_PRED_VALUE failed, Node: %s", op_desc->GetName().c_str());
  3319. batch_info_.clear();
  3320. return FAILED;
  3321. }
  3322. batch_info_.emplace_back(batch_shape);
  3323. batch_shape.clear();
  3324. const string attr_combined_batch = ATTR_NAME_COMBINED_BATCH + "_" + std::to_string(i);
  3325. if (AttrUtils::GetListInt(op_desc, attr_combined_batch, batch_shape)) {
  3326. combined_batch_info_.emplace_back(batch_shape);
  3327. }
  3328. }
  3329. return SUCCESS;
  3330. }
  3331. Status DavinciModel::InitCase(const OpDescPtr &op_desc) {
  3332. uint32_t batch_num = 0;
  3333. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_BATCH_NUM, batch_num)) {
  3334. GELOGI("Not multi-batch Node: %s", op_desc->GetName().c_str());
  3335. return SUCCESS;
  3336. }
  3337. return SetDynamicBatchInfo(op_desc, batch_num);
  3338. }
  3339. bool DavinciModel::IsBroadCastOpData(const ge::NodePtr &var_node) {
  3340. for (auto out_anchor : var_node->GetAllOutDataAnchors()) {
  3341. GE_RT_FALSE_CHECK_NOTNULL(out_anchor);
  3342. for (auto in_anchor : out_anchor->GetPeerInDataAnchors()) {
  3343. GE_RT_FALSE_CHECK_NOTNULL(in_anchor);
  3344. ge::NodePtr dst_node = in_anchor->GetOwnerNode();
  3345. GE_RT_FALSE_CHECK_NOTNULL(dst_node);
  3346. if (dst_node->GetType() == HCOMBROADCAST || dst_node->GetType() == HVDCALLBACKBROADCAST) {
  3347. return true;
  3348. }
  3349. }
  3350. }
  3351. return false;
  3352. }
  3353. ///
  3354. /// @ingroup ge
  3355. /// @brief Init model stream for NN model.
  3356. /// @param [in] stream user input model stream.
  3357. /// @return Status
  3358. ///
  3359. Status DavinciModel::InitModelStream(rtStream_t stream) {
  3360. ExecuteMode curr_mode = is_async_mode_ ? ASYNCHRONIZATION : SYNCHRONIZATION;
  3361. GE_CHK_BOOL_RET_STATUS((curr_mode == last_execute_mode_) || (last_execute_mode_ == INITIALIZATION), INTERNAL_ERROR,
  3362. "NnExecute not support mix execute.");
  3363. last_execute_mode_ = curr_mode;
  3364. // asynchronize mode, use user input stream.
  3365. if (is_async_mode_) {
  3366. rt_model_stream_ = stream;
  3367. is_inner_model_stream_ = false;
  3368. return SUCCESS;
  3369. }
  3370. // synchronize mode, use forbidden stream.
  3371. if (stream != nullptr) {
  3372. if ((rt_model_stream_ != nullptr) && is_inner_model_stream_) {
  3373. GE_LOGW_IF(rtStreamDestroy(rt_model_stream_) != RT_ERROR_NONE, "Destroy rt_stream failed!");
  3374. }
  3375. rt_model_stream_ = stream;
  3376. is_inner_model_stream_ = false;
  3377. return SUCCESS;
  3378. }
  3379. if (rt_model_stream_ == nullptr) {
  3380. GE_CHK_RT_RET(rtStreamCreateWithFlags(&rt_model_stream_, priority_, RT_STREAM_FORBIDDEN_DEFAULT));
  3381. is_inner_model_stream_ = true;
  3382. }
  3383. return SUCCESS;
  3384. }
  3385. ///
  3386. /// @ingroup ge
  3387. /// @brief ACL case, do not start new thread, return execute result.
  3388. /// @param [in] stream execute model stream.
  3389. /// @param [in] async_mode is asynchronize mode.
  3390. /// @param [in] input_data model input data.
  3391. /// @param [out] output_data model output data.
  3392. ///
  3393. Status DavinciModel::NnExecute(rtStream_t stream, bool async_mode, const InputData &input_data,
  3394. OutputData &output_data) {
  3395. is_async_mode_ = async_mode;
  3396. GELOGI("Model Run begin, model id:%u, data index:%u, flag:%d.", model_id_, input_data.index, is_async_mode_);
  3397. GE_CHK_STATUS_RET(InitModelStream(stream), "Init model stream failed.");
  3398. is_dynamic_ = input_data.is_dynamic_batch;
  3399. if (!is_dynamic_) {
  3400. zero_copy_batch_label_addrs_.clear();
  3401. }
  3402. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_PRE_PROC_START));
  3403. Status ret = CopyModelData(input_data, output_data, is_dynamic_);
  3404. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Copy input data to model failed. model id: %u",
  3405. model_id_);
  3406. GELOGI("current_data.index=%u", input_data.index);
  3407. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_PRE_PROC_END));
  3408. if (!task_list_.empty()) {
  3409. GELOGD("rtModelExecute do");
  3410. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_INFER_START));
  3411. rtError_t rt_ret = rtModelExecute(rt_model_handle_, rt_model_stream_, 0);
  3412. GE_CHK_RT_EXEC(rt_ret, return RT_ERROR_TO_GE_STATUS(rt_ret));
  3413. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_INFER_END));
  3414. GELOGI("rtModelExecute end");
  3415. }
  3416. if (!is_async_mode_) {
  3417. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_AFTER_PROC_START));
  3418. ret = CopyOutputData(input_data.index, output_data, RT_MEMCPY_DEVICE_TO_DEVICE);
  3419. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Copy Output data to user failed.");
  3420. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), SetProfileTime(MODEL_AFTER_PROC_END));
  3421. }
  3422. // report model time data
  3423. GE_IF_BOOL_EXEC(ProfilingManager::Instance().ProfilingModelExecuteOn(), (void)SinkTimeProfile(input_data));
  3424. GELOGI("Model run end, model id:%u", model_id_);
  3425. return SUCCESS;
  3426. }
  3427. // Add active entry stream for special env.
  3428. Status DavinciModel::AddHeadStream() {
  3429. if (active_stream_list_.empty()) {
  3430. GELOGE(INTERNAL_ERROR, "Active stream is empty, stream list size: %zu, stream indication size: %zu.",
  3431. stream_list_.size(), active_stream_indication_.size());
  3432. return INTERNAL_ERROR;
  3433. }
  3434. if (active_stream_list_.size() == 1) {
  3435. GELOGI("Just one active stream, take as head stream.");
  3436. rt_head_stream_ = active_stream_list_[0];
  3437. is_pure_head_stream_ = false;
  3438. } else {
  3439. // Create stream which rt_model_handel running on, this is S0, TS stream.
  3440. GELOGI("Multiple active stream: %zu, create head stream.", active_stream_list_.size());
  3441. GE_CHK_RT_RET(rtStreamCreateWithFlags(&rt_head_stream_, priority_, RT_STREAM_PERSISTENT));
  3442. GE_CHK_RT_RET(rtModelBindStream(rt_model_handle_, rt_head_stream_, RT_INVALID_FLAG)); // Not active.
  3443. is_pure_head_stream_ = true;
  3444. for (auto s : active_stream_list_) {
  3445. std::shared_ptr<CpuTaskActiveEntry> active_entry = MakeShared<CpuTaskActiveEntry>(rt_head_stream_);
  3446. if (active_entry == nullptr) {
  3447. GELOGE(MEMALLOC_FAILED, "Make CpuTaskActiveEntry task failed.");
  3448. return MEMALLOC_FAILED;
  3449. }
  3450. Status status = active_entry->Init(s);
  3451. if (status != SUCCESS) {
  3452. return status;
  3453. }
  3454. cpu_task_list_.emplace_back(active_entry);
  3455. }
  3456. }
  3457. // Create entry stream active head stream. AICPU stream.
  3458. GE_CHK_RT_RET(rtStreamCreateWithFlags(&rt_entry_stream_, priority_, RT_STREAM_AICPU));
  3459. GE_CHK_RT_RET(rtModelBindStream(rt_model_handle_, rt_entry_stream_, RT_HEAD_STREAM));
  3460. return SUCCESS;
  3461. }
  3462. Status DavinciModel::InitEntryTask() {
  3463. if (deploy_type_ == AICPU_DEPLOY_CROSS_THREAD) {
  3464. GE_CHK_STATUS_RET(AddHeadStream(), "Add head stream failed.");
  3465. return CpuActiveStream();
  3466. } else {
  3467. return LoadWithQueue();
  3468. }
  3469. }
  3470. uint8_t *DavinciModel::MallocFeatureMapMem(size_t data_size) {
  3471. uint8_t *mem_base = nullptr;
  3472. const string purpose("feature map,used for op input and output.");
  3473. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3474. data_size = static_cast<size_t>(VarManager::Instance(session_id_)->GetGraphMemoryMaxSize());
  3475. string memory_key = std::to_string(0) + "_f";
  3476. mem_base = MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, memory_key, data_size, GetDeviceId());
  3477. } else {
  3478. mem_base = MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, data_size, GetDeviceId());
  3479. }
  3480. if (mem_base != nullptr) {
  3481. GE_CHK_RT(rtMemset(mem_base, data_size, 0U, data_size));
  3482. }
  3483. return mem_base;
  3484. }
  3485. uint8_t *DavinciModel::MallocP2PMem(size_t p2p_data_size) {
  3486. uint8_t *p2p_mem_base = nullptr;
  3487. const string purpose("p2p memory, used for some op related to hcom");
  3488. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3489. string p2p_memory_key = std::to_string(0) + "_p";
  3490. p2p_mem_base =
  3491. MemManager::Instance(RT_MEMORY_P2P_DDR)->MallocMemory(purpose, p2p_memory_key, p2p_data_size, GetDeviceId());
  3492. } else {
  3493. p2p_mem_base = MemManager::Instance(RT_MEMORY_P2P_DDR)->MallocMemory(purpose, p2p_data_size, GetDeviceId());
  3494. }
  3495. return p2p_mem_base;
  3496. }
  3497. uint8_t *DavinciModel::MallocWeightsMem(size_t weights_size) {
  3498. uint8_t *weights_mem_base = nullptr;
  3499. const string purpose("weights memory in inference network.");
  3500. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3501. string weight_memory_key = std::to_string(0) + "_w";
  3502. weights_mem_base =
  3503. MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, weight_memory_key, weights_size, GetDeviceId());
  3504. } else {
  3505. weights_mem_base = MemManager::Instance(RT_MEMORY_HBM)->MallocMemory(purpose, weights_size, GetDeviceId());
  3506. }
  3507. return weights_mem_base;
  3508. }
  3509. void DavinciModel::FreeFeatureMapMem() {
  3510. if (std::getenv(kEnvGeuseStaticMemory) != nullptr && is_inner_mem_base_) {
  3511. string weight_memory_key = std::to_string(0) + "_f";
  3512. if (MemManager::Instance(RT_MEMORY_HBM)->GetMemoryAddr(weight_memory_key) != nullptr) {
  3513. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(weight_memory_key, GetDeviceId()),
  3514. "failed to free weight memory");
  3515. }
  3516. mem_base_ = nullptr;
  3517. } else {
  3518. GE_IF_BOOL_EXEC(mem_base_ != nullptr && is_inner_mem_base_,
  3519. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(mem_base_, GetDeviceId()),
  3520. "failed to free feature_map memory");
  3521. mem_base_ = nullptr);
  3522. }
  3523. }
  3524. void DavinciModel::FreeP2PMem() {
  3525. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3526. std::string p2p_memory_key = std::to_string(0) + "_p";
  3527. if (MemManager::Instance(RT_MEMORY_P2P_DDR)->GetMemoryAddr(p2p_memory_key) != nullptr) {
  3528. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_P2P_DDR)->FreeMemory(p2p_memory_key, GetDeviceId()),
  3529. "failed to free p2p memory");
  3530. }
  3531. p2p_mem_base_ = nullptr;
  3532. } else {
  3533. GE_IF_BOOL_EXEC(p2p_mem_base_ != nullptr && is_inner_mem_base_,
  3534. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_P2P_DDR)->FreeMemory(p2p_mem_base_, GetDeviceId()),
  3535. "failed to free p2p memory");
  3536. p2p_mem_base_ = nullptr);
  3537. }
  3538. }
  3539. void DavinciModel::FreeWeightsMem() {
  3540. if (std::getenv(kEnvGeuseStaticMemory) != nullptr) {
  3541. string memory_key = std::to_string(0) + "_w";
  3542. if (MemManager::Instance(RT_MEMORY_HBM)->GetMemoryAddr(memory_key) != nullptr) {
  3543. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(memory_key, GetDeviceId()),
  3544. "failed to free feature_map memory");
  3545. }
  3546. weights_mem_base_ = nullptr;
  3547. } else {
  3548. GE_IF_BOOL_EXEC(weights_mem_base_ != nullptr && weights_mem_base_ != mem_base_ && is_inner_weight_base_,
  3549. GE_CHK_STATUS(MemManager::Instance(RT_MEMORY_HBM)->FreeMemory(weights_mem_base_, GetDeviceId()),
  3550. "failed to free weight memory");
  3551. weights_mem_base_ = nullptr);
  3552. }
  3553. }
  3554. Status DavinciModel::TransAllVarData(ComputeGraphPtr &graph, uint32_t graph_id) {
  3555. GELOGI("TransAllVarData start: session_id:%lu, graph_id: %u.", session_id_, graph_id);
  3556. rtContext_t ctx = nullptr;
  3557. rtError_t rt_ret = rtCtxGetCurrent(&ctx);
  3558. if (rt_ret != RT_ERROR_NONE) {
  3559. GELOGE(RT_FAILED, "Failed to get current context, error_code is: 0x%X.", rt_ret);
  3560. return RT_ERROR_TO_GE_STATUS(rt_ret);
  3561. }
  3562. std::vector<NodePtr> variable_node_list;
  3563. for (ge::NodePtr &node : graph->GetDirectNode()) {
  3564. if (node == nullptr) {
  3565. continue;
  3566. }
  3567. if (node->GetType() != VARIABLE) {
  3568. continue;
  3569. }
  3570. variable_node_list.emplace_back(node);
  3571. }
  3572. GE_CHK_STATUS_RET_NOLOG(
  3573. TransVarDataUtils::TransAllVarData(variable_node_list, session_id_, ctx, graph_id, kThreadNum));
  3574. GELOGI("TransAllVarData success.");
  3575. return SUCCESS;
  3576. }
  3577. void DavinciModel::SetDataDumperArgs(const ComputeGraphPtr &compute_graph) {
  3578. GELOGI("set data dumper args, name: %s, id: %u.", name_.c_str(), model_id_);
  3579. data_dumper_.SetModelName(name_);
  3580. data_dumper_.SetModelId(model_id_);
  3581. data_dumper_.SetOmName(om_name_);
  3582. data_dumper_.SetComputeGraph(compute_graph);
  3583. data_dumper_.SetRefInfo(saved_task_addrs_);
  3584. data_dumper_.SetL1FusionAddr(l1_fusion_addr_);
  3585. int32_t device_id = 0;
  3586. rtError_t rt_ret = rtGetDevice(&device_id);
  3587. if (rt_ret != RT_ERROR_NONE || device_id < 0) {
  3588. GELOGE(RT_FAILED, "Call rtGetDevice failed, ret = 0x%X, device_id = %d.", rt_ret, device_id);
  3589. return;
  3590. }
  3591. data_dumper_.SetDeviceId(device_id);
  3592. // set loop count addr
  3593. auto get_var_addr = [](const OpDescPtr &op, const RuntimeParam &runtime_param) -> void * {
  3594. if (op != nullptr) {
  3595. auto v_output_size = ModelUtils::GetOutputSize(op);
  3596. auto v_output_addr = ModelUtils::GetOutputDataAddrs(runtime_param, op);
  3597. if (v_output_size.empty() || v_output_addr.empty()) {
  3598. return nullptr;
  3599. }
  3600. return v_output_addr[0];
  3601. }
  3602. GELOGW("op is null.");
  3603. return nullptr;
  3604. };
  3605. data_dumper_.SetLoopAddr(get_var_addr(GetVariableOp(NODE_NAME_GLOBAL_STEP), runtime_param_),
  3606. get_var_addr(GetVariableOp(NODE_NAME_FLOWCTRL_LOOP_PER_ITER), runtime_param_),
  3607. get_var_addr(GetVariableOp(NODE_NAME_FLOWCTRL_LOOP_COND), runtime_param_));
  3608. GELOGI("SetDataDumperArgs end.");
  3609. }
  3610. uint32_t DavinciModel::GetFlowctrlIndex(uint32_t op_index) {
  3611. std::lock_guard<std::mutex> lock(flowctrl_op_index_internal_map_mutex_);
  3612. return (++flowctrl_op_index_internal_map_[op_index]) - 1;
  3613. }
  3614. void DavinciModel::PushHcclStream(rtStream_t value) {
  3615. std::lock_guard<std::mutex> lock(all_hccl_stream_list_mutex_);
  3616. all_hccl_stream_list_.push_back(value);
  3617. }
  3618. void DavinciModel::SaveHcclFollowStream(int64_t main_stream_id, rtStream_t stream) {
  3619. std::lock_guard<std::mutex> lock(capacity_of_stream_mutex_);
  3620. main_follow_stream_mapping_[main_stream_id].emplace_back(stream);
  3621. }
  3622. Status DavinciModel::GetComputeGraphInfo(vector<ComputeGraphDescInfo> &graph_desc_info) {
  3623. GELOGI("GetComputeGraphInfo start.");
  3624. auto &all_op_desc = data_dumper_.GetAllOpDescInfo();
  3625. for (auto &op_desc : all_op_desc) {
  3626. ComputeGraphDescInfo compute_graph_info;
  3627. if (!om_name_.empty()) {
  3628. compute_graph_info.model_name = om_name_;
  3629. } else {
  3630. compute_graph_info.model_name = name_;
  3631. }
  3632. compute_graph_info.op_name = op_desc.op_name;
  3633. compute_graph_info.op_type = op_desc.op_type;
  3634. compute_graph_info.input_format = op_desc.input_format;
  3635. compute_graph_info.input_shape = op_desc.input_shape;
  3636. compute_graph_info.input_data_type = op_desc.input_data_type;
  3637. compute_graph_info.output_format = op_desc.output_format;
  3638. compute_graph_info.output_shape = op_desc.output_shape;
  3639. compute_graph_info.output_data_type = op_desc.output_data_type;
  3640. graph_desc_info.emplace_back(compute_graph_info);
  3641. }
  3642. GELOGI("GetComputeGraphInfo end.");
  3643. return SUCCESS;
  3644. }
  3645. void DavinciModel::SetTotalFixedAddrsSize(string tensor_name, int64_t fix_addr_size) {
  3646. if (tensor_name_to_fixed_addr_size_.find(tensor_name) == tensor_name_to_fixed_addr_size_.end()) {
  3647. tensor_name_to_fixed_addr_size_[tensor_name] = total_fixed_addr_size_;
  3648. total_fixed_addr_size_ += fix_addr_size;
  3649. }
  3650. }
  3651. Status DavinciModel::GetOrigInputInfo(uint32_t index, OriginInputInfo &orig_input_info) {
  3652. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  3653. OpDescPtr data_op = data_op_list_[index];
  3654. if (!data_op->HasAttr(ATTR_NAME_AIPP_INPUTS) || !data_op->HasAttr(ATTR_NAME_AIPP_OUTPUTS)) {
  3655. GELOGE(GE_AIPP_NOT_EXIST, "GetOrigInputInfo: there is not AIPP related with index %u.", index);
  3656. return GE_AIPP_NOT_EXIST;
  3657. }
  3658. vector<std::string> inputs;
  3659. if (AttrUtils::GetListStr(data_op, ATTR_NAME_AIPP_INPUTS, inputs) && !inputs.empty()) {
  3660. std::string input = inputs[kAippOriginInputIndex];
  3661. GELOGI("GetOrigInputInfo: origin input str: %s", input.c_str());
  3662. std::vector<std::string> infos = ge::StringUtils::Split(input, ':');
  3663. if (infos.size() != kAippInfoNum) {
  3664. GELOGW("origin input str is invalid.");
  3665. }
  3666. orig_input_info.format = TypeUtils::SerialStringToFormat(infos[kAippInfoFormat]);
  3667. orig_input_info.data_type = TypeUtils::SerialStringToDataType(infos[kAippInfoDataType]);
  3668. orig_input_info.dim_num = std::strtol(infos[kAippInfoDimNum].c_str(), nullptr, kDecimal);
  3669. }
  3670. return SUCCESS;
  3671. }
  3672. void DavinciModel::ParseAIPPInfo(std::string in_out_info, InputOutputDims &dims_info) {
  3673. GELOGI("ParseAIPPInfo: origin str: %s", in_out_info.c_str());
  3674. std::vector<std::string> infos = ge::StringUtils::Split(in_out_info, ':');
  3675. if (infos.size() != kAippInfoNum) {
  3676. GELOGW("origin input str is invalid.");
  3677. }
  3678. dims_info.name = infos[kAippInfoTensorName];
  3679. dims_info.size = std::strtol(infos[kAippInfoTensorSize].c_str(), nullptr, kDecimal);
  3680. dims_info.dim_num = std::strtol(infos[kAippInfoDimNum].c_str(), nullptr, kDecimal);
  3681. std::vector<std::string> dims = ge::StringUtils::Split(infos[kAippInfoShape], ',');
  3682. for (const auto &dim : dims) {
  3683. if (dim.empty()) {
  3684. continue;
  3685. }
  3686. dims_info.dims.emplace_back(std::strtol(dim.c_str(), nullptr, kDecimal));
  3687. }
  3688. }
  3689. Status DavinciModel::GetAllAippInputOutputDims(uint32_t index, std::vector<InputOutputDims> &input_dims,
  3690. std::vector<InputOutputDims> &output_dims) {
  3691. GE_CHK_BOOL_RET_STATUS(index < data_op_list_.size(), PARAM_INVALID, "Index %u is invalid.", index);
  3692. OpDescPtr data_op = data_op_list_[index];
  3693. if (!data_op->HasAttr(ATTR_NAME_AIPP_INPUTS) || !data_op->HasAttr(ATTR_NAME_AIPP_OUTPUTS)) {
  3694. GELOGE(GE_AIPP_NOT_EXIST, "GetAllAippInputOutputDims: there is not AIPP related with index %u.", index);
  3695. return GE_AIPP_NOT_EXIST;
  3696. }
  3697. vector<std::string> inputs;
  3698. if (AttrUtils::GetListStr(data_op, ATTR_NAME_AIPP_INPUTS, inputs) && !inputs.empty()) {
  3699. GELOGI("GetAllAippInputOutputDims: Data: %s has %u related aippInfo.", data_op->GetName().c_str(), inputs.size());
  3700. for (auto it : inputs) {
  3701. InputOutputDims input_info;
  3702. ParseAIPPInfo(it, input_info);
  3703. input_dims.emplace_back(input_info);
  3704. GELOGD("GetAllAippInputOutputDims Aipp origin input dims info: %s", it.c_str());
  3705. ConstGeTensorDescPtr data_input_desc = data_op->GetInputDescPtr(kDataIndex);
  3706. int64_t data_input_size;
  3707. (void)TensorUtils::GetSize(*(data_op->GetInputDescPtr(kDataIndex)), data_input_size);
  3708. GELOGD(
  3709. "GetAllAippInputOutputDims related Data[%d]: tensor_name is %s, dim_num is %u, tensor_size: %zu, format: "
  3710. "%s, data_type: %s, shape: %s .",
  3711. index, data_op->GetName().c_str(), data_input_desc->GetShape().GetDimNum(), data_input_size,
  3712. TypeUtils::FormatToSerialString(data_input_desc->GetFormat()).c_str(),
  3713. TypeUtils::DataTypeToSerialString(data_input_desc->GetDataType()).c_str(),
  3714. formats::JoinToString(data_input_desc->GetShape().GetDims()).c_str());
  3715. }
  3716. }
  3717. vector<std::string> outputs;
  3718. if (AttrUtils::GetListStr(data_op, ATTR_NAME_AIPP_OUTPUTS, outputs) && !outputs.empty()) {
  3719. for (auto it : outputs) {
  3720. InputOutputDims output_info;
  3721. ParseAIPPInfo(it, output_info);
  3722. output_dims.emplace_back(output_info);
  3723. GELOGD("GetAllAippInputOutputDims Aipp output dims info: %s", it.c_str());
  3724. }
  3725. }
  3726. return SUCCESS;
  3727. }
  3728. int64_t DavinciModel::GetFixedAddrsSize(string tensor_name) {
  3729. if (tensor_name_to_fixed_addr_size_.find(tensor_name) != tensor_name_to_fixed_addr_size_.end()) {
  3730. return tensor_name_to_fixed_addr_size_[tensor_name];
  3731. } else {
  3732. return total_fixed_addr_size_;
  3733. }
  3734. }
  3735. } // namespace ge

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