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

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