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_runtime.cc 30 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. /**
  2. * Copyright 2019 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 "device/kernel_runtime.h"
  17. #include <vector>
  18. #include <utility>
  19. #include <numeric>
  20. #include <functional>
  21. #include "common/utils.h"
  22. #include "common/trans.h"
  23. #include "utils/utils.h"
  24. #include "utils/context/ms_context.h"
  25. #include "operator/ops.h"
  26. #include "pipeline/parse/python_adapter.h"
  27. #include "session/kernel_graph.h"
  28. #include "session/anf_runtime_algorithm.h"
  29. #include "kernel/common_utils.h"
  30. #include "kernel/oplib/oplib.h"
  31. #include "ir/value.h"
  32. using mindspore::kernel::Address;
  33. using mindspore::kernel::AddressPtr;
  34. namespace mindspore {
  35. namespace device {
  36. KernelRuntime::~KernelRuntime() {
  37. #ifdef ENABLE_DUMP_E2E
  38. dump_conf_ptr_ = nullptr;
  39. #endif
  40. }
  41. bool KernelRuntime::Run(session::KernelGraph *graph) {
  42. bool ret = false;
  43. auto context_ptr = MsContext::GetInstance();
  44. MS_EXCEPTION_IF_NULL(context_ptr);
  45. #if defined(_WIN32) || defined(_WIN64)
  46. auto start_time = std::chrono::steady_clock::now();
  47. #else
  48. struct timeval start_time, end_time;
  49. (void)gettimeofday(&start_time, nullptr);
  50. #endif
  51. bool is_task_sink = context_ptr->enable_task_sink();
  52. if (is_task_sink) {
  53. ret = RunTask(graph);
  54. } else {
  55. ret = LaunchKernel(graph);
  56. }
  57. #if defined(_WIN32) || defined(_WIN64)
  58. auto end_time = std::chrono::steady_clock::now();
  59. std::chrono::duration<double, std::ratio<1, 1000000>> cost = end_time - start_time;
  60. MS_LOG(INFO) << "Call MS Run Success in " << cost.count() << " us";
  61. #else
  62. (void)gettimeofday(&end_time, nullptr);
  63. const uint64_t kUSecondInSecond = 1000000;
  64. uint64_t cost = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec);
  65. cost += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec);
  66. MS_LOG(INFO) << "Call MS Run Success in " << cost << " us";
  67. #endif
  68. return ret;
  69. }
  70. // for D to impl
  71. bool KernelRuntime::DumpData(mindspore::session::KernelGraph *graph) {
  72. if (graph != nullptr) {
  73. return true;
  74. }
  75. return false;
  76. }
  77. // for D to impl
  78. bool KernelRuntime::GenTask(const session::KernelGraph *graph) {
  79. if (graph != nullptr) {
  80. return true;
  81. }
  82. return false;
  83. }
  84. bool KernelRuntime::LoadTask(const session::KernelGraph *graph) {
  85. if (graph != nullptr) {
  86. return true;
  87. }
  88. return false;
  89. }
  90. // for D to impl
  91. bool KernelRuntime::RunTask(const session::KernelGraph *graph) {
  92. if (graph != nullptr) {
  93. return true;
  94. }
  95. return false;
  96. }
  97. bool KernelRuntime::NodeOutputDeviceAddressExist(const AnfNodePtr &kernel, size_t index) {
  98. MS_EXCEPTION_IF_NULL(kernel);
  99. if (AnfAlgo::OutputAddrExist(kernel, index)) {
  100. return true;
  101. }
  102. return false;
  103. }
  104. size_t KernelRuntime::CountNodeDeviceMemorySize(const mindspore::AnfNodePtr &node, size_t output_index) {
  105. MS_EXCEPTION_IF_NULL(node);
  106. if (output_index >= AnfAlgo::GetOutputTensorNum(node)) {
  107. MS_EXCEPTION(ArgumentError) << "output index [" << output_index << "] large than the output size ["
  108. << AnfAlgo::GetOutputTensorNum(node) << "] of node!";
  109. }
  110. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(node, output_index);
  111. if (output_type_id == kTypeUnknown) {
  112. output_type_id = AnfAlgo::GetOutputInferDataType(node, output_index);
  113. }
  114. size_t type_size = GetTypeByte(TypeIdToType(output_type_id));
  115. std::vector<size_t> shape = AnfAlgo::GetOutputDeviceShape(node, output_index);
  116. auto format = AnfAlgo::GetOutputFormat(node, output_index);
  117. if (shape.empty() && format != kOpFormat_DEFAULT) {
  118. shape = trans::PaddingShapeTo4d(shape, AnfAlgo::GetOutputReshapeType(node, output_index));
  119. shape = trans::TransShapeToDevice(shape, format);
  120. }
  121. // scalar's output shape is a empty vector
  122. size_t tensor_size = std::accumulate(shape.begin(), shape.end(), type_size, std::multiplies<size_t>());
  123. return tensor_size;
  124. }
  125. void KernelRuntime::AssignMemory(session::KernelGraph *graph) {
  126. auto context_ptr = MsContext::GetInstance();
  127. MS_EXCEPTION_IF_NULL(context_ptr);
  128. MS_EXCEPTION_IF_NULL(mem_manager_);
  129. mem_manager_->ResetDynamicMemory();
  130. AssignStaticMemory(graph);
  131. AssignDynamicMemory(graph);
  132. UpdateRefNodeOutputMem(graph);
  133. }
  134. void KernelRuntime::RunOpAssignMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  135. session::KernelGraph *graph) {
  136. MS_EXCEPTION_IF_NULL(graph);
  137. RunOpAssignInputMemory(input_tensors, graph);
  138. AssignStaticMemoryValueNode(graph);
  139. for (const auto &cnode : graph->execution_order()) {
  140. RunOpAssignOutputMemory(cnode);
  141. RunOpAssignWorkSpaceMemory(cnode);
  142. }
  143. UpdateRefNodeOutputMem(graph);
  144. }
  145. void KernelRuntime::RunOpClearMemory(session::KernelGraph *graph) {
  146. MS_EXCEPTION_IF_NULL(graph);
  147. // clear input parameter memory resource
  148. for (const auto &input_node : graph->inputs()) {
  149. MS_EXCEPTION_IF_NULL(input_node);
  150. AnfAlgo::SetOutputAddr(nullptr, 0, input_node.get());
  151. }
  152. // clear input value node memory resource
  153. for (const auto &value_node : graph->graph_value_nodes()) {
  154. MS_EXCEPTION_IF_NULL(value_node);
  155. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  156. }
  157. for (const auto &cnode : graph->execution_order()) {
  158. MS_EXCEPTION_IF_NULL(cnode);
  159. // clear output memory resource
  160. for (size_t index = 0; index < AnfAlgo::GetOutputTensorNum(cnode); ++index) {
  161. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  162. }
  163. // clear workspace memory resource
  164. auto kernel_mod = AnfAlgo::GetKernelMod(cnode);
  165. MS_EXCEPTION_IF_NULL(kernel_mod);
  166. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  167. for (size_t index = 0; index < workspace_lists.size(); ++index) {
  168. AnfAlgo::SetWorkspaceAddr(nullptr, index, cnode.get());
  169. }
  170. }
  171. }
  172. void KernelRuntime::AssignStaticMemory(session::KernelGraph *graph) {
  173. AssignStaticMemoryInput(graph);
  174. AssignStaticMemoryValueNode(graph);
  175. AssignStaticMemoryOutput(graph);
  176. }
  177. void KernelRuntime::RunOpAssignInputMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  178. const session::KernelGraph *graph) {
  179. MS_EXCEPTION_IF_NULL(graph);
  180. MS_EXCEPTION_IF_NULL(mem_manager_);
  181. if (input_tensors.size() != graph->inputs().size()) {
  182. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors.size()
  183. << " should be equal to graph input parameter size " << graph->inputs().size();
  184. }
  185. for (size_t input_index = 0; input_index < graph->inputs().size(); ++input_index) {
  186. auto item = graph->inputs()[input_index];
  187. MS_EXCEPTION_IF_NULL(item);
  188. if (!item->isa<Parameter>()) {
  189. continue;
  190. }
  191. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  192. for (size_t index = 0; index < output_size; index++) {
  193. MS_EXCEPTION_IF_NULL(input_tensors[input_index]);
  194. if (input_tensors[input_index]->device_address().get() != nullptr) {
  195. AnfAlgo::SetOutputAddr(input_tensors[input_index]->device_address(), index, item.get());
  196. continue;
  197. }
  198. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  199. if (output_type_id == kTypeUnknown) {
  200. output_type_id = AnfAlgo::GetOutputInferDataType(item, index);
  201. }
  202. auto tensor_size = CountNodeDeviceMemorySize(item, index);
  203. auto device_address =
  204. CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  205. MS_EXCEPTION_IF_NULL(device_address);
  206. MS_EXCEPTION_IF_NULL(mem_manager_);
  207. auto ret = mem_manager_->MallocMemFromMemPool(device_address, tensor_size);
  208. if (!ret) {
  209. MS_LOG(EXCEPTION) << "Malloc device memory failed.";
  210. }
  211. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  212. }
  213. }
  214. }
  215. void KernelRuntime::RunOpAssignOutputMemory(const AnfNodePtr &kernel) {
  216. MS_EXCEPTION_IF_NULL(kernel);
  217. MS_EXCEPTION_IF_NULL(mem_manager_);
  218. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  219. MS_EXCEPTION_IF_NULL(kernel_mod);
  220. auto output_sizes = kernel_mod->GetOutputSizeList();
  221. if (output_sizes.empty()) {
  222. return;
  223. }
  224. for (size_t i = 0; i < output_sizes.size(); ++i) {
  225. if (AnfAlgo::OutputAddrExist(kernel, i)) {
  226. continue;
  227. }
  228. if (AnfAlgo::GetCNodeName(kernel) == kApplyMomentumOpName) {
  229. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i);
  230. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  231. continue;
  232. }
  233. std::string output_format = AnfAlgo::GetOutputFormat(kernel, i);
  234. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  235. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  236. MS_EXCEPTION_IF_NULL(device_address);
  237. auto ret = mem_manager_->MallocMemFromMemPool(device_address, output_sizes[i]);
  238. if (!ret) {
  239. MS_LOG(EXCEPTION) << "Malloc device memory failed.";
  240. }
  241. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  242. }
  243. }
  244. void KernelRuntime::RunOpAssignWorkSpaceMemory(const AnfNodePtr &kernel) {
  245. MS_EXCEPTION_IF_NULL(kernel);
  246. MS_EXCEPTION_IF_NULL(mem_manager_);
  247. if (kernel->isa<CNode>()) {
  248. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  249. MS_EXCEPTION_IF_NULL(kernel_mod);
  250. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  251. for (size_t i = 0; i < workspace_lists.size(); ++i) {
  252. auto device_address = CreateDeviceAddress(nullptr, workspace_lists[i], "", kTypeUnknown);
  253. MS_EXCEPTION_IF_NULL(device_address);
  254. auto ret = mem_manager_->MallocMemFromMemPool(device_address, workspace_lists[i]);
  255. if (!ret) {
  256. MS_LOG(EXCEPTION) << "Malloc device memory failed.";
  257. }
  258. AnfAlgo::SetWorkspaceAddr(device_address, i, kernel.get());
  259. }
  260. }
  261. }
  262. void KernelRuntime::AssignStaticMemoryInput(const session::KernelGraph *graph) {
  263. MS_EXCEPTION_IF_NULL(graph);
  264. MS_EXCEPTION_IF_NULL(mem_manager_);
  265. auto graph_inputs = graph->inputs();
  266. auto graph_valid_input = graph->valid_inputs();
  267. std::vector<AnfNodePtr> need_alloc_nodes;
  268. for (size_t i = 0; i < graph_inputs.size(); ++i) {
  269. auto item = graph_inputs[i];
  270. MS_EXCEPTION_IF_NULL(item);
  271. if (i < graph_valid_input.size() && !graph_valid_input[i]) {
  272. continue;
  273. }
  274. if (AnfAlgo::CheckPrimitiveType(item, prim::kPrimMakeTuple)) {
  275. auto outs = AnfAlgo::GetAllOutput(item);
  276. for (auto &out : outs) {
  277. MS_EXCEPTION_IF_NULL(out);
  278. if (!out->isa<Parameter>()) {
  279. continue;
  280. }
  281. if (NodeOutputDeviceAddressExist(out, 0)) {
  282. continue;
  283. }
  284. need_alloc_nodes.push_back(out);
  285. }
  286. }
  287. if (!item->isa<Parameter>()) {
  288. continue;
  289. }
  290. if (NodeOutputDeviceAddressExist(item, 0)) {
  291. continue;
  292. }
  293. need_alloc_nodes.push_back(item);
  294. }
  295. for (auto &item : need_alloc_nodes) {
  296. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  297. for (size_t index = 0; index < output_size; index++) {
  298. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  299. // if graph output is a weight and doesn't link to any cnode, it's data type will be unknown
  300. if (output_type_id == kTypeUnknown) {
  301. MS_LOG(WARNING) << "It is not suggested to use a lonely weight parameter as the output of graph";
  302. output_type_id = AnfAlgo::GetOutputInferDataType(item, index);
  303. }
  304. auto tensor_size = CountNodeDeviceMemorySize(item, index);
  305. auto ptr = mem_manager_->MallocMem(kStaticMem, tensor_size);
  306. auto address = CreateDeviceAddress(ptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  307. AnfAlgo::SetOutputAddr(address, index, item.get());
  308. }
  309. }
  310. }
  311. void KernelRuntime::AssignStaticMemoryOutput(const session::KernelGraph *graph) {
  312. MS_EXCEPTION_IF_NULL(graph);
  313. auto nodes = AnfAlgo::GetAllOutput(graph->output(), {prim::kPrimTupleGetItem});
  314. std::vector<session::KernelWithIndex> non_communication_op;
  315. // Assign Communicate Op Memory firstly.
  316. for (const auto &node : nodes) {
  317. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(node, 0, true);
  318. MS_EXCEPTION_IF_NULL(item_with_index.first);
  319. if (!item_with_index.first->isa<CNode>() || !AnfAlgo::IsRealKernel(item_with_index.first)) {
  320. continue;
  321. }
  322. if (AnfAlgo::IsCommunicationOp(item_with_index.first)) {
  323. AssignCommunicationNodeMem(kStaticMem, item_with_index.first);
  324. } else {
  325. non_communication_op.emplace_back(item_with_index);
  326. }
  327. }
  328. for (const auto &item_with_index : non_communication_op) {
  329. AssignNodeOutputMem(kStaticMem, item_with_index.first, SizeToInt(item_with_index.second));
  330. }
  331. }
  332. void KernelRuntime::UpdateRefNodeOutputMem(const session::KernelGraph *graph) {
  333. MS_EXCEPTION_IF_NULL(graph);
  334. auto &kernels = graph->execution_order();
  335. for (auto &kernel : kernels) {
  336. MS_EXCEPTION_IF_NULL(kernel);
  337. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  338. MS_EXCEPTION_IF_NULL(kernel_mod);
  339. auto output_sizes = kernel_mod->GetOutputSizeList();
  340. if (output_sizes.empty()) {
  341. MS_LOG(INFO) << "This kernel has no output size.";
  342. continue;
  343. }
  344. for (size_t i = 0; i < output_sizes.size(); ++i) {
  345. session::AnfWithOutIndex out_pair(kernel, i);
  346. if (graph->IsInRefOutputMap(out_pair)) {
  347. auto origin_pair = graph->GetRefCorrespondOutput(out_pair);
  348. MS_EXCEPTION_IF_NULL(origin_pair.first);
  349. auto origin_node_output_addr = AnfAlgo::GetMutableOutputAddr(origin_pair.first, origin_pair.second);
  350. MS_EXCEPTION_IF_NULL(origin_node_output_addr);
  351. auto cur_node_output_addr = AnfAlgo::GetMutableOutputAddr(kernel, i);
  352. if (origin_node_output_addr.get() != cur_node_output_addr.get()) {
  353. MS_LOG(INFO) << "REF address is not same, ref node output need address update";
  354. MS_LOG(INFO) << "REF origin op is " << origin_pair.first->DebugString() << ", output index is "
  355. << origin_pair.second << ", cur op is " << kernel->DebugString() << ", out index is " << i;
  356. AnfAlgo::SetOutputAddr(origin_node_output_addr, i, kernel.get());
  357. }
  358. }
  359. }
  360. }
  361. }
  362. void KernelRuntime::AssignCommunicationNodeMem(int flag, const AnfNodePtr &node) {
  363. AssignCommunicationNodeInputMem(node);
  364. AssignCommunicationNodeOutputMem(flag, node);
  365. }
  366. void KernelRuntime::AssignCommunicationNodeOutputMem(int flag, const AnfNodePtr &node) {
  367. MS_EXCEPTION_IF_NULL(node);
  368. MS_EXCEPTION_IF_NULL(mem_manager_);
  369. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  370. MS_EXCEPTION_IF_NULL(kernel_mod);
  371. auto output_sizes = kernel_mod->GetOutputSizeList();
  372. if (output_sizes.empty()) {
  373. MS_LOG(INFO) << "This kernel[" << node->DebugString() << "] has no output size.";
  374. return;
  375. }
  376. auto context_ptr = MsContext::GetInstance();
  377. MS_EXCEPTION_IF_NULL(context_ptr);
  378. size_t total_size = 0;
  379. size_t output_index = 0;
  380. std::vector<size_t> align_size_list;
  381. for (uint64_t mem_size : output_sizes) {
  382. if (AnfAlgo::OutputAddrExist(node, output_index++)) {
  383. MS_LOG(INFO) << "communication op addr exist";
  384. continue;
  385. }
  386. if (context_ptr->enable_hccl()) {
  387. mem_size = mem_manager_->GetCommonAlignSize(mem_size);
  388. }
  389. total_size += mem_size;
  390. align_size_list.emplace_back(mem_size);
  391. }
  392. uint8_t *output_ptr = mem_manager_->MallocOutputMem(node, 0, flag, total_size);
  393. for (size_t j = 0; j < align_size_list.size(); ++j) {
  394. std::string output_format = AnfAlgo::GetOutputFormat(node, j);
  395. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, j);
  396. auto address = CreateDeviceAddress(output_ptr, output_sizes[j], output_format, output_type);
  397. AnfAlgo::SetOutputAddr(address, j, node.get());
  398. output_ptr += align_size_list[j];
  399. }
  400. }
  401. DeviceAddressPtr KernelRuntime::PreAssignCNodeMemory(const AnfNodePtr &anf_node, size_t index) {
  402. MS_EXCEPTION_IF_NULL(anf_node);
  403. auto kernel_mod = AnfAlgo::GetKernelMod(anf_node);
  404. auto output_sizes = kernel_mod->GetOutputSizeList();
  405. if (output_sizes.size() <= index) {
  406. MS_LOG(EXCEPTION) << "Previous node output size < node index";
  407. }
  408. std::string output_format = AnfAlgo::GetOutputFormat(anf_node, index);
  409. auto output_type = AnfAlgo::GetOutputDeviceDataType(anf_node, index);
  410. auto address = CreateDeviceAddress(nullptr, output_sizes[index], output_format, output_type);
  411. AnfAlgo::SetOutputAddr(address, index, anf_node.get());
  412. return address;
  413. }
  414. void KernelRuntime::AssignCommunicationNodeInputMem(const AnfNodePtr &node) {
  415. auto context_ptr = MsContext::GetInstance();
  416. MS_EXCEPTION_IF_NULL(context_ptr);
  417. MS_EXCEPTION_IF_NULL(node);
  418. MS_EXCEPTION_IF_NULL(mem_manager_);
  419. size_t total_size = 0;
  420. std::vector<std::pair<mindspore::device::DeviceAddress *, size_t>> addr_size;
  421. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(node); ++i) {
  422. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(node, i);
  423. auto input_node = input_node_with_index.first;
  424. DeviceAddressPtr address = nullptr;
  425. if (input_node->isa<CNode>()) {
  426. address = PreAssignCNodeMemory(input_node, input_node_with_index.second);
  427. } else {
  428. MS_LOG(EXCEPTION) << "Communication node inputs only support CNode";
  429. }
  430. MS_EXCEPTION_IF_NULL(address);
  431. auto mem_size = mem_manager_->GetCommonAlignSize(address->size());
  432. total_size += mem_size;
  433. addr_size.emplace_back(address.get(), mem_size);
  434. }
  435. uint8_t *input_ptr = mem_manager_->MallocOutputMem(node, 0, kDynamicMem, total_size);
  436. for (const auto &iter : addr_size) {
  437. MS_EXCEPTION_IF_NULL(iter.first);
  438. iter.first->set_ptr(input_ptr);
  439. input_ptr += iter.second;
  440. }
  441. }
  442. void KernelRuntime::AssignNodeOutputMem(int flag, const AnfNodePtr &node, int index) {
  443. MS_EXCEPTION_IF_NULL(node);
  444. MS_EXCEPTION_IF_NULL(mem_manager_);
  445. if (AnfAlgo::IsGetNext(NOT_NULL(node)) && flag == kReuseDynamicMem) {
  446. MS_LOG(INFO) << "GetNext disable mem_reuse";
  447. flag = kDynamicMem;
  448. }
  449. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  450. MS_EXCEPTION_IF_NULL(kernel_mod);
  451. auto output_sizes = kernel_mod->GetOutputSizeList();
  452. if (output_sizes.empty()) {
  453. MS_LOG(INFO) << "This kernel[" << node->DebugString() << "] has no output size.";
  454. return;
  455. }
  456. for (size_t i = 0; i < output_sizes.size(); ++i) {
  457. if ((kGetAllOuts != index) && (SizeToInt(i) != index)) {
  458. continue;
  459. }
  460. if (NodeOutputDeviceAddressExist(node, i)) {
  461. MS_LOG(INFO) << "Already malloc index:" << i;
  462. continue;
  463. }
  464. auto ptr = mem_manager_->MallocOutputMem(node, i, flag, output_sizes[i]);
  465. if (ptr == nullptr) {
  466. // reused ptr, no need alloc, continue;
  467. continue;
  468. }
  469. std::string output_format = AnfAlgo::GetOutputFormat(node, i);
  470. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, i);
  471. AnfAlgo::SetOutputAddr(CreateDeviceAddress(ptr, output_sizes[i], output_format, output_type), i, node.get());
  472. }
  473. }
  474. void KernelRuntime::AssignValueNodeTensor(const ValueNodePtr &value_node, const ValuePtr &node_value,
  475. size_t output_idx) {
  476. MS_EXCEPTION_IF_NULL(value_node);
  477. MS_EXCEPTION_IF_NULL(node_value);
  478. MS_EXCEPTION_IF_NULL(mem_manager_);
  479. auto ms_context = MsContext::GetInstance();
  480. MS_EXCEPTION_IF_NULL(ms_context);
  481. auto tensor = node_value->cast<TensorPtr>();
  482. if (tensor == nullptr) {
  483. MS_LOG(WARNING) << "Tensor is null";
  484. return;
  485. }
  486. size_t tensor_size = tensor->data().nbytes();
  487. auto node_size = CountNodeDeviceMemorySize(value_node, output_idx);
  488. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(value_node, output_idx);
  489. if (output_type_id == kTypeUnknown) {
  490. output_type_id = AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  491. }
  492. auto output_format = AnfAlgo::GetOutputFormat(value_node, output_idx);
  493. DeviceAddressPtr address = nullptr;
  494. if (ms_context->enable_pynative_infer()) {
  495. address = CreateDeviceAddress(nullptr, node_size, output_format, output_type_id);
  496. MS_EXCEPTION_IF_NULL(address);
  497. if (!mem_manager_->MallocMemFromMemPool(address, node_size)) {
  498. MS_LOG(EXCEPTION) << "Malloc value node device memory failed !";
  499. }
  500. } else {
  501. auto ptr = mem_manager_->MallocMem(kStaticMem, node_size);
  502. address = CreateDeviceAddress(ptr, node_size, output_format, output_type_id);
  503. MS_EXCEPTION_IF_NULL(address);
  504. }
  505. AnfAlgo::SetOutputAddr(address, output_idx, value_node.get());
  506. if (!address->SyncHostToDevice(trans::GetRuntimePaddingShape(value_node, 0), tensor_size, tensor->data_type(),
  507. tensor->data_c(false))) {
  508. MS_EXCEPTION(NotExistsError) << "ValueNode SyncHostToDevice fail!" << value_node->DebugString() << "node format is"
  509. << AnfAlgo::GetOutputFormat(value_node, output_idx) << "node dtype is "
  510. << AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  511. }
  512. }
  513. void KernelRuntime::AssignStaticMemoryValueNode(session::KernelGraph *graph) {
  514. MS_EXCEPTION_IF_NULL(graph);
  515. MS_EXCEPTION_IF_NULL(mem_manager_);
  516. auto ms_context = MsContext::GetInstance();
  517. MS_EXCEPTION_IF_NULL(ms_context);
  518. for (auto &value_node : graph->graph_value_nodes()) {
  519. MS_EXCEPTION_IF_NULL(value_node);
  520. if (NodeOutputDeviceAddressExist(value_node, 0)) {
  521. MS_LOG(INFO) << "value_node[" << value_node->DebugString() << "] address already exist";
  522. continue;
  523. }
  524. auto &node_value = value_node->value();
  525. MS_EXCEPTION_IF_NULL(node_value);
  526. if (node_value->isa<Tensor>()) {
  527. AssignValueNodeTensor(value_node, node_value, 0);
  528. } else if (node_value->isa<StringImm>()) {
  529. auto value = GetValue<std::string>(node_value);
  530. size_t tensor_size = value.size();
  531. DeviceAddressPtr address = nullptr;
  532. if (ms_context->enable_pynative_infer()) {
  533. address = CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8);
  534. MS_EXCEPTION_IF_NULL(address);
  535. if (!mem_manager_->MallocMemFromMemPool(address, tensor_size)) {
  536. MS_LOG(EXCEPTION) << "Malloc value node device memory failed !";
  537. }
  538. } else {
  539. auto ptr = mem_manager_->MallocMem(kStaticMem, tensor_size);
  540. address = CreateDeviceAddress(ptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8);
  541. MS_EXCEPTION_IF_NULL(address);
  542. }
  543. AnfAlgo::SetOutputAddr(address, 0, value_node.get());
  544. std::vector<int> shape = {1, SizeToInt(tensor_size)};
  545. if (!address->SyncHostToDevice(shape, tensor_size, kNumberTypeUInt8, value.data())) {
  546. MS_LOG(EXCEPTION) << "kValueNode SyncHostToDevice fail!";
  547. }
  548. }
  549. }
  550. }
  551. void KernelRuntime::AssignDynamicMemory(session::KernelGraph *graph) {
  552. MS_EXCEPTION_IF_NULL(graph);
  553. MS_EXCEPTION_IF_NULL(mem_manager_);
  554. auto context_ptr = MsContext::GetInstance();
  555. MS_EXCEPTION_IF_NULL(context_ptr);
  556. bool is_enable_mem_reuse = context_ptr->enable_mem_reuse();
  557. auto mem_flag = kDynamicMem;
  558. if (is_enable_mem_reuse) {
  559. mem_manager_->MallocReusedDynamicMem(graph);
  560. mem_flag = kReuseDynamicMem;
  561. }
  562. auto &execution_nodes = graph->execution_order();
  563. std::vector<CNodePtr> compute_nodes;
  564. // communication nodes first
  565. for (auto &node : execution_nodes) {
  566. if (AnfAlgo::IsCommunicationOp(node)) {
  567. // skip if the memory is already alocated
  568. AssignCommunicationNodeMem(mem_flag, node);
  569. } else {
  570. compute_nodes.emplace_back(node);
  571. }
  572. }
  573. // then compute nodes
  574. for (auto &node : compute_nodes) {
  575. AssignNodeOutputMem(mem_flag, node, kGetAllOuts);
  576. AssignWorkSpaceMem(mem_flag, node);
  577. }
  578. }
  579. void KernelRuntime::AssignWorkSpaceMem(int flag, const AnfNodePtr &node) {
  580. MS_EXCEPTION_IF_NULL(node);
  581. MS_EXCEPTION_IF_NULL(mem_manager_);
  582. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  583. MS_EXCEPTION_IF_NULL(kernel_mod);
  584. size_t index = 0;
  585. for (auto &size : kernel_mod->GetWorkspaceSizeList()) {
  586. auto ptr = mem_manager_->MallocWorkSpaceMem(node, index, flag, size);
  587. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(ptr, size, "", kTypeUnknown), index, node.get());
  588. index++;
  589. }
  590. }
  591. void KernelRuntime::GenLaunchArgs(const mindspore::kernel::KernelMod &kernel_mod, const mindspore::AnfNodePtr &kernel,
  592. AddressPtrList *kernel_inputs, AddressPtrList *const kernel_workspaces,
  593. AddressPtrList *kernel_outputs) {
  594. MS_EXCEPTION_IF_NULL(kernel);
  595. MS_EXCEPTION_IF_NULL(kernel_inputs);
  596. MS_EXCEPTION_IF_NULL(kernel_workspaces);
  597. MS_EXCEPTION_IF_NULL(kernel_outputs);
  598. auto cnode = kernel->cast<CNodePtr>();
  599. MS_EXCEPTION_IF_NULL(cnode);
  600. if (AnfAlgo::GetCNodeName(cnode) == kAtomicAddrCleanOpName) {
  601. return GenAddrCleanLaunchArgs(cnode, kernel_inputs);
  602. }
  603. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) {
  604. auto real_input = AnfAlgo::GetRealInputIndex(kernel, i);
  605. auto device_address = AnfAlgo::GetPrevNodeOutputAddr(kernel, real_input);
  606. MS_EXCEPTION_IF_NULL(device_address);
  607. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  608. MS_EXCEPTION_IF_NULL(input);
  609. input->addr = device_address->ptr_;
  610. MS_EXCEPTION_IF_NULL(input->addr);
  611. input->size = device_address->size_;
  612. kernel_inputs->emplace_back(input);
  613. }
  614. for (size_t i = 0; i < kernel_mod.GetOutputSizeList().size(); ++i) {
  615. auto device_address = AnfAlgo::GetOutputAddr(kernel, i);
  616. kernel::AddressPtr output = std::make_shared<kernel::Address>();
  617. MS_EXCEPTION_IF_NULL(output);
  618. output->addr = device_address->ptr_;
  619. MS_EXCEPTION_IF_NULL(output->addr);
  620. output->size = device_address->size_;
  621. kernel_outputs->emplace_back(output);
  622. }
  623. for (size_t i = 0; i < kernel_mod.GetWorkspaceSizeList().size(); ++i) {
  624. auto device_address = AnfAlgo::GetWorkspaceAddr(kernel, i);
  625. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  626. MS_EXCEPTION_IF_NULL(workspace);
  627. workspace->addr = device_address->ptr_;
  628. MS_EXCEPTION_IF_NULL(workspace->addr);
  629. workspace->size = device_address->size_;
  630. kernel_workspaces->emplace_back(workspace);
  631. }
  632. }
  633. void KernelRuntime::GenAddrCleanLaunchArgs(const CNodePtr &cnode, AddressPtrList *kernel_inputs) {
  634. if (cnode->inputs().size() != 2) {
  635. MS_LOG(EXCEPTION) << "Atomic Addr clean Node Input nodes not equal 2.";
  636. }
  637. MS_EXCEPTION_IF_NULL(cnode->inputs()[1]);
  638. auto pre_node = (cnode->inputs()[1])->cast<CNodePtr>();
  639. // set clean output address
  640. if (AnfAlgo::HasNodeAttr(kAttrAutomicOutputIndexs, pre_node)) {
  641. auto clean_output_indexs = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAutomicOutputIndexs);
  642. for (auto index : clean_output_indexs) {
  643. auto device_address = AnfAlgo::GetOutputAddr(pre_node, index);
  644. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  645. MS_EXCEPTION_IF_NULL(input);
  646. input->addr = device_address->ptr_;
  647. MS_EXCEPTION_IF_NULL(input->addr);
  648. input->size = device_address->size_;
  649. kernel_inputs->emplace_back(input);
  650. }
  651. MS_LOG(INFO) << "AtomicAddClean clean output size:" << clean_output_indexs.size();
  652. }
  653. // set clean workspace address
  654. if (AnfAlgo::HasNodeAttr(kAttrAutomicWorkspaceSize, pre_node)) {
  655. auto clean_workspaces = AnfAlgo::GetNodeAttr<int>(pre_node, kAttrAutomicWorkspaceSize);
  656. if (clean_workspaces != 0) {
  657. auto device_address = AnfAlgo::GetWorkspaceAddr(pre_node, 0);
  658. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  659. MS_EXCEPTION_IF_NULL(workspace);
  660. workspace->addr = device_address->ptr_;
  661. MS_EXCEPTION_IF_NULL(workspace->addr);
  662. workspace->size = device_address->size_;
  663. kernel_inputs->emplace_back(workspace);
  664. }
  665. MS_LOG(INFO) << "AtomicAddClean clean workspace size" << clean_workspaces;
  666. }
  667. }
  668. bool KernelRuntime::LaunchKernelMod(const session::KernelGraph &graph) {
  669. auto &kernels = graph.execution_order();
  670. for (const auto &kernel : kernels) {
  671. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  672. MS_EXCEPTION_IF_NULL(kernel_mod);
  673. AddressPtrList kernel_inputs;
  674. AddressPtrList kernel_workspaces;
  675. AddressPtrList kernel_outputs;
  676. GenLaunchArgs(*kernel_mod, kernel, &kernel_inputs, &kernel_workspaces, &kernel_outputs);
  677. auto ret = kernel_mod->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_);
  678. if (!ret) {
  679. MS_LOG(ERROR) << "Launch kernel failed.";
  680. return false;
  681. }
  682. }
  683. return true;
  684. }
  685. bool KernelRuntime::LaunchKernel(const session::KernelGraph *graph) {
  686. MS_EXCEPTION_IF_NULL(graph);
  687. if (!LaunchKernelMod(*graph)) {
  688. MS_LOG(ERROR) << "LaunchKernelMod failed!";
  689. return false;
  690. }
  691. return true;
  692. }
  693. void KernelRuntime::ClearGraphRuntimeResource(uint32_t graph_id) {
  694. MS_LOG(INFO) << "Clear graph:" << graph_id << " runtime resource";
  695. }
  696. #ifdef ENABLE_DUMP_E2E
  697. bool KernelRuntime::SetDumpConf() {
  698. dump_conf_ptr_ = std::make_shared<Dump>();
  699. MS_EXCEPTION_IF_NULL(dump_conf_ptr_);
  700. bool ret = dump_conf_ptr_->SetDumpConfFromJsonFile();
  701. return ret;
  702. }
  703. DumpConfPtr KernelRuntime::GetDumpConf() { return dump_conf_ptr_; }
  704. #endif
  705. } // namespace device
  706. } // namespace mindspore