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

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