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

5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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 <functional>
  18. #include <numeric>
  19. #include <utility>
  20. #include <vector>
  21. #include "backend/optimizer/common/helper.h"
  22. #include "backend/session/anf_runtime_algorithm.h"
  23. #include "backend/session/kernel_graph.h"
  24. #include "common/trans.h"
  25. #include "debug/data_dump/dump_json_parser.h"
  26. #include "frontend/operator/ops.h"
  27. #include "ir/value.h"
  28. #include "utils/ms_context.h"
  29. #include "utils/ms_utils.h"
  30. #include "utils/shape_utils.h"
  31. #include "utils/utils.h"
  32. #include "frontend/parallel/context.h"
  33. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  34. #include "ps/ps_cache/ps_cache_manager.h"
  35. #endif
  36. using mindspore::kernel::Address;
  37. using mindspore::kernel::AddressPtr;
  38. namespace mindspore {
  39. namespace device {
  40. KernelRuntime::~KernelRuntime() {}
  41. bool KernelRuntime::Load(session::KernelGraph *graph, bool is_task_sink) { return true; }
  42. bool KernelRuntime::LoadData(session::KernelGraph *graph) { return false; }
  43. bool KernelRuntime::NodeOutputDeviceAddressExist(const AnfNodePtr &kernel, size_t index) {
  44. MS_EXCEPTION_IF_NULL(kernel);
  45. if (AnfAlgo::OutputAddrExist(kernel, index)) {
  46. const auto &address = AnfAlgo::GetOutputAddr(kernel, index);
  47. MS_EXCEPTION_IF_NULL(address);
  48. return address->DeviceType() == GetTargetDeviceAddressType();
  49. }
  50. return false;
  51. }
  52. size_t KernelRuntime::CountNodeDeviceMemorySize(const mindspore::AnfNodePtr &node, size_t output_index) {
  53. MS_EXCEPTION_IF_NULL(node);
  54. if (output_index >= AnfAlgo::GetOutputTensorNum(node)) {
  55. MS_EXCEPTION(ArgumentError) << "output index [" << output_index << "] large than the output size ["
  56. << AnfAlgo::GetOutputTensorNum(node) << "] of node!";
  57. }
  58. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(node, output_index);
  59. if (output_type_id == kTypeUnknown) {
  60. output_type_id = AnfAlgo::GetOutputInferDataType(node, output_index);
  61. }
  62. size_t type_size = GetTypeByte(TypeIdToType(output_type_id));
  63. std::vector<size_t> shape = AnfAlgo::GetOutputDeviceShape(node, output_index);
  64. auto format = AnfAlgo::GetOutputFormat(node, output_index);
  65. if (shape.empty() && format != kOpFormat_DEFAULT) {
  66. shape = trans::PaddingShape(shape, format, AnfAlgo::GetOutputReshapeType(node, output_index));
  67. shape = trans::TransShapeToDevice(shape, format);
  68. }
  69. // scalar's output shape is a empty vector
  70. size_t tensor_size = std::accumulate(shape.begin(), shape.end(), type_size, std::multiplies<size_t>());
  71. return tensor_size;
  72. }
  73. void KernelRuntime::AssignMemory(session::KernelGraph *graph) {
  74. auto context_ptr = MsContext::GetInstance();
  75. MS_EXCEPTION_IF_NULL(context_ptr);
  76. MS_EXCEPTION_IF_NULL(mem_manager_);
  77. mem_manager_->ResetDynamicMemory();
  78. AssignStaticMemory(graph);
  79. AssignDynamicMemory(graph);
  80. UpdateRefNodeOutputMem(graph);
  81. }
  82. void KernelRuntime::RunOpAssignMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  83. session::KernelGraph *graph) {
  84. MS_EXCEPTION_IF_NULL(graph);
  85. MS_EXCEPTION_IF_NULL(mem_manager_);
  86. mem_manager_->ResetDynamicMemory();
  87. RunOpAssignInputMemory(input_tensors, graph);
  88. AssignStaticMemoryValueNode(graph);
  89. for (const auto &cnode : graph->execution_order()) {
  90. RunOpAssignOutputMemory(cnode);
  91. RunOpAssignWorkSpaceMemory(cnode);
  92. }
  93. UpdateRefNodeOutputMem(graph);
  94. }
  95. void KernelRuntime::RunOpClearMemory(const session::KernelGraph *graph) {
  96. MS_EXCEPTION_IF_NULL(graph);
  97. // clear input parameter memory resource
  98. for (const auto &input_node : graph->inputs()) {
  99. MS_EXCEPTION_IF_NULL(input_node);
  100. AnfAlgo::SetOutputAddr(nullptr, 0, input_node.get());
  101. }
  102. // clear input value node memory resource
  103. for (const auto &value_node : graph->graph_value_nodes()) {
  104. MS_EXCEPTION_IF_NULL(value_node);
  105. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  106. }
  107. for (const auto &cnode : graph->execution_order()) {
  108. MS_EXCEPTION_IF_NULL(cnode);
  109. // clear output memory resource
  110. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  111. for (size_t index = 0; index < output_num; ++index) {
  112. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  113. }
  114. // clear workspace memory resource
  115. auto kernel_mod = AnfAlgo::GetKernelMod(cnode);
  116. MS_EXCEPTION_IF_NULL(kernel_mod);
  117. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  118. for (size_t index = 0; index < workspace_lists.size(); ++index) {
  119. AnfAlgo::SetWorkspaceAddr(nullptr, index, cnode.get());
  120. }
  121. }
  122. }
  123. bool KernelRuntime::DumpDataEnabled() {
  124. auto &dump_json_parser = DumpJsonParser::GetInstance();
  125. return dump_json_parser.e2e_dump_enabled();
  126. }
  127. bool KernelRuntime::DumpDataEnabledIteration() {
  128. auto &dump_json_parser = DumpJsonParser::GetInstance();
  129. if (!dump_json_parser.e2e_dump_enabled()) {
  130. return false;
  131. }
  132. auto cur_iter = dump_json_parser.cur_dump_iter() + 1;
  133. if (dump_json_parser.iteration() != 0) {
  134. return cur_iter == dump_json_parser.iteration();
  135. }
  136. return true;
  137. }
  138. void KernelRuntime::AssignStaticMemory(session::KernelGraph *graph) {
  139. AssignStaticMemoryInput(graph);
  140. AssignStaticMemoryValueNode(graph);
  141. AssignStaticMemoryOutput(graph);
  142. }
  143. void KernelRuntime::RunOpAssignInputMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  144. const session::KernelGraph *graph) {
  145. MS_EXCEPTION_IF_NULL(graph);
  146. MS_EXCEPTION_IF_NULL(mem_manager_);
  147. if (input_tensors.size() != graph->inputs().size()) {
  148. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors.size()
  149. << " should be equal to graph input parameter size " << graph->inputs().size();
  150. }
  151. for (size_t input_index = 0; input_index < graph->inputs().size(); ++input_index) {
  152. auto item = graph->inputs()[input_index];
  153. MS_EXCEPTION_IF_NULL(item);
  154. if (!item->isa<Parameter>()) {
  155. continue;
  156. }
  157. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  158. for (size_t index = 0; index < output_size; index++) {
  159. MS_EXCEPTION_IF_NULL(input_tensors[input_index]);
  160. auto output_address =
  161. std::dynamic_pointer_cast<device::DeviceAddress>(input_tensors[input_index]->device_address());
  162. if (output_address != nullptr && output_address->DeviceType() == GetTargetDeviceAddressType()) {
  163. AnfAlgo::SetOutputAddr(output_address, index, item.get());
  164. continue;
  165. }
  166. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  167. if (output_type_id == kTypeUnknown) {
  168. output_type_id = AnfAlgo::GetOutputInferDataType(item, index);
  169. }
  170. auto tensor_size = CountNodeDeviceMemorySize(item, index);
  171. auto device_address =
  172. CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  173. MS_EXCEPTION_IF_NULL(device_address);
  174. MS_EXCEPTION_IF_NULL(mem_manager_);
  175. auto ret = mem_manager_->MallocMemFromMemPool(device_address, tensor_size);
  176. if (!ret) {
  177. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  178. }
  179. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  180. }
  181. }
  182. }
  183. void KernelRuntime::RunOpAssignOutputMemory(const AnfNodePtr &kernel) {
  184. MS_EXCEPTION_IF_NULL(kernel);
  185. MS_EXCEPTION_IF_NULL(mem_manager_);
  186. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  187. MS_EXCEPTION_IF_NULL(kernel_mod);
  188. auto output_sizes = kernel_mod->GetOutputSizeList();
  189. if (output_sizes.empty()) {
  190. return;
  191. }
  192. for (size_t i = 0; i < output_sizes.size(); ++i) {
  193. if (AnfAlgo::OutputAddrExist(kernel, i)) {
  194. continue;
  195. }
  196. if (AnfAlgo::GetCNodeName(kernel) == kApplyMomentumOpName) {
  197. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i);
  198. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  199. continue;
  200. }
  201. std::string output_format = AnfAlgo::GetOutputFormat(kernel, i);
  202. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  203. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  204. device_address->set_host_shape(trans::GetRuntimePaddingShape(kernel, i));
  205. MS_EXCEPTION_IF_NULL(device_address);
  206. auto ret = mem_manager_->MallocMemFromMemPool(device_address, output_sizes[i]);
  207. if (!ret) {
  208. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << output_sizes[i];
  209. }
  210. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  211. }
  212. }
  213. void KernelRuntime::RunOpAssignWorkSpaceMemory(const AnfNodePtr &kernel) {
  214. MS_EXCEPTION_IF_NULL(kernel);
  215. MS_EXCEPTION_IF_NULL(mem_manager_);
  216. if (kernel->isa<CNode>()) {
  217. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  218. MS_EXCEPTION_IF_NULL(kernel_mod);
  219. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  220. for (size_t i = 0; i < workspace_lists.size(); ++i) {
  221. auto device_address = CreateDeviceAddress(nullptr, workspace_lists[i], "", kTypeUnknown);
  222. MS_EXCEPTION_IF_NULL(device_address);
  223. auto ret = mem_manager_->MallocMemFromMemPool(device_address, workspace_lists[i]);
  224. if (!ret) {
  225. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << workspace_lists[i];
  226. }
  227. AnfAlgo::SetWorkspaceAddr(device_address, i, kernel.get());
  228. }
  229. }
  230. }
  231. void KernelRuntime::RunOpAssignOutputNodeMemory(const ValuePtr &pre_output_value, session::KernelGraph *graph) {
  232. if (pre_output_value == nullptr) {
  233. return;
  234. }
  235. std::vector<tensor::TensorPtr> pre_output_tensors;
  236. TensorValueToTensor(pre_output_value, &pre_output_tensors);
  237. MS_EXCEPTION_IF_NULL(graph);
  238. auto output_nodes = graph->outputs();
  239. if (pre_output_tensors.size() != output_nodes.size()) {
  240. MS_LOG(EXCEPTION) << "The size of pre output tensors [" << pre_output_tensors.size()
  241. << "] is not equal to the size of output nodes of graph [" << output_nodes.size() << "]";
  242. }
  243. // share output address with pre output tensors
  244. for (size_t i = 0; i < output_nodes.size(); ++i) {
  245. auto output_node_with_index = AnfAlgo::VisitKernel(output_nodes[i], 0);
  246. if (!output_node_with_index.first->isa<CNode>()) {
  247. if (output_node_with_index.first->isa<Parameter>()) {
  248. auto param = output_node_with_index.first->cast<ParameterPtr>();
  249. if (!param->has_default()) {
  250. MS_LOG(EXCEPTION) << "The output parameter should be real parameter!";
  251. }
  252. }
  253. continue;
  254. }
  255. auto real_output_cnode = output_node_with_index.first->cast<CNodePtr>();
  256. MS_EXCEPTION_IF_NULL(real_output_cnode);
  257. MS_EXCEPTION_IF_NULL(pre_output_tensors[i]);
  258. if (pre_output_tensors[i]->device_address() == nullptr) {
  259. MS_LOG(INFO) << "The address of pre output tensor [" << i << "] is a nullptr!";
  260. continue;
  261. }
  262. if (opt::IsNopNode(real_output_cnode)) {
  263. if (real_output_cnode->inputs().size() < 2) {
  264. MS_LOG(EXCEPTION) << "The input size of output node: " << real_output_cnode->DebugString()
  265. << " should large than one!";
  266. }
  267. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(pre_output_tensors[i]->device_address()),
  268. output_node_with_index.second, real_output_cnode->input(1).get());
  269. } else {
  270. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(pre_output_tensors[i]->device_address()),
  271. output_node_with_index.second, output_node_with_index.first.get());
  272. }
  273. }
  274. }
  275. void KernelRuntime::AssignStaticMemoryInput(const session::KernelGraph *graph) {
  276. MS_EXCEPTION_IF_NULL(graph);
  277. MS_EXCEPTION_IF_NULL(mem_manager_);
  278. MS_LOG(INFO) << "AssignStaticMemoryInput start";
  279. auto graph_inputs = graph->inputs();
  280. auto graph_valid_input = graph->valid_inputs();
  281. graph_inputs.insert(graph_inputs.end(), graph->child_graph_result().begin(), graph->child_graph_result().end());
  282. std::vector<AnfNodePtr> need_alloc_nodes;
  283. for (size_t i = 0; i < graph_inputs.size(); ++i) {
  284. auto item = graph_inputs[i];
  285. MS_EXCEPTION_IF_NULL(item);
  286. if (i < graph_valid_input.size() && !graph_valid_input[i]) {
  287. continue;
  288. }
  289. if (AnfAlgo::CheckPrimitiveType(item, prim::kPrimMakeTuple)) {
  290. auto outs = AnfAlgo::GetAllOutput(item);
  291. for (auto &out : outs) {
  292. MS_EXCEPTION_IF_NULL(out);
  293. if (!out->isa<Parameter>()) {
  294. continue;
  295. }
  296. if (NodeOutputDeviceAddressExist(out, 0)) {
  297. continue;
  298. }
  299. need_alloc_nodes.push_back(out);
  300. }
  301. }
  302. if (!item->isa<Parameter>()) {
  303. continue;
  304. }
  305. if (NodeOutputDeviceAddressExist(item, 0)) {
  306. continue;
  307. }
  308. need_alloc_nodes.push_back(item);
  309. }
  310. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  311. bool ps_cache_check = false;
  312. #endif
  313. for (auto &item : need_alloc_nodes) {
  314. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  315. for (size_t index = 0; index < output_size; index++) {
  316. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  317. // if graph output is a weight and doesn't link to any cnode, it's data type will be unknown
  318. if (output_type_id == kTypeUnknown) {
  319. MS_LOG(WARNING) << "It is not suggested to use a lonely weight parameter as the output of graph";
  320. continue;
  321. }
  322. DeviceAddressPtr device_address = nullptr;
  323. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  324. const std::string &param_name = item->fullname_with_scope();
  325. if (ps::ps_cache_instance.IsHashTable(param_name)) {
  326. MS_LOG(INFO) << "Parameter(" << param_name << ")"
  327. << " enables the embeddingLookup cache in parameter server training mode.";
  328. // PS embeddingLookup cache check.
  329. if (!ps_cache_check) {
  330. CheckIfSupportPSEmbeddingCache(graph);
  331. ps_cache_check = true;
  332. }
  333. const auto &address = ps::ps_cache_instance.QueryHashTableAddr(param_name);
  334. MS_EXCEPTION_IF_NULL(address.addr);
  335. device_address =
  336. CreateDeviceAddress(address.addr, address.size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  337. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  338. continue;
  339. }
  340. #endif
  341. auto tensor_size = CountNodeDeviceMemorySize(item, index);
  342. device_address = CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  343. MS_LOG(DEBUG) << "Malloc static memory for " << item->fullname_with_scope();
  344. if (mem_manager_->MallocMem(kStaticMem, tensor_size, device_address, graph->graph_id()) == nullptr) {
  345. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  346. }
  347. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  348. }
  349. }
  350. MS_LOG(INFO) << "AssignStaticMemoryInput end";
  351. }
  352. void KernelRuntime::AssignStaticMemoryOutput(const session::KernelGraph *graph) {
  353. MS_EXCEPTION_IF_NULL(graph);
  354. MS_LOG(INFO) << "AssignStaticMemoryOutput start";
  355. auto nodes = AnfAlgo::GetAllOutput(graph->output(), {prim::kPrimTupleGetItem});
  356. std::vector<session::KernelWithIndex> non_communication_op;
  357. // Assign Communicate Op Memory firstly.
  358. for (const auto &node : nodes) {
  359. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(node, 0, true);
  360. MS_EXCEPTION_IF_NULL(item_with_index.first);
  361. if (!item_with_index.first->isa<CNode>() || !AnfAlgo::IsRealKernel(item_with_index.first)) {
  362. continue;
  363. }
  364. if (AnfAlgo::IsCommunicationOp(item_with_index.first)) {
  365. AssignCommunicationNodeMem(kStaticMem, item_with_index.first);
  366. } else {
  367. non_communication_op.emplace_back(item_with_index);
  368. }
  369. }
  370. for (const auto &item_with_index : non_communication_op) {
  371. MS_LOG(DEBUG) << "AssignNodeOutputMem for " << item_with_index.first->fullname_with_scope();
  372. AssignNodeOutputMem(kStaticMem, item_with_index.first, SizeToInt(item_with_index.second));
  373. }
  374. MS_LOG(INFO) << "AssignStaticMemoryOutput end";
  375. }
  376. void KernelRuntime::UpdateRefNodeOutputMem(const session::KernelGraph *graph) {
  377. MS_EXCEPTION_IF_NULL(graph);
  378. auto &kernels = graph->execution_order();
  379. for (auto &kernel : kernels) {
  380. MS_EXCEPTION_IF_NULL(kernel);
  381. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  382. MS_EXCEPTION_IF_NULL(kernel_mod);
  383. auto output_sizes = kernel_mod->GetOutputSizeList();
  384. if (output_sizes.empty()) {
  385. MS_LOG(INFO) << "This kernel has no output size.";
  386. continue;
  387. }
  388. for (size_t i = 0; i < output_sizes.size(); ++i) {
  389. session::AnfWithOutIndex out_pair(kernel, i);
  390. if (graph->IsInRefOutputMap(out_pair)) {
  391. auto origin_pair = graph->GetRefCorrespondOutput(out_pair);
  392. MS_EXCEPTION_IF_NULL(origin_pair.first);
  393. auto origin_node_output_addr = AnfAlgo::GetMutableOutputAddr(origin_pair.first, origin_pair.second);
  394. MS_EXCEPTION_IF_NULL(origin_node_output_addr);
  395. auto cur_node_output_addr = AnfAlgo::GetMutableOutputAddr(kernel, i);
  396. if (origin_node_output_addr.get() != cur_node_output_addr.get()) {
  397. MS_LOG(DEBUG) << "REF address is not same, ref node output need address update";
  398. MS_LOG(DEBUG) << "REF origin op is " << origin_pair.first->DebugString() << ", output index is "
  399. << origin_pair.second << ", cur op is " << kernel->DebugString() << ", out index is " << i;
  400. AnfAlgo::SetOutputAddr(origin_node_output_addr, i, kernel.get());
  401. }
  402. }
  403. }
  404. }
  405. }
  406. void KernelRuntime::AssignCommunicationNodeMem(MemType type, const AnfNodePtr &node) {
  407. AssignCommunicationNodeInputMem(type, node);
  408. AssignCommunicationNodeOutputMem(type, node);
  409. }
  410. void KernelRuntime::AssignCommunicationNodeOutputMem(MemType type, const AnfNodePtr &node) {
  411. MS_EXCEPTION_IF_NULL(node);
  412. MS_EXCEPTION_IF_NULL(mem_manager_);
  413. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  414. MS_EXCEPTION_IF_NULL(kernel_mod);
  415. auto output_sizes = kernel_mod->GetOutputSizeList();
  416. if (output_sizes.empty()) {
  417. MS_LOG(INFO) << "This kernel[" << node->DebugString() << "] has no output size.";
  418. return;
  419. }
  420. auto context_ptr = MsContext::GetInstance();
  421. MS_EXCEPTION_IF_NULL(context_ptr);
  422. size_t total_size = 0;
  423. size_t output_index = 0;
  424. std::vector<size_t> align_size_list;
  425. for (uint64_t mem_size : output_sizes) {
  426. if (AnfAlgo::OutputAddrExist(node, output_index++)) {
  427. MS_LOG(INFO) << "communication op addr exist";
  428. continue;
  429. }
  430. if (context_ptr->get_param<bool>(MS_CTX_ENABLE_HCCL)) {
  431. mem_size = mem_manager_->GetCommonAlignSize(mem_size);
  432. }
  433. total_size += mem_size;
  434. align_size_list.emplace_back(mem_size);
  435. }
  436. if (type == kReuseDynamicMem) {
  437. // reuse communication op's all outputs' memory
  438. type = kReuseDynamicCommMem;
  439. }
  440. if (type == kReuseDynamicCommMem || type == kSomasReuseDynamicMem) {
  441. bool not_reuse = KernelMemNotReuse(node);
  442. if (not_reuse) {
  443. type = kDynamicMem;
  444. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  445. }
  446. }
  447. uint8_t *output_ptr = nullptr;
  448. for (size_t j = 0; j < align_size_list.size(); ++j) {
  449. std::string output_format = AnfAlgo::GetOutputFormat(node, j);
  450. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, j);
  451. auto address = CreateDeviceAddress(nullptr, output_sizes[j], output_format, output_type);
  452. MS_EXCEPTION_IF_NULL(address);
  453. if (output_ptr == nullptr) {
  454. output_ptr = mem_manager_->MallocOutputMem(node, 0, type, total_size, address, true);
  455. MS_EXCEPTION_IF_NULL(output_ptr);
  456. } else {
  457. address->set_ptr(output_ptr);
  458. }
  459. AnfAlgo::SetOutputAddr(address, j, node.get());
  460. output_ptr += align_size_list[j];
  461. }
  462. }
  463. bool KernelRuntime::KernelMemNotReuse(const AnfNodePtr &node) { return false; }
  464. DeviceAddressPtr KernelRuntime::PreAssignCNodeMemory(const AnfNodePtr &anf_node, size_t index) {
  465. MS_EXCEPTION_IF_NULL(anf_node);
  466. if (!anf_node->isa<CNode>()) {
  467. MS_LOG(EXCEPTION) << "anf_node should be a cnode";
  468. }
  469. auto cnode = anf_node->cast<CNodePtr>();
  470. if (opt::IsNopNode(cnode)) {
  471. const size_t kNopNodeInputSize = 2;
  472. if (cnode->size() != kNopNodeInputSize) {
  473. MS_LOG(EXCEPTION) << cnode->fullname_with_scope() << " has invalid input size: " << cnode->size();
  474. }
  475. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(anf_node, index);
  476. return PreAssignCNodeMemory(input_node_with_index.first, input_node_with_index.second);
  477. }
  478. auto kernel_mod = AnfAlgo::GetKernelMod(anf_node);
  479. MS_EXCEPTION_IF_NULL(kernel_mod);
  480. auto output_sizes = kernel_mod->GetOutputSizeList();
  481. if (output_sizes.size() <= index) {
  482. MS_LOG(EXCEPTION) << "Previous node output size < node index";
  483. }
  484. std::string output_format = AnfAlgo::GetOutputFormat(anf_node, index);
  485. auto output_type = AnfAlgo::GetOutputDeviceDataType(anf_node, index);
  486. auto address = CreateDeviceAddress(nullptr, output_sizes[index], output_format, output_type);
  487. AnfAlgo::SetOutputAddr(address, index, anf_node.get());
  488. return address;
  489. }
  490. void KernelRuntime::AssignCommunicationNodeInputMem(MemType type, const AnfNodePtr &node) {
  491. auto context_ptr = MsContext::GetInstance();
  492. MS_EXCEPTION_IF_NULL(context_ptr);
  493. MS_EXCEPTION_IF_NULL(node);
  494. MS_EXCEPTION_IF_NULL(mem_manager_);
  495. size_t total_size = 0;
  496. std::vector<std::pair<DeviceAddressPtr, size_t>> addr_size;
  497. size_t input_num = AnfAlgo::GetInputTensorNum(node);
  498. for (size_t i = 0; i < input_num; ++i) {
  499. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(node, i);
  500. auto input_node = input_node_with_index.first;
  501. DeviceAddressPtr address = nullptr;
  502. if (input_node->isa<CNode>()) {
  503. address = PreAssignCNodeMemory(input_node, input_node_with_index.second);
  504. } else {
  505. MS_LOG(EXCEPTION) << "Communication node inputs only support CNode";
  506. }
  507. MS_EXCEPTION_IF_NULL(address);
  508. auto mem_size = mem_manager_->GetCommonAlignSize(address->size());
  509. total_size += mem_size;
  510. addr_size.emplace_back(address, mem_size);
  511. }
  512. if (addr_size.empty()) {
  513. return;
  514. }
  515. if (type == kReuseDynamicMem || type == kSomasReuseDynamicMem) {
  516. bool not_reuse = KernelMemNotReuse(node);
  517. if (not_reuse) {
  518. type = kDynamicMem;
  519. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s input.";
  520. }
  521. }
  522. auto cnode = node->cast<CNodePtr>();
  523. MS_EXCEPTION_IF_NULL(cnode);
  524. if (cnode->inputs().size() < 2) {
  525. // communication node's input should contain itself and at least on input
  526. MS_LOG(ERROR) << "No inputs for " << cnode->fullname_with_scope();
  527. return;
  528. }
  529. auto first_input_node = cnode->input(1);
  530. auto prenode_index = AnfAlgo::VisitKernelWithReturnType(first_input_node, 0, true);
  531. uint8_t *input_ptr = mem_manager_->MallocOutputMem(prenode_index.first, prenode_index.second, type, total_size,
  532. addr_size[0].first, true);
  533. for (const auto &iter : addr_size) {
  534. MS_EXCEPTION_IF_NULL(iter.first);
  535. iter.first->set_ptr(input_ptr);
  536. input_ptr += iter.second;
  537. }
  538. }
  539. void KernelRuntime::AssignNodeOutputMem(MemType type, const AnfNodePtr &node, int index) {
  540. MS_EXCEPTION_IF_NULL(node);
  541. MS_EXCEPTION_IF_NULL(mem_manager_);
  542. if (AnfAlgo::IsGetNext(NOT_NULL(node)) && type == kReuseDynamicMem) {
  543. MS_LOG(INFO) << "GetNext disable mem_reuse";
  544. type = kDynamicMem;
  545. }
  546. if (node->isa<CNode>()) {
  547. bool independent = AnfAlgo::IsIndependentNode(node->cast<CNodePtr>());
  548. if (independent && (type == kReuseDynamicMem)) {
  549. MS_LOG(INFO) << "Independent node " << node->fullname_with_scope() << " disable memory reuse";
  550. type = kDynamicMem;
  551. }
  552. }
  553. if (type == kReuseDynamicMem || type == kSomasReuseDynamicMem) {
  554. bool not_reuse = KernelMemNotReuse(node);
  555. if (not_reuse) {
  556. type = kDynamicMem;
  557. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  558. }
  559. }
  560. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  561. MS_EXCEPTION_IF_NULL(kernel_mod);
  562. auto output_sizes = kernel_mod->GetOutputSizeList();
  563. if (output_sizes.empty()) {
  564. return;
  565. }
  566. for (size_t i = 0; i < output_sizes.size(); ++i) {
  567. if ((kGetAllOuts != index) && (SizeToInt(i) != index)) {
  568. continue;
  569. }
  570. if (NodeOutputDeviceAddressExist(node, i)) {
  571. MS_LOG(INFO) << "Already malloc index:" << i;
  572. continue;
  573. }
  574. MS_LOG(DEBUG) << "Assign Node:" << node->fullname_with_scope() << " output memory size:" << output_sizes[i];
  575. std::string output_format = AnfAlgo::GetOutputFormat(node, i);
  576. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, i);
  577. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  578. MS_EXCEPTION_IF_NULL(device_address);
  579. uint8_t *ptr = mem_manager_->MallocOutputMem(node, i, type, output_sizes[i], device_address, false);
  580. MS_EXCEPTION_IF_NULL(ptr);
  581. device_address->set_host_shape(trans::GetRuntimePaddingShape(node, i));
  582. AnfAlgo::SetOutputAddr(device_address, i, node.get());
  583. }
  584. }
  585. void KernelRuntime::AssignValueNodeTensor(const ValueNodePtr &value_node, const ValuePtr &node_value,
  586. size_t output_idx) {
  587. MS_EXCEPTION_IF_NULL(value_node);
  588. MS_EXCEPTION_IF_NULL(node_value);
  589. MS_EXCEPTION_IF_NULL(mem_manager_);
  590. auto ms_context = MsContext::GetInstance();
  591. MS_EXCEPTION_IF_NULL(ms_context);
  592. std::vector<tensor::TensorPtr> tensors;
  593. TensorValueToTensor(node_value, &tensors);
  594. // Graph id should be passed to record static memory if profiling is enabled.
  595. auto kernel_info = static_cast<device::KernelInfo *>(value_node->kernel_info());
  596. MS_EXCEPTION_IF_NULL(kernel_info);
  597. uint32_t graph_id = kernel_info->graph_id();
  598. for (const auto &tensor : tensors) {
  599. if (tensor == nullptr) {
  600. MS_LOG(WARNING) << "Tensor is null";
  601. return;
  602. }
  603. auto output_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  604. if (output_address != nullptr && output_address->DeviceType() == GetTargetDeviceAddressType()) {
  605. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), output_idx++,
  606. value_node.get());
  607. continue;
  608. }
  609. size_t tensor_size = tensor->data().nbytes();
  610. auto node_size = CountNodeDeviceMemorySize(value_node, output_idx);
  611. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(value_node, output_idx);
  612. if (output_type_id == kTypeUnknown) {
  613. output_type_id = AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  614. }
  615. auto output_format = AnfAlgo::GetOutputFormat(value_node, output_idx);
  616. DeviceAddressPtr address = CreateDeviceAddress(nullptr, node_size, output_format, output_type_id);
  617. MS_EXCEPTION_IF_NULL(address);
  618. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  619. !mem_manager_->MallocMemFromMemPool(address, node_size)) {
  620. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << node_size;
  621. } else if (mem_manager_->MallocMem(kStaticMem, node_size, address, graph_id) == nullptr) {
  622. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << node_size;
  623. }
  624. AnfAlgo::SetOutputAddr(address, output_idx, value_node.get());
  625. if (!address->SyncHostToDevice(trans::GetRuntimePaddingShape(value_node, 0), tensor_size, tensor->data_type(),
  626. tensor->data_c())) {
  627. MS_EXCEPTION(NotExistsError) << "ValueNode SyncHostToDevice fail!" << value_node->DebugString()
  628. << "node format is" << AnfAlgo::GetOutputFormat(value_node, output_idx)
  629. << "node dtype is " << AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  630. }
  631. }
  632. return;
  633. }
  634. void KernelRuntime::AssignStaticMemoryValueNode(session::KernelGraph *graph) {
  635. MS_EXCEPTION_IF_NULL(graph);
  636. MS_EXCEPTION_IF_NULL(mem_manager_);
  637. MS_LOG(INFO) << "AssignStaticMemoryValueNode start";
  638. auto ms_context = MsContext::GetInstance();
  639. MS_EXCEPTION_IF_NULL(ms_context);
  640. for (auto &value_node : graph->graph_value_nodes()) {
  641. MS_EXCEPTION_IF_NULL(value_node);
  642. if (NodeOutputDeviceAddressExist(value_node, 0)) {
  643. MS_LOG(DEBUG) << "value_node[" << value_node->DebugString() << "] address already exist";
  644. continue;
  645. }
  646. auto &node_value = value_node->value();
  647. MS_EXCEPTION_IF_NULL(node_value);
  648. MS_LOG(DEBUG) << "Malloc memory for " << value_node->fullname_with_scope();
  649. if (node_value->isa<Tensor>() || node_value->isa<ValueTuple>()) {
  650. AssignValueNodeTensor(value_node, node_value, 0);
  651. } else if (node_value->isa<StringImm>()) {
  652. auto value = GetValue<std::string>(node_value);
  653. size_t tensor_size = value.size();
  654. DeviceAddressPtr address = nullptr;
  655. address = CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8);
  656. MS_EXCEPTION_IF_NULL(address);
  657. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  658. !mem_manager_->MallocMemFromMemPool(address, tensor_size)) {
  659. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  660. } else if (mem_manager_->MallocMem(kStaticMem, tensor_size, address, graph->graph_id()) == nullptr) {
  661. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  662. }
  663. AnfAlgo::SetOutputAddr(address, 0, value_node.get());
  664. ShapeVector shape = {1, SizeToLong(tensor_size)};
  665. if (!address->SyncHostToDevice(shape, tensor_size, kNumberTypeUInt8, value.data())) {
  666. MS_LOG(EXCEPTION) << "kValueNode SyncHostToDevice fail!";
  667. }
  668. }
  669. }
  670. MS_LOG(INFO) << "AssignStaticMemoryValueNode end";
  671. }
  672. void KernelRuntime::SyncValueNodeDeviceAddr(session::KernelGraph *graph) {
  673. MS_EXCEPTION_IF_NULL(graph);
  674. MS_LOG(INFO) << "SyncValueNodeDeviceAddr start";
  675. for (auto &value_node : graph->graph_value_nodes()) {
  676. MS_EXCEPTION_IF_NULL(value_node);
  677. auto &node_value = value_node->value();
  678. MS_EXCEPTION_IF_NULL(node_value);
  679. if (!node_value->isa<Tensor>() && !node_value->isa<ValueTuple>()) {
  680. continue;
  681. }
  682. std::vector<tensor::TensorPtr> tensors;
  683. TensorValueToTensor(node_value, &tensors);
  684. for (size_t index = 0; index < tensors.size(); index += 1) {
  685. const auto &tensor = tensors[index];
  686. if (tensor->device_address() != nullptr) {
  687. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), index,
  688. value_node.get());
  689. } else {
  690. MS_LOG(INFO) << "Tensor of ValueNode[" << value_node->fullname_with_scope() << "]'s device address is nullptr.";
  691. }
  692. }
  693. }
  694. MS_LOG(INFO) << "SyncValueNodeDeviceAddr end";
  695. }
  696. void KernelRuntime::CleanValueNodeDeviceAddr(session::KernelGraph *graph) {
  697. MS_EXCEPTION_IF_NULL(graph);
  698. MS_LOG(INFO) << "CleanValueNodeDeviceAddr start";
  699. for (auto &value_node : graph->graph_value_nodes()) {
  700. MS_EXCEPTION_IF_NULL(value_node);
  701. auto &node_value = value_node->value();
  702. MS_EXCEPTION_IF_NULL(node_value);
  703. if (!node_value->isa<Tensor>() && !node_value->isa<ValueTuple>()) {
  704. continue;
  705. }
  706. std::vector<tensor::TensorPtr> tensors;
  707. TensorValueToTensor(node_value, &tensors);
  708. for (size_t index = 0; index < tensors.size(); index += 1) {
  709. if (tensors[index]->device_address() != nullptr) {
  710. AnfAlgo::SetOutputAddr(nullptr, index, value_node.get());
  711. }
  712. }
  713. }
  714. MS_LOG(INFO) << "CleanValueNodeDeviceAddr end";
  715. }
  716. void KernelRuntime::AssignDynamicMemory(session::KernelGraph *graph) {
  717. MS_EXCEPTION_IF_NULL(graph);
  718. MS_EXCEPTION_IF_NULL(mem_manager_);
  719. auto context_ptr = MsContext::GetInstance();
  720. MS_EXCEPTION_IF_NULL(context_ptr);
  721. bool is_enable_mem_reuse = context_ptr->get_param<bool>(MS_CTX_ENABLE_MEM_REUSE);
  722. auto mem_type = kDynamicMem;
  723. auto &dump_json_parser = DumpJsonParser::GetInstance();
  724. if (dump_json_parser.e2e_dump_enabled() && dump_json_parser.dump_mode() == 0) {
  725. context_ptr->set_param<bool>(MS_CTX_ENABLE_MEM_REUSE, false);
  726. is_enable_mem_reuse = false;
  727. MS_LOG(INFO) << "Disable Memory Reuse when e2e dump is enable and dump mode is set to dump all kernels";
  728. }
  729. if (is_enable_mem_reuse) {
  730. MS_LOG(INFO) << "Memory Reuse is enable...";
  731. #ifdef MEM_REUSE_DEBUG
  732. mem_manager_->MallocReusedDynamicMem(graph);
  733. mem_type = kReuseDynamicMem;
  734. #else
  735. mem_manager_->MallocSomasDynamicMem(graph);
  736. mem_type = kSomasReuseDynamicMem;
  737. #endif
  738. } else {
  739. MS_LOG(INFO) << "Memory Reuse is disable...";
  740. }
  741. auto &execution_nodes = graph->execution_order();
  742. std::vector<CNodePtr> compute_nodes;
  743. // communication nodes first
  744. for (auto &node : execution_nodes) {
  745. if (AnfAlgo::IsCommunicationOp(node)) {
  746. // skip if the memory is already allocated
  747. AssignCommunicationNodeMem(mem_type, node);
  748. } else {
  749. compute_nodes.emplace_back(node);
  750. }
  751. }
  752. // then compute nodes
  753. for (auto &node : compute_nodes) {
  754. AssignNodeOutputMem(mem_type, node, kGetAllOuts);
  755. AssignWorkSpaceMem(mem_type, node);
  756. }
  757. }
  758. void KernelRuntime::AssignWorkSpaceMem(MemType type, const AnfNodePtr &node) {
  759. MS_EXCEPTION_IF_NULL(node);
  760. MS_EXCEPTION_IF_NULL(mem_manager_);
  761. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  762. MS_EXCEPTION_IF_NULL(kernel_mod);
  763. size_t index = 0;
  764. for (auto &size : kernel_mod->GetWorkspaceSizeList()) {
  765. auto ptr = mem_manager_->MallocWorkSpaceMem(node, index, type, size);
  766. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(ptr, size, "", kTypeUnknown), index, node.get());
  767. index++;
  768. }
  769. }
  770. void KernelRuntime::GenLaunchArgs(const mindspore::kernel::KernelMod &kernel_mod, const mindspore::AnfNodePtr &kernel,
  771. AddressPtrList *kernel_inputs, AddressPtrList *const kernel_workspaces,
  772. AddressPtrList *kernel_outputs) {
  773. MS_EXCEPTION_IF_NULL(kernel);
  774. MS_EXCEPTION_IF_NULL(kernel_inputs);
  775. MS_EXCEPTION_IF_NULL(kernel_workspaces);
  776. MS_EXCEPTION_IF_NULL(kernel_outputs);
  777. auto cnode = kernel->cast<CNodePtr>();
  778. MS_EXCEPTION_IF_NULL(cnode);
  779. if (AnfAlgo::GetCNodeName(cnode) == kAtomicAddrCleanOpName) {
  780. return GenAddrCleanLaunchArgs(cnode, kernel_inputs);
  781. }
  782. auto ms_context = MsContext::GetInstance();
  783. MS_EXCEPTION_IF_NULL(ms_context);
  784. auto visit_nop_node = (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode);
  785. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  786. for (size_t i = 0; i < input_num; ++i) {
  787. auto op_name = AnfAlgo::GetCNodeName(cnode);
  788. constexpr auto none_placeholder_index = 3;
  789. if (op_name == kDynamicRNNOpName && i == none_placeholder_index) {
  790. continue;
  791. }
  792. if (op_name == kDynamicGRUV2OpName) {
  793. auto none_index = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(cnode, "placeholder_index");
  794. auto item = std::find(none_index.begin(), none_index.end(), i);
  795. if (item != none_index.end()) {
  796. continue;
  797. }
  798. }
  799. auto real_input = AnfAlgo::GetRealInputIndex(kernel, i);
  800. auto device_address = AnfAlgo::GetPrevNodeOutputAddr(kernel, real_input, visit_nop_node);
  801. MS_EXCEPTION_IF_NULL(device_address);
  802. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  803. MS_EXCEPTION_IF_NULL(input);
  804. input->addr = device_address->ptr_;
  805. MS_EXCEPTION_IF_NULL(input->addr);
  806. input->size = device_address->size_;
  807. kernel_inputs->emplace_back(input);
  808. }
  809. for (size_t i = 0; i < kernel_mod.GetOutputSizeList().size(); ++i) {
  810. auto device_address = AnfAlgo::GetOutputAddr(kernel, i, visit_nop_node);
  811. kernel::AddressPtr output = std::make_shared<kernel::Address>();
  812. MS_EXCEPTION_IF_NULL(output);
  813. output->addr = device_address->ptr_;
  814. MS_EXCEPTION_IF_NULL(output->addr);
  815. output->size = device_address->size_;
  816. kernel_outputs->emplace_back(output);
  817. }
  818. for (size_t i = 0; i < kernel_mod.GetWorkspaceSizeList().size(); ++i) {
  819. auto device_address = AnfAlgo::GetWorkspaceAddr(kernel, i);
  820. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  821. MS_EXCEPTION_IF_NULL(workspace);
  822. workspace->addr = device_address->ptr_;
  823. MS_EXCEPTION_IF_NULL(workspace->addr);
  824. workspace->size = device_address->size_;
  825. kernel_workspaces->emplace_back(workspace);
  826. }
  827. }
  828. void KernelRuntime::GenAddrCleanLaunchArgs(const CNodePtr &cnode, AddressPtrList *kernel_inputs) {
  829. if (cnode->inputs().size() != 2) {
  830. MS_LOG(EXCEPTION) << "Atomic Addr clean Node Input nodes not equal 2.";
  831. }
  832. MS_EXCEPTION_IF_NULL(cnode->inputs()[1]);
  833. auto pre_node = (cnode->inputs()[1])->cast<CNodePtr>();
  834. // set clean output address
  835. if (AnfAlgo::HasNodeAttr(kAttrAtomicOutputIndexs, pre_node)) {
  836. #if defined(__APPLE__)
  837. auto clean_output_indexes = AnfAlgo::GetNodeAttr<std::vector<int>>(pre_node, kAttrAtomicOutputIndexs);
  838. #else
  839. auto clean_output_indexes = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicOutputIndexs);
  840. #endif
  841. for (auto index : clean_output_indexes) {
  842. auto device_address = AnfAlgo::GetOutputAddr(pre_node, index);
  843. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  844. MS_EXCEPTION_IF_NULL(input);
  845. input->addr = device_address->ptr_;
  846. MS_EXCEPTION_IF_NULL(input->addr);
  847. input->size = device_address->size_;
  848. kernel_inputs->emplace_back(input);
  849. }
  850. MS_LOG(INFO) << "AtomicAddClean clean output size:" << clean_output_indexes.size();
  851. }
  852. // set clean workspace address
  853. if (AnfAlgo::HasNodeAttr(kAttrAtomicWorkspaceIndexs, pre_node)) {
  854. #if defined(__APPLE__)
  855. auto clean_workspaces_indexes = AnfAlgo::GetNodeAttr<std::vector<int>>(pre_node, kAttrAtomicWorkspaceIndexs);
  856. #else
  857. auto clean_workspaces_indexes = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicWorkspaceIndexs);
  858. #endif
  859. for (const auto &index : clean_workspaces_indexes) {
  860. auto device_address = AnfAlgo::GetWorkspaceAddr(pre_node, index);
  861. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  862. MS_EXCEPTION_IF_NULL(workspace);
  863. workspace->addr = device_address->ptr_;
  864. MS_EXCEPTION_IF_NULL(workspace->addr);
  865. workspace->size = device_address->size_;
  866. kernel_inputs->emplace_back(workspace);
  867. }
  868. }
  869. }
  870. bool KernelRuntime::LaunchKernelMod(const session::KernelGraph &graph) {
  871. const auto &kernels = graph.execution_order();
  872. std::vector<DynamicKernelPtr> dynamic_kernel_list;
  873. auto iter = graph_dynamic_kernel_map_.find(graph.graph_id());
  874. if (iter != graph_dynamic_kernel_map_.end()) {
  875. dynamic_kernel_list = iter->second;
  876. }
  877. if (!dynamic_kernel_list.empty() && dynamic_kernel_list.size() != kernels.size()) {
  878. MS_LOG(EXCEPTION) << "The size of dynamic kernels " << dynamic_kernel_list.size()
  879. << " should be equal to the size of kernels " << kernels.size();
  880. }
  881. for (size_t i = 0; i < kernels.size(); ++i) {
  882. if (!dynamic_kernel_list.empty() && dynamic_kernel_list[i] != nullptr &&
  883. dynamic_kernel_list[i]->is_dynamic_shape()) {
  884. dynamic_kernel_list[i]->InferShape();
  885. dynamic_kernel_list[i]->UpdateArgs();
  886. dynamic_kernel_list[i]->Execute();
  887. if (!SyncStream()) {
  888. MS_LOG(ERROR) << "SyncStream failed";
  889. return false;
  890. }
  891. dynamic_kernel_list[i]->PostExecute();
  892. } else {
  893. auto &kernel = kernels[i];
  894. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  895. MS_EXCEPTION_IF_NULL(kernel_mod);
  896. AddressPtrList kernel_inputs;
  897. AddressPtrList kernel_workspaces;
  898. AddressPtrList kernel_outputs;
  899. GenLaunchArgs(*kernel_mod, kernel, &kernel_inputs, &kernel_workspaces, &kernel_outputs);
  900. auto ret = kernel_mod->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_);
  901. if (!ret) {
  902. MS_LOG(ERROR) << "Launch kernel failed.";
  903. return false;
  904. }
  905. KernelLaunchProfiling(kernels[i]->fullname_with_scope());
  906. }
  907. }
  908. return true;
  909. }
  910. bool KernelRuntime::LaunchKernel(const session::KernelGraph *graph) {
  911. MS_EXCEPTION_IF_NULL(graph);
  912. if (!LaunchKernelMod(*graph)) {
  913. MS_LOG(ERROR) << "LaunchKernelMod failed!";
  914. return false;
  915. }
  916. auto ms_context = MsContext::GetInstance();
  917. MS_EXCEPTION_IF_NULL(ms_context);
  918. if (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kGraphMode) {
  919. if (!SyncStream()) {
  920. MS_LOG(ERROR) << "SyncStream failed";
  921. return false;
  922. }
  923. }
  924. return true;
  925. }
  926. void KernelRuntime::ClearGraphRuntimeResource(uint32_t graph_id, const std::vector<AnfNodePtr> &,
  927. const std::unordered_set<ValueNodePtr> &, const std::vector<CNodePtr> &) {
  928. MS_LOG(INFO) << "Clear graph:" << graph_id << " runtime resource";
  929. }
  930. void KernelRuntime::ClearOutputAddress(const std::vector<AnfNodePtr> &inputs,
  931. const std::unordered_set<ValueNodePtr> &value_nodes,
  932. const std::vector<CNodePtr> &execution_order) {
  933. // clear input parameter output address.
  934. for (const auto &input_node : inputs) {
  935. MS_EXCEPTION_IF_NULL(input_node);
  936. if (!input_node->isa<Parameter>()) {
  937. continue;
  938. }
  939. auto parameter = input_node->cast<ParameterPtr>();
  940. MS_EXCEPTION_IF_NULL(parameter);
  941. parameter->DecreaseUsedGraphCount();
  942. // Only the parameter has no graph used, then clear the output address.
  943. if (parameter->used_graph_count() != 0) {
  944. continue;
  945. }
  946. size_t output_num = AnfAlgo::GetOutputTensorNum(input_node);
  947. for (size_t index = 0; index < output_num; ++index) {
  948. if (!AnfAlgo::OutputAddrExist(input_node, index)) {
  949. continue;
  950. }
  951. AnfAlgo::SetOutputAddr(nullptr, index, input_node.get());
  952. }
  953. }
  954. // clear input value node output address.
  955. for (const auto &value_node : value_nodes) {
  956. if (!AnfAlgo::OutputAddrExist(value_node, 0)) {
  957. continue;
  958. }
  959. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  960. }
  961. // clear cnode output address.
  962. for (const auto &cnode : execution_order) {
  963. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  964. for (size_t index = 0; index < output_num; ++index) {
  965. if (!AnfAlgo::OutputAddrExist(cnode, index)) {
  966. continue;
  967. }
  968. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  969. }
  970. }
  971. }
  972. bool KernelRuntime::LaunchTaskBasedOnSingleKernel(kernel::KernelModPtr kernel_mod_ptr,
  973. const AddressPtrList &kernel_inputs,
  974. const AddressPtrList &kernel_outputs,
  975. const AddressPtrList &kernel_workspaces) const {
  976. MS_EXCEPTION_IF_NULL(kernel_mod_ptr);
  977. auto ret = kernel_mod_ptr->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_);
  978. if (!ret) {
  979. MS_LOG(ERROR) << "Launch kernel failed.";
  980. return false;
  981. }
  982. return true;
  983. }
  984. DeviceAddressPtr KernelRuntime::AssignSingleOpLaunchMemory(size_t size, const std::string &format, TypeId type) {
  985. auto device_address = CreateDeviceAddress(nullptr, size, format, type);
  986. MS_EXCEPTION_IF_NULL(device_address);
  987. MS_EXCEPTION_IF_NULL(mem_manager_);
  988. auto base_ptr = mem_manager_->MallocMem(kStaticMem, size, device_address);
  989. MS_EXCEPTION_IF_NULL(base_ptr);
  990. return device_address;
  991. }
  992. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  993. void KernelRuntime::GetFirstPSEmbeddingCache(const session::KernelGraph *graph, AnfNodePtr *first_cache_input_index,
  994. size_t *first_cache_size) {
  995. MS_EXCEPTION_IF_NULL(graph);
  996. for (const auto &kernel : graph->execution_order()) {
  997. MS_EXCEPTION_IF_NULL(kernel);
  998. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  999. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1000. continue;
  1001. }
  1002. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1003. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1004. MS_EXCEPTION_IF_NULL(input_param.first);
  1005. MS_EXCEPTION_IF_NULL(input_index.first);
  1006. auto param_name = input_param.first->fullname_with_scope();
  1007. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1008. continue;
  1009. }
  1010. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1011. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1012. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1013. MS_EXCEPTION_IF_NULL(input_index.first);
  1014. }
  1015. auto input_index_node_name = AnfAlgo::GetCNodeName(input_index.first);
  1016. if (input_index.first->isa<CNode>() && (input_index_node_name != kGetNextOpName)) {
  1017. bool full_batch = parallel::ParallelContext::GetInstance()->full_batch();
  1018. if ((!full_batch && (input_index_node_name != kUniqueOpName)) ||
  1019. (full_batch && (input_index_node_name != kMinimumOpName))) {
  1020. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope()
  1021. << ") cache is from " << input_index.first->fullname_with_scope();
  1022. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1023. "parameter server training mode.";
  1024. }
  1025. }
  1026. *first_cache_input_index = input_index.first;
  1027. *first_cache_size = size;
  1028. MS_LOG(INFO) << "The input index of the first embeddingLookup cache is from "
  1029. << input_index.first->fullname_with_scope() << ", the cache size is " << size;
  1030. return;
  1031. }
  1032. }
  1033. void KernelRuntime::CheckSparsePSEmbeddingCache(const CNodePtr &node) {
  1034. MS_EXCEPTION_IF_NULL(node);
  1035. auto pre_node = AnfAlgo::GetPrevNodeOutput(node, 1, true);
  1036. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1037. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1038. MS_EXCEPTION_IF_NULL(pre_node.first);
  1039. }
  1040. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1041. MS_LOG(EXCEPTION) << "The input_indices of kernel[SparseGatherV2] must be unique in parameter server cache mode";
  1042. }
  1043. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1044. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) == kCastOpName)) {
  1045. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1046. MS_EXCEPTION_IF_NULL(pre_node.first);
  1047. }
  1048. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kGetNextOpName)) {
  1049. MS_LOG(EXCEPTION) << "The input indices of kernel[Unique] must be produced from dataset directly and the indices "
  1050. "value can not be changed before delivering to kernel[Unique] in parameter server cache mode.";
  1051. }
  1052. }
  1053. void KernelRuntime::CheckIfSupportPSEmbeddingCache(const session::KernelGraph *graph) {
  1054. MS_EXCEPTION_IF_NULL(graph);
  1055. AnfNodePtr first_cache_input_index = nullptr;
  1056. size_t first_cache_size = 0;
  1057. GetFirstPSEmbeddingCache(graph, &first_cache_input_index, &first_cache_size);
  1058. MS_EXCEPTION_IF_NULL(first_cache_input_index);
  1059. for (const auto &kernel : graph->execution_order()) {
  1060. MS_EXCEPTION_IF_NULL(kernel);
  1061. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  1062. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1063. continue;
  1064. }
  1065. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1066. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1067. MS_EXCEPTION_IF_NULL(input_param.first);
  1068. MS_EXCEPTION_IF_NULL(input_index.first);
  1069. if (!input_param.first->isa<Parameter>()) {
  1070. continue;
  1071. }
  1072. auto param_name = input_param.first->fullname_with_scope();
  1073. if (ps::ps_cache_instance.IsHashTable(param_name) && (kernel_name == kSparseGatherV2OpName)) {
  1074. CheckSparsePSEmbeddingCache(kernel);
  1075. }
  1076. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1077. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1078. MS_EXCEPTION_IF_NULL(input_index.first);
  1079. }
  1080. if (input_index.first == first_cache_input_index) {
  1081. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1082. MS_LOG(ERROR) << "The embeddingLookup(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1083. MS_LOG(EXCEPTION) << "All the embeddingLookups whose input indices are from dataset must enable cache at the "
  1084. "same time when one of them enables cache in parameter server training mode.";
  1085. }
  1086. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1087. if (size != first_cache_size) {
  1088. MS_LOG(ERROR) << "The cache size(" << size << ") of embeddingLookup(" << kernel->fullname_with_scope()
  1089. << ") is not the same as other embeddingLookup cache size(" << first_cache_size << ").";
  1090. MS_LOG(EXCEPTION) << "The cache sizes of embeddingLookups are not the same in parameter server training mode.";
  1091. }
  1092. } else if (ps::ps_cache_instance.IsHashTable(param_name)) {
  1093. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope() << ") cache is from "
  1094. << input_index.first->fullname_with_scope();
  1095. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1096. "parameter server training mode.";
  1097. } else if (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kGetNextOpName)) {
  1098. MS_LOG(ERROR) << "The EmbeddingLookup kernel(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1099. MS_LOG(EXCEPTION) << "All EmbeddingLookup kernels whose input indices are from dataset must enable cache at "
  1100. "the same time and parameter 'sparse' must be equal to the value of 'enable_sparse' in "
  1101. "context setting in parameter server training mode.";
  1102. }
  1103. }
  1104. }
  1105. #endif
  1106. } // namespace device
  1107. } // namespace mindspore