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.

gpu_kernel_runtime.cc 25 kB

6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /**
  2. * Copyright 2019 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 "device/gpu/gpu_kernel_runtime.h"
  17. #include "device/gpu/gpu_device_address.h"
  18. #include "device/gpu/cuda_driver.h"
  19. #include "device/gpu/gpu_buffer_mgr.h"
  20. #include "device/gpu/gpu_device_manager.h"
  21. #include "device/gpu/gpu_memory_allocator.h"
  22. #include "device/gpu/distribution/collective_init.h"
  23. #include "utils/convert_utils.h"
  24. #include "utils/context/ms_context.h"
  25. #include "device/kernel_runtime_manager.h"
  26. #include "device/gpu/gpu_common.h"
  27. #include "common/utils.h"
  28. #include "device/gpu/gpu_memory_manager.h"
  29. #include "kernel/common_utils.h"
  30. #include "device/gpu/gpu_memory_copy_manager.h"
  31. namespace mindspore {
  32. namespace device {
  33. namespace gpu {
  34. using mindspore::device::memswap::MemSwapManager;
  35. using mindspore::device::memswap::SwapKind;
  36. bool GPUKernelRuntime::SyncStream() { return GPUDeviceManager::GetInstance().SyncStream(stream_); }
  37. bool GPUKernelRuntime::Init() {
  38. if (device_init_ == true) {
  39. GPUMemoryAllocator::GetInstance().CheckMaxDeviceMemory();
  40. return true;
  41. }
  42. auto ret = InitDevice();
  43. if (!ret) {
  44. MS_LOG(ERROR) << "InitDevice error.";
  45. return ret;
  46. }
  47. mem_manager_ = std::make_shared<GPUMemoryManager>();
  48. MS_EXCEPTION_IF_NULL(mem_manager_);
  49. mem_manager_->MallocDeviceMemory();
  50. const void *collective_handle_ = CollectiveInitializer::instance().collective_handle();
  51. bool collective_inited = CollectiveInitializer::instance().collective_inited();
  52. if (collective_inited && collective_handle_ != nullptr) {
  53. auto init_nccl_comm_funcptr =
  54. reinterpret_cast<InitNCCLComm>(dlsym(const_cast<void *>(collective_handle_), "InitNCCLComm"));
  55. MS_EXCEPTION_IF_NULL(init_nccl_comm_funcptr);
  56. (*init_nccl_comm_funcptr)();
  57. }
  58. device_init_ = true;
  59. return ret;
  60. }
  61. DeviceAddressPtr GPUKernelRuntime::CreateDeviceAddress(void *device_ptr, size_t device_size, const string &format,
  62. TypeId type_id) {
  63. return std::make_shared<GPUDeviceAddress>(device_ptr, device_size, format, type_id);
  64. }
  65. bool GPUKernelRuntime::InitDevice() {
  66. if (GPUDeviceManager::GetInstance().device_count() <= 0) {
  67. MS_LOG(ERROR) << "No GPU device found.";
  68. return false;
  69. }
  70. const void *collective_handle_ = CollectiveInitializer::instance().collective_handle();
  71. bool collective_inited = CollectiveInitializer::instance().collective_inited();
  72. if (collective_inited && collective_handle_ != nullptr) {
  73. auto get_local_rank_funcptr =
  74. reinterpret_cast<GetLocalRankId>(dlsym(const_cast<void *>(collective_handle_), "local_rank_id"));
  75. MS_EXCEPTION_IF_NULL(get_local_rank_funcptr);
  76. device_id_ = IntToUint((*get_local_rank_funcptr)());
  77. }
  78. if (!GPUDeviceManager::GetInstance().is_device_id_init()) {
  79. if (!GPUDeviceManager::GetInstance().set_cur_device_id(device_id_)) {
  80. MS_LOG(ERROR) << "Failed to set current device to " << SizeToInt(device_id_);
  81. return false;
  82. }
  83. }
  84. GPUDeviceManager::GetInstance().InitDevice();
  85. stream_ = GPUDeviceManager::GetInstance().default_stream();
  86. if (stream_ == nullptr) {
  87. MS_LOG(ERROR) << "No default CUDA stream found.";
  88. return false;
  89. }
  90. return true;
  91. }
  92. void GPUKernelRuntime::ReleaseDeviceRes() {
  93. // For dataset mode.
  94. if (GpuBufferMgr::GetInstance().IsInit()) {
  95. if (!GpuBufferMgr::GetInstance().IsClosed()) {
  96. if (!GpuBufferMgr::GetInstance().CloseNotify()) {
  97. MS_LOG(EXCEPTION) << "Could not close gpu data queue.";
  98. }
  99. }
  100. CHECK_OP_RET_WITH_EXCEPT(GpuBufferMgr::GetInstance().Destroy(), "Could not destroy gpu data queue.");
  101. }
  102. // Destroy remaining memory swap events and free host memory.
  103. for (auto &item : mem_swap_map_) {
  104. auto &mem_swap_manager = item.second;
  105. MS_EXCEPTION_IF_NULL(mem_swap_manager);
  106. if (mem_swap_manager->trigger_swap()) {
  107. mem_swap_manager->ClearSwapQueue();
  108. mem_swap_manager->ReleaseHostPinnedMem();
  109. }
  110. }
  111. GPUDeviceManager::GetInstance().ReleaseDevice();
  112. if (mem_manager_ != nullptr) {
  113. mem_manager_->FreeDeviceMemory();
  114. }
  115. kernel::KernelMeta *bin_map = kernel::KernelMeta::GetInstance();
  116. MS_EXCEPTION_IF_NULL(bin_map);
  117. bin_map->RemoveKernelCache();
  118. }
  119. void GPUKernelRuntime::AssignMemory(session::KernelGraph *graph) {
  120. auto context_ptr = MsContext::GetInstance();
  121. MS_EXCEPTION_IF_NULL(context_ptr);
  122. MS_EXCEPTION_IF_NULL(mem_manager_);
  123. mem_manager_->ResetDynamicMemory();
  124. AssignStaticMemoryInput(graph);
  125. AssignStaticMemoryValueNode(graph);
  126. bool is_enable_dynamic_mem = context_ptr->enable_dynamic_mem_pool();
  127. if (is_enable_dynamic_mem) {
  128. // Use the dynamic memory pool.
  129. InitKernelRefCount(graph);
  130. InitKernelOutputAddress(graph);
  131. } else {
  132. AssignDynamicMemory(graph);
  133. }
  134. }
  135. bool GPUKernelRuntime::Run(session::KernelGraph *graph) {
  136. bool ret = true;
  137. auto context_ptr = MsContext::GetInstance();
  138. MS_EXCEPTION_IF_NULL(context_ptr);
  139. bool is_enable_dynamic_mem = context_ptr->enable_dynamic_mem_pool();
  140. bool is_enable_pynative_infer = context_ptr->enable_pynative_infer();
  141. auto iter = mem_swap_map_.find(graph);
  142. if (iter == mem_swap_map_.end()) {
  143. GPUMemCopyManagerPtr gpu_mem_copy_manager = std::make_shared<GPUMemCopyManager>();
  144. iter = mem_swap_map_.emplace(graph, std::make_shared<MemSwapManager>(gpu_mem_copy_manager)).first;
  145. }
  146. mem_swap_manager_ = iter->second;
  147. MS_EXCEPTION_IF_NULL(mem_swap_manager_);
  148. struct timeval start_time, end_time;
  149. (void)gettimeofday(&start_time, nullptr);
  150. if (is_enable_dynamic_mem && !is_enable_pynative_infer) {
  151. while (!LaunchKernelDynamic(graph)) {
  152. ClearKernelOutputAddress(graph);
  153. if (!mem_swap_manager_->mem_swap_init()) {
  154. mem_swap_manager_->Init(graph);
  155. }
  156. if (!mem_swap_manager_->RetreatSwapInfo()) {
  157. return false;
  158. }
  159. }
  160. } else {
  161. ret = LaunchKernel(graph);
  162. }
  163. (void)gettimeofday(&end_time, nullptr);
  164. const uint64_t kUSecondInSecond = 1000000;
  165. uint64_t cost = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec);
  166. cost += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec);
  167. MS_LOG(DEBUG) << "GPU kernel runtime run graph in " << cost << " us";
  168. return ret;
  169. }
  170. void GPUKernelRuntime::InitKernelRefCount(const session::KernelGraph *graph) {
  171. MS_EXCEPTION_IF_NULL(graph);
  172. MemReuseUtilPtr mem_reuse_util_ptr = std::make_shared<memreuse::MemReuseUtil>();
  173. MS_EXCEPTION_IF_NULL(mem_reuse_util_ptr);
  174. // Init the kernel reference count.
  175. if (!mem_reuse_util_ptr->InitDynamicKernelRef(graph)) {
  176. MS_LOG(EXCEPTION) << "Init kernel reference count failed";
  177. }
  178. mem_reuse_util_ptr->SetKernelDefMap();
  179. mem_reuse_util_ptr->SetReuseRefCount();
  180. // Can't free the device address of graph output, so set the reference count of graph output specially.
  181. mem_reuse_util_ptr->SetGraphOutputRefCount();
  182. // Can't free the device address of summary nodes, so set the reference count of summary nodes specially.
  183. mem_reuse_util_ptr->SetSummaryNodesRefCount();
  184. auto graph_id = graph->graph_id();
  185. mem_reuse_util_map_[graph_id] = mem_reuse_util_ptr;
  186. }
  187. void GPUKernelRuntime::InitKernelOutputAddress(const session::KernelGraph *graph) {
  188. MS_EXCEPTION_IF_NULL(graph);
  189. auto &kernels = graph->execution_order();
  190. for (const auto &kernel : kernels) {
  191. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  192. MS_EXCEPTION_IF_NULL(kernel_mod);
  193. auto output_sizes = kernel_mod->GetOutputSizeList();
  194. for (size_t i = 0; i < output_sizes.size(); ++i) {
  195. if (AnfAlgo::OutputAddrExist(kernel, i)) {
  196. continue;
  197. }
  198. std::string output_format = AnfAlgo::GetOutputFormat(kernel, i);
  199. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  200. auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type);
  201. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  202. }
  203. }
  204. }
  205. void GPUKernelRuntime::ClearKernelOutputAddress(const session::KernelGraph *graph) {
  206. MS_EXCEPTION_IF_NULL(graph);
  207. auto &kernels = graph->execution_order();
  208. for (const auto &kernel : kernels) {
  209. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  210. MS_EXCEPTION_IF_NULL(kernel_mod);
  211. auto output_sizes = kernel_mod->GetOutputSizeList();
  212. for (size_t i = 0; i < output_sizes.size(); ++i) {
  213. if (!AnfAlgo::OutputAddrExist(kernel, i)) {
  214. continue;
  215. }
  216. auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i, false);
  217. if (device_address->ptr_) {
  218. mem_manager_->FreeMemFromMemPool(device_address);
  219. }
  220. device_address->set_status(DeviceAddressStatus::kInDevice);
  221. }
  222. }
  223. }
  224. bool GPUKernelRuntime::LaunchKernelDynamic(const session::KernelGraph *graph) {
  225. MS_EXCEPTION_IF_NULL(graph);
  226. MS_EXCEPTION_IF_NULL(mem_swap_manager_);
  227. auto graph_id = graph->graph_id();
  228. auto mem_reuse_util_ptr = mem_reuse_util_map_[graph_id];
  229. MS_EXCEPTION_IF_NULL(mem_reuse_util_ptr);
  230. // Reset the reference count.
  231. mem_reuse_util_ptr->ResetDynamicUsedRefCount();
  232. // The inputs and outputs memory of communication kernel need be continuous, so separate processing.
  233. AllocCommunicationOpDynamicRes(graph);
  234. auto &kernels = graph->execution_order();
  235. for (const auto &kernel : kernels) {
  236. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  237. MS_EXCEPTION_IF_NULL(kernel_mod);
  238. AddressPtrList kernel_inputs;
  239. AddressPtrList kernel_workspaces;
  240. AddressPtrList kernel_outputs;
  241. auto ret = AllocKernelDynamicRes(*kernel_mod, kernel, &kernel_inputs, &kernel_workspaces, &kernel_outputs);
  242. if (!ret) {
  243. return false;
  244. }
  245. if (!kernel_mod->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_)) {
  246. MS_LOG(EXCEPTION) << "Launch kernel failed.";
  247. }
  248. FreeKernelDynamicRes(kernel, kernel_workspaces, graph_id);
  249. if (mem_swap_manager_->trigger_swap() && mem_swap_manager_->QueryKernelTriggerSwap(kernel)) {
  250. CHECK_OP_RET_WITH_EXCEPT(SyncStream(), "SyncStream failed.");
  251. if (!AddMemSwapTask(kernel)) {
  252. return false;
  253. }
  254. }
  255. if (mem_swap_manager_->trigger_swap()) {
  256. mem_swap_manager_->SyncMemCopyStream(SwapKind::kDeviceToHost);
  257. }
  258. }
  259. CHECK_OP_RET_WITH_EXCEPT(SyncStream(), "SyncStream failed.");
  260. if (mem_swap_manager_->trigger_swap()) {
  261. mem_swap_manager_->ClearSwapQueue();
  262. }
  263. return true;
  264. }
  265. bool GPUKernelRuntime::AddMemSwapTask(const AnfNodePtr &kernel) {
  266. MS_EXCEPTION_IF_NULL(mem_swap_manager_);
  267. auto &mem_swap_info_list = mem_swap_manager_->QueryKernelMemSwapInfo(kernel);
  268. for (auto &mem_swap_info : mem_swap_info_list) {
  269. auto &kernel_exec_info = mem_swap_manager_->SearchKernelExecutionInfo(mem_swap_info.kernel_);
  270. const HostAddress &host_address = kernel_exec_info.host_addrs_[mem_swap_info.output_idx_];
  271. auto device_address = AnfAlgo::GetMutableOutputAddr(mem_swap_info.kernel_, mem_swap_info.output_idx_, false);
  272. if (mem_swap_info.swap_kind_ == SwapKind::kDeviceToHost) {
  273. mem_swap_manager_->AddMemSwapTask(SwapKind::kDeviceToHost, device_address, host_address);
  274. } else if (mem_swap_info.swap_kind_ == SwapKind::kHostToDevice) {
  275. auto status = device_address->status();
  276. if (status == DeviceAddressStatus::kInDeviceToHost) {
  277. mem_swap_manager_->InsertSwapInBlackList(device_address->ptr_);
  278. device_address->set_status(DeviceAddressStatus::kInDevice);
  279. } else if (status == DeviceAddressStatus::kInHost) {
  280. if (!device_address->ptr_ && !AttemptMallocMem(device_address, device_address->size_)) {
  281. return false;
  282. }
  283. if (!mem_swap_manager_->FindInSwapInBlackList(device_address->ptr_)) {
  284. mem_swap_manager_->AddMemSwapTask(SwapKind::kHostToDevice, device_address, host_address);
  285. }
  286. }
  287. }
  288. }
  289. return true;
  290. }
  291. bool GPUKernelRuntime::AttemptMallocMem(const DeviceAddressPtr &device_address, size_t size) {
  292. MS_EXCEPTION_IF_NULL(mem_manager_);
  293. auto ret = mem_manager_->MallocMemFromMemPool(device_address, size);
  294. if (!ret) {
  295. if (!mem_swap_manager_->trigger_swap()) {
  296. return false;
  297. }
  298. mem_swap_manager_->SyncMemCopyStream(SwapKind::kDeviceToHost);
  299. while (auto device_address_swap_out = mem_swap_manager_->UpdateSwapQueue(SwapKind::kDeviceToHost)) {
  300. if (!mem_swap_manager_->FindInSwapInBlackList(device_address_swap_out->ptr_) && device_address_swap_out->ptr_) {
  301. device_address_swap_out->set_status(DeviceAddressStatus::kInHost);
  302. mem_manager_->FreeMemFromMemPool(device_address_swap_out);
  303. }
  304. }
  305. ret = mem_manager_->MallocMemFromMemPool(device_address, size);
  306. if (!ret) {
  307. return false;
  308. }
  309. }
  310. return true;
  311. }
  312. void *GPUKernelRuntime::AttemptMallocMem(size_t size) {
  313. MS_EXCEPTION_IF_NULL(mem_manager_);
  314. auto device_ptr = mem_manager_->MallocMemFromMemPool(size);
  315. if (!device_ptr) {
  316. if (!mem_swap_manager_->trigger_swap()) {
  317. return nullptr;
  318. }
  319. mem_swap_manager_->SyncMemCopyStream(SwapKind::kDeviceToHost);
  320. while (auto device_address_swap_out = mem_swap_manager_->UpdateSwapQueue(SwapKind::kDeviceToHost)) {
  321. if (!mem_swap_manager_->FindInSwapInBlackList(device_address_swap_out->ptr_) && device_address_swap_out->ptr_) {
  322. device_address_swap_out->set_status(DeviceAddressStatus::kInHost);
  323. mem_manager_->FreeMemFromMemPool(device_address_swap_out);
  324. }
  325. }
  326. device_ptr = mem_manager_->MallocMemFromMemPool(size);
  327. if (!device_ptr) {
  328. return nullptr;
  329. }
  330. }
  331. return device_ptr;
  332. }
  333. bool GPUKernelRuntime::AllocKernelDynamicRes(const mindspore::kernel::KernelMod &kernel_mod,
  334. const mindspore::AnfNodePtr &kernel, AddressPtrList *kernel_inputs,
  335. AddressPtrList *kernel_workspaces, AddressPtrList *kernel_outputs) {
  336. if (!AllocKernelInputDynamicRes(kernel, kernel_inputs)) {
  337. return false;
  338. }
  339. if (!AllocKernelOutputDynamicRes(kernel_mod, kernel, kernel_outputs)) {
  340. return false;
  341. }
  342. if (!AllocKernelWorkspaceDynamicRes(kernel_mod, kernel, kernel_workspaces)) {
  343. return false;
  344. }
  345. return true;
  346. }
  347. bool GPUKernelRuntime::AllocKernelInputDynamicRes(const mindspore::AnfNodePtr &kernel, AddressPtrList *kernel_inputs) {
  348. MS_EXCEPTION_IF_NULL(kernel);
  349. MS_EXCEPTION_IF_NULL(kernel_inputs);
  350. MS_EXCEPTION_IF_NULL(mem_swap_manager_);
  351. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) {
  352. // Graph may be all nop nodes and not remove nop node, so this can not skip nop node.
  353. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i, false);
  354. MS_EXCEPTION_IF_NULL(device_address);
  355. if (mem_swap_manager_->trigger_swap()) {
  356. while (auto device_address_swap_in = mem_swap_manager_->UpdateSwapQueue(SwapKind::kHostToDevice)) {
  357. device_address_swap_in->set_status(DeviceAddressStatus::kInDevice);
  358. }
  359. auto status = device_address->status();
  360. switch (status) {
  361. case DeviceAddressStatus::kInDevice:
  362. break;
  363. case DeviceAddressStatus::kInHost:
  364. break;
  365. case DeviceAddressStatus::kInDeviceToHost: {
  366. mem_swap_manager_->InsertSwapInBlackList(device_address->ptr_);
  367. device_address->set_status(DeviceAddressStatus::kInDevice);
  368. break;
  369. }
  370. case DeviceAddressStatus::kInHostToDevice: {
  371. while (device_address->status() != DeviceAddressStatus::kInDevice) {
  372. while (auto device_address_swap_in = mem_swap_manager_->UpdateSwapQueue(SwapKind::kHostToDevice)) {
  373. device_address_swap_in->set_status(DeviceAddressStatus::kInDevice);
  374. }
  375. }
  376. break;
  377. }
  378. default:
  379. MS_LOG(ERROR) << "Invaild device address status";
  380. return false;
  381. }
  382. }
  383. MS_EXCEPTION_IF_NULL(device_address->ptr_);
  384. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  385. MS_EXCEPTION_IF_NULL(input);
  386. input->addr = device_address->ptr_;
  387. input->size = device_address->size_;
  388. kernel_inputs->emplace_back(input);
  389. }
  390. return true;
  391. }
  392. bool GPUKernelRuntime::AllocKernelOutputDynamicRes(const mindspore::kernel::KernelMod &kernel_mod,
  393. const mindspore::AnfNodePtr &kernel,
  394. AddressPtrList *kernel_outputs) {
  395. MS_EXCEPTION_IF_NULL(kernel);
  396. MS_EXCEPTION_IF_NULL(kernel_outputs);
  397. MS_EXCEPTION_IF_NULL(mem_manager_);
  398. MS_EXCEPTION_IF_NULL(mem_swap_manager_);
  399. if (mem_swap_manager_->trigger_swap()) {
  400. while (auto device_address_swap_out = mem_swap_manager_->UpdateSwapQueue(SwapKind::kDeviceToHost)) {
  401. if (!mem_swap_manager_->FindInSwapInBlackList(device_address_swap_out->ptr_) && device_address_swap_out->ptr_) {
  402. device_address_swap_out->set_status(DeviceAddressStatus::kInHost);
  403. mem_manager_->FreeMemFromMemPool(device_address_swap_out);
  404. }
  405. }
  406. }
  407. auto output_sizes = kernel_mod.GetOutputSizeList();
  408. for (size_t i = 0; i < output_sizes.size(); ++i) {
  409. auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i, false);
  410. MS_EXCEPTION_IF_NULL(device_address);
  411. if (device_address->ptr_ == nullptr && !AttemptMallocMem(device_address, output_sizes[i])) {
  412. return false;
  413. }
  414. kernel::AddressPtr output = std::make_shared<kernel::Address>();
  415. MS_EXCEPTION_IF_NULL(output);
  416. output->addr = device_address->ptr_;
  417. output->size = output_sizes[i];
  418. kernel_outputs->emplace_back(output);
  419. }
  420. return true;
  421. }
  422. bool GPUKernelRuntime::AllocKernelWorkspaceDynamicRes(const mindspore::kernel::KernelMod &kernel_mod,
  423. const mindspore::AnfNodePtr &kernel,
  424. AddressPtrList *kernel_workspaces) {
  425. MS_EXCEPTION_IF_NULL(kernel);
  426. MS_EXCEPTION_IF_NULL(kernel_workspaces);
  427. auto workspace_sizes = kernel_mod.GetWorkspaceSizeList();
  428. for (size_t i = 0; i < workspace_sizes.size(); ++i) {
  429. if (workspace_sizes[i] == 0) {
  430. kernel_workspaces->emplace_back(nullptr);
  431. continue;
  432. }
  433. auto device_ptr = AttemptMallocMem(workspace_sizes[i]);
  434. if (!device_ptr) {
  435. return false;
  436. }
  437. kernel::AddressPtr workspace = std::make_shared<kernel::Address>();
  438. MS_EXCEPTION_IF_NULL(workspace);
  439. workspace->addr = device_ptr;
  440. workspace->size = workspace_sizes[i];
  441. kernel_workspaces->emplace_back(workspace);
  442. }
  443. return true;
  444. }
  445. void GPUKernelRuntime::AllocCommunicationOpDynamicRes(const session::KernelGraph *graph) {
  446. MS_EXCEPTION_IF_NULL(graph);
  447. auto &kernels = graph->execution_order();
  448. for (auto &kernel : kernels) {
  449. MS_EXCEPTION_IF_NULL(kernel);
  450. if (AnfAlgo::IsCommunicationOp(kernel)) {
  451. AllocCommunicationOpInputDynamicRes(kernel);
  452. AllocCommunicationOpOutputDynamicRes(kernel);
  453. }
  454. }
  455. }
  456. void GPUKernelRuntime::AllocCommunicationOpInputDynamicRes(const mindspore::AnfNodePtr &kernel) {
  457. MS_EXCEPTION_IF_NULL(kernel);
  458. bool is_need_alloc_memory = false;
  459. bool is_need_free_memory = false;
  460. size_t total_size = 0;
  461. std::vector<size_t> size_list;
  462. DeviceAddressPtrList addr_list;
  463. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) {
  464. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i, false);
  465. MS_EXCEPTION_IF_NULL(device_address);
  466. if (device_address->ptr_ == nullptr) {
  467. is_need_alloc_memory = true;
  468. } else {
  469. is_need_free_memory = true;
  470. }
  471. total_size += device_address->size_;
  472. size_list.emplace_back(device_address->size_);
  473. addr_list.emplace_back(device_address);
  474. }
  475. AllocCommunicationOpMemory(is_need_alloc_memory, is_need_free_memory, addr_list, total_size, size_list);
  476. }
  477. void GPUKernelRuntime::AllocCommunicationOpOutputDynamicRes(const mindspore::AnfNodePtr &kernel) {
  478. MS_EXCEPTION_IF_NULL(kernel);
  479. bool is_need_alloc_memory = false;
  480. bool is_need_free_memory = false;
  481. size_t total_size = 0;
  482. std::vector<size_t> size_list;
  483. DeviceAddressPtrList addr_list;
  484. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  485. MS_EXCEPTION_IF_NULL(kernel_mod);
  486. auto output_sizes = kernel_mod->GetOutputSizeList();
  487. for (size_t i = 0; i < output_sizes.size(); ++i) {
  488. auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i, false);
  489. MS_EXCEPTION_IF_NULL(device_address);
  490. if (device_address->ptr_ == nullptr) {
  491. is_need_alloc_memory = true;
  492. } else {
  493. is_need_free_memory = true;
  494. }
  495. total_size += output_sizes[i];
  496. size_list.emplace_back(output_sizes[i]);
  497. addr_list.emplace_back(device_address);
  498. }
  499. AllocCommunicationOpMemory(is_need_alloc_memory, is_need_free_memory, addr_list, total_size, size_list);
  500. }
  501. void GPUKernelRuntime::AllocCommunicationOpMemory(bool is_need_alloc_memory, bool is_need_free_memory,
  502. const DeviceAddressPtrList addr_list, size_t total_size,
  503. std::vector<size_t> size_list) {
  504. MS_EXCEPTION_IF_NULL(mem_manager_);
  505. if (!is_need_alloc_memory) {
  506. return;
  507. }
  508. if (is_need_free_memory) {
  509. for (const auto &iter : addr_list) {
  510. MS_EXCEPTION_IF_NULL(iter);
  511. // Free the inputs/outputs of communication kernel which are not released.
  512. if (iter->ptr_ != nullptr) {
  513. mem_manager_->FreeMemFromMemPool(iter);
  514. }
  515. }
  516. }
  517. auto ret = mem_manager_->MallocContinuousMemFromMemPool(addr_list, total_size, size_list);
  518. if (!ret) {
  519. MS_LOG(EXCEPTION) << "Malloc device memory failed.";
  520. }
  521. }
  522. void GPUKernelRuntime::FreeKernelDynamicRes(const mindspore::AnfNodePtr &kernel,
  523. const AddressPtrList &kernel_workspaces, uint32_t graph_id) {
  524. MS_EXCEPTION_IF_NULL(kernel);
  525. MS_EXCEPTION_IF_NULL(mem_manager_);
  526. auto mem_reuse_util_ptr = mem_reuse_util_map_[graph_id];
  527. MS_EXCEPTION_IF_NULL(mem_reuse_util_ptr);
  528. auto cnode = kernel->cast<CNodePtr>();
  529. MS_EXCEPTION_IF_NULL(cnode);
  530. if (AnfAlgo::GetCNodeName(kernel) == kAllReduceOpName) {
  531. return;
  532. }
  533. // Free the input of kernel by reference count.
  534. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) {
  535. auto kernel_ref_count_ptr = mem_reuse_util_ptr->GetKernelInputRef(cnode, i);
  536. if (kernel_ref_count_ptr == nullptr) {
  537. continue;
  538. }
  539. kernel_ref_count_ptr->ref_count_dynamic_use_--;
  540. if (kernel_ref_count_ptr->ref_count_dynamic_use_ < 0) {
  541. MS_LOG(EXCEPTION) << "Check dynamic reference count failed.";
  542. }
  543. if (kernel_ref_count_ptr->ref_count_dynamic_use_ == 0) {
  544. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i, false);
  545. mem_manager_->FreeMemFromMemPool(device_address);
  546. device_address->set_status(DeviceAddressStatus::kInDevice);
  547. }
  548. }
  549. // Free the output of kernel, if output has no reference.
  550. for (size_t i = 0; i < AnfAlgo::GetOutputTensorNum(kernel); ++i) {
  551. auto kernel_ref_count_ptr = mem_reuse_util_ptr->GetRef(cnode, i);
  552. if (kernel_ref_count_ptr == nullptr) {
  553. continue;
  554. }
  555. if (kernel_ref_count_ptr->ref_count_dynamic_use_ == 0) {
  556. auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i, false);
  557. mem_manager_->FreeMemFromMemPool(device_address);
  558. device_address->set_status(DeviceAddressStatus::kInDevice);
  559. }
  560. }
  561. // Free the workspace of kernel.
  562. for (size_t i = 0; i < kernel_workspaces.size(); ++i) {
  563. auto workspace = kernel_workspaces[i];
  564. if (workspace != nullptr) {
  565. MS_EXCEPTION_IF_NULL(workspace->addr);
  566. mem_manager_->FreeMemFromMemPool(workspace->addr);
  567. workspace->addr = nullptr;
  568. }
  569. }
  570. }
  571. } // namespace gpu
  572. } // namespace device
  573. } // namespace mindspore