我的目标:
我有一个脚本,可以在给定范围内因式分解质数:
# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
我希望使用GPU而非CPU来运行此脚本以提高速度。
问题:
我的Intel NUC NUC8i7HVK没有NVIDIA GPU,而是一个“离散GPU”
如果我运行以下代码检查我的GPU:
import pyopencl as cl
import numpy as np
a = np.arange(32).astype(np.float32)
res = np.empty_like(a)
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
mf = cl.mem_flags
a_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a)
dest_buf = cl.Buffer(ctx, mf.WRITE_ONLY, res.nbytes)
prg = cl.Program(ctx, """
__kernel void sq(__global const float *a,
__global float *c)
{
int gid = get_global_id(0);
c[gid] = a[gid] * a[gid];
}
""").build()
prg.sq(queue, a.shape, None, a_buf, dest_buf)
cl.enqueue_copy(queue, res, dest_buf)
print (a, res)
我收到:
[0] <pyopencl.Platform 'AMD Accelerated Parallel Processing' at 0x7ffb3d492fd0>
[1] <pyopencl.Platform 'Intel(R) OpenCL HD Graphics' at 0x187b648ed80>
解决问题的可能方法:
我找到一篇指南,手把手地讲解了如何在GPU上运行它,并且步骤非常详细。但是所有将Python程序通过GPU进行处理的库,如PyOpenGL,PyOpenCL,Tensorflow (Force python script on GPU),PyTorch等都是为NVIDIA量身定制的。
如果你有AMD,所有的库都要求安装ROCm,但据我所知,这种软件仍不支持集成GPU或离散GPU(请看下面我的回复)。
我只发现了一篇指南,涉及这种方法,但我无法使其工作。
是否有希望,还是我在尝试做一件不可能的事情?
编辑:回复@chapelo
如果我选择0
,则回复为:
Set the environment variable PYOPENCL_CTX='0' to avoid being asked again.
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.
18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.] [ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81. 100. 121. 144. 169.
196. 225. 256. 289. 324. 361. 400. 441. 484. 529. 576. 625. 676. 729.
784. 841. 900. 961.]
如果我选择
1
,则回复如下:Set the environment variable PYOPENCL_CTX='1' to avoid being asked again.
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.
18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.] [ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81. 100. 121. 144. 169.
196. 225. 256. 289. 324. 361. 400. 441. 484. 529. 576. 625. 676. 729.
784. 841. 900. 961.]
0
。现在我该如何告诉Python在运行该脚本时使用GPU呢? - Francesco Mantovanicl.create_some_context()
,而是自己指定上下文,例如ctx = cl.Context(dev_type=cl.device_type.ALL, properties=[(cl.context_properties.PLATFORM, plat[0])])
。 - chapelo