我正在学习使用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次电源开启时,它变得很慢。

我在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 内核队列的问题。

请参阅以下内容:

  • https://github.com/cupy/cupy/issues/1294
  • https://github.com/cupy/cupy/issues/1765

  • 在您的代码中观察到的短执行是假的,因为当队列未满时,cupy 会立即返回。

    实际表现是最后一行。

    注意: 这不是内存分配问题——正如我最初在我的初始答案中所建议的那样——但我在这里包含了记录的原始答案。

    原始(错误)答案

    可能是由于重新分配。

    当您 import cupy 时,cupy 会分配“一些”GPU 内存。当cupy使用所有这些时,它必须分配更多的内存。这会增加执行时间。

    关于python - 当迭代增加时,Cupy 变得更慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54376218/

    10-11 04:33