-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathheapsort.cu
944 lines (817 loc) · 32.9 KB
/
heapsort.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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
#include <math.h>
#include <stdio.h>
#include "common/cuPrintf.cu"
/* Heapsort.cu: Individual block sorting works at this point, and is stored
* in the "midlist" structure passed to the GPUheapsort function. Block
* combinations via metaheaps do not work.
*/
#define BLOCKSIZE 1023 //Size of blocks at the bottom heap
#define METASIZE 511 //Size of metaheap
#define METACACHE 4 //Size of metacache
#define METADEPTH 9 //Max depth of metaheap (ceil of log of metaSize)
#define OUTSIZE 512 //Size of output shared memory
#define BLOCKDEPTH 10 //Max Depth of bottom heap, and ceil of log of blocksize
#define MINWARPS 1 //Minimum warp count to run code.
#define INVALID -1 //special value signifying invalid Buffer/heap entry.
typedef struct metaEntry {
float value;
short key;
} metaEntry_t;
//Tells us our current progress on building a given block.
typedef struct blockInfo{
int bufSize; //How many popped elements are buffered right now?
int writeLoc; //Index into blockwrite array for next write
int readLoc; //Index into blockwrite array for next read
short remaining; //How many elements are left to pop?
short size; //Total number of elements in the block. 0 iff uninit.
short index; //Which block are we?
short heapified; //Only a bool is needed, but short maintains alignment.
} blockInfo_t;
//Forward declarations
__global__ void GPUHeapSort(float *d_list, float *midList, float *sortedList,
blockInfo_t *blockInfo,
int numBlocks, int len, int topHeapSize,
int botHeapSize,
int warpSize, int metaDepth);
__device__ void bottomLevel(float *d_list, int len); //NYI
__device__ void topLevel(float *d_list, int len); //NYI
__device__ void heapify(__volatile__ float *in_list, int len);
__device__ void metaHeapify(__volatile__ metaEntry_t *in_list,
__volatile__ float buf[METASIZE][METACACHE], int len);
__device__ void pipelinedPop(__volatile__ float *heap, float *out_list,
int d, int popCount);
__device__ void fillBuffer(float *g_block, blockInfo_t *blockInfo,
float *buffer, int firstThread, int *isDone,
int nextBlock_temp);
__device__ void loadBlock(float *g_block, float *s_block,
blockInfo_t *g_info, blockInfo_t *s_info);
__device__ void writeBlock(float *g_block, float *s_block,
int writeLen,
blockInfo_t *g_info, blockInfo_t *s_info);
__device__ void printBlock(float *s_block, int blockLen);
__device__ void initBlocks(blockInfo_t *blockInfo, int numBlocks, int len);
__device__ void initMetaHeap(metaEntry *heap, float buf[METASIZE][METACACHE]);
__host__ int heapSort(float *h_list, metaEntry_t *superTemp,
int len, int threadsPerBlock,
int blocks, cudaDeviceProp devProp);
__host__ int floorlog2(int x);
//Ceiling of log2 of x. Could be made faster, but effect would be negligible.
int ceilLog2(int x){
if (x < 1){
return -1;
}
x--;
int output = 0;
while (x > 0) {
x >>= 1;
output++;
}
return output;
}
/* Heapsort definition. Takes a pointer to a list of floats.
* the length of the list, the number of threads per block, and
* the number of blocks on which to execute.
* Puts the list into sorted order in-place.*/
int heapSort(float *h_list, metaEntry_t *superTemp,
int len, int threadsPerBlock, int blocks,
cudaDeviceProp devProp) {
float *d_list, *midList, *sortedList; //various lists that will live on GPU
blockInfo_t *blockInfo;
blockInfo_t *dummyBlocks; //A bunch of zeroed blockinfos to zero GPU mem.
int logLen; //log of length of list
int metaDepth; //layers of metaheaps
int topHeapSize; //Size of the top heap
int logBotHeapSize; //log_2 of max size of the bottom heaps
int logMidHeapSize; //log_2 of max size of intermediate heaps
int numBlocks; //Number of bottom heaps. Poor choice of name =p.
int temp;
//Trivial list? Just return.
if (len < 2){
return 0;
}
//Ensure that we have a valid number of threads per block.
if (threadsPerBlock == 0){
threadsPerBlock = devProp.maxThreadsPerBlock;
}
//We require a minimum of 2 warps per block to run our code
else if (threadsPerBlock < 2*devProp.warpSize){
printf("At least 2 warps are required to run heapsort. ");
printf("Increasing thread count to 64.\n");
threadsPerBlock = MINWARPS*devProp.warpSize;
}
if (threadsPerBlock > devProp.maxThreadsPerBlock) {
printf("Device cannot handle %d threads per block. Max is %d\n",
threadsPerBlock, devProp.maxThreadsPerBlock);
return -1;
}
//We require a minimum of 2 blocks to run our code.
if (blocks < 2){
printf("At least 2 blocks are required to run heapsort.\n");
return -1;
}
//Calculate size of heaps. BotHeapSize is 1/8 shared mem size.
//logBotHeapSize = ceilLog2(devProp.sharedMemPerBlock>>3);
logBotHeapSize = BLOCKDEPTH;
logMidHeapSize = logBotHeapSize - 2;
printf("logBotHeap: %d, logMidHeap: %d\n", logBotHeapSize, logMidHeapSize);
//Calculate metaDepth and topHeapSize.
metaDepth = 0; //Will increment this if necessary.
logLen = ceilLog2(len);
temp = logBotHeapSize; //temp is a counter tracking total subheap depth.
//Do we only need one heap?
if (temp >= logLen){
topHeapSize = len;
}
//Otherwise, how many metaheaps do we need?
else {
while (temp < logLen){
metaDepth++;
temp += logMidHeapSize;
}
topHeapSize = len>>temp;
}
//Nevermind the fancy calculations above... let's just do this.
topHeapSize = ceil((float)len/BLOCKSIZE);
printf("metaDepth is %d\n", metaDepth);
printf("len is %d, blocksize is %d\n", len, BLOCKSIZE);
printf("topHeapSize is %d\n", topHeapSize);
if (metaDepth > blocks){
printf("Must have at least metaDepth blocks available.");
printf("metaDepth is %d, but only %d blocks were given.\n",
metaDepth, blocks);
return -1;
}
if (metaDepth > 2){
printf("Current implementation only supports metaDepth of 2. ");
printf("Given metadepth was %d. In practice, ", metaDepth);
printf("this means that list lengths cannot equal or exceed 2^20.");
}
if ( (cudaMalloc((void **) &d_list, len*sizeof(float))) ==
cudaErrorMemoryAllocation) {
printf("Error: Insufficient device memory at line %d\n", __LINE__);
return -1;
}
if ( (cudaMalloc((void **) &midList, len*sizeof(float))) ==
cudaErrorMemoryAllocation) {
printf("Error: Insufficient device memory at line %d\n", __LINE__);
return -1;
}
if ( (cudaMalloc((void **) &sortedList, len*sizeof(float))) ==
cudaErrorMemoryAllocation) {
printf("Error: Insufficient device memory at line %d\n", __LINE__);
return -1;
}
cudaMemcpy(d_list, h_list, len*sizeof(float), cudaMemcpyHostToDevice);
numBlocks = ceil((float)len/BLOCKSIZE); //number of bottom heaps
printf("numHBlocks: %d\n", numBlocks);
dummyBlocks = (blockInfo_t *)calloc(numBlocks, sizeof(blockInfo_t));
if ( (cudaMalloc((void **) &blockInfo, len*sizeof(blockInfo_t))) ==
cudaErrorMemoryAllocation) {
printf("Error: Insufficient device memory at line %d\n", __LINE__);
return -1;
}
cudaMemcpy(blockInfo, dummyBlocks, len*sizeof(float),
cudaMemcpyHostToDevice);
printf("Attempting to call GPUHeapSort\n\n");
GPUHeapSort<<<blocks, threadsPerBlock>>>
(d_list, midList, sortedList, blockInfo, numBlocks,
len, topHeapSize, BLOCKSIZE, devProp.warpSize, metaDepth);
cudaThreadSynchronize();
cudaMemcpy(h_list, midList, len*sizeof(float), cudaMemcpyDeviceToHost);
return 0;
}
/* GPUHeapSort definition. Takes a pointer to a list of floats, the length
* of the list, and the number of list elements given to each thread.
* Puts the list into sorted order in-place.*/
__global__ void GPUHeapSort(float *d_list, float *midList, float *sortedList,
blockInfo_t *blockInfo,
int numBlocks, int len, int topHeapSize,
int botHeapSize,
int warpSize, int metaDepth){
__shared__ float heap[BLOCKSIZE];
__shared__ float buffer[METASIZE][METACACHE];
__shared__ float output[OUTSIZE];
if (blockIdx.x == 0) {
__shared__ int isDone; //Tracks how many blocks we have loaded.
__shared__ metaEntry_t *metaHeap;
int nextBlock;
if (threadIdx.x == 32){
metaHeap = (metaEntry_t *)heap; //reuse the "heap" declaration.
isDone = 0;
}
__syncthreads();
//cuPrintf("numBlocks reaches %d just before initing\n", numBlocks);
//Initialize datastructures
initMetaHeap(metaHeap, buffer);
//cuPrintf("numBlocks eez %d\n", numBlocks);
__syncthreads();
//First warp maintains metaheap.
if (threadIdx.x < 31){
//cuPrintf("topHeapSize is %d\n", topHeapSize);
metaHeapify(metaHeap, buffer, topHeapSize);
//cuPrintf("warp 0 says that isDone is now %d\n", isDone);
}
//Laters warps maintain buffers.
else {
nextBlock = (threadIdx.x>>5) -1;
while (isDone < numBlocks) {
//cuPrintf("isDone is %d\n", isDone);
fillBuffer(&midList[nextBlock*BLOCKSIZE],
&blockInfo[nextBlock], buffer[nextBlock],
threadIdx.x & ~31, &isDone, nextBlock);
nextBlock += (blockDim.x>>5)-1;
if (nextBlock > numBlocks){
nextBlock = (threadIdx.x>>5)-1;
}
}
}
__syncthreads();
//Temporary -- write the metaheap to memory.
for (int i = threadIdx.x; i < topHeapSize; i+= blockDim.x){
sortedList[i] = metaHeap[i].value;
}
__syncthreads();
}
else {
__shared__ blockInfo_t curBlockInfo;
__shared__ int popCount; //How many heap elements are we popping?
int curIdx; //The index of the current block
//cuPrintf("About to call init\n");
//Initialize datastructures
initBlocks(blockInfo, numBlocks, len);
//cuPrintf("Init finished.\n");
__syncthreads();
curIdx = blockIdx.x-1;
while (curIdx < numBlocks){
//Load memory
loadBlock(&d_list[curIdx*BLOCKSIZE], (float *)heap,
&blockInfo[curIdx], &curBlockInfo);
/*cuPrintf("curBlockInfo: (bufsize: %d, writeloc: %d, heapified: %d \
remaining: %d, size: %d\n",
curBlockInfo.bufSize, curBlockInfo.writeLoc,
curBlockInfo.heapified, curBlockInfo.remaining,
curBlockInfo.size);
*/
if (curBlockInfo.heapified == 0){
//First warp heapifies
if (threadIdx.x < 8){
heapify(heap, curBlockInfo.size);
}
curBlockInfo.heapified = 1;
__syncthreads();
}
//cuPrintf("Entering while Loop\n");
while (curBlockInfo.remaining > 0){
//First warp pops
/*cuPrintf("curBlockInfo: (bufsize: %d, writeloc: %d, heapified: %d \
remaining: %d, size: %d\n",
curBlockInfo.bufSize, curBlockInfo.writeLoc,
curBlockInfo.heapified, curBlockInfo.remaining,
curBlockInfo.size);
*/
if (threadIdx.x == 0){
popCount = curBlockInfo.remaining;
if (popCount > OUTSIZE) {
popCount = OUTSIZE;
}
curBlockInfo.remaining -= popCount;
}
if (threadIdx.x < 8){
pipelinedPop(heap, (float *)output, BLOCKDEPTH, popCount);
}
__syncthreads();
//cuPrintf("Calling writeBlock with popcount %d\n", popCount);
writeBlock(midList, output, popCount,
&blockInfo[curBlockInfo.index], &curBlockInfo);
__syncthreads();
//cuPrintf("At end, remaining: %d\n", curBlockInfo.remaining);
}
//cuPrintf("After the while loop...\n");
curIdx += (gridDim.x - 1);
}
}
return;
}
/* Loads a block of data from global memory into shared memory. Must be
* called by all threads of a thread block to ensure proper operation.
* g_info: A pointer to the specific (global) blockinfo to be read.
*/
__device__ void loadBlock(float *g_block, float *s_block,
blockInfo_t *g_info, blockInfo_t *s_info){
if (threadIdx.x == 0){
*s_info = *g_info;
__threadfence_block();
}
//cuPrintf("Entering loadBlock\n");
for(int i = threadIdx.x; i < BLOCKSIZE; i += gridDim.x){
if(i < s_info->size){
s_block[i] = g_block[i];
}
else {
s_block[i] = 0;
}
}
__syncthreads();
return;
}
/*
* fillBuffer: Fills empty slots in buffer with data from g_block.
* Expects to be called by METACACHE blocks.
* g_block: Pointer to the location we should start reading from.
* blockInfo: Pointer to the blockInfo struct for the g_block.
* buffer: pointer to the location of a float[4] buffer for the metaheap.
* firstThread: The first of METACACHE contiguous threads running this func.
*/
__device__ void fillBuffer(float *g_block, blockInfo_t *blockInfo,
float *buffer,
int firstThread, int *isDone,
int nextBlock_temp){
__shared__ int readLoc;
__shared__ int isReady;
__shared__ int writeLoc;
__shared__ int toCacheCount; //How many new elements do we need to cache?
int index;
//The first three threads perform slow memory operations. The fourth
//does some processing while the others are waiting for memory.
if(threadIdx.x == firstThread) {
isReady = blockInfo->writeLoc;
cuPrintf("Blocksize begins as %d\n", blockInfo->size);
}
if (threadIdx.x == firstThread+1){
readLoc = blockInfo->readLoc;
}
if (threadIdx.x == firstThread+2){
writeLoc = blockInfo->writeLoc;
}
if (threadIdx.x == firstThread+3){
toCacheCount = 0;
for (int i = 0; i < METACACHE; i++){
if (buffer[i] == INVALID) {
toCacheCount++;
}
}
}
__threadfence_block();
//Block isn't ready. Do nothing.
if (isReady == 0){
//cuPrintf("Not ready yet!\n");
return;
}
else {
//cuPrintf("Totally ready!\n");
//For threads firstThread through METACACHE...
index = threadIdx.x - firstThread;
if (index < METACACHE){
//cuPrintf("index < METACACHE! ! !\n");
//Note that the following three lines risk a race w/warp 0. Alas,
//atomic TAS on shared is not implemented in compute capacity 1.1, so this is
//more-or-less unavoidable. We need to atomically test the buffer for
//INVALID state and then write to it to avoid the race condition. If this
//were going to be run on something of compute capacity 1.2 or greater,
//an atomic TAS would be used and all would be well.
//Do we have an invalid cache entry?
if (buffer[index] == INVALID) {
//cuPrintf("INVALID index! ! !\n");
//Does g_block have an element that can fill our invalid entry?
if (readLoc + index < writeLoc){
buffer[index] = g_block[readLoc+index];
/*cuPrintf("filled %d th buffer %d with %f\n",
nextBlock_temp, index, buffer[index]);
cuPrintf("buffer addr is %d\n", (long)&buffer[index]);
cuPrintf("read addr is %d\n",
(long)&g_block[readLoc+index]);*/
}
}
}
}
if (threadIdx.x == firstThread){
if (readLoc + toCacheCount > writeLoc){
toCacheCount = writeLoc - readLoc;
__threadfence_block();
}
}
//update the blockData structure in global memory
if (threadIdx.x == firstThread){
atomicSub(&blockInfo->bufSize, toCacheCount);
}
if (threadIdx.x == firstThread + 1){
//cuPrintf("ended up caching %d elements\n", toCacheCount);
blockInfo->readLoc = readLoc + toCacheCount;
}
if (threadIdx.x == firstThread + 2){
if (toCacheCount > 0){
*isDone = *isDone + 1;
}
}
return;
}
/* Writes a block of data from shared memory into global memory. Must be
* called by all threads of a thread block to ensure proper operation.
* g_info: A pointer to the specific (global) g_info to be written.
*/
__device__ void writeBlock(float *g_block, float *s_block, int writeLen,
blockInfo_t *g_info, blockInfo_t *s_info){
//cuPrintf("beginning writeBlock\n");
for(int i = threadIdx.x; i < writeLen; i += blockDim.x){
g_block[s_info->writeLoc+i] = s_block[i];
//cuPrintf("writing block %d to %d with value %f\n",
// i, s_info->writeLoc + i, g_block[s_info->writeLoc + i]);
}
__syncthreads();
//Update the blockInfo struct in global memory
if (threadIdx.x == 0){
//s_info->writeLoc += writeLen;
//*g_info = *s_info;
//cuPrintf("setting writeLoc to %d\n", s_info->writeLoc + writeLen);
s_info->writeLoc += writeLen;
g_info->writeLoc = s_info->writeLoc;
g_info->remaining = s_info->remaining;
atomicAdd(&g_info->bufSize, writeLen);
}
__syncthreads();
return;
}
/* Writes a chunk of raw floats from shared memory into global memory. Must be
* called by all threads of a thread block to ensure proper operation.
* g_info: A pointer to the specific (global) g_info to be written.
*/
__device__ void writeRawFloats(float *g_block, float *s_block, int writeLen){
//cuPrintf("beginning writeBlock\n");
for(int i = threadIdx.x; i < writeLen; i += blockDim.x){
g_block[i] = s_block[i];
//cuPrintf("writing block %d to %d with value %f\n",
// i, s_info->writeLoc + i, g_block[s_info->writeLoc + i]);
}
__syncthreads();
return;
}
/* Prints a block of data in shared memory */
__device__ void printBlock(float *s_block, int blockLen){
for (int i = threadIdx.x; i < blockLen; i += blockDim.x){
cuPrintf("s_block[%d] = %f\n", i, s_block[i]);
}
}
/* Initializes data structures for heapsort. Must be run by all threads
* of all nonzero blocks.
* blockInfo: A pointer to the entire array of blockInfos.
*/
__device__ void initBlocks(blockInfo_t *blockInfo, int numBlocks, int len){
if ((threadIdx.x == 0) && (blockIdx.x != 0) ){
cuPrintf("attempting to init\n");
//Initialize blockinfo structs. Initialization is done by the blocks
//that own each blockinfo struct.
blockInfo_t BI;
BI.bufSize = 0;
BI.heapified = 0;
BI.readLoc = 0;
BI.remaining = BLOCKSIZE;
BI.size = BLOCKSIZE;
for (int idx = (blockIdx.x-1); idx < numBlocks; idx += (gridDim.x-1)){
BI.writeLoc = idx*BLOCKSIZE;
BI.index = idx;
cuPrintf("writeloc is %d\n", BI.writeLoc);
//Did we overrun our bounds when setting size?
if ((idx+1)*BLOCKSIZE > len){
BI.size = len - idx*BLOCKSIZE;
BI.remaining = BI.size;
}
blockInfo[idx] = BI;
}
}
__syncthreads();
}
__device__ void initMetaHeap(metaEntry *heap, float buf[METASIZE][METACACHE]){
for (int i = threadIdx.x; i < METASIZE; i += blockDim.x){
heap[i].value = INVALID;
heap[i].key = i;
for (int j = 0; j < METACACHE; j++){
buf[i][j] = INVALID;
//cuPrintf("Invalidating buf[%d][%d]\n", i, j);
}
}
return;
}
/* Heapifies a list using a single warp. Must be run on the bottom warp of a
* thread. If this function is not executed by all of threads 0-7, the GPU
* will stall.
*/
__device__ void heapify(__volatile__ float *inList, int len){
int focusIdx = 0; //Index of element currently being heapified
float focus=0, parent=0; //current element being heapified and its parent
__volatile__ __shared__ int temp;
/*int localTemp=0; Temp doesn't need to be re-read _every_ time.
* Temp will be used to track the next element to percolate.
*/
if (threadIdx.x == 0){
temp = 0; //Index of next element to heapify
}
//localTemp = 0;
//We maintain the invariant that no two threads are processing on
//adjacent layers of the heap in order to avoid memory conflicts and
//race conditions.
while (temp < len){
if (threadIdx.x == (temp & 7)){
focusIdx = temp;
focus = inList[focusIdx];
temp = temp + 1;
//cuPrintf("Focusing on element %d with value %f\n",
// focusIdx, focus);
}
//Unrolled loop once to avoid race conditions and get a small speed
//boost over using a for loop on 2 iterations.
if (focusIdx != 0){
parent = inList[(focusIdx-1)>>1];
//Swap focus and parent if focus is bigger than parent
if (focus > parent){
//cuPrintf("Focus %f > parent %f\n", focus, parent);
inList[focusIdx] = parent;
inList[(focusIdx-1)>>1] = focus;
focusIdx = (focusIdx - 1)>>1;
}
else {
//cuPrintf("Parent %f > focus %f\n", parent, focus);
focusIdx = 0;
}
}
if (focusIdx != 0){
parent = inList[(focusIdx-1)>>1];
//Swap focus and parent if focus is bigger than parent
if (focus > parent){
//cuPrintf("Focus %f > parent %f\n", focus, parent);
inList[focusIdx] = parent;
inList[(focusIdx-1)>>1] = focus;
focusIdx = (focusIdx-1)>>1;
}
else {
//cuPrintf("Parent %f > focus %f\n", parent, focus);
focusIdx = 0;
}
}
//localTemp = *temp;
}
//Empty the pipeline before returning
while (focusIdx !=0){
parent = inList[(focusIdx-1)>>1];
//Swap focus and parent if focus is bigger than parent
if (focus > parent){
cuPrintf("Focus %f > parent %f\n", focus, parent);
inList[focusIdx] = parent;
inList[(focusIdx-1)>>1] = focus;
focusIdx = (focusIdx-1)>>1;
}
else {
//cuPrintf("Parent %f > focus %f\n", parent, focus);
focusIdx = 0;
}
}
return;
}
/* Heapifies a list using a single warp. Must be run on the bottom warp of a
* thread. If this function is not executed by all of threads 0-7, the GPU
* will stall.
*/
__device__ void metaHeapify(__volatile__ metaEntry_t *inList,
__volatile__ float buf[METASIZE][METACACHE],
int len){
int focusIdx = 0; //Index of element currently being heapified
__volatile__ metaEntry_t focus, parent; //current element being heapified and its parent
__volatile__ __shared__ int temp;
/*int localTemp=0; Temp doesn't need to be re-read _every_ time.
* Temp will be used to track the next element to percolate.
*/
if (threadIdx.x == 0){
temp = 0; //Index of next element to heapify
}
//localTemp = 0;
//We maintain the invariant that no two threads are processing on
//adjacent layers of the heap in order to avoid memory conflicts and
//race conditions.
while (temp < len){
if (threadIdx.x == (temp & 7)){
focusIdx = temp;
focus.key = inList[focusIdx].key;
focus.value = inList[focusIdx].value;
//Initialize the inList entry
do {
inList[focusIdx].value = buf[focus.key][0];
focus.value = inList[focusIdx].value;
/*
if ((i % 1000) == 0) {
cuPrintf("(key, value) is (%d, %f)\n",
focus.key, focus.value);
}
i++;
*/
//} while (i < 10000);
} while (focus.value == INVALID);
temp = temp + 1;
/*cuPrintf("Focusing on element %d with value %f\n",
focusIdx, focus.value);*/
}
//Unrolled loop once to avoid race conditions and get a small speed
//boost over using a for loop on 2 iterations.
if (focusIdx != 0){
parent.key = inList[(focusIdx-1)>>1].key;
parent.value = inList[(focusIdx-1)>>1].value;
//Swap focus and parent if focus is bigger than parent
if (focus.value > parent.value){
cuPrintf("Focus %f > parent %f. Setting index %d to focus\n",
focus.value, parent.value, (focusIdx-1)>>1);
inList[focusIdx].key = parent.key;
inList[focusIdx].value = parent.value;
inList[(focusIdx-1)>>1].key = focus.key;
inList[(focusIdx-1)>>1].value = focus.value;
focusIdx = (focusIdx - 1)>>1;
}
else {
//cuPrintf("Parent %f > focus %f\n", parent, focus);
focusIdx = 0;
}
}
if (focusIdx != 0){
parent.key = inList[(focusIdx-1)>>1].key;
parent.value = inList[(focusIdx-1)>>1].value;
//Swap focus and parent if focus is bigger than parent
if (focus.value > parent.value){
cuPrintf("Focus %f > parent %f. Setting index %d to focus\n",
focus.value, parent.value, (focusIdx-1)>>1);
inList[focusIdx].key = parent.key;
inList[focusIdx].value = parent.value;
inList[(focusIdx-1)>>1].key = focus.key;
inList[(focusIdx-1)>>1].value = focus.value;
focusIdx = (focusIdx-1)>>1;
}
else {
//cuPrintf("Parent %f > focus %f\n", parent, focus);
focusIdx = 0;
}
}
//localTemp = *temp;
}
//Empty the pipeline before returning
while (focusIdx !=0){
parent.key = inList[(focusIdx-1)>>1].key;
parent.value = inList[(focusIdx-1)>>1].value;
//Swap focus and parent if focus is bigger than parent
if (focus.value > parent.value){
cuPrintf("Focus %f > parent %f\n", focus.value, parent.value);
inList[focusIdx].key = parent.key;
inList[focusIdx].value = parent.value;
inList[(focusIdx-1)>>1].key = focus.key;
inList[(focusIdx-1)>>1].value = focus.value;
focusIdx = (focusIdx-1)>>1;
}
else {
//cuPrintf("Parent %f > focus %f\n", parent, focus);
focusIdx = 0;
}
}
return;
}
/* Pops a heap using a single warp. Must be run on the bottom warp of a
* thread. If this function is not executed by all of threads 0-7, the GPU
* will stall.
* heap: a pointer to a heap structure w/ space for a complete heap of depth d
* d: The depth of the heap
* count: The number of elements to pop
*/
__device__ void pipelinedPop(__volatile__ float *heap, float *out_list,
int d, int popCount){
int focusIdx = 0; //Index of element currently percolating down
int maxChildIdx=0; //Index of largest child of element percolating down
int curDepth=d+1; //Depth of element currently percolating down
__volatile__ __shared__ int temp;
/*int localTemp=0; Temp doesn't need to be re-read _every_ time.
* Temp will be used to track the next element to percolate.
*/
if (threadIdx.x == 0){
temp = 0; //We have thus far popped 0 elements
}
//localTemp = 0;
//We maintain the invariant that no two threads are processing on
//adjacent layers of the heap in order to avoid memory conflicts and
//race conditions.
while (temp < popCount){
if (threadIdx.x == (temp & 7)){
focusIdx = 0;
curDepth = 0;
out_list[temp] = heap[0];
temp = temp + 1;
//cuPrintf("temp is: %d\n", *temp);
//cuPrintf("top of heap is: %f\n", heap[0]);
}
//Unrolled loop once to avoid race conditions and get a small speed
//boost over using a for loop on 2 iterations.
if (curDepth < d-1){
maxChildIdx = 2*focusIdx+1;
//cuPrintf("Children are %f, %f\n", heap[2*focusIdx+2],
// heap[maxChildIdx]);
//cuPrintf("Depth is %d, Focusing on element %d\n", curDepth,
// focusIdx);
if (heap[2*focusIdx+2] > heap[maxChildIdx]){
maxChildIdx = 2*focusIdx+2;
}
heap[focusIdx] = heap[maxChildIdx];
focusIdx = maxChildIdx;
curDepth++;
}
if (curDepth < d-1){
maxChildIdx = 2*focusIdx+1;
//cuPrintf("Depth is %d, Focusing on element %d\n", curDepth,
// focusIdx);
if (heap[2*focusIdx+2] > heap[maxChildIdx]){
maxChildIdx = 2*focusIdx+2;
}
heap[focusIdx] = heap[maxChildIdx];
focusIdx = maxChildIdx;
curDepth++;
}
if (curDepth == d-1){
//cuPrintf("curDepth is %d\n", curDepth);
//cuPrintf("focusIdx is %d\n", focusIdx);
//cuPrintf("Depth is %d (max). Focusing on element %d\n", curDepth,
//focusIdx);
heap[focusIdx] = 0;
curDepth++;
//continue;
}
}
//empty the pipeline before returning
while (curDepth < d-1){
//cuPrintf("Emptying Pipeline. Focusing on element %d\n", focusIdx);
maxChildIdx = 2*focusIdx+1;
if (heap[2*focusIdx+2] > heap[maxChildIdx]){
maxChildIdx = 2*focusIdx+2;
}
heap[focusIdx] = heap[maxChildIdx];
focusIdx = maxChildIdx;
curDepth++;
}
if (curDepth == d-1){
//cuPrintf("curDepth is %d\n", curDepth);
//cuPrintf("focusIdx is %d\n", focusIdx);
//cuPrintf("Depth is %d (max). Focusing on element %d\n", curDepth,
//focusIdx);
heap[focusIdx] = 0;
curDepth++;
//continue;
}
return;
}
void usage(){
printf("Usage: in_list [thread_count] [kernel_count]\n");
}
int main(int argc, char *argv[]){
int len;
float *h_list;
cudaPrintfInit();
if ((argc > 4) || argc < 2) {
printf("Invalid argument count. %s accepts 1-4 arguments, %d given\n",
argv[0], argc);
usage();
return -1;
}
cudaDeviceProp devProp;
cudaGetDeviceProperties(&devProp, 0);
int thread_count = 64;
//int block_count = devProp.maxGridSize[0];
int block_count = 2;
if (argc > 2){
thread_count = atoi(argv[2]);
}
if (argc > 3){
block_count = atoi(argv[3]);
}
FILE *fin = fopen(argv[1], "r");
if (fin == NULL){
printf("Could not open file: %s", argv[1]);
return -2;
}
fscanf(fin, "#%d#", &len);
h_list = (float *)malloc(len*sizeof(float));
if (h_list == NULL){
printf("Insufficient host memory to allocate at %d", __LINE__);
return -3;
}
for (int i = 0; i < len; i++){
if (EOF == fscanf(fin, "%f ", &h_list[i])){
break;
}
}
/*
printf("\nInitial list is:\n");
for (int i = 0; i < len; i++){
printf("%f\n", h_list[i]);
}
*/
metaEntry_t temp[BLOCKSIZE];
heapSort(h_list, temp, len, thread_count, block_count, devProp);
cudaThreadSynchronize();
cudaPrintfDisplay(stdout, true);
cudaPrintfEnd();
printf("\nFinal list is:\n");
for (int i = 0; i < len; i++){
printf("%f\n", h_list[i]);
}
return 0;
}