CUDA 内核参数
当调用CUDA内核进行特定线程配置时,是否有严格的规则 内核参数应该驻留在哪个内存空间(设备/主机)以及它们应该是什么类型?
假设我启动一个一维线程网格,
kernel<<<numblocks, threadsperblock >>> (/*parameters*/)
我可以传递一个整数参数int foo
,它是一个主机整数变量, 直接进入CUDA内核?或者我应该将cudaMalloc
内存存储为单个整数,例如dev_foo
,然后将cudaMemcpy
foo
放入devfoo
code> 然后将 devfoo
作为内核参数传递?
When invoking a CUDA kernel for a specific thread configuration, are there any strict rules on
which memory space (device/host) kernel parameters should reside in and what type they should be?
Suppose I launch a 1-D grid of threads with
kernel<<<numblocks, threadsperblock >>> (/*parameters*/)
Can I pass an integer parameter int foo
which is a host-integer variable,
directly to the CUDA kernel? Or should I cudaMalloc
memory for a single integer say dev_foo
and then cudaMemcpy
foo
into devfoo
and then pass devfoo
as a kernel parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
内核参数的规则是 C++ 参数传递规则以及设备和主机内存在物理上分离的事实的逻辑结果。
CUDA 不允许通过引用传递参数,因此您必须小心使用指针。
具体来说,您必须按值传递参数。传递用户定义类型要求默认复制构造函数或您自己的复制构造函数(如果存在)不包含任何内存分配(带有“new”或“malloc”的堆分配)。
总之,按值传递对于整数、浮点或其他基本类型以及简单的平面用户定义结构或类对象非常有效。
The rules for kernel arguments are a logical consequence of C++ parameter passing rules and the fact that device and host memory are physically separate.
CUDA does not allow passing arguments by reference and you must be careful with pointers.
Specifically, you must pass parameters by value. Passing user-defined types requires that the default copy-constructor or your own copy-constructor (if present) does not contain any memory allocations (heap allocations with "new" or "malloc").
In summary pass-by-value works well for integral, floating point or other primitive types, and simple flat user-defined structs or class objects.
您只需对数据块使用
cudaMalloc()
和cudaMemcpy()
即可。不是单个 int 之类的。您还可以将结构体作为参数传递,只要它们没有指向主机内存中数据块的成员即可。因此,根据经验:如果您将指针传递给内核,请确保它指向设备内存。
You only need to use
cudaMalloc()
andcudaMemcpy()
for blocks of data. Not singleint
s and the like. You also can passstruct
s as parameters, as long as they have no members pointing to a block of data in host memory.So as a rule of thumb: if you are passing a pointer to a kernel, make sure it points into device memory.