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