首页 > 解决方案 > 使用cupy时内存不足

问题描述

当我使用cupy处理一些大数组时,出现了内存不足的错误,但是当我检查nvidia-smi查看内存使用情况时,它没有达到我的GPU内存的限制,我正在使用nvidia geforce RTX 2060,GPU 内存为 6 GB,这是我的代码:

import cupy as cp

mempool = cp.get_default_memory_pool()
print(mempool.used_bytes())              # 0
print(mempool.total_bytes())             # 0

a = cp.random.randint(0, 256, (10980, 10980)).astype(cp.uint8)
a = a.ravel()
print(a.nbytes)                          # 120560400
print(mempool.used_bytes())              # 120560640
print(mempool.total_bytes())             # 602803712
# when I finish create this array, the nvidia-smi shows like this
#+-----------------------------------------------------------------------------+
 | NVIDIA-SMI 430.86       Driver Version: 430.86       CUDA Version: 10.2     |
 |-------------------------------+----------------------+----------------------+
 | GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |
 | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
 |===============================+======================+======================|
 |   0  GeForce RTX 2060   WDDM  | 00000000:01:00.0  On |                  N/A |
 | N/A   46C    P8     9W /  N/A |   1280MiB /  6144MiB |      1%      Default |
 +-------------------------------+----------------------+----------------------+

# but then I run this command, and error cames out
s_values, s_idx, s_counts = cp.unique(
    a, return_inverse=True, return_counts=True)
# and the error shows
# cupy.cuda.memory.OutOfMemoryError: out of memory to allocate 964483584 bytes (total 5545867264 bytes)
# the nvidia-smi shows
# +-----------------------------------------------------------------------------+
  | NVIDIA-SMI 430.86       Driver Version: 430.86       CUDA Version: 10.2     |
  |-------------------------------+----------------------+----------------------+
  | GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |
  | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
  |===============================+======================+======================|
  |   0  GeForce RTX 2060   WDDM  | 00000000:01:00.0  On |                  N/A |
  | N/A   45C    P8     9W /  N/A |   5075MiB /  6144MiB |      3%      Default |
  +-------------------------------+----------------------+----------------------+

似乎有足够的空间可以使用,为什么会发生这个错误,这是因为我的 GPU 没有足够的内存,还是因为我的代码错误或我没有正确分配内存。

标签: pythoncupy

解决方案


964,483,584 不是比你mempool.total_bytes()的 602,803,712 大吗?

正如评论中所说,您可以分批完成,而不是一次完成整个计算。


推荐阅读