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