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