另一个答案非常危险!自己计算车道标识和线程块标识。
#include <cuda.h>
#include <iostream>
inline __device__ unsigned get_lane_id() {
unsigned ret;
asm volatile("mov.u32 %0, %laneid;" : "=r"(ret));
return ret;
}
inline __device__ unsigned get_warp_id() {
unsigned ret;
asm volatile("mov.u32 %0, %warpid;" : "=r"(ret));
return ret;
}
__global__ void kernel() {
const int actual_warpid = get_warp_id();
const int actual_laneid = get_lane_id();
const int expected_warpid = threadIdx.x / 32;
const int expected_laneid = threadIdx.x % 32;
if (expected_laneid == 0) {
printf("[warp:] actual: %i expected: %i\n", actual_warpid,
expected_warpid);
printf("[lane:] actual: %i expected: %i\n", actual_laneid,
expected_laneid);
}
}
int main(int argc, char const *argv[]) {
dim3 grid(8, 7, 1);
dim3 block(4 * 32, 1);
kernel<<<grid, block>>>();
cudaDeviceSynchronize();
return 0;
}
这会得到类似于以下的结果:
[warp:] actual: 4 expected: 3
[warp:] actual: 10 expected: 0
[warp:] actual: 1 expected: 1
[warp:] actual: 12 expected: 1
[warp:] actual: 4 expected: 3
[warp:] actual: 0 expected: 0
[warp:] actual: 13 expected: 2
[warp:] actual: 12 expected: 1
[warp:] actual: 6 expected: 1
[warp:] actual: 6 expected: 1
[warp:] actual: 13 expected: 2
[warp:] actual: 10 expected: 0
[warp:] actual: 1 expected: 1
...
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
[lane:] actual: 0 expected: 0
请参阅PTX文档。
预定义的只读特殊寄存器,返回线程所在warp的标识符。warp标识符提供CTA内唯一的warp编号,但不跨越网格中的CTA。单个warp内的所有线程的warp标识符将相同。
请注意,%warpid是易失性的,并在读取时返回线程位置,但其值可能在执行期间更改,例如,由于抢占后线程的重新调度。
因此,它是调度程序的warp-id,不能保证与虚拟warp-id(从0开始计数)匹配。
文档已经表明:
因此,在核心代码中,如果需要这样的值,则应使用%ctaid和%tid来计算虚拟warp索引;%warpid主要用于启用分析和诊断代码采样和记录信息,例如工作场所映射和负载分布。
如果您认为可以使用CUB解决此问题:这甚至会影响 cub::WarpId()
返回调用线程的warp ID。 Warp ID保证在warp之间是唯一的,但可能不对应于线程块内的基于零的排名。
编辑:使用%laneid
似乎是安全的。
threadIdx.x&0x1f
来获取lane id,这相当于threadIdx.x%32
。 - Azmisov