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

davinci_model.cc 165 kB

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

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