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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. AssignWorkSpaceMem(type, node);
  410. }
  411. void KernelRuntime::AssignCommunicationNodeOutputMem(MemType type, const AnfNodePtr &node) {
  412. MS_EXCEPTION_IF_NULL(node);
  413. MS_EXCEPTION_IF_NULL(mem_manager_);
  414. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  415. MS_EXCEPTION_IF_NULL(kernel_mod);
  416. auto output_sizes = kernel_mod->GetOutputSizeList();
  417. if (output_sizes.empty()) {
  418. MS_LOG(INFO) << "This kernel[" << node->DebugString() << "] has no output size.";
  419. return;
  420. }
  421. auto context_ptr = MsContext::GetInstance();
  422. MS_EXCEPTION_IF_NULL(context_ptr);
  423. size_t total_size = 0;
  424. size_t output_index = 0;
  425. std::vector<size_t> align_size_list;
  426. for (uint64_t mem_size : output_sizes) {
  427. if (AnfAlgo::OutputAddrExist(node, output_index++)) {
  428. MS_LOG(INFO) << "communication op addr exist";
  429. continue;
  430. }
  431. if (context_ptr->get_param<bool>(MS_CTX_ENABLE_HCCL)) {
  432. mem_size = mem_manager_->GetCommonAlignSize(mem_size);
  433. }
  434. total_size += mem_size;
  435. align_size_list.emplace_back(mem_size);
  436. }
  437. if (type == kReuseDynamicMem) {
  438. // reuse communication op's all outputs' memory
  439. type = kReuseDynamicCommMem;
  440. }
  441. if (type == kReuseDynamicCommMem || type == kSomasReuseDynamicMem) {
  442. bool not_reuse = KernelMemNotReuse(node);
  443. if (not_reuse) {
  444. type = kDynamicMem;
  445. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  446. }
  447. }
  448. uint8_t *output_ptr = nullptr;
  449. for (size_t j = 0; j < align_size_list.size(); ++j) {
  450. std::string output_format = AnfAlgo::GetOutputFormat(node, j);
  451. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, j);
  452. auto address = CreateDeviceAddress(nullptr, output_sizes[j], output_format, output_type);
  453. MS_EXCEPTION_IF_NULL(address);
  454. if (output_ptr == nullptr) {
  455. output_ptr = mem_manager_->MallocOutputMem(node, 0, type, total_size, address, true);
  456. MS_EXCEPTION_IF_NULL(output_ptr);
  457. } else {
  458. address->set_ptr(output_ptr);
  459. }
  460. AnfAlgo::SetOutputAddr(address, j, node.get());
  461. output_ptr += align_size_list[j];
  462. }
  463. }
  464. bool KernelRuntime::KernelMemNotReuse(const AnfNodePtr &node) { return false; }
  465. DeviceAddressPtr KernelRuntime::PreAssignCNodeMemory(const AnfNodePtr &anf_node, size_t index) {
  466. MS_EXCEPTION_IF_NULL(anf_node);
  467. if (!anf_node->isa<CNode>()) {
  468. MS_LOG(EXCEPTION) << "anf_node should be a cnode";
  469. }
  470. auto cnode = anf_node->cast<CNodePtr>();
  471. if (opt::IsNopNode(cnode)) {
  472. const size_t kNopNodeInputSize = 2;
  473. if (cnode->size() != kNopNodeInputSize) {
  474. MS_LOG(EXCEPTION) << cnode->fullname_with_scope() << " has invalid input size: " << cnode->size();
  475. }
  476. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(anf_node, index);
  477. return PreAssignCNodeMemory(input_node_with_index.first, input_node_with_index.second);
  478. }
  479. auto kernel_mod = AnfAlgo::GetKernelMod(anf_node);
  480. MS_EXCEPTION_IF_NULL(kernel_mod);
  481. auto output_sizes = kernel_mod->GetOutputSizeList();
  482. if (output_sizes.size() <= index) {
  483. MS_LOG(EXCEPTION) << "Previous node output size < node index";
  484. }
  485. std::string output_format = AnfAlgo::GetOutputFormat(anf_node, index);
  486. auto output_type = AnfAlgo::GetOutputDeviceDataType(anf_node, index);
  487. auto address = CreateDeviceAddress(nullptr, output_sizes[index], output_format, output_type);
  488. AnfAlgo::SetOutputAddr(address, index, anf_node.get());
  489. return address;
  490. }
  491. void KernelRuntime::AssignCommunicationNodeInputMem(MemType type, const AnfNodePtr &node) {
  492. auto context_ptr = MsContext::GetInstance();
  493. MS_EXCEPTION_IF_NULL(context_ptr);
  494. MS_EXCEPTION_IF_NULL(node);
  495. MS_EXCEPTION_IF_NULL(mem_manager_);
  496. size_t total_size = 0;
  497. std::vector<std::pair<DeviceAddressPtr, size_t>> addr_size;
  498. size_t input_num = AnfAlgo::GetInputTensorNum(node);
  499. for (size_t i = 0; i < input_num; ++i) {
  500. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(node, i);
  501. auto input_node = input_node_with_index.first;
  502. DeviceAddressPtr address = nullptr;
  503. if (input_node->isa<CNode>()) {
  504. address = PreAssignCNodeMemory(input_node, input_node_with_index.second);
  505. } else {
  506. MS_LOG(EXCEPTION) << "Communication node inputs only support CNode";
  507. }
  508. MS_EXCEPTION_IF_NULL(address);
  509. auto mem_size = mem_manager_->GetCommonAlignSize(address->size());
  510. total_size += mem_size;
  511. addr_size.emplace_back(address, mem_size);
  512. }
  513. if (addr_size.empty()) {
  514. return;
  515. }
  516. if (type == kReuseDynamicMem || type == kSomasReuseDynamicMem) {
  517. bool not_reuse = KernelMemNotReuse(node);
  518. if (not_reuse) {
  519. type = kDynamicMem;
  520. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s input.";
  521. }
  522. }
  523. auto cnode = node->cast<CNodePtr>();
  524. MS_EXCEPTION_IF_NULL(cnode);
  525. if (cnode->inputs().size() < 2) {
  526. // communication node's input should contain itself and at least on input
  527. MS_LOG(ERROR) << "No inputs for " << cnode->fullname_with_scope();
  528. return;
  529. }
  530. auto first_input_node = cnode->input(1);
  531. auto prenode_index = AnfAlgo::VisitKernelWithReturnType(first_input_node, 0, true);
  532. uint8_t *input_ptr = mem_manager_->MallocOutputMem(prenode_index.first, prenode_index.second, type, total_size,
  533. addr_size[0].first, true);
  534. for (const auto &iter : addr_size) {
  535. MS_EXCEPTION_IF_NULL(iter.first);
  536. iter.first->set_ptr(input_ptr);
  537. input_ptr += iter.second;
  538. }
  539. }
  540. void KernelRuntime::AssignNodeOutputMem(MemType type, const AnfNodePtr &node, int index) {
  541. MS_EXCEPTION_IF_NULL(node);
  542. MS_EXCEPTION_IF_NULL(mem_manager_);
  543. if (AnfAlgo::IsGetNext(NOT_NULL(node)) && type == kReuseDynamicMem) {
  544. MS_LOG(INFO) << "GetNext disable mem_reuse";
  545. type = kDynamicMem;
  546. }
  547. if (node->isa<CNode>()) {
  548. bool independent = AnfAlgo::IsIndependentNode(node->cast<CNodePtr>());
  549. if (independent && (type == kReuseDynamicMem)) {
  550. MS_LOG(INFO) << "Independent node " << node->fullname_with_scope() << " disable memory reuse";
  551. type = kDynamicMem;
  552. }
  553. }
  554. if (type == kReuseDynamicMem || type == kSomasReuseDynamicMem) {
  555. bool not_reuse = KernelMemNotReuse(node);
  556. if (not_reuse) {
  557. type = kDynamicMem;
  558. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  559. }
  560. }
  561. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  562. MS_EXCEPTION_IF_NULL(kernel_mod);
  563. auto output_sizes = kernel_mod->GetOutputSizeList();
  564. if (output_sizes.empty()) {
  565. return;
  566. }
  567. for (size_t i = 0; i < output_sizes.size(); ++i) {
  568. if ((kGetAllOuts != index) && (SizeToInt(i) != index)) {
  569. continue;
  570. }
  571. if (NodeOutputDeviceAddressExist(node, i)) {
  572. MS_LOG(INFO) << "Already malloc index:" << i;
  573. continue;
  574. }
  575. MS_LOG(DEBUG) << "Assign Node:" << node->fullname_with_scope() << " output memory size:" << output_sizes[i];
  576. std::string output_format = AnfAlgo::GetOutputFormat(node, i);
  577. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, i);
  578. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  579. MS_EXCEPTION_IF_NULL(device_address);
  580. uint8_t *ptr = mem_manager_->MallocOutputMem(node, i, type, output_sizes[i], device_address, false);
  581. MS_EXCEPTION_IF_NULL(ptr);
  582. device_address->set_host_shape(trans::GetRuntimePaddingShape(node, i));
  583. AnfAlgo::SetOutputAddr(device_address, i, node.get());
  584. }
  585. }
  586. void KernelRuntime::AssignValueNodeTensor(const ValueNodePtr &value_node, const ValuePtr &node_value,
  587. size_t output_idx) {
  588. MS_EXCEPTION_IF_NULL(value_node);
  589. MS_EXCEPTION_IF_NULL(node_value);
  590. MS_EXCEPTION_IF_NULL(mem_manager_);
  591. auto ms_context = MsContext::GetInstance();
  592. MS_EXCEPTION_IF_NULL(ms_context);
  593. std::vector<tensor::TensorPtr> tensors;
  594. TensorValueToTensor(node_value, &tensors);
  595. // Graph id should be passed to record static memory if profiling is enabled.
  596. auto kernel_info = static_cast<device::KernelInfo *>(value_node->kernel_info());
  597. MS_EXCEPTION_IF_NULL(kernel_info);
  598. uint32_t graph_id = kernel_info->graph_id();
  599. for (const auto &tensor : tensors) {
  600. if (tensor == nullptr) {
  601. MS_LOG(WARNING) << "Tensor is null";
  602. return;
  603. }
  604. auto output_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  605. if (output_address != nullptr && output_address->DeviceType() == GetTargetDeviceAddressType()) {
  606. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), output_idx++,
  607. value_node.get());
  608. continue;
  609. }
  610. size_t tensor_size = tensor->data().nbytes();
  611. auto node_size = CountNodeDeviceMemorySize(value_node, output_idx);
  612. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(value_node, output_idx);
  613. if (output_type_id == kTypeUnknown) {
  614. output_type_id = AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  615. }
  616. auto output_format = AnfAlgo::GetOutputFormat(value_node, output_idx);
  617. DeviceAddressPtr address = CreateDeviceAddress(nullptr, node_size, output_format, output_type_id);
  618. MS_EXCEPTION_IF_NULL(address);
  619. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  620. !mem_manager_->MallocMemFromMemPool(address, node_size)) {
  621. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << node_size;
  622. } else if (mem_manager_->MallocMem(kStaticMem, node_size, address, graph_id) == nullptr) {
  623. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << node_size;
  624. }
  625. AnfAlgo::SetOutputAddr(address, output_idx, value_node.get());
  626. if (!address->SyncHostToDevice(trans::GetRuntimePaddingShape(value_node, 0), tensor_size, tensor->data_type(),
  627. tensor->data_c())) {
  628. MS_EXCEPTION(NotExistsError) << "ValueNode SyncHostToDevice fail!" << value_node->DebugString()
  629. << "node format is" << AnfAlgo::GetOutputFormat(value_node, output_idx)
  630. << "node dtype is " << AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  631. }
  632. }
  633. return;
  634. }
  635. void KernelRuntime::AssignStaticMemoryValueNode(session::KernelGraph *graph) {
  636. MS_EXCEPTION_IF_NULL(graph);
  637. MS_EXCEPTION_IF_NULL(mem_manager_);
  638. MS_LOG(INFO) << "AssignStaticMemoryValueNode start";
  639. auto ms_context = MsContext::GetInstance();
  640. MS_EXCEPTION_IF_NULL(ms_context);
  641. for (auto &value_node : graph->graph_value_nodes()) {
  642. MS_EXCEPTION_IF_NULL(value_node);
  643. if (NodeOutputDeviceAddressExist(value_node, 0)) {
  644. MS_LOG(DEBUG) << "value_node[" << value_node->DebugString() << "] address already exist";
  645. continue;
  646. }
  647. auto &node_value = value_node->value();
  648. MS_EXCEPTION_IF_NULL(node_value);
  649. MS_LOG(DEBUG) << "Malloc memory for " << value_node->fullname_with_scope();
  650. if (node_value->isa<Tensor>() || node_value->isa<ValueTuple>()) {
  651. AssignValueNodeTensor(value_node, node_value, 0);
  652. } else if (node_value->isa<StringImm>()) {
  653. auto value = GetValue<std::string>(node_value);
  654. size_t tensor_size = value.size();
  655. DeviceAddressPtr address = nullptr;
  656. address = CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8);
  657. MS_EXCEPTION_IF_NULL(address);
  658. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  659. !mem_manager_->MallocMemFromMemPool(address, tensor_size)) {
  660. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  661. } else if (mem_manager_->MallocMem(kStaticMem, tensor_size, address, graph->graph_id()) == nullptr) {
  662. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  663. }
  664. AnfAlgo::SetOutputAddr(address, 0, value_node.get());
  665. ShapeVector shape = {1, SizeToLong(tensor_size)};
  666. if (!address->SyncHostToDevice(shape, tensor_size, kNumberTypeUInt8, value.data())) {
  667. MS_LOG(EXCEPTION) << "kValueNode SyncHostToDevice fail!";
  668. }
  669. }
  670. }
  671. MS_LOG(INFO) << "AssignStaticMemoryValueNode end";
  672. }
  673. void KernelRuntime::SyncValueNodeDeviceAddr(session::KernelGraph *graph) {
  674. MS_EXCEPTION_IF_NULL(graph);
  675. MS_LOG(INFO) << "SyncValueNodeDeviceAddr start";
  676. for (auto &value_node : graph->graph_value_nodes()) {
  677. MS_EXCEPTION_IF_NULL(value_node);
  678. auto &node_value = value_node->value();
  679. MS_EXCEPTION_IF_NULL(node_value);
  680. if (!node_value->isa<Tensor>() && !node_value->isa<ValueTuple>()) {
  681. continue;
  682. }
  683. std::vector<tensor::TensorPtr> tensors;
  684. TensorValueToTensor(node_value, &tensors);
  685. for (size_t index = 0; index < tensors.size(); index += 1) {
  686. const auto &tensor = tensors[index];
  687. if (tensor->device_address() != nullptr) {
  688. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), index,
  689. value_node.get());
  690. } else {
  691. MS_LOG(INFO) << "Tensor of ValueNode[" << value_node->fullname_with_scope() << "]'s device address is nullptr.";
  692. }
  693. }
  694. }
  695. MS_LOG(INFO) << "SyncValueNodeDeviceAddr end";
  696. }
  697. void KernelRuntime::CleanValueNodeDeviceAddr(session::KernelGraph *graph) {
  698. MS_EXCEPTION_IF_NULL(graph);
  699. MS_LOG(INFO) << "CleanValueNodeDeviceAddr start";
  700. for (auto &value_node : graph->graph_value_nodes()) {
  701. MS_EXCEPTION_IF_NULL(value_node);
  702. auto &node_value = value_node->value();
  703. MS_EXCEPTION_IF_NULL(node_value);
  704. if (!node_value->isa<Tensor>() && !node_value->isa<ValueTuple>()) {
  705. continue;
  706. }
  707. std::vector<tensor::TensorPtr> tensors;
  708. TensorValueToTensor(node_value, &tensors);
  709. for (size_t index = 0; index < tensors.size(); index += 1) {
  710. if (tensors[index]->device_address() != nullptr) {
  711. AnfAlgo::SetOutputAddr(nullptr, index, value_node.get());
  712. }
  713. }
  714. }
  715. MS_LOG(INFO) << "CleanValueNodeDeviceAddr end";
  716. }
  717. void KernelRuntime::AssignDynamicMemory(session::KernelGraph *graph) {
  718. MS_EXCEPTION_IF_NULL(graph);
  719. MS_EXCEPTION_IF_NULL(mem_manager_);
  720. auto context_ptr = MsContext::GetInstance();
  721. MS_EXCEPTION_IF_NULL(context_ptr);
  722. bool is_enable_mem_reuse = context_ptr->get_param<bool>(MS_CTX_ENABLE_MEM_REUSE);
  723. auto mem_type = kDynamicMem;
  724. auto &dump_json_parser = DumpJsonParser::GetInstance();
  725. if (dump_json_parser.e2e_dump_enabled() && dump_json_parser.dump_mode() == 0) {
  726. context_ptr->set_param<bool>(MS_CTX_ENABLE_MEM_REUSE, false);
  727. is_enable_mem_reuse = false;
  728. MS_LOG(INFO) << "Disable Memory Reuse when e2e dump is enable and dump mode is set to dump all kernels";
  729. }
  730. if (is_enable_mem_reuse) {
  731. MS_LOG(INFO) << "Memory Reuse is enable...";
  732. #ifdef MEM_REUSE_DEBUG
  733. mem_manager_->MallocReusedDynamicMem(graph);
  734. mem_type = kReuseDynamicMem;
  735. #else
  736. mem_manager_->MallocSomasDynamicMem(graph);
  737. mem_type = kSomasReuseDynamicMem;
  738. #endif
  739. } else {
  740. MS_LOG(INFO) << "Memory Reuse is disable...";
  741. }
  742. auto &execution_nodes = graph->execution_order();
  743. std::vector<CNodePtr> compute_nodes;
  744. // communication nodes first
  745. for (auto &node : execution_nodes) {
  746. if (AnfAlgo::IsCommunicationOp(node)) {
  747. // skip if the memory is already allocated
  748. AssignCommunicationNodeMem(mem_type, node);
  749. } else {
  750. compute_nodes.emplace_back(node);
  751. }
  752. }
  753. // then compute nodes
  754. for (auto &node : compute_nodes) {
  755. AssignNodeOutputMem(mem_type, node, kGetAllOuts);
  756. AssignWorkSpaceMem(mem_type, node);
  757. }
  758. }
  759. void KernelRuntime::AssignWorkSpaceMem(MemType type, const AnfNodePtr &node) {
  760. MS_EXCEPTION_IF_NULL(node);
  761. MS_EXCEPTION_IF_NULL(mem_manager_);
  762. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  763. MS_EXCEPTION_IF_NULL(kernel_mod);
  764. size_t index = 0;
  765. for (auto &size : kernel_mod->GetWorkspaceSizeList()) {
  766. auto ptr = mem_manager_->MallocWorkSpaceMem(node, index, type, size);
  767. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(ptr, size, "", kTypeUnknown), index, node.get());
  768. index++;
  769. }
  770. }
  771. void KernelRuntime::GenLaunchArgs(const mindspore::kernel::KernelMod &kernel_mod, const mindspore::AnfNodePtr &kernel,
  772. AddressPtrList *kernel_inputs, AddressPtrList *const kernel_workspaces,
  773. AddressPtrList *kernel_outputs) {
  774. MS_EXCEPTION_IF_NULL(kernel);
  775. MS_EXCEPTION_IF_NULL(kernel_inputs);
  776. MS_EXCEPTION_IF_NULL(kernel_workspaces);
  777. MS_EXCEPTION_IF_NULL(kernel_outputs);
  778. auto cnode = kernel->cast<CNodePtr>();
  779. MS_EXCEPTION_IF_NULL(cnode);
  780. if (AnfAlgo::GetCNodeName(cnode) == kAtomicAddrCleanOpName) {
  781. return GenAddrCleanLaunchArgs(cnode, kernel_inputs);
  782. }
  783. auto ms_context = MsContext::GetInstance();
  784. MS_EXCEPTION_IF_NULL(ms_context);
  785. auto visit_nop_node = (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode);
  786. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  787. for (size_t i = 0; i < input_num; ++i) {
  788. auto op_name = AnfAlgo::GetCNodeName(cnode);
  789. constexpr auto none_placeholder_index = 3;
  790. if (op_name == kDynamicRNNOpName && i == none_placeholder_index) {
  791. continue;
  792. }
  793. if (op_name == kDynamicGRUV2OpName) {
  794. auto none_index = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(cnode, "placeholder_index");
  795. auto item = std::find(none_index.begin(), none_index.end(), i);
  796. if (item != none_index.end()) {
  797. continue;
  798. }
  799. }
  800. auto real_input = AnfAlgo::GetRealInputIndex(kernel, i);
  801. auto device_address = AnfAlgo::GetPrevNodeOutputAddr(kernel, real_input, visit_nop_node);
  802. MS_EXCEPTION_IF_NULL(device_address);
  803. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  804. MS_EXCEPTION_IF_NULL(input);
  805. input->addr = device_address->ptr_;
  806. MS_EXCEPTION_IF_NULL(input->addr);
  807. input->size = device_address->size_;
  808. kernel_inputs->emplace_back(input);
  809. }
  810. for (size_t i = 0; i < kernel_mod.GetOutputSizeList().size(); ++i) {
  811. auto device_address = AnfAlgo::GetOutputAddr(kernel, i, visit_nop_node);
  812. kernel::AddressPtr output = std::make_shared<kernel::Address>();
  813. MS_EXCEPTION_IF_NULL(output);
  814. output->addr = device_address->ptr_;
  815. MS_EXCEPTION_IF_NULL(output->addr);
  816. output->size = device_address->size_;
  817. kernel_outputs->emplace_back(output);
  818. }
  819. for (size_t i = 0; i < kernel_mod.GetWorkspaceSizeList().size(); ++i) {
  820. auto device_address = AnfAlgo::GetWorkspaceAddr(kernel, i);
  821. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  822. MS_EXCEPTION_IF_NULL(workspace);
  823. workspace->addr = device_address->ptr_;
  824. MS_EXCEPTION_IF_NULL(workspace->addr);
  825. workspace->size = device_address->size_;
  826. kernel_workspaces->emplace_back(workspace);
  827. }
  828. }
  829. void KernelRuntime::GenAddrCleanLaunchArgs(const CNodePtr &cnode, AddressPtrList *kernel_inputs) {
  830. if (cnode->inputs().size() != 2) {
  831. MS_LOG(EXCEPTION) << "Atomic Addr clean Node Input nodes not equal 2.";
  832. }
  833. MS_EXCEPTION_IF_NULL(cnode->inputs()[1]);
  834. auto pre_node = (cnode->inputs()[1])->cast<CNodePtr>();
  835. // set clean output address
  836. if (AnfAlgo::HasNodeAttr(kAttrAtomicOutputIndexs, pre_node)) {
  837. #if defined(__APPLE__)
  838. auto clean_output_indexes = AnfAlgo::GetNodeAttr<std::vector<int>>(pre_node, kAttrAtomicOutputIndexs);
  839. #else
  840. auto clean_output_indexes = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicOutputIndexs);
  841. #endif
  842. for (auto index : clean_output_indexes) {
  843. auto device_address = AnfAlgo::GetOutputAddr(pre_node, index);
  844. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  845. MS_EXCEPTION_IF_NULL(input);
  846. input->addr = device_address->ptr_;
  847. MS_EXCEPTION_IF_NULL(input->addr);
  848. input->size = device_address->size_;
  849. kernel_inputs->emplace_back(input);
  850. }
  851. MS_LOG(INFO) << "AtomicAddClean clean output size:" << clean_output_indexes.size();
  852. }
  853. // set clean workspace address
  854. if (AnfAlgo::HasNodeAttr(kAttrAtomicWorkspaceIndexs, pre_node)) {
  855. #if defined(__APPLE__)
  856. auto clean_workspaces_indexes = AnfAlgo::GetNodeAttr<std::vector<int>>(pre_node, kAttrAtomicWorkspaceIndexs);
  857. #else
  858. auto clean_workspaces_indexes = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicWorkspaceIndexs);
  859. #endif
  860. for (const auto &index : clean_workspaces_indexes) {
  861. auto device_address = AnfAlgo::GetWorkspaceAddr(pre_node, index);
  862. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  863. MS_EXCEPTION_IF_NULL(workspace);
  864. workspace->addr = device_address->ptr_;
  865. MS_EXCEPTION_IF_NULL(workspace->addr);
  866. workspace->size = device_address->size_;
  867. kernel_inputs->emplace_back(workspace);
  868. }
  869. }
  870. }
  871. bool KernelRuntime::LaunchKernelMod(const session::KernelGraph &graph) {
  872. const auto &kernels = graph.execution_order();
  873. std::vector<DynamicKernelPtr> dynamic_kernel_list;
  874. auto iter = graph_dynamic_kernel_map_.find(graph.graph_id());
  875. if (iter != graph_dynamic_kernel_map_.end()) {
  876. dynamic_kernel_list = iter->second;
  877. }
  878. if (!dynamic_kernel_list.empty() && dynamic_kernel_list.size() != kernels.size()) {
  879. MS_LOG(EXCEPTION) << "The size of dynamic kernels " << dynamic_kernel_list.size()
  880. << " should be equal to the size of kernels " << kernels.size();
  881. }
  882. for (size_t i = 0; i < kernels.size(); ++i) {
  883. if (!dynamic_kernel_list.empty() && dynamic_kernel_list[i] != nullptr &&
  884. dynamic_kernel_list[i]->is_dynamic_shape()) {
  885. dynamic_kernel_list[i]->InferShape();
  886. dynamic_kernel_list[i]->UpdateArgs();
  887. dynamic_kernel_list[i]->Execute();
  888. if (!SyncStream()) {
  889. MS_LOG(ERROR) << "SyncStream failed";
  890. return false;
  891. }
  892. dynamic_kernel_list[i]->PostExecute();
  893. } else {
  894. auto &kernel = kernels[i];
  895. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  896. MS_EXCEPTION_IF_NULL(kernel_mod);
  897. AddressPtrList kernel_inputs;
  898. AddressPtrList kernel_workspaces;
  899. AddressPtrList kernel_outputs;
  900. GenLaunchArgs(*kernel_mod, kernel, &kernel_inputs, &kernel_workspaces, &kernel_outputs);
  901. auto ret = kernel_mod->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_);
  902. if (!ret) {
  903. MS_LOG(ERROR) << "Launch kernel failed.";
  904. return false;
  905. }
  906. KernelLaunchProfiling(kernels[i]->fullname_with_scope());
  907. }
  908. }
  909. return true;
  910. }
  911. bool KernelRuntime::LaunchKernel(const session::KernelGraph *graph) {
  912. MS_EXCEPTION_IF_NULL(graph);
  913. if (!LaunchKernelMod(*graph)) {
  914. MS_LOG(ERROR) << "LaunchKernelMod failed!";
  915. return false;
  916. }
  917. auto ms_context = MsContext::GetInstance();
  918. MS_EXCEPTION_IF_NULL(ms_context);
  919. if (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kGraphMode) {
  920. if (!SyncStream()) {
  921. MS_LOG(ERROR) << "SyncStream failed";
  922. return false;
  923. }
  924. }
  925. return true;
  926. }
  927. void KernelRuntime::ClearGraphRuntimeResource(uint32_t graph_id, const std::vector<AnfNodePtr> &,
  928. const std::unordered_set<ValueNodePtr> &, const std::vector<CNodePtr> &) {
  929. MS_LOG(INFO) << "Clear graph:" << graph_id << " runtime resource";
  930. }
  931. void KernelRuntime::ClearOutputAddress(const std::vector<AnfNodePtr> &inputs,
  932. const std::unordered_set<ValueNodePtr> &value_nodes,
  933. const std::vector<CNodePtr> &execution_order) {
  934. // clear input parameter output address.
  935. for (const auto &input_node : inputs) {
  936. MS_EXCEPTION_IF_NULL(input_node);
  937. if (!input_node->isa<Parameter>()) {
  938. continue;
  939. }
  940. auto parameter = input_node->cast<ParameterPtr>();
  941. MS_EXCEPTION_IF_NULL(parameter);
  942. parameter->DecreaseUsedGraphCount();
  943. // Only the parameter has no graph used, then clear the output address.
  944. if (parameter->used_graph_count() != 0) {
  945. continue;
  946. }
  947. size_t output_num = AnfAlgo::GetOutputTensorNum(input_node);
  948. for (size_t index = 0; index < output_num; ++index) {
  949. if (!AnfAlgo::OutputAddrExist(input_node, index)) {
  950. continue;
  951. }
  952. AnfAlgo::SetOutputAddr(nullptr, index, input_node.get());
  953. }
  954. }
  955. // clear input value node output address.
  956. for (const auto &value_node : value_nodes) {
  957. if (!AnfAlgo::OutputAddrExist(value_node, 0)) {
  958. continue;
  959. }
  960. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  961. }
  962. // clear cnode output address.
  963. for (const auto &cnode : execution_order) {
  964. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  965. for (size_t index = 0; index < output_num; ++index) {
  966. if (!AnfAlgo::OutputAddrExist(cnode, index)) {
  967. continue;
  968. }
  969. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  970. }
  971. }
  972. }
  973. bool KernelRuntime::LaunchTaskBasedOnSingleKernel(kernel::KernelModPtr kernel_mod_ptr,
  974. const AddressPtrList &kernel_inputs,
  975. const AddressPtrList &kernel_outputs,
  976. const AddressPtrList &kernel_workspaces) const {
  977. MS_EXCEPTION_IF_NULL(kernel_mod_ptr);
  978. auto ret = kernel_mod_ptr->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_);
  979. if (!ret) {
  980. MS_LOG(ERROR) << "Launch kernel failed.";
  981. return false;
  982. }
  983. return true;
  984. }
  985. DeviceAddressPtr KernelRuntime::AssignSingleOpLaunchMemory(size_t size, const std::string &format, TypeId type) {
  986. auto device_address = CreateDeviceAddress(nullptr, size, format, type);
  987. MS_EXCEPTION_IF_NULL(device_address);
  988. MS_EXCEPTION_IF_NULL(mem_manager_);
  989. auto base_ptr = mem_manager_->MallocMem(kStaticMem, size, device_address);
  990. MS_EXCEPTION_IF_NULL(base_ptr);
  991. return device_address;
  992. }
  993. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  994. void KernelRuntime::GetFirstPSEmbeddingCache(const session::KernelGraph *graph, AnfNodePtr *first_cache_input_index,
  995. size_t *first_cache_size) {
  996. MS_EXCEPTION_IF_NULL(graph);
  997. for (const auto &kernel : graph->execution_order()) {
  998. MS_EXCEPTION_IF_NULL(kernel);
  999. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  1000. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1001. continue;
  1002. }
  1003. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1004. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1005. MS_EXCEPTION_IF_NULL(input_param.first);
  1006. MS_EXCEPTION_IF_NULL(input_index.first);
  1007. auto param_name = input_param.first->fullname_with_scope();
  1008. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1009. continue;
  1010. }
  1011. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1012. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1013. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1014. MS_EXCEPTION_IF_NULL(input_index.first);
  1015. }
  1016. auto input_index_node_name = AnfAlgo::GetCNodeName(input_index.first);
  1017. if (input_index.first->isa<CNode>() && (input_index_node_name != kGetNextOpName)) {
  1018. bool full_batch = parallel::ParallelContext::GetInstance()->full_batch();
  1019. if ((!full_batch && (input_index_node_name != kUniqueOpName)) ||
  1020. (full_batch && (input_index_node_name != kMinimumOpName))) {
  1021. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope()
  1022. << ") cache is from " << input_index.first->fullname_with_scope();
  1023. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1024. "parameter server training mode.";
  1025. }
  1026. }
  1027. *first_cache_input_index = input_index.first;
  1028. *first_cache_size = size;
  1029. MS_LOG(INFO) << "The input index of the first embeddingLookup cache is from "
  1030. << input_index.first->fullname_with_scope() << ", the cache size is " << size;
  1031. return;
  1032. }
  1033. }
  1034. void KernelRuntime::CheckSparsePSEmbeddingCache(const CNodePtr &node) {
  1035. MS_EXCEPTION_IF_NULL(node);
  1036. auto pre_node = AnfAlgo::GetPrevNodeOutput(node, 1, true);
  1037. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1038. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1039. MS_EXCEPTION_IF_NULL(pre_node.first);
  1040. }
  1041. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1042. MS_LOG(EXCEPTION) << "The input_indices of kernel[SparseGatherV2] must be unique in parameter server cache mode";
  1043. }
  1044. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1045. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) == kCastOpName)) {
  1046. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1047. MS_EXCEPTION_IF_NULL(pre_node.first);
  1048. }
  1049. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kGetNextOpName)) {
  1050. MS_LOG(EXCEPTION) << "The input indices of kernel[Unique] must be produced from dataset directly and the indices "
  1051. "value can not be changed before delivering to kernel[Unique] in parameter server cache mode.";
  1052. }
  1053. }
  1054. void KernelRuntime::CheckIfSupportPSEmbeddingCache(const session::KernelGraph *graph) {
  1055. MS_EXCEPTION_IF_NULL(graph);
  1056. AnfNodePtr first_cache_input_index = nullptr;
  1057. size_t first_cache_size = 0;
  1058. GetFirstPSEmbeddingCache(graph, &first_cache_input_index, &first_cache_size);
  1059. MS_EXCEPTION_IF_NULL(first_cache_input_index);
  1060. for (const auto &kernel : graph->execution_order()) {
  1061. MS_EXCEPTION_IF_NULL(kernel);
  1062. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  1063. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1064. continue;
  1065. }
  1066. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1067. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1068. MS_EXCEPTION_IF_NULL(input_param.first);
  1069. MS_EXCEPTION_IF_NULL(input_index.first);
  1070. if (!input_param.first->isa<Parameter>()) {
  1071. continue;
  1072. }
  1073. auto param_name = input_param.first->fullname_with_scope();
  1074. if (ps::ps_cache_instance.IsHashTable(param_name) && (kernel_name == kSparseGatherV2OpName)) {
  1075. CheckSparsePSEmbeddingCache(kernel);
  1076. }
  1077. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1078. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1079. MS_EXCEPTION_IF_NULL(input_index.first);
  1080. }
  1081. if (input_index.first == first_cache_input_index) {
  1082. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1083. MS_LOG(ERROR) << "The embeddingLookup(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1084. MS_LOG(EXCEPTION) << "All the embeddingLookups whose input indices are from dataset must enable cache at the "
  1085. "same time when one of them enables cache in parameter server training mode.";
  1086. }
  1087. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1088. if (size != first_cache_size) {
  1089. MS_LOG(ERROR) << "The cache size(" << size << ") of embeddingLookup(" << kernel->fullname_with_scope()
  1090. << ") is not the same as other embeddingLookup cache size(" << first_cache_size << ").";
  1091. MS_LOG(EXCEPTION) << "The cache sizes of embeddingLookups are not the same in parameter server training mode.";
  1092. }
  1093. } else if (ps::ps_cache_instance.IsHashTable(param_name)) {
  1094. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope() << ") cache is from "
  1095. << input_index.first->fullname_with_scope();
  1096. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1097. "parameter server training mode.";
  1098. } else if (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kGetNextOpName)) {
  1099. MS_LOG(ERROR) << "The EmbeddingLookup kernel(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1100. MS_LOG(EXCEPTION) << "All EmbeddingLookup kernels whose input indices are from dataset must enable cache at "
  1101. "the same time and parameter 'sparse' must be equal to the value of 'enable_sparse' in "
  1102. "context setting in parameter server training mode.";
  1103. }
  1104. }
  1105. }
  1106. #endif
  1107. } // namespace device
  1108. } // namespace mindspore