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 50 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  109. for (size_t index = 0; index < output_num; ++index) {
  110. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  111. }
  112. // clear workspace memory resource
  113. auto kernel_mod = AnfAlgo::GetKernelMod(cnode);
  114. MS_EXCEPTION_IF_NULL(kernel_mod);
  115. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  116. for (size_t index = 0; index < workspace_lists.size(); ++index) {
  117. AnfAlgo::SetWorkspaceAddr(nullptr, index, cnode.get());
  118. }
  119. }
  120. }
  121. bool KernelRuntime::DumpDataEnabled() {
  122. auto &dump_json_parser = DumpJsonParser::GetInstance();
  123. return dump_json_parser.e2e_dump_enabled();
  124. }
  125. bool KernelRuntime::DumpDataEnabledIteration() {
  126. auto &dump_json_parser = DumpJsonParser::GetInstance();
  127. if (!dump_json_parser.e2e_dump_enabled()) {
  128. return false;
  129. }
  130. auto cur_iter = dump_json_parser.cur_dump_iter() + 1;
  131. if (dump_json_parser.iteration() != 0) {
  132. return cur_iter == dump_json_parser.iteration();
  133. }
  134. return true;
  135. }
  136. void KernelRuntime::AssignStaticMemory(session::KernelGraph *graph) {
  137. AssignStaticMemoryInput(graph);
  138. AssignStaticMemoryValueNode(graph);
  139. AssignStaticMemoryOutput(graph);
  140. }
  141. void KernelRuntime::RunOpAssignInputMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  142. const session::KernelGraph *graph) {
  143. MS_EXCEPTION_IF_NULL(graph);
  144. MS_EXCEPTION_IF_NULL(mem_manager_);
  145. if (input_tensors.size() != graph->inputs().size()) {
  146. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors.size()
  147. << " should be equal to graph input parameter size " << graph->inputs().size();
  148. }
  149. for (size_t input_index = 0; input_index < graph->inputs().size(); ++input_index) {
  150. auto item = graph->inputs()[input_index];
  151. MS_EXCEPTION_IF_NULL(item);
  152. if (!item->isa<Parameter>()) {
  153. continue;
  154. }
  155. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  156. for (size_t index = 0; index < output_size; index++) {
  157. MS_EXCEPTION_IF_NULL(input_tensors[input_index]);
  158. auto output_address =
  159. std::dynamic_pointer_cast<device::DeviceAddress>(input_tensors[input_index]->device_address());
  160. if (output_address != nullptr) {
  161. AnfAlgo::SetOutputAddr(output_address, index, item.get());
  162. continue;
  163. }
  164. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  165. if (output_type_id == kTypeUnknown) {
  166. output_type_id = AnfAlgo::GetOutputInferDataType(item, index);
  167. }
  168. auto tensor_size = CountNodeDeviceMemorySize(item, index);
  169. auto device_address =
  170. CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  171. MS_EXCEPTION_IF_NULL(device_address);
  172. MS_EXCEPTION_IF_NULL(mem_manager_);
  173. auto ret = mem_manager_->MallocMemFromMemPool(device_address, tensor_size);
  174. if (!ret) {
  175. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  176. }
  177. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  178. }
  179. }
  180. }
  181. void KernelRuntime::RunOpAssignOutputMemory(const AnfNodePtr &kernel) {
  182. MS_EXCEPTION_IF_NULL(kernel);
  183. MS_EXCEPTION_IF_NULL(mem_manager_);
  184. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  185. MS_EXCEPTION_IF_NULL(kernel_mod);
  186. auto output_sizes = kernel_mod->GetOutputSizeList();
  187. if (output_sizes.empty()) {
  188. return;
  189. }
  190. for (size_t i = 0; i < output_sizes.size(); ++i) {
  191. if (AnfAlgo::OutputAddrExist(kernel, i)) {
  192. continue;
  193. }
  194. if (AnfAlgo::GetCNodeName(kernel) == kApplyMomentumOpName) {
  195. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i);
  196. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  197. continue;
  198. }
  199. std::string output_format = AnfAlgo::GetOutputFormat(kernel, i);
  200. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  201. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  202. device_address->set_host_shape(trans::GetRuntimePaddingShape(kernel, i));
  203. MS_EXCEPTION_IF_NULL(device_address);
  204. auto ret = mem_manager_->MallocMemFromMemPool(device_address, output_sizes[i]);
  205. if (!ret) {
  206. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << output_sizes[i];
  207. }
  208. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  209. }
  210. }
  211. void KernelRuntime::RunOpAssignWorkSpaceMemory(const AnfNodePtr &kernel) {
  212. MS_EXCEPTION_IF_NULL(kernel);
  213. MS_EXCEPTION_IF_NULL(mem_manager_);
  214. if (kernel->isa<CNode>()) {
  215. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  216. MS_EXCEPTION_IF_NULL(kernel_mod);
  217. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  218. for (size_t i = 0; i < workspace_lists.size(); ++i) {
  219. auto device_address = CreateDeviceAddress(nullptr, workspace_lists[i], "", kTypeUnknown);
  220. MS_EXCEPTION_IF_NULL(device_address);
  221. auto ret = mem_manager_->MallocMemFromMemPool(device_address, workspace_lists[i]);
  222. if (!ret) {
  223. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << workspace_lists[i];
  224. }
  225. AnfAlgo::SetWorkspaceAddr(device_address, i, kernel.get());
  226. }
  227. }
  228. }
  229. void KernelRuntime::RunOpAssignOutputNodeMemory(const ValuePtr &pre_output_value, session::KernelGraph *graph) {
  230. if (pre_output_value == nullptr) {
  231. return;
  232. }
  233. std::vector<tensor::TensorPtr> pre_output_tensors;
  234. TensorValueToTensor(pre_output_value, &pre_output_tensors);
  235. MS_EXCEPTION_IF_NULL(graph);
  236. auto output_nodes = graph->outputs();
  237. if (pre_output_tensors.size() != output_nodes.size()) {
  238. MS_LOG(EXCEPTION) << "The size of pre output tensors [" << pre_output_tensors.size()
  239. << "] is not equal to the size of output nodes of graph [" << output_nodes.size() << "]";
  240. }
  241. // share output address with pre output tensors
  242. for (size_t i = 0; i < output_nodes.size(); ++i) {
  243. auto output_node_with_index = AnfAlgo::VisitKernel(output_nodes[i], 0);
  244. if (!output_node_with_index.first->isa<CNode>()) {
  245. if (output_node_with_index.first->isa<Parameter>()) {
  246. auto param = output_node_with_index.first->cast<ParameterPtr>();
  247. if (!param->has_default()) {
  248. MS_LOG(EXCEPTION) << "The output parameter should be real parameter!";
  249. }
  250. }
  251. continue;
  252. }
  253. auto real_output_cnode = output_node_with_index.first->cast<CNodePtr>();
  254. MS_EXCEPTION_IF_NULL(real_output_cnode);
  255. MS_EXCEPTION_IF_NULL(pre_output_tensors[i]);
  256. if (pre_output_tensors[i]->device_address() == nullptr) {
  257. MS_LOG(INFO) << "The address of pre output tensor [" << i << "] is a nullptr!";
  258. continue;
  259. }
  260. if (opt::IsNopNode(real_output_cnode)) {
  261. if (real_output_cnode->inputs().size() < 2) {
  262. MS_LOG(EXCEPTION) << "The input size of output node: " << real_output_cnode->DebugString()
  263. << " should large than one!";
  264. }
  265. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(pre_output_tensors[i]->device_address()),
  266. output_node_with_index.second, real_output_cnode->input(1).get());
  267. } else {
  268. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(pre_output_tensors[i]->device_address()),
  269. output_node_with_index.second, output_node_with_index.first.get());
  270. }
  271. }
  272. }
  273. void KernelRuntime::AssignStaticMemoryInput(const session::KernelGraph *graph) {
  274. MS_EXCEPTION_IF_NULL(graph);
  275. MS_EXCEPTION_IF_NULL(mem_manager_);
  276. MS_LOG(INFO) << "AssignStaticMemoryInput start";
  277. auto graph_inputs = graph->inputs();
  278. auto graph_valid_input = graph->valid_inputs();
  279. graph_inputs.insert(graph_inputs.end(), graph->child_graph_result().begin(), graph->child_graph_result().end());
  280. std::vector<AnfNodePtr> need_alloc_nodes;
  281. for (size_t i = 0; i < graph_inputs.size(); ++i) {
  282. auto item = graph_inputs[i];
  283. MS_EXCEPTION_IF_NULL(item);
  284. if (i < graph_valid_input.size() && !graph_valid_input[i]) {
  285. continue;
  286. }
  287. if (AnfAlgo::CheckPrimitiveType(item, prim::kPrimMakeTuple)) {
  288. auto outs = AnfAlgo::GetAllOutput(item);
  289. for (auto &out : outs) {
  290. MS_EXCEPTION_IF_NULL(out);
  291. if (!out->isa<Parameter>()) {
  292. continue;
  293. }
  294. if (NodeOutputDeviceAddressExist(out, 0)) {
  295. continue;
  296. }
  297. need_alloc_nodes.push_back(out);
  298. }
  299. }
  300. if (!item->isa<Parameter>()) {
  301. continue;
  302. }
  303. if (NodeOutputDeviceAddressExist(item, 0)) {
  304. continue;
  305. }
  306. need_alloc_nodes.push_back(item);
  307. }
  308. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  309. bool ps_cache_check = false;
  310. #endif
  311. for (auto &item : need_alloc_nodes) {
  312. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  313. for (size_t index = 0; index < output_size; index++) {
  314. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  315. // if graph output is a weight and doesn't link to any cnode, it's data type will be unknown
  316. if (output_type_id == kTypeUnknown) {
  317. MS_LOG(WARNING) << "It is not suggested to use a lonely weight parameter as the output of graph";
  318. continue;
  319. }
  320. DeviceAddressPtr device_address = nullptr;
  321. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  322. const std::string &param_name = item->fullname_with_scope();
  323. if (ps::ps_cache_instance.IsHashTable(param_name)) {
  324. MS_LOG(INFO) << "Parameter(" << param_name << ")"
  325. << " enables the embeddingLookup cache in parameter server training mode.";
  326. // PS embeddingLookup cache check.
  327. if (!ps_cache_check) {
  328. CheckIfSupportPSEmbeddingCache(graph);
  329. ps_cache_check = true;
  330. }
  331. const auto &address = ps::ps_cache_instance.QueryHashTableAddr(param_name);
  332. MS_EXCEPTION_IF_NULL(address.addr);
  333. device_address =
  334. CreateDeviceAddress(address.addr, address.size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  335. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  336. continue;
  337. }
  338. #endif
  339. auto tensor_size = CountNodeDeviceMemorySize(item, index);
  340. device_address = CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id);
  341. MS_LOG(DEBUG) << "Malloc static memory for " << item->fullname_with_scope();
  342. if (mem_manager_->MallocMem(kStaticMem, tensor_size, device_address, graph->graph_id()) == nullptr) {
  343. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  344. }
  345. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  346. }
  347. }
  348. MS_LOG(INFO) << "AssignStaticMemoryInput end";
  349. }
  350. void KernelRuntime::AssignStaticMemoryOutput(const session::KernelGraph *graph) {
  351. MS_EXCEPTION_IF_NULL(graph);
  352. MS_LOG(INFO) << "AssignStaticMemoryOutput start";
  353. auto nodes = AnfAlgo::GetAllOutput(graph->output(), {prim::kPrimTupleGetItem});
  354. std::vector<session::KernelWithIndex> non_communication_op;
  355. // Assign Communicate Op Memory firstly.
  356. for (const auto &node : nodes) {
  357. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(node, 0, true);
  358. MS_EXCEPTION_IF_NULL(item_with_index.first);
  359. if (!item_with_index.first->isa<CNode>() || !AnfAlgo::IsRealKernel(item_with_index.first)) {
  360. continue;
  361. }
  362. if (AnfAlgo::IsCommunicationOp(item_with_index.first)) {
  363. AssignCommunicationNodeMem(kStaticMem, item_with_index.first);
  364. } else {
  365. non_communication_op.emplace_back(item_with_index);
  366. }
  367. }
  368. for (const auto &item_with_index : non_communication_op) {
  369. MS_LOG(DEBUG) << "AssignNodeOutputMem for " << item_with_index.first->fullname_with_scope();
  370. AssignNodeOutputMem(kStaticMem, item_with_index.first, SizeToInt(item_with_index.second));
  371. }
  372. MS_LOG(INFO) << "AssignStaticMemoryOutput end";
  373. }
  374. void KernelRuntime::UpdateRefNodeOutputMem(const session::KernelGraph *graph) {
  375. MS_EXCEPTION_IF_NULL(graph);
  376. auto &kernels = graph->execution_order();
  377. for (auto &kernel : kernels) {
  378. MS_EXCEPTION_IF_NULL(kernel);
  379. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  380. MS_EXCEPTION_IF_NULL(kernel_mod);
  381. auto output_sizes = kernel_mod->GetOutputSizeList();
  382. if (output_sizes.empty()) {
  383. MS_LOG(INFO) << "This kernel has no output size.";
  384. continue;
  385. }
  386. for (size_t i = 0; i < output_sizes.size(); ++i) {
  387. session::AnfWithOutIndex out_pair(kernel, i);
  388. if (graph->IsInRefOutputMap(out_pair)) {
  389. auto origin_pair = graph->GetRefCorrespondOutput(out_pair);
  390. MS_EXCEPTION_IF_NULL(origin_pair.first);
  391. auto origin_node_output_addr = AnfAlgo::GetMutableOutputAddr(origin_pair.first, origin_pair.second);
  392. MS_EXCEPTION_IF_NULL(origin_node_output_addr);
  393. auto cur_node_output_addr = AnfAlgo::GetMutableOutputAddr(kernel, i);
  394. if (origin_node_output_addr.get() != cur_node_output_addr.get()) {
  395. MS_LOG(DEBUG) << "REF address is not same, ref node output need address update";
  396. MS_LOG(DEBUG) << "REF origin op is " << origin_pair.first->DebugString() << ", output index is "
  397. << origin_pair.second << ", cur op is " << kernel->DebugString() << ", out index is " << i;
  398. AnfAlgo::SetOutputAddr(origin_node_output_addr, i, kernel.get());
  399. }
  400. }
  401. }
  402. }
  403. }
  404. void KernelRuntime::AssignCommunicationNodeMem(MemType type, const AnfNodePtr &node) {
  405. AssignCommunicationNodeInputMem(type, node);
  406. AssignCommunicationNodeOutputMem(type, node);
  407. }
  408. void KernelRuntime::AssignCommunicationNodeOutputMem(MemType type, const AnfNodePtr &node) {
  409. MS_EXCEPTION_IF_NULL(node);
  410. MS_EXCEPTION_IF_NULL(mem_manager_);
  411. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  412. MS_EXCEPTION_IF_NULL(kernel_mod);
  413. auto output_sizes = kernel_mod->GetOutputSizeList();
  414. if (output_sizes.empty()) {
  415. MS_LOG(INFO) << "This kernel[" << node->DebugString() << "] has no output size.";
  416. return;
  417. }
  418. auto context_ptr = MsContext::GetInstance();
  419. MS_EXCEPTION_IF_NULL(context_ptr);
  420. size_t total_size = 0;
  421. size_t output_index = 0;
  422. std::vector<size_t> align_size_list;
  423. for (uint64_t mem_size : output_sizes) {
  424. if (AnfAlgo::OutputAddrExist(node, output_index++)) {
  425. MS_LOG(INFO) << "communication op addr exist";
  426. continue;
  427. }
  428. if (context_ptr->get_param<bool>(MS_CTX_ENABLE_HCCL)) {
  429. mem_size = mem_manager_->GetCommonAlignSize(mem_size);
  430. }
  431. total_size += mem_size;
  432. align_size_list.emplace_back(mem_size);
  433. }
  434. if (type == kReuseDynamicMem) {
  435. // reuse communication op's all outputs' memory
  436. type = kReuseDynamicCommMem;
  437. }
  438. if (type == kReuseDynamicCommMem || type == kSomasReuseDynamicMem) {
  439. bool not_reuse = KernelMemNotReuse(node);
  440. if (not_reuse) {
  441. type = kDynamicMem;
  442. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  443. }
  444. }
  445. uint8_t *output_ptr = nullptr;
  446. for (size_t j = 0; j < align_size_list.size(); ++j) {
  447. std::string output_format = AnfAlgo::GetOutputFormat(node, j);
  448. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, j);
  449. auto address = CreateDeviceAddress(nullptr, output_sizes[j], output_format, output_type);
  450. MS_EXCEPTION_IF_NULL(address);
  451. if (output_ptr == nullptr) {
  452. output_ptr = mem_manager_->MallocOutputMem(node, 0, type, total_size, address, true);
  453. MS_EXCEPTION_IF_NULL(output_ptr);
  454. } else {
  455. address->set_ptr(output_ptr);
  456. }
  457. AnfAlgo::SetOutputAddr(address, j, node.get());
  458. output_ptr += align_size_list[j];
  459. }
  460. }
  461. bool KernelRuntime::KernelMemNotReuse(const AnfNodePtr &node) { return false; }
  462. DeviceAddressPtr KernelRuntime::PreAssignCNodeMemory(const AnfNodePtr &anf_node, size_t index) {
  463. MS_EXCEPTION_IF_NULL(anf_node);
  464. if (!anf_node->isa<CNode>()) {
  465. MS_LOG(EXCEPTION) << "anf_node should be a cnode";
  466. }
  467. auto cnode = anf_node->cast<CNodePtr>();
  468. if (opt::IsNopNode(cnode)) {
  469. const size_t kNopNodeInputSize = 2;
  470. if (cnode->size() != kNopNodeInputSize) {
  471. MS_LOG(EXCEPTION) << cnode->fullname_with_scope() << " has invalid input size: " << cnode->size();
  472. }
  473. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(anf_node, index);
  474. return PreAssignCNodeMemory(input_node_with_index.first, input_node_with_index.second);
  475. }
  476. auto kernel_mod = AnfAlgo::GetKernelMod(anf_node);
  477. MS_EXCEPTION_IF_NULL(kernel_mod);
  478. auto output_sizes = kernel_mod->GetOutputSizeList();
  479. if (output_sizes.size() <= index) {
  480. MS_LOG(EXCEPTION) << "Previous node output size < node index";
  481. }
  482. std::string output_format = AnfAlgo::GetOutputFormat(anf_node, index);
  483. auto output_type = AnfAlgo::GetOutputDeviceDataType(anf_node, index);
  484. auto address = CreateDeviceAddress(nullptr, output_sizes[index], output_format, output_type);
  485. AnfAlgo::SetOutputAddr(address, index, anf_node.get());
  486. return address;
  487. }
  488. void KernelRuntime::AssignCommunicationNodeInputMem(MemType type, const AnfNodePtr &node) {
  489. auto context_ptr = MsContext::GetInstance();
  490. MS_EXCEPTION_IF_NULL(context_ptr);
  491. MS_EXCEPTION_IF_NULL(node);
  492. MS_EXCEPTION_IF_NULL(mem_manager_);
  493. size_t total_size = 0;
  494. std::vector<std::pair<DeviceAddressPtr, size_t>> addr_size;
  495. size_t input_num = AnfAlgo::GetInputTensorNum(node);
  496. for (size_t i = 0; i < input_num; ++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. return;
  563. }
  564. for (size_t i = 0; i < output_sizes.size(); ++i) {
  565. if ((kGetAllOuts != index) && (SizeToInt(i) != index)) {
  566. continue;
  567. }
  568. if (NodeOutputDeviceAddressExist(node, i)) {
  569. MS_LOG(INFO) << "Already malloc index:" << i;
  570. continue;
  571. }
  572. MS_LOG(DEBUG) << "Assign Node:" << node->fullname_with_scope() << " output memory size:" << output_sizes[i];
  573. std::string output_format = AnfAlgo::GetOutputFormat(node, i);
  574. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, i);
  575. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  576. MS_EXCEPTION_IF_NULL(device_address);
  577. uint8_t *ptr = mem_manager_->MallocOutputMem(node, i, type, output_sizes[i], device_address, false);
  578. MS_EXCEPTION_IF_NULL(ptr);
  579. device_address->set_host_shape(trans::GetRuntimePaddingShape(node, i));
  580. AnfAlgo::SetOutputAddr(device_address, i, node.get());
  581. }
  582. }
  583. void KernelRuntime::AssignValueNodeTensor(const ValueNodePtr &value_node, const ValuePtr &node_value,
  584. size_t output_idx) {
  585. MS_EXCEPTION_IF_NULL(value_node);
  586. MS_EXCEPTION_IF_NULL(node_value);
  587. MS_EXCEPTION_IF_NULL(mem_manager_);
  588. auto ms_context = MsContext::GetInstance();
  589. MS_EXCEPTION_IF_NULL(ms_context);
  590. std::vector<tensor::TensorPtr> tensors;
  591. TensorValueToTensor(node_value, &tensors);
  592. // Graph id should be passed to record static memory if profiling is enabled.
  593. auto kernel_info = static_cast<device::KernelInfo *>(value_node->kernel_info());
  594. MS_EXCEPTION_IF_NULL(kernel_info);
  595. uint32_t graph_id = kernel_info->graph_id();
  596. for (const auto &tensor : tensors) {
  597. if (tensor == nullptr) {
  598. MS_LOG(WARNING) << "Tensor is null";
  599. return;
  600. }
  601. if (tensor->device_address() != nullptr) {
  602. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), output_idx++,
  603. value_node.get());
  604. continue;
  605. }
  606. size_t tensor_size = tensor->data().nbytes();
  607. auto node_size = CountNodeDeviceMemorySize(value_node, output_idx);
  608. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(value_node, output_idx);
  609. if (output_type_id == kTypeUnknown) {
  610. output_type_id = AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  611. }
  612. auto output_format = AnfAlgo::GetOutputFormat(value_node, output_idx);
  613. DeviceAddressPtr address = CreateDeviceAddress(nullptr, node_size, output_format, output_type_id);
  614. MS_EXCEPTION_IF_NULL(address);
  615. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  616. !mem_manager_->MallocMemFromMemPool(address, node_size)) {
  617. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << node_size;
  618. } else if (mem_manager_->MallocMem(kStaticMem, node_size, address, graph_id) == nullptr) {
  619. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << node_size;
  620. }
  621. AnfAlgo::SetOutputAddr(address, output_idx, value_node.get());
  622. if (!address->SyncHostToDevice(trans::GetRuntimePaddingShape(value_node, 0), tensor_size, tensor->data_type(),
  623. tensor->data_c())) {
  624. MS_EXCEPTION(NotExistsError) << "ValueNode SyncHostToDevice fail!" << value_node->DebugString()
  625. << "node format is" << AnfAlgo::GetOutputFormat(value_node, output_idx)
  626. << "node dtype is " << AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  627. }
  628. }
  629. return;
  630. }
  631. void KernelRuntime::AssignStaticMemoryValueNode(session::KernelGraph *graph) {
  632. MS_EXCEPTION_IF_NULL(graph);
  633. MS_EXCEPTION_IF_NULL(mem_manager_);
  634. MS_LOG(INFO) << "AssignStaticMemoryValueNode start";
  635. auto ms_context = MsContext::GetInstance();
  636. MS_EXCEPTION_IF_NULL(ms_context);
  637. for (auto &value_node : graph->graph_value_nodes()) {
  638. MS_EXCEPTION_IF_NULL(value_node);
  639. if (NodeOutputDeviceAddressExist(value_node, 0)) {
  640. MS_LOG(DEBUG) << "value_node[" << value_node->DebugString() << "] address already exist";
  641. continue;
  642. }
  643. auto &node_value = value_node->value();
  644. MS_EXCEPTION_IF_NULL(node_value);
  645. MS_LOG(DEBUG) << "Malloc memory for " << value_node->fullname_with_scope();
  646. if (node_value->isa<Tensor>() || node_value->isa<ValueTuple>()) {
  647. AssignValueNodeTensor(value_node, node_value, 0);
  648. } else if (node_value->isa<StringImm>()) {
  649. auto value = GetValue<std::string>(node_value);
  650. size_t tensor_size = value.size();
  651. DeviceAddressPtr address = nullptr;
  652. address = CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8);
  653. MS_EXCEPTION_IF_NULL(address);
  654. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  655. !mem_manager_->MallocMemFromMemPool(address, tensor_size)) {
  656. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  657. } else if (mem_manager_->MallocMem(kStaticMem, tensor_size, address, graph->graph_id()) == nullptr) {
  658. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  659. }
  660. AnfAlgo::SetOutputAddr(address, 0, value_node.get());
  661. ShapeVector shape = {1, SizeToLong(tensor_size)};
  662. if (!address->SyncHostToDevice(shape, tensor_size, kNumberTypeUInt8, value.data())) {
  663. MS_LOG(EXCEPTION) << "kValueNode SyncHostToDevice fail!";
  664. }
  665. }
  666. }
  667. MS_LOG(INFO) << "AssignStaticMemoryValueNode end";
  668. }
  669. void KernelRuntime::SyncValueNodeDeviceAddr(session::KernelGraph *graph) {
  670. MS_EXCEPTION_IF_NULL(graph);
  671. MS_LOG(INFO) << "SyncValueNodeDeviceAddr start";
  672. for (auto &value_node : graph->graph_value_nodes()) {
  673. MS_EXCEPTION_IF_NULL(value_node);
  674. auto &node_value = value_node->value();
  675. MS_EXCEPTION_IF_NULL(node_value);
  676. if (!node_value->isa<Tensor>() && !node_value->isa<ValueTuple>()) {
  677. continue;
  678. }
  679. std::vector<tensor::TensorPtr> tensors;
  680. TensorValueToTensor(node_value, &tensors);
  681. for (size_t index = 0; index < tensors.size(); index += 1) {
  682. const auto &tensor = tensors[index];
  683. if (tensor->device_address() != nullptr) {
  684. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), index,
  685. value_node.get());
  686. } else {
  687. MS_LOG(INFO) << "Tensor of ValueNode[" << value_node->fullname_with_scope() << "]'s device address is nullptr.";
  688. }
  689. }
  690. }
  691. MS_LOG(INFO) << "SyncValueNodeDeviceAddr end";
  692. }
  693. void KernelRuntime::CleanValueNodeDeviceAddr(session::KernelGraph *graph) {
  694. MS_EXCEPTION_IF_NULL(graph);
  695. MS_LOG(INFO) << "CleanValueNodeDeviceAddr start";
  696. for (auto &value_node : graph->graph_value_nodes()) {
  697. MS_EXCEPTION_IF_NULL(value_node);
  698. auto &node_value = value_node->value();
  699. MS_EXCEPTION_IF_NULL(node_value);
  700. if (!node_value->isa<Tensor>() && !node_value->isa<ValueTuple>()) {
  701. continue;
  702. }
  703. std::vector<tensor::TensorPtr> tensors;
  704. TensorValueToTensor(node_value, &tensors);
  705. for (size_t index = 0; index < tensors.size(); index += 1) {
  706. if (tensors[index]->device_address() != nullptr) {
  707. AnfAlgo::SetOutputAddr(nullptr, index, value_node.get());
  708. }
  709. }
  710. }
  711. MS_LOG(INFO) << "CleanValueNodeDeviceAddr end";
  712. }
  713. void KernelRuntime::AssignDynamicMemory(session::KernelGraph *graph) {
  714. MS_EXCEPTION_IF_NULL(graph);
  715. MS_EXCEPTION_IF_NULL(mem_manager_);
  716. auto context_ptr = MsContext::GetInstance();
  717. MS_EXCEPTION_IF_NULL(context_ptr);
  718. bool is_enable_mem_reuse = context_ptr->get_param<bool>(MS_CTX_ENABLE_MEM_REUSE);
  719. auto mem_type = kDynamicMem;
  720. auto &dump_json_parser = DumpJsonParser::GetInstance();
  721. if (dump_json_parser.e2e_dump_enabled() && dump_json_parser.dump_mode() == 0) {
  722. context_ptr->set_param<bool>(MS_CTX_ENABLE_MEM_REUSE, false);
  723. is_enable_mem_reuse = false;
  724. MS_LOG(INFO) << "Disable Memory Reuse when e2e dump is enable and dump mode is set to dump all kernels";
  725. }
  726. if (is_enable_mem_reuse) {
  727. MS_LOG(INFO) << "Memory Reuse is enable...";
  728. #ifdef MEM_REUSE_DEBUG
  729. mem_manager_->MallocReusedDynamicMem(graph);
  730. mem_type = kReuseDynamicMem;
  731. #else
  732. mem_manager_->MallocSomasDynamicMem(graph);
  733. mem_type = kSomasReuseDynamicMem;
  734. #endif
  735. } else {
  736. MS_LOG(INFO) << "Memory Reuse is disable...";
  737. }
  738. auto &execution_nodes = graph->execution_order();
  739. std::vector<CNodePtr> compute_nodes;
  740. // communication nodes first
  741. for (auto &node : execution_nodes) {
  742. if (AnfAlgo::IsCommunicationOp(node)) {
  743. // skip if the memory is already allocated
  744. AssignCommunicationNodeMem(mem_type, node);
  745. } else {
  746. compute_nodes.emplace_back(node);
  747. }
  748. }
  749. // then compute nodes
  750. for (auto &node : compute_nodes) {
  751. AssignNodeOutputMem(mem_type, node, kGetAllOuts);
  752. AssignWorkSpaceMem(mem_type, node);
  753. }
  754. }
  755. void KernelRuntime::AssignWorkSpaceMem(MemType type, const AnfNodePtr &node) {
  756. MS_EXCEPTION_IF_NULL(node);
  757. MS_EXCEPTION_IF_NULL(mem_manager_);
  758. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  759. MS_EXCEPTION_IF_NULL(kernel_mod);
  760. size_t index = 0;
  761. for (auto &size : kernel_mod->GetWorkspaceSizeList()) {
  762. auto ptr = mem_manager_->MallocWorkSpaceMem(node, index, type, size);
  763. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(ptr, size, "", kTypeUnknown), index, node.get());
  764. index++;
  765. }
  766. }
  767. void KernelRuntime::GenLaunchArgs(const mindspore::kernel::KernelMod &kernel_mod, const mindspore::AnfNodePtr &kernel,
  768. AddressPtrList *kernel_inputs, AddressPtrList *const kernel_workspaces,
  769. AddressPtrList *kernel_outputs) {
  770. MS_EXCEPTION_IF_NULL(kernel);
  771. MS_EXCEPTION_IF_NULL(kernel_inputs);
  772. MS_EXCEPTION_IF_NULL(kernel_workspaces);
  773. MS_EXCEPTION_IF_NULL(kernel_outputs);
  774. auto cnode = kernel->cast<CNodePtr>();
  775. MS_EXCEPTION_IF_NULL(cnode);
  776. if (AnfAlgo::GetCNodeName(cnode) == kAtomicAddrCleanOpName) {
  777. return GenAddrCleanLaunchArgs(cnode, kernel_inputs);
  778. }
  779. auto ms_context = MsContext::GetInstance();
  780. MS_EXCEPTION_IF_NULL(ms_context);
  781. auto visit_nop_node = (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode);
  782. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  783. for (size_t i = 0; i < input_num; ++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. size_t output_num = AnfAlgo::GetOutputTensorNum(input_node);
  944. for (size_t index = 0; index < output_num; ++index) {
  945. if (!AnfAlgo::OutputAddrExist(input_node, index)) {
  946. continue;
  947. }
  948. AnfAlgo::SetOutputAddr(nullptr, index, input_node.get());
  949. }
  950. }
  951. // clear input value node output address.
  952. for (const auto &value_node : value_nodes) {
  953. if (!AnfAlgo::OutputAddrExist(value_node, 0)) {
  954. continue;
  955. }
  956. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  957. }
  958. // clear cnode output address.
  959. for (const auto &cnode : execution_order) {
  960. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  961. for (size_t index = 0; index < output_num; ++index) {
  962. if (!AnfAlgo::OutputAddrExist(cnode, index)) {
  963. continue;
  964. }
  965. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  966. }
  967. }
  968. }
  969. bool KernelRuntime::LaunchTaskBasedOnSingleKernel(kernel::KernelModPtr kernel_mod_ptr,
  970. const AddressPtrList &kernel_inputs,
  971. const AddressPtrList &kernel_outputs,
  972. const AddressPtrList &kernel_workspaces) const {
  973. MS_EXCEPTION_IF_NULL(kernel_mod_ptr);
  974. auto ret = kernel_mod_ptr->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_);
  975. if (!ret) {
  976. MS_LOG(ERROR) << "Launch kernel failed.";
  977. return false;
  978. }
  979. return true;
  980. }
  981. DeviceAddressPtr KernelRuntime::AssignSingleOpLaunchMemory(size_t size, const std::string &format, TypeId type) {
  982. auto device_address = CreateDeviceAddress(nullptr, size, format, type);
  983. MS_EXCEPTION_IF_NULL(device_address);
  984. MS_EXCEPTION_IF_NULL(mem_manager_);
  985. auto base_ptr = mem_manager_->MallocMem(kStaticMem, size, device_address);
  986. MS_EXCEPTION_IF_NULL(base_ptr);
  987. return device_address;
  988. }
  989. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  990. void KernelRuntime::GetFirstPSEmbeddingCache(const session::KernelGraph *graph, AnfNodePtr *first_cache_input_index,
  991. size_t *first_cache_size) {
  992. MS_EXCEPTION_IF_NULL(graph);
  993. for (const auto &kernel : graph->execution_order()) {
  994. MS_EXCEPTION_IF_NULL(kernel);
  995. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  996. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  997. continue;
  998. }
  999. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1000. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1001. MS_EXCEPTION_IF_NULL(input_param.first);
  1002. MS_EXCEPTION_IF_NULL(input_index.first);
  1003. auto param_name = input_param.first->fullname_with_scope();
  1004. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1005. continue;
  1006. }
  1007. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1008. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1009. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1010. MS_EXCEPTION_IF_NULL(input_index.first);
  1011. }
  1012. auto input_index_node_name = AnfAlgo::GetCNodeName(input_index.first);
  1013. if (input_index.first->isa<CNode>() && (input_index_node_name != kGetNextOpName)) {
  1014. bool full_batch = parallel::ParallelContext::GetInstance()->full_batch();
  1015. if ((!full_batch && (input_index_node_name != kUniqueOpName)) ||
  1016. (full_batch && (input_index_node_name != kMinimumOpName))) {
  1017. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope()
  1018. << ") cache is from " << input_index.first->fullname_with_scope();
  1019. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1020. "parameter server training mode.";
  1021. }
  1022. }
  1023. *first_cache_input_index = input_index.first;
  1024. *first_cache_size = size;
  1025. MS_LOG(INFO) << "The input index of the first embeddingLookup cache is from "
  1026. << input_index.first->fullname_with_scope() << ", the cache size is " << size;
  1027. return;
  1028. }
  1029. }
  1030. void KernelRuntime::CheckSparsePSEmbeddingCache(const CNodePtr &node) {
  1031. MS_EXCEPTION_IF_NULL(node);
  1032. auto pre_node = AnfAlgo::GetPrevNodeOutput(node, 1, true);
  1033. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1034. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1035. MS_EXCEPTION_IF_NULL(pre_node.first);
  1036. }
  1037. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1038. MS_LOG(EXCEPTION) << "The input_indices of kernel[SparseGatherV2] must be unique in parameter server cache mode";
  1039. }
  1040. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1041. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) == kCastOpName)) {
  1042. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1043. MS_EXCEPTION_IF_NULL(pre_node.first);
  1044. }
  1045. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kGetNextOpName)) {
  1046. MS_LOG(EXCEPTION) << "The input indices of kernel[Unique] must be produced from dataset directly and the indices "
  1047. "value can not be changed before delivering to kernel[Unique] in parameter server cache mode.";
  1048. }
  1049. }
  1050. void KernelRuntime::CheckIfSupportPSEmbeddingCache(const session::KernelGraph *graph) {
  1051. MS_EXCEPTION_IF_NULL(graph);
  1052. AnfNodePtr first_cache_input_index = nullptr;
  1053. size_t first_cache_size = 0;
  1054. GetFirstPSEmbeddingCache(graph, &first_cache_input_index, &first_cache_size);
  1055. MS_EXCEPTION_IF_NULL(first_cache_input_index);
  1056. for (const auto &kernel : graph->execution_order()) {
  1057. MS_EXCEPTION_IF_NULL(kernel);
  1058. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  1059. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1060. continue;
  1061. }
  1062. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1063. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1064. MS_EXCEPTION_IF_NULL(input_param.first);
  1065. MS_EXCEPTION_IF_NULL(input_index.first);
  1066. if (!input_param.first->isa<Parameter>()) {
  1067. continue;
  1068. }
  1069. auto param_name = input_param.first->fullname_with_scope();
  1070. if (ps::ps_cache_instance.IsHashTable(param_name) && (kernel_name == kSparseGatherV2OpName)) {
  1071. CheckSparsePSEmbeddingCache(kernel);
  1072. }
  1073. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1074. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1075. MS_EXCEPTION_IF_NULL(input_index.first);
  1076. }
  1077. if (input_index.first == first_cache_input_index) {
  1078. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1079. MS_LOG(ERROR) << "The embeddingLookup(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1080. MS_LOG(EXCEPTION) << "All the embeddingLookups whose input indices are from dataset must enable cache at the "
  1081. "same time when one of them enables cache in parameter server training mode.";
  1082. }
  1083. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1084. if (size != first_cache_size) {
  1085. MS_LOG(ERROR) << "The cache size(" << size << ") of embeddingLookup(" << kernel->fullname_with_scope()
  1086. << ") is not the same as other embeddingLookup cache size(" << first_cache_size << ").";
  1087. MS_LOG(EXCEPTION) << "The cache sizes of embeddingLookups are not the same in parameter server training mode.";
  1088. }
  1089. } else if (ps::ps_cache_instance.IsHashTable(param_name)) {
  1090. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope() << ") cache is from "
  1091. << input_index.first->fullname_with_scope();
  1092. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1093. "parameter server training mode.";
  1094. } else if (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kGetNextOpName)) {
  1095. MS_LOG(ERROR) << "The EmbeddingLookup kernel(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1096. MS_LOG(EXCEPTION) << "All EmbeddingLookup kernels whose input indices are from dataset must enable cache at "
  1097. "the same time and parameter 'sparse' must be equal to the value of 'enable_sparse' in "
  1098. "context setting in parameter server training mode.";
  1099. }
  1100. }
  1101. }
  1102. #endif
  1103. } // namespace device
  1104. } // namespace mindspore