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

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