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

5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 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
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
4 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  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. constexpr float kMaxMemReuseFactor = 0.8;
  43. constexpr float kMinMemReuseFactor = 0.5;
  44. constexpr float kRetryFactor = 0.1;
  45. constexpr size_t kAtomicCleanInputSize = 2;
  46. namespace {
  47. std::vector<AnfNodePtr> GetGraphInputs(const session::KernelGraph &graph) {
  48. auto graph_inputs = graph.inputs();
  49. std::vector<AnfNodePtr> result(graph_inputs.begin(), graph_inputs.end());
  50. std::set<AnfNodePtr> inputs_set(graph_inputs.begin(), graph_inputs.end());
  51. auto kernels = graph.execution_order();
  52. for (auto &kernel : kernels) {
  53. MS_EXCEPTION_IF_NULL(kernel);
  54. auto input_num = AnfAlgo::GetInputTensorNum(kernel);
  55. for (size_t i = 0; i < input_num; ++i) {
  56. auto input_node = kernel->input(i + 1);
  57. auto input_real_node = AnfAlgo::VisitKernelWithReturnType(input_node, 0).first;
  58. MS_EXCEPTION_IF_NULL(input_real_node);
  59. if (input_real_node->isa<Parameter>() && inputs_set.find(input_real_node) == inputs_set.end()) {
  60. (void)inputs_set.insert(input_real_node);
  61. (void)result.emplace_back(input_real_node);
  62. }
  63. }
  64. }
  65. return result;
  66. }
  67. } // namespace
  68. constexpr size_t kMinInputSize = 2;
  69. KernelRuntime::~KernelRuntime() {
  70. stream_ = nullptr;
  71. independent_stream_ = nullptr;
  72. communication_stream_ = nullptr;
  73. }
  74. bool KernelRuntime::Load(const session::KernelGraph &, bool) {
  75. MS_LOG(INFO) << "Call default load.";
  76. return true;
  77. }
  78. bool KernelRuntime::LoadData(const session::KernelGraph &) {
  79. MS_LOG(INFO) << "Call default load data.";
  80. return false;
  81. }
  82. bool KernelRuntime::NodeOutputDeviceAddressExist(const AnfNodePtr &kernel, size_t index) {
  83. MS_EXCEPTION_IF_NULL(kernel);
  84. if (AnfAlgo::OutputAddrExist(kernel, index)) {
  85. const auto &address = AnfAlgo::GetOutputAddr(kernel, index);
  86. MS_EXCEPTION_IF_NULL(address);
  87. return address->DeviceType() == GetTargetDeviceAddressType();
  88. }
  89. return false;
  90. }
  91. void KernelRuntime::AssignMemory(const session::KernelGraph &graph) {
  92. auto context_ptr = MsContext::GetInstance();
  93. MS_EXCEPTION_IF_NULL(context_ptr);
  94. if (UseMemScheduler()) {
  95. AssignStaticMemoryValueNode(graph);
  96. ResetNodeAddress(graph);
  97. AssignCommunicationMem(graph);
  98. } else {
  99. MS_EXCEPTION_IF_NULL(mem_manager_);
  100. mem_manager_->ResetDynamicMemory();
  101. AssignStaticMemory(graph);
  102. AssignDynamicMemory(graph);
  103. }
  104. UpdateRefNodeOutputMem(graph);
  105. }
  106. void KernelRuntime::GetCommunicationInputInfo(const AnfNodePtr &node, size_t *total_size,
  107. DeviceAddressPtrList *address_list,
  108. std::vector<size_t> *align_size_list) const {
  109. MS_EXCEPTION_IF_NULL(node);
  110. MS_EXCEPTION_IF_NULL(total_size);
  111. MS_EXCEPTION_IF_NULL(address_list);
  112. MS_EXCEPTION_IF_NULL(align_size_list);
  113. size_t input_num = AnfAlgo::GetInputTensorNum(node);
  114. for (size_t i = 0; i < input_num; ++i) {
  115. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(node, i, true);
  116. auto input_node = input_node_with_index.first;
  117. MS_EXCEPTION_IF_NULL(input_node);
  118. DeviceAddressPtr address = nullptr;
  119. if (AnfAlgo::OutputAddrExist(input_node, input_node_with_index.second)) {
  120. address = AnfAlgo::GetMutableOutputAddr(input_node, input_node_with_index.second);
  121. } else {
  122. if (input_node->isa<CNode>()) {
  123. address = PreAssignCNodeMemory(input_node, input_node_with_index.second);
  124. } else {
  125. MS_LOG(EXCEPTION) << "Communication node inputs only support CNode";
  126. }
  127. }
  128. MS_EXCEPTION_IF_NULL(address);
  129. auto align_size = MemoryManager::GetCommonAlignSize(address->size());
  130. *total_size += align_size;
  131. address_list->emplace_back(address);
  132. align_size_list->emplace_back(align_size);
  133. }
  134. }
  135. void KernelRuntime::AssignCommunicationInputFromMemoryPool(const AnfNodePtr &node) const {
  136. if (!AnfAlgo::IsCommunicationOp(node)) {
  137. return;
  138. }
  139. MS_EXCEPTION_IF_NULL(node);
  140. MS_EXCEPTION_IF_NULL(mem_manager_);
  141. size_t total_size = 0;
  142. DeviceAddressPtrList address_list;
  143. std::vector<size_t> align_size_list;
  144. GetCommunicationInputInfo(node, &total_size, &address_list, &align_size_list);
  145. if (align_size_list.empty()) {
  146. MS_LOG(WARNING) << "No inputs for " << node->fullname_with_scope();
  147. return;
  148. }
  149. if (!mem_manager_->MallocContinuousMemFromMemPool(address_list, total_size, align_size_list)) {
  150. MS_LOG(EXCEPTION) << "Allocate continuous memory failed, totol_size:" << total_size;
  151. }
  152. }
  153. void KernelRuntime::GetCommunicationOutputInfo(const AnfNodePtr &node, size_t *total_size,
  154. DeviceAddressPtrList *address_list,
  155. std::vector<size_t> *align_size_list) const {
  156. MS_EXCEPTION_IF_NULL(node);
  157. MS_EXCEPTION_IF_NULL(total_size);
  158. MS_EXCEPTION_IF_NULL(align_size_list);
  159. MS_EXCEPTION_IF_NULL(address_list);
  160. const auto kernel_mod = AnfAlgo::GetKernelMod(node);
  161. MS_EXCEPTION_IF_NULL(kernel_mod);
  162. const auto output_size_list = kernel_mod->GetOutputSizeList();
  163. for (size_t i = 0; i < output_size_list.size(); ++i) {
  164. DeviceAddressPtr address = nullptr;
  165. if (AnfAlgo::OutputAddrExist(node, i)) {
  166. address = AnfAlgo::GetMutableOutputAddr(node, i);
  167. } else {
  168. const std::string output_format = AnfAlgo::GetOutputFormat(node, i);
  169. const auto output_type = AnfAlgo::GetOutputDeviceDataType(node, i);
  170. const auto tensor_size = AnfAlgo::GetOutputTensorMemSize(node, i);
  171. address = CreateDeviceAddress(nullptr, tensor_size, output_format, output_type, {node, i});
  172. AnfAlgo::SetOutputAddr(address, i, node.get());
  173. }
  174. MS_EXCEPTION_IF_NULL(address);
  175. auto align_size = MemoryManager::GetCommonAlignSize(address->size());
  176. *total_size += align_size;
  177. align_size_list->emplace_back(align_size);
  178. address_list->emplace_back(address);
  179. }
  180. }
  181. void KernelRuntime::AssignCommunicationOutputFromMemoryPool(const AnfNodePtr &node) const {
  182. if (!AnfAlgo::IsCommunicationOp(node)) {
  183. return;
  184. }
  185. MS_EXCEPTION_IF_NULL(node);
  186. MS_EXCEPTION_IF_NULL(mem_manager_);
  187. size_t total_size = 0;
  188. std::vector<size_t> align_size_list;
  189. std::vector<DeviceAddressPtr> address_list;
  190. GetCommunicationOutputInfo(node, &total_size, &address_list, &align_size_list);
  191. if (align_size_list.empty()) {
  192. MS_LOG(WARNING) << "No output for " << node->fullname_with_scope();
  193. return;
  194. }
  195. if (!mem_manager_->MallocContinuousMemFromMemPool(address_list, total_size, align_size_list)) {
  196. MS_LOG(EXCEPTION) << "Allocate continuous memory failed, totol_size:" << total_size;
  197. }
  198. }
  199. void KernelRuntime::RunOpMallocPre(const session::KernelGraph &graph,
  200. const std::vector<tensor::TensorPtr> &input_tensors) {
  201. const auto &nodes = graph.execution_order();
  202. // Malloc for Node output
  203. for (const auto &node : nodes) {
  204. auto output_num = AnfAlgo::GetOutputTensorNum(node);
  205. for (size_t i = 0; i < output_num; ++i) {
  206. MS_EXCEPTION_IF_NULL(node);
  207. auto runtime_info = node->user_data<session::OpRuntimeInfo>();
  208. MS_EXCEPTION_IF_NULL(runtime_info);
  209. auto const &output_format = runtime_info->output_format(i);
  210. auto output_type = runtime_info->output_type(i);
  211. auto tensor_size = runtime_info->output_tensor_size(i);
  212. // Create DeviceAddress without ptr.
  213. // Get real device ptr after KernelBuild finish.
  214. auto device_address = CreateDeviceAddress(nullptr, tensor_size, output_format, output_type);
  215. device_address->set_host_shape(trans::GetRuntimePaddingShape(node, i));
  216. AnfAlgo::SetOutputAddr(device_address, i, node.get());
  217. }
  218. }
  219. // Malloc for graph input
  220. if (input_tensors.size() != graph.inputs().size()) {
  221. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors.size()
  222. << " should be equal to graph input parameter size " << graph.inputs().size();
  223. }
  224. for (size_t input_index = 0; input_index < graph.inputs().size(); ++input_index) {
  225. auto item = graph.inputs()[input_index];
  226. MS_EXCEPTION_IF_NULL(item);
  227. if (!item->isa<Parameter>()) {
  228. continue;
  229. }
  230. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  231. for (size_t index = 0; index < output_size; index++) {
  232. auto current_tensor = input_tensors[input_index];
  233. MS_EXCEPTION_IF_NULL(current_tensor);
  234. auto output_address = std::dynamic_pointer_cast<device::DeviceAddress>(current_tensor->device_address());
  235. if (output_address != nullptr && output_address->DeviceType() == GetTargetDeviceAddressType()) {
  236. AnfAlgo::SetOutputAddr(output_address, index, item.get());
  237. continue;
  238. }
  239. auto op_runtime_info = item->user_data<session::OpRuntimeInfo>();
  240. MS_EXCEPTION_IF_NULL(op_runtime_info);
  241. TypeId output_type_id = op_runtime_info->output_type(index);
  242. auto output_tensor_size = op_runtime_info->output_tensor_size(index);
  243. auto output_format = op_runtime_info->output_format(index);
  244. auto device_address =
  245. CreateDeviceAddress(nullptr, output_tensor_size, output_format, output_type_id, {item, index});
  246. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  247. current_tensor->set_device_address(device_address);
  248. current_tensor->set_sync_status(kNeedSyncHostToDevice);
  249. }
  250. }
  251. }
  252. void KernelRuntime::ResetNodeAddress(const session::KernelGraph &kernel_graph) {
  253. auto kernels = kernel_graph.execution_order();
  254. for (auto &kernel : kernels) {
  255. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  256. MS_EXCEPTION_IF_NULL(kernel_mod);
  257. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  258. for (size_t j = 0; j < input_num; ++j) {
  259. auto input_index = AnfAlgo::GetRealInputIndex(kernel, j);
  260. KernelWithIndex kernel_with_index = AnfAlgo::GetPrevNodeOutput(kernel, input_index, true);
  261. auto index = kernel_with_index.second;
  262. auto &input_node = kernel_with_index.first;
  263. if (NodeOutputDeviceAddressExist(input_node, index)) {
  264. continue;
  265. }
  266. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(input_node, index);
  267. if (output_type_id == kTypeUnknown) {
  268. MS_LOG(WARNING) << "It is not suggested to use a lonely weight parameter as the output of graph";
  269. continue;
  270. }
  271. auto tensor_size = AnfAlgo::GetOutputTensorMemSize(input_node, index);
  272. auto device_address = CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(input_node, index),
  273. output_type_id, {input_node, index});
  274. AnfAlgo::SetOutputAddr(device_address, index, input_node.get());
  275. }
  276. auto output_sizes = kernel_mod->GetOutputSizeList();
  277. for (size_t i = 0; i < output_sizes.size(); ++i) {
  278. auto output_format = AnfAlgo::GetOutputFormat(kernel, i);
  279. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  280. AnfAlgo::SetOutputAddr(CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type), i,
  281. kernel.get());
  282. }
  283. auto workspace_sizes = kernel_mod->GetWorkspaceSizeList();
  284. for (size_t i = 0; i < workspace_sizes.size(); ++i) {
  285. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(nullptr, workspace_sizes[i], kOpFormat_DEFAULT, kNumberTypeFloat32),
  286. i, kernel.get());
  287. }
  288. }
  289. }
  290. void KernelRuntime::RunOpAssignMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  291. const session::KernelGraph &graph,
  292. const std::map<tensor::TensorPtr, session::KernelWithIndex> &tensor_to_node) {
  293. MS_EXCEPTION_IF_NULL(mem_manager_);
  294. mem_manager_->ResetDynamicMemory();
  295. for (const auto &node : graph.execution_order()) {
  296. AssignCommunicationOutputFromMemoryPool(node);
  297. AssignCommunicationInputFromMemoryPool(node);
  298. }
  299. RunOpAssignInputMemory(input_tensors, graph);
  300. AssignStaticMemoryValueNode(graph);
  301. for (const auto &node : graph.execution_order()) {
  302. RunOpAssignOutputMemory(node, tensor_to_node);
  303. RunOpAssignWorkSpaceMemory(node);
  304. }
  305. UpdateRefNodeOutputMem(graph);
  306. }
  307. void KernelRuntime::RunOpClearMemory(const session::KernelGraph &graph) const {
  308. // clear input parameter memory resource
  309. for (const auto &input_node : graph.inputs()) {
  310. MS_EXCEPTION_IF_NULL(input_node);
  311. AnfAlgo::SetOutputAddr(nullptr, 0, input_node.get());
  312. }
  313. // clear input value node memory resource
  314. for (const auto &value_node : graph.graph_value_nodes()) {
  315. MS_EXCEPTION_IF_NULL(value_node);
  316. AnfAlgo::SetOutputAddr(nullptr, 0, value_node.get());
  317. }
  318. for (const auto &cnode : graph.execution_order()) {
  319. MS_EXCEPTION_IF_NULL(cnode);
  320. // clear output memory resource
  321. size_t output_num = AnfAlgo::GetOutputTensorNum(cnode);
  322. for (size_t index = 0; index < output_num; ++index) {
  323. AnfAlgo::SetOutputAddr(nullptr, index, cnode.get());
  324. }
  325. // clear workspace memory resource
  326. auto kernel_mod = AnfAlgo::GetKernelMod(cnode);
  327. MS_EXCEPTION_IF_NULL(kernel_mod);
  328. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  329. for (size_t index = 0; index < workspace_lists.size(); ++index) {
  330. AnfAlgo::SetWorkspaceAddr(nullptr, index, cnode.get());
  331. }
  332. }
  333. }
  334. #ifdef ENABLE_DEBUGGER
  335. bool KernelRuntime::DumpDataEnabled() {
  336. auto &dump_json_parser = DumpJsonParser::GetInstance();
  337. return dump_json_parser.e2e_dump_enabled();
  338. }
  339. bool KernelRuntime::DumpDataEnabledIteration() {
  340. auto &dump_json_parser = DumpJsonParser::GetInstance();
  341. if (!dump_json_parser.e2e_dump_enabled()) {
  342. return false;
  343. }
  344. auto cur_iter = dump_json_parser.cur_dump_iter();
  345. if (dump_json_parser.IsDumpIter(cur_iter)) {
  346. return true;
  347. }
  348. return false;
  349. }
  350. #endif
  351. void KernelRuntime::AssignStaticMemory(const session::KernelGraph &graph) {
  352. AssignStaticMemoryInput(graph);
  353. AssignStaticMemoryValueNode(graph);
  354. AssignStaticMemoryOutput(graph);
  355. }
  356. void KernelRuntime::RunOpAssignInputMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  357. const session::KernelGraph &graph) {
  358. MS_EXCEPTION_IF_NULL(mem_manager_);
  359. if (input_tensors.size() != graph.inputs().size()) {
  360. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors.size()
  361. << " should be equal to graph input parameter size " << graph.inputs().size();
  362. }
  363. for (size_t input_index = 0; input_index < graph.inputs().size(); ++input_index) {
  364. auto item = graph.inputs()[input_index];
  365. MS_EXCEPTION_IF_NULL(item);
  366. if (!item->isa<Parameter>()) {
  367. continue;
  368. }
  369. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  370. for (size_t index = 0; index < output_size; index++) {
  371. auto current_tensor = input_tensors[input_index];
  372. MS_EXCEPTION_IF_NULL(current_tensor);
  373. auto output_address = std::dynamic_pointer_cast<device::DeviceAddress>(current_tensor->device_address());
  374. if (output_address != nullptr && output_address->DeviceType() == GetTargetDeviceAddressType()) {
  375. if (output_address->ptr_ == nullptr) {
  376. if (!mem_manager_->MallocMemFromMemPool(output_address, output_address->size())) {
  377. MS_LOG(EXCEPTION) << "Allocate memory failed, size:" << output_address->size();
  378. }
  379. }
  380. AnfAlgo::SetOutputAddr(output_address, index, item.get());
  381. continue;
  382. }
  383. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  384. if (output_type_id == kTypeUnknown) {
  385. output_type_id = AnfAlgo::GetOutputInferDataType(item, index);
  386. }
  387. auto tensor_size = AnfAlgo::GetOutputTensorMemSize(item, index);
  388. auto device_address =
  389. CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id, {item, index});
  390. MS_EXCEPTION_IF_NULL(device_address);
  391. MS_EXCEPTION_IF_NULL(mem_manager_);
  392. auto ret = mem_manager_->MallocMemFromMemPool(device_address, tensor_size);
  393. if (!ret) {
  394. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  395. }
  396. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  397. }
  398. }
  399. }
  400. void KernelRuntime::RunOpAssignOutputMemory(
  401. const AnfNodePtr &kernel, const std::map<tensor::TensorPtr, session::KernelWithIndex> &tensor_to_node) {
  402. MS_EXCEPTION_IF_NULL(kernel);
  403. MS_EXCEPTION_IF_NULL(mem_manager_);
  404. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  405. MS_EXCEPTION_IF_NULL(kernel_mod);
  406. auto output_sizes = kernel_mod->GetOutputSizeList();
  407. if (output_sizes.empty()) {
  408. return;
  409. }
  410. // Use device_address Allocated in RunOpMallocPre.
  411. for (auto &iter : tensor_to_node) {
  412. auto device_address = iter.first->device_address();
  413. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(device_address), iter.second.second,
  414. iter.second.first.get());
  415. }
  416. for (size_t i = 0; i < output_sizes.size(); ++i) {
  417. if (AnfAlgo::OutputAddrExist(kernel, i, false)) {
  418. auto address = AnfAlgo::GetMutableOutputAddr(kernel, i, false);
  419. MS_EXCEPTION_IF_NULL(address);
  420. if (address->ptr() == nullptr) {
  421. MS_EXCEPTION_IF_NULL(mem_manager_);
  422. if (!mem_manager_->MallocMemFromMemPool(address, address->size())) {
  423. MS_LOG(EXCEPTION) << "Allocate memory failed, size:" << address->size();
  424. }
  425. }
  426. continue;
  427. }
  428. if (AnfAlgo::GetCNodeName(kernel) == kApplyMomentumOpName) {
  429. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i);
  430. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  431. continue;
  432. }
  433. std::string output_format = AnfAlgo::GetOutputFormat(kernel, i);
  434. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  435. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type, {kernel, i});
  436. device_address->set_host_shape(trans::GetRuntimePaddingShape(kernel, i));
  437. MS_EXCEPTION_IF_NULL(device_address);
  438. auto ret = mem_manager_->MallocMemFromMemPool(device_address, output_sizes[i]);
  439. if (!ret) {
  440. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << output_sizes[i];
  441. }
  442. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  443. }
  444. }
  445. void KernelRuntime::RunOpAssignWorkSpaceMemory(const AnfNodePtr &kernel) {
  446. MS_EXCEPTION_IF_NULL(kernel);
  447. MS_EXCEPTION_IF_NULL(mem_manager_);
  448. if (kernel->isa<CNode>()) {
  449. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  450. MS_EXCEPTION_IF_NULL(kernel_mod);
  451. auto workspace_lists = kernel_mod->GetWorkspaceSizeList();
  452. for (size_t i = 0; i < workspace_lists.size(); ++i) {
  453. auto device_address = CreateDeviceAddress(nullptr, workspace_lists[i], "", kTypeUnknown);
  454. MS_EXCEPTION_IF_NULL(device_address);
  455. auto ret = mem_manager_->MallocMemFromMemPool(device_address, workspace_lists[i]);
  456. if (!ret) {
  457. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << workspace_lists[i];
  458. }
  459. AnfAlgo::SetWorkspaceAddr(device_address, i, kernel.get());
  460. }
  461. }
  462. }
  463. void KernelRuntime::RunOpAssignOutputNodeMemory(const ValuePtr &pre_output_value, const session::KernelGraph &graph) {
  464. if (pre_output_value == nullptr) {
  465. return;
  466. }
  467. std::vector<tensor::TensorPtr> pre_output_tensors;
  468. TensorValueToTensor(pre_output_value, &pre_output_tensors);
  469. auto output_nodes = graph.outputs();
  470. if (pre_output_tensors.size() != output_nodes.size()) {
  471. MS_LOG(EXCEPTION) << "The size of pre output tensors [" << pre_output_tensors.size()
  472. << "] is not equal to the size of output nodes of graph [" << output_nodes.size() << "]";
  473. }
  474. // share output address with pre output tensors
  475. for (size_t i = 0; i < output_nodes.size(); ++i) {
  476. auto output_node_with_index = AnfAlgo::VisitKernel(output_nodes[i], 0);
  477. auto output_node = output_node_with_index.first;
  478. MS_EXCEPTION_IF_NULL(output_node);
  479. if (!output_node->isa<CNode>()) {
  480. if (output_node->isa<Parameter>()) {
  481. auto param = output_node->cast<ParameterPtr>();
  482. if (param != nullptr && !param->has_default()) {
  483. MS_LOG(EXCEPTION) << "The output parameter should be real parameter!";
  484. }
  485. }
  486. continue;
  487. }
  488. auto real_output_cnode = output_node->cast<CNodePtr>();
  489. MS_EXCEPTION_IF_NULL(real_output_cnode);
  490. MS_EXCEPTION_IF_NULL(pre_output_tensors[i]);
  491. if (pre_output_tensors[i]->device_address() == nullptr) {
  492. MS_LOG(INFO) << "The address of pre output tensor [" << i << "] is a nullptr!";
  493. continue;
  494. }
  495. if (opt::IsNopNode(real_output_cnode)) {
  496. if (real_output_cnode->inputs().size() < kMinInputSize) {
  497. MS_LOG(EXCEPTION) << "The input size of output node: " << real_output_cnode->DebugString()
  498. << " should large than one!";
  499. }
  500. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(pre_output_tensors[i]->device_address()),
  501. output_node_with_index.second, real_output_cnode->input(1).get());
  502. } else {
  503. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(pre_output_tensors[i]->device_address()),
  504. output_node_with_index.second, output_node_with_index.first.get());
  505. }
  506. }
  507. }
  508. void KernelRuntime::AssignStaticMemoryInput(const session::KernelGraph &graph) {
  509. MS_EXCEPTION_IF_NULL(mem_manager_);
  510. MS_LOG(INFO) << "AssignStaticMemoryInput start for graph " << graph.graph_id();
  511. auto graph_inputs = GetGraphInputs(graph);
  512. auto graph_valid_input = graph.valid_inputs();
  513. graph_inputs.insert(graph_inputs.end(), graph.child_graph_result().begin(), graph.child_graph_result().end());
  514. std::vector<AnfNodePtr> need_alloc_nodes;
  515. auto add_need_alloc_nodes = [&need_alloc_nodes, graph, this](const AnfNodePtr &node) {
  516. MS_EXCEPTION_IF_NULL(node);
  517. if (!node->isa<Parameter>()) {
  518. return;
  519. }
  520. if (NodeOutputDeviceAddressExist(node, 0)) {
  521. return;
  522. }
  523. auto input_param = node->cast<ParameterPtr>();
  524. if (input_param != nullptr && !input_param->IsUsedByRealKernelInGraph(graph.graph_id())) {
  525. return;
  526. }
  527. need_alloc_nodes.push_back(node);
  528. };
  529. for (size_t i = 0; i < graph_inputs.size(); ++i) {
  530. auto input_node = graph_inputs[i];
  531. MS_EXCEPTION_IF_NULL(input_node);
  532. if (i < graph_valid_input.size() && !graph_valid_input[i]) {
  533. continue;
  534. }
  535. if (AnfAlgo::CheckPrimitiveType(input_node, prim::kPrimMakeTuple)) {
  536. auto outs = AnfAlgo::GetAllOutput(input_node);
  537. for (auto &out : outs) {
  538. MS_EXCEPTION_IF_NULL(out);
  539. add_need_alloc_nodes(out);
  540. }
  541. }
  542. add_need_alloc_nodes(input_node);
  543. }
  544. #if ((defined ENABLE_CPU) && (!defined _WIN32))
  545. bool ps_cache_check = false;
  546. #endif
  547. for (auto &item : need_alloc_nodes) {
  548. MS_EXCEPTION_IF_NULL(item);
  549. auto output_size = AnfAlgo::GetOutputTensorNum(item);
  550. for (size_t index = 0; index < output_size; index++) {
  551. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  552. // if graph output is a weight and doesn't link to any cnode, it's data type will be unknown
  553. if (output_type_id == kTypeUnknown) {
  554. MS_LOG(WARNING) << "It is not suggested to use a lonely weight parameter as the output of graph";
  555. continue;
  556. }
  557. DeviceAddressPtr device_address = nullptr;
  558. #if ((defined ENABLE_CPU) && (!defined _WIN32))
  559. const std::string &param_name = item->fullname_with_scope();
  560. if (ps::ps_cache_instance.IsHashTable(param_name)) {
  561. MS_LOG(INFO) << "Parameter(" << param_name << ")"
  562. << " enables the embeddingLookup cache in parameter server training mode.";
  563. // PS embeddingLookup cache check.
  564. if (!ps_cache_check) {
  565. CheckIfSupportPSEmbeddingCache(graph);
  566. ps_cache_check = true;
  567. }
  568. const auto &address = ps::ps_cache_instance.QueryHashTableAddr(param_name);
  569. MS_EXCEPTION_IF_NULL(address.addr);
  570. device_address = CreateDeviceAddress(address.addr, address.size, AnfAlgo::GetOutputFormat(item, index),
  571. output_type_id, {item, index});
  572. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  573. continue;
  574. }
  575. #endif
  576. auto tensor_size = AnfAlgo::GetOutputTensorMemSize(item, index);
  577. device_address =
  578. CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id, {item, index});
  579. MS_LOG(INFO) << "Assign Static Memory for Input node, size:" << tensor_size
  580. << " node:" << item->fullname_with_scope() << " index: " << index;
  581. if (mem_manager_->MallocMem(kStaticMem, tensor_size, device_address, graph.graph_id()) == nullptr) {
  582. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  583. }
  584. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  585. }
  586. }
  587. MS_LOG(INFO) << "AssignStaticMemoryInput end";
  588. }
  589. void KernelRuntime::AssignStaticMemoryOutput(const session::KernelGraph &graph) {
  590. MS_LOG(INFO) << "AssignStaticMemoryOutput start for graph " << graph.graph_id();
  591. auto nodes = AnfAlgo::GetAllOutput(graph.output(), {prim::kPrimTupleGetItem});
  592. std::vector<session::KernelWithIndex> non_communication_op;
  593. // Assign Communicate Op Memory firstly.
  594. for (const auto &node : nodes) {
  595. auto kernel_with_index = AnfAlgo::VisitKernelWithReturnType(node, 0, true);
  596. MS_EXCEPTION_IF_NULL(kernel_with_index.first);
  597. if (!kernel_with_index.first->isa<CNode>() || !AnfUtils::IsRealKernel(kernel_with_index.first)) {
  598. continue;
  599. }
  600. if (AnfAlgo::IsCommunicationOp(kernel_with_index.first)) {
  601. AssignCommunicationNodeMem(kStaticMem, kernel_with_index.first);
  602. } else {
  603. non_communication_op.emplace_back(kernel_with_index);
  604. }
  605. }
  606. for (const auto &item_with_index : non_communication_op) {
  607. MS_EXCEPTION_IF_NULL(item_with_index.first);
  608. MS_LOG(DEBUG) << "AssignNodeOutputMem for " << item_with_index.first->fullname_with_scope();
  609. AssignNodeOutputMem(kStaticMem, item_with_index.first, SizeToInt(item_with_index.second));
  610. }
  611. MS_LOG(INFO) << "AssignStaticMemoryOutput end";
  612. }
  613. void KernelRuntime::UpdateRefNodeOutputMem(const session::KernelGraph &graph) {
  614. auto &kernels = graph.execution_order();
  615. for (auto &kernel : kernels) {
  616. MS_EXCEPTION_IF_NULL(kernel);
  617. auto output_num = AnfAlgo::GetOutputTensorNum(kernel);
  618. if (output_num == 0) {
  619. MS_LOG(DEBUG) << "This kernel has no output size.";
  620. continue;
  621. }
  622. for (size_t i = 0; i < output_num; ++i) {
  623. session::AnfWithOutIndex out_pair(kernel, i);
  624. if (graph.IsInRefOutputMap(out_pair)) {
  625. auto origin_pair = graph.GetRefCorrespondOutput(out_pair);
  626. MS_EXCEPTION_IF_NULL(origin_pair.first);
  627. auto origin_node_output_addr = AnfAlgo::GetMutableOutputAddr(origin_pair.first, origin_pair.second);
  628. MS_EXCEPTION_IF_NULL(origin_node_output_addr);
  629. auto cur_node_output_addr = AnfAlgo::GetMutableOutputAddr(kernel, i);
  630. if (origin_node_output_addr.get() != cur_node_output_addr.get()) {
  631. MS_LOG(DEBUG) << "REF address is not same, ref node output need address update";
  632. MS_LOG(DEBUG) << "REF origin op is " << origin_pair.first->DebugString() << ", output index is "
  633. << origin_pair.second << ", cur op is " << kernel->DebugString() << ", out index is " << i;
  634. AnfAlgo::SetOutputAddr(origin_node_output_addr, i, kernel.get());
  635. }
  636. }
  637. }
  638. }
  639. }
  640. void KernelRuntime::AssignCommunicationNodeMem(MemType type, const AnfNodePtr &node) {
  641. AssignCommunicationNodeInputMem(type, node);
  642. AssignCommunicationNodeOutputMem(type, node);
  643. AssignWorkSpaceMem(type, node);
  644. }
  645. void KernelRuntime::AssignCommunicationNodeOutputMem(MemType type, const AnfNodePtr &node) {
  646. MS_EXCEPTION_IF_NULL(node);
  647. MS_EXCEPTION_IF_NULL(mem_manager_);
  648. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  649. MS_EXCEPTION_IF_NULL(kernel_mod);
  650. auto output_sizes = kernel_mod->GetOutputSizeList();
  651. if (output_sizes.empty()) {
  652. MS_LOG(INFO) << "This kernel[" << node->DebugString() << "] has no output size.";
  653. return;
  654. }
  655. auto context_ptr = MsContext::GetInstance();
  656. MS_EXCEPTION_IF_NULL(context_ptr);
  657. size_t total_size = 0;
  658. size_t output_index = 0;
  659. std::vector<size_t> align_size_list;
  660. for (uint64_t mem_size : output_sizes) {
  661. if (AnfAlgo::OutputAddrExist(node, output_index++)) {
  662. MS_LOG(INFO) << "Communication op " << node->fullname_with_scope() << " has output device address";
  663. return;
  664. }
  665. if (context_ptr->get_param<bool>(MS_CTX_ENABLE_HCCL)) {
  666. mem_size = MemoryManager::GetCommonAlignSize(mem_size);
  667. }
  668. total_size += mem_size;
  669. align_size_list.emplace_back(mem_size);
  670. }
  671. if (align_size_list.empty()) {
  672. return;
  673. }
  674. if (type == kSomasReuseDynamicMem) {
  675. bool not_reuse = KernelMemNotReuse(node);
  676. if (not_reuse) {
  677. type = kDynamicMem;
  678. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  679. }
  680. }
  681. uint8_t *output_ptr = nullptr;
  682. for (size_t j = 0; j < align_size_list.size(); ++j) {
  683. std::string output_format = AnfAlgo::GetOutputFormat(node, j);
  684. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, j);
  685. auto address = CreateDeviceAddress(nullptr, output_sizes[j], output_format, output_type, {node, j});
  686. MS_EXCEPTION_IF_NULL(address);
  687. if (output_ptr == nullptr) {
  688. output_ptr = mem_manager_->MallocOutputMem(node, 0, type, total_size, address, true);
  689. MS_EXCEPTION_IF_NULL(output_ptr);
  690. } else {
  691. address->set_ptr(output_ptr);
  692. }
  693. AnfAlgo::SetOutputAddr(address, j, node.get());
  694. output_ptr += align_size_list[j];
  695. }
  696. }
  697. bool KernelRuntime::KernelMemNotReuse(const AnfNodePtr &node) {
  698. MS_EXCEPTION_IF_NULL(node);
  699. return false;
  700. }
  701. DeviceAddressPtr KernelRuntime::PreAssignCNodeMemory(const AnfNodePtr &anf_node, size_t index) const {
  702. MS_EXCEPTION_IF_NULL(anf_node);
  703. if (!anf_node->isa<CNode>()) {
  704. MS_LOG(EXCEPTION) << "anf_node should be a cnode";
  705. }
  706. auto cnode = anf_node->cast<CNodePtr>();
  707. MS_EXCEPTION_IF_NULL(cnode);
  708. if (opt::IsNopNode(cnode)) {
  709. const size_t kNopNodeInputSize = 2;
  710. if (cnode->size() != kNopNodeInputSize) {
  711. MS_LOG(EXCEPTION) << cnode->fullname_with_scope() << " has invalid input size: " << cnode->size();
  712. }
  713. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(anf_node, index);
  714. return PreAssignCNodeMemory(input_node_with_index.first, input_node_with_index.second);
  715. }
  716. auto kernel_mod = AnfAlgo::GetKernelMod(anf_node);
  717. MS_EXCEPTION_IF_NULL(kernel_mod);
  718. auto output_sizes = kernel_mod->GetOutputSizeList();
  719. if (output_sizes.size() <= index) {
  720. MS_LOG(EXCEPTION) << "Previous node output size " << output_sizes.size() << " <= node index " << index;
  721. }
  722. std::string output_format = AnfAlgo::GetOutputFormat(anf_node, index);
  723. auto output_type = AnfAlgo::GetOutputDeviceDataType(anf_node, index);
  724. auto address = CreateDeviceAddress(nullptr, output_sizes[index], output_format, output_type, {anf_node, index});
  725. AnfAlgo::SetOutputAddr(address, index, anf_node.get());
  726. return address;
  727. }
  728. void KernelRuntime::AssignCommunicationNodeInputMem(MemType type, const AnfNodePtr &node) {
  729. auto context_ptr = MsContext::GetInstance();
  730. MS_EXCEPTION_IF_NULL(context_ptr);
  731. MS_EXCEPTION_IF_NULL(node);
  732. MS_EXCEPTION_IF_NULL(mem_manager_);
  733. size_t total_size = 0;
  734. std::vector<std::pair<DeviceAddressPtr, size_t>> addr_size;
  735. size_t input_num = AnfAlgo::GetInputTensorNum(node);
  736. for (size_t i = 0; i < input_num; ++i) {
  737. auto input_node_with_index = AnfAlgo::GetPrevNodeOutput(node, i, true);
  738. auto input_node = input_node_with_index.first;
  739. MS_EXCEPTION_IF_NULL(input_node);
  740. if (AnfAlgo::OutputAddrExist(input_node, input_node_with_index.second)) {
  741. MS_LOG(INFO) << "Communication op " << input_node->fullname_with_scope() << " has input device address";
  742. return;
  743. }
  744. DeviceAddressPtr address = nullptr;
  745. if (input_node->isa<CNode>()) {
  746. address = PreAssignCNodeMemory(input_node, input_node_with_index.second);
  747. } else {
  748. MS_LOG(EXCEPTION) << "Communication node inputs only support CNode";
  749. }
  750. MS_EXCEPTION_IF_NULL(address);
  751. auto mem_size = MemoryManager::GetCommonAlignSize(address->size());
  752. total_size += mem_size;
  753. addr_size.emplace_back(address, mem_size);
  754. }
  755. if (addr_size.empty()) {
  756. return;
  757. }
  758. if (type == kSomasReuseDynamicMem) {
  759. bool not_reuse = KernelMemNotReuse(node);
  760. if (not_reuse) {
  761. type = kDynamicMem;
  762. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s input.";
  763. }
  764. }
  765. auto cnode = node->cast<CNodePtr>();
  766. MS_EXCEPTION_IF_NULL(cnode);
  767. if (cnode->inputs().size() < kMinInputSize) {
  768. // communication node's input should contain itself and at least on input
  769. MS_LOG(ERROR) << "No inputs for " << cnode->fullname_with_scope();
  770. return;
  771. }
  772. auto first_input_node = cnode->input(1);
  773. auto prenode_index = AnfAlgo::VisitKernelWithReturnType(first_input_node, 0, true);
  774. uint8_t *input_ptr = mem_manager_->MallocOutputMem(prenode_index.first, prenode_index.second, type, total_size,
  775. addr_size[0].first, true);
  776. for (const auto &iter : addr_size) {
  777. MS_EXCEPTION_IF_NULL(iter.first);
  778. iter.first->set_ptr(input_ptr);
  779. input_ptr += iter.second;
  780. }
  781. }
  782. void KernelRuntime::AssignNodeOutputMem(MemType type, const AnfNodePtr &node, int index) {
  783. MS_EXCEPTION_IF_NULL(node);
  784. MS_EXCEPTION_IF_NULL(mem_manager_);
  785. if (type == kSomasReuseDynamicMem) {
  786. bool not_reuse = KernelMemNotReuse(node);
  787. if (not_reuse) {
  788. type = kDynamicMem;
  789. MS_LOG(INFO) << "Disable Memory Reuse for " << node->fullname_with_scope() << "'s output.";
  790. }
  791. }
  792. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  793. MS_EXCEPTION_IF_NULL(kernel_mod);
  794. auto output_sizes = kernel_mod->GetOutputSizeList();
  795. if (output_sizes.empty()) {
  796. return;
  797. }
  798. for (size_t i = 0; i < output_sizes.size(); ++i) {
  799. if ((kGetAllOuts != index) && (SizeToInt(i) != index)) {
  800. continue;
  801. }
  802. if (NodeOutputDeviceAddressExist(node, i)) {
  803. MS_LOG(INFO) << "Already malloc index:" << i;
  804. continue;
  805. }
  806. MS_LOG(DEBUG) << "Assign Node:" << node->fullname_with_scope() << " output memory size:" << output_sizes[i];
  807. if (type == kStaticMem) {
  808. MS_LOG(INFO) << "Assign Static Memory for Output node, size:" << output_sizes[i]
  809. << " node:" << node->fullname_with_scope();
  810. }
  811. std::string output_format = AnfAlgo::GetOutputFormat(node, i);
  812. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, i);
  813. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type, {node, i});
  814. MS_EXCEPTION_IF_NULL(device_address);
  815. uint8_t *ptr = mem_manager_->MallocOutputMem(node, i, type, output_sizes[i], device_address, false);
  816. MS_EXCEPTION_IF_NULL(ptr);
  817. device_address->set_host_shape(trans::GetRuntimePaddingShape(node, i));
  818. AnfAlgo::SetOutputAddr(device_address, i, node.get());
  819. }
  820. }
  821. DeviceAddressPtr KernelRuntime::AssignExtraStaticMem(const TensorPtr &tensor, const AnfNodePtr &node, size_t index) {
  822. MS_EXCEPTION_IF_NULL(node);
  823. MS_EXCEPTION_IF_NULL(mem_manager_);
  824. auto tensor_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  825. MS_LOG(DEBUG) << "Assign Node:" << node->fullname_with_scope()
  826. << "Assign Static Memory for Output node, size:" << tensor_address->size();
  827. auto device_address = CreateDeviceAddress(nullptr, tensor_address->size(), tensor_address->format(),
  828. tensor_address->type_id(), {node, index});
  829. MS_EXCEPTION_IF_NULL(device_address);
  830. uint8_t *ptr = mem_manager_->MallocOutputMem(node, index, kStaticMem, tensor_address->size(), device_address, false);
  831. MS_EXCEPTION_IF_NULL(ptr);
  832. return device_address;
  833. }
  834. void KernelRuntime::AssignValueNodeTensor(const ValueNodePtr &value_node, const ValuePtr &node_value,
  835. size_t output_idx) {
  836. MS_EXCEPTION_IF_NULL(value_node);
  837. MS_EXCEPTION_IF_NULL(node_value);
  838. MS_EXCEPTION_IF_NULL(mem_manager_);
  839. auto ms_context = MsContext::GetInstance();
  840. MS_EXCEPTION_IF_NULL(ms_context);
  841. std::vector<tensor::TensorPtr> tensors;
  842. TensorValueToTensor(node_value, &tensors);
  843. // Graph id should be passed to record static memory if profiling is enabled.
  844. auto kernel_info = dynamic_cast<device::KernelInfo *>(value_node->kernel_info());
  845. MS_EXCEPTION_IF_NULL(kernel_info);
  846. uint32_t graph_id = kernel_info->graph_id();
  847. for (const auto &tensor : tensors) {
  848. if (tensor == nullptr) {
  849. MS_LOG(WARNING) << "Tensor is null";
  850. return;
  851. }
  852. auto output_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  853. if (output_address != nullptr && output_address->DeviceType() == GetTargetDeviceAddressType()) {
  854. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), output_idx++,
  855. value_node.get());
  856. continue;
  857. }
  858. size_t tensor_size = LongToSize(tensor->data().nbytes());
  859. auto node_size = AnfAlgo::GetOutputTensorMemSize(value_node, output_idx);
  860. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(value_node, output_idx);
  861. if (output_type_id == kTypeUnknown) {
  862. output_type_id = AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  863. }
  864. auto output_format = AnfAlgo::GetOutputFormat(value_node, output_idx);
  865. DeviceAddressPtr address =
  866. CreateDeviceAddress(nullptr, node_size, output_format, output_type_id, {value_node, output_idx});
  867. MS_EXCEPTION_IF_NULL(address);
  868. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  869. !mem_manager_->MallocMemFromMemPool(address, node_size)) {
  870. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << node_size;
  871. } else {
  872. MS_LOG(INFO) << "Assign Static Memory for Value node, size:" << node_size
  873. << " node:" << value_node->fullname_with_scope();
  874. if (mem_manager_->MallocMem(kStaticMem, node_size, address, graph_id) == nullptr) {
  875. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << node_size;
  876. }
  877. }
  878. AnfAlgo::SetOutputAddr(address, output_idx, value_node.get());
  879. if (!address->SyncHostToDevice(trans::GetRuntimePaddingShape(value_node, 0), tensor_size, tensor->data_type(),
  880. tensor->data_c(), tensor->device_info().host_format_)) {
  881. MS_EXCEPTION(NotExistsError) << "ValueNode SyncHostToDevice fail!" << value_node->DebugString()
  882. << "node format is" << AnfAlgo::GetOutputFormat(value_node, output_idx)
  883. << "node dtype is " << AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  884. }
  885. }
  886. }
  887. void KernelRuntime::AssignStaticMemoryValueNode(const session::KernelGraph &graph) {
  888. MS_EXCEPTION_IF_NULL(mem_manager_);
  889. MS_LOG(DEBUG) << "AssignStaticMemoryValueNode start for graph " << graph.graph_id();
  890. auto ms_context = MsContext::GetInstance();
  891. MS_EXCEPTION_IF_NULL(ms_context);
  892. // order the value nodes
  893. std::map<std::string, ValueNodePtr> value_nodes_map;
  894. for (auto &node : graph.graph_value_nodes()) {
  895. MS_EXCEPTION_IF_NULL(node);
  896. value_nodes_map[node->fullname_with_scope()] = node;
  897. }
  898. for (auto &item : value_nodes_map) {
  899. auto value_node = item.second;
  900. MS_EXCEPTION_IF_NULL(value_node);
  901. if (NodeOutputDeviceAddressExist(value_node, 0)) {
  902. MS_LOG(DEBUG) << "value_node[" << value_node->DebugString() << "] address already exist";
  903. auto device_address = AnfAlgo::GetMutableOutputAddr(value_node, 0);
  904. if (device_address->ptr_ == nullptr) {
  905. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER)) {
  906. if (!mem_manager_->MallocMemFromMemPool(device_address, device_address->size_)) {
  907. MS_LOG(EXCEPTION) << "MallocMemFromMemPool failed";
  908. }
  909. } else {
  910. if (mem_manager_->MallocMem(kStaticMem, device_address->size_, device_address, graph.graph_id())) {
  911. MS_LOG(EXCEPTION) << "MallocMem kStaticMem failed";
  912. }
  913. }
  914. }
  915. continue;
  916. }
  917. auto &node_value = value_node->value();
  918. MS_EXCEPTION_IF_NULL(node_value);
  919. MS_LOG(DEBUG) << "Malloc memory for " << value_node->fullname_with_scope();
  920. if (node_value->isa<Tensor>() || node_value->isa<ValueTuple>()) {
  921. AssignValueNodeTensor(value_node, node_value, 0);
  922. } else if (node_value->isa<StringImm>()) {
  923. const bool use_mem_from_memory_pool = ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) ||
  924. ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode;
  925. auto address = CreateDeviceAddressForStringValue(node_value, use_mem_from_memory_pool, graph.graph_id());
  926. MS_EXCEPTION_IF_NULL(address);
  927. AnfAlgo::SetOutputAddr(address, 0, value_node.get());
  928. }
  929. }
  930. MS_LOG(DEBUG) << "AssignStaticMemoryValueNode end";
  931. }
  932. DeviceAddressPtr KernelRuntime::CreateDeviceAddressForStringValue(const ValuePtr &value, bool use_mem_pool,
  933. uint32_t graph_id) {
  934. auto value_string = GetValue<std::string>(value);
  935. size_t tensor_size = value_string.size();
  936. DeviceAddressPtr address = CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8);
  937. MS_EXCEPTION_IF_NULL(address);
  938. auto ms_context = MsContext::GetInstance();
  939. MS_EXCEPTION_IF_NULL(ms_context);
  940. if (use_mem_pool && !mem_manager_->MallocMemFromMemPool(address, tensor_size)) {
  941. MS_LOG(EXCEPTION) << "Device memory isn't enough and alloc failed, alloc size:" << tensor_size;
  942. } else {
  943. MS_LOG(INFO) << "Assign Static Memory for string Value node, size:" << tensor_size;
  944. if (mem_manager_->MallocMem(kStaticMem, tensor_size, address, graph_id) == nullptr) {
  945. MS_LOG(EXCEPTION) << "Cannot alloc address when flag is: " << kStaticMem << ", tensor size is: " << tensor_size;
  946. }
  947. }
  948. ShapeVector shape = {1, SizeToLong(tensor_size)};
  949. if (!address->SyncHostToDevice(shape, tensor_size, kNumberTypeUInt8, value_string.data())) {
  950. MS_LOG(EXCEPTION) << "kValueNode SyncHostToDevice fail!";
  951. }
  952. return address;
  953. }
  954. void KernelRuntime::AssignDynamicMemory(const session::KernelGraph &graph) {
  955. MS_EXCEPTION_IF_NULL(mem_manager_);
  956. auto context_ptr = MsContext::GetInstance();
  957. MS_EXCEPTION_IF_NULL(context_ptr);
  958. bool is_enable_mem_reuse = EnvConfigParser::GetInstance().GetSysMemreuse();
  959. auto mem_type = kDynamicMem;
  960. auto &dump_json_parser = DumpJsonParser::GetInstance();
  961. if (dump_json_parser.e2e_dump_enabled() && dump_json_parser.dump_mode() == 0) {
  962. mindspore::EnvConfigParser::GetInstance().SetSysMemreuse(false);
  963. is_enable_mem_reuse = false;
  964. MS_LOG(INFO) << "Disable Memory Reuse when e2e dump is enable and dump mode is set to dump all kernels";
  965. }
  966. if (is_enable_mem_reuse) {
  967. MS_LOG(INFO) << "Memory Reuse is enable...";
  968. mem_manager_->MallocSomasDynamicMem(graph);
  969. mem_type = kSomasReuseDynamicMem;
  970. } else {
  971. MS_LOG(INFO) << "Memory Reuse is disable...";
  972. }
  973. auto &execution_nodes = graph.execution_order();
  974. std::vector<CNodePtr> compute_nodes;
  975. // communication nodes first
  976. for (auto &node : execution_nodes) {
  977. if (AnfAlgo::IsCommunicationOp(node)) {
  978. // skip if the memory is already allocated
  979. AssignCommunicationNodeMem(mem_type, node);
  980. } else {
  981. compute_nodes.emplace_back(node);
  982. }
  983. }
  984. // then compute nodes
  985. for (auto &node : compute_nodes) {
  986. AssignNodeOutputMem(mem_type, node, kGetAllOuts);
  987. AssignWorkSpaceMem(mem_type, node);
  988. }
  989. }
  990. void KernelRuntime::AssignWorkSpaceMem(MemType type, const AnfNodePtr &node) {
  991. MS_EXCEPTION_IF_NULL(node);
  992. MS_EXCEPTION_IF_NULL(mem_manager_);
  993. auto kernel_mod = AnfAlgo::GetKernelMod(node);
  994. MS_EXCEPTION_IF_NULL(kernel_mod);
  995. size_t index = 0;
  996. for (auto &size : kernel_mod->GetWorkspaceSizeList()) {
  997. if (AnfAlgo::WorkspaceAddrExist(node, index)) {
  998. MS_LOG(INFO) << "Op " << node->fullname_with_scope() << " has workspace device address";
  999. return;
  1000. }
  1001. auto ptr = mem_manager_->MallocWorkSpaceMem(node, index, type, size);
  1002. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(ptr, size, "", kTypeUnknown), index, node.get());
  1003. index++;
  1004. }
  1005. }
  1006. void KernelRuntime::GenLaunchArgs(const mindspore::kernel::KernelMod &kernel_mod, const mindspore::AnfNodePtr &kernel,
  1007. KernelLaunchInfo *kernel_launch_info) {
  1008. MS_EXCEPTION_IF_NULL(kernel);
  1009. MS_EXCEPTION_IF_NULL(kernel_launch_info);
  1010. auto cnode = kernel->cast<CNodePtr>();
  1011. MS_EXCEPTION_IF_NULL(cnode);
  1012. if (AnfAlgo::GetCNodeName(cnode) == kAtomicAddrCleanOpName) {
  1013. return GenAddrCleanLaunchArgs(cnode, &(kernel_launch_info->inputs_));
  1014. }
  1015. auto ms_context = MsContext::GetInstance();
  1016. MS_EXCEPTION_IF_NULL(ms_context);
  1017. auto skip_nop_node = (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode);
  1018. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  1019. for (size_t i = 0; i < input_num; ++i) {
  1020. auto op_name = AnfAlgo::GetCNodeName(cnode);
  1021. constexpr auto none_placeholder_index = 3;
  1022. if (op_name == kDynamicRNNOpName && i == none_placeholder_index) {
  1023. continue;
  1024. }
  1025. if (op_name == kDynamicGRUV2OpName) {
  1026. auto none_index = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(cnode, "placeholder_index");
  1027. auto item = std::find(none_index.begin(), none_index.end(), i);
  1028. if (item != none_index.end()) {
  1029. continue;
  1030. }
  1031. }
  1032. auto real_input = AnfAlgo::GetRealInputIndex(kernel, i);
  1033. auto device_address = AnfAlgo::GetPrevNodeOutputAddr(kernel, real_input, skip_nop_node);
  1034. MS_EXCEPTION_IF_NULL(device_address);
  1035. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  1036. MS_EXCEPTION_IF_NULL(input);
  1037. input->addr = device_address->ptr_;
  1038. MS_EXCEPTION_IF_NULL(input->addr);
  1039. input->size = device_address->size_;
  1040. kernel_launch_info->inputs_.emplace_back(input);
  1041. }
  1042. for (size_t i = 0; i < kernel_mod.GetOutputSizeList().size(); ++i) {
  1043. auto device_address = AnfAlgo::GetOutputAddr(kernel, i, skip_nop_node);
  1044. kernel::AddressPtr output = std::make_shared<kernel::Address>();
  1045. MS_EXCEPTION_IF_NULL(output);
  1046. output->addr = device_address->ptr_;
  1047. MS_EXCEPTION_IF_NULL(output->addr);
  1048. output->size = device_address->size_;
  1049. kernel_launch_info->outputs_.emplace_back(output);
  1050. }
  1051. for (size_t i = 0; i < kernel_mod.GetWorkspaceSizeList().size(); ++i) {
  1052. auto device_address = AnfAlgo::GetWorkspaceAddr(kernel, i);
  1053. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  1054. MS_EXCEPTION_IF_NULL(workspace);
  1055. workspace->addr = device_address->ptr_;
  1056. MS_EXCEPTION_IF_NULL(workspace->addr);
  1057. workspace->size = device_address->size_;
  1058. kernel_launch_info->workspaces_.emplace_back(workspace);
  1059. }
  1060. }
  1061. bool KernelRuntime::UseMemScheduler() {
  1062. auto context_ptr = MsContext::GetInstance();
  1063. MS_EXCEPTION_IF_NULL(context_ptr);
  1064. if (!context_ptr->get_param<bool>(MS_CTX_ENABLE_MEM_SCHEDULER)) {
  1065. return false;
  1066. }
  1067. // Not use MemScheduler when running single op
  1068. return (!context_ptr->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER) &&
  1069. (context_ptr->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode));
  1070. }
  1071. void KernelRuntime::GenKernelEvents(const session::KernelGraph &graph) {
  1072. auto &kernels = graph.execution_order();
  1073. if (kernels.empty() || graph_kernel_events_map_.find(graph.graph_id()) != graph_kernel_events_map_.end()) {
  1074. return;
  1075. }
  1076. auto kernel_events = std::pair<std::map<AnfNodePtr, std::vector<std::function<void()>>>,
  1077. std::map<AnfNodePtr, std::vector<std::function<void()>>>>();
  1078. auto &kernel_pre_run_events = kernel_events.first;
  1079. auto &kernel_post_run_events = kernel_events.second;
  1080. for (size_t i = 0; i < kernels.size(); ++i) {
  1081. auto &kernel = kernels[i];
  1082. if (!AnfAlgo::IsCommunicationOp(kernel)) {
  1083. continue;
  1084. }
  1085. auto pre_event = CreateDeviceEvent();
  1086. auto post_event = CreateDeviceEvent();
  1087. MS_EXCEPTION_IF_NULL(pre_event);
  1088. MS_EXCEPTION_IF_NULL(post_event);
  1089. pre_event->set_wait_stream(communication_stream_);
  1090. pre_event->set_record_stream(stream_);
  1091. post_event->set_wait_stream(stream_);
  1092. post_event->set_record_stream(communication_stream_);
  1093. kernel_pre_run_events[kernel].emplace_back([pre_event]() {
  1094. pre_event->RecordEvent();
  1095. pre_event->WaitEvent();
  1096. });
  1097. kernel_post_run_events[kernel].emplace_back([post_event]() { post_event->RecordEvent(); });
  1098. bool found_nearest_child = false;
  1099. for (size_t j = i + 1; j < kernels.size(); ++j) {
  1100. auto &child = kernels[j];
  1101. MS_EXCEPTION_IF_NULL(child);
  1102. if (AnfAlgo::IsCommunicationOp(child)) {
  1103. continue;
  1104. }
  1105. auto input_size = child->inputs().size() - 1;
  1106. for (size_t k = 0; k < input_size; ++k) {
  1107. auto kernel_index = AnfAlgo::VisitKernelWithReturnType(AnfAlgo::GetInputNode(child, k), 0, true);
  1108. if (kernel_index.first == kernel) {
  1109. found_nearest_child = true;
  1110. break;
  1111. }
  1112. }
  1113. if (found_nearest_child) {
  1114. kernel_pre_run_events[child].emplace_back([post_event]() { post_event->WaitEvent(); });
  1115. break;
  1116. }
  1117. }
  1118. if (!found_nearest_child) {
  1119. kernel_post_run_events[kernel].emplace_back([post_event]() { post_event->WaitEvent(); });
  1120. }
  1121. }
  1122. graph_kernel_events_map_[graph.graph_id()] = std::move(kernel_events);
  1123. }
  1124. void KernelRuntime::GenAddrCleanLaunchArgs(const CNodePtr &cnode, AddressPtrList *kernel_inputs,
  1125. const std::shared_ptr<MemScheduler> &mem_scheduler) {
  1126. MS_EXCEPTION_IF_NULL(cnode);
  1127. MS_EXCEPTION_IF_NULL(kernel_inputs);
  1128. if (cnode->inputs().size() != kAtomicCleanInputSize) {
  1129. MS_LOG(EXCEPTION) << "Atomic Addr clean Node Input nodes not equal 2.";
  1130. }
  1131. MS_EXCEPTION_IF_NULL(cnode->inputs()[1]);
  1132. auto pre_node = (cnode->inputs()[1])->cast<CNodePtr>();
  1133. // set clean output address
  1134. if (AnfAlgo::HasNodeAttr(kAttrAtomicOutputIndexs, pre_node)) {
  1135. #if defined(__APPLE__)
  1136. auto clean_output_indexes = AnfAlgo::GetNodeAttr<std::vector<int>>(pre_node, kAttrAtomicOutputIndexs);
  1137. #else
  1138. auto clean_output_indexes = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicOutputIndexs);
  1139. #endif
  1140. for (auto index : clean_output_indexes) {
  1141. auto device_address = AnfAlgo::GetOutputAddr(pre_node, index);
  1142. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  1143. MS_EXCEPTION_IF_NULL(input);
  1144. if (mem_scheduler != nullptr) {
  1145. GetOrMallocAddress(mem_scheduler, device_address, input);
  1146. } else {
  1147. input->addr = device_address->ptr_;
  1148. MS_EXCEPTION_IF_NULL(input->addr);
  1149. }
  1150. input->size = device_address->size_;
  1151. kernel_inputs->emplace_back(input);
  1152. }
  1153. MS_LOG(DEBUG) << "AtomicAddClean clean output size:" << clean_output_indexes.size();
  1154. }
  1155. // set clean workspace address
  1156. if (AnfAlgo::HasNodeAttr(kAttrAtomicWorkspaceIndexs, pre_node)) {
  1157. #if defined(__APPLE__)
  1158. auto clean_workspaces_indexes = AnfAlgo::GetNodeAttr<std::vector<int>>(pre_node, kAttrAtomicWorkspaceIndexs);
  1159. #else
  1160. auto clean_workspaces_indexes = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicWorkspaceIndexs);
  1161. #endif
  1162. for (const auto &index : clean_workspaces_indexes) {
  1163. auto device_address = AnfAlgo::GetWorkspaceAddr(pre_node, index);
  1164. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  1165. MS_EXCEPTION_IF_NULL(workspace);
  1166. if (mem_scheduler != nullptr) {
  1167. GetOrMallocAddress(mem_scheduler, device_address, workspace);
  1168. } else {
  1169. workspace->addr = device_address->ptr_;
  1170. MS_EXCEPTION_IF_NULL(workspace->addr);
  1171. }
  1172. workspace->size = device_address->size_;
  1173. kernel_inputs->emplace_back(workspace);
  1174. }
  1175. }
  1176. }
  1177. void KernelRuntime::LaunchKernelEvent(const std::map<AnfNodePtr, std::vector<std::function<void()>>> &kernel_events,
  1178. const AnfNodePtr &node) const {
  1179. if (kernel_events.find(node) == kernel_events.end()) {
  1180. return;
  1181. }
  1182. for (auto &event : kernel_events.at(node)) {
  1183. event();
  1184. }
  1185. }
  1186. bool KernelRuntime::LaunchKernelWithPynativeProfiling(kernel::KernelMod *kernel_mod, const std::string &op_name,
  1187. const KernelLaunchInfo &kernel_launch_info, void *stream) {
  1188. MS_EXCEPTION_IF_NULL(kernel_mod);
  1189. MS_EXCEPTION_IF_NULL(stream);
  1190. float cost_time = 0;
  1191. auto start = CreateDeviceTimeEvent();
  1192. auto end = CreateDeviceTimeEvent();
  1193. MS_EXCEPTION_IF_NULL(start);
  1194. MS_EXCEPTION_IF_NULL(end);
  1195. start->set_record_stream(stream);
  1196. end->set_record_stream(stream);
  1197. start->RecordEvent();
  1198. bool ret = kernel_mod->Launch(kernel_launch_info, stream);
  1199. end->RecordEvent();
  1200. start->SyncEvent();
  1201. end->SyncEvent();
  1202. start->ElapsedTime(&cost_time, end.get());
  1203. auto launch_end_time = GetTime();
  1204. double launch_start_time = launch_end_time - cost_time / kBasicTimeTransferUnit;
  1205. auto op_launch_start_time_end_time = std::make_pair(launch_start_time, launch_end_time);
  1206. PynativeProfiler::SetDeviceOpNameAndLaunchTimePoint(std::make_pair(op_name, op_launch_start_time_end_time));
  1207. PynativeProfiler::SetDeviceOpNameAndLaunchCostTime(std::make_pair(op_name, cost_time / kBasicTimeTransferUnit));
  1208. if (!ret) {
  1209. MS_LOG(EXCEPTION) << "Launch kernel failed, kernel name is : " << op_name;
  1210. }
  1211. return ret;
  1212. }
  1213. void KernelRuntime::DebugStreamSync(const CNodePtr &kernel) {
  1214. auto ms_context = MsContext::GetInstance();
  1215. MS_EXCEPTION_IF_NULL(ms_context);
  1216. auto enable_sync_run = ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_SYNCHRONIZE);
  1217. if (enable_sync_run) {
  1218. if (!SyncStream()) {
  1219. MS_LOG(EXCEPTION) << "Op " << kernel->fullname_with_scope() << " run failed!";
  1220. }
  1221. }
  1222. }
  1223. void KernelRuntime::GetOrMallocAddress(const std::shared_ptr<MemScheduler> &mem_scheduler,
  1224. const DeviceAddress *device_address, const kernel::AddressPtr &kernel_addr) {
  1225. if (device_address->ptr_ != nullptr) {
  1226. kernel_addr->addr = device_address->ptr_;
  1227. } else {
  1228. kernel_addr->addr = mem_scheduler->GetOrMalloc(device_address, device_address->size_);
  1229. if (mem_scheduler->IsHighPriorityMem(device_address)) {
  1230. device_address->ptr_ = kernel_addr->addr;
  1231. }
  1232. }
  1233. }
  1234. void KernelRuntime::AssignKernelAddress(const std::shared_ptr<MemScheduler> &mem_scheduler, const AnfNodePtr &kernel,
  1235. KernelLaunchInfo *kernel_launch_info) {
  1236. MS_EXCEPTION_IF_NULL(kernel);
  1237. MS_EXCEPTION_IF_NULL(kernel_launch_info);
  1238. auto cnode = kernel->cast<CNodePtr>();
  1239. MS_EXCEPTION_IF_NULL(cnode);
  1240. if (AnfAlgo::GetCNodeName(cnode) == kAtomicAddrCleanOpName) {
  1241. return GenAddrCleanLaunchArgs(cnode, &(kernel_launch_info->inputs_), mem_scheduler);
  1242. }
  1243. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  1244. MS_EXCEPTION_IF_NULL(kernel_mod);
  1245. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  1246. for (size_t j = 0; j < input_num; ++j) {
  1247. auto real_input = AnfAlgo::GetRealInputIndex(kernel, j);
  1248. auto kernel_with_index = AnfAlgo::GetPrevNodeOutput(kernel, real_input, true);
  1249. auto index = kernel_with_index.second;
  1250. auto &input_node = kernel_with_index.first;
  1251. auto device_address = AnfAlgo::GetOutputAddr(input_node, index, true);
  1252. MS_EXCEPTION_IF_NULL(device_address);
  1253. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  1254. GetOrMallocAddress(mem_scheduler, device_address, input);
  1255. input->size = device_address->size_;
  1256. kernel_launch_info->inputs_.emplace_back(input);
  1257. }
  1258. for (size_t j = 0; j < kernel_mod->GetOutputSizeList().size(); ++j) {
  1259. auto device_address = AnfAlgo::GetOutputAddr(kernel, j, true);
  1260. kernel::AddressPtr output = std::make_shared<kernel::Address>();
  1261. GetOrMallocAddress(mem_scheduler, device_address, output);
  1262. output->size = device_address->size_;
  1263. kernel_launch_info->outputs_.emplace_back(output);
  1264. }
  1265. for (size_t i = 0; i < kernel_mod->GetWorkspaceSizeList().size(); ++i) {
  1266. auto device_address = AnfAlgo::GetWorkspaceAddr(kernel, i);
  1267. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  1268. GetOrMallocAddress(mem_scheduler, device_address, workspace);
  1269. workspace->size = device_address->size_;
  1270. kernel_launch_info->workspaces_.emplace_back(workspace);
  1271. }
  1272. }
  1273. void KernelRuntime::SyncNodeOutputTensors(const std::shared_ptr<MemScheduler> &mem_scheduler,
  1274. const session::KernelGraph &graph, const AnfNodePtr &kernel, bool mock) {
  1275. MS_EXCEPTION_IF_NULL(mem_scheduler);
  1276. MS_EXCEPTION_IF_NULL(kernel);
  1277. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  1278. MS_EXCEPTION_IF_NULL(kernel_mod);
  1279. for (size_t input_idx = 0; input_idx < kernel_mod->GetInputSizeList().size(); ++input_idx) {
  1280. const auto input_node_index = AnfAlgo::GetPrevNodeOutput(kernel, input_idx, true);
  1281. if (input_node_index.first == nullptr || !input_node_index.first->isa<Parameter>()) {
  1282. continue;
  1283. }
  1284. SyncNodeOutputTensor(mem_scheduler, input_node_index, graph, mock);
  1285. }
  1286. for (size_t output_idx = 0; output_idx < kernel_mod->GetOutputSizeList().size(); ++output_idx) {
  1287. SyncNodeOutputTensor(mem_scheduler, std::make_pair(kernel, output_idx), graph, mock);
  1288. }
  1289. }
  1290. void KernelRuntime::SyncNodeOutputTensor(const std::shared_ptr<MemScheduler> &mem_scheduler,
  1291. const KernelWithIndex &node_output_index, const session::KernelGraph &graph,
  1292. bool mock) {
  1293. MS_EXCEPTION_IF_NULL(mem_scheduler);
  1294. if (node_output_index.first == nullptr) {
  1295. return;
  1296. }
  1297. auto device_address = AnfAlgo::GetMutableOutputAddr(node_output_index, true);
  1298. if (mock) {
  1299. if (graph.IsInternalOutput(node_output_index.first, node_output_index.second) && device_address != nullptr) {
  1300. mem_scheduler->SetMemPriority(device_address.get(), kMemPriorityHigh);
  1301. }
  1302. return;
  1303. }
  1304. auto tensor = graph.GetNodeOutputTensor(node_output_index);
  1305. if (tensor == nullptr) {
  1306. return;
  1307. }
  1308. if (device_address == nullptr) {
  1309. tensor->data_sync(false);
  1310. tensor->set_device_address(nullptr);
  1311. tensor->set_sync_status(kNeedSyncHostToDevice);
  1312. return;
  1313. }
  1314. if (!SyncStream()) {
  1315. MS_LOG(EXCEPTION) << "SyncStream failed";
  1316. }
  1317. auto origin_ptr = device_address->ptr_;
  1318. if (device_address->ptr_ == nullptr) {
  1319. device_address->ptr_ = mem_scheduler->GetOrMalloc(device_address.get(), device_address->size_);
  1320. }
  1321. tensor->set_device_address(device_address);
  1322. tensor->data_sync(false);
  1323. tensor->set_device_address(nullptr);
  1324. device_address->ptr_ = origin_ptr;
  1325. tensor->set_sync_status(kNeedSyncHostToDevice);
  1326. }
  1327. void KernelRuntime::InitGraphInputTensors(const std::shared_ptr<MemScheduler> &mem_scheduler,
  1328. const session::KernelGraph &graph) {
  1329. MS_EXCEPTION_IF_NULL(mem_scheduler);
  1330. auto &input_nodes = graph.input_nodes();
  1331. auto &input_tensors = graph.input_tensors();
  1332. if (input_tensors.size() != input_nodes.size()) {
  1333. MS_LOG_EXCEPTION << "Invalid input tensor size:" << input_tensors.size() << " vs node size:" << input_nodes.size();
  1334. }
  1335. for (size_t i = 0; i < input_tensors.size(); ++i) {
  1336. auto tensor = input_tensors[i];
  1337. MS_EXCEPTION_IF_NULL(tensor);
  1338. auto input_node = input_nodes[i];
  1339. if (!input_node->isa<Parameter>() || !AnfAlgo::OutputAddrExist(input_node, 0)) {
  1340. continue;
  1341. }
  1342. auto device_address = AnfAlgo::GetMutableOutputAddr(input_node, 0);
  1343. MS_EXCEPTION_IF_NULL(tensor);
  1344. MemPriority priority = kMemPriorityLow;
  1345. auto tensor_address = tensor->device_address();
  1346. if (!tensor->NeedSyncHostToDevice() && tensor_address != nullptr && tensor_address != device_address) {
  1347. tensor->data_sync(false);
  1348. }
  1349. if (AnfAlgo::IsParameterWeight(input_node->cast<ParameterPtr>()) ||
  1350. graph.IsUpdatedParameter(input_node->cast<ParameterPtr>())) {
  1351. tensor->set_device_address(device_address);
  1352. priority = kMemPriorityHigh;
  1353. }
  1354. auto tensor_size = LongToSize(tensor->data().nbytes());
  1355. mem_scheduler->Init(device_address.get(), tensor->data_c(), tensor_size, priority);
  1356. tensor->set_sync_status(kNoNeedSync);
  1357. }
  1358. }
  1359. void KernelRuntime::AssignCommunicationMem(const session::KernelGraph &graph) {
  1360. for (const auto &kernel : graph.execution_order()) {
  1361. if (!AnfAlgo::IsCommunicationOp(kernel)) {
  1362. continue;
  1363. }
  1364. AssignCommunicationInputFromMemoryPool(kernel);
  1365. AssignCommunicationOutputFromMemoryPool(kernel);
  1366. }
  1367. }
  1368. bool KernelRuntime::LaunchKernel(const session::KernelGraph &graph, const AnfNodePtr &kernel,
  1369. const std::shared_ptr<MemScheduler> &mem_scheduler, bool mock) {
  1370. MS_EXCEPTION_IF_NULL(kernel);
  1371. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  1372. MS_EXCEPTION_IF_NULL(kernel_mod);
  1373. KernelLaunchInfo kernel_launch_info;
  1374. auto stream = kernel_mod->GetStream();
  1375. if (stream == nullptr) {
  1376. if (AnfAlgo::IsCommunicationOp(kernel)) {
  1377. stream = communication_stream_;
  1378. } else {
  1379. stream = stream_;
  1380. }
  1381. }
  1382. bool ret = true;
  1383. if (mem_scheduler != nullptr) {
  1384. ret = mem_scheduler->PreCompute(stream);
  1385. if (!ret) {
  1386. return ret;
  1387. }
  1388. AssignKernelAddress(mem_scheduler, kernel, &kernel_launch_info);
  1389. } else if (!kernel_mod->GetInputsAddr().empty() || !kernel_mod->GetOutputsAddr().empty()) {
  1390. kernel_launch_info.inputs_ = kernel_mod->GetInputsAddr();
  1391. kernel_launch_info.outputs_ = kernel_mod->GetOutputsAddr();
  1392. kernel_launch_info.workspaces_ = kernel_mod->GetWorkSpacesAddr();
  1393. } else {
  1394. GenLaunchArgs(*kernel_mod, kernel, &kernel_launch_info);
  1395. }
  1396. if (!mock) {
  1397. if (pynative_mode_profiling_flag_) {
  1398. ret = LaunchKernelWithPynativeProfiling(kernel_mod, kernel->fullname_with_scope(), kernel_launch_info, stream);
  1399. } else {
  1400. ret = kernel_mod->Launch(kernel_launch_info, stream);
  1401. }
  1402. }
  1403. if (mem_scheduler != nullptr) {
  1404. SyncNodeOutputTensors(mem_scheduler, graph, kernel, mock);
  1405. ret = mem_scheduler->PostCompute(stream);
  1406. if (!ret) {
  1407. return ret;
  1408. }
  1409. }
  1410. return ret;
  1411. }
  1412. bool KernelRuntime::LaunchKernelMod(const session::KernelGraph &graph, bool mock) {
  1413. auto context_ptr = MsContext::GetInstance();
  1414. MS_EXCEPTION_IF_NULL(context_ptr);
  1415. std::shared_ptr<MemScheduler> mem_scheduler = nullptr;
  1416. if (UseMemScheduler()) {
  1417. mem_scheduler = mem_scheduler_manager_.GetOrCreateMemScheduler(graph.graph_id());
  1418. MS_EXCEPTION_IF_NULL(mem_scheduler);
  1419. mem_scheduler->SetMemHandler(mem_manager_);
  1420. mem_scheduler->Reset();
  1421. InitGraphInputTensors(mem_scheduler, graph);
  1422. }
  1423. const auto &kernels = graph.execution_order();
  1424. std::vector<DynamicKernelPtr> dynamic_kernel_list;
  1425. auto iter = graph_dynamic_kernel_map_.find(graph.graph_id());
  1426. if (iter != graph_dynamic_kernel_map_.end()) {
  1427. dynamic_kernel_list = iter->second;
  1428. }
  1429. if (!dynamic_kernel_list.empty() && dynamic_kernel_list.size() != kernels.size()) {
  1430. MS_LOG(EXCEPTION) << "The size of dynamic kernels " << dynamic_kernel_list.size()
  1431. << " should be equal to the size of kernels " << kernels.size();
  1432. }
  1433. std::map<AnfNodePtr, std::vector<std::function<void()>>> kernel_pre_run_events;
  1434. std::map<AnfNodePtr, std::vector<std::function<void()>>> kernel_post_run_events;
  1435. auto events_iter = graph_kernel_events_map_.find(graph.graph_id());
  1436. if (events_iter != graph_kernel_events_map_.end()) {
  1437. kernel_pre_run_events = events_iter->second.first;
  1438. kernel_post_run_events = events_iter->second.second;
  1439. }
  1440. for (size_t i = 0; i < kernels.size(); ++i) {
  1441. LaunchKernelEvent(kernel_pre_run_events, kernels[i]);
  1442. if (!dynamic_kernel_list.empty() && dynamic_kernel_list[i] != nullptr &&
  1443. dynamic_kernel_list[i]->is_dynamic_shape()) {
  1444. dynamic_kernel_list[i]->InferShape();
  1445. dynamic_kernel_list[i]->UpdateArgs();
  1446. dynamic_kernel_list[i]->Execute();
  1447. if (!SyncStream()) {
  1448. MS_LOG(ERROR) << "SyncStream failed";
  1449. return false;
  1450. }
  1451. dynamic_kernel_list[i]->PostExecute();
  1452. } else {
  1453. auto &kernel = kernels[i];
  1454. MS_EXCEPTION_IF_NULL(kernel);
  1455. // Skip transpose kernel with "nop_op" attr which is not hidden or removed in PyNative infer scenario. Transpose
  1456. // kernel, which is not supposed to be executed, is generated in TransDataSplit to support specific Transdata.
  1457. // And hard code here should be removed after new Transdata programme is implemented in the foreseeable future.
  1458. if (AnfAlgo::HasNodeAttr("nop_op", kernel)) {
  1459. for (size_t idx = 0; idx < AnfAlgo::GetOutputTensorNum(kernel); idx += 1) {
  1460. auto real_input = AnfAlgo::GetRealInputIndex(kernel, idx);
  1461. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, real_input);
  1462. AnfAlgo::SetOutputAddr(device_address, idx, kernel.get());
  1463. }
  1464. continue;
  1465. }
  1466. auto ret = LaunchKernel(graph, kernel, mem_scheduler, mock);
  1467. if (!ret) {
  1468. MS_LOG(ERROR) << "Launch kernel failed.";
  1469. return false;
  1470. }
  1471. KernelLaunchProfiling(kernel->fullname_with_scope());
  1472. DebugStreamSync(kernel);
  1473. }
  1474. LaunchKernelEvent(kernel_post_run_events, kernels[i]);
  1475. }
  1476. return true;
  1477. }
  1478. void KernelRuntime::UseMemSchedulerIfNeeded(const session::KernelGraph &graph) {
  1479. auto context_ptr = MsContext::GetInstance();
  1480. MS_EXCEPTION_IF_NULL(context_ptr);
  1481. if (!UseMemScheduler()) {
  1482. return;
  1483. }
  1484. auto mem_scheduler = mem_scheduler_manager_.GetOrCreateMemScheduler(graph.graph_id());
  1485. if (mem_scheduler->need_record_event()) {
  1486. (void)LaunchKernelMod(graph, true);
  1487. mem_scheduler->set_need_record_event(false);
  1488. }
  1489. float mem_used_factor = kMaxMemReuseFactor;
  1490. while (!mem_scheduler->optimized() && mem_used_factor >= kMinMemReuseFactor) {
  1491. mem_scheduler->SetMemUsedFactor(mem_used_factor);
  1492. mem_scheduler->OptMemUsage();
  1493. bool ret = LaunchKernelMod(graph, true);
  1494. if (ret) {
  1495. mem_scheduler->set_optimized(true);
  1496. } else {
  1497. mem_used_factor -= kRetryFactor;
  1498. }
  1499. }
  1500. if (!mem_scheduler->optimized()) {
  1501. MS_LOG_EXCEPTION << "Can't run graph " << graph.graph_id() << " for memory limit.";
  1502. }
  1503. }
  1504. bool KernelRuntime::LaunchKernels(const session::KernelGraph &graph) {
  1505. UseMemSchedulerIfNeeded(graph);
  1506. if (!LaunchKernelMod(graph)) {
  1507. MS_LOG(ERROR) << "LaunchKernelMod failed!";
  1508. return false;
  1509. }
  1510. auto ms_context = MsContext::GetInstance();
  1511. MS_EXCEPTION_IF_NULL(ms_context);
  1512. if (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kGraphMode) {
  1513. if (!SyncStream()) {
  1514. MS_LOG(ERROR) << "SyncStream failed";
  1515. return false;
  1516. }
  1517. }
  1518. return true;
  1519. }
  1520. void KernelRuntime::ClearGraphRuntimeResource(uint32_t graph_id) {
  1521. MS_LOG(INFO) << "Clear graph:" << graph_id << " runtime resource";
  1522. }
  1523. #if ((defined ENABLE_CPU) && (!defined _WIN32))
  1524. void KernelRuntime::GetFirstPSEmbeddingCache(const session::KernelGraph &graph,
  1525. AnfNodePtr *const first_cache_input_index,
  1526. size_t *const first_cache_size) {
  1527. for (const auto &kernel : graph.execution_order()) {
  1528. MS_EXCEPTION_IF_NULL(kernel);
  1529. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  1530. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1531. continue;
  1532. }
  1533. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1534. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1535. MS_EXCEPTION_IF_NULL(input_param.first);
  1536. MS_EXCEPTION_IF_NULL(input_index.first);
  1537. auto param_name = input_param.first->fullname_with_scope();
  1538. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1539. continue;
  1540. }
  1541. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1542. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1543. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1544. MS_EXCEPTION_IF_NULL(input_index.first);
  1545. }
  1546. auto cnode =
  1547. AnfAlgo::IsGraphKernel(input_index.first) ? AnfAlgo::GetOutputOfGraphkernel(input_index) : input_index.first;
  1548. MS_EXCEPTION_IF_NULL(cnode);
  1549. if (!cnode->isa<CNode>()) {
  1550. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index should be a CNode but got "
  1551. << cnode->fullname_with_scope();
  1552. }
  1553. auto input_index_node_name = AnfAlgo::GetCNodeName(cnode);
  1554. if (input_index_node_name != kGetNextOpName) {
  1555. bool full_batch = parallel::ParallelContext::GetInstance()->full_batch();
  1556. if ((!full_batch && (input_index_node_name != kUniqueOpName)) ||
  1557. (full_batch && (input_index_node_name != kMinimumOpName))) {
  1558. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope()
  1559. << ") cache is from " << cnode->fullname_with_scope();
  1560. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1561. "parameter server training mode.";
  1562. }
  1563. }
  1564. *first_cache_input_index = cnode;
  1565. *first_cache_size = size;
  1566. MS_LOG(INFO) << "The input index of the first embeddingLookup cache is from " << cnode->fullname_with_scope()
  1567. << ", the cache size is " << size;
  1568. return;
  1569. }
  1570. }
  1571. void KernelRuntime::CheckSparsePSEmbeddingCache(const CNodePtr &node) {
  1572. MS_EXCEPTION_IF_NULL(node);
  1573. auto pre_node = AnfAlgo::GetPrevNodeOutput(node, 1, true);
  1574. MS_EXCEPTION_IF_NULL(pre_node.first);
  1575. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1576. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1577. MS_EXCEPTION_IF_NULL(pre_node.first);
  1578. }
  1579. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kUniqueOpName)) {
  1580. MS_LOG(EXCEPTION) << "The input_indices of kernel[SparseGatherV2] must be unique in parameter server cache mode";
  1581. }
  1582. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1583. MS_EXCEPTION_IF_NULL(pre_node.first);
  1584. while (pre_node.first->isa<CNode>() && (AnfAlgo::GetCNodeName(pre_node.first) == kCastOpName)) {
  1585. pre_node = AnfAlgo::GetPrevNodeOutput(pre_node.first, 0, true);
  1586. MS_EXCEPTION_IF_NULL(pre_node.first);
  1587. }
  1588. if (!(pre_node.first->isa<CNode>()) || (AnfAlgo::GetCNodeName(pre_node.first) != kGetNextOpName)) {
  1589. MS_LOG(EXCEPTION) << "The input indices of kernel[Unique] must be produced from dataset directly and the indices "
  1590. "value can not be changed before delivering to kernel[Unique] in parameter server cache mode.";
  1591. }
  1592. }
  1593. void KernelRuntime::CheckIfSupportPSEmbeddingCache(const session::KernelGraph &graph) {
  1594. AnfNodePtr first_cache_input_index = nullptr;
  1595. size_t first_cache_size = 0;
  1596. GetFirstPSEmbeddingCache(graph, &first_cache_input_index, &first_cache_size);
  1597. MS_EXCEPTION_IF_NULL(first_cache_input_index);
  1598. for (const auto &kernel : graph.execution_order()) {
  1599. MS_EXCEPTION_IF_NULL(kernel);
  1600. auto kernel_name = AnfAlgo::GetCNodeName(kernel);
  1601. if (kernel_name != kGatherV2OpName && kernel_name != kSparseGatherV2OpName) {
  1602. continue;
  1603. }
  1604. auto input_param = AnfAlgo::GetPrevNodeOutput(kernel, 0, true);
  1605. auto input_index = AnfAlgo::GetPrevNodeOutput(kernel, 1, true);
  1606. MS_EXCEPTION_IF_NULL(input_param.first);
  1607. MS_EXCEPTION_IF_NULL(input_index.first);
  1608. if (!input_param.first->isa<Parameter>()) {
  1609. continue;
  1610. }
  1611. auto param_name = input_param.first->fullname_with_scope();
  1612. if (ps::ps_cache_instance.IsHashTable(param_name) && (kernel_name == kSparseGatherV2OpName)) {
  1613. CheckSparsePSEmbeddingCache(kernel);
  1614. }
  1615. while (input_index.first->isa<CNode>() && (AnfAlgo::GetCNodeName(input_index.first) == kCastOpName)) {
  1616. input_index = AnfAlgo::GetPrevNodeOutput(input_index.first, 0, true);
  1617. MS_EXCEPTION_IF_NULL(input_index.first);
  1618. }
  1619. auto cnode =
  1620. AnfAlgo::IsGraphKernel(input_index.first) ? AnfAlgo::GetOutputOfGraphkernel(input_index) : input_index.first;
  1621. MS_EXCEPTION_IF_NULL(cnode);
  1622. if (cnode == first_cache_input_index) {
  1623. if (!ps::ps_cache_instance.IsHashTable(param_name)) {
  1624. MS_LOG(ERROR) << "The embeddingLookup(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1625. MS_LOG(EXCEPTION) << "All the embeddingLookups whose input indices are from dataset must enable cache at the "
  1626. "same time when one of them enables cache in parameter server training mode.";
  1627. }
  1628. auto size = ps::ps_cache_instance.QueryHashTableSize(param_name);
  1629. if (size != first_cache_size) {
  1630. MS_LOG(ERROR) << "The cache size(" << size << ") of embeddingLookup(" << kernel->fullname_with_scope()
  1631. << ") is not the same as other embeddingLookup cache size(" << first_cache_size << ").";
  1632. MS_LOG(EXCEPTION) << "The cache sizes of embeddingLookups are not the same in parameter server training mode.";
  1633. }
  1634. } else if (ps::ps_cache_instance.IsHashTable(param_name)) {
  1635. MS_LOG(ERROR) << "The input index of the embeddingLookup(" << kernel->fullname_with_scope() << ") cache is from "
  1636. << cnode->fullname_with_scope();
  1637. MS_LOG(EXCEPTION) << "The embeddingLookup whose input index isn't from dataset doesn't support cache in "
  1638. "parameter server training mode.";
  1639. } else if (cnode->isa<CNode>() && (AnfAlgo::GetCNodeName(cnode) == kGetNextOpName)) {
  1640. MS_LOG(ERROR) << "The EmbeddingLookup kernel(" << kernel->fullname_with_scope() << ") doesn't enable cache.";
  1641. MS_LOG(EXCEPTION) << "All EmbeddingLookup kernels whose input indices are from dataset must enable cache at "
  1642. "the same time and parameter 'sparse' must be equal to the value of 'enable_sparse' in "
  1643. "context setting in parameter server training mode.";
  1644. }
  1645. }
  1646. }
  1647. #endif
  1648. } // namespace device
  1649. } // namespace mindspore