[問題] CUDA關於Threads新手問題

看板C_and_CPP (C/C++)作者 (Alexam)時間11年前 (2014/12/31 22:21), 11年前編輯推噓0(0015)
留言15則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VS2013 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) CUDA 問題(Question): 先附上程式碼: http://ideone.com/RwJCBZ 給一個input array 並且總共有GridDim*BlockDim個Threads(例子裡面是1*4) 假設 Input[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; ^^^^^^^ ^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^ Thread1 Thread2 Thread3 Thread4 希望用Threads分別把各自的Input範圍加總 Output[0]=1+2+3+4 = 6; Output[1]=5+6+7+8 = 22; Output[2]=9+10+11+12 = 38; Output[3]=12+13+14+15 = 54; 但這個程式好像只有在GridDim=1的情況下才會正確 如果GridDim不為1,譬如(2*2) 雖然一樣是有4個Threads, 但是就只有第一個Block的Threads答案會正確, 錯誤Output如下: Output[0]=6; Output[1]=22; Output[2]=14; Output[3]=30; 想請問是否我__global__ kernel的部分有理解錯誤嗎? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.62.9 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1420035668.A.260.html

01/01 01:18, , 1F
原本結果應該就是錯的吧 你的output array根本沒有初始化
01/01 01:18, 1F

01/01 01:20, , 2F
然後你改用2D grid的時候有考慮到blockIdx.y嗎?
01/01 01:20, 2F

01/01 01:32, , 3F
若是2D grid和1D block要把他map到一維index 你的idx應該是
01/01 01:32, 3F

01/01 01:34, , 4F
(blockIdx.y * gridDim.x + blockIdx.x) * blockDim.x +
01/01 01:34, 4F

01/01 01:34, , 5F
threadIdx.x
01/01 01:34, 5F
Host的Output array我有在第29行有初始化,網頁裡的多一個分號 int h_output[PATHS] = { 0 }; 另外我不太懂改用2D grid是什麼意思? 我的確是想把2D矩陣在1D array裡使用, 我的想法如下 譬如N*M的矩陣,mapping到1D array有N*M個elements 但是我只有GridDim*BlockDim=N個Threads 所以我每個Threads要加M個elements 小弟剛學CUDA,觀念不清楚請多多指教^^ ※ 編輯: qcmi (1.171.62.9), 01/01/2015 13:04:16

01/01 14:19, , 6F
可是你cudaMalloc出來在device上的output array沒有初始化啊
01/01 14:19, 6F

01/01 14:45, , 7F
我是直接參考cuda vecAdd的範例,output array在cudaMalloc完
01/01 14:45, 7F

01/01 14:47, , 8F
之後好像就直接呼叫Kernel計算了, output沒有cudaMemcpy到
01/01 14:47, 8F

01/01 14:48, , 9F
device, 請問這樣是錯的嗎? d_output也要用cudaMemcpy?
01/01 14:48, 9F

01/01 14:48, , 10F
因為vector add是直接用=給值啊 你用+=原本就要先初始化
01/01 14:48, 10F

01/01 14:49, , 11F
以你的例子應該是迴圈開始前先清成0就好 或是用cudaMemset
01/01 14:49, 11F

01/01 14:56, , 12F
至於設計上的問題 你目前的寫法就和你想的一樣不是嗎@@
01/01 14:56, 12F

01/01 14:56, , 13F
不懂為什麼要把2D的grid扯進來把問題複雜化
01/01 14:56, 13F
在Kernel的部分我更新了程式碼, 謝謝^^ http://ideone.com/wVWRwi 改成先宣告int sum = 0; 然後才用for迴圈去跑sum+=input[i]; 最後再讓output[idx]=sum; 這樣還需要初始化d_output嗎? 因為我試了您給的建議,讓d_output都先為0,答案還是一樣錯誤@@ 我還是不太清楚什麼是2D的grid? 如果指的是GridDim 不等於1的話 是因為這只是個簡單的練習case 其實真的想做的是input array可能有100萬個elements 但每個Block的Threads數目有限 所以才會想用多個Block一起算比較快 ※ 編輯: qcmi (1.171.62.9), 01/01/2015 17:03:40

01/01 17:35, , 14F
原來你所謂的2*2是指2*2=4 我以為你是想要用dim3(2,2)...
01/01 17:35, 14F

01/01 17:36, , 15F
話說應該ndx = idx * steps吧?你現在這樣會加乘順序是錯的
01/01 17:36, 15F
文章代碼(AID): #1Kf0PK9W (C_and_CPP)
文章代碼(AID): #1Kf0PK9W (C_and_CPP)