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

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