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 170 kB

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

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