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