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

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