gpt4 book ai didi

cuda - 故意导致 CUDA 设备上的共享内存发生库冲突

转载 作者:行者123 更新时间:2023-12-02 03:25:35 24 4
gpt4 key购买 nike

cuda 设备上的共享内存如何工作对我来说是个谜。我很好奇计算访问同一共享内存的线程数。为此我写了一个简单的程序

#include <cuda_runtime.h>
#include <stdio.h>

#define nblc 13
#define nthr 1024

//------------------------@device--------------------

__device__ int inwarpD[nblc];

__global__ void kernel(){
__shared__ int mywarp;

mywarp=0;
for (int i=0;i<5;i++) mywarp += (10000*threadIdx.x+1);
__syncthreads();

inwarpD[blockIdx.x]=mywarp;
}
//------------------------@host-----------------------

int main(int argc, char **argv){
int inwarpH[nblc];
cudaSetDevice(2);

kernel<<<nblc, nthr>>>();

cudaMemcpyFromSymbol(inwarpH, inwarpD, nblc*sizeof(int), 0, cudaMemcpyDeviceToHost);

for (int i=0;i<nblc;i++) printf("%i : %i\n",i, inwarpH[i]);
}

并在 K80 GPU 上运行。由于多个线程正在访问同一个共享内存变量,我预计该变量将被更新 5*nthr 次,尽管由于存储区冲突而不是在同一周期。但是,输出表明 mywarp 共享变量仅更新了 5 次。对于每个 block ,不同的线程完成了这个任务:

0 : 35150005
1 : 38350005
2 : 44750005
3 : 38350005
4 : 51150005
5 : 38350005
6 : 38350005
7 : 38350005
8 : 51150005
9 : 44750005
10 : 51150005
11 : 38350005
12 : 38350005

相反,我期待

 523776*10000+5*1024=5237765120

对于每个 block 。有人可以向我解释我对共享内存的理解在哪里失败。我还想知道一个 block 中的所有线程如何访问(更新)同一个共享变量。我知道不可能在同一个 MP 周期。连载对我来说很好,因为这将是一个罕见的事件。

最佳答案

让我们来看看它生成的 ptx。

//Declare some registers
.reg .s32 %r<5>;
.reg .s64 %rd<4>;

// demoted variable
.shared .align 4 .u32 _Z6kernelv$__cuda_local_var_35411_30_non_const_mywarp;

//load tid in register r1
mov.u32 %r1, %tid.x;

//multiple tid*5000+5 and store in r2
mad.lo.s32 %r2, %r1, 50000, 5;

//store result in shared memory
st.shared.u32 [_Z6kernelv$__cuda_local_var_35411_30_non_const_mywarp], %r2;

///synchronize
bar.sync 0;

//load from shared memory and store in r3
ld.shared.u32 %r3, [_Z6kernelv$__cuda_local_var_35411_30_non_const_mywarp];

mov.u32 %r4, %ctaid.x;
mul.wide.u32 %rd1, %r4, 4;
mov.u64 %rd2, inwarpD;
add.s64 %rd3, %rd2, %rd1;

//store r3 in global memory
st.global.u32 [%rd3], %r3;
ret;

基本上是这样

for (int i=0;i<5;i++)
mywarp += (10000*threadIdx.x+1);

正在优化到

mywarp=50000*threadIdx.x+5

所以您没有遇到银行冲突。您遇到了竞争条件。

关于cuda - 故意导致 CUDA 设备上的共享内存发生库冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com