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

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