-
Notifications
You must be signed in to change notification settings - Fork 0
/
TiledMatrixMul.cu
407 lines (319 loc) · 12.7 KB
/
TiledMatrixMul.cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/**
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/**
* Matrix multiplication: C = A * B.
* Host code.
*
* This sample implements matrix multiplication which makes use of shared memory
* to ensure data reuse, the matrix multiplication is done using tiling approach.
* It has been written for clarity of exposition to illustrate various CUDA programming
* principles, not with the goal of providing the most performant generic kernel for matrix multiplication.
* See also:
* V. Volkov and J. Demmel, "Benchmarking GPUs to tune dense linear algebra,"
* in Proc. 2008 ACM/IEEE Conf. on Supercomputing (SC '08),
* Piscataway, NJ: IEEE Press, 2008, pp. Art. 31:1-11.
*/
// System includes
#include <stdio.h>
#include <assert.h>
#include<string> //z
// CUDA runtime
#include <cuda_runtime.h>
// Helper functions and utilities to work with CUDA
#include <helper_functions.h>
#include <helper_cuda.h>
#include<stdlib.h>
/**
* 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(float *C, float *A, float *B, int wA, int wB)
{
if(wA!=wB) //z
{
printf("A and B are not both square matrix\n"); //z
assert(0); //z
}
// 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 = wA * BLOCK_SIZE * by;
// Index of the last sub-matrix of A processed by the block
//z int aEnd = aBegin + wA - 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 * wB;
// Csub is used to store the element of the block sub-matrix
// that is computed by the thread
float Csub = 0;
int row = wA; //z
int XY_BLOCKS = (BLOCK_SIZE+row-1) /BLOCK_SIZE; //z
// Loop over all the sub-matrices of A and B
// required to compute the block sub-matrix
//z for (int a = aBegin, b = bBegin;
//z a <= aEnd;
//z a += aStep, b += bStep) {
int a = aBegin, b = bBegin; //z
// 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];
// Load the matrices from device memory
// to shared memory; each thread loads
// one element of each matrix
//z As[ty][tx] = A[a + wA * ty + tx];
//z Bs[ty][tx] = B[b + wB * ty + tx];
for(int i=0;i<XY_BLOCKS;i++) //z
{
if((i*BLOCK_SIZE+tx)<row &&(by*BLOCK_SIZE+ty)<row) //z
{
As[ty][tx] = A[a + row * ty + tx]; //z
}
else{
As[ty][tx] = 0; //z
}
if((i*BLOCK_SIZE+ty)<row &&(bx*BLOCK_SIZE+tx)<row) //z
{
Bs[ty][tx] = B[b + row * ty + tx];//z
}
else{
Bs[ty][tx] = 0; //z
}
a += aStep; //z
b += bStep; //z
// Synchronize to make sure the matrices are loaded
__syncthreads();
// 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();
}
//z // Synchronize to make sure the matrices are loaded
//z __syncthreads();
// Multiply the two matrices together;
// each thread computes one element
// of the block sub-matrix
//z #pragma unroll
//z for (int k = 0; k < BLOCK_SIZE; ++k) {
//z Csub += As[ty][k] * Bs[k][tx];
//z }
// Synchronize to make sure that the preceding
// computation is done before loading two new
// sub-matrices of A and B in the next iteration
//z __syncthreads();
//z }
// Write the block sub-matrix to device memory;
// each thread writes one element
//z int c = wB * BLOCK_SIZE * by + BLOCK_SIZE * bx;
//z C[c + wB * ty + tx] = Csub; //TODO
if((BLOCK_SIZE*bx+tx)<row && ((BLOCK_SIZE*by+ty)<row))
{
C[row * (BLOCK_SIZE * by+ty) + (BLOCK_SIZE * bx + tx) ] = Csub;
}
}
void ConstantInit(float *data, int size, float val) {
for (int i = 0; i < size; ++i) {
data[i] = val;
}
}
/**
* Run a simple test of matrix multiplication using CUDA
*/
int MatrixMultiply(int argc, char **argv,
int block_size, const dim3 &dimsA,
const dim3 &dimsB) {
// Allocate host memory for matrices A and B
unsigned int size_A = dimsA.x * dimsA.y;
unsigned int mem_size_A = sizeof(float) * size_A;
float *h_A = reinterpret_cast<float *>(malloc(mem_size_A));
unsigned int size_B = dimsB.x * dimsB.y;
unsigned int mem_size_B = sizeof(float) * size_B;
float *h_B = reinterpret_cast<float *>(malloc(mem_size_B));
// Initialize host memory
const float valB = 0.01f;
ConstantInit(h_A, size_A, 1.0f);
ConstantInit(h_B, size_B, valB);
// Allocate device memory
float *d_A, *d_B, *d_C;
// Allocate host matrix C
dim3 dimsC(dimsB.x, dimsA.y, 1);
unsigned int mem_size_C = dimsC.x * dimsC.y * sizeof(float);
float *h_C = reinterpret_cast<float *>(malloc(mem_size_C));
if (h_C == NULL) {
fprintf(stderr, "Failed to allocate host matrix C!\n");
exit(EXIT_FAILURE);
}
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_A), mem_size_A));
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_B), mem_size_B));
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_C), mem_size_C));
// copy host memory to device
checkCudaErrors(cudaMemcpy(d_A, h_A, mem_size_A, cudaMemcpyHostToDevice));
checkCudaErrors(cudaMemcpy(d_B, h_B, mem_size_B, cudaMemcpyHostToDevice));
// Setup execution parameters
dim3 threads(block_size, block_size);
//z dim3 grid(dimsB.x / threads.x, dimsA.y / threads.y);
dim3 grid((dimsB.x+block_size-1)/threads.x , (dimsA.y+block_size-1)/threads.y);
// Create and start timer
printf("Computing result using CUDA Kernel...\n");
// Performs warmup operation using TiledMatrixMul CUDA kernel
if (block_size == 16) {
MatrixMulCUDA<16> <<< grid, threads >>>(d_C, d_A, d_B,
dimsA.x, dimsB.x);
} else {
MatrixMulCUDA<32> <<< grid, threads >>>(d_C, d_A, d_B,
dimsA.x, dimsB.x);
}
printf("done\n");
cudaDeviceSynchronize();
// Allocate CUDA events that we'll use for timing
cudaEvent_t start;
checkCudaErrors(cudaEventCreate(&start));
cudaEvent_t stop;
checkCudaErrors(cudaEventCreate(&stop));
// Record the start event
checkCudaErrors(cudaEventRecord(start, NULL));
// Execute the kernel
int nIter = 300;
for (int j = 0; j < nIter; j++) {
if (block_size == 16) {
MatrixMulCUDA<16> <<< grid, threads >>>(d_C, d_A, d_B,
dimsA.x, dimsB.x);
} else {
MatrixMulCUDA<32> <<< grid, threads >>>(d_C, d_A, d_B,
dimsA.x, dimsB.x);
}
}
// Record the stop event
checkCudaErrors(cudaEventRecord(stop, NULL));
// Wait for the stop event to complete
checkCudaErrors(cudaEventSynchronize(stop));
float msecTotal = 0.0f;
checkCudaErrors(cudaEventElapsedTime(&msecTotal, start, stop));
// Compute and print the performance
float msecPerMatrixMul = msecTotal / nIter;
double flopsPerMatrixMul = 2.0 * static_cast<double>(dimsA.x) *
static_cast<double>(dimsA.y) *
static_cast<double>(dimsB.x);
double gigaFlops = (flopsPerMatrixMul * 1.0e-9f) /
(msecPerMatrixMul / 1000.0f);
printf(
"Performance= %.2f GFlop/s, Time= %.3f msec, Size= %.0f Ops," \
" WorkgroupSize= %u threads/block\n",
gigaFlops,
msecPerMatrixMul,
flopsPerMatrixMul,
threads.x * threads.y);
// Copy result from device to host
checkCudaErrors(cudaMemcpy(h_C, d_C, mem_size_C, cudaMemcpyDeviceToHost));
printf("Checking computed result for correctness: ");
bool correct = true;
// test relative error by the formula
// |<x, y>_cpu - <x,y>_gpu|/<|x|, |y|> < eps
double eps = 1.e-6; // machine zero
for (int i = 0; i < static_cast<int>(dimsC.x * dimsC.y); i++) {
double abs_err = fabs(h_C[i] - (dimsA.x * valB));
double dot_length = dimsA.x;
double abs_val = fabs(h_C[i]);
double rel_err = abs_err / abs_val / dot_length;
if (rel_err > eps) {
printf("Error! Matrix[%05d]=%.8f, ref=%.8f error term is > %E\n",
i, h_C[i], dimsA.x * valB, eps);
correct = false;
}
}
printf("%s\n", correct ? "Result = PASS" : "Result = FAIL");
// Clean up memory
free(h_A);
free(h_B);
free(h_C);
checkCudaErrors(cudaFree(d_A));
checkCudaErrors(cudaFree(d_B));
checkCudaErrors(cudaFree(d_C));
printf("\nNOTE: The CUDA Samples are not meant for performance"\
"measurements. Results may vary when GPU Boost is enabled.\n");
if (correct) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
/**
* Program main
*/
int main(int argc, char **argv) {
std::string Argv1(argv[1]); //z
std::string Argv2(argv[2]); //z
int row = atoi(argv[2]); //z
if(argc!=3 || strcmp(argv[1],"-i")!=0 || row <=0){ //z
printf("- Usage: ./TiledMatrixMul -i <rowDim>\n"); //z
if(row<=0) printf("- Usage: <rowDim> can't less than 1\n"); //z
return -1; //z
} //z
//z printf("[Matrix Multiply Using CUDA] - Starting...\n");
//zif (checkCmdLineFlag(argc, (const char **)argv, "help") ||
//z checkCmdLineFlag(argc, (const char **)argv, "?")) {
//z printf("Usage -device=n (n >= 0 for deviceID)\n");
//z printf(" -wA=WidthA -hA=HeightA (Width x Height of Matrix A)\n");
//z printf(" -wB=WidthB -hB=HeightB (Width x Height of Matrix B)\n");
//z printf(" Note: Outer matrix dimensions of A & B matrices" \
" must be equal.\n");
//z exit(EXIT_SUCCESS);
//z}
// This will pick the best possible CUDA capable device, otherwise
// override the device ID based on input provided at the command line
//z int dev = findCudaDevice(argc, (const char **)argv);
int block_size = 32;
//z dim3 dimsA(5 * 2 * block_size, 5 * 2 * block_size, 1);
//z dim3 dimsB(5 * 4 * block_size, 5 * 2 * block_size, 1);
dim3 dimsA(row, row, 1); //z
dim3 dimsB(row, row, 1); //z
// width of Matrix A
//z if (checkCmdLineFlag(argc, (const char **)argv, "wA")) {
//z dimsA.x = getCmdLineArgumentInt(argc, (const char **)argv, "wA");
//z }
// height of Matrix A
//z if (checkCmdLineFlag(argc, (const char **)argv, "hA")) {
//z dimsA.y = getCmdLineArgumentInt(argc, (const char **)argv, "hA");
//z }
// width of Matrix B
//z if (checkCmdLineFlag(argc, (const char **)argv, "wB")) {
//z dimsB.x = getCmdLineArgumentInt(argc, (const char **)argv, "wB");
//z }
// height of Matrix B
//z if (checkCmdLineFlag(argc, (const char **)argv, "hB")) {
//z dimsB.y = getCmdLineArgumentInt(argc, (const char **)argv, "hB");
//z }
// if (dimsA.x != dimsB.y) {
//z printf("Error: outer matrix dimensions must be equal. (%d != %d)\n",
//z dimsA.x, dimsB.y);
//z exit(EXIT_FAILURE);
//z }
printf("MatrixA(%d,%d), MatrixB(%d,%d)\n", dimsA.x, dimsA.y,
dimsB.x, dimsB.y);
int matrix_result = MatrixMultiply(argc, argv, block_size, dimsA, dimsB);
exit(matrix_result);
}