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

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