forked from trantalaiho/Cuda-Histogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcuda_histogram.h
3882 lines (3533 loc) · 140 KB
/
cuda_histogram.h
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* cuda_histogram.h
*
* Created on: 3.5.2011
* Author: Teemu Rantalaiho (teemu.rantalaiho@helsinki.fi)
*
*
* Copyright 2011-2012 Teemu Rantalaiho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*/
#ifndef CUDA_HISTOGRAM_H_
#define CUDA_HISTOGRAM_H_
#include <cuda_runtime_api.h>
// Public API:
/*------------------------------------------------------------------------*//*!
* \brief Enumeration to define the type of histogram we are interested in
*//**************************************************************************/
enum histogram_type {
histogram_generic, /*!< \brief Generic histogram, for any types */
histogram_atomic_inc, /*!< \brief Each output-value is constant 1 */
histogram_atomic_add, /*!< \brief Output-type is such that atomicAdd()
function can be used */
};
/*------------------------------------------------------------------------*//*!
* \brief Check the size of the temporary buffer needed for histogram
*
* This function can be used to check the size of the temporary buffer7
* needed in \ref callHistogramKernel() so that a buffer of correct
* size can be passed in to the histogram call -- this way one can
* avoid the latency involved in GPU-memory allocations when running
* multiple histograms
*
* \tparam histotype Type of histogram: generic, atomic-inc or atomic-add
* \tparam OUTPUTTYPE The type for the outputs of the histogram
* (type of each bin)
* \param zero Invariant element of the sum-function
* (TODO: remove this?)
* \param nOut Number of bins in the histogram
*//**************************************************************************/
template <histogram_type histotype, typename OUTPUTTYPE>
static
int
getHistogramBufSize(OUTPUTTYPE zero, int nOut);
/*------------------------------------------------------------------------*//*!
* \brief Implements generic histogram on the device
*
* \tparam histotype Type of histogram: generic, atomic-inc or atomic-add
* \tparam nMultires Number of results each input produces. Typically 1
* \tparam INDEXT Integer type to be used for indexing (int, size_t, ...)
* \tparam INPUTTYPE Arbitrary type passed in as input
* \tparam TRANSFORMFUNTYPE Function object that takes in the input, index
* and produces 'nMultires' results and indices.
* The signature therefore is as follows:
* struct xform
* {
* __device__
* void operator() (
* INPUTTYPE* input, int index, int* result_index,
* OUTPUTTYPE* results, int nresults) const
* {
* *result_index[0] = <Some bin-number - from 0 to nOut - 1>;
* *results = input[i];
* }
* };
* \note Passing out indices out of range (of [0, nOut-1]) will result
* in unspecified behavior
* \tparam SUMFUNTYPE Function object type that implements the binary
* reduction of two input variables
* \tparam OUTPUTTYPE The type for the outputs of the histogram
*
* \param input Arbitrary input that will be passed as context
* for the transform-operator
* \param xformObj The transform-function object for this operation
* \param sumfunObj The binary-operator that combines OUTPUTTYPE-values
* inside each bin.
* \param start Starting index for the operation - first index
* to be passed into the transform-functor
* \param end Ending index for the operation - first index
* _NOT_ to be passed into the transform-functor
* \param zero Invariant object of the sumfunObj-functor (0 + x = x)
* \param out Output-bins - this operations adds on top of the values
* already contained on bins
* \param nOut Number of arrays in output and therefore number of bins
* \param outInDev The output-bins \ref out reside in device (ie GPU) memory
* Default value: false
* \param stream Cudastream to be used for this operation - all GPU
* operations will be run on this stream. \note in case the
* output-bins reside in HOST memory the last memory copy
* from device to host will be synchronized, so that when
* this API-call returns, the results will be available on
* host memory (ie. no cudaStreamSynchronize() is necessary)
* Default value: 0 - the default stream
* \param tmpBuffer A temporary buffer of device (GPU) memory to be used.
* Has to be large enough - check size with
* \ref getHistogramBufSize().
*//**************************************************************************/
template <histogram_type histotype, int nMultires,
typename INPUTTYPE, typename TRANSFORMFUNTYPE, typename SUMFUNTYPE,
typename OUTPUTTYPE, typename INDEXT>
static
cudaError_t
callHistogramKernel(
INPUTTYPE input,
TRANSFORMFUNTYPE xformObj,
SUMFUNTYPE sumfunObj,
INDEXT start, INDEXT end,
OUTPUTTYPE zero, OUTPUTTYPE* out, int nOut,
bool outInDev = false,
cudaStream_t stream = 0, void* tmpBuffer = NULL,
bool allowMultiPass = true);
/*------------------------------------------------------------------------*//*!
* \brief Histogram implementation with multidimensional input indices
*
* Exactly as \ref callHistogramKernel(), except that input-indices
* are replaced by a multidimensional array of indices
*
* \tparam nDim Number of dimesions in multidimensional indices
* \param starts Array of length nDim, giving starting index for
* each dimension of input indices (exclusive (*))
* \param ends Array of length nDim, giving ending index for
* each dimension of input indices (inclusive)
* \note (*) Indices are the [start, start + size - 1], size = end - start
*//**************************************************************************/
template <histogram_type histotype, int nMultires, int nDim,
typename INPUTTYPE, typename TRANSFORMFUNTYPE, typename SUMFUNTYPE,
typename OUTPUTTYPE, typename INDEXT>
static
cudaError_t
callHistogramKernelNDim(
INPUTTYPE input,
TRANSFORMFUNTYPE xformObj,
SUMFUNTYPE sumfunObj,
INDEXT* starts, INDEXT* ends,
OUTPUTTYPE zero, OUTPUTTYPE* out, int nOut,
bool outInDev = false,
cudaStream_t stream = 0, void* tmpBuffer = NULL,
bool allowMultiPass = true);
/*------------------------------------------------------------------------*//*!
* \brief Histogram implementation with two-dimensional input indices
*
* Exactly as \ref callHistogramKernel(), except that input-indices
* are replaced by a two indices
*
* \param x0 Start x-coordinate
* \param x1 End x-coordinate (width = x1 - x0)
* \param y0 Start y-coordinate
* \param y1 End y-coordinate (height = y1 - y0)
*//**************************************************************************/
template <histogram_type histotype, int nMultires,
typename INPUTTYPE, typename TRANSFORMFUNTYPE, typename SUMFUNTYPE,
typename OUTPUTTYPE, typename INDEXT>
cudaError_t
callHistogramKernel2Dim(
INPUTTYPE input,
TRANSFORMFUNTYPE xformObj,
SUMFUNTYPE sumfunObj,
INDEXT x0, INDEXT x1,
INDEXT y0, INDEXT y1,
OUTPUTTYPE zero, OUTPUTTYPE* out, int nOut,
bool outInDev,
cudaStream_t stream, void* tmpBuffer,
bool allowMultiPass = true);
// Start implementation:
// Define this to be one to enable cuda Error-checks (runs a tad slower)
#define H_ERROR_CHECKS 0
#if H_ERROR_CHECKS
#include <assert.h>
#include <stdio.h>
#endif
#define HBLOCK_SIZE_LOG2 7
#define HBLOCK_SIZE (1 << HBLOCK_SIZE_LOG2) // = 32
#define HMBLOCK_SIZE_LOG2 8
#define HMBLOCK_SIZE (1 << HMBLOCK_SIZE_LOG2) // = 32
#define LBLOCK_SIZE_LOG2 5
#define LBLOCK_SIZE (1 << LBLOCK_SIZE_LOG2) // = 256
#define LBLOCK_WARPS (LBLOCK_SIZE >> 5)
#define USE_MEDIUM_PATH 1
#if USE_MEDIUM_PATH
// For now only MEDIUM_BLOCK_SIZE_LOG2 == LBLOCK_SIZE_LOG2 works
# define MEDIUM_BLOCK_SIZE_LOG2 8
# define MEDIUM_BLOCK_SIZE (1 << MEDIUM_BLOCK_SIZE_LOG2) // 128
# define MBLOCK_WARPS (MEDIUM_BLOCK_SIZE >> 5)
#define MED_THREAD_DEGEN 16
#endif
#define RBLOCK_SIZE 64
#define RMAXSTEPS 80
#define NHSTEPSPERKEY 32
#define MAX_NHSTEPS 1024
#define MAX_MULTISTEPS 1024
#define MAX_NLHSTEPS 2048
#define GATHER_BLOCK_SIZE_LOG2 6
#define GATHER_BLOCK_SIZE (1 << GATHER_BLOCK_SIZE_LOG2)
#define STRATEGY_CHECK_INTERVAL_LOG2 7
#define STRATEGY_CHECK_INTERVAL (1 << STRATEGY_CHECK_INTERVAL_LOG2)
#define HISTOGRAM_DEGEN_LIMIT 20
#define HASH_COLLISION_STEPS 2
const int numActiveUpperLimit = 24;
#define USE_JENKINS_HASH 0
#define LARGE_NBIN_CHECK_INTERVAL_LOG2 5
#define LARGE_NBIN_CHECK_INTERVAL (1 << LARGE_NBIN_CHECK_INTERVAL_LOG2)
#define SMALL_BLOCK_SIZE_LOG2 6
#define SMALL_BLOCK_SIZE (1 << SMALL_BLOCK_SIZE_LOG2)
#define MAX_SMALL_STEPS 2040
#if __CUDA_ARCH__ >= 120
#define USE_ATOMICS_HASH 0
#else
#define USE_ATOMICS_HASH 0
#endif
#if (__CUDA_ARCH__ >= 200)
# define USE_BALLOT_HISTOGRAM 1
#else
# define USE_BALLOT_HISTOGRAM 0
#endif
#ifndef __device__
#define __device__
#endif
#ifndef __host__
#define __host__
#endif
#ifndef __shared__
#define __shared__
#endif
//#include <stdio.h>
template <typename OUTPUTTYPE, typename SUMFUNTYPE>
__global__
void multireduceKernel(OUTPUTTYPE* input, int n, int nOut, int nsteps, SUMFUNTYPE sumFun, OUTPUTTYPE zero, int stride, OUTPUTTYPE* initialValues)
{
int tid = threadIdx.x;
int bidx = blockIdx.x;
int bidy = blockIdx.y;
OUTPUTTYPE myout = zero;
int i;
for (i = 0; i < nsteps; i++)
{
int subIndex = bidx * RBLOCK_SIZE + tid;
int cidx = subIndex + i * RBLOCK_SIZE * gridDim.x;
if (cidx < n)
{
// printf("t(%2d)b(%3d,%2d) r(%d)\n", tid, bidx, bidy, cidx + bidy * stride);
myout = sumFun(myout, input[cidx + bidy * stride]);
}
}
__shared__ OUTPUTTYPE tmp[RBLOCK_SIZE / 2];
for (int curLimit = RBLOCK_SIZE / 2; curLimit > 0; curLimit >>= 1)
{
// First write out the current result for threads above the limit
if (tid >= curLimit && tid < (curLimit << 1))
tmp[tid - curLimit] = myout;
// Otherwise wait for the write the complete and add that value to our result
__syncthreads();
if (tid < curLimit)
myout = sumFun(myout, tmp[tid]);
// IMPORTANT: Wait before new loop for the read to complete
__syncthreads();
}
// Done! myout contains the result for our block for thread 0!!
if (tid == 0)
{
// NOTE: If gridDim == 1 then we have finally reached the last iteration and
// can write the result into the final result-value array
// (ie. The same as initialvalue-array)
if (gridDim.x == 1)
{
OUTPUTTYPE initVal = initialValues[bidy];
initialValues[bidy] = sumFun(initVal, myout);
// And we are DONE!
}
else
{
// printf("t(%2d)b(%3d,%2d) w(%d)\n", tid, bidx, bidy, bidx + bidy * stride);
initialValues[bidx + bidy * stride] = myout;
}
}
}
/*------------------------------------------------------------------------*//*!
* \brief Implements multidimensional reduction on the device
*
* \tparam OUTPUTTYPE The type for the inputs and outputs of the reduction
* \tparam SUMFUNTYPE Function object type that implements the binary
* reduction of two input variables
*
* \param arrLen The length of each array in inputs
* \param nOut Number of arrays in input
* \param input The input data laid out as a two-dimensional array,
* where the 'n:th' element of 'i:th' array
* is input[n + i * arrLen].
* MUST RESIDE IN DEVICE MEMORY!
* \param h_results Pointer to an array. where the results
* are to be stored. 'n:th' result will be located at
* h_results[n]. MUST RESIDE IN HOST-MEMORY!
*
* \note \ref input has to reside in device memory
* \note \ref h_results has to reside in host memory
* \note \ref SUMFUNTYPE has to implement operator:
* '__device__ OUTPUTTYPE operator()(OUTPUTTYPE in1, OUTPUTTYPE in2)'
*
* \note Uses \ref RBLOCK_SIZE and \ref RMAX_STEPS as parameters for
* kernel-sizes. Varying these parameters can affect performance.
*//**************************************************************************/
template <typename OUTPUTTYPE, typename SUMFUNTYPE>
static
void callMultiReduce(
int arrLen, int nOut, OUTPUTTYPE* h_results, OUTPUTTYPE* input,
SUMFUNTYPE sumFunObj, OUTPUTTYPE zero,
cudaStream_t stream, void* tmpbuf, bool outInDev)
{
int n = arrLen;
// Set-up yet another temp buffer: (TODO: Pool alloc somehow?)
OUTPUTTYPE* resultTemp = NULL;
// TODO: Why do we need such a large temporary array?
// Shouldn't sizeof(OUTPUTTYPE) * nOut * xblocks be enough??
if (tmpbuf)
{
resultTemp = (OUTPUTTYPE*)tmpbuf;
}
else
{
cudaMalloc((void**)&resultTemp, sizeof(OUTPUTTYPE) * nOut * arrLen);
#if H_ERROR_CHECKS
//printf("resultTemp = %p\n", resultTemp);
cudaError_t error = cudaGetLastError();
if (error != cudaSuccess)
printf("Cudaerror0 = %s\n", cudaGetErrorString( error ));
#endif
}
OUTPUTTYPE* output = resultTemp;
enum cudaMemcpyKind fromOut = outInDev ? cudaMemcpyDeviceToDevice : cudaMemcpyHostToDevice;
enum cudaMemcpyKind toOut = outInDev ? cudaMemcpyDeviceToDevice : cudaMemcpyDeviceToHost;
// Copy initial values:
do
{
int steps = (n + (RBLOCK_SIZE - 1)) / RBLOCK_SIZE;
if (steps > RMAXSTEPS)
steps = RMAXSTEPS;
int yblocks = nOut;
int xblocks = (n + (steps * RBLOCK_SIZE - 1)) / (steps * RBLOCK_SIZE);
const dim3 block = RBLOCK_SIZE;
const dim3 grid(xblocks, yblocks, 1);
if (xblocks == 1) // LAST ONE to start
{
//printf("cudaMemcpy(%p, %p, %d, %d);\n", output, h_results, sizeof(OUTPUTTYPE) * nOut, fromOut);
if (stream != 0)
cudaMemcpyAsync(output, h_results, sizeof(OUTPUTTYPE) * nOut, fromOut, stream);
else
cudaMemcpy(output, h_results, sizeof(OUTPUTTYPE) * nOut, fromOut);
}
#if H_ERROR_CHECKS
cudaError_t error = cudaGetLastError();
if (error != cudaSuccess)
printf("Cudaerror1 = %s\n", cudaGetErrorString( error ));
#endif
// Then the actual kernel call
multireduceKernel<<<grid, block, 0, stream>>>(input, n, nOut, steps, sumFunObj, zero, arrLen, output);
#if H_ERROR_CHECKS
error = cudaGetLastError();
if (error != cudaSuccess)
printf("Cudaerror2 = %s\n", cudaGetErrorString( error ));
#endif
if (xblocks > 1)
{
// Swap pointers:
OUTPUTTYPE* tmpptr = output;
output = input;
input = tmpptr;
}
n = xblocks;
} while(n > 1);
// Then copy back the results:
//cudaMemcpyAsync(h_results, resultTemp, sizeof(OUTPUTTYPE) * nOut, cudaMemcpyDeviceToHost, CURRENT_STREAM());
// TODO: Support async copy here??
if (outInDev && stream != 0)
cudaMemcpyAsync(h_results, output, sizeof(OUTPUTTYPE) * nOut, toOut, stream);
else
cudaMemcpy(h_results, output, sizeof(OUTPUTTYPE) * nOut, toOut);
#if H_ERROR_CHECKS
cudaError_t error = cudaGetLastError();
if (error != cudaSuccess)
printf("Cudaerror3 = %s\n", cudaGetErrorString( error ));
#endif
if (!tmpbuf)
{
cudaFree(resultTemp);
}
#if H_ERROR_CHECKS
error = cudaGetLastError();
if (error != cudaSuccess)
printf("Cudaerror4 = %s\n", cudaGetErrorString( error ));
#endif
}
template <typename SUMFUNTYPE, typename OUTPUTTYPE>
__global__
void gatherKernel(SUMFUNTYPE sumfunObj, OUTPUTTYPE* blockOut, int nOut, int nEntries, OUTPUTTYPE zero)
{
//int resIdx = threadIdx.x + blockDim.x * blockIdx.x;
int resIdx = blockIdx.x;
if (resIdx < nOut)
{
// Let's divide the nEntries first evenly on all threads and read 4 entries in a row
int locEntries = (nEntries) >> (GATHER_BLOCK_SIZE_LOG2);
// Note: Original array entry is stored in resIdx + nOut * nEntries!
OUTPUTTYPE res = zero;
if (threadIdx.x == 0)
res = blockOut[resIdx + nOut * nEntries];
// Shift starting ptr:
blockOut = &blockOut[resIdx];
int locIdx = threadIdx.x * locEntries;
for (int i=0; i < locEntries/4; i++)
{
OUTPUTTYPE x1 = blockOut[nOut * (locIdx + (i << 2))];
OUTPUTTYPE x2 = blockOut[nOut * (locIdx + (i << 2) + 1)];
OUTPUTTYPE x3 = blockOut[nOut * (locIdx + (i << 2) + 2)];
OUTPUTTYPE x4 = blockOut[nOut * (locIdx + (i << 2) + 3)];
res = sumfunObj(res, x1);
res = sumfunObj(res, x2);
res = sumfunObj(res, x3);
res = sumfunObj(res, x4);
}
// Then do the rest
for (int j = (locEntries/4)*4; j < locEntries; j++)
{
OUTPUTTYPE x1 = blockOut[nOut * (locIdx + j)];
res = sumfunObj(res, x1);
}
// Still handle rest starting from index "locEntries * BLOCK_SIZE":
locIdx = threadIdx.x + (locEntries << GATHER_BLOCK_SIZE_LOG2);
if (locIdx < nEntries)
res = sumfunObj(res, blockOut[nOut * locIdx]);
// Ok - all that is left is to do the final parallel reduction between threads:
{
__shared__ OUTPUTTYPE data[GATHER_BLOCK_SIZE];
//volatile OUTPUTTYPE* data = (volatile OUTPUTTYPE*)&dataTmp[0];
// TODO Compiler complains with volatile from this - why?
//error: no operator "=" matches these operands
// operand types are: volatile myTestType_s = myTestType
// Silly - does not happen with built-in types (nice...)
data[threadIdx.x] = res;
#if GATHER_BLOCK_SIZE == 512
__syncthreads();
if (threadIdx.x < 256)
data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 256]);
#endif
#if GATHER_BLOCK_SIZE >= 256
__syncthreads();
if (threadIdx.x < 128)
data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 128]);
#endif
#if GATHER_BLOCK_SIZE >= 128
__syncthreads();
if (threadIdx.x < 64)
data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 64]);
__syncthreads();
#endif
#if GATHER_BLOCK_SIZE >= 64
__syncthreads();
if (threadIdx.x < 32)
data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 32]);
#endif
__syncthreads();
if (threadIdx.x < 16) data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 16]);
__syncthreads();
if (threadIdx.x < 8) data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 8]);
__syncthreads();
if (threadIdx.x < 4) data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 4]);
__syncthreads();
if (threadIdx.x < 2) data[threadIdx.x] = sumfunObj(data[threadIdx.x], data[threadIdx.x + 2]);
__syncthreads();
if (threadIdx.x < 1) *blockOut = sumfunObj(data[threadIdx.x], data[threadIdx.x + 1]);
}
}
}
#define FREE_MUTEX_ID 0xffeecafe
#define TAKE_WARP_MUTEX(ID) do { \
int warpIdWAM = threadIdx.x >> 5; \
__shared__ volatile int lockVarWarpAtomicMutex;\
bool doneWAM = false;\
bool allDone = false; \
while(!allDone){ \
__syncthreads(); \
if (!doneWAM) lockVarWarpAtomicMutex = warpIdWAM; \
__syncthreads(); \
if (lockVarWarpAtomicMutex == FREE_MUTEX_ID) allDone = true; \
__syncthreads(); \
if (lockVarWarpAtomicMutex == warpIdWAM){ /* We Won */
// User code comes here
#define GIVE_WARP_MUTEX(ID) doneWAM = true; \
lockVarWarpAtomicMutex = FREE_MUTEX_ID; \
} \
} \
__syncthreads(); \
} while(0)
// NOTE: Init must be called from divergent-free code (or with exited warps)
#define INIT_WARP_MUTEX2(MUTEX) do { MUTEX = FREE_MUTEX_ID; __syncthreads(); } while(0)
#if 0 && __CUDA_ARCH__ >= 120 // TODO: NOT WORKING THIS CODEPATH - find out why
#define TAKE_WARP_MUTEX2(MUTEX) do { \
int warpIdWAM = 1000000 + threadIdx.x / 32; \
bool doneWAM = false;\
while(!doneWAM){ \
int old = -2; \
if (threadIdx.x % 32 == 0) \
old = atomicCAS(&MUTEX, FREE_MUTEX_ID, warpIdWAM); \
if (__any(old == FREE_MUTEX_ID)){ /* We Won */
// User code comes here
#define GIVE_WARP_MUTEX2(MUTEX) doneWAM = true; \
atomicExch(&MUTEX, FREE_MUTEX_ID); \
} \
} \
} while(0)
#else
#define TAKE_WARP_MUTEX2(MUTEX) do { \
int warpIdWAM = 1000000 + threadIdx.x / 32; \
bool doneWAM = false;\
bool allDone = false; \
while(!allDone){ \
__syncthreads(); \
if (!doneWAM) MUTEX = warpIdWAM; \
__syncthreads(); \
if (MUTEX == FREE_MUTEX_ID) allDone = true; \
if (MUTEX == warpIdWAM){ /* We Won */
// User code comes here
#define GIVE_WARP_MUTEX2(MUTEX) doneWAM = true; \
MUTEX = FREE_MUTEX_ID; \
} \
} \
} while(0)
#endif
#if USE_BALLOT_HISTOGRAM
template <typename OUTPUTTYPE>
static inline __device__
OUTPUTTYPE mySillyPopCount(unsigned int mymask, OUTPUTTYPE zero)
{
return zero;
}
static inline __device__
int mySillyPopCount(unsigned int mymask, int zero)
{
return (int)__popc(mymask);
}
static inline __device__
unsigned int mySillyPopCount(unsigned int mymask, unsigned int zero)
{
return (unsigned int)__popc(mymask);
}
static inline __device__
long long mySillyPopCount(unsigned int mymask, long long zero)
{
return (long long)__popc(mymask);
}
static inline __device__
unsigned long long mySillyPopCount(unsigned int mymask, unsigned long long zero)
{
return (unsigned long long)__popc(mymask);
}
template <histogram_type histotype, bool checkNSame, typename SUMFUNTYPE, typename OUTPUTTYPE>
static inline __device__
bool ballot_makeUnique(
SUMFUNTYPE sumfunObj,
int myKey, OUTPUTTYPE* myOut, OUTPUTTYPE* s_vals, int* s_keys, int* nSameKeys)
{
unsigned int mymask;
/* #if HBLOCK_SIZE != 32
#error Please use threadblocks of 32 threads
#endif*/
//startKey = s_keys[startIndex];
// First dig out for each thread who are the other threads that have the same key as us...
//int i = 0;
if (checkNSame) {
unsigned int donemask = 0;
int startIndex = 32 - 1;
int startKey = s_keys[startIndex];
*nSameKeys = 0;
while (~donemask != 0 /*&& i++ < 32*/)
{
unsigned int mask = __ballot(myKey == startKey);
if (myKey == startKey)
mymask = mask;
donemask |= mask;
{
int nSame = __popc(mask);
if (nSame > *nSameKeys)
*nSameKeys = nSame;
}
startIndex = 31 - __clz(~donemask);
//if (myKey == 0) printf("Startindex = %d, donemask = 0x%08x, mask = 0x%08x\n", startIndex, donemask, mask);
if (startIndex >= 0)
startKey = s_keys[startIndex];
}
} else {
unsigned int donemask = 0;
int startIndex = 32 - 1;
while (startIndex >= 0)
{
int startKey = s_keys[startIndex];
unsigned int mask = __ballot(myKey == startKey);
if (myKey == startKey)
mymask = mask;
donemask |= mask;
startIndex = 31 - __clz(~donemask);
}
}
// Ok now mymask contains those threads - now we just reduce locally - all threads run at the same
// time, but reducing threads lose always half of them with each iteration - it would help
// to work with more than 32 entries, but the algorithm seems to get tricky there.
{
// Compute the left side of the mask and the right side. rmask first will contain our thread index, but
// we zero it out immediately
unsigned int lmask = (mymask >> (threadIdx.x & 31)) << (threadIdx.x & 31);
int IamNth = __popc(lmask) - 1;
bool Iwrite = IamNth == 0;
if (histotype == histogram_atomic_inc)
{
// Fast-path for atomic inc
*myOut = mySillyPopCount(mymask, *myOut);
return Iwrite && (myKey >= 0);
}
else
{
unsigned int rmask = mymask & (~lmask);
// Now compute which number is our thread in the subarray of those threads that have the same key
// starting from the left (ie. index == 31). So for thread 31 this will be always zero.
int nextIdx = 31 - __clz(rmask);
s_vals[(threadIdx.x & 31)] = *myOut;
//if (myKey == 0) printf("tid = %02d, IamNth = %02d, mask = 0x%08x, rmask = 0x%08x \n", threadIdx.x, IamNth, mymask, rmask);
//bool done = __all(nextIdx < 0);
// TODO: Unroll 5?
while (!__all(nextIdx < 0))
{
// Reduce towards those threads that have lower IamNth
// Our thread reads the next one if our internal ID is even
if ((IamNth & 0x1) == 0)
{
if (nextIdx >= 0){
// if (myKey == 0) printf("tid:%02d, add with %02d\n", threadIdx.x, nextIdx);
*myOut = sumfunObj(*myOut, s_vals[nextIdx]);
}
// And writes to the shared memory if our internal ID is third on every 4-long subarray:
if ((IamNth & 0x3) == 2)
{
// if (myKey == 0) printf("Tid %02d, store\n", threadIdx.x);
s_vals[(threadIdx.x & 31)] = *myOut;
}
}
// Now the beautiful part: Kill every other bit in the rmask bitfield. How, you ask?
// Using ballot: Every bit we want to kill has IamNth odd, or conversely, we only
// want to keep those bits that have IamNth even...
rmask &= __ballot((IamNth & 0x1) == 0);
nextIdx = 31 - __clz(rmask);
// if (myKey == 0) printf("tid = %02d, next = %02d, key = %d\n", threadIdx.x, rmask, nextIdx, myKey);
IamNth >>= 1;
//printf("i = %d\n", i);
}
// And voila, we are done - write out the result:
return Iwrite && (myKey >= 0);
}
}
}
#endif
template <bool laststeps, typename SUMFUNTYPE, typename OUTPUTTYPE>
static inline __device__
void myAtomicWarpAdd(OUTPUTTYPE* addr, OUTPUTTYPE val, volatile int* keyAddr, SUMFUNTYPE sumfunObj, bool Iwrite, int* warpmutex)
{
// Taken from http://forums.nvidia.com/index.php?showtopic=72925
// This is a tad slow, but allows arbitrary operation
// For writes of 16 bytes or less AtomicCAS could be faster
// (See CUDA programming guide)
TAKE_WARP_MUTEX(0);
//__shared__ int warpmutex;
//INIT_WARP_MUTEX2(*warpmutex);
//TAKE_WARP_MUTEX2(*warpmutex);
bool write = Iwrite;
#define MU_TEMP_MAGIC 0xffffaaaa
*keyAddr = MU_TEMP_MAGIC;
while (1)
{
// Vote whose turn is it - remember, one thread does succeed always!:
if (write) *keyAddr = threadIdx.x;
if (*keyAddr == MU_TEMP_MAGIC)
break;
if (*keyAddr == threadIdx.x) // We won!
{
// Do arbitrary atomic op:
*addr = sumfunObj(*addr, val);
write = false;
*keyAddr = MU_TEMP_MAGIC;
}
}
GIVE_WARP_MUTEX(0);
//GIVE_WARP_MUTEX2(*warpmutex);
#undef MU_TEMP_MAGIC
}
template <typename SUMFUNTYPE, typename OUTPUTTYPE>
static inline __device__
void myAtomicAdd(OUTPUTTYPE* addr, OUTPUTTYPE val, volatile int* keyAddr, SUMFUNTYPE sumfunObj)
{
// Taken from http://forums.nvidia.com/index.php?showtopic=72925
// This is a tad slow, but allows arbitrary operation
// For writes of 16 bytes or less AtomicCAS could be faster
// (See CUDA programming guide)
bool write = true;
#define MU_TEMP_MAGIC 0xffffaaaa
*keyAddr = MU_TEMP_MAGIC;
while (1)
{
// Vote whose turn is it - remember, one thread does succeed always!:
if (write ) *keyAddr = threadIdx.x;
if (*keyAddr == MU_TEMP_MAGIC)
break;
if (*keyAddr == threadIdx.x) // We won!
{
// Do arbitrary atomic op:
*addr = sumfunObj(*addr, val);
write = false;
*keyAddr = MU_TEMP_MAGIC;
}
}
#undef MU_TEMP_MAGIC
}
/*static __inline__ __device__ unsigned long long int atomicAdd(unsigned long long int *address, unsigned long long int val)
{
return __ullAtomicAdd(address, val);
}*/
template <typename OUTPUTTYPE>
static inline __device__
void atomicAdd(OUTPUTTYPE* addr, OUTPUTTYPE val)
{
//*addr = val;
}
template <typename OUTPUTTYPE>
static inline __device__
void atomicAdd(OUTPUTTYPE* addr, int val)
{
//*addr = val;
}
#if 0
template <typename OUTPUTTYPE>
static inline __device__
void atomicAdd(OUTPUTTYPE* addr, float val)
{
//*addr = val;
}
#endif
template <typename OUTPUTTYPE>
static inline __device__
void atomicAdd(OUTPUTTYPE* addr, unsigned int val)
{
//*addr = val;
}
template <typename SUMFUNTYPE, typename OUTPUTTYPE>
static inline __device__
void myAtomicAddStats(OUTPUTTYPE* addr, OUTPUTTYPE val, volatile int* keyAddr, SUMFUNTYPE sumfunObj, int* nSameOut, bool Iwrite)
{
// Taken from http://forums.nvidia.com/index.php?showtopic=72925
bool write = true;
*keyAddr = 0xffffffff;
while (Iwrite)
{
// Vote whose turn is it - remember, one thread does succeed always!:
if (write ) *keyAddr = threadIdx.x;
if (*keyAddr == 0xffffffff)
break;
if (*keyAddr == threadIdx.x) // We won!
{
// Do arbitrary atomic op:
*addr = sumfunObj(*addr, val);
write = false;
*keyAddr = 0xffffffff;
} else {
*nSameOut = *nSameOut + 1;
}
}
{
// Then find max
__shared__ int nSame[HBLOCK_SIZE];
nSame[threadIdx.x] = *nSameOut;
#define TMPMAX(A,B) (A) > (B) ? (A) : (B)
#define tidx threadIdx.x
if (tidx < 16) nSame[tidx] = TMPMAX(nSame[tidx] , nSame[tidx + 16]);
if (tidx < 8) nSame[tidx] = TMPMAX(nSame[tidx] , nSame[tidx + 8]);
if (tidx < 4) nSame[tidx] = TMPMAX(nSame[tidx] , nSame[tidx + 4]);
if (tidx < 2) nSame[tidx] = TMPMAX(nSame[tidx] , nSame[tidx + 2]);
if (tidx < 1) nSame[tidx] = TMPMAX(nSame[tidx] , nSame[tidx + 1]);
#undef TMPMAX
#undef tidx
// Broadcast to all threads
*nSameOut = nSame[0];
}
}
// TODO: Make unique within one warp?
template<histogram_type histotype, bool checkNSame, typename SUMFUNTYPE, typename OUTPUTTYPE>
static inline __device__
bool reduceToUnique(OUTPUTTYPE* res, int myKey, int* nSame, SUMFUNTYPE sumfunObj, int* keys, OUTPUTTYPE* outputs)
{
keys[(threadIdx.x & 31)] = myKey;
#if USE_BALLOT_HISTOGRAM
return ballot_makeUnique<histotype, checkNSame>(sumfunObj, myKey, res, outputs, keys, nSame);
#else
{
int i;
bool writeResult = myKey >= 0;
int myIdx = (threadIdx.x & 31) + 1;
outputs[(threadIdx.x & 31)] = *res;
// The assumption for sanity of this loop here is that all the data is in registers or shared memory and
// hence this loop will not actually be __that__ slow.. Also it helps if the data is spread out (ie. there are
// a lot of different indices here)
for (i = 1; i < 32 && writeResult; i++)
{
if (myIdx >= 32)
myIdx = 0;
// Is my index the same as the index on the index-list?
if (keys[myIdx] == myKey /*&& threadIdx.x != myIdx*/)
{
if (checkNSame) (*nSame)++;
// If yes, then we can sum up the result using users sum-functor
*res = sumfunObj(*res, outputs[myIdx]);
// But if somebody else is summing up this index already, we don't need to (wasted effort done here)
if (myIdx < threadIdx.x)
writeResult = false;
}
myIdx++;
}
// Ok - we are done - now we can proceed in writing the result (if some other thread isn't doing it already)
if (checkNSame)
{
// Manual reduce
int tid = threadIdx.x;
keys[tid] = *nSame;
if (tid < 16) keys[tid] = keys[tid] > keys[tid + 16] ? keys[tid] : keys[tid+16];
if (tid < 8) keys[tid] = keys[tid] > keys[tid + 8] ? keys[tid] : keys[tid+8];
if (tid < 4) keys[tid] = keys[tid] > keys[tid + 4] ? keys[tid] : keys[tid+4];
if (tid < 2) keys[tid] = keys[tid] > keys[tid + 2] ? keys[tid] : keys[tid+2];
if (tid < 1) keys[tid] = keys[tid] > keys[tid + 1] ? keys[tid] : keys[tid+1];
*nSame = keys[0];
}
return writeResult;
}
#endif
}
static inline __host__ __device__
void checkStrategyFun(bool *reduce, int nSame, int nSameTot, int step, int nBinSetslog2)
{
#if __CUDA_ARCH__ >= 200
#define STR_LIMIT 12
#else
#define STR_LIMIT 24
#endif
// TODO: Fix average case - a lot of things to tune here...
if ((nSameTot > STR_LIMIT * step || nSame > STR_LIMIT))
*reduce = true;
else
*reduce = false;
#undef STR_LIMIT
}
// Special case for floats (atomicAdd works only from __CUDA_ARCH__ 200 and up)
template <typename SUMFUNTYPE>
static inline __device__
void wrapAtomicAdd2(float* addr, float val, int* key, SUMFUNTYPE sumFunObj)
{
//*addr = val;
#if __CUDA_ARCH__ >= 200
atomicAdd(addr, val);
#else
myAtomicAdd(addr, val, key, sumFunObj);
#endif
}
template <typename SUMFUNTYPE,typename OUTPUTTYPE>
static inline __device__
void wrapAtomicAdd2(OUTPUTTYPE* addr, OUTPUTTYPE val, int* key, SUMFUNTYPE sumFunObj)
{
atomicAdd(addr, val);
}
// Special case for floats (atomicAdd works only from __CUDA_ARCH__ 200 and up)