我正在学习使用 cupy。但是我发现了一个非常令人困惑的问题。似乎 cupy 起初在一个程序中表现不错。当它运行一段时间后,Cupy 似乎慢了很多。这是代码:
import cupy as np
from line_profiler import LineProfiler
def test(ary):
for i in range(1000):
ary**6
def main():
rand=np.random.rand(1024,1024)
test(rand)
test(rand)
test(rand)
test(rand)
test(rand)
test(rand)
test(rand)
lp = LineProfiler()
lp_wrapper = lp(main)
lp_wrapper()
lp.print_stats()
这是时间表现:
Timer unit: 2.85103e-07 s
Total time: 16.3308 s
File: E:\Desktop\test.py
Function: main at line 8
Line # Hits Time Per Hit % Time Line Contents
==============================================================
8 def main():
9 1 1528817.0 1528817.0 2.7 rand=np.random.rand(1024,1024)
10 1 111014.0 111014.0 0.2 test(rand)
11 1 94528.0 94528.0 0.2 test(rand)
12 1 95636.0 95636.0 0.2 test(rand)
13 1 94892.0 94892.0 0.2 test(rand)
14 1 7728318.0 7728318.0 13.5 test(rand)
15 1 23872383.0 23872383.0 41.7 test(rand)
16 1 23754666.0 23754666.0 41.5 test(rand)
当 cupy 完成 5000 次 power openrations 时,它变得非常慢。
这段代码是在windows上跑的,cuda版本是10.0
希望得到解答。非常感谢!
感谢您的回答!我打印了 Cupy 的内存使用情况:
import cupy as np
def test(ary):
mempool = cupy.get_default_memory_pool()
pinned_mempool = cupy.get_default_pinned_memory_pool()
for i in range(1000):
ary**6
print("used bytes: %s"%mempool.used_bytes())
print("total bytes: %s\n"%mempool.total_bytes())
def main():
rand=np.random.rand(1024,1024)
test(rand)
test(rand)
test(rand)
test(rand)
test(rand)
test(rand)
test(rand)
这是输出:
used bytes: 8388608
total bytes: 16777216
used bytes: 8388608
total bytes: 16777216
used bytes: 8388608
total bytes: 16777216
used bytes: 8388608
total bytes: 16777216
used bytes: 8388608
total bytes: 16777216
used bytes: 8388608
total bytes: 16777216
used bytes: 8388608
total bytes: 16777216
在迭代过程中,GPU 内存使用情况似乎保持不变。
请问有什么方法可以避免这种速度下降吗?
最佳答案
这是CUDA内核队列的问题。
请参阅以下内容:
在您的代码中观察到的短暂执行是假的,因为 cupy 在队列未满时立即返回。
实际表现是最后一行。
注意:这不是内存分配问题——正如我最初在最初的回答中建议的那样——但我在这里包含了原始答案以供记录。
原始(不正确)答案
可能是由于重新分配。
当您导入 cupy
时,cupy 会分配“一些”GPU 内存。当 cupy 使用所有这些时,它必须分配更多内存。这会增加执行时间。
关于python - 当迭代次数增加时,Cupy 变得更慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376218/