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

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