You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

davinci_model.cc 172 kB

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

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