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

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