Pycuda 函数调用后如何释放内存?
例如下面的例子,如何释放a_gpu使用的内存,这样我就有足够的内存分配给b_gpu,而不是出现如下错误?
我尝试导入 from pycuda.tools import PooledDeviceAllocation
或 import pycuda.tools.PooledDeviceAllocation
希望使用 free() 函数,但它们在导入时都会导致错误ImportError: 无法从 'pycuda.tools' (D:\ProgramData\Anaconda3\lib\site-packages\pycuda\tools.py) 导入名称 'PooledDeviceAllocation'
和 ModuleNotFoundError: 没有名为 ' 的模块pycuda.tools.PooledDeviceAllocation'; “pycuda.tools”不是一个包
。如果它应该适用于较新版本的 Pycuda,但只是我的 Pycuda 版本太旧,是否有其他方法可以释放我的版本或旧版本的 Pycuda 中的内存?我希望升级 Pycuda 是最后的手段,因为我的 NVidia 卡已经是 2060 系列了,以防新版本的 Pycuda 不支持我的旧卡。
提前非常感谢。
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
import os
_path = r"D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64"
if os.system("cl.exe"):
os.environ['PATH'] += ';' + _path
if os.system("cl.exe"):
raise RuntimeError("cl.exe still not found, path probably incorrect")
import numpy as np
a = np.zeros(1000000000).astype(np.float32)
a_gpu = cuda.mem_alloc(a.nbytes)
cuda.memcpy_htod(a_gpu, a)
mod = SourceModule("""
__global__ void func1(float *a)
{
a[0] = 1;
}
""")
func = mod.get_function("func1")
func(a_gpu, block=(1,1,1))
a_out = np.empty_like(a)
cuda.memcpy_dtoh(a_out, a_gpu)
print (a_out)
# Memory release code wanted here
b = np.zeros(1000000000).astype(np.float32)
b_gpu = cuda.mem_alloc(b.nbytes)
cuda.memcpy_htod(b_gpu, b)
mod = SourceModule("""
__global__ void func2(float *b)
{
b[1] = 1;
}
""")
func = mod.get_function("func2")
func(b_gpu, block=(1,1,1))
b_out = np.empty_like(b)
cuda.memcpy_dtoh(b_out, b_gpu)
print (b_out)
[1. 0. 0. ... 0. 0. 0.]
Traceback (most recent call last):
File "D:\PythonProjects\Test\CUDA\Test_PyCUDA_MemoryRelease.py", line 47, in <module>
b_gpu = cuda.mem_alloc(b.nbytes)
MemoryError: cuMemAlloc failed: out of memory
最佳答案
尝试将 free()
应用于 DeviceAllocation
对象(在本例中为 a_gpu
)
import pycuda.driver as cuda
a = np.zeros(1000000000).astype(np.float32)
a_gpu = cuda.mem_alloc(a.nbytes)
a_gpu.free()
来自documentation :
free()
Release the held device memory now instead of when this object becomes unreachable. Any further use of the object is an error and will lead to undefined behavior.
检查:
cuda.mem_get_info()
关于python - 为 Pycuda 释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70332345/