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.

graph_scheduler.cc 99 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. /**
  2. * Copyright 2021-2022 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 "runtime/framework/graph_scheduler.h"
  17. #include <queue>
  18. #include "runtime/framework/actor/memory_manager_actor.h"
  19. #include "runtime/framework/actor/debug_actor.h"
  20. #include "runtime/framework/actor/recorder_actor.h"
  21. #include "runtime/hardware/device_context_manager.h"
  22. #include "mindrt/src/actor/actormgr.h"
  23. #include "mindrt/include/async/async.h"
  24. #include "backend/session/anf_runtime_algorithm.h"
  25. #include "backend/optimizer/common/helper.h"
  26. #include "utils/anf_utils.h"
  27. #include "utils/config_manager.h"
  28. #include "utils/log_adapter.h"
  29. #include "utils/convert_utils.h"
  30. #include "utils/ms_context.h"
  31. #include "utils/profile.h"
  32. #if !defined(_WIN32) && !defined(_WIN64)
  33. #include "utils/signal_util.h"
  34. #endif
  35. #ifndef ENABLE_SECURITY
  36. #include "debug/data_dump/dump_json_parser.h"
  37. #endif
  38. #ifdef ENABLE_DUMP_IR
  39. #include "debug/rdr/recorder_manager.h"
  40. #include "debug/rdr/running_data_recorder.h"
  41. #endif
  42. #ifdef ENABLE_DEBUGGER
  43. #include "debug/debugger/debugger.h"
  44. #endif
  45. #include "profiler/device/profiling.h"
  46. #include "debug/common.h"
  47. namespace mindspore {
  48. namespace runtime {
  49. namespace {
  50. bool IsNeedInsertCopyActor(const DeviceContext *from_device_context, const DeviceContext *to_device_context) {
  51. MS_EXCEPTION_IF_NULL(from_device_context);
  52. MS_EXCEPTION_IF_NULL(to_device_context);
  53. if (from_device_context->GetDeviceAddressType() == to_device_context->GetDeviceAddressType()) {
  54. return false;
  55. } else {
  56. return true;
  57. }
  58. }
  59. inline bool IsSingleOpActorSet(const ActorSet *actor_set) {
  60. MS_EXCEPTION_IF_NULL(actor_set);
  61. return actor_set->kernel_actors_.size() == 1;
  62. }
  63. // Convert the actors vector by the actor set.
  64. std::vector<AbstractActorPtr> CollectActors(const ActorSet *actor_set) {
  65. MS_EXCEPTION_IF_NULL(actor_set);
  66. std::vector<AbstractActorPtr> actors;
  67. if (actor_set->data_prepare_actor_ != nullptr) {
  68. (void)actors.emplace_back(static_cast<AbstractActorPtr>(actor_set->data_prepare_actor_));
  69. }
  70. for (auto &data_source_actor : actor_set->data_source_actors_) {
  71. MS_EXCEPTION_IF_NULL(data_source_actor);
  72. (void)actors.emplace_back(static_cast<AbstractActorPtr>(data_source_actor));
  73. }
  74. for (auto &custom_actor : actor_set->custom_actors_) {
  75. MS_EXCEPTION_IF_NULL(custom_actor);
  76. (void)actors.emplace_back(static_cast<AbstractActorPtr>(custom_actor));
  77. }
  78. for (auto &kernel_actor : actor_set->kernel_actors_) {
  79. MS_EXCEPTION_IF_NULL(kernel_actor);
  80. (void)actors.emplace_back(static_cast<AbstractActorPtr>(kernel_actor));
  81. }
  82. for (auto &super_kernel_actor : actor_set->super_kernel_actors_) {
  83. MS_EXCEPTION_IF_NULL(super_kernel_actor);
  84. (void)actors.emplace_back(static_cast<AbstractActorPtr>(super_kernel_actor));
  85. }
  86. for (auto &copy_actor : actor_set->copy_actors_) {
  87. MS_EXCEPTION_IF_NULL(copy_actor);
  88. (void)actors.emplace_back(static_cast<AbstractActorPtr>(copy_actor));
  89. }
  90. if (actor_set->loop_count_actor_ != nullptr) {
  91. (void)actors.emplace_back(static_cast<AbstractActorPtr>(actor_set->loop_count_actor_));
  92. }
  93. if (actor_set->output_actor_ != nullptr) {
  94. (void)actors.emplace_back(static_cast<AbstractActorPtr>(actor_set->output_actor_));
  95. }
  96. if (actor_set->control_actors_ != nullptr) {
  97. const auto &control_actor_set = actor_set->control_actors_;
  98. for (auto &switch_actor : control_actor_set->switch_actors_) {
  99. MS_EXCEPTION_IF_NULL(switch_actor);
  100. (void)actors.emplace_back(static_cast<AbstractActorPtr>(switch_actor));
  101. }
  102. for (auto &gather_actor : control_actor_set->gather_actors_) {
  103. MS_EXCEPTION_IF_NULL(gather_actor);
  104. (void)actors.emplace_back(static_cast<AbstractActorPtr>(gather_actor));
  105. }
  106. for (auto &entrance_actor : control_actor_set->entrance_actors_) {
  107. MS_EXCEPTION_IF_NULL(entrance_actor);
  108. (void)actors.emplace_back(static_cast<AbstractActorPtr>(entrance_actor));
  109. }
  110. for (auto &exit_actor : control_actor_set->exit_actors_) {
  111. MS_EXCEPTION_IF_NULL(exit_actor);
  112. (void)actors.emplace_back(static_cast<AbstractActorPtr>(exit_actor));
  113. }
  114. for (auto &stack_actor : control_actor_set->stack_actors_) {
  115. MS_EXCEPTION_IF_NULL(stack_actor);
  116. (void)actors.emplace_back(static_cast<AbstractActorPtr>(stack_actor));
  117. }
  118. }
  119. return actors;
  120. }
  121. void ClearNodeInfo(const KernelGraphPtr &graph) {
  122. MS_EXCEPTION_IF_NULL(graph);
  123. // Clear input parameter device tensor and device tensor store.
  124. for (const auto &input_node : graph->input_nodes()) {
  125. MS_EXCEPTION_IF_NULL(input_node);
  126. if (!input_node->isa<Parameter>()) {
  127. continue;
  128. }
  129. auto parameter = input_node->cast<ParameterPtr>();
  130. MS_EXCEPTION_IF_NULL(parameter);
  131. parameter->DecreaseUsedGraphCount();
  132. // Only the parameter has no graph used, then clear the device tensor.
  133. if (parameter->used_graph_count() != 0) {
  134. continue;
  135. }
  136. auto front_input_node = FetchFrontNodeByBackendNode(input_node, graph);
  137. DeviceTensorStore::GetInstance().Remove(front_input_node.get());
  138. size_t output_num = AnfAlgo::GetOutputTensorNum(input_node);
  139. for (size_t index = 0; index < output_num; ++index) {
  140. if (AnfAlgo::OutputAddrExist(input_node, index)) {
  141. AnfAlgo::SetOutputAddr(nullptr, index, input_node.get());
  142. }
  143. }
  144. }
  145. // Clear input value node device tensor and device tensor store.
  146. for (const auto &value_node : graph->graph_value_nodes()) {
  147. auto front_value_node = FetchFrontNodeByBackendNode(value_node, graph);
  148. DeviceTensorStore::GetInstance().Remove(front_value_node.get());
  149. if (AnfAlgo::OutputAddrExist(value_node, 0)) {
  150. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  151. }
  152. }
  153. // Clear cnode device tensor.
  154. for (const auto &cnode : graph->execution_order()) {
  155. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  156. for (size_t index = 0; index < output_num; ++index) {
  157. if (AnfAlgo::OutputAddrExist(cnode, index)) {
  158. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  159. }
  160. }
  161. }
  162. }
  163. #if !defined(_WIN32) && !defined(_WIN64)
  164. void IntHandler(int, siginfo_t *, void *) {
  165. int this_pid = getpid();
  166. MS_LOG(WARNING) << "Process " << this_pid << " receive KeyboardInterrupt signal.";
  167. (void)kill(this_pid, SIGTERM);
  168. }
  169. #endif
  170. } // namespace
  171. void GraphScheduler::Clear(const ActorInfo &actor_info, const std::vector<KernelGraphPtr> &graphs) noexcept {
  172. // Terminate the actors of actor info.
  173. if (actors_.count(actor_info) > 0) {
  174. auto actor_manager = ActorMgr::GetActorMgrRef();
  175. if (actor_manager == nullptr) {
  176. MS_LOG(ERROR) << "Actor manager is not exist.";
  177. return;
  178. }
  179. auto actor_set = actors_[actor_info];
  180. auto base_actors = CollectActors(actor_set.get());
  181. for (auto &base_actor : base_actors) {
  182. MS_EXCEPTION_IF_NULL(base_actor);
  183. EraseActor(base_actor->GetAID().Name());
  184. actor_manager->Terminate(base_actor->GetAID());
  185. }
  186. }
  187. // Clear device tensor and device tensor store.
  188. for (auto &graph : graphs) {
  189. ClearNodeInfo(graph);
  190. }
  191. // Clear global maps of actor info.
  192. (void)actors_.erase(actor_info);
  193. }
  194. void GraphScheduler::Clear() {
  195. // Terminate all actors.
  196. auto actor_manager = ActorMgr::GetActorMgrRef();
  197. MS_EXCEPTION_IF_NULL(actor_manager);
  198. actor_manager->Finalize();
  199. // Clear the member of DeviceTensorStore.
  200. DeviceTensorStore::GetInstance().Clear();
  201. // Clear global maps.
  202. actors_.clear();
  203. ClearAllActors();
  204. }
  205. void GraphScheduler::ClearActorData(const ActorSet *actor_set) {
  206. MS_EXCEPTION_IF_NULL(actor_set);
  207. // Clear the member of DeviceTensorCopyStore.
  208. DeviceTensorCopyStore::GetInstance().Clear();
  209. for (auto &super_kernel_actor : actor_set->super_kernel_actors_) {
  210. MS_EXCEPTION_IF_NULL(super_kernel_actor);
  211. super_kernel_actor->memory_free_lists_ = std::queue<std::vector<DeviceTensor *>>();
  212. }
  213. control_node_scheduler_.ClearActorData(actor_set->control_actors_.get());
  214. }
  215. using DataArrowLinkFunc = void (GraphScheduler::*)(AbstractActor *const, AbstractActor *const, const KernelWithIndex &,
  216. const KernelWithIndex &, const KernelGraphPtr &);
  217. static std::map<KernelTransformType, DataArrowLinkFunc> kKernelTypeToLinkFunc;
  218. void GraphScheduler::Initialize() {
  219. if (init_) {
  220. return;
  221. }
  222. init_ = true;
  223. (void)kKernelTypeToLinkFunc.emplace(KernelTransformType::kDeviceDataSourceActor,
  224. &GraphScheduler::LinkDataArrowForBaseActor);
  225. (void)kKernelTypeToLinkFunc.emplace(KernelTransformType::kHostDataSourceActor,
  226. &GraphScheduler::LinkDataArrowForHostDSActor);
  227. (void)kKernelTypeToLinkFunc.emplace(KernelTransformType::kKernelActor, &GraphScheduler::LinkDataArrowForKernelActor);
  228. (void)kKernelTypeToLinkFunc.emplace(KernelTransformType::kSuperKernelActor,
  229. &GraphScheduler::LinkDataArrowForBaseActor);
  230. (void)kKernelTypeToLinkFunc.emplace(KernelTransformType::kDeviceTensorStore,
  231. &GraphScheduler::LinkDataArrowForDeviceTensorStore);
  232. (void)kKernelTypeToLinkFunc.emplace(KernelTransformType::kInternalParameter,
  233. &GraphScheduler::LinkDataArrowForInternalParameter);
  234. // Create the thread pool of actor runtime and Set the OMP_NUM_THREADS env.
  235. size_t actor_thread_num = 0;
  236. size_t actor_and_kernel_thread_num = 0;
  237. ComputeThreadNums(&actor_thread_num, &actor_and_kernel_thread_num);
  238. auto actor_manager = ActorMgr::GetActorMgrRef();
  239. MS_EXCEPTION_IF_NULL(actor_manager);
  240. auto ret = actor_manager->Initialize(true, actor_thread_num, actor_and_kernel_thread_num);
  241. if (ret != MINDRT_OK) {
  242. MS_LOG(EXCEPTION) << "Actor manager init failed.";
  243. }
  244. common::SetOMPThreadNum();
  245. MS_LOG(INFO) << "The actor thread number: " << actor_thread_num
  246. << ", the kernel thread number: " << (actor_and_kernel_thread_num - actor_thread_num);
  247. BuildAndScheduleGlobalActor();
  248. }
  249. void GraphScheduler::BuildAndScheduleGlobalActor() {
  250. auto actor_manager = ActorMgr::GetActorMgrRef();
  251. MS_EXCEPTION_IF_NULL(actor_manager);
  252. // Create and schedule memory manager actor.
  253. auto memory_manager_actor = std::make_shared<MemoryManagerActor>();
  254. MS_EXCEPTION_IF_NULL(memory_manager_actor);
  255. memory_manager_aid_ = memory_manager_actor->GetAID();
  256. auto base_actor = static_cast<ActorReference>(memory_manager_actor);
  257. // Bind single thread to response to memory alloc and free quickly.
  258. (void)actor_manager->Spawn(base_actor, false);
  259. // Create and schedule recorder actor.
  260. auto recorder_actor = std::make_shared<RecorderActor>();
  261. MS_EXCEPTION_IF_NULL(recorder_actor);
  262. recorder_aid_ = &(recorder_actor->GetAID());
  263. auto base_recorder_actor = static_cast<ActorReference>(recorder_actor);
  264. (void)actor_manager->Spawn(base_recorder_actor, true);
  265. // Create and schedule debug actor.
  266. // debugger_actor_need is true for CPU when e2e dump is enabled and for Ascend and GPU is true when debugger or dump
  267. // is enabled.
  268. #ifndef ENABLE_SECURITY
  269. bool debugger_actor_need = DumpJsonParser::GetInstance().e2e_dump_enabled();
  270. #endif
  271. #ifdef ENABLE_DEBUGGER
  272. if (Debugger::GetInstance()->DebuggerBackendEnabled()) {
  273. debugger_actor_need = true;
  274. }
  275. #endif
  276. #ifndef ENABLE_SECURITY
  277. if (debugger_actor_need) {
  278. auto debug_actor = std::make_shared<DebugActor>();
  279. MS_EXCEPTION_IF_NULL(debug_actor);
  280. debug_aid_ = &(debug_actor->GetAID());
  281. auto base_debug_actor = static_cast<ActorReference>(debug_actor);
  282. (void)actor_manager->Spawn(base_debug_actor, true);
  283. }
  284. #endif
  285. }
  286. ActorSet *GraphScheduler::Transform(const GraphCompilerInfo &graph_compiler_info) {
  287. MS_LOG(INFO) << "Graph(" << graph_compiler_info.name_ << ") transforms actor begin.";
  288. if (graph_compiler_info.graphs_.size() == 0) {
  289. MS_LOG(EXCEPTION) << "The number of graphs is zero.";
  290. }
  291. if (graph_compiler_info.graphs_.size() != graph_compiler_info.device_contexts_.size()) {
  292. MS_LOG(EXCEPTION) << "The number of graphs is not equal to the number of device contexts.";
  293. }
  294. PersistDeviceTensor(graph_compiler_info);
  295. const auto &actor_set = Build(graph_compiler_info);
  296. MS_EXCEPTION_IF_NULL(actor_set);
  297. CacheGraphOutputToActor(graph_compiler_info);
  298. Link(actor_set.get(), graph_compiler_info);
  299. DumpActor(actor_set.get(), graph_compiler_info);
  300. if (graph_compiler_info.strategy_ == GraphExecutionStrategy::kPipeline) {
  301. CheckActorValid(actor_set.get());
  302. }
  303. MS_LOG(INFO) << "Graph(" << graph_compiler_info.name_ << ") transforms actor end.";
  304. // Local maps and vectors clear.
  305. graph_output_to_actor_.clear();
  306. copy_actors_.clear();
  307. return actor_set.get();
  308. }
  309. void GraphScheduler::Schedule(const ActorSet *actor_set) {
  310. MS_EXCEPTION_IF_NULL(actor_set);
  311. auto actors = CollectActors(actor_set);
  312. // Schedule actors.
  313. auto actor_manager = ActorMgr::GetActorMgrRef();
  314. MS_EXCEPTION_IF_NULL(actor_manager);
  315. for (auto actor : actors) {
  316. (void)actor_manager->Spawn(actor);
  317. }
  318. }
  319. void GraphScheduler::Run(ActorSet *const actor_set, const std::vector<DeviceContext *> &device_contexts,
  320. const std::vector<std::vector<TensorPtr>> &input_tensors,
  321. const std::vector<TensorPtr> &input_tensors_with_value_node, GraphExecutionStrategy strategy) {
  322. MS_EXCEPTION_IF_NULL(actor_set);
  323. MS_EXCEPTION_IF_NULL(actor_set->data_prepare_actor_);
  324. #if !defined(_WIN32) && !defined(_WIN64)
  325. SignalGuard sg(IntHandler);
  326. #endif
  327. // Construct OpContext.
  328. OpContext<DeviceTensor> op_context;
  329. std::vector<Promise<int>> result(1);
  330. op_context.sequential_num_ = RandInt::Instance().Get();
  331. op_context.results_ = &result;
  332. if ((strategy == GraphExecutionStrategy::kStep) && IsSingleOpActorSet(actor_set)) {
  333. actor_set->data_prepare_actor_->PrepareData(input_tensors, &op_context, GraphExecutionStrategy::kStep);
  334. MS_EXCEPTION_IF_NULL(actor_set->kernel_actors_[0]);
  335. actor_set->kernel_actors_[0]->RunOpControlWithInputTensor(nullptr, &op_context, &input_tensors_with_value_node);
  336. return;
  337. }
  338. // Trigger data prepare actor running.
  339. MS_EXCEPTION_IF_NULL(ActorMgr::GetActorMgrRef());
  340. auto thread_pool = ActorMgr::GetActorMgrRef()->GetActorThreadPool();
  341. MS_EXCEPTION_IF_NULL(thread_pool);
  342. if (actor_set->is_multi_thread_execution_) {
  343. thread_pool->SetSpinCountMaxValue();
  344. }
  345. ActorDispatcher::is_multi_thread_execution(actor_set->is_multi_thread_execution_);
  346. double start_time = GetTime();
  347. ActorDispatcher::Send(actor_set->data_prepare_actor_->GetAID(), &DataPrepareActor::PrepareData, input_tensors,
  348. &op_context, GraphExecutionStrategy::kPipeline);
  349. // Get the run result.
  350. auto result_future = result[0].GetFuture();
  351. result_future.Wait();
  352. MsException::Instance().CheckException();
  353. thread_pool->SetSpinCountMinValue();
  354. if (!result_future.IsOK()) {
  355. #ifdef ENABLE_DUMP_IR
  356. mindspore::RDR::TriggerAll();
  357. #endif
  358. // When temporary variable 'op_context' has beed set failed status, the main thread need wait other threads until
  359. // they finish respective task, otherwise segmentation fault will happen when these task access 'op_context',
  360. // because it has been destroyed.
  361. std::mutex mutex;
  362. std::unique_lock<std::mutex> locker(mutex);
  363. std::condition_variable thread_blocker;
  364. const int64_t kTimeToWait = 2;
  365. (void)thread_blocker.wait_for(locker, std::chrono::seconds(kTimeToWait));
  366. MS_LOG(EXCEPTION) << op_context.error_info_;
  367. }
  368. // Sync device stream.
  369. if (strategy == GraphExecutionStrategy::kPipeline) {
  370. std::set<DeviceContext *> sync_stream_device_contexts;
  371. for (auto &device_context : device_contexts) {
  372. MS_EXCEPTION_IF_NULL(device_context);
  373. if ((sync_stream_device_contexts.count(device_context) == 0) && (!device_context->SyncStream())) {
  374. MS_LOG(EXCEPTION) << "Sync stream failed:" << device_context->device_context_key().ToString();
  375. }
  376. (void)sync_stream_device_contexts.insert(device_context);
  377. }
  378. }
  379. double end_time = GetTime();
  380. const size_t kSecondsToMilliseconds = 1000;
  381. SetActorExecutionStrategy(actor_set, strategy, (end_time - start_time) * kSecondsToMilliseconds);
  382. }
  383. void GraphScheduler::SetActorExecutionStrategy(ActorSet *const actor_set, GraphExecutionStrategy strategy,
  384. double execution_time) {
  385. MS_EXCEPTION_IF_NULL(actor_set);
  386. MS_EXCEPTION_IF_NULL(actor_set->loop_count_actor_);
  387. ++actor_set->execution_count_;
  388. MS_LOG(DEBUG) << "Execution count: " << actor_set->execution_count_ << ", execution time cost: " << execution_time
  389. << " ms in multi thread or not: " << actor_set->is_multi_thread_execution_ << ".";
  390. #if defined(_WIN32) || defined(_WIN64)
  391. return;
  392. #endif
  393. // The step mode uses the default multi thread.
  394. if (strategy == GraphExecutionStrategy::kStep) {
  395. return;
  396. }
  397. // The constraint condition of not supporting the single thread execution.
  398. if ((actor_set->control_actors_ != nullptr) || (actor_set->copy_actors_.size() > 0) ||
  399. (actor_set->super_kernel_actors_.size() > 0) || (actor_set->loop_count_actor_->loop_count() > 1) ||
  400. (actor_set->kernel_actors_.size() > ActorDispatcher::kSingleThreadExecutionActorMaxNum)) {
  401. return;
  402. }
  403. if ((actor_set->is_multi_thread_execution_) &&
  404. (actor_set->execution_count_ >= ActorDispatcher::kMultiThreadExecutionCountBegin) &&
  405. (actor_set->execution_count_ <= ActorDispatcher::kMultiThreadExecutionCountEnd)) {
  406. actor_set->multi_thread_execution_time_ += execution_time;
  407. if (actor_set->execution_count_ == ActorDispatcher::kMultiThreadExecutionCountEnd) {
  408. actor_set->multi_thread_execution_time_ /=
  409. (ActorDispatcher::kMultiThreadExecutionCountEnd - ActorDispatcher::kMultiThreadExecutionCountBegin + 1);
  410. actor_set->is_multi_thread_execution_ = false;
  411. }
  412. return;
  413. }
  414. if ((!actor_set->is_multi_thread_execution_) &&
  415. (actor_set->execution_count_ >= ActorDispatcher::kSingleThreadExecutionCountBegin) &&
  416. (actor_set->execution_count_ <= ActorDispatcher::kSingleThreadExecutionCountEnd)) {
  417. actor_set->single_thread_execution_time_ += execution_time;
  418. if (actor_set->execution_count_ == ActorDispatcher::kSingleThreadExecutionCountEnd) {
  419. actor_set->single_thread_execution_time_ /=
  420. (ActorDispatcher::kSingleThreadExecutionCountEnd - ActorDispatcher::kSingleThreadExecutionCountBegin + 1);
  421. actor_set->is_multi_thread_execution_ =
  422. (actor_set->multi_thread_execution_time_ <= actor_set->single_thread_execution_time_) ? true : false;
  423. MS_LOG(INFO) << "Multi thread execution time cost: " << actor_set->multi_thread_execution_time_
  424. << " ms, single thread execution time cost: " << actor_set->single_thread_execution_time_
  425. << " ms, decide to use multi thread execution or not: " << actor_set->is_multi_thread_execution_
  426. << ".";
  427. }
  428. return;
  429. }
  430. }
  431. ActorSet *GraphScheduler::Fetch(const ActorInfo &actor_info) const {
  432. auto iter = actors_.find(actor_info);
  433. if (iter != actors_.end()) {
  434. return iter->second.get();
  435. } else {
  436. MS_LOG(ERROR) << "Can't find the actors map of " << actor_info;
  437. return nullptr;
  438. }
  439. }
  440. ActorSetPtr GraphScheduler::Build(const GraphCompilerInfo &graph_compiler_info) {
  441. auto actor_set = std::make_shared<ActorSet>(graph_compiler_info.name_);
  442. MS_EXCEPTION_IF_NULL(actor_set);
  443. (void)actors_.emplace(actor_set->name_, actor_set);
  444. auto host_queue = std::make_shared<HostTensorQueue>();
  445. actor_set->data_source_actors_ = BuildDataSourceActor(graph_compiler_info, host_queue);
  446. actor_set->custom_actors_ = BuildCustomActor(graph_compiler_info);
  447. actor_set->kernel_actors_ = BuildKernelActor(graph_compiler_info);
  448. actor_set->super_kernel_actors_ = BuildSuperKernelActor(graph_compiler_info);
  449. actor_set->loop_count_actor_ = BuildLoopCountActor(graph_compiler_info);
  450. actor_set->output_actor_ = BuildOutputActor(graph_compiler_info);
  451. actor_set->data_prepare_actor_ =
  452. BuildDataPrepareActor(graph_compiler_info, actor_set->data_source_actors_, host_queue);
  453. actor_set->control_actors_ = control_node_scheduler_.Build(graph_compiler_info, memory_manager_aid_);
  454. return actor_set;
  455. }
  456. void GraphScheduler::CacheGraphOutputToActor(const GraphCompilerInfo &graph_compiler_info) {
  457. if (graph_compiler_info.strategy_ == GraphExecutionStrategy::kStep) {
  458. return;
  459. }
  460. for (const auto &graph : graph_compiler_info.graphs_) {
  461. MS_EXCEPTION_IF_NULL(graph);
  462. auto outputs = AnfAlgo::GetAllOutputWithIndex(graph->output());
  463. for (const auto &output_with_index : outputs) {
  464. auto output_kernel = output_with_index.first;
  465. MS_EXCEPTION_IF_NULL(output_kernel);
  466. auto origin_output_with_index = graph->GetFrontNodeWithIndexByGraphOutput(output_with_index);
  467. if (origin_output_with_index.first == nullptr) {
  468. MS_LOG(WARNING) << "The graph " << graph->graph_id() << " output node:" << output_kernel->fullname_with_scope()
  469. << " with index: " << output_with_index.second << " has no front node.";
  470. continue;
  471. }
  472. auto kernel_type = FetchKernelTransformType(output_kernel, graph, graph_compiler_info.origin_parameters_order_);
  473. auto output_actor = FetchActor(kernel_type, graph_compiler_info.name_, output_kernel, graph);
  474. if (output_actor == nullptr) {
  475. MS_LOG(INFO) << "The graph " << graph->graph_id() << " output node:" << output_kernel->fullname_with_scope()
  476. << " with index:" << output_with_index.second
  477. << " is not actor, and the kernel type is:" << kernel_type;
  478. }
  479. auto output_actor_name = (output_actor != nullptr) ? output_actor->GetAID().Name() : "";
  480. (void)graph_output_to_actor_.emplace(origin_output_with_index, GraphOutputPair(output_actor, output_with_index));
  481. MS_LOG(INFO) << "Cache the graph " << graph->graph_id() << " output node:" << output_kernel->fullname_with_scope()
  482. << " with index:" << output_with_index.second << " to actor:" << output_actor_name
  483. << ", from front node:" << origin_output_with_index.first->fullname_with_scope()
  484. << " with index:" << origin_output_with_index.second;
  485. }
  486. }
  487. }
  488. void GraphScheduler::Link(ActorSet *actor_set, const GraphCompilerInfo &graph_compiler_info) {
  489. MS_EXCEPTION_IF_NULL(actor_set);
  490. std::vector<AbstractActor *> auto_monad_actors;
  491. std::vector<CNodePtr> communication_nodes;
  492. for (const auto &graph : graph_compiler_info.graphs_) {
  493. MS_EXCEPTION_IF_NULL(graph);
  494. if (graph->execution_order().empty()) {
  495. MS_LOG(INFO) << "The graph " << graph->graph_id() << " is an empty graph and skips linking.";
  496. continue;
  497. }
  498. if (graph->is_executing_sink()) {
  499. LinkDataArrowInSinkMode(graph, graph_compiler_info, &auto_monad_actors);
  500. } else {
  501. LinkDataArrowInNonSinkMode(graph, graph_compiler_info, &auto_monad_actors, &communication_nodes);
  502. }
  503. }
  504. LinkGlobalControlArrow(actor_set, communication_nodes, auto_monad_actors, graph_compiler_info);
  505. LinkOutputResultArrowForOutputActor(actor_set->output_actor_.get(), graph_compiler_info);
  506. // The copy actors are built in the link, so need push into the actor set after link.
  507. actor_set->copy_actors_ = copy_actors_;
  508. // Link the arrow in the control flow scene.
  509. if (graph_compiler_info.strategy_ == GraphExecutionStrategy::kPipeline &&
  510. graph_compiler_info.control_node_parser_ != nullptr && graph_compiler_info.control_node_parser_->IsInited()) {
  511. control_node_scheduler_.Link(actor_set, graph_compiler_info);
  512. }
  513. }
  514. std::vector<DataSourceActorPtr> GraphScheduler::BuildDataSourceActor(const GraphCompilerInfo &graph_compiler_info,
  515. const HostTensorQueuePtr &host_queue) {
  516. std::vector<DataSourceActorPtr> data_source_actors;
  517. HostQueueDSActorPtr host_queue_ds_actor = nullptr;
  518. size_t data_node_position = 0;
  519. mindspore::HashMap<AnfNodePtr, size_t> front_node_position_temp_map;
  520. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  521. const auto &graph = graph_compiler_info.graphs_[i];
  522. const auto &device_context = graph_compiler_info.device_contexts_[i];
  523. MS_EXCEPTION_IF_NULL(graph);
  524. // Build host queue data source actor.
  525. const std::vector<AnfNodePtr> &input_nodes = graph->input_nodes();
  526. const auto &root_parameters = graph_compiler_info.origin_parameters_order_;
  527. for (size_t j = 0; j < input_nodes.size(); j++) {
  528. const auto &input_node = input_nodes[j];
  529. MS_EXCEPTION_IF_NULL(input_node);
  530. if (IsHostQueueDSActor(input_node, graph, root_parameters, graph_compiler_info.strategy_)) {
  531. // In control flow, parameters from subgraph need not init in data source actor.
  532. if (graph_compiler_info.control_node_parser_->IsInited()) {
  533. auto node_with_index = graph->GetElementInTupleBackendFrontIndexMap(input_node);
  534. if (node_with_index.first != nullptr && node_with_index.first->isa<Parameter>() &&
  535. find(root_parameters.begin(), root_parameters.end(), node_with_index.first) == root_parameters.end())
  536. continue;
  537. }
  538. if (host_queue_ds_actor == nullptr) {
  539. auto actor_name = graph_compiler_info.name_ + "_HostDSActor";
  540. MS_LOG(INFO) << "Create host queue data source actor: " << actor_name;
  541. host_queue_ds_actor = std::make_shared<HostQueueDataSourceActor>(actor_name, 1, memory_manager_aid_, nullptr,
  542. nullptr, host_queue);
  543. InsertActor(host_queue_ds_actor.get());
  544. (void)data_source_actors.emplace_back(host_queue_ds_actor);
  545. }
  546. const auto &front_node = FetchFrontNodeByBackendNode(input_node, graph);
  547. // In the scenario where multiple backend nodes correspond to the same front node, only the first backend node
  548. // is saved in the host queue data source actor.
  549. if (front_node_position_temp_map.count(front_node) > 0) {
  550. (void)host_queue_ds_actor->data_node_position_map_.emplace(input_node,
  551. front_node_position_temp_map[front_node]);
  552. continue;
  553. }
  554. (void)host_queue_ds_actor->data_nodes_.emplace_back(input_node);
  555. (void)host_queue_ds_actor->device_contexts_.emplace_back(device_context);
  556. (void)host_queue_ds_actor->data_node_position_map_.emplace(input_node, data_node_position);
  557. // In control flow, need to rely on the front node to find the location of the corresponding real parameter.
  558. (void)host_queue_ds_actor->data_node_position_map_.emplace(front_node, data_node_position);
  559. (void)front_node_position_temp_map.emplace(front_node, data_node_position);
  560. data_node_position++;
  561. }
  562. }
  563. // The graph sink mode has no device queue data source actor.
  564. if (!graph->is_executing_sink()) {
  565. // Build device queue data source actor.
  566. const auto &execution_order = graph->execution_order();
  567. const auto &iter =
  568. std::find_if(execution_order.begin(), execution_order.end(), [&graph_compiler_info](const CNodePtr &node) {
  569. return IsDeviceQueueDSActor(node, graph_compiler_info.strategy_);
  570. });
  571. if (iter != execution_order.end()) {
  572. auto actor_name = graph_compiler_info.name_ + "_DeviceDSActor" + "_" + std::to_string(graph->graph_id());
  573. MS_LOG(INFO) << "Create queue data source actor: " << actor_name;
  574. auto device_queue_ds_actor = std::make_shared<DeviceQueueDataSourceActor>(
  575. actor_name, 1, device_context, memory_manager_aid_, debug_aid_, recorder_aid_);
  576. MS_EXCEPTION_IF_NULL(device_queue_ds_actor);
  577. InsertActor(device_queue_ds_actor.get());
  578. (void)data_source_actors.emplace_back(device_queue_ds_actor);
  579. device_queue_ds_actor->data_kernel_ = *iter;
  580. device_queue_ds_actor->kernel_info_ = dynamic_cast<device::KernelInfo *>((*iter)->kernel_info());
  581. }
  582. }
  583. }
  584. const auto parser = graph_compiler_info.control_node_parser_;
  585. MS_EXCEPTION_IF_NULL(parser);
  586. // Initialize the parameter in the control node, first get all the front parameters in the control node, then find
  587. // the corresponding backend parameter from the map, and insert it into the host data source actor.
  588. const auto &control_node_parameters = parser->control_node_parameters();
  589. for (const auto &parameter : control_node_parameters) {
  590. if (IsPersistentDeviceTensor(parameter)) {
  591. continue;
  592. }
  593. if (host_queue_ds_actor == nullptr) {
  594. auto actor_name = graph_compiler_info.name_ + "_HostDSActor";
  595. MS_LOG(INFO) << "Create host queue data source actor: " << actor_name;
  596. host_queue_ds_actor =
  597. std::make_shared<HostQueueDataSourceActor>(actor_name, 1, memory_manager_aid_, nullptr, nullptr, host_queue);
  598. InsertActor(host_queue_ds_actor.get());
  599. (void)data_source_actors.emplace_back(host_queue_ds_actor);
  600. }
  601. auto &node_map = host_queue_ds_actor->data_node_position_map_;
  602. if (node_map.find(parameter) != node_map.end()) {
  603. continue;
  604. }
  605. const auto &backend_parameter_with_context =
  606. parser->FetchBackendParameterWithContextByFrontParameter({parameter, 0});
  607. const auto &backend_node = backend_parameter_with_context.first;
  608. MS_EXCEPTION_IF_NULL(backend_node);
  609. auto iter = find(host_queue_ds_actor->data_nodes_.begin(), host_queue_ds_actor->data_nodes_.end(), backend_node);
  610. if (iter != host_queue_ds_actor->data_nodes_.end()) {
  611. (void)node_map.emplace(parameter, iter - host_queue_ds_actor->data_nodes_.begin());
  612. } else {
  613. (void)node_map.emplace(parameter, host_queue_ds_actor->data_nodes_.size());
  614. (void)node_map.emplace(backend_node, host_queue_ds_actor->data_nodes_.size());
  615. (void)host_queue_ds_actor->data_nodes_.emplace_back(backend_node);
  616. (void)host_queue_ds_actor->device_contexts_.emplace_back(backend_parameter_with_context.second);
  617. }
  618. }
  619. return data_source_actors;
  620. }
  621. std::vector<CustomActorPtr> GraphScheduler::BuildCustomActor(const GraphCompilerInfo &graph_compiler_info) {
  622. std::vector<CustomActorPtr> custom_actors;
  623. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  624. const auto &device_context = graph_compiler_info.device_contexts_[i];
  625. const auto &graph = graph_compiler_info.graphs_[i];
  626. MS_EXCEPTION_IF_NULL(graph);
  627. if (graph->is_executing_sink()) {
  628. continue;
  629. }
  630. auto all_nodes = TopoSort(graph->get_return());
  631. for (const auto &node : all_nodes) {
  632. if (!AnfUtils::IsCustomActorNode(node)) {
  633. continue;
  634. }
  635. auto actor_name = AnfUtils::GetCustomActorName(node);
  636. auto custom_actor = std::make_shared<CustomActor>(actor_name, node, device_context, recorder_aid_);
  637. MS_EXCEPTION_IF_NULL(custom_actor);
  638. InsertActor(custom_actor.get());
  639. custom_actors.emplace_back(custom_actor);
  640. }
  641. }
  642. return custom_actors;
  643. }
  644. std::vector<KernelActorPtr> GraphScheduler::BuildKernelActor(const GraphCompilerInfo &graph_compiler_info) {
  645. std::vector<KernelActorPtr> kernel_actors;
  646. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  647. const auto &graph = graph_compiler_info.graphs_[i];
  648. const auto &device_context = graph_compiler_info.device_contexts_[i];
  649. MS_EXCEPTION_IF_NULL(graph);
  650. if (graph->is_executing_sink()) {
  651. continue;
  652. }
  653. auto execution_order = graph->execution_order();
  654. // Single op graph in step mode, kernel actor executes synchronously.
  655. bool is_single_op_graph = execution_order.size() == 1;
  656. GraphExecutionStrategy strategy = graph_compiler_info.strategy_;
  657. if (strategy == GraphExecutionStrategy::kStep) {
  658. strategy = (is_single_op_graph ? strategy : GraphExecutionStrategy::kPipeline);
  659. }
  660. for (auto &kernel : execution_order) {
  661. MS_EXCEPTION_IF_NULL(kernel);
  662. if (IsKernelActor(kernel, graph_compiler_info.strategy_) && (!IsSkippedKernelActor(kernel))) {
  663. auto ref_input_indexes = FetchModifiableRefInputIndex(kernel);
  664. auto ref_output_indexes = FetchModifiableRefOutputIndex(kernel, graph);
  665. auto kernel_actor =
  666. std::make_shared<KernelActor>(kernel->fullname_with_scope(), kernel, device_context, memory_manager_aid_,
  667. debug_aid_, recorder_aid_, strategy, ref_input_indexes, ref_output_indexes);
  668. MS_EXCEPTION_IF_NULL(kernel_actor);
  669. InsertActor(kernel_actor.get());
  670. (void)kernel_actors.emplace_back(kernel_actor);
  671. }
  672. }
  673. }
  674. return kernel_actors;
  675. }
  676. std::vector<SuperKernelActorPtr> GraphScheduler::BuildSuperKernelActor(const GraphCompilerInfo &graph_compiler_info) {
  677. std::vector<SuperKernelActorPtr> super_kernel_actors;
  678. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  679. const auto &graph = graph_compiler_info.graphs_[i];
  680. const auto &device_context = graph_compiler_info.device_contexts_[i];
  681. MS_EXCEPTION_IF_NULL(graph);
  682. if (!graph->is_executing_sink()) {
  683. continue;
  684. }
  685. if (graph->execution_order().empty()) {
  686. MS_LOG(INFO) << "The graph " << graph->graph_id() << " is an empty graph and skips building.";
  687. continue;
  688. }
  689. auto actor_name = graph->ToString() + "_SuperKernelActor";
  690. auto super_kernel_actor =
  691. std::make_shared<SuperKernelActor>(actor_name, graph, device_context, memory_manager_aid_, debug_aid_, nullptr);
  692. MS_EXCEPTION_IF_NULL(super_kernel_actor);
  693. InsertActor(super_kernel_actor.get());
  694. (void)super_kernel_actors.emplace_back(super_kernel_actor);
  695. }
  696. return super_kernel_actors;
  697. }
  698. LoopCountActorPtr GraphScheduler::BuildLoopCountActor(const GraphCompilerInfo &graph_compiler_info) {
  699. auto actor_set = Fetch(graph_compiler_info.name_);
  700. if ((graph_compiler_info.strategy_ == GraphExecutionStrategy::kStep) && IsSingleOpActorSet(actor_set)) {
  701. return nullptr;
  702. }
  703. auto loop_count = ConfigManager::GetInstance().iter_num();
  704. if ((graph_compiler_info.strategy_ == GraphExecutionStrategy::kStep) ||
  705. (graph_compiler_info.graphs_.size() == 1 && graph_compiler_info.graphs_[0]->is_loop_count_sink())) {
  706. loop_count = 1;
  707. }
  708. auto actor_name = graph_compiler_info.name_ + "_LoopCountActor";
  709. auto loop_count_actor =
  710. std::make_shared<LoopCountActor>(actor_name, loop_count, memory_manager_aid_, debug_aid_, recorder_aid_);
  711. MS_LOG(INFO) << "Create loop count actor: " << actor_name;
  712. MS_EXCEPTION_IF_NULL(loop_count_actor);
  713. InsertActor(loop_count_actor.get());
  714. return loop_count_actor;
  715. }
  716. OutputActorPtr GraphScheduler::BuildOutputActor(const GraphCompilerInfo &graph_compiler_info) {
  717. auto actor_set = Fetch(graph_compiler_info.name_);
  718. if ((graph_compiler_info.strategy_ == GraphExecutionStrategy::kStep) && IsSingleOpActorSet(actor_set)) {
  719. return nullptr;
  720. }
  721. auto loop_count = ConfigManager::GetInstance().iter_num();
  722. if ((graph_compiler_info.strategy_ == GraphExecutionStrategy::kStep) ||
  723. (graph_compiler_info.graphs_.size() == 1 && graph_compiler_info.graphs_[0]->is_loop_count_sink())) {
  724. loop_count = 1;
  725. }
  726. auto actor_name = graph_compiler_info.name_ + "_" + "OutputActor";
  727. auto output_actor = std::make_shared<OutputActor>(actor_name, loop_count, graph_compiler_info.outputs_num_);
  728. MS_LOG(INFO) << "Create output actor: " << actor_name;
  729. MS_EXCEPTION_IF_NULL(output_actor);
  730. InsertActor(output_actor.get());
  731. return output_actor;
  732. }
  733. DataPrepareActorPtr GraphScheduler::BuildDataPrepareActor(const GraphCompilerInfo &graph_compiler_info,
  734. const std::vector<DataSourceActorPtr> &data_source_actors,
  735. const HostTensorQueuePtr &host_queue) {
  736. HostQueueDSActorPtr host_queue_ds_actor = nullptr;
  737. auto iter = std::find_if(data_source_actors.begin(), data_source_actors.end(), [&](const auto &data_source_actor) {
  738. return data_source_actor->type_ == KernelTransformType::kHostDataSourceActor;
  739. });
  740. if (iter != data_source_actors.end()) {
  741. host_queue_ds_actor = std::dynamic_pointer_cast<HostQueueDataSourceActor>(*iter);
  742. }
  743. auto actor_name = graph_compiler_info.name_ + "_DataPrepareActor";
  744. auto data_prepare_actor = std::make_shared<DataPrepareActor>(actor_name, memory_manager_aid_, debug_aid_,
  745. &graph_compiler_info, host_queue_ds_actor, host_queue);
  746. MS_LOG(INFO) << "Create data prepare actor: " << actor_name;
  747. MS_EXCEPTION_IF_NULL(data_prepare_actor);
  748. // Cache the nodes which need continuous memory.
  749. if (graph_compiler_info.strategy_ == GraphExecutionStrategy::kPipeline) {
  750. for (size_t index = 0; index < graph_compiler_info.graphs_.size(); ++index) {
  751. const auto &graph = graph_compiler_info.graphs_[index];
  752. MS_EXCEPTION_IF_NULL(graph);
  753. if (graph->is_executing_sink()) {
  754. continue;
  755. }
  756. auto &execution_order = graph->execution_order();
  757. for (auto &kernel : execution_order) {
  758. if (!AnfAlgo::IsCommunicationOp(kernel)) {
  759. continue;
  760. }
  761. auto key = std::make_pair(kernel, graph_compiler_info.device_contexts_[index]);
  762. auto value = std::make_pair(false, false);
  763. if (AnfAlgo::GetInputTensorNum(kernel) > 1) {
  764. value.first = true;
  765. }
  766. if (AnfAlgo::GetOutputTensorNum(kernel) > 1) {
  767. value.second = true;
  768. }
  769. if ((value.first == true) || (value.second == true)) {
  770. data_prepare_actor->continuous_memory_nodes_[key] = value;
  771. }
  772. }
  773. }
  774. }
  775. InsertActor(data_prepare_actor.get());
  776. return data_prepare_actor;
  777. }
  778. std::vector<AbstractActorPtr> GraphScheduler::BuildNoInputKernelActor(const ActorSet *actor_set,
  779. GraphExecutionStrategy strategy) {
  780. MS_EXCEPTION_IF_NULL(actor_set);
  781. std::vector<AbstractActorPtr> no_input_kernel_actors;
  782. for (auto &super_kernel_actor : actor_set->super_kernel_actors_) {
  783. MS_EXCEPTION_IF_NULL(super_kernel_actor);
  784. if ((super_kernel_actor->input_datas_num_ == 0) && (super_kernel_actor->input_controls_num_ == 0)) {
  785. (void)no_input_kernel_actors.emplace_back(super_kernel_actor);
  786. }
  787. }
  788. for (auto &kernel_actor : actor_set->kernel_actors_) {
  789. MS_EXCEPTION_IF_NULL(kernel_actor);
  790. // Framework will trigger kernel actor running in the step execution strategy.
  791. if (strategy == GraphExecutionStrategy::kStep && IsSingleOpActorSet(actor_set)) {
  792. kernel_actor->input_controls_num_++;
  793. continue;
  794. }
  795. if ((kernel_actor->input_datas_num_ == 0) && (kernel_actor->input_controls_num_ == 0)) {
  796. (void)no_input_kernel_actors.emplace_back(kernel_actor);
  797. }
  798. }
  799. return no_input_kernel_actors;
  800. }
  801. void GraphScheduler::LinkDataArrowInSinkMode(const KernelGraphPtr &graph, const GraphCompilerInfo &graph_compiler_info,
  802. std::vector<AbstractActor *> *const auto_monad_actors) {
  803. MS_EXCEPTION_IF_NULL(graph);
  804. // The data arrow linking is taken over by the control flow.
  805. if (graph_compiler_info.control_node_parser_ != nullptr &&
  806. graph_compiler_info.control_node_parser_->IsControlFlowDataArrow(graph, nullptr)) {
  807. return;
  808. }
  809. auto to_actor_name = graph->ToString() + "_SuperKernelActor";
  810. auto to_actor = FetchActor(to_actor_name);
  811. MS_EXCEPTION_IF_NULL(to_actor);
  812. auto &input_nodes = graph->input_nodes();
  813. for (size_t node_index = 0; node_index < input_nodes.size(); ++node_index) {
  814. auto &input_node = input_nodes[node_index];
  815. MS_EXCEPTION_IF_NULL(input_node);
  816. if (HasAbstractMonad(input_node)) {
  817. MS_LOG(INFO) << "The graph:" << graph->graph_id()
  818. << " has abstract monad input node:" << input_node->DebugString() << ", input index:" << node_index;
  819. LinkControlArrowByAutoMonad(to_actor, input_node, graph);
  820. continue; // No data arrow for monad input.
  821. }
  822. UpdateRefCount(input_node, 0, true);
  823. KernelWithIndex from_kernel_with_output_idx = std::make_pair(input_node, 0);
  824. KernelWithIndex to_kernel_with_input_idx = std::make_pair(input_node, node_index);
  825. // The gather of linking data arrows of kernel by the different from kernel type.
  826. LinkDataArrow(to_actor, graph_compiler_info, graph, from_kernel_with_output_idx, to_kernel_with_input_idx);
  827. }
  828. std::vector<CNodePtr> auto_monad_kernels;
  829. // Foreach the execution order to get the auto monad kernels.
  830. auto &execution_order = graph->execution_order();
  831. (void)std::for_each(execution_order.begin(), execution_order.end(), [&](const CNodePtr &kernel) {
  832. for (size_t i = 0; i < AnfAlgo::GetInputNum(kernel); ++i) {
  833. auto input_node = AnfAlgo::GetInputNode(kernel, i);
  834. if (HasAbstractMonad(input_node)) {
  835. (void)auto_monad_kernels.emplace_back(kernel);
  836. continue;
  837. }
  838. }
  839. });
  840. // Foreach auto monad kernels to get the auto monad device tensor stores.
  841. (void)std::for_each(auto_monad_kernels.begin(), auto_monad_kernels.end(), [&](const CNodePtr &kernel) {
  842. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) {
  843. KernelWithIndex from_kernel_with_output_idx = AnfAlgo::GetPrevNodeOutput(kernel, i, false);
  844. auto front_node = FetchFrontNodeByBackendNode(from_kernel_with_output_idx.first, graph);
  845. if (IsPersistentDeviceTensor(front_node)) {
  846. (void)to_actor->auto_monad_device_tensor_stores_.insert(front_node);
  847. }
  848. }
  849. });
  850. if (to_actor->auto_monad_device_tensor_stores_.size() > 0) {
  851. (void)auto_monad_actors->emplace_back(to_actor);
  852. }
  853. }
  854. void GraphScheduler::LinkDataArrowInNonSinkMode(const KernelGraphPtr &graph,
  855. const GraphCompilerInfo &graph_compiler_info,
  856. std::vector<AbstractActor *> *const auto_monad_actors,
  857. std::vector<CNodePtr> *const communication_nodes) {
  858. MS_EXCEPTION_IF_NULL(graph);
  859. MS_EXCEPTION_IF_NULL(auto_monad_actors);
  860. MS_EXCEPTION_IF_NULL(communication_nodes);
  861. const mindspore::HashSet<PrimitivePtr, PrimitiveHasher, PrimitiveEqual> auto_monad_prims = {
  862. prim::kPrimDepend, prim::kPrimUpdateState, prim::kPrimLoad};
  863. auto &execution_order = graph->execution_order();
  864. // Foreach the execution order to link the actors.
  865. for (const auto &kernel : execution_order) {
  866. MS_EXCEPTION_IF_NULL(kernel);
  867. if (AnfAlgo::IsCommunicationOp(kernel)) {
  868. (void)communication_nodes->emplace_back(kernel);
  869. }
  870. if (IsSkippedKernelActor(kernel) || (!IsKernelActor(kernel, graph_compiler_info.strategy_))) {
  871. continue;
  872. }
  873. const auto &kernel_actor = FetchActor(kernel->fullname_with_scope());
  874. MS_EXCEPTION_IF_NULL(kernel_actor);
  875. for (size_t i = 0; i < AnfAlgo::GetInputNum(kernel); ++i) {
  876. auto input_node = AnfAlgo::GetInputNode(kernel, i);
  877. // Link the control arrows of kernel actor by the auto monad, the inputs include monad node.
  878. if (IsOneOfPrimitiveCNode(input_node, auto_monad_prims) || HasAbstractMonad(input_node)) {
  879. LinkControlArrowByAutoMonad(kernel_actor, input_node, graph, graph_compiler_info.control_node_parser_);
  880. }
  881. if (HasAbstractMonad(input_node)) {
  882. (void)auto_monad_actors->emplace_back(kernel_actor);
  883. continue; // No data arrow for monad input.
  884. }
  885. KernelWithIndex from_kernel_with_output_idx = AnfAlgo::VisitKernelWithReturnType(input_node, 0, false);
  886. KernelWithIndex to_kernel_with_input_idx = std::make_pair(kernel, i);
  887. // The data arrow linking is taken over by the control flow.
  888. if (graph_compiler_info.control_node_parser_ != nullptr &&
  889. graph_compiler_info.control_node_parser_->IsControlFlowDataArrow(graph, from_kernel_with_output_idx.first)) {
  890. continue;
  891. }
  892. // The gather of linking data arrows of kernel by the different from kernel type.
  893. LinkDataArrow(kernel_actor, graph_compiler_info, graph, from_kernel_with_output_idx, to_kernel_with_input_idx);
  894. }
  895. }
  896. // Link the control arrows for allreduce kernel by the send/recv nodes in the kernel graph.
  897. LinkControlArrowBySendRecvNodes(graph);
  898. }
  899. void GraphScheduler::LinkDataArrow(AbstractActor *const to_actor, const GraphCompilerInfo &graph_compiler_info,
  900. const KernelGraphPtr &graph, const KernelWithIndex &from_kernel_with_output_idx,
  901. const KernelWithIndex &to_kernel_with_input_idx) {
  902. MS_EXCEPTION_IF_NULL(to_actor);
  903. MS_EXCEPTION_IF_NULL(graph);
  904. auto from_kernel = from_kernel_with_output_idx.first;
  905. MS_EXCEPTION_IF_NULL(from_kernel);
  906. auto kernel_type = FetchKernelTransformType(from_kernel, graph, graph_compiler_info.origin_parameters_order_,
  907. graph_compiler_info.strategy_);
  908. auto from_actor = FetchActor(kernel_type, graph_compiler_info.name_, from_kernel, graph);
  909. if (kKernelTypeToLinkFunc.count(kernel_type) == 0) {
  910. if (graph_compiler_info.strategy_ == GraphExecutionStrategy::kPipeline) {
  911. MS_LOG(WARNING) << "Invalid from node:" << from_kernel->fullname_with_scope() << ", type:" << kernel_type;
  912. }
  913. return;
  914. }
  915. (this->*kKernelTypeToLinkFunc[kernel_type])(from_actor, to_actor, from_kernel_with_output_idx,
  916. to_kernel_with_input_idx, graph);
  917. }
  918. void GraphScheduler::LinkDataArrowForDeviceTensorStore(AbstractActor *const, AbstractActor *const to_actor,
  919. const KernelWithIndex &from_kernel_with_output_idx,
  920. const KernelWithIndex &to_kernel_with_input_idx,
  921. const KernelGraphPtr &graph) {
  922. MS_EXCEPTION_IF_NULL(to_actor);
  923. MS_EXCEPTION_IF_NULL(graph);
  924. auto from_kernel = from_kernel_with_output_idx.first;
  925. MS_EXCEPTION_IF_NULL(from_kernel);
  926. auto device_tensor_store_key = FetchFrontNodeByBackendNode(from_kernel, graph);
  927. (void)to_actor->device_tensor_store_keys_.emplace_back(to_kernel_with_input_idx.second, device_tensor_store_key);
  928. }
  929. void GraphScheduler::LinkDataArrowForInternalParameter(AbstractActor *const, AbstractActor *to_actor,
  930. const KernelWithIndex &from_kernel_with_output_idx,
  931. const KernelWithIndex &to_kernel_with_input_idx,
  932. const KernelGraphPtr &graph) {
  933. MS_EXCEPTION_IF_NULL(to_actor);
  934. MS_EXCEPTION_IF_NULL(graph);
  935. auto internal_parameter = from_kernel_with_output_idx.first;
  936. MS_EXCEPTION_IF_NULL(internal_parameter);
  937. // Parameter ---> front node.
  938. auto front_output_with_index = graph->GetFrontNodeByInternalParameter(internal_parameter);
  939. auto front_output_node = front_output_with_index.first;
  940. MS_EXCEPTION_IF_NULL(front_output_node);
  941. if (IsSwitchActor(front_output_node)) {
  942. return;
  943. }
  944. auto real_from_kernel_with_output_idx = from_kernel_with_output_idx;
  945. AbstractActor *real_from_actor = nullptr;
  946. KernelTransformType kernel_type;
  947. if (IsPersistentDeviceTensor(front_output_node)) {
  948. kernel_type = KernelTransformType::kDeviceTensorStore;
  949. } else {
  950. // front node ---> actor.
  951. if (graph_output_to_actor_.count(front_output_with_index) == 0) {
  952. MS_LOG(EXCEPTION) << "Can't find actor by front node:" << AnfAlgo::GetNodeDebugString(front_output_node)
  953. << ", internal parameter:" << AnfAlgo::GetNodeDebugString(internal_parameter);
  954. }
  955. auto actor_pair = graph_output_to_actor_[front_output_with_index];
  956. MS_EXCEPTION_IF_NULL(actor_pair.first);
  957. MS_EXCEPTION_IF_NULL(actor_pair.second.first);
  958. MS_LOG(INFO) << "Graph " << graph->graph_id() << " internal parameter:" << internal_parameter->DebugString()
  959. << ", corresponding front node:" << front_output_node->fullname_with_scope()
  960. << " with index:" << front_output_with_index.second
  961. << ", from actor:" << actor_pair.first->GetAID().Name()
  962. << " node:" << actor_pair.second.first->fullname_with_scope()
  963. << " with index:" << actor_pair.second.second << ", to actor:" << to_actor->GetAID().Name()
  964. << " with index:" << to_kernel_with_input_idx.second;
  965. real_from_actor = actor_pair.first;
  966. real_from_kernel_with_output_idx = actor_pair.second;
  967. kernel_type = actor_pair.first->type_;
  968. }
  969. if (kKernelTypeToLinkFunc.count(kernel_type) == 0) {
  970. MS_LOG(EXCEPTION) << "Invalid internal parameter:" << internal_parameter->DebugString() << ", type:" << kernel_type;
  971. }
  972. (this->*kKernelTypeToLinkFunc[kernel_type])(real_from_actor, to_actor, real_from_kernel_with_output_idx,
  973. to_kernel_with_input_idx, graph);
  974. }
  975. void GraphScheduler::LinkDataArrowForBaseActor(AbstractActor *const from_actor, AbstractActor *const to_actor,
  976. const KernelWithIndex &from_kernel_with_output_idx,
  977. const KernelWithIndex &to_kernel_with_input_idx,
  978. const KernelGraphPtr &) {
  979. MS_EXCEPTION_IF_NULL(from_actor);
  980. MS_EXCEPTION_IF_NULL(to_actor);
  981. auto from_kernel = from_kernel_with_output_idx.first;
  982. MS_EXCEPTION_IF_NULL(from_kernel);
  983. auto from_output_index = from_kernel_with_output_idx.second;
  984. auto to_input_index = to_kernel_with_input_idx.second;
  985. // Get the position of from kernel in the data source actor.
  986. auto position = from_actor->FetchNodePosition(from_kernel);
  987. if ((from_actor->device_contexts_.size() <= position) || (to_actor->device_contexts_.size() <= 0)) {
  988. MS_LOG(EXCEPTION) << "The device contexts size is wrong.";
  989. }
  990. if (IsNeedInsertCopyActor(from_actor->device_contexts_[position], to_actor->device_contexts_[0])) {
  991. LinkDataArrowForCopyActor(from_actor, to_actor, from_kernel_with_output_idx, to_kernel_with_input_idx);
  992. } else {
  993. AddDataArrow(from_actor, to_actor, from_kernel, from_output_index, to_input_index);
  994. }
  995. }
  996. void GraphScheduler::LinkDataArrowForHostDSActor(AbstractActor *const from_actor, AbstractActor *const to_actor,
  997. const KernelWithIndex &from_kernel_with_output_idx,
  998. const KernelWithIndex &to_kernel_with_input_idx,
  999. const KernelGraphPtr &graph) {
  1000. auto host_ds_actor = dynamic_cast<HostQueueDataSourceActor *>(from_actor);
  1001. MS_EXCEPTION_IF_NULL(host_ds_actor);
  1002. MS_EXCEPTION_IF_NULL(from_kernel_with_output_idx.first);
  1003. KernelWithIndex real_from_kernel_with_output_idx = from_kernel_with_output_idx;
  1004. // Get the position and real kernel by from kernel in the data source actor.
  1005. auto position = host_ds_actor->FetchNodePosition(from_kernel_with_output_idx.first);
  1006. real_from_kernel_with_output_idx.first = host_ds_actor->FetchNode(position);
  1007. LinkDataArrowForBaseActor(from_actor, to_actor, real_from_kernel_with_output_idx, to_kernel_with_input_idx, graph);
  1008. }
  1009. void GraphScheduler::LinkDataArrowForKernelActor(AbstractActor *const from_actor, AbstractActor *const to_actor,
  1010. const KernelWithIndex &from_kernel_with_output_idx,
  1011. const KernelWithIndex &to_kernel_with_input_idx,
  1012. const KernelGraphPtr &graph) {
  1013. auto real_from_actor = from_actor;
  1014. auto real_from_kernel_with_output_idx = from_kernel_with_output_idx;
  1015. auto from_kernel = from_kernel_with_output_idx.first;
  1016. // Update the from kernel info by the real node info.
  1017. MS_EXCEPTION_IF_NULL(from_kernel);
  1018. if (IsSkippedKernelActor(from_kernel)) {
  1019. real_from_kernel_with_output_idx = AnfAlgo::GetPrevNodeOutput(from_kernel, 0, false);
  1020. MS_EXCEPTION_IF_NULL(real_from_kernel_with_output_idx.first);
  1021. LinkControlArrowBySkippedNode(to_actor, from_kernel);
  1022. MS_EXCEPTION_IF_NULL(to_kernel_with_input_idx.first);
  1023. MS_LOG(INFO) << "Link data arrow for inplace node, aggregate node: "
  1024. << to_kernel_with_input_idx.first->fullname_with_scope()
  1025. << ", aggregate input index: " << to_kernel_with_input_idx.second
  1026. << ", skip node: " << from_kernel->fullname_with_scope()
  1027. << ", real node: " << real_from_kernel_with_output_idx.first->fullname_with_scope();
  1028. real_from_actor = FetchActor(real_from_kernel_with_output_idx.first->fullname_with_scope());
  1029. MS_EXCEPTION_IF_NULL(real_from_actor);
  1030. }
  1031. LinkDataArrowForBaseActor(real_from_actor, to_actor, real_from_kernel_with_output_idx, to_kernel_with_input_idx,
  1032. graph);
  1033. }
  1034. void GraphScheduler::LinkDataArrowForCopyActor(AbstractActor *const from_actor, AbstractActor *const to_actor,
  1035. const KernelWithIndex &from_kernel_with_output_idx,
  1036. const KernelWithIndex &to_kernel_with_input_idx) {
  1037. MS_EXCEPTION_IF_NULL(from_actor);
  1038. MS_EXCEPTION_IF_NULL(to_actor);
  1039. auto from_kernel = from_kernel_with_output_idx.first;
  1040. MS_EXCEPTION_IF_NULL(from_kernel);
  1041. std::string name = "copy_from:" + from_actor->GetAID().Name() + "_node:" + from_kernel->fullname_with_scope() +
  1042. "_output_index:" + std::to_string(from_kernel_with_output_idx.second);
  1043. CopyActor *copy_actor = dynamic_cast<CopyActor *>(FetchActor(name));
  1044. // Link between from actor and copy actor.
  1045. if (copy_actor == nullptr) {
  1046. // Create the copy actor.
  1047. auto copy_actor_shared_ptr = std::make_shared<CopyActor>(name, memory_manager_aid_);
  1048. (void)copy_actors_.emplace_back(copy_actor_shared_ptr);
  1049. copy_actor = copy_actor_shared_ptr.get();
  1050. MS_EXCEPTION_IF_NULL(copy_actor);
  1051. InsertActor(copy_actor);
  1052. // Set the member device_contexts_ of the copy actor.
  1053. auto position = from_actor->FetchNodePosition(from_kernel);
  1054. if ((from_actor->device_contexts_.size() <= position) || (to_actor->device_contexts_.size() <= 0)) {
  1055. MS_LOG(EXCEPTION) << "The device contexts size is wrong.";
  1056. }
  1057. auto from_device_context = from_actor->device_contexts_[position];
  1058. auto to_device_context = to_actor->device_contexts_[0];
  1059. MS_EXCEPTION_IF_NULL(from_device_context);
  1060. MS_EXCEPTION_IF_NULL(to_device_context);
  1061. (void)copy_actor->device_contexts_.emplace_back(from_device_context);
  1062. (void)copy_actor->device_contexts_.emplace_back(to_device_context);
  1063. // Set the member output_ of the copy actor.
  1064. if (to_actor->type_ == KernelTransformType::kSuperKernelActor) {
  1065. copy_actor->output_ = AnfAlgo::GetMutableOutputAddr(to_kernel_with_input_idx.first, 0, false);
  1066. } else {
  1067. copy_actor->output_ =
  1068. AnfAlgo::GetPrevNodeMutableOutputAddr(to_kernel_with_input_idx.first, to_kernel_with_input_idx.second, false);
  1069. }
  1070. MS_EXCEPTION_IF_NULL(copy_actor->output_);
  1071. if (copy_actor->output_->DeviceType() != to_device_context->GetDeviceAddressType()) {
  1072. MS_LOG(EXCEPTION) << "The device type is not equal, output device type:" << copy_actor->output_->DeviceType()
  1073. << ", to device context type:" << to_device_context->GetDeviceAddressType();
  1074. }
  1075. // Link between from actor and copy actor.
  1076. AddDataArrow(from_actor, copy_actor, from_kernel, from_kernel_with_output_idx.second, 0);
  1077. }
  1078. // If the copy actor already exists, only need link between copy actor and to actor.
  1079. AddDataArrow(copy_actor, to_actor, nullptr, 0, to_kernel_with_input_idx.second);
  1080. if (to_actor->type_ == KernelTransformType::kSuperKernelActor) {
  1081. UpdateRefCount(copy_actor->output_.get(), true);
  1082. } else {
  1083. UpdateRefCount(copy_actor->output_.get(), false);
  1084. }
  1085. }
  1086. void GraphScheduler::LinkControlArrowByAutoMonad(AbstractActor *to_actor, const AnfNodePtr &from_node,
  1087. const KernelGraphPtr &graph, const ControlNodeParserPtr &parser) {
  1088. MS_EXCEPTION_IF_NULL(to_actor);
  1089. MS_EXCEPTION_IF_NULL(from_node);
  1090. MS_EXCEPTION_IF_NULL(graph);
  1091. // Find the real input node, include the monad node and make tuple node.
  1092. const std::vector<PrimitivePtr> return_types = {prim::kPrimDepend, prim::kPrimUpdateState, prim::kPrimLoad,
  1093. prim::kPrimMakeTuple};
  1094. const auto &input_kernel_with_output_idx = AnfAlgo::VisitKernelWithReturnType(from_node, 0, false, return_types);
  1095. MS_EXCEPTION_IF_NULL(input_kernel_with_output_idx.first);
  1096. auto input_anfnode = input_kernel_with_output_idx.first;
  1097. CNodePtr input_cnode = nullptr;
  1098. if (input_anfnode->isa<CNode>()) {
  1099. input_cnode = input_anfnode->cast<CNodePtr>();
  1100. }
  1101. // Make tuple node needs to be expanded.
  1102. if (AnfAlgo::CheckPrimitiveType(input_anfnode, prim::kPrimMakeTuple)) {
  1103. MS_EXCEPTION_IF_NULL(input_cnode);
  1104. for (size_t i = 1; i < input_cnode->inputs().size(); ++i) {
  1105. LinkControlArrowByAutoMonad(to_actor, input_cnode->input(i), graph, parser);
  1106. }
  1107. return;
  1108. }
  1109. const mindspore::HashSet<PrimitivePtr, PrimitiveHasher, PrimitiveEqual> recursion_prims = {
  1110. prim::kPrimDepend, prim::kPrimUpdateState, prim::kPrimLoad, prim::kPrimMakeTuple};
  1111. // Get the real depend input by monad node which needs to link the control arrow.
  1112. std::vector<AnfNodePtr> real_depend_inputs;
  1113. if (AnfAlgo::CheckPrimitiveType(input_anfnode, prim::kPrimDepend) ||
  1114. AnfAlgo::CheckPrimitiveType(input_anfnode, prim::kPrimLoad)) {
  1115. MS_EXCEPTION_IF_NULL(input_cnode);
  1116. real_depend_inputs.push_back(input_cnode->input(kDependAttachNodeIndex));
  1117. // The real input may be this scene: depend/load --> load/depend, so need add the control arrow for real input
  1118. // node in this scene.
  1119. if (IsOneOfPrimitiveCNode(input_cnode->input(kRealInputIndexInDepend), recursion_prims)) {
  1120. real_depend_inputs.push_back(input_cnode->input(kRealInputIndexInDepend));
  1121. }
  1122. } else if (AnfAlgo::CheckPrimitiveType(input_anfnode, prim::kPrimUpdateState)) {
  1123. MS_EXCEPTION_IF_NULL(input_cnode);
  1124. for (size_t i = kUpdateStateRealInput; i < input_cnode->inputs().size(); ++i) {
  1125. real_depend_inputs.push_back(input_cnode->input(i));
  1126. }
  1127. } else {
  1128. real_depend_inputs.push_back(input_anfnode);
  1129. }
  1130. for (const auto &real_depend_input : real_depend_inputs) {
  1131. auto real_depend_input_with_idx = AnfAlgo::VisitKernelWithReturnType(real_depend_input, 0, false, return_types);
  1132. MS_EXCEPTION_IF_NULL(real_depend_input_with_idx.first);
  1133. auto real_depend_kernel = real_depend_input_with_idx.first;
  1134. // Update the real depend kernel in the subgraphs connecting scene.
  1135. if (IsInternalParameter(real_depend_kernel, graph)) {
  1136. auto front_output_with_index = graph->GetFrontNodeByInternalParameter(real_depend_kernel);
  1137. MS_EXCEPTION_IF_NULL(front_output_with_index.first);
  1138. if (graph_output_to_actor_.count(front_output_with_index) == 0) {
  1139. if (AnfAlgo::IsCallNode(front_output_with_index.first)) {
  1140. continue;
  1141. }
  1142. MS_LOG(EXCEPTION) << "Can't find graph output by front node:" << front_output_with_index.first->DebugString();
  1143. }
  1144. if (parser != nullptr && parser->IsInited() &&
  1145. (!parser->IsSameKernelGraphGroup(front_output_with_index.first, graph))) {
  1146. MS_LOG(DEBUG) << "Skip in control flow from node:" << front_output_with_index.first->DebugString()
  1147. << " is not in the graph:" << graph->ToString();
  1148. continue;
  1149. }
  1150. real_depend_kernel = graph_output_to_actor_[front_output_with_index].second.first;
  1151. MS_EXCEPTION_IF_NULL(real_depend_kernel);
  1152. MS_LOG(INFO) << "The graph " << graph->graph_id() << " link control arrow by auto monad from internal parameter: "
  1153. << real_depend_input_with_idx.first->DebugString()
  1154. << ", front output node: " << front_output_with_index.first->fullname_with_scope()
  1155. << ", backend output node: " << real_depend_kernel->fullname_with_scope();
  1156. auto from_actor = graph_output_to_actor_[front_output_with_index].first;
  1157. if (from_actor != nullptr) {
  1158. MS_LOG(INFO) << "Link control arrow by auto monad from actor: " << from_actor->GetAID().Name()
  1159. << ", to actor: " << to_actor->GetAID().Name() << " for the graph: " << graph->graph_id();
  1160. AddControlArrow(from_actor, to_actor);
  1161. continue;
  1162. }
  1163. }
  1164. // The monad node and make tuple node need recursion.
  1165. if (IsOneOfPrimitiveCNode(real_depend_kernel, recursion_prims)) {
  1166. LinkControlArrowByAutoMonad(to_actor, real_depend_kernel, graph, parser);
  1167. continue;
  1168. }
  1169. auto type = FetchKernelTransformType(real_depend_kernel, nullptr);
  1170. auto from_actor = FetchActor(type, "", real_depend_kernel);
  1171. if (from_actor == nullptr) {
  1172. MS_LOG(DEBUG) << "Link control arrow by auto monad from depend node:" << real_depend_kernel->fullname_with_scope()
  1173. << " is not actor for the graph: " << graph->graph_id();
  1174. continue;
  1175. }
  1176. MS_LOG(INFO) << "Link control arrow by auto monad from actor: " << from_actor->GetAID().Name()
  1177. << ", to actor: " << to_actor->GetAID().Name() << " for the graph: " << graph->graph_id();
  1178. AddControlArrow(from_actor, to_actor);
  1179. }
  1180. }
  1181. void GraphScheduler::LinkControlArrowBySkippedNode(AbstractActor *to_actor, const AnfNodePtr &skipped_node) {
  1182. MS_EXCEPTION_IF_NULL(to_actor);
  1183. MS_EXCEPTION_IF_NULL(skipped_node);
  1184. // Link the control arrow from all the inputs of skipped node to the user of skipped node.
  1185. auto input_num = AnfAlgo::GetInputTensorNum(skipped_node);
  1186. for (size_t i = 0; i < input_num; ++i) {
  1187. auto kernel_with_index = AnfAlgo::GetPrevNodeOutput(skipped_node, i, false);
  1188. MS_EXCEPTION_IF_NULL(kernel_with_index.first);
  1189. auto from_actor = FetchActor(kernel_with_index.first->fullname_with_scope());
  1190. MS_EXCEPTION_IF_NULL(from_actor);
  1191. MS_LOG(INFO) << "Link control arrow by skipped node: " << skipped_node->fullname_with_scope()
  1192. << ", from actor: " << from_actor->GetAID().Name() << ", to actor: " << to_actor->GetAID().Name();
  1193. AddControlArrow(from_actor, to_actor);
  1194. }
  1195. }
  1196. void GraphScheduler::LinkControlArrowBySendRecvNodes(const KernelGraphPtr &graph) {
  1197. MS_EXCEPTION_IF_NULL(graph);
  1198. for (auto &from_iter : graph->allreduce_from_send_recv_pairs()) {
  1199. auto to_allreduce_node = from_iter.first;
  1200. auto from_send_node = from_iter.second.first;
  1201. auto from_recv_node = from_iter.second.second;
  1202. MS_EXCEPTION_IF_NULL(to_allreduce_node);
  1203. MS_EXCEPTION_IF_NULL(from_send_node);
  1204. MS_EXCEPTION_IF_NULL(from_recv_node);
  1205. MS_LOG(INFO) << "Link control arrow for to_allreduce_node: " << to_allreduce_node->fullname_with_scope();
  1206. auto to_allreduce_actor = FetchActor(to_allreduce_node->fullname_with_scope());
  1207. auto from_send_actor = FetchActor(from_send_node->fullname_with_scope());
  1208. auto from_recv_actor = FetchActor(from_recv_node->fullname_with_scope());
  1209. MS_EXCEPTION_IF_NULL(to_allreduce_actor);
  1210. MS_EXCEPTION_IF_NULL(from_send_actor);
  1211. MS_EXCEPTION_IF_NULL(from_recv_actor);
  1212. // inputs of to_allreduce_actor --> from_send_actor
  1213. for (auto &input_aid : to_allreduce_actor->input_data_arrow_aids_) {
  1214. auto input_actor = dynamic_cast<KernelActor *>(FetchActor(input_aid.Name()));
  1215. if (input_actor != nullptr) {
  1216. AddControlArrow(input_actor, from_send_actor);
  1217. }
  1218. }
  1219. // from_send_actor --> from_recv_actor
  1220. AddControlArrow(from_send_actor, from_recv_actor);
  1221. // from_recv_actor --> to_allreduce_actor
  1222. AddControlArrow(from_recv_actor, to_allreduce_actor);
  1223. }
  1224. for (auto &to_iter : graph->allreduce_to_send_recv_pairs()) {
  1225. auto from_allreduce_node = to_iter.first;
  1226. auto to_send_node = to_iter.second.first;
  1227. auto to_recv_node = to_iter.second.second;
  1228. MS_EXCEPTION_IF_NULL(from_allreduce_node);
  1229. MS_EXCEPTION_IF_NULL(to_send_node);
  1230. MS_EXCEPTION_IF_NULL(to_recv_node);
  1231. MS_LOG(INFO) << "Link control arrow for from_allreduce_node: " << from_allreduce_node->fullname_with_scope();
  1232. auto from_allreduce_actor = FetchActor(from_allreduce_node->fullname_with_scope());
  1233. auto to_send_actor = FetchActor(to_send_node->fullname_with_scope());
  1234. auto to_recv_actor = dynamic_cast<KernelActor *>(FetchActor(to_recv_node->fullname_with_scope()));
  1235. MS_EXCEPTION_IF_NULL(from_allreduce_actor);
  1236. MS_EXCEPTION_IF_NULL(to_send_actor);
  1237. MS_EXCEPTION_IF_NULL(to_recv_actor);
  1238. // from_allreduce_actor --> to_send_actor
  1239. AddControlArrow(from_allreduce_actor, to_send_actor);
  1240. // to_send_actor --> to_recv_actor
  1241. AddControlArrow(to_send_actor, to_recv_actor);
  1242. // to_recv_actor --> outputs of from_allreduce_actor
  1243. for (auto &output_data_arrow : from_allreduce_actor->output_data_arrows_) {
  1244. auto output_actor = FetchActor(output_data_arrow->to_op_id_.Name());
  1245. if (output_actor != nullptr) {
  1246. AddControlArrow(to_recv_actor, output_actor);
  1247. }
  1248. }
  1249. // In the scene of allreduce op and computing op parallel multi stream, the input memory of allreduce can be
  1250. // reused only when the recv node runs finished, which is expressed by the reference count increased.
  1251. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(from_allreduce_node); ++i) {
  1252. auto device_tensor = AnfAlgo::GetPrevNodeMutableOutputAddr(from_allreduce_node, i, false);
  1253. MS_EXCEPTION_IF_NULL(device_tensor);
  1254. UpdateRefCount(device_tensor.get());
  1255. (void)to_recv_actor->external_reference_tensors_.emplace_back(device_tensor.get());
  1256. }
  1257. }
  1258. }
  1259. void GraphScheduler::LinkGlobalControlArrow(ActorSet *const actor_set, const std::vector<CNodePtr> &communication_nodes,
  1260. const std::vector<AbstractActor *> &auto_monad_actors,
  1261. const GraphCompilerInfo &graph_compiler_info) {
  1262. MS_EXCEPTION_IF_NULL(actor_set);
  1263. // Link the control arrows by the communication nodes to ensure communication nodes running order.
  1264. LinkControlArrowByCommunicationNode(communication_nodes, graph_compiler_info);
  1265. // Auto monad actor may modify the device tensor store.
  1266. LinkDeviceTensorStoreForAutoMonadActor(auto_monad_actors);
  1267. // BuildNoInputKernelActor depends on whether kernel actors have input, so must be behind the link of kernel actors.
  1268. actor_set->no_input_kernel_actors_ = BuildNoInputKernelActor(actor_set, graph_compiler_info.strategy_);
  1269. // Link the control arrows of data prepare actor, which depends on the no input kernel actors.
  1270. if ((graph_compiler_info.strategy_ == GraphExecutionStrategy::kPipeline) || (!IsSingleOpActorSet(actor_set))) {
  1271. LinkControlArrowForDataPrepareActor(actor_set->data_prepare_actor_.get(), actor_set,
  1272. graph_compiler_info.control_node_parser_);
  1273. }
  1274. LinkControlArrowForLoopCountActor(actor_set->loop_count_actor_.get(), actor_set,
  1275. graph_compiler_info.control_node_parser_);
  1276. // Link control arrows for custom actor
  1277. LinkControlArrowForCustomActor(actor_set, graph_compiler_info);
  1278. }
  1279. void GraphScheduler::LinkControlArrowForCustomActor(ActorSet *const actor_set,
  1280. const GraphCompilerInfo &graph_compiler_info) {
  1281. constexpr size_t kDependFromIdx = 2;
  1282. constexpr size_t kDependToIdx = 1;
  1283. MS_EXCEPTION_IF_NULL(actor_set);
  1284. MS_EXCEPTION_IF_NULL(actor_set->data_prepare_actor_);
  1285. // prepare for kernel => actor map
  1286. HashMap<AnfNodePtr, AbstractActorPtr> kernel_to_actors = {};
  1287. HashSet<AbstractActorPtr> no_depend_custom_actors = {};
  1288. for (const auto &actor : actor_set->custom_actors_) {
  1289. MS_EXCEPTION_IF_NULL(actor);
  1290. auto kernel = actor->kernel().lock();
  1291. MS_EXCEPTION_IF_NULL(kernel);
  1292. kernel_to_actors.emplace(kernel, actor);
  1293. no_depend_custom_actors.insert(actor);
  1294. }
  1295. for (const auto &actor : actor_set->kernel_actors_) {
  1296. MS_EXCEPTION_IF_NULL(actor);
  1297. auto kernel = actor->kernel();
  1298. MS_EXCEPTION_IF_NULL(kernel);
  1299. kernel_to_actors.emplace(kernel, actor);
  1300. }
  1301. for (const auto &actor : actor_set->data_source_actors_) {
  1302. MS_EXCEPTION_IF_NULL(actor);
  1303. auto device_data_source_actor = dynamic_cast<DeviceQueueDataSourceActor *>(actor.get());
  1304. if (device_data_source_actor != nullptr) {
  1305. auto kernel = device_data_source_actor->data_kernel();
  1306. MS_EXCEPTION_IF_NULL(kernel);
  1307. if (AnfAlgo::GetCNodeName(kernel) == kGetNextOpName) {
  1308. kernel_to_actors.emplace(kernel, actor);
  1309. }
  1310. }
  1311. }
  1312. // find depend(custom, custom)
  1313. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  1314. const auto &graph = graph_compiler_info.graphs_[i];
  1315. MS_EXCEPTION_IF_NULL(graph);
  1316. if (graph->is_executing_sink()) {
  1317. continue;
  1318. }
  1319. auto all_nodes = TopoSort(graph->get_return());
  1320. for (const auto &node : all_nodes) {
  1321. if (!IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1322. continue;
  1323. }
  1324. auto depend_cnode = node->cast<CNodePtr>();
  1325. MS_EXCEPTION_IF_NULL(depend_cnode);
  1326. MS_EXCEPTION_IF_CHECK_FAIL(depend_cnode->size() > kDependFromIdx,
  1327. "depend node " + depend_cnode->DebugString() + " input size " +
  1328. std::to_string(depend_cnode->size()) + " is invalid.");
  1329. MS_EXCEPTION_IF_NULL(depend_cnode->input(kDependFromIdx));
  1330. MS_EXCEPTION_IF_NULL(depend_cnode->input(kDependToIdx));
  1331. auto from_node = depend_cnode->input(kDependFromIdx);
  1332. auto to_node = depend_cnode->input(kDependToIdx);
  1333. if (!AnfUtils::IsCustomActorNode(from_node) && !AnfUtils::IsCustomActorNode(to_node)) {
  1334. continue;
  1335. }
  1336. auto from_iter = kernel_to_actors.find(from_node);
  1337. if (from_iter == kernel_to_actors.end()) {
  1338. MS_LOG(INFO) << from_node->fullname_with_scope() << " is a CNode but cannot find Actor.";
  1339. continue;
  1340. }
  1341. auto to_iter = kernel_to_actors.find(to_node);
  1342. if (to_iter == kernel_to_actors.end()) {
  1343. MS_LOG(INFO) << to_node->fullname_with_scope() << " is a CNode but cannot find Actor.";
  1344. continue;
  1345. }
  1346. AddControlArrow(from_iter->second.get(), to_iter->second.get());
  1347. no_depend_custom_actors.erase(std::dynamic_pointer_cast<CustomActor>(to_iter->second));
  1348. }
  1349. }
  1350. for (const auto &custom_actor : no_depend_custom_actors) {
  1351. AddControlArrow(actor_set->data_prepare_actor_.get(), custom_actor.get());
  1352. }
  1353. }
  1354. void GraphScheduler::LinkControlArrowByCommunicationNode(const std::vector<CNodePtr> &communication_nodes,
  1355. const GraphCompilerInfo &graph_compiler_info) {
  1356. const size_t kCommunicationNodesMinNum = 2;
  1357. if (communication_nodes.size() < kCommunicationNodesMinNum) {
  1358. return;
  1359. }
  1360. // Ensure communication node to execute orderly.
  1361. for (size_t i = 1; i < communication_nodes.size(); ++i) {
  1362. auto from_actor = FetchActor(communication_nodes[i - 1]->fullname_with_scope());
  1363. auto to_actor = FetchActor(communication_nodes[i]->fullname_with_scope());
  1364. MS_EXCEPTION_IF_NULL(from_actor);
  1365. MS_EXCEPTION_IF_NULL(to_actor);
  1366. AddControlArrow(from_actor, to_actor);
  1367. }
  1368. // Ensure all actors execute orderly to optimize the execution performance in the multi device scenario currently.
  1369. // Using the multi stream to optimize the performance in the future.
  1370. for (auto &graph : graph_compiler_info.graphs_) {
  1371. MS_EXCEPTION_IF_NULL(graph);
  1372. auto &execution_order = graph->execution_order();
  1373. for (size_t i = 1; i < execution_order.size(); ++i) {
  1374. auto from_actor = FetchActor(execution_order[i - 1]->fullname_with_scope());
  1375. auto to_actor = FetchActor(execution_order[i]->fullname_with_scope());
  1376. if ((from_actor != nullptr) && (to_actor != nullptr)) {
  1377. AddControlArrow(from_actor, to_actor);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. void GraphScheduler::LinkControlArrowForDataPrepareActor(DataPrepareActor *data_prepare_actor,
  1383. const ActorSet *actor_set,
  1384. const ControlNodeParserPtr &parser) {
  1385. MS_EXCEPTION_IF_NULL(data_prepare_actor);
  1386. MS_EXCEPTION_IF_NULL(actor_set);
  1387. MS_EXCEPTION_IF_NULL(parser);
  1388. // Data prepare actor --> data source actor.
  1389. for (auto &data_source_actor : actor_set->data_source_actors_) {
  1390. MS_EXCEPTION_IF_NULL(data_source_actor);
  1391. AddControlArrow(data_prepare_actor, data_source_actor.get());
  1392. }
  1393. // In control flow, control arrow of no input kernel actor needs to be connected to the corresponding entrance actor.
  1394. if (!parser->IsInited()) {
  1395. // Data prepare actor --> no input kernel actor.
  1396. for (auto &no_input_kernel_actor : actor_set->no_input_kernel_actors_) {
  1397. MS_EXCEPTION_IF_NULL(no_input_kernel_actor);
  1398. AddControlArrow(data_prepare_actor, no_input_kernel_actor.get());
  1399. }
  1400. }
  1401. // Data prepare actor --> loop count actor.
  1402. if ((actor_set->data_source_actors_.size() + actor_set->no_input_kernel_actors_.size() == 0) &&
  1403. (actor_set->loop_count_actor_ != nullptr)) {
  1404. AddControlArrow(data_prepare_actor, actor_set->loop_count_actor_.get());
  1405. }
  1406. }
  1407. void GraphScheduler::LinkControlArrowForLoopCountActor(LoopCountActor *loop_count_actor, const ActorSet *actor_set,
  1408. const ControlNodeParserPtr &parser) {
  1409. MS_EXCEPTION_IF_NULL(actor_set);
  1410. MS_EXCEPTION_IF_NULL(parser);
  1411. // There is no loop count actor in step mode.
  1412. if (loop_count_actor == nullptr) {
  1413. return;
  1414. }
  1415. // Collect the actors which have no output.
  1416. std::vector<MemoryAwareActor *> no_output_actors;
  1417. for (auto &super_actor : actor_set->super_kernel_actors_) {
  1418. if ((super_actor->output_data_arrows_.size() == 0) && (super_actor->output_control_arrows_.size() == 0)) {
  1419. (void)no_output_actors.emplace_back(super_actor.get());
  1420. }
  1421. }
  1422. for (auto &kernel_actor : actor_set->kernel_actors_) {
  1423. // The no output kernel control side in subgraph needs to be connected to the corresponding output switch actor.
  1424. if ((kernel_actor->output_data_arrows_.size() == 0) && (kernel_actor->output_control_arrows_.size() == 0)) {
  1425. (void)no_output_actors.emplace_back(kernel_actor.get());
  1426. }
  1427. }
  1428. for (auto &data_actor : actor_set->data_source_actors_) {
  1429. if ((data_actor->output_data_arrows_.size() == 0) && (data_actor->output_control_arrows_.size() == 0)) {
  1430. (void)no_output_actors.emplace_back(data_actor.get());
  1431. }
  1432. }
  1433. for (auto &copy_actor : copy_actors_) {
  1434. if ((copy_actor->output_data_arrows_.size() == 0) && (copy_actor->output_control_arrows_.size() == 0)) {
  1435. (void)no_output_actors.emplace_back(copy_actor.get());
  1436. }
  1437. }
  1438. // No output actor --> loop count actor.
  1439. // In control flow scenario, no output actor needs to be connected to the corresponding exit actor, not loop count.
  1440. if (!parser->IsInited()) {
  1441. for (auto &no_output_actor : no_output_actors) {
  1442. AddControlArrow(no_output_actor, loop_count_actor);
  1443. }
  1444. }
  1445. // Loop count actor --> output actor.
  1446. AddControlArrow(loop_count_actor, actor_set->output_actor_.get());
  1447. // Loop count actor --> data prepare actor.
  1448. MS_EXCEPTION_IF_NULL(actor_set->data_prepare_actor_);
  1449. loop_count_actor->data_prepare_aid_ = actor_set->data_prepare_actor_->GetAID();
  1450. }
  1451. void GraphScheduler::LinkOutputResultArrowForOutputActor(OutputActor *to_actor,
  1452. const GraphCompilerInfo &graph_compiler_info) {
  1453. if (graph_compiler_info.strategy_ == GraphExecutionStrategy::kStep ||
  1454. (graph_compiler_info.control_node_parser_ != nullptr && graph_compiler_info.control_node_parser_->IsInited())) {
  1455. // In control flow, the exit actor of the root graph sends output data to the output actor.
  1456. return;
  1457. }
  1458. MS_EXCEPTION_IF_NULL(to_actor);
  1459. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  1460. const auto &graph = graph_compiler_info.graphs_[i];
  1461. MS_EXCEPTION_IF_NULL(graph);
  1462. auto outputs = AnfAlgo::GetAllOutputWithIndex(graph->output());
  1463. std::set<std::vector<size_t>> unique_output_positions;
  1464. std::set<KernelWithIndex> unique_outputs;
  1465. for (const auto &output : outputs) {
  1466. if (IsInternalParameter(output.first, graph)) {
  1467. MS_LOG(INFO) << "Ignore the internal parameter node:" << output.first->DebugString();
  1468. continue;
  1469. }
  1470. (void)unique_outputs.insert(output);
  1471. }
  1472. for (const auto &output_with_index : unique_outputs) {
  1473. MS_EXCEPTION_IF_NULL(output_with_index.first);
  1474. auto origin_output_with_index = FetchFrontNodeWithIndexByGraphOutput(output_with_index, graph);
  1475. const auto &iter = graph_compiler_info.origin_outputs_order_.find(origin_output_with_index);
  1476. if (iter == graph_compiler_info.origin_outputs_order_.end()) {
  1477. continue;
  1478. }
  1479. // Skip duplicate position.
  1480. if (unique_output_positions.count(iter->second) > 0) {
  1481. continue;
  1482. }
  1483. (void)unique_output_positions.insert(iter->second);
  1484. for (auto &output_position : iter->second) {
  1485. if (output_position >= to_actor->device_contexts_.size()) {
  1486. MS_LOG(EXCEPTION) << "The output position is out of range.";
  1487. }
  1488. to_actor->device_contexts_[output_position] = graph_compiler_info.device_contexts_[i];
  1489. // The graph output is from device tensor store.
  1490. if (IsPersistentDeviceTensor(output_with_index.first)) {
  1491. (void)to_actor->device_tensor_store_keys_.emplace_back(output_position, output_with_index.first);
  1492. // In the scenario where the ValueTuple is expanded, the output_with_index.second may be incorrect, so use 0
  1493. // as output_idx directly.
  1494. auto device_tensor = AnfAlgo::GetMutableOutputAddr(output_with_index.first, 0, false);
  1495. MS_EXCEPTION_IF_NULL(device_tensor);
  1496. // The output actor need use the relevant information of node to create output tensor.
  1497. device_tensor->SetNodeIndex(output_with_index.first, 0);
  1498. continue;
  1499. }
  1500. // The graph output is from kernel actor or data source actor.
  1501. auto kernel_type = FetchKernelTransformType(
  1502. output_with_index.first, graph, graph_compiler_info.origin_parameters_order_, graph_compiler_info.strategy_);
  1503. auto from_actor = FetchActor(kernel_type, graph_compiler_info.name_, output_with_index.first, graph);
  1504. if (from_actor == nullptr) {
  1505. continue;
  1506. }
  1507. auto real_from_kernel = output_with_index.first;
  1508. // Update the real node in the host data source actor.
  1509. if (kernel_type == KernelTransformType::kHostDataSourceActor) {
  1510. auto host_queue_ds_actor = dynamic_cast<HostQueueDataSourceActor *>(from_actor);
  1511. MS_EXCEPTION_IF_NULL(host_queue_ds_actor);
  1512. auto position = host_queue_ds_actor->FetchNodePosition(output_with_index.first);
  1513. real_from_kernel = host_queue_ds_actor->FetchNode(position);
  1514. UpdateRefCount(output_with_index.first, output_with_index.second, true);
  1515. }
  1516. AddResultArrow(from_actor, to_actor, real_from_kernel, output_with_index.second, output_position);
  1517. }
  1518. }
  1519. }
  1520. }
  1521. void GraphScheduler::LinkDeviceTensorStoreForAutoMonadActor(const std::vector<AbstractActor *> &auto_monad_actors) {
  1522. const size_t kNeedUpdateDeviceTensorStoreNum = 2;
  1523. for (auto &auto_monad_actor : auto_monad_actors) {
  1524. MS_EXCEPTION_IF_NULL(auto_monad_actor);
  1525. for (auto &device_tensor_store_key : auto_monad_actor->device_tensor_store_keys_) {
  1526. auto device_tensors = DeviceTensorStore::GetInstance().Fetch(device_tensor_store_key.second.get());
  1527. if (device_tensors.size() < kNeedUpdateDeviceTensorStoreNum) {
  1528. continue;
  1529. }
  1530. // Find the device tensor store that needs to be processed accurately.
  1531. if ((auto_monad_actor->type_ == KernelTransformType::kSuperKernelActor) &&
  1532. (auto_monad_actor->auto_monad_device_tensor_stores_.find(device_tensor_store_key.second) ==
  1533. auto_monad_actor->auto_monad_device_tensor_stores_.end())) {
  1534. continue;
  1535. }
  1536. // Create the copy actor.
  1537. std::string name = "copy_from:" + auto_monad_actor->GetAID().Name() +
  1538. "_device_tensor_store:" + device_tensor_store_key.second->fullname_with_scope();
  1539. if (FetchActor(name) != nullptr) {
  1540. continue;
  1541. }
  1542. auto copy_actor = std::make_shared<CopyActor>(name, memory_manager_aid_);
  1543. MS_EXCEPTION_IF_NULL(copy_actor);
  1544. (void)copy_actors_.emplace_back(copy_actor);
  1545. InsertActor(copy_actor.get());
  1546. // Set the member of the copy actor.
  1547. (void)copy_actor->device_tensor_store_keys_.emplace_back(0, device_tensor_store_key.second);
  1548. auto input_device_context = auto_monad_actor->device_contexts_[0];
  1549. (void)copy_actor->device_contexts_.emplace_back(input_device_context);
  1550. auto another_device_tensor = (device_tensors[0]->DeviceType() == input_device_context->GetDeviceAddressType())
  1551. ? device_tensors[1]
  1552. : device_tensors[0];
  1553. MS_EXCEPTION_IF_NULL(another_device_tensor);
  1554. auto another_device_type = another_device_tensor->DeviceType();
  1555. const auto &another_device_context = device::DeviceContextManager::GetInstance().GetOrCreateDeviceContext(
  1556. {device::kDeviceTypeToName.at(another_device_type), input_device_context->device_context_key().device_id_});
  1557. MS_EXCEPTION_IF_NULL(another_device_context);
  1558. (void)copy_actor->device_contexts_.emplace_back(another_device_context);
  1559. MS_LOG(INFO) << "The auto monad actor: " << auto_monad_actor->GetAID().Name()
  1560. << "has control arrows number:" << auto_monad_actor->output_control_arrows_.size();
  1561. // Link from copy actor to auto monad actor users.
  1562. for (auto &output_contorl : auto_monad_actor->output_control_arrows_) {
  1563. (void)copy_actor->output_control_arrows_.emplace_back(output_contorl);
  1564. }
  1565. // Move the control arrows from auto monad actor to auto monad actor users.
  1566. auto_monad_actor->output_control_arrows_.clear();
  1567. // Link from auto monad actor to copy actor.
  1568. AddControlArrow(auto_monad_actor, copy_actor.get());
  1569. }
  1570. }
  1571. }
  1572. void GraphScheduler::AddDeviceTensorStore(const AnfNode *anf_node, const DeviceTensorPtr &device_tensor) {
  1573. MS_EXCEPTION_IF_NULL(device_tensor);
  1574. DeviceTensorStore::GetInstance().Insert(const_cast<AnfNode *>(anf_node), device_tensor);
  1575. UpdateRefCount(device_tensor.get(), true);
  1576. }
  1577. void GraphScheduler::AddDataArrow(AbstractActor *const from_actor, AbstractActor *const to_actor,
  1578. const AnfNodePtr &from_kernel, size_t from_output_index, size_t to_input_index) {
  1579. MS_EXCEPTION_IF_NULL(from_actor);
  1580. MS_EXCEPTION_IF_NULL(to_actor);
  1581. auto data_arrow = std::make_shared<DataArrow>(from_output_index, to_actor->GetAID(), to_input_index);
  1582. (void)from_actor->output_data_arrows_.emplace_back(data_arrow);
  1583. (void)from_actor->output_data_nodes_.emplace_back(from_kernel);
  1584. to_actor->input_datas_num_++;
  1585. (void)to_actor->input_data_arrow_aids_.emplace_back(from_actor->GetAID());
  1586. if (from_kernel == nullptr) {
  1587. return;
  1588. }
  1589. // Update the reference count of from_kernel.
  1590. // The device address of super kernel actor can't be changed, so set the max reference count.
  1591. if ((from_actor->type_ == KernelTransformType::kSuperKernelActor) ||
  1592. (to_actor->type_ == KernelTransformType::kSuperKernelActor)) {
  1593. UpdateRefCount(from_kernel, from_output_index, true);
  1594. } else {
  1595. UpdateRefCount(from_kernel, from_output_index, false);
  1596. }
  1597. }
  1598. void GraphScheduler::AddResultArrow(AbstractActor *const from_actor, OutputActor *const to_actor,
  1599. const AnfNodePtr &from_kernel, size_t from_output_index, size_t output_position) {
  1600. MS_EXCEPTION_IF_NULL(from_actor);
  1601. MS_EXCEPTION_IF_NULL(to_actor);
  1602. MS_EXCEPTION_IF_NULL(from_kernel);
  1603. auto result_arrow = std::make_shared<DataArrow>(from_output_index, to_actor->GetAID(), output_position);
  1604. (void)from_actor->output_data_arrows_.insert(from_actor->output_data_arrows_.begin(), result_arrow);
  1605. (void)from_actor->output_data_nodes_.insert(from_actor->output_data_nodes_.begin(), from_kernel);
  1606. to_actor->input_datas_num_++;
  1607. (void)to_actor->input_data_arrow_aids_.emplace_back(from_actor->GetAID());
  1608. auto device_tensor = AnfAlgo::GetMutableOutputAddr(from_kernel, from_output_index, false);
  1609. MS_EXCEPTION_IF_NULL(device_tensor);
  1610. // The output actor need use the relevant information of node to create output tensor.
  1611. device_tensor->SetNodeIndex(from_kernel, from_output_index);
  1612. // The device tensor of graph out need be taken over by host tensor, so set the max reference count.
  1613. UpdateRefCount(device_tensor.get(), true);
  1614. }
  1615. void GraphScheduler::AddControlArrow(AbstractActor *const from_actor, AbstractActor *const to_actor) {
  1616. MS_EXCEPTION_IF_NULL(from_actor);
  1617. MS_EXCEPTION_IF_NULL(to_actor);
  1618. (void)from_actor->output_control_arrows_.emplace_back(to_actor->GetAID());
  1619. to_actor->input_controls_num_++;
  1620. (void)to_actor->input_control_arrow_aids_.emplace_back(from_actor->GetAID());
  1621. }
  1622. void GraphScheduler::CheckActorValid(const ActorSet *actor_set) const {
  1623. MS_EXCEPTION_IF_NULL(actor_set);
  1624. auto actors = CollectActors(actor_set);
  1625. for (auto &actor : actors) {
  1626. MS_EXCEPTION_IF_NULL(actor);
  1627. if (actor->type_ >= KernelTransformType::kSwitchActor) {
  1628. continue;
  1629. }
  1630. if ((actor->input_datas_num_ != actor->input_data_arrow_aids_.size()) ||
  1631. (actor->input_controls_num_ != actor->input_control_arrow_aids_.size())) {
  1632. MS_LOG(EXCEPTION) << "The input num of " << actor->GetAID().Name()
  1633. << " is wrong, expect data num: " << actor->input_datas_num_
  1634. << ", actual data num: " << actor->input_data_arrow_aids_.size()
  1635. << ", expect control num: " << actor->input_controls_num_
  1636. << ", actual control num: " << actor->input_control_arrow_aids_.size();
  1637. }
  1638. if ((actor->type_ != KernelTransformType::kOutputActor) && (actor->type_ != KernelTransformType::kCustomActor) &&
  1639. (actor->output_data_arrows_.size() == 0) && (actor->output_control_arrows_.size() == 0)) {
  1640. MS_LOG(EXCEPTION) << actor->GetAID().Name() << " has no user.";
  1641. }
  1642. if ((actor->type_ != KernelTransformType::kDataPrepareActor) &&
  1643. (actor->type_ != KernelTransformType::kCustomActor) && (actor->input_datas_num_ == 0) &&
  1644. (actor->input_controls_num_ == 0)) {
  1645. MS_LOG(EXCEPTION) << actor->GetAID().Name() << " has no source.";
  1646. }
  1647. // Check the input of kernel actors and copy actors.
  1648. if ((actor->type_ == KernelTransformType::kKernelActor) || (actor->type_ == KernelTransformType::kCopyActor)) {
  1649. size_t expect_toal_input_num = 1;
  1650. if (actor->type_ == KernelTransformType::kKernelActor) {
  1651. auto kernel_actor = dynamic_cast<KernelActor *>(actor.get());
  1652. MS_EXCEPTION_IF_NULL(kernel_actor);
  1653. expect_toal_input_num = AnfAlgo::GetInputTensorNum(kernel_actor->kernel_);
  1654. }
  1655. auto input_data_num = actor->input_datas_num_;
  1656. auto device_tensor_store_num = actor->device_tensor_store_keys_.size();
  1657. if (input_data_num + device_tensor_store_num != expect_toal_input_num) {
  1658. MS_LOG(EXCEPTION) << "The input building of " << actor->GetAID().Name()
  1659. << " is wrong, input data num: " << input_data_num
  1660. << ", device tensor store num: " << device_tensor_store_num
  1661. << ", total input num: " << expect_toal_input_num;
  1662. }
  1663. }
  1664. }
  1665. // Check the output actor.
  1666. auto output_actor = actor_set->output_actor_;
  1667. MS_EXCEPTION_IF_NULL(output_actor);
  1668. if (output_actor->input_datas_num_ + output_actor->device_tensor_store_keys_.size() != output_actor->outputs_num_) {
  1669. MS_LOG(EXCEPTION) << "The outputs num of output actor is wrong, the total outputs num: "
  1670. << output_actor->outputs_num_ << ", the input data arrows num: " << output_actor->input_datas_num_
  1671. << ", the device tensor store num: " << output_actor->device_tensor_store_keys_.size();
  1672. }
  1673. control_node_scheduler_.CheckActorValid(actor_set);
  1674. }
  1675. void GraphScheduler::PersistDeviceTensor(const GraphCompilerInfo &graph_compiler_info) {
  1676. const auto &parser = graph_compiler_info.control_node_parser_;
  1677. MS_EXCEPTION_IF_NULL(parser);
  1678. for (size_t i = 0; i < graph_compiler_info.graphs_.size(); ++i) {
  1679. const auto &graph = graph_compiler_info.graphs_[i];
  1680. const auto &device_context = graph_compiler_info.device_contexts_[i];
  1681. MS_EXCEPTION_IF_NULL(graph);
  1682. MS_EXCEPTION_IF_NULL(device_context);
  1683. for (auto &value_node : graph->graph_value_nodes()) {
  1684. MS_EXCEPTION_IF_NULL(value_node);
  1685. if (!AnfAlgo::OutputAddrExist(value_node, 0)) {
  1686. MS_LOG(INFO) << "The device address is not exist: " << value_node->ToString();
  1687. continue;
  1688. }
  1689. auto device_tensor = AnfAlgo::GetMutableOutputAddr(value_node, 0, false);
  1690. const auto &front_node = FetchFrontNodeByBackendNode(value_node, graph);
  1691. device_tensor->SetNodeIndex(value_node, 0);
  1692. AddDeviceTensorStore(front_node.get(), device_tensor);
  1693. }
  1694. for (auto &input_node : graph->input_nodes()) {
  1695. MS_EXCEPTION_IF_NULL(input_node);
  1696. AnfNodePtr front_node = nullptr;
  1697. if (IsInternalParameter(input_node, graph)) {
  1698. auto front_output_with_index = graph->GetFrontNodeByInternalParameter(input_node);
  1699. front_node = front_output_with_index.first;
  1700. } else if (IsPersistentDeviceTensor(input_node)) {
  1701. front_node = FetchFrontNodeByBackendNode(input_node, graph);
  1702. }
  1703. if (front_node == nullptr || (!parser->IsRootGraphPersistentDeviceTensor(front_node))) {
  1704. continue;
  1705. }
  1706. auto device_tensor = AnfAlgo::GetMutableOutputAddr(input_node, 0, false);
  1707. MS_EXCEPTION_IF_NULL(device_tensor);
  1708. if (IsPersistentDeviceTensor(input_node)) {
  1709. device_tensor->SetNodeIndex(input_node, 0);
  1710. AddDeviceTensorStore(front_node.get(), device_tensor);
  1711. }
  1712. if (device_tensor->is_ptr_persisted()) {
  1713. device_tensor->SetNodeIndex(input_node, 0);
  1714. AddDeviceTensorStore(front_node.get(), device_tensor);
  1715. }
  1716. // If the device tensor store of this device type is not exist, then create the new device tensor of this type.
  1717. if (DeviceTensorStore::GetInstance().Fetch(front_node.get(), device_context->GetDeviceAddressType()) == nullptr) {
  1718. MS_LOG(INFO) << "Fetch no device tensor store by:" << front_node->fullname_with_scope()
  1719. << ", type:" << device_context->GetDeviceAddressType();
  1720. auto other_type_device_tensor = device_context->CreateDeviceAddress(
  1721. nullptr, device_tensor->GetSize(), device_tensor->format(), device_tensor->type_id());
  1722. other_type_device_tensor->SetNodeIndex(input_node, 0);
  1723. other_type_device_tensor->set_from_persistent_mem(input_node->isa<Parameter>());
  1724. AddDeviceTensorStore(front_node.get(), other_type_device_tensor);
  1725. }
  1726. }
  1727. }
  1728. PersistDeviceTensorForRootGraphControlNode(graph_compiler_info);
  1729. }
  1730. void GraphScheduler::PersistDeviceTensorForRootGraphControlNode(const GraphCompilerInfo &graph_compiler_info) {
  1731. const auto &parser = graph_compiler_info.control_node_parser_;
  1732. if (parser == nullptr || (!parser->IsInited())) {
  1733. return;
  1734. }
  1735. const auto &control_node_parameters = parser->control_node_parameters();
  1736. for (size_t i = 0; i < control_node_parameters.size(); ++i) {
  1737. const auto &input_node = control_node_parameters[i];
  1738. MS_EXCEPTION_IF_NULL(input_node);
  1739. if (!parser->IsRootGraphPersistentDeviceTensor(input_node)) {
  1740. continue;
  1741. }
  1742. const auto &backend_parameter_with_context =
  1743. parser->FetchBackendParameterWithContextByFrontParameter({input_node, 0});
  1744. if (backend_parameter_with_context.first == nullptr) {
  1745. MS_LOG(EXCEPTION) << "Cannot find backend node for weight parameter:" << input_node->DebugString();
  1746. }
  1747. const auto &backend_node = backend_parameter_with_context.first;
  1748. const auto &device_context = backend_parameter_with_context.second;
  1749. MS_EXCEPTION_IF_NULL(backend_node);
  1750. MS_EXCEPTION_IF_NULL(device_context);
  1751. if (!DeviceTensorStore::GetInstance().Fetch(input_node.get()).empty()) {
  1752. continue;
  1753. }
  1754. auto device_tensor = AnfAlgo::GetMutableOutputAddr(backend_node, 0, false);
  1755. MS_EXCEPTION_IF_NULL(device_tensor);
  1756. AddDeviceTensorStore(input_node.get(), device_tensor);
  1757. }
  1758. }
  1759. void GraphScheduler::DumpActor(const ActorSet *actor_set, const GraphCompilerInfo &graph_compiler_info) const {
  1760. MS_EXCEPTION_IF_NULL(actor_set);
  1761. const auto &context_ptr = MsContext::GetInstance();
  1762. MS_EXCEPTION_IF_NULL(context_ptr);
  1763. auto save_graphs = context_ptr->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG);
  1764. if (!save_graphs) {
  1765. return;
  1766. }
  1767. // Get the saved actor set name.
  1768. auto &kernel_graphs = graph_compiler_info.graphs_;
  1769. MS_EXCEPTION_IF_NULL(kernel_graphs.front());
  1770. auto first_graph_id = kernel_graphs.front()->graph_id();
  1771. MS_EXCEPTION_IF_NULL(kernel_graphs.back());
  1772. auto last_graph_id = kernel_graphs.back()->graph_id();
  1773. std::string strategy = (graph_compiler_info.strategy_ == GraphExecutionStrategy::kPipeline) ? "pipeline" : "step";
  1774. std::string save_name = "actor_set_" + strategy + "_kernel_graph_" + std::to_string(first_graph_id);
  1775. if (last_graph_id != first_graph_id) {
  1776. save_name = save_name + "-" + std::to_string(last_graph_id);
  1777. }
  1778. std::string filename = GetSaveGraphsPathName(save_name + ".ir");
  1779. std::ofstream ofs(filename);
  1780. if (!ofs.is_open()) {
  1781. MS_LOG(ERROR) << "Open file [" << filename << "] failed!";
  1782. return;
  1783. }
  1784. DumpDeviceTensorStore(graph_compiler_info, ofs);
  1785. DumpDataPrepareActor(actor_set->data_prepare_actor_, ofs);
  1786. DumpDSActors(actor_set->data_source_actors_, ofs);
  1787. DumpKernelActors(actor_set->kernel_actors_, ofs);
  1788. DumpSuperKernelActors(actor_set->super_kernel_actors_, ofs);
  1789. // The on input kernel actors are taken over by control actor in the control flow scene.
  1790. if ((graph_compiler_info.control_node_parser_ == nullptr) ||
  1791. (!graph_compiler_info.control_node_parser_->IsInited())) {
  1792. DumpNoInputKernelActors(actor_set->no_input_kernel_actors_, ofs);
  1793. }
  1794. DumpCopyActors(actor_set->copy_actors_, ofs);
  1795. DumpLoopCountActor(actor_set->loop_count_actor_, ofs);
  1796. DumpOutputActor(actor_set->output_actor_, ofs);
  1797. DumpControlActors(actor_set->control_actors_, ofs);
  1798. DumpCustomActors(actor_set->custom_actors_, ofs);
  1799. }
  1800. void GraphScheduler::DumpDeviceTensorStore(const GraphCompilerInfo &graph_compiler_info, std::ofstream &ofs) const {
  1801. ofs << "[Device tensor stores]\n";
  1802. for (const auto &graph : graph_compiler_info.graphs_) {
  1803. MS_EXCEPTION_IF_NULL(graph);
  1804. ofs << "\tgraph_id:" << graph->graph_id() << "\tis_executing_sink:" << graph->is_executing_sink()
  1805. << "\tis_loop_count_sink:" << graph->is_loop_count_sink()
  1806. << "\texecution_strategy:" << graph_compiler_info.strategy_ << "\n";
  1807. for (auto &value_node : graph->graph_value_nodes()) {
  1808. MS_EXCEPTION_IF_NULL(value_node);
  1809. if (!AnfAlgo::OutputAddrExist(value_node, 0)) {
  1810. continue;
  1811. }
  1812. const auto &front_node = FetchFrontNodeByBackendNode(value_node, graph);
  1813. MS_EXCEPTION_IF_NULL(front_node);
  1814. const auto device_tensors = DeviceTensorStore::GetInstance().Fetch(front_node.get());
  1815. ofs << "\t\tdevice tensor key:" << front_node->fullname_with_scope() << "\tvalue size:" << device_tensors.size()
  1816. << "\n";
  1817. for (const auto &device_tensor : device_tensors) {
  1818. MS_EXCEPTION_IF_NULL(device_tensor);
  1819. ofs << "\t\t\tdevice tensor value:" << device_tensor << "\tptr:" << device_tensor->GetPtr()
  1820. << "\tsize:" << device_tensor->GetSize() << "\toriginal_ref_count:" << device_tensor->original_ref_count()
  1821. << "\tdynamic_ref_count:" << device_tensor->dynamic_ref_count()
  1822. << "\tdevice_type:" << device_tensor->DeviceType()
  1823. << "\tis_ptr_persisted:" << device_tensor->is_ptr_persisted() << "\n ";
  1824. }
  1825. }
  1826. for (auto &input_node : graph->input_nodes()) {
  1827. MS_EXCEPTION_IF_NULL(input_node);
  1828. if (!IsPersistentDeviceTensor(input_node)) {
  1829. continue;
  1830. }
  1831. const auto &sub_front_node = FetchFrontNodeByBackendNode(input_node, graph);
  1832. // The sub front nodes share the device tensor store with the root front node.
  1833. auto front_node = sub_front_node;
  1834. if (graph_compiler_info.control_node_parser_ != nullptr) {
  1835. front_node = graph_compiler_info.control_node_parser_->FetchRootGraphFrontNodeBySubFrontNode(sub_front_node);
  1836. }
  1837. const auto device_tensors = DeviceTensorStore::GetInstance().Fetch(front_node.get());
  1838. MS_EXCEPTION_IF_NULL(front_node);
  1839. ofs << "\t\tdevice tensor key:" << front_node->fullname_with_scope() << "\tvalue size:" << device_tensors.size()
  1840. << "\n";
  1841. for (const auto &device_tensor : device_tensors) {
  1842. MS_EXCEPTION_IF_NULL(device_tensor);
  1843. ofs << "\t\t\tdevice tensor value:" << device_tensor << "\tptr:" << device_tensor->GetPtr()
  1844. << "\tsize:" << device_tensor->GetSize() << "\toriginal_ref_count:" << device_tensor->original_ref_count()
  1845. << "\tdynamic_ref_count:" << device_tensor->dynamic_ref_count()
  1846. << "\tdevice_type:" << device_tensor->DeviceType()
  1847. << "\tis_ptr_persisted:" << device_tensor->is_ptr_persisted() << "\n ";
  1848. }
  1849. }
  1850. ofs << "\n";
  1851. for (auto &backend_front_map : graph->backend_front_anf_map()) {
  1852. MS_EXCEPTION_IF_NULL(backend_front_map.first);
  1853. MS_EXCEPTION_IF_NULL(backend_front_map.second);
  1854. MS_LOG(DEBUG) << "Graph: " << graph->graph_id()
  1855. << ", backend node: " << backend_front_map.first->fullname_with_scope()
  1856. << ", front node: " << backend_front_map.second->DebugString();
  1857. }
  1858. }
  1859. }
  1860. } // namespace runtime
  1861. } // namespace mindspore