Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Matrix multiplication (CUDA Kernel) on the device: C = A * B
- * wA is A's width and wB is B's width
- */
- template <int BLOCK_SIZE> __global__ void
- matrixMulCUDA_WSP(float *C, float *A, float *B, int width)
- {
- // Block index
- int bx = blockIdx.x;
- int by = blockIdx.y;
- // Thread index
- int tx = threadIdx.x;
- int ty = threadIdx.y;
- // Index of the first sub-matrix of A processed by the block
- int aBegin = width * BLOCK_SIZE * by;
- // Index of the last sub-matrix of A processed by the block
- int aEnd = aBegin + width - 1;
- // Step size used to iterate through the sub-matrices of A
- int aStep = BLOCK_SIZE;
- // Index of the first sub-matrix of B processed by the block
- int bBegin = BLOCK_SIZE * bx;
- // Step size used to iterate through the sub-matrices of B
- int bStep = BLOCK_SIZE * width;
- // Csub is used to store the element of the block sub-matrix
- // that is computed by the thread
- float Csub = 0;
- // Declaration of the shared memory array As used to
- // store the sub-matrix of A
- __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
- // Declaration of the shared memory array Bs used to
- // store the sub-matrix of B
- __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
- __shared__ float A_shared[BLOCK_SIZE][BLOCK_SIZE];
- // Declaration of the shared memory array Bs used to
- // store the sub-matrix of B
- __shared__ float B_shared[BLOCK_SIZE][BLOCK_SIZE];
- // Load the matrices from device memory
- // to shared memory; each thread loads
- // one element of each matrix
- As[ty][tx] = A[0 + width * ty + tx];
- Bs[ty][tx] = B[0 + width * ty + tx];
- // Loop over all the sub-matrices of A and B
- // required to compute the block sub-matrix
- for (int a = aBegin, b = bBegin;
- a <= aEnd;
- a += aStep, b += bStep) {
- // Load the matrices from device memory
- // to shared memory; each thread loads
- // one element of each matrix
- As[ty][tx] = A[a + width * ty + tx];
- Bs[ty][tx] = B[b + width * ty + tx];
- // Synchronize to make sure the matrices are loaded
- __syncthreads();
- As[ty][tx] = A_shared[a + width * ty + tx];
- Bs[ty][tx] = B_shared[b + width * ty + tx];
- // Multiply the two matrices together;
- // each thread computes one element
- // of the block sub-matrix
- #pragma unroll
- for (int k = 0; k < BLOCK_SIZE; ++k) {
- Csub += As[ty][k] * Bs[k][tx];
- }
- // Synchronize to make sure that the preceding
- // computation is done before loading two new
- // sub-matrices of A and B in the next iteration
- __syncthreads();
- }
- // Write the block sub-matrix to device memory;
- // each thread writes one element
- int c = width * BLOCK_SIZE * by + BLOCK_SIZE * bx;
- C[c + width * ty + tx] = Csub;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement