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

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