python - PyCUDA + numpy,以及一般字符串处理

标签 python arrays numpy pycuda

我对标题中提到的所有内容都比较陌生,所以请耐心等待。

目前我陷入了 python 和 C 之间的转换。由于 CUDA 内核是用 C 编写的,所以我不能只用 python 的方式来看待它。

由于文档相当有限,并且对于初学者来说过于复杂,我想问一下 pyCuda 实际上如何转换 python(或 numpy)数组以在 C 中使用。

例如,字符串“stuff”在 C 中是一个字符数组,但在 python 中它是一个不可变的字符串。但是我可以执行以下操作:

stuff = "stuff"
d_stuff = cuda.mem_alloc(len(stuff))
cuda.memcpy_htod(d_stuff, stuff)

在 CUDA 内核中,现在我可以将它用作 char* d_stuff。

但是我无法以同样的方式取回它,因为 python 字符串是不可变的。因此,执行以下操作显然会引发错误:

newstuff = ""
cuda.memcpy_dtoh(newstuff, d_stuff)

我知道这些可以写成

d_stuff = gpuarray.to_gpu(numpy.array(stuff)) # I need numpy, as the to_gpu expects an array
newstuff = d_stuff.get()

但我不知道它是如何工作的,以及它在幕后的作用,所以如果有人能简要解释一下转换是如何工作的,我将非常感激。(例如第二个示例是如何工作的)返回一个字符串)

此外,我对使用 numpy 创建的数组有疑问。我已经看到它们广泛用于 GPU,但我不知道它们是如何工作的。

给 numpy 一个字符串是否会根据 C 代码创建一个字符数组,如果是,字符串数组是否会变成 char,或者其他什么?(当然当翻译成 C 时)

仅使用 C 语言编写 CUDA 代码可能会更好,但我想探索 python 的功能,并且我这样做是为了学习目的。

最佳答案

I'd like to ask how PyCUDA actually converts python(or numpy) arrays for use in C.

事实并非如此。 PyCUDA 只需采用任何支持 Python 的对象 buffer protocol (通常是 numpy 数组)并直接访问其主机内存缓冲区以将数据传输到 GPU 或从 GPU 传输数据。不执行任何类型转换或数据操作。。类型直接从 CTypes interface 推断出来,(通常通过 numpy dtype ,因为 numpy 数组是常用的数据源)。

Does giving numpy a string create an array of characters in terms of C code, if yes, does an array of strings become char, or something else?

这要看情况。例如这样做:

ttt = np.asarray([ "stuff" + str(i)  for i in range(0,20) ])

print( ttt.dtype, type(ttt[0]) ) 
|S7 <type 'numpy.string_'>

这里 numpy 使用特殊的固定长度字符串数据类型,其长度是根据输入数据计算的。这是一个有效的 C 有序数组 char[7]。查看更多here 。由于缓冲区协议(protocol)和底层直接映射到 native C 类型,PyCUDA 自动理解如何处理此问题。

但是您也可以这样做:

ttt = np.asarray([ "stuff" + str(i)  for i in range(0,20) ], dtype=object)

print( ttt.dtype, type(ttt[0]) )
object <type 'str'>

这里,创建的 numpy 数组包含 Python 对象(在本例中为字符串)。这不能在 PyCUDA 中使用,因为 Python 对象在 C 中没有直接表示。

关于python - PyCUDA + numpy,以及一般字符串处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038577/

相关文章:

python - 如何在 tf.keras 自定义损失函数中触发 python 函数?

python - 如何跳过python for循环中的索引

python - 在 Heroku 上部署现有的 Django 应用程序

python - Cython 使用 gmp 算术

java - 队列不循环,提前终止?

python - pandas astype python bool 而不是 numpy.bool_

python - 在Python中计算两个二维数组之间的行相关系数

javascript - 将赛季时间表分成几周而不重复球队比赛

c++ - 是什么导致这个数组值改变?

python - OpenCV 错误 : Unsupported format or combination of formats (Unsupported combination of input and output formats) in getRectSubPix