我正在寻找使用 GPU 加速 bincount 计算的可能性。
numpy中的引用代码:
x_new = numpy.random.randint(0, 1000, 1000000)
%timeit numpy.bincount(x_new)
100 loops, best of 3: 2.33 ms per loop
我只想测量操作速度,而不是传递数组所花费的时间,所以我创建了一个共享变量:
x = theano.shared(numpy.random.randint(0, 1000, 1000000))
theano_bincount = theano.function([], T.extra_ops.bincount(x))
这个操作当然是高度可并行的,但实际上在 GPU 上这个代码比 CPU 版本慢很多倍:
%timeit theano_bincount()
10 loops, best of 3: 25.7 ms per loop
所以我的问题是:
- 性能如此低下的原因可能是什么?
- 我可以使用 theano 编写并行版本的 bincount 吗?
最佳答案
我认为你不能在 GPU 上进一步增加这个操作,除非你能以某种方式手动告诉 Theano 以并行方式执行,这似乎是不可能的。在 GPU 上,不应该并行完成的计算将以与 CPU 相同或更慢的速度完成。
引自 Daniel Renshaw :
To an extent, Theano expects you to focus more on what you want computed rather than on how you want it computed. The idea is that the Theano optimizing compiler will automatically parallelize as much as possible (either on GPU or on CPU using OpenMP).
还有一句引述:
You need to be able to specify your computation in terms of Theano operations. If those operations can be parallelized on the GPU, they should be parallelized automatically.
引自 Theano 的网页:
- Indexing, dimension-shuffling and constant-time reshaping will be equally fast on GPU as on CPU.
- Summation over rows/columns of tensors can be a little slower on the GPU than on the CPU.
我认为您唯一能做的就是在您的 .theanorc
文件中将 openmp
标志设置为 True
。
无论如何,我尝试了一个主意。它现在不起作用,但希望有人可以帮助我们让它发挥作用。如果可行,您也许可以在 GPU 上并行化操作。下面的代码尝试使用 CUDA API 在 GPU 中做所有事情。然而,有两个瓶颈不允许操作发生:1)目前(截至 2016 年 1 月 4 日) Theano 和 CUDA 不支持对任何数据类型的任何操作,而不是 float32 和 2) T.extra_ops.bincount()
仅适用于 int
数据类型。所以这可能是 Theano 无法完全并行化操作的瓶颈。
import theano.tensor as T
from theano import shared, Out, function
import numpy as np
import theano.sandbox.cuda.basic_ops as sbasic
shared_var = shared(np.random.randint(0, 1000, 1000000).astype(T.config.floatX), borrow = True)
x = T.vector('x');
computeFunc = T.extra_ops.bincount(sbasic.as_cuda_ndarray_variable(T.cast(x, 'int16')))
func = function([], Out(sbasic.gpu_from_host(computeFunc), borrow = True), givens = {x: shared_var})
来源
1- How do I set many elements in parallel in theano
2- http://deeplearning.net/software/theano/tutorial/using_gpu.html#what-can-be-accelerated-on-the-gpu
3- http://deeplearning.net/software/theano/tutorial/multi_cores.html
关于python - 如何强制 Theano 在 GPU 上并行化操作(测试用例 : numpy. bincount),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34520471/