-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatMultCUDA.cu
673 lines (497 loc) · 15.8 KB
/
MatMultCUDA.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/*
* CPSC 4210
* - High Performance Parallel Computing
*
* Name: Austin Kothig
* ID: 001182645
* Sem: Spring 2018
*
* Purpose:
*
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <getopt.h>
#include <iostream>
/* Enable / Disable debugging */
#define debug 0
/* Block Size specification */
#define BLOCK 16
/* For running all Matrix Matrix Multiplication Tests */
void RunAllTests (int n);
/* Helper Function Prototypes */
float randomize (int *seed);
void clear (int n, float *X);
void stats (char* desc, int n, double *T, double *R);
void help ( );
void getGPUStats (cudaDeviceProp& prop);
int validate (int n, float *S, float *X);
/* Matrix Multiplication Prototypes*/
void global_cuda (int n, float *A, float *B, float *C);
void shared_cuda (int n, float *A, float *B, float *C);
/* kernel Function Implementation */
__global__
void global_cuda_kernel(int n, float* A, float* B, float* C) {
//-- get current position to be calculated
const unsigned int tx = threadIdx.x;
const unsigned int ty = threadIdx.y;
const unsigned int ROW = blockIdx.y * blockDim.y + ty;
const unsigned int COL = blockIdx.x * blockDim.x + tx;
float sum = 0.f;
//-- make sure we are valid
if (ROW < n && COL < n) {
//-- compute the element in block
for (int i = 0; i < n; i++) {
sum += B[ROW*n + i] * C[i*n + COL];
}
}
//-- write sum to device memory
A[ROW*n + COL] = sum;
}
__global__
void shared_cuda_kernel(int n, float* A, float* B, float* C) {
//-- get current position to be calculated
const unsigned int tx = threadIdx.x;
const unsigned int ty = threadIdx.y;
const unsigned int ROW = blockIdx.y * blockDim.y + ty;
const unsigned int COL = blockIdx.x * blockDim.x + tx;
const unsigned int grid = gridDim.y;
//-- allocate shared memory on the device
__shared__ float d_b[BLOCK][BLOCK], d_c[BLOCK][BLOCK];
//-- check that we are in range
if (ROW < n && COL < n) {
float sum = 0.f;
//-- scan through the elements of the grid
for (int i = 0; i < grid; i++) {
//-- load the block from device memory to shared memory
d_b[ty][tx] = B[ROW*n + i*BLOCK + tx];
d_c[ty][tx] = C[COL+n*(i*BLOCK + ty)];
//-- wait for all threads to load device memory
//-- into shared memory before continuing.
__syncthreads();
//-- multiply the shared memories together
for (int j = 0; j < BLOCK; j++) {
sum += d_b[ty][j] * d_c[j][tx];
}
//-- wait for all calculations to finish
__syncthreads();
}
//-- write to device memory
A[ROW*n + COL] = sum;
}
}
#if debug
/* Used to build a validation Matrix */
void optim_serial (int n, float *A, float *B, float *C);
/* Variables for error checking */
int ErrorCount = 0;
float *s;
#endif
/* Global Variables */
cudaEvent_t time_begin;
cudaEvent_t time_stop;
double avgTime_Global; double avgRate_Global;
double avgTime_Shared; double avgRate_Shared;
//--
//-- Main
//--
int main (int argc, char *argv[]) {
//--
//-- @@@ SH Note 1b:
//-- These values need to be read in from command line.
int n = -1;
//-- loop through arguments
int opt;
while ((opt = getopt(argc, argv, "hn:")) != -1) {
switch (opt) {
case 'h': help(); exit(0); break;
case 'n': n = atoi(optarg); break;
default :
printf("wrong argument\n");
exit(0); break;
}
}
//-- check to see if we missed any arguments
if (n == -1) {
printf("\n\n./MatMultCUDA: Missing required n!!\n");
help();
return 0;
}
//-- display general information
printf ( "\n" );
printf ( "Dense NxN\n" );
printf ( " CUDA version.\n" );
printf ( "\n" );
printf ( " Matrix multiplication tests.\n" );
#if debug
//--
//-- generate a validation matrix, and give debug stats
//--
printf("n is %d\n", n);
int i, j;
float* b = (float *) malloc (n*n*sizeof (float));
float* c = (float *) malloc (n*n*sizeof (float));
//--
//-- Assign randomly generated values to the input matrices B and C.
//--
int seed = 123456789;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
b[i*n + j] = randomize (&seed);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
c[i*n + j] = randomize (&seed);
}
}
//-- allocate the space for s
s = (float *) malloc (n*n*sizeof (float));
//-- Generate a "Good" Solution
optim_serial (n, s, b, c);
printf("\n\nFinished Generating Solution Mat.\n\n");
free(b); free(c);
#endif
//-- Display FOPS
unsigned long long ops;
ops = (unsigned long long)n;
ops *= (unsigned long long)n;
ops *= (unsigned long long)n;
ops *= 2;
printf(" Floating point OPS roughly = %llu\n", ops);
//--
//-- @@@ SH Note 1a:
//-- You must read in the dimension of the matrix and the number of threads
//-- from the command line.
//-- cuda initializations
cudaDeviceProp prop;
getGPUStats(prop);
printf ( "\n" );
printf ( " Thread Blocks = %d\n", (((n+BLOCK-1)/BLOCK)*((n+BLOCK-1)/BLOCK))-((n+BLOCK-1)/BLOCK));
printf ( " Threads Per Block %d\n", BLOCK*BLOCK);
avgTime_Global = 0.0; avgRate_Global = 0.0;
avgTime_Shared = 0.0; avgRate_Shared = 0.0;
for (int i = 1; i <= 10; i++) {
printf("\n\n\n\n Beginning Trial %d, of Matrix Size %d\n", i, n);
printf( "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
//-- call the matrix multiplication routines for serial cases
RunAllTests(n);
}
avgTime_Global /= 10.0; avgRate_Global /= 10.0;
avgTime_Shared /= 10.0; avgRate_Shared /= 10.0;
printf("\n\n\n Total Averages for All 10 CUDA Trials \n");
printf( "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
printf(" Global Time %f\n Global Rate %f\n\n", avgTime_Global, avgRate_Global);
printf(" Shared Time %f\n Shared Rate %f\n\n", avgTime_Shared, avgRate_Shared);
//--
//-- Terminate.
//--
printf("\n");
printf("Dense NxN:\n");
printf(" Normal end of execution.\n" );
#if debug
printf(" Execution Finished with %d Error(s) Found.\n", ErrorCount);
//-- Deallocate the used memory
free(s);
#endif
return 0;
}
//--
//-- Run a series of NxN Matrix Matrix multiplication
//-- using different stratagies
//--
void RunAllTests (int n) {
//--
//-- Variables used in this function
//--
int i; int j; int seed;
double T; double R;
//--
//-- Allocate the storage for matrices.
//--
float *a; float *b; float *c;
a = (float *) malloc (n*n*sizeof (float));
b = (float *) malloc (n*n*sizeof (float));
c = (float *) malloc (n*n*sizeof (float));
//--
//-- Assign randomly generated values to the input matrices B and C.
//--
seed = 123456789;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
b[i*n + j] = randomize (&seed);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
c[i*n + j] = randomize (&seed);
}
}
clear(n, a);
//######################################################
//--
//-- Run the Global CUDA Test
//--
//######################################################
//-- create an event
cudaEventCreate(&time_begin);
cudaEventCreate(&time_stop);
//-- run the test
global_cuda(n, a, b, c);
#if debug
//-- Optional Validation
if (validate (n, s, a)) {
printf ("\n\n\n###################################\n\n\n");
printf ("global_cuda is incorrect!!");
printf ("\n\n\n###################################\n\n\n");
ErrorCount++;
}
#endif
//-- Display Stats
char global_cuda_desc[] = "Global CUDA.";
stats(global_cuda_desc, n, &T, &R);
//-- add to averages
avgTime_Global += T;
avgRate_Global += R;
//-- destroy the cuda events
cudaEventDestroy(time_begin);
cudaEventDestroy(time_stop);
//-- Clear out Mat A
clear(n, a);
//######################################################
//--
//-- Run the Shared CUDA Test
//--
//######################################################
//-- create an event
cudaEventCreate(&time_begin);
cudaEventCreate(&time_stop);
//-- run the test
shared_cuda (n, a, b, c);
#if debug
//-- Optional Validation
if (validate (n, s, a)) {
printf ("\n\n\n###################################\n\n\n");
printf ("shared_cuda is incorrect!!");
printf ("\n\n\n###################################\n\n\n");
ErrorCount++;
}
#endif
//-- Display Stats
char shared_cuda_desc[] = "Shared CUDA.";
stats(shared_cuda_desc, n, &T, &R);
avgTime_Shared += T;
avgRate_Shared += R;
//-- destroy the cuda events
cudaEventDestroy(time_begin);
cudaEventDestroy(time_stop);
//-- Clear out Mat A
clear(n, a);
//-- Deallocate the used memory
free(a); free(b); free(c);
return;
}
//--
//-- Get a randomized value, and refresh seed.
//--
float randomize (int *seed) {
int k; float r;
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 ) { *seed = *seed + 2147483647; }
r = (float) (*seed) * 4.656612875E-10;
return r;
}
//--
//-- clear out the contents of X
//--
void clear (int n, float *X) {
int i ,j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
X[i*n + j] = 0.f;
}
}
}
//--
//-- compare the passed in matracies to see
//-- if there are any differences between them
//--
int validate (int n, float *S, float *X) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (abs(S[i*n + j] - X[i*n + j]) > 0.001) {
std::cout << "\n\n\n\n";
std::cout << "Fail at pos " << i*n << " x " << j << std::endl;
std::cout << S[i*n + j] << " != " << X[i*n + j] << std::endl;
return 1;
}
}
}
return 0;
}
//--
//-- Stats : give the user the stats of this implementation
//--
void stats (char* desc, int n, double *T, double *R) {
unsigned long long ops;
float time;
double rate;
ops = (unsigned long long)n;
ops *= (unsigned long long)n;
ops *= (unsigned long long)n;
ops *= 2;
cudaEventElapsedTime(&time, time_begin, time_stop);
time /= 1000.f;
rate = ( double ) ( ops ) / (time) / 1000000.0;
printf("\n############################################\n");
printf(" Test = %s\n", desc);
printf(" N = %d\n", n);
printf(" Floating point OPS roughly = %llu\n", ops);
printf(" Elapsed time dT = %f\n", time);
printf(" Rate = MegaOPS/dT = %f\n", rate);
(*T) = time;
(*R) = rate;
}
//--
//-- Help : simple function for how to use this program
//--
void help () {
printf("\n");
printf("Usage: ./MatMultCUDA [-h] -n <num> -t <num> \n");
printf("Options:\n");
printf(" -h\t\tPrint this help message.\n");
printf(" -n <num>\tSize of N.\n");
printf("Examples:\n");
printf("linux> ./MatMultCUDA -n 1024\n");
}
//--
//-- getGPUStats : print out general information about the GPU
//--
void getGPUStats (cudaDeviceProp &prop) {
int count;
cudaGetDeviceCount(&count);
for (int i = 0; i < count; i++) {
cudaGetDeviceProperties(&prop, i);
std::cout << "---------------------------------------------------------------" << std::endl;
std::cout << "Name " << prop.name << std::endl;
std::cout << "GPU clock rate " << (double)prop.clockRate / 1024 << " MHz" << std::endl;
std::cout << "Registers Per Block " << prop.regsPerBlock << std::endl;
std::cout << "Compute capability " << prop.major << "." << prop.minor << std::endl;
std::cout << "Total global memory " << (double)prop.totalGlobalMem / (1024*1024) << " MB" << std::endl;
std::cout << "Total constant memory " << (double)prop.totalConstMem / (1024) << " KB" << std::endl;
std::cout << "Shared memory per block " << (double)prop.sharedMemPerBlock / (1024) << " KB" << std::endl;
std::cout << "Maximum threads per block " << prop.maxThreadsPerBlock << std::endl << std::endl;
std::cout << "Maximum threads along X " << prop.maxThreadsDim[0] << std::endl;
std::cout << " Y " << prop.maxThreadsDim[1] << std::endl;
std::cout << " Z " << prop.maxThreadsDim[2] << std::endl << std::endl;
std::cout << "Maximum grid size along X " << prop.maxGridSize[0] << std::endl;
std::cout << " Y " << prop.maxGridSize[1] << std::endl;
std::cout << " Z " << prop.maxGridSize[2] << std::endl << std::endl;
std::cout << "Warp size " << prop.warpSize << std::endl;
std::cout << "Multiprocessor count " << prop.multiProcessorCount << std::endl;
std::cout << "Device overlap " << prop.deviceOverlap << std::endl << std::endl;
std::cout << "Maximum resident threads " << prop.maxThreadsPerMultiProcessor << std::endl
<< " per multi-processor \n";
std::cout << std::endl;
}
}
//--
//-- Implementation of Different NxN Matrix Multiplication
//--
//--
//-- global_cuda : use global memory on GPU to multiply two matracies
//--
void global_cuda (int n, float *A, float *B, float *C) {
//-- initialize variables
float *d_A; float *d_B; float *d_C;
//-- Allocate Memory on the GPU
cudaMalloc(&d_A, n*n*sizeof (float));
cudaMalloc(&d_B, n*n*sizeof (float));
cudaMalloc(&d_C, n*n*sizeof (float));
//-- copy data over to gpu
cudaMemcpy(d_A, A, n*n*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, B, n*n*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_C, C, n*n*sizeof(float), cudaMemcpyHostToDevice);
//-- initialize blocks and threads per blocks
dim3 DimBlock(BLOCK, BLOCK);
dim3 DimGrid((n + DimBlock.x - 1) / DimBlock.x,
(n + DimBlock.y - 1) / DimBlock.y);
size_t SharedMemBytes = 128;
//-- recored when the event begin
cudaEventRecord(time_begin);
//-- Start the Kernel
global_cuda_kernel<<<DimGrid,DimBlock,SharedMemBytes>>>(n, d_A, d_B, d_C);
//-- sync the threads
cudaThreadSynchronize();
//-- record when the event ended
cudaEventRecord(time_stop);
//-- sync the events
cudaEventSynchronize(time_stop);
//-- copy the results out of gpu
cudaMemcpy(A, d_A, n*n*sizeof(float), cudaMemcpyDeviceToHost);
//-- Deallocate device Memory
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
}
//--
//-- shared_cuda : use shared memory on GPU to multiply two matracies
//--
void shared_cuda (int n, float *A, float *B, float *C) {
//-- initialize variables
float *d_A; float *d_B; float *d_C;
//-- Allocate Memory on the GPU
cudaMalloc(&d_A, n*n*sizeof (float));
cudaMalloc(&d_B, n*n*sizeof (float));
cudaMalloc(&d_C, n*n*sizeof (float));
//-- copy data over to gpu
cudaMemcpy(d_A, A, n*n*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, B, n*n*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_C, C, n*n*sizeof(float), cudaMemcpyHostToDevice);
//-- initialize blocks and threads per blocks
dim3 DimBlock(BLOCK, BLOCK);
dim3 DimGrid((n + DimBlock.x - 1) / DimBlock.x,
(n + DimBlock.y - 1) / DimBlock.y);
size_t SharedMemBytes = 128;
//-- recored when the event begin
cudaEventRecord(time_begin);
//-- Start the kernel
shared_cuda_kernel<<<DimGrid,DimBlock,SharedMemBytes>>>(n, d_A, d_B, d_C);
//-- sync the threads
cudaThreadSynchronize();
//-- record when the event ended
cudaEventRecord(time_stop);
//-- sync the events
cudaEventSynchronize(time_stop);
//-- copy the results out of gpu
cudaMemcpy(A, d_A, n*n*sizeof(float), cudaMemcpyDeviceToHost);
//-- Deallocate device Memory
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
}
#if debug
//--
//-- optim_serial : kij row by row with fixed B.
//--
//-- notes : good cache performance, serial.
//-- used to build a validation matrix.
//--
void optim_serial (int n, float *A, float *B, float *C) {
int i, j, k;
float r;
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
r = B[i*n + k];
for (j = 0; j < n; j++) {
A[i*n + j] += r * C[k*n + j];
}
}
}
}
#endif