使用共享内存平铺技术在CUDA中乘以矩阵

时间:2013-01-04 17:45:24

标签: c matrix cuda

在下面的作业代码中我需要找出平铺矩阵乘法需要更多边界条件才能工作。请帮帮我,我已经试了一个星期找出问题所在是吗?

#include    <wb.h>

#define TILE_WIDTH 16


__global__ void matrixMultiplyShared(float * A, float * B, float * C,

                     int numARows, int numAColumns,
                     int numBRows, int numBColumns,
                     int numCRows, int numCColumns) {

//@@ Insert code to implement matrix multiplication here
//@@ You have to use shared memory for this MP
  __shared__ float s_A[TILE_WIDTH][TILE_WIDTH];
  __shared__ float s_B[TILE_WIDTH][TILE_WIDTH];

  int tx= threadIdx.x; int ty = threadIdx.y;
  int bx= blockIdx.x ; int by = blockIdx.y ;

  int Row = by*TILE_WIDTH + ty;
  int Col = bx*TILE_WIDTH + tx;



   if((Row < numARows  ) && (Col < numBColumns )) {


 float Pvalue =0.0;
  for (int m = 0; m < (numAColumns-1)/TILE_WIDTH+1; ++m) {

    if((Row < numARows) && ( (m*TILE_WIDTH+tx) < numAColumns)) {

      s_A[ty][tx] = A[Row*numAColumns +( m*TILE_WIDTH+tx)];
    }
    else
    {
      s_A[ty][tx] = 0.0;
    }
    if(((m*TILE_WIDTH+ty) < numBRows) && (Col < numBColumns)) {

      s_B[ty][tx] = B[(m*TILE_WIDTH+ty)*numBColumns+Col];
    }
    else
    {
      s_B[ty][tx] = 0.0;
    }
    __syncthreads();

   if((Row < numARows  ) && (Col < numBColumns )) {
    for (int k = 0; k < TILE_WIDTH; ++k)
      {

         Pvalue += s_A[ty][k] * s_B[k][tx];

      }
    __syncthreads();

  }
  }
    if((Row < numARows  ) && (Col < numBColumns )) { 
       C[Row*numCColumns+Col] = Pvalue;
    }
}
else
return;
}

1 个答案:

答案 0 :(得分:2)

问题在于进入加载TILE的循环的条件,即if((Row&lt; numARows)&amp;&amp;(Col&lt; numBColumns)),并且下次再次检查它在为每个加载的TILE执行结果元素的实际计算时,只有最后一个条件,即写入全局的条件就足够了。您可以找到参考here

的详细实施