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

davinci_model.cc 172 kB

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

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