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