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.

kernel_adjust.cc 34 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "runtime/device/kernel_adjust.h"
  17. #include <map>
  18. #include <algorithm>
  19. #include <string>
  20. #include <vector>
  21. #include <utility>
  22. #include "backend/session/anf_runtime_algorithm.h"
  23. #include "utils/ms_context.h"
  24. #include "common/trans.h"
  25. #include "utils/config_manager.h"
  26. #include "utils/ms_utils.h"
  27. #include "backend/kernel_compiler/kernel_build_info.h"
  28. #include "utils/utils.h"
  29. #include "runtime/device/ascend/profiling/profiling_manager.h"
  30. #include "runtime/base.h"
  31. #include "runtime/device/ascend/ascend_stream_assign.h"
  32. #include "utils/shape_utils.h"
  33. namespace {
  34. constexpr auto kProfilingGraphId = "PROFILING_GRAPH_ID";
  35. } // namespace
  36. namespace mindspore {
  37. namespace device {
  38. using device::ascend::ProfilingUtils;
  39. void KernelAdjust::ReorderGetNext(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr) {
  40. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  41. const std::vector<CNodePtr> &origin_cnode_list = kernel_graph_ptr->execution_order();
  42. std::vector<CNodePtr> getnext_list;
  43. std::vector<CNodePtr> other_list;
  44. for (const auto &cnode : origin_cnode_list) {
  45. if (AnfAlgo::GetCNodeName(cnode) == kGetNextOpName) {
  46. getnext_list.emplace_back(cnode);
  47. } else {
  48. other_list.emplace_back(cnode);
  49. }
  50. }
  51. std::vector<CNodePtr> new_order_list;
  52. new_order_list.insert(new_order_list.end(), getnext_list.begin(), getnext_list.end());
  53. new_order_list.insert(new_order_list.end(), other_list.begin(), other_list.end());
  54. kernel_graph_ptr->set_execution_order(new_order_list);
  55. }
  56. bool KernelAdjust::NeedInsertSwitch() {
  57. auto context_ptr = MsContext::GetInstance();
  58. MS_EXCEPTION_IF_NULL(context_ptr);
  59. return (context_ptr->get_param<bool>(MS_CTX_ENABLE_TASK_SINK) &&
  60. context_ptr->get_param<bool>(MS_CTX_ENABLE_LOOP_SINK) && ConfigManager::GetInstance().iter_num() > 1);
  61. }
  62. CNodePtr KernelAdjust::CreateSendApplyKernel(const std::shared_ptr<session::KernelGraph> &graph_ptr,
  63. uint32_t event_id) {
  64. MS_EXCEPTION_IF_NULL(graph_ptr);
  65. auto send_op = std::make_shared<Primitive>(kSendOpName);
  66. MS_EXCEPTION_IF_NULL(send_op);
  67. auto send_apply = std::make_shared<ValueNode>(send_op);
  68. MS_EXCEPTION_IF_NULL(send_apply);
  69. std::vector<AnfNodePtr> send_input_list = {send_apply};
  70. CNodePtr send_node_ptr = graph_ptr->NewCNode(send_input_list);
  71. MS_EXCEPTION_IF_NULL(send_node_ptr);
  72. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder;
  73. selected_kernel_builder.SetKernelType(KernelType::RT_KERNEL);
  74. AnfAlgo::SetSelectKernelBuildInfo(selected_kernel_builder.Build(), send_node_ptr.get());
  75. AnfAlgo::SetNodeAttr(kAttrEventId, MakeValue(event_id), send_node_ptr);
  76. auto abstract_none = std::make_shared<abstract::AbstractNone>();
  77. MS_EXCEPTION_IF_NULL(abstract_none);
  78. send_node_ptr->set_abstract(abstract_none);
  79. return send_node_ptr;
  80. }
  81. CNodePtr KernelAdjust::CreateRecvApplyKernel(const std::shared_ptr<session::KernelGraph> &graph_ptr,
  82. uint32_t event_id) {
  83. MS_EXCEPTION_IF_NULL(graph_ptr);
  84. auto recv_op = std::make_shared<Primitive>(kRecvOpName);
  85. MS_EXCEPTION_IF_NULL(recv_op);
  86. auto recv_apply = std::make_shared<ValueNode>(recv_op);
  87. MS_EXCEPTION_IF_NULL(recv_apply);
  88. std::vector<AnfNodePtr> recv_input_list = {recv_apply};
  89. CNodePtr recv_node_ptr = graph_ptr->NewCNode(recv_input_list);
  90. MS_EXCEPTION_IF_NULL(recv_node_ptr);
  91. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder;
  92. selected_kernel_builder.SetKernelType(KernelType::RT_KERNEL);
  93. AnfAlgo::SetSelectKernelBuildInfo(selected_kernel_builder.Build(), recv_node_ptr.get());
  94. AnfAlgo::SetNodeAttr(kAttrEventId, MakeValue(event_id), recv_node_ptr);
  95. auto abstract_none = std::make_shared<abstract::AbstractNone>();
  96. MS_EXCEPTION_IF_NULL(abstract_none);
  97. recv_node_ptr->set_abstract(abstract_none);
  98. return recv_node_ptr;
  99. }
  100. bool KernelAdjust::ExistGetNext(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr) {
  101. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  102. const std::vector<CNodePtr> &cnode_list = kernel_graph_ptr->execution_order();
  103. for (const auto &cnode : cnode_list) {
  104. if (AnfAlgo::GetCNodeName(cnode) == kGetNextOpName) {
  105. return true;
  106. }
  107. }
  108. return false;
  109. }
  110. bool KernelAdjust::ExistIndependent(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr) {
  111. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  112. const auto &exe_orders = kernel_graph_ptr->execution_order();
  113. for (const auto &node : exe_orders) {
  114. if (AnfAlgo::IsIndependentNode(node)) {
  115. MS_LOG(INFO) << "graph exit independent node";
  116. return true;
  117. }
  118. }
  119. return false;
  120. }
  121. void KernelAdjust::InsertSwitchLoop(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr) {
  122. device::ascend::AscendResourceMng &resource_manager = device::ascend::AscendResourceMng::GetInstance();
  123. resource_manager.ResetResource();
  124. if (!NeedInsertSwitch()) {
  125. return;
  126. }
  127. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  128. if (kernel_graph_ptr->is_dynamic_shape()) {
  129. MS_LOG(INFO) << "KernelGraph:" << kernel_graph_ptr->graph_id() << " is dynamic shape, skip InsertSwitchLoop";
  130. return;
  131. }
  132. bool exist_getnext = ExistGetNext(kernel_graph_ptr);
  133. bool eos_mode = ConfigManager::GetInstance().iter_num() == INT32_MAX && exist_getnext;
  134. MS_LOG(INFO) << "GetNext exist:" << exist_getnext << " End of Sequence mode:" << eos_mode
  135. << " iter num:" << ConfigManager::GetInstance().iter_num();
  136. if (exist_getnext) {
  137. ReorderGetNext(kernel_graph_ptr);
  138. }
  139. std::map<std::string, mindspore::ParameterPtr> switch_loop_input;
  140. CreateSwitchOpParameters(kernel_graph_ptr, &switch_loop_input);
  141. std::vector<AnfNodePtr> *mute_inputs = kernel_graph_ptr->MutableInputs();
  142. MS_EXCEPTION_IF_NULL(mute_inputs);
  143. mute_inputs->push_back(switch_loop_input[kCurLoopCountParamName]);
  144. mute_inputs->push_back(switch_loop_input[kNextLoopCountParamName]);
  145. mute_inputs->push_back(switch_loop_input[kEpochParamName]);
  146. mute_inputs->push_back(switch_loop_input[kIterLoopParamName]);
  147. mute_inputs->push_back(switch_loop_input[kOneParamName]);
  148. for (const auto &input : kernel_graph_ptr->inputs()) {
  149. MS_EXCEPTION_IF_NULL(input);
  150. if (input->isa<Parameter>()) {
  151. ParameterPtr param_ptr = input->cast<ParameterPtr>();
  152. if (param_ptr == nullptr) {
  153. MS_EXCEPTION(NotSupportError) << "Cast to parameter point failed !";
  154. }
  155. }
  156. }
  157. const std::vector<CNodePtr> &orders = kernel_graph_ptr->execution_order();
  158. if (orders.empty()) {
  159. MS_LOG(EXCEPTION) << "graph execution order is empty";
  160. }
  161. std::vector<CNodePtr> exec_order;
  162. std::vector<uint32_t> getnext_active_streams;
  163. std::vector<uint32_t> fpbp_active_streams;
  164. CNodePtr getnext_cnode;
  165. uint32_t getnext_switch_stream_id = UINT32_MAX;
  166. uint32_t fpbp_start_event_id = UINT32_MAX;
  167. uint32_t eos_start_event_id = UINT32_MAX;
  168. uint32_t eos_done_event_id = UINT32_MAX;
  169. size_t i = 0;
  170. // getnext loop process
  171. if (exist_getnext) {
  172. // getnext loop stream switch op
  173. getnext_switch_stream_id = resource_manager.ApplyNewStream();
  174. uint32_t getnext_stream_id = resource_manager.ApplyNewStream();
  175. CNodePtr getnext_switch_app = CreateStreamSwitchOp(kernel_graph_ptr, switch_loop_input, kGetNextStreamSwitch);
  176. MS_EXCEPTION_IF_NULL(getnext_switch_app);
  177. AnfAlgo::SetStreamId(getnext_switch_stream_id, getnext_switch_app.get());
  178. // update getnext loop stream switch true_branch_stream attr
  179. AnfAlgo::SetNodeAttr(kStreamNeedActivedFirst, MakeValue<bool>(true), getnext_switch_app);
  180. AnfAlgo::SetNodeAttr(kAttrTrueBranchStream, MakeValue<uint32_t>(getnext_stream_id), getnext_switch_app);
  181. AnfAlgo::SetNodeAttr(kAttrStreamSwitchKind, MakeValue<uint32_t>(kGetNextStreamSwitch), getnext_switch_app);
  182. exec_order.push_back(getnext_switch_app);
  183. MS_LOG(INFO) << "GetNext loop insert Stream Switch " << getnext_switch_app->fullname_with_scope();
  184. // getnext op
  185. for (; i < orders.size(); i++) {
  186. auto node = orders[i];
  187. exec_order.push_back(node);
  188. AnfAlgo::SetStreamId(getnext_stream_id, exec_order[exec_order.size() - 1].get());
  189. if (AnfAlgo::GetCNodeName(node) == kGetNextOpName) {
  190. getnext_cnode = node;
  191. break;
  192. }
  193. }
  194. // getnext loop fpbp start send
  195. fpbp_start_event_id = resource_manager.ApplyNewEvent();
  196. CNodePtr fpbp_start_send = CreateSendApplyKernel(kernel_graph_ptr, fpbp_start_event_id);
  197. AnfAlgo::SetStreamId(getnext_stream_id, fpbp_start_send.get());
  198. exec_order.push_back(fpbp_start_send);
  199. MS_LOG(INFO) << "GetNext loop insert FpBp start Send " << fpbp_start_send->fullname_with_scope();
  200. if (eos_mode) {
  201. // getnext loop eos start send
  202. eos_start_event_id = resource_manager.ApplyNewEvent();
  203. CNodePtr eos_start_send = CreateSendApplyKernel(kernel_graph_ptr, eos_start_event_id);
  204. AnfAlgo::SetStreamId(getnext_stream_id, eos_start_send.get());
  205. exec_order.push_back(eos_start_send);
  206. MS_LOG(INFO) << "GetNext loop insert EoS start Send " << eos_start_send->fullname_with_scope();
  207. }
  208. }
  209. // End Of Sequence loop process
  210. if (eos_mode) {
  211. // eos loop stream switch
  212. uint32_t eos_switch_stream_id = resource_manager.ApplyNewStream();
  213. uint32_t eos_stream_id = resource_manager.ApplyNewStream();
  214. CNodePtr eos_switch_app = CreateStreamSwitchOp(kernel_graph_ptr, switch_loop_input, kEosStreamSwitch);
  215. MS_EXCEPTION_IF_NULL(eos_switch_app);
  216. AnfAlgo::SetStreamId(eos_switch_stream_id, eos_switch_app.get());
  217. AnfAlgo::SetNodeAttr(kStreamNeedActivedFirst, MakeValue<bool>(true), eos_switch_app);
  218. // update eos loop stream switch true_branch_stream attr
  219. AnfAlgo::SetNodeAttr(kAttrTrueBranchStream, MakeValue<uint32_t>(eos_stream_id), eos_switch_app);
  220. AnfAlgo::SetNodeAttr(kAttrStreamSwitchKind, MakeValue<uint32_t>(kEosStreamSwitch), eos_switch_app);
  221. exec_order.push_back(eos_switch_app);
  222. MS_LOG(INFO) << "EoS loop insert Stream Switch " << eos_switch_app->fullname_with_scope();
  223. // eos loop eos start recv
  224. CNodePtr eos_start_recv = CreateRecvApplyKernel(kernel_graph_ptr, eos_start_event_id);
  225. AnfAlgo::SetStreamId(eos_stream_id, eos_start_recv.get());
  226. exec_order.push_back(eos_start_recv);
  227. MS_LOG(INFO) << "EoS loop insert EoS Recv " << eos_start_recv->fullname_with_scope();
  228. // EndOfSequence op
  229. CNodePtr end_of_sequence_op = CreateEndOfSequenceOP(kernel_graph_ptr, getnext_cnode);
  230. MS_EXCEPTION_IF_NULL(end_of_sequence_op);
  231. AnfAlgo::SetStreamId(eos_stream_id, end_of_sequence_op.get());
  232. exec_order.push_back(end_of_sequence_op);
  233. MS_LOG(INFO) << "EoS loop insert Eos Op " << end_of_sequence_op->fullname_with_scope();
  234. // eos loop eos done send
  235. eos_done_event_id = resource_manager.ApplyNewEvent();
  236. CNodePtr eos_done_send = CreateSendApplyKernel(kernel_graph_ptr, eos_done_event_id);
  237. AnfAlgo::SetStreamId(eos_stream_id, eos_done_send.get());
  238. exec_order.push_back(eos_done_send);
  239. MS_LOG(INFO) << "EoS loop insert EoS done Send " << eos_done_send->fullname_with_scope();
  240. // eos loop stream active
  241. fpbp_active_streams.push_back(eos_switch_stream_id);
  242. }
  243. bool exist_independent = ExistIndependent(kernel_graph_ptr);
  244. if (exist_independent) {
  245. // Independet parallel
  246. CNodePtr independent_switch_app =
  247. CreateStreamSwitchOp(kernel_graph_ptr, switch_loop_input, kIndependentStreamSwitch);
  248. MS_EXCEPTION_IF_NULL(independent_switch_app);
  249. uint32_t independent_switch_stream_id = resource_manager.ApplyNewStream();
  250. AnfAlgo::SetStreamId(independent_switch_stream_id, independent_switch_app.get());
  251. AnfAlgo::SetNodeAttr(kStreamNeedActivedFirst, MakeValue<bool>(true), independent_switch_app);
  252. AnfAlgo::SetNodeAttr(kAttrStreamSwitchKind, MakeValue<uint32_t>(kIndependentStreamSwitch), independent_switch_app);
  253. exec_order.push_back(independent_switch_app);
  254. MS_LOG(INFO) << "Independent op loop insert Stream Switch " << independent_switch_app->fullname_with_scope();
  255. }
  256. // fpbp loop process
  257. // fpbp loop stream switch
  258. uint32_t fpbp_switch_stream_id = resource_manager.ApplyNewStream();
  259. uint32_t fpbp_stream_id = resource_manager.ApplyNewStream();
  260. CNodePtr fpbp_switch_app = CreateStreamSwitchOp(kernel_graph_ptr, switch_loop_input, kFpBpStreamSwitch);
  261. MS_EXCEPTION_IF_NULL(fpbp_switch_app);
  262. AnfAlgo::SetStreamId(fpbp_switch_stream_id, fpbp_switch_app.get());
  263. AnfAlgo::SetNodeAttr(kStreamNeedActivedFirst, MakeValue<bool>(true), fpbp_switch_app);
  264. // update fpbp loop stream switch true_branch_stream attr
  265. AnfAlgo::SetNodeAttr(kAttrTrueBranchStream, MakeValue<uint32_t>(fpbp_stream_id), fpbp_switch_app);
  266. AnfAlgo::SetNodeAttr(kAttrStreamSwitchKind, MakeValue<uint32_t>(kFpBpStreamSwitch), fpbp_switch_app);
  267. exec_order.push_back(fpbp_switch_app);
  268. MS_LOG(INFO) << "FpBp loop insert Stream Switch " << fpbp_switch_app->fullname_with_scope();
  269. if (exist_getnext) {
  270. // fpbp loop fpbp start recv
  271. CNodePtr fpbp_start_recv = CreateRecvApplyKernel(kernel_graph_ptr, fpbp_start_event_id);
  272. AnfAlgo::SetStreamId(fpbp_stream_id, fpbp_start_recv.get());
  273. exec_order.push_back(fpbp_start_recv);
  274. MS_LOG(INFO) << "FpBp loop insert FpBp start Recv " << fpbp_start_recv->fullname_with_scope();
  275. }
  276. // next loop AssignAdd
  277. CNodePtr assign_add_one = CreateStreamAssignAddnOP(kernel_graph_ptr, switch_loop_input, false);
  278. MS_EXCEPTION_IF_NULL(assign_add_one);
  279. AnfAlgo::SetStreamId(fpbp_stream_id, assign_add_one.get());
  280. exec_order.push_back(assign_add_one);
  281. MS_LOG(INFO) << "FpBp loop insert next loop AssignAdd " << assign_add_one->fullname_with_scope();
  282. // fpbp getnext output memcpy
  283. std::vector<CNodePtr> memcpy_list;
  284. std::vector<CNodePtr> other_list;
  285. if (exist_getnext) {
  286. CNodePtr cur_cnode = nullptr;
  287. for (size_t idx = i + 1; idx < orders.size(); idx++) {
  288. cur_cnode = orders[idx];
  289. if (AnfAlgo::HasNodeAttr(kAttrLabelForInsertStreamActive, cur_cnode)) {
  290. auto pre_node = orders[idx - 1];
  291. auto pre_kernel_name = AnfAlgo::GetCNodeName(pre_node);
  292. if (pre_kernel_name == kAtomicAddrCleanOpName) {
  293. other_list.pop_back();
  294. memcpy_list.push_back(pre_node);
  295. }
  296. memcpy_list.emplace_back(cur_cnode);
  297. } else {
  298. other_list.emplace_back(cur_cnode);
  299. }
  300. }
  301. (void)std::copy(memcpy_list.begin(), memcpy_list.end(), std::back_inserter(exec_order));
  302. } else {
  303. other_list = orders;
  304. }
  305. // fpbp loop eos done recv
  306. if (eos_mode) {
  307. CNodePtr eos_done_recv = CreateRecvApplyKernel(kernel_graph_ptr, eos_done_event_id);
  308. AnfAlgo::SetStreamId(fpbp_stream_id, eos_done_recv.get());
  309. exec_order.push_back(eos_done_recv);
  310. MS_LOG(INFO) << "FpBp loop insert EoS done Recv " << eos_done_recv->fullname_with_scope();
  311. }
  312. // stream active to activate getnext loop
  313. if (exist_getnext) {
  314. CNodePtr getnext_active_app = CreateStreamActiveOp(kernel_graph_ptr);
  315. MS_EXCEPTION_IF_NULL(getnext_active_app);
  316. getnext_active_streams.push_back(getnext_switch_stream_id);
  317. AnfAlgo::SetNodeAttr(kAttrActiveStreamList, MakeValue<std::vector<uint32_t>>(getnext_active_streams),
  318. getnext_active_app);
  319. exec_order.push_back(getnext_active_app);
  320. MS_LOG(INFO) << "FpBp loop insert GetNext loop Stream Active " << getnext_active_app->fullname_with_scope();
  321. }
  322. // fpbp loop other ops
  323. (void)std::copy(other_list.begin(), other_list.end(), std::back_inserter(exec_order));
  324. // current assign add op
  325. CNodePtr cur_assign_add = CreateStreamAssignAddnOP(kernel_graph_ptr, switch_loop_input, true);
  326. MS_EXCEPTION_IF_NULL(cur_assign_add);
  327. AnfAlgo::SetNodeAttr(kAttrFpBpEnd, MakeValue<bool>(true), cur_assign_add);
  328. exec_order.push_back(cur_assign_add);
  329. MS_LOG(INFO) << "FpBp loop insert current loop AssignAdd " << cur_assign_add->fullname_with_scope();
  330. // stream active to activate fpbp loop and eos loop
  331. CNodePtr fpbp_active_app = CreateStreamActiveOp(kernel_graph_ptr);
  332. MS_EXCEPTION_IF_NULL(fpbp_active_app);
  333. fpbp_active_streams.push_back(fpbp_switch_stream_id);
  334. AnfAlgo::SetNodeAttr(kAttrActiveStreamList, MakeValue<std::vector<uint32_t>>(fpbp_active_streams), fpbp_active_app);
  335. exec_order.push_back(fpbp_active_app);
  336. MS_LOG(INFO) << "FpBp loop insert FpBp loop and Eos loop Stream Active " << fpbp_active_app->fullname_with_scope();
  337. kernel_graph_ptr->set_execution_order(exec_order);
  338. }
  339. void KernelAdjust::CreateSwitchOpParameters(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr,
  340. std::map<std::string, mindspore::ParameterPtr> *switch_loop_input) {
  341. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  342. MS_EXCEPTION_IF_NULL(switch_loop_input);
  343. ShapeVector shp = {1};
  344. tensor::TensorPtr tensor_ptr = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  345. MS_EXCEPTION_IF_NULL(tensor_ptr);
  346. mindspore::abstract::AbstractBasePtr paremeter_abstract_ptr = tensor_ptr->ToAbstract();
  347. if (paremeter_abstract_ptr == nullptr) {
  348. MS_LOG(EXCEPTION) << "create abstract before insert switch op failed!";
  349. }
  350. ParameterPtr cur_loop_count = std::make_shared<Parameter>(kernel_graph_ptr);
  351. MS_EXCEPTION_IF_NULL(cur_loop_count);
  352. cur_loop_count->set_name(kCurLoopCountParamName);
  353. cur_loop_count->set_abstract(paremeter_abstract_ptr);
  354. ParameterPtr loop_count_cur = kernel_graph_ptr->NewParameter(cur_loop_count);
  355. (*switch_loop_input)[kCurLoopCountParamName] = loop_count_cur;
  356. ParameterPtr next_loop_count = std::make_shared<Parameter>(kernel_graph_ptr);
  357. MS_EXCEPTION_IF_NULL(next_loop_count);
  358. next_loop_count->set_name(kNextLoopCountParamName);
  359. next_loop_count->set_abstract(paremeter_abstract_ptr);
  360. ParameterPtr loop_count_next = kernel_graph_ptr->NewParameter(next_loop_count);
  361. (*switch_loop_input)[kNextLoopCountParamName] = loop_count_next;
  362. ParameterPtr iter_loop = std::make_shared<Parameter>(kernel_graph_ptr);
  363. iter_loop->set_name(kIterLoopParamName);
  364. iter_loop->set_abstract(paremeter_abstract_ptr);
  365. ParameterPtr iter_loop_new = kernel_graph_ptr->NewParameter(iter_loop);
  366. (*switch_loop_input)[kIterLoopParamName] = iter_loop_new;
  367. ParameterPtr one = std::make_shared<Parameter>(kernel_graph_ptr);
  368. one->set_name(kOneParamName);
  369. one->set_abstract(paremeter_abstract_ptr);
  370. ParameterPtr one_new = kernel_graph_ptr->NewParameter(one);
  371. (*switch_loop_input)[kOneParamName] = one_new;
  372. ParameterPtr epoch = std::make_shared<Parameter>(kernel_graph_ptr);
  373. MS_EXCEPTION_IF_NULL(epoch);
  374. epoch->set_name(kEpochParamName);
  375. epoch->set_abstract(paremeter_abstract_ptr);
  376. ParameterPtr epoch_new = kernel_graph_ptr->NewParameter(epoch);
  377. (*switch_loop_input)[kEpochParamName] = epoch_new;
  378. }
  379. kernel::KernelBuildInfo::KernelBuildInfoBuilder KernelAdjust::CreateMngKernelBuilder(
  380. const std::vector<std::string> &formats, const std::vector<TypeId> &type_ids) {
  381. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder;
  382. selected_kernel_builder.SetInputsFormat(formats);
  383. selected_kernel_builder.SetInputsDeviceType(type_ids);
  384. selected_kernel_builder.SetFusionType(kernel::FusionType::OPAQUE);
  385. selected_kernel_builder.SetProcessor(kernel::Processor::AICORE);
  386. selected_kernel_builder.SetKernelType(KernelType::RT_KERNEL);
  387. return selected_kernel_builder;
  388. }
  389. CNodePtr KernelAdjust::CreateStreamSwitchOp(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr,
  390. const std::map<std::string, mindspore::ParameterPtr> &switch_loop_input,
  391. StreamSwitchKind kind) {
  392. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder = CreateMngKernelBuilder(
  393. {kOpFormat_DEFAULT, kOpFormat_DEFAULT}, {TypeId::kNumberTypeInt32, TypeId::kNumberTypeInt32});
  394. auto typeNone_abstract = std::make_shared<abstract::AbstractNone>();
  395. auto stream_switch = std::make_shared<Primitive>(kStreamSwitchOpName);
  396. std::vector<AnfNodePtr> inputs;
  397. inputs.push_back(NewValueNode(stream_switch));
  398. if (kind == kFpBpStreamSwitch || kind == kEosStreamSwitch) {
  399. inputs.push_back(switch_loop_input.at(kNextLoopCountParamName));
  400. } else if (kind == kGetNextStreamSwitch || kind == kIndependentStreamSwitch) {
  401. inputs.push_back(switch_loop_input.at(kNextLoopCountParamName));
  402. } else {
  403. MS_LOG(ERROR) << "unknown stream switch kind";
  404. }
  405. inputs.push_back(switch_loop_input.at(kIterLoopParamName));
  406. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  407. CNodePtr stream_switch_app = kernel_graph_ptr->NewCNode(inputs);
  408. MS_EXCEPTION_IF_NULL(stream_switch_app);
  409. AnfAlgo::SetSelectKernelBuildInfo(selected_kernel_builder.Build(), stream_switch_app.get());
  410. stream_switch_app->set_abstract(typeNone_abstract);
  411. // set attr: cond_ RT_LESS
  412. int condition = static_cast<int>(RT_LESS);
  413. ValuePtr cond = MakeValue(condition);
  414. AnfAlgo::SetNodeAttr(kAttrSwitchCondition, cond, stream_switch_app);
  415. // set attr:data_type
  416. int data_type = static_cast<int>(RT_SWITCH_INT64);
  417. ValuePtr dt = MakeValue(data_type);
  418. AnfAlgo::SetNodeAttr(kAttrDataType, dt, stream_switch_app);
  419. // set distinction label and graph id
  420. return stream_switch_app;
  421. }
  422. CNodePtr KernelAdjust::CreateStreamActiveOp(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr) {
  423. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder = CreateMngKernelBuilder(
  424. {kOpFormat_DEFAULT, kOpFormat_DEFAULT}, {TypeId::kNumberTypeInt32, TypeId::kNumberTypeInt32});
  425. abstract::AbstractBasePtr typeNone_abstract = std::make_shared<abstract::AbstractNone>();
  426. auto stream_active_others = std::make_shared<Primitive>(kStreamActiveOpName);
  427. std::vector<AnfNodePtr> inputs;
  428. inputs.push_back(NewValueNode(stream_active_others));
  429. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  430. CNodePtr stream_active_others_app = kernel_graph_ptr->NewCNode(inputs);
  431. MS_EXCEPTION_IF_NULL(stream_active_others_app);
  432. AnfAlgo::SetSelectKernelBuildInfo(selected_kernel_builder.Build(), stream_active_others_app.get());
  433. stream_active_others_app->set_abstract(typeNone_abstract);
  434. return stream_active_others_app;
  435. }
  436. CNodePtr KernelAdjust::CreatTupleGetItemNode(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr,
  437. const CNodePtr &node, size_t output_idx) {
  438. auto idx = NewValueNode(SizeToLong(output_idx));
  439. MS_EXCEPTION_IF_NULL(idx);
  440. auto imm = std::make_shared<Int64Imm>(SizeToInt(output_idx));
  441. auto abstract_scalar = std::make_shared<abstract::AbstractScalar>(imm);
  442. idx->set_abstract(abstract_scalar);
  443. CNodePtr tuple_getitem = kernel_graph_ptr->NewCNode({NewValueNode(prim::kPrimTupleGetItem), node, idx});
  444. MS_EXCEPTION_IF_NULL(tuple_getitem);
  445. tuple_getitem->set_scope(node->scope());
  446. std::vector<size_t> origin_shape = AnfAlgo::GetOutputInferShape(node, output_idx);
  447. TypeId origin_type = AnfAlgo::GetOutputInferDataType(node, output_idx);
  448. AnfAlgo::SetOutputInferTypeAndShape({origin_type}, {origin_shape}, tuple_getitem.get());
  449. return tuple_getitem;
  450. }
  451. CNodePtr KernelAdjust::CreateEndOfSequenceOP(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr,
  452. const CNodePtr &getnext_cnode) {
  453. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  454. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder;
  455. selected_kernel_builder.SetInputsFormat({kOpFormat_DEFAULT});
  456. selected_kernel_builder.SetInputsDeviceType({kNumberTypeUInt8});
  457. selected_kernel_builder.SetFusionType(kernel::FusionType::OPAQUE);
  458. selected_kernel_builder.SetProcessor(kernel::Processor::AICPU);
  459. selected_kernel_builder.SetKernelType(KernelType::AICPU_KERNEL);
  460. selected_kernel_builder.SetOutputsFormat({kOpFormat_DEFAULT});
  461. selected_kernel_builder.SetOutputsDeviceType({kNumberTypeUInt8});
  462. // EndOfSequence
  463. auto end_of_sequence = std::make_shared<Primitive>(kEndOfSequence);
  464. std::vector<AnfNodePtr> inputs;
  465. inputs.push_back(NewValueNode(end_of_sequence));
  466. // GetNext output 0 is EndOfSequence's input
  467. auto tuple_get_item = CreatTupleGetItemNode(kernel_graph_ptr, getnext_cnode, 0);
  468. inputs.push_back(tuple_get_item);
  469. CNodePtr end_of_sequence_node = kernel_graph_ptr->NewCNode(inputs);
  470. MS_EXCEPTION_IF_NULL(end_of_sequence_node);
  471. AnfAlgo::SetSelectKernelBuildInfo(selected_kernel_builder.Build(), end_of_sequence_node.get());
  472. std::vector<std::string> input_names = {"x"};
  473. ValuePtr input_names_v = MakeValue(input_names);
  474. AnfAlgo::SetNodeAttr("input_names", input_names_v, end_of_sequence_node);
  475. std::vector<std::string> output_names = {"y"};
  476. ValuePtr output_names_v = MakeValue(output_names);
  477. AnfAlgo::SetNodeAttr("output_names", output_names_v, end_of_sequence_node);
  478. end_of_sequence_node->set_abstract(tuple_get_item->abstract());
  479. return end_of_sequence_node;
  480. }
  481. CNodePtr KernelAdjust::CreateStreamAssignAddnOP(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr,
  482. const std::map<std::string, mindspore::ParameterPtr> &switch_loop_input,
  483. bool cur_loop) {
  484. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  485. kernel::KernelBuildInfo::KernelBuildInfoBuilder selected_kernel_builder = CreateMngKernelBuilder(
  486. {kOpFormat_DEFAULT, kOpFormat_DEFAULT}, {TypeId::kNumberTypeInt32, TypeId::kNumberTypeInt32});
  487. selected_kernel_builder.SetOutputsFormat({kOpFormat_DEFAULT});
  488. selected_kernel_builder.SetOutputsDeviceType({kNumberTypeInt32});
  489. // AssignAdd
  490. auto assign_add = std::make_shared<Primitive>(kAssignAddOpName);
  491. std::vector<AnfNodePtr> inputs;
  492. inputs.push_back(NewValueNode(assign_add));
  493. if (cur_loop) {
  494. inputs.push_back(switch_loop_input.at(kCurLoopCountParamName));
  495. } else {
  496. inputs.push_back(switch_loop_input.at(kNextLoopCountParamName));
  497. }
  498. inputs.push_back(switch_loop_input.at(kOneParamName));
  499. CNodePtr assign_add_one = kernel_graph_ptr->NewCNode(inputs);
  500. MS_EXCEPTION_IF_NULL(assign_add_one);
  501. AnfAlgo::SetSelectKernelBuildInfo(selected_kernel_builder.Build(), assign_add_one.get());
  502. std::vector<std::string> input_names = {"ref", "value"};
  503. std::vector<std::string> output_names = {"output"};
  504. ValuePtr input_names_v = MakeValue(input_names);
  505. ValuePtr output_names_v = MakeValue(output_names);
  506. AnfAlgo::SetNodeAttr("input_names", input_names_v, assign_add_one);
  507. AnfAlgo::SetNodeAttr("output_names", output_names_v, assign_add_one);
  508. selected_kernel_builder.SetKernelType(KernelType::TBE_KERNEL);
  509. MS_EXCEPTION_IF_NULL(switch_loop_input.at(kCurLoopCountParamName));
  510. assign_add_one->set_abstract(switch_loop_input.at(kCurLoopCountParamName)->abstract());
  511. // add AssignAdd op to kernel ref node map
  512. session::AnfWithOutIndex final_pair = std::make_pair(assign_add_one, 0);
  513. session::KernelWithIndex kernel_with_index = AnfAlgo::VisitKernel(AnfAlgo::GetInputNode(assign_add_one, 0), 0);
  514. kernel_graph_ptr->AddRefCorrespondPairs(final_pair, kernel_with_index);
  515. return assign_add_one;
  516. }
  517. bool KernelAdjust::StepLoadCtrlInputs(const std::shared_ptr<session::KernelGraph> &kernel_graph_ptr) {
  518. if (!NeedInsertSwitch()) {
  519. return true;
  520. }
  521. MS_EXCEPTION_IF_NULL(kernel_graph_ptr);
  522. if (kernel_graph_ptr->is_dynamic_shape()) {
  523. MS_LOG(INFO) << "Skip StepLoadCtrlInputs";
  524. return true;
  525. }
  526. auto input_nodes = kernel_graph_ptr->inputs();
  527. std::vector<tensor::TensorPtr> inputs;
  528. LoadSwitchInputs(&inputs);
  529. std::shared_ptr<std::vector<tensor::TensorPtr>> inputsPtr = std::make_shared<std::vector<tensor::TensorPtr>>(inputs);
  530. kernel_graph_ptr->set_input_ctrl_tensors(inputsPtr);
  531. size_t input_ctrl_size = inputs.size();
  532. // inputs_node:include four ctrl nodes in the back. such as:conv,loop_cnt, ites_loop, zero, one.
  533. // deal four ctrl nodes.
  534. for (size_t i = 0; i < inputs.size(); ++i) {
  535. auto tensor = inputs[i];
  536. size_t deal_index = input_nodes.size() - input_ctrl_size + i;
  537. if (deal_index >= input_nodes.size()) {
  538. MS_LOG(EXCEPTION) << "deal_index[" << deal_index << "] out of range";
  539. }
  540. auto input_node = input_nodes[deal_index];
  541. bool need_sync = false;
  542. MS_EXCEPTION_IF_NULL(input_node);
  543. if (input_node->isa<Parameter>()) {
  544. auto pk_node = input_node->cast<ParameterPtr>();
  545. MS_EXCEPTION_IF_NULL(tensor);
  546. MS_EXCEPTION_IF_NULL(pk_node);
  547. if (tensor->NeedSyncHostToDevice() || !pk_node->has_default()) {
  548. need_sync = true;
  549. }
  550. }
  551. if (need_sync) {
  552. auto pk_node = input_node->cast<ParameterPtr>();
  553. MS_EXCEPTION_IF_NULL(pk_node);
  554. auto device_address = AnfAlgo::GetMutableOutputAddr(pk_node, 0);
  555. MS_EXCEPTION_IF_NULL(device_address);
  556. tensor->set_device_address(device_address);
  557. if (!device_address->SyncHostToDevice(trans::GetRuntimePaddingShape(pk_node, 0),
  558. LongToSize(tensor->data().nbytes()), tensor->data_type(),
  559. tensor->data_c())) {
  560. MS_LOG(INFO) << "SyncHostToDevice failed.";
  561. return false;
  562. }
  563. }
  564. tensor->set_sync_status(kNoNeedSync);
  565. }
  566. return true;
  567. }
  568. void KernelAdjust::LoadSwitchInputs(std::vector<tensor::TensorPtr> *inputs) {
  569. MS_LOG(INFO) << "---------------- LoadSwitchInputs---";
  570. MS_EXCEPTION_IF_NULL(inputs);
  571. // current loop count
  572. ShapeVector shp = {1};
  573. tensor::TensorPtr cur_loop_count = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  574. MS_EXCEPTION_IF_NULL(cur_loop_count);
  575. int32_t *val = nullptr;
  576. val = static_cast<int32_t *>(cur_loop_count->data_c());
  577. MS_EXCEPTION_IF_NULL(val);
  578. *val = 0;
  579. inputs->push_back(cur_loop_count);
  580. // next loop count
  581. tensor::TensorPtr next_loop_count = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  582. MS_EXCEPTION_IF_NULL(next_loop_count);
  583. val = static_cast<int32_t *>(next_loop_count->data_c());
  584. MS_EXCEPTION_IF_NULL(val);
  585. *val = 0;
  586. inputs->push_back(next_loop_count);
  587. // Epoch in device
  588. tensor::TensorPtr epoch_tensor = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  589. MS_EXCEPTION_IF_NULL(epoch_tensor);
  590. val = static_cast<int32_t *>(epoch_tensor->data_c());
  591. MS_EXCEPTION_IF_NULL(val);
  592. *val = 0;
  593. inputs->push_back(epoch_tensor);
  594. // total loop count per iter
  595. tensor::TensorPtr iter_loop_tensor = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  596. MS_EXCEPTION_IF_NULL(iter_loop_tensor);
  597. val = static_cast<int32_t *>(iter_loop_tensor->data_c());
  598. MS_EXCEPTION_IF_NULL(val);
  599. *val = SizeToInt(LongToSize(ConfigManager::GetInstance().iter_num()));
  600. MS_LOG(INFO) << "iter_loop_tensor = " << *val;
  601. inputs->push_back(iter_loop_tensor);
  602. tensor::TensorPtr one_tensor = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  603. MS_EXCEPTION_IF_NULL(one_tensor);
  604. val = static_cast<int32_t *>(one_tensor->data_c());
  605. MS_EXCEPTION_IF_NULL(val);
  606. *val = 1;
  607. inputs->push_back(one_tensor);
  608. MS_LOG(INFO) << "---------------- LoadSwitchInputs End--";
  609. }
  610. void KernelAdjust::Profiling(NotNull<session::KernelGraph *> kernel_graph_ptr) {
  611. if (!ascend::ProfilingManager::GetInstance().IsProfiling()) {
  612. MS_LOG(INFO) << "No need to profiling";
  613. return;
  614. }
  615. auto graph_id_env = std::getenv(kProfilingGraphId);
  616. if (graph_id_env != nullptr) {
  617. auto graph_id = std::stoul(graph_id_env);
  618. if (graph_id != kernel_graph_ptr->graph_id()) {
  619. MS_LOG(WARNING) << "Get PROFILING_GRAPH_ID " << graph_id
  620. << " Not Match Current Graph Id:" << kernel_graph_ptr->graph_id();
  621. return;
  622. }
  623. }
  624. ProfilingTraceInfo profiling_trace_info = ProfilingUtils::GetProfilingTraceFromEnv(kernel_graph_ptr);
  625. if (!profiling_trace_info.IsValid()) {
  626. MS_LOG(INFO) << "[profiling] no profiling node found!";
  627. return;
  628. }
  629. InsertProfilingKernel(profiling_trace_info, kernel_graph_ptr);
  630. }
  631. void KernelAdjust::InsertProfilingKernel(const ProfilingTraceInfo &profiling_trace_info,
  632. NotNull<session::KernelGraph *> kernel_graph_ptr) {
  633. MS_LOG(INFO) << "[profiling] Insert profiling kernel start";
  634. if (!profiling_trace_info.IsValid()) {
  635. MS_LOG(WARNING) << "Profiling trace point not found";
  636. return;
  637. }
  638. std::vector<CNodePtr> new_cnode_list;
  639. std::vector<CNodePtr> cnode_ptr_list = kernel_graph_ptr->execution_order();
  640. if (cnode_ptr_list.empty()) {
  641. MS_LOG(ERROR) << "No CNode in graph";
  642. return;
  643. }
  644. for (const auto &cnode_ptr : cnode_ptr_list) {
  645. ProfilingUtils::ProfilingTraceFpStart(cnode_ptr, profiling_trace_info, kernel_graph_ptr, NOT_NULL(&new_cnode_list));
  646. new_cnode_list.emplace_back(cnode_ptr);
  647. ProfilingUtils::ProfilingCustomOp(cnode_ptr, profiling_trace_info, kernel_graph_ptr, NOT_NULL(&new_cnode_list));
  648. ProfilingUtils::ProfilingTraceBpEnd(cnode_ptr, profiling_trace_info, kernel_graph_ptr, NOT_NULL(&new_cnode_list));
  649. ProfilingUtils::ProfilingTraceEnd(cnode_ptr, profiling_trace_info, kernel_graph_ptr, NOT_NULL(&new_cnode_list));
  650. }
  651. kernel_graph_ptr->set_execution_order(new_cnode_list);
  652. }
  653. } // namespace device
  654. } // namespace mindspore