This repository was archived by the owner on Dec 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathBitonicSort.cpp
More file actions
655 lines (534 loc) · 17.9 KB
/
BitonicSort.cpp
File metadata and controls
655 lines (534 loc) · 17.9 KB
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
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <hip/hip_runtime.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "../include/HIPUtil.hpp"
#define SAMPLE_VERSION "HIP-Examples-Applications-v1.0"
using namespace appsdk;
using namespace std;
/**
* BitonicSort
*/
class BitonicSort
{
unsigned int seed; /**< Seed value for random number generation */
double setupTime; /**< Time for setting up HIP */
double totalKernelTime; /**< Time for kernel execution */
double totalProgramTime; /**< Time for program execution */
double referenceKernelTime; /**< Time for reference implementation */
unsigned int sortFlag; /**< Flag to indicate sorting order */
std::string sortOrder; /**< Argument to indicate sorting order */
unsigned int *input; /**< Input array */
unsigned int length; /**< length of the array */
unsigned int *verificationInput; /**< Input array for reference implementation */
unsigned int* inputBuffer; /**< memory buffer */
int iterations; /**< Number of iterations to execute kernel */
SDKTimer *sampleTimer; /**< SDKTimer object */
public:
HIPCommandArgs *sampleArgs; /**< Command argument class */
/**
* Constructor
* Initialize member variables
*/
BitonicSort()
{
seed = 123;
sortFlag = 0;
sortOrder ="desc";
input = NULL;
verificationInput = NULL;
length = 32768;
setupTime = 0;
totalKernelTime = 0;
iterations = 1;
sampleArgs = new HIPCommandArgs() ;
sampleTimer = new SDKTimer();
sampleArgs->sampleVerStr = SAMPLE_VERSION;
}
inline long long get_time()
{
struct timeval tv;
gettimeofday(&tv, 0);
return (tv.tv_sec * 1000000) + tv.tv_usec;
}
/**
* Allocate and initialize host memory array with random values
* @return SDK_SUCCESS on success and nonzero on failure
*/
int setupBitonicSort();
/**
* HIP related initialisations.
* Set up Memory buffers
* @return SDK_SUCCESS on success and nonzero on failure
*/
int setupHIP();
/**
* Set values for kernels' arguments, enqueue calls to the kernels
* on to the command queue, wait till end of kernel execution.
* Get kernel start and end time if timing is enabled
* @return SDK_SUCCESS on success and nonzero on failure
*/
int runKernels();
/**
* Helper to swap two values if first one is greater
* @param a an unsigned int value
* @param b an unsigned int value
*/
void swapIfFirstIsGreater(unsigned int *a, unsigned int *b);
/**
* Reference CPU implementation of Bitonic Sort
* for performance comparison
* @param input the input array
* @param length length of the array
* @param sortIncreasing flag to indicate sorting order
*/
void bitonicSortCPUReference(
unsigned int * input,
const unsigned int length,
const bool sortIncreasing);
/**
* Override from SDKSample. Print sample stats.
*/
void printStats();
/**
* Override from SDKSample. Initialize
* command line parser, add custom options
* @return SDK_SUCCESS on success and nonzero on failure
*/
int initialize();
/**
* Override from SDKSample, adjust width and height
* of execution domain, perform all sample setup
* @return SDK_SUCCESS on success and nonzero on failure
*/
int setup();
/**
* Override from SDKSample
* Run HIP Bitonic Sort
* @return SDK_SUCCESS on success and nonzero on failure
*/
int run();
/**
* Override from SDKSample
* Cleanup memory allocations
* @return SDK_SUCCESS on success and nonzero on failure
*/
int cleanup();
/**
* Override from SDKSample
* Verify against reference implementation
* @return SDK_SUCCESS on success and nonzero on failure
*/
int verifyResults();
};
__global__ void bitonicSort(unsigned int * theArray,
const unsigned int stage,
const unsigned int passOfStage,
const unsigned int direction)
{
unsigned int sortIncreasing = direction;
unsigned int threadId = hipBlockDim_x*hipBlockIdx_x + hipThreadIdx_x;
unsigned int pairDistance = 1 << (stage - passOfStage);
unsigned int blockWidth = 2 * pairDistance;
unsigned int leftId = (threadId % pairDistance)
+ (threadId / pairDistance) * blockWidth;
unsigned int rightId = leftId + pairDistance;
unsigned int leftElement = theArray[leftId];
unsigned int rightElement = theArray[rightId];
unsigned int sameDirectionBlockWidth = 1 << stage;
if((threadId/sameDirectionBlockWidth) % 2 == 1)
sortIncreasing = 1 - sortIncreasing;
unsigned int greater;
unsigned int lesser;
if(leftElement > rightElement)
{
greater = leftElement;
lesser = rightElement;
}
else
{
greater = rightElement;
lesser = leftElement;
}
if(sortIncreasing)
{
theArray[leftId] = lesser;
theArray[rightId] = greater;
}
else
{
theArray[leftId] = greater;
theArray[rightId] = lesser;
}
}
int BitonicSort::setupBitonicSort()
{
int inputSizeBytes = length * sizeof(unsigned int);
input = (unsigned int *) malloc(inputSizeBytes);
fillRandom<unsigned int>(input, length, 1, 0, 255);
if(sampleArgs->verify)
{
verificationInput = (unsigned int *) malloc(length * sizeof(unsigned int));
CHECK_ALLOCATION(verificationInput,
"Failed to allocate host memory. (verificationInput)");
memcpy(verificationInput, input, length * sizeof(unsigned int));
}
/*
* Unless sampleArgs->quiet mode has been enabled, print the INPUT array.
* No more than 256 values are printed because it clutters the screen
* and it is not practical to manually compare a large set of numbers
*/
if(!sampleArgs->quiet)
{
printArray<unsigned int>(
"Unsorted Input",
input,
length,
1);
}
return SDK_SUCCESS;
}
int
BitonicSort::setupHIP(void)
{
hipDeviceProp_t devProp;
hipGetDeviceProperties(&devProp, 0);
cout << " System minor " << devProp.minor << endl;
cout << " System major " << devProp.major << endl;
cout << " agent prop name " << devProp.name << endl;
return SDK_SUCCESS;
}
int
BitonicSort::runKernels(void)
{
hipEvent_t start, stop;
hipEventCreate(&start);
hipEventCreate(&stop);
float eventMs = 1.0f;
unsigned int numStages = 0;
unsigned int temp;
unsigned int stage;
unsigned int passOfStage;
unsigned int globalThreads = {length / 2};
unsigned int localThreads = 256;
// allocate and init memory used by host
hipHostMalloc((void**)&inputBuffer,length * sizeof(unsigned int), hipHostMallocDefault);
unsigned int *din;
hipHostGetDevicePointer((void**)&din, inputBuffer,0);
hipMemcpy(din, input,length * sizeof(unsigned int), hipMemcpyHostToDevice);
/*
* This algorithm is run as NS stages. Each stage has NP passes.
* so the total number of times the kernel call is enqueued is NS * NP.
*
* For every stage S, we have S + 1 passes.
* eg: For stage S = 0, we have 1 pass.
* For stage S = 1, we have 2 passes.
*
* if length is 2^N, then the number of stages (numStages) is N.
* Do keep in mind the fact that the algorithm only works for
* arrays whose size is a power of 2.
*
* here, numStages is N.
*
* For an explanation of how the algorithm works, please go through
* the documentation of this sample.
*/
/*
* 2^numStages should be equal to length.
* i.e the number of times you halve length to get 1 should be numStages
*/
for(temp = length; temp > 1; temp >>= 1)
{
++numStages;
}
// Set appropriate arguments to the kernel
// whether sort is to be in increasing order. TRUE implies increasing
if(sortOrder.compare("asc")==0)
{
sortFlag = 1;
}
else if(sortOrder.compare("desc")==0)
{
sortFlag = 0;
}
else
{
std::cout << "Please input asc or desc,the default sort order is desc!" <<
std::endl;
sortFlag = 0;
}
for(stage = 0; stage < numStages; ++stage)
{
for(passOfStage = 0; passOfStage < stage + 1; ++passOfStage)
{
hipEventRecord(start, NULL);
hipLaunchKernelGGL(bitonicSort,
dim3(globalThreads/localThreads),
dim3(localThreads),
0, 0,
inputBuffer ,stage, passOfStage ,sortFlag);
hipEventRecord(stop, NULL);
hipEventSynchronize(stop);
hipEventElapsedTime(&eventMs, start, stop);
printf ("kernel_time (hipEventElapsedTime) =%6.3fms\n", eventMs);
}
}
hipMemcpy(input, din,length * sizeof(unsigned int), hipMemcpyDeviceToHost);
return SDK_SUCCESS;
}
void
BitonicSort::swapIfFirstIsGreater(unsigned int *a, unsigned int *b)
{
if(*a > *b)
{
unsigned int temp = *a;
*a = *b;
*b = temp;
}
}
/*
* sorts the input array (in place) using the bitonic sort algorithm
* sorts in increasing order if sortIncreasing is TRUE
* else sorts in decreasing order
* length specifies the length of the array
*/
void
BitonicSort::bitonicSortCPUReference(
unsigned int * input,
const unsigned int length,
const bool sortIncreasing)
{
const unsigned int halfLength = length/2;
unsigned int i;
for(i = 2; i <= length; i *= 2)
{
unsigned int j;
for(j = i; j > 1; j /= 2)
{
bool increasing = sortIncreasing;
const unsigned int half_j = j/2;
unsigned int k;
for(k = 0; k < length; k += j)
{
const unsigned int k_plus_half_j = k + half_j;
unsigned int l;
if(i < length)
{
if((k == i) || ((k % i) == 0) && (k != halfLength))
{
increasing = !increasing;
}
}
for(l = k; l < k_plus_half_j; ++l)
{
if(increasing)
{
swapIfFirstIsGreater(&input[l], &input[l + half_j]);
}
else
{
swapIfFirstIsGreater(&input[l + half_j], &input[l]);
}
}
}
}
}
}
int BitonicSort::initialize()
{
// Call base class Initialize to get default configuration
CHECK_ERROR(sampleArgs->initialize(), SDK_SUCCESS,
"HIP resource initilization failed");
// Now add customized options
Option* array_length = new Option;
CHECK_ALLOCATION(array_length, "Memory allocation error.\n");
array_length->_sVersion = "x";
array_length->_lVersion = "length";
array_length->_description = "Length of the array to be sorted";
array_length->_type = CA_ARG_INT;
array_length->_value = &length;
sampleArgs->AddOption(array_length);
delete array_length;
Option* sort_order = new Option;
CHECK_ALLOCATION(sort_order, "Memory allocation error.\n");
sort_order->_sVersion = "s";
sort_order->_lVersion = "sort";
sort_order->_description = "Sort in descending/ascending order[desc/asc]";
sort_order->_type = CA_ARG_STRING;
sort_order->_value = &sortOrder;
sampleArgs->AddOption(sort_order);
delete sort_order;
Option* num_iterations = new Option;
CHECK_ALLOCATION(num_iterations, "Memory allocation error.\n");
num_iterations->_sVersion = "i";
num_iterations->_lVersion = "iterations";
num_iterations->_description = "Number of iterations for kernel execution";
num_iterations->_type = CA_ARG_INT;
num_iterations->_value = &iterations;
sampleArgs->AddOption(num_iterations);
delete num_iterations;
return SDK_SUCCESS;
}
int BitonicSort::setup()
{
if(iterations < 1)
{
std::cout<<"Error, iterations cannot be 0 or negative. Exiting..\n";
exit(0);
}
int i = length & (length - 1);
if(i != 0)
{
std::cout<<"\nThe input lentgh must be a power of 2\n"<<std::endl;
return SDK_FAILURE;
}
int timer = sampleTimer->createTimer();
sampleTimer->resetTimer(timer);
sampleTimer->startTimer(timer);
if(setupHIP())
{
return SDK_FAILURE;
}
if(setupBitonicSort() != SDK_SUCCESS)
{
return SDK_FAILURE;
}
sampleTimer->stopTimer(timer);
setupTime = (double)sampleTimer->readTimer(timer);
return SDK_SUCCESS;
}
int BitonicSort::run()
{
// Warm up
for(int i = 0; i < 2 && iterations != 1; i++)
{
// Arguments are set and execution call is enqueued on command buffer
if(runKernels())
{
return SDK_FAILURE;
}
}
std::cout << "Executing kernel for " << iterations
<< " iterations" << std::endl;
std::cout << "-------------------------------------------" << std::endl;
int timer = sampleTimer->createTimer();
sampleTimer->resetTimer(timer);
sampleTimer->startTimer(timer);
for(int i = 0; i < iterations; i++)
{
// Arguments are set and execution call is enqueued on command buffer
if(runKernels())
{
return SDK_FAILURE;
}
}
sampleTimer->stopTimer(timer);
totalKernelTime = (double)(sampleTimer->readTimer(timer));
if(!sampleArgs->quiet)
{
printArray<unsigned int>("Output", input, length, 1);
}
return SDK_SUCCESS;
}
int BitonicSort::verifyResults()
{
if(sampleArgs->verify)
{
/**
* reference implementation
* it overwrites the input array with the output
*/
int refTimer = sampleTimer->createTimer();
sampleTimer->resetTimer(refTimer);
sampleTimer->startTimer(refTimer);
bitonicSortCPUReference(verificationInput, length, sortFlag);
sampleTimer->stopTimer(refTimer);
referenceKernelTime = sampleTimer->readTimer(refTimer);
//hipMemcpy(input, din,inputSizeBytes, hipMemcpyDeviceToHost);
// compare the results and see if they match
if(memcmp(input, verificationInput, length*sizeof(unsigned int)) == 0)
{
std::cout<<"PASSED!\n" << std::endl;
return SDK_SUCCESS;
}
else
{
std::cout<<"FAILED\n" << std::endl;
return SDK_FAILURE;
}
}
return SDK_SUCCESS;
}
void BitonicSort::printStats()
{
if(sampleArgs->timing)
{
std::string strArray[4] = {"Elements", "Setup Time (sec)", "Avg. Kernel Time (sec)", "Elements/sec"};
std::string stats[4];
sampleTimer->totalTime = ( totalKernelTime/ iterations );
stats[0] = toString(length, std::dec);
stats[1] = toString(setupTime, std::dec);
stats[2] = toString(sampleTimer->totalTime, std::dec);
stats[3] = toString(( length/sampleTimer->totalTime ), std::dec);
printStatistics(strArray, stats, 4);
}
}
int BitonicSort::cleanup()
{
// Releases HIP resources (Context, Memory etc.)
hipFree(inputBuffer);
FREE(verificationInput);
return SDK_SUCCESS;
}
int
main(int argc, char * argv[])
{
BitonicSort hipBitonicSort;
if(hipBitonicSort.initialize() != SDK_SUCCESS)
{
return SDK_FAILURE;
}
if(hipBitonicSort.sampleArgs->parseCommandLine(argc, argv) != SDK_SUCCESS)
{
return SDK_FAILURE;
}
{
if(hipBitonicSort.setup() != SDK_SUCCESS)
{
return SDK_FAILURE;
}
if(hipBitonicSort.run() != SDK_SUCCESS)
{
return SDK_FAILURE;
}
if(hipBitonicSort.verifyResults() != SDK_SUCCESS)
{
return SDK_FAILURE;
}
if(hipBitonicSort.cleanup() != SDK_SUCCESS)
{
return SDK_FAILURE;
}
hipBitonicSort.printStats();
}
return SDK_SUCCESS;
}