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

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

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