-
Notifications
You must be signed in to change notification settings - Fork 548
/
Copy pathbh.cu
1531 lines (1319 loc) · 60.8 KB
/
bh.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
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 BarnesHut v3.1: Simulation of the gravitational forces
in a galactic cluster using the Barnes-Hut n-body algorithm
Copyright (c) 2013, Texas State University-San Marcos. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted for academic, research, experimental, or personal use provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Texas State University-San Marcos nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
For all other uses, please contact the Office for Commercialization and Industry
Relations at Texas State University-San Marcos <http://www.txstate.edu/ocir/>.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
Author: Martin Burtscher <burtscher@txstate.edu>
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include <cuda.h>
#include <chrono>
#include <bh_tsne.h>
#include <cuda_runtime_api.h>
#ifndef NO_ZMQ
#include <zmq.hpp>
#endif
#ifndef CUDART_VERSION
#error CUDART_VERSION Undefined!
#endif
// #ifdef __KEPLER__
// #define GPU_ARCH "KEPLER"
// // thread count
// #define THREADS1 1024 /* must be a power of 2 */
// #define THREADS2 1024
// #define THREADS3 768
// #define THREADS4 128
// #define THREADS5 1024
// #define THREADS6 1024
// // block count = factor * #SMs
// #define FACTOR1 2
// #define FACTOR2 2
// #define FACTOR3 1 /* must all be resident at the same time */
// #define FACTOR4 4 /* must all be resident at the same time */
// #define FACTOR5 2
// #define FACTOR6 2
// #elif __MAXWELL__
// #define GPU_ARCH "MAXWELL"
// // thread count
// #define THREADS1 512 /* must be a power of 2 */
// #define THREADS2 512
// #define THREADS3 128
// #define THREADS4 64
// #define THREADS5 256
// #define THREADS6 1024
// // block count = factor * #SMs
// #define FACTOR1 3
// #define FACTOR2 3
// #define FACTOR3 6 /* must all be resident at the same time */
// #define FACTOR4 6 /* must all be resident at the same time */
// #define FACTOR5 5
// #define FACTOR6 1
// #elif __PASCAL__
#define GPU_ARCH "PASCAL"
// thread count
#define THREADS1 512 /* must be a power of 2 */
#define THREADS2 512
#define THREADS3 768
#define THREADS4 128
#define THREADS5 1024
#define THREADS6 1024
#define THREADS7 1024
// block count = factor * #SMs
#define FACTOR1 3
#define FACTOR2 3
#define FACTOR3 1 /* must all be resident at the same time */
#define FACTOR4 4 /* must all be resident at the same time */
#define FACTOR5 2
#define FACTOR6 2
#define FACTOR7 1
// #else
// #define GPU_ARCH "UNKNOWN"
// // thread count
// #define THREADS1 512 /* must be a power of 2 */
// #define THREADS2 512
// #define THREADS3 128
// #define THREADS4 64
// #define THREADS5 256
// #define THREADS6 1024
// // block count = factor * #SMs
// #define FACTOR1 3
// #define FACTOR2 3
// #define FACTOR3 6 /* must all be resident at the same time */
// #define FACTOR4 6 /* must all be resident at the same time */
// #define FACTOR5 5
// #define FACTOR6 1
// #endif
#define WARPSIZE 32
#define MAXDEPTH 32
__device__ volatile int stepd, bottomd, maxdepthd;
__device__ unsigned int blkcntd;
__device__ volatile float radiusd;
/******************************************************************************/
/*** initialize memory ********************************************************/
/******************************************************************************/
__global__ void InitializationKernel(int * __restrict errd)
{
*errd = 0;
stepd = -1;
maxdepthd = 1;
blkcntd = 0;
}
/******************************************************************************/
/*** compute center and radius ************************************************/
/******************************************************************************/
__global__
__launch_bounds__(THREADS1, FACTOR1)
void BoundingBoxKernel(int nnodesd,
int nbodiesd,
volatile int * __restrict startd,
volatile int * __restrict childd,
volatile float * __restrict massd,
volatile float * __restrict posxd,
volatile float * __restrict posyd,
volatile float * __restrict maxxd,
volatile float * __restrict maxyd,
volatile float * __restrict minxd,
volatile float * __restrict minyd)
{
register int i, j, k, inc;
register float val, minx, maxx, miny, maxy;
__shared__ volatile float sminx[THREADS1], smaxx[THREADS1], sminy[THREADS1], smaxy[THREADS1];
// initialize with valid data (in case #bodies < #threads)
minx = maxx = posxd[0];
miny = maxy = posyd[0];
// scan all bodies
i = threadIdx.x;
inc = THREADS1 * gridDim.x;
for (j = i + blockIdx.x * THREADS1; j < nbodiesd; j += inc) {
val = posxd[j];
minx = fminf(minx, val);
maxx = fmaxf(maxx, val);
val = posyd[j];
miny = fminf(miny, val);
maxy = fmaxf(maxy, val);
}
// reduction in shared memory
sminx[i] = minx;
smaxx[i] = maxx;
sminy[i] = miny;
smaxy[i] = maxy;
for (j = THREADS1 / 2; j > 0; j /= 2) {
__syncthreads();
if (i < j) {
k = i + j;
sminx[i] = minx = fminf(minx, sminx[k]);
smaxx[i] = maxx = fmaxf(maxx, smaxx[k]);
sminy[i] = miny = fminf(miny, sminy[k]);
smaxy[i] = maxy = fmaxf(maxy, smaxy[k]);
}
}
// write block result to global memory
if (i == 0) {
k = blockIdx.x;
minxd[k] = minx;
maxxd[k] = maxx;
minyd[k] = miny;
maxyd[k] = maxy;
__threadfence();
inc = gridDim.x - 1;
if (inc == atomicInc(&blkcntd, inc)) {
// I'm the last block, so combine all block results
for (j = 0; j <= inc; j++) {
minx = fminf(minx, minxd[j]);
maxx = fmaxf(maxx, maxxd[j]);
miny = fminf(miny, minyd[j]);
maxy = fmaxf(maxy, maxyd[j]);
}
// compute 'radius'
radiusd = fmaxf(maxx - minx, maxy - miny) * 0.5f + 1e-5f;
// create root node
k = nnodesd;
bottomd = k;
massd[k] = -1.0f;
startd[k] = 0;
posxd[k] = (minx + maxx) * 0.5f;
posyd[k] = (miny + maxy) * 0.5f;
k *= 4;
for (i = 0; i < 4; i++) childd[k + i] = -1;
stepd++;
}
}
}
/******************************************************************************/
/*** build tree ***************************************************************/
/******************************************************************************/
__global__
__launch_bounds__(1024, 1)
void ClearKernel1(int nnodesd, int nbodiesd, volatile int * __restrict childd)
{
register int k, inc, top, bottom;
top = 4 * nnodesd;
bottom = 4 * nbodiesd;
inc = blockDim.x * gridDim.x;
k = (bottom & (-WARPSIZE)) + threadIdx.x + blockIdx.x * blockDim.x; // align to warp size
if (k < bottom) k += inc;
// iterate over all cells assigned to thread
while (k < top) {
childd[k] = -1;
k += inc;
}
}
__global__
__launch_bounds__(THREADS2, FACTOR2)
void TreeBuildingKernel(int nnodesd,
int nbodiesd,
volatile int * __restrict errd,
volatile int * __restrict childd,
volatile float * __restrict posxd,
volatile float * __restrict posyd)
{
register int i, j, depth, localmaxdepth, skip, inc;
register float x, y, r;
register float px, py;
register float dx, dy;
register int ch, n, cell, locked, patch;
register float radius, rootx, rooty;
// cache root data
radius = radiusd;
rootx = posxd[nnodesd];
rooty = posyd[nnodesd];
localmaxdepth = 1;
skip = 1;
inc = blockDim.x * gridDim.x;
i = threadIdx.x + blockIdx.x * blockDim.x;
// iterate over all bodies assigned to thread
while (i < nbodiesd) {
// if (TID == 0)
// printf("\tStarting\n");
if (skip != 0) {
// new body, so start traversing at root
skip = 0;
px = posxd[i];
py = posyd[i];
n = nnodesd;
depth = 1;
r = radius * 0.5f;
dx = dy = -r;
j = 0;
// determine which child to follow
if (rootx < px) {j = 1; dx = r;}
if (rooty < py) {j |= 2; dy = r;}
x = rootx + dx;
y = rooty + dy;
}
// follow path to leaf cell
ch = childd[n*4+j];
while (ch >= nbodiesd) {
n = ch;
depth++;
r *= 0.5f;
dx = dy = -r;
j = 0;
// determine which child to follow
if (x < px) {j = 1; dx = r;}
if (y < py) {j |= 2; dy = r;}
x += dx;
y += dy;
ch = childd[n*4+j];
}
if (ch != -2) { // skip if child pointer is locked and try again later
locked = n*4+j;
if (ch == -1) {
if (-1 == atomicCAS((int *)&childd[locked], -1, i)) { // if null, just insert the new body
localmaxdepth = max(depth, localmaxdepth);
i += inc; // move on to next body
skip = 1;
}
} else { // there already is a body in this position
if (ch == atomicCAS((int *)&childd[locked], ch, -2)) { // try to lock
patch = -1;
// create new cell(s) and insert the old and new body
do {
depth++;
cell = atomicSub((int *)&bottomd, 1) - 1;
if (cell <= nbodiesd) {
*errd = 1;
bottomd = nnodesd;
}
if (patch != -1) {
childd[n*4+j] = cell;
}
patch = max(patch, cell);
j = 0;
if (x < posxd[ch]) j = 1;
if (y < posyd[ch]) j |= 2;
childd[cell*4+j] = ch;
n = cell;
r *= 0.5f;
dx = dy = -r;
j = 0;
if (x < px) {j = 1; dx = r;}
if (y < py) {j |= 2; dy = r;}
x += dx;
y += dy;
ch = childd[n*4+j];
// repeat until the two bodies are different children
} while (ch >= 0 && r > 1e-10); // add radius check because bodies that are very close together can cause this to fail... there is some error condition here that I'm not entirely sure of (not just when two bodies are equal)
childd[n*4+j] = i;
localmaxdepth = max(depth, localmaxdepth);
i += inc; // move on to next body
skip = 2;
}
}
}
__threadfence();
if (skip == 2) {
childd[locked] = patch;
}
}
// record maximum tree depth
atomicMax((int *)&maxdepthd, localmaxdepth);
}
__global__
__launch_bounds__(1024, 1)
void ClearKernel2(int nnodesd, volatile int * __restrict startd, volatile float * __restrict massd)
{
register int k, inc, bottom;
bottom = bottomd;
inc = blockDim.x * gridDim.x;
k = (bottom & (-WARPSIZE)) + threadIdx.x + blockIdx.x * blockDim.x; // align to warp size
if (k < bottom) k += inc;
// iterate over all cells assigned to thread
while (k < nnodesd) {
massd[k] = -1.0f;
startd[k] = -1;
k += inc;
}
}
/******************************************************************************/
/*** compute center of mass ***************************************************/
/******************************************************************************/
__global__
__launch_bounds__(THREADS3, FACTOR3)
void SummarizationKernel(const int nnodesd,
const int nbodiesd,
volatile int * __restrict countd,
const int * __restrict childd,
volatile float * __restrict massd,
volatile float * __restrict posxd,
volatile float * __restrict posyd)
{
register int i, j, k, ch, inc, cnt, bottom, flag;
register float m, cm, px, py;
__shared__ int child[THREADS3 * 4];
__shared__ float mass[THREADS3 * 4];
bottom = bottomd;
inc = blockDim.x * gridDim.x;
k = (bottom & (-WARPSIZE)) + threadIdx.x + blockIdx.x * blockDim.x; // align to warp size
if (k < bottom) k += inc;
register int restart = k;
for (j = 0; j < 5; j++) { // wait-free pre-passes
// iterate over all cells assigned to thread
while (k <= nnodesd) {
if (massd[k] < 0.0f) {
for (i = 0; i < 4; i++) {
ch = childd[k*4+i];
child[i*THREADS3+threadIdx.x] = ch; // cache children
if ((ch >= nbodiesd) && ((mass[i*THREADS3+threadIdx.x] = massd[ch]) < 0.0f)) {
break;
}
}
if (i == 4) {
// all children are ready
cm = 0.0f;
px = 0.0f;
py = 0.0f;
cnt = 0;
for (i = 0; i < 4; i++) {
ch = child[i*THREADS3+threadIdx.x];
if (ch >= 0) {
if (ch >= nbodiesd) { // count bodies (needed later)
m = mass[i*THREADS3+threadIdx.x];
cnt += countd[ch];
} else {
m = massd[ch];
cnt++;
}
// add child's contribution
cm += m;
px += posxd[ch] * m;
py += posyd[ch] * m;
}
}
countd[k] = cnt;
m = 1.0f / cm;
posxd[k] = px * m;
posyd[k] = py * m;
__threadfence(); // make sure data are visible before setting mass
massd[k] = cm;
}
}
k += inc; // move on to next cell
}
k = restart;
}
flag = 0;
j = 0;
// iterate over all cells assigned to thread
while (k <= nnodesd) {
if (massd[k] >= 0.0f) {
k += inc;
} else {
if (j == 0) {
j = 4;
for (i = 0; i < 4; i++) {
ch = childd[k*4+i];
child[i*THREADS3+threadIdx.x] = ch; // cache children
if ((ch < nbodiesd) || ((mass[i*THREADS3+threadIdx.x] = massd[ch]) >= 0.0f)) {
j--;
}
}
} else {
j = 4;
for (i = 0; i < 4; i++) {
ch = child[i*THREADS3+threadIdx.x];
if ((ch < nbodiesd) || (mass[i*THREADS3+threadIdx.x] >= 0.0f) || ((mass[i*THREADS3+threadIdx.x] = massd[ch]) >= 0.0f)) {
j--;
}
}
}
if (j == 0) {
// all children are ready
cm = 0.0f;
px = 0.0f;
py = 0.0f;
cnt = 0;
for (i = 0; i < 4; i++) {
ch = child[i*THREADS3+threadIdx.x];
if (ch >= 0) {
if (ch >= nbodiesd) { // count bodies (needed later)
m = mass[i*THREADS3+threadIdx.x];
cnt += countd[ch];
} else {
m = massd[ch];
cnt++;
}
// add child's contribution
cm += m;
px += posxd[ch] * m;
py += posyd[ch] * m;
}
}
countd[k] = cnt;
m = 1.0f / cm;
posxd[k] = px * m;
posyd[k] = py * m;
flag = 1;
}
}
__syncthreads();
// __threadfence();
if (flag != 0) {
massd[k] = cm;
k += inc;
flag = 0;
}
}
}
/******************************************************************************/
/*** sort bodies **************************************************************/
/******************************************************************************/
__global__
__launch_bounds__(THREADS4, FACTOR4)
void SortKernel(int nnodesd, int nbodiesd, int * __restrict sortd, int * __restrict countd, volatile int * __restrict startd, int * __restrict childd)
{
register int i, j, k, ch, dec, start, bottom;
bottom = bottomd;
dec = blockDim.x * gridDim.x;
k = nnodesd + 1 - dec + threadIdx.x + blockIdx.x * blockDim.x;
// iterate over all cells assigned to thread
while (k >= bottom) {
start = startd[k];
if (start >= 0) {
j = 0;
for (i = 0; i < 4; i++) {
ch = childd[k*4+i];
if (ch >= 0) {
if (i != j) {
// move children to front (needed later for speed)
childd[k*4+i] = -1;
childd[k*4+j] = ch;
}
j++;
if (ch >= nbodiesd) {
// child is a cell
startd[ch] = start; // set start ID of child
start += countd[ch]; // add #bodies in subtree
} else {
// child is a body
sortd[start] = ch; // record body in 'sorted' array
start++;
}
}
}
k -= dec; // move on to next cell
}
}
}
/******************************************************************************/
/*** compute force ************************************************************/
/******************************************************************************/
__global__
__launch_bounds__(THREADS5, FACTOR5)
void ForceCalculationKernel(int nnodesd,
int nbodiesd,
volatile int * __restrict errd,
float theta,
float epssqd, // correction for zero distance
volatile int * __restrict sortd,
volatile int * __restrict childd,
volatile float * __restrict massd,
volatile float * __restrict posxd,
volatile float * __restrict posyd,
volatile float * __restrict velxd,
volatile float * __restrict velyd,
volatile float * __restrict normd)
{
register int i, j, k, n, depth, base, sbase, diff, pd, nd;
register float px, py, vx, vy, dx, dy, normsum, tmp, mult;
__shared__ volatile int pos[MAXDEPTH * THREADS5/WARPSIZE], node[MAXDEPTH * THREADS5/WARPSIZE];
__shared__ float dq[MAXDEPTH * THREADS5/WARPSIZE];
if (0 == threadIdx.x) {
dq[0] = (radiusd * radiusd) / (theta * theta);
for (i = 1; i < maxdepthd; i++) {
dq[i] = dq[i - 1] * 0.25f; // radius is halved every level of tree so squared radius is quartered
dq[i - 1] += epssqd;
}
dq[i - 1] += epssqd;
if (maxdepthd > MAXDEPTH) {
*errd = maxdepthd;
}
}
__syncthreads();
if (maxdepthd <= MAXDEPTH) {
// figure out first thread in each warp (lane 0)
base = threadIdx.x / WARPSIZE;
sbase = base * WARPSIZE;
j = base * MAXDEPTH;
diff = threadIdx.x - sbase;
// make multiple copies to avoid index calculations later
if (diff < MAXDEPTH) {
dq[diff+j] = dq[diff];
}
__syncthreads();
__threadfence_block();
// iterate over all bodies assigned to thread
for (k = threadIdx.x + blockIdx.x * blockDim.x; k < nbodiesd; k += blockDim.x * gridDim.x) {
i = sortd[k]; // get permuted/sorted index
// cache position info
px = posxd[i];
py = posyd[i];
vx = 0.0f;
vy = 0.0f;
normsum = 0.0f;
// initialize iteration stack, i.e., push root node onto stack
depth = j;
if (sbase == threadIdx.x) {
pos[j] = 0;
node[j] = nnodesd * 4;
}
do {
// stack is not empty
pd = pos[depth];
nd = node[depth];
while (pd < 4) {
// node on top of stack has more children to process
n = childd[nd + pd]; // load child pointer
pd++;
if (n >= 0) {
dx = px - posxd[n];
dy = py - posyd[n];
tmp = dx*dx + dy*dy + epssqd; // distance squared plus small constant to prevent zeros
#if (CUDART_VERSION >= 9000)
if ((n < nbodiesd) || __all_sync(__activemask(), tmp >= dq[depth])) { // check if all threads agree that cell is far enough away (or is a body)
#else
if ((n < nbodiesd) || __all(tmp >= dq[depth])) { // check if all threads agree that cell is far enough away (or is a body)
#endif
// from bhtsne - sptree.cpp
tmp = 1 / (1 + tmp);
mult = massd[n] * tmp;
normsum += mult;
mult *= tmp;
vx += dx * mult;
vy += dy * mult;
} else {
// push cell onto stack
if (sbase == threadIdx.x) { // maybe don't push and inc if last child
pos[depth] = pd;
node[depth] = nd;
}
depth++;
pd = 0;
nd = n * 4;
}
} else {
pd = 4; // early out because all remaining children are also zero
}
}
depth--; // done with this level
} while (depth >= j);
if (stepd >= 0) {
// update velocity
velxd[i] += vx;
velyd[i] += vy;
normd[i] = normsum - 1.0f; // subtract one for self computation (qii)
}
}
}
}
/******************************************************************************/
/*** advance bodies ***********************************************************/
/******************************************************************************/
// Edited to add momentum, repulsive, attr forces, etc.
__global__
__launch_bounds__(THREADS6, FACTOR6)
void IntegrationKernel(int N,
int nnodes,
float eta,
float norm,
float momentum,
float exaggeration,
volatile float * __restrict pts, // (nnodes + 1) x 2
volatile float * __restrict attr_forces, // (N x 2)
volatile float * __restrict rep_forces, // (nnodes + 1) x 2
volatile float * __restrict gains,
volatile float * __restrict old_forces) // (N x 2)
{
register int i, inc;
register float dx, dy, ux, uy, gx, gy;
// iterate over all bodies assigned to thread
inc = blockDim.x * gridDim.x;
for (i = threadIdx.x + blockIdx.x * blockDim.x; i < N; i += inc) {
ux = old_forces[i];
uy = old_forces[N + i];
gx = gains[i];
gy = gains[N + i];
dx = exaggeration*attr_forces[i] - (rep_forces[i] / norm);
dy = exaggeration*attr_forces[i + N] - (rep_forces[nnodes + 1 + i] / norm);
gx = (signbit(dx) != signbit(ux)) ? gx + 0.2 : gx * 0.8;
gy = (signbit(dy) != signbit(uy)) ? gy + 0.2 : gy * 0.8;
gx = (gx < 0.01) ? 0.01 : gx;
gy = (gy < 0.01) ? 0.01 : gy;
ux = momentum * ux - eta * gx * dx;
uy = momentum * uy - eta * gy * dy;
pts[i] += ux;
pts[i + nnodes + 1] += uy;
old_forces[i] = ux;
old_forces[N + i] = uy;
gains[i] = gx;
gains[N + i] = gy;
}
}
/******************************************************************************/
/*** compute attractive force *************************************************/
/******************************************************************************/
__global__
void csr2coo(int N, int nnz,
volatile int * __restrict pijRowPtr,
volatile int * __restrict pijColInd,
volatile int * __restrict indices)
{
register int TID, i, j, start, end;
TID = threadIdx.x + blockIdx.x * blockDim.x;
if (TID >= nnz) return;
start = 0; end = N + 1;
i = (N + 1) >> 1;
while (end - start > 1) {
j = pijRowPtr[i];
end = (j <= TID) ? end : i;
start = (j > TID) ? start : i;
i = (start + end) >> 1;
}
j = pijColInd[TID];
indices[2*TID] = i;
indices[2*TID+1] = j;
}
__global__
void ComputePijKernel(const unsigned int N,
const unsigned int K,
float * __restrict pij,
const float * __restrict sqdist,
const float * __restrict betas)
{
register int TID, i, j;
register float dist, beta;
TID = threadIdx.x + blockIdx.x * blockDim.x;
if (TID >= N * K) return;
i = TID / K;
j = TID % K;
beta = betas[i];
dist = sqdist[TID];
pij[TID] = (j == 0 && dist == 0.0f) ? 0.0f : __expf(-beta * dist); // condition deals with evaluation of pii
}
__global__
void ComputePijxQijKernel(int N, int nnz, int nnodes,
volatile int * indices,
volatile float * __restrict pij,
volatile float * __restrict forceProd,
volatile float * __restrict pts)
{
register int TID, i, j; //, inc;
register float ix, iy, jx, jy, dx, dy;
TID = threadIdx.x + blockIdx.x * blockDim.x;
// inc = blockDim.x * gridDim.x;
// for (TID = threadIdx.x + blockIdx.x * blockDim.x; TID < nnz; TID += inc) {
if (TID >= nnz) return;
i = indices[2*TID];
j = indices[2*TID+1];
ix = pts[i]; iy = pts[nnodes + 1 + i];
jx = pts[j]; jy = pts[nnodes + 1 + j];
dx = ix - jx;
dy = iy - jy;
forceProd[TID] = pij[TID] * 1 / (1 + dx*dx + dy*dy);
// }
}
__global__
void PerplexitySearchKernel(const unsigned int N,
const float perplexity_target,
const float eps,
float * __restrict betas,
float * __restrict lower_bound,
float * __restrict upper_bound,
int * __restrict found,
const float * __restrict neg_entropy,
const float * __restrict row_sum)
{
register int i, is_found;
register float perplexity, neg_ent, sum_P, pdiff, beta, min_beta, max_beta;
i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= N) return;
neg_ent = neg_entropy[i];
sum_P = row_sum[i];
beta = betas[i];
min_beta = lower_bound[i];
max_beta = upper_bound[i];
perplexity = (neg_ent / sum_P) + __logf(sum_P);
pdiff = perplexity - __logf(perplexity_target);
is_found = (pdiff < eps && - pdiff < eps);
if (!is_found) {
if (pdiff > 0) {
min_beta = beta;
beta = (max_beta == FLT_MAX || max_beta == -FLT_MAX) ? beta * 2.0f : (beta + max_beta) / 2.0f;
} else {
max_beta = beta;
beta = (min_beta == -FLT_MAX || min_beta == FLT_MAX) ? beta / 2.0f : (beta + min_beta) / 2.0f;
}
lower_bound[i] = min_beta;
upper_bound[i] = max_beta;
betas[i] = beta;
}
found[i] = is_found;
}
// computes unnormalized attractive forces
void computeAttrForce(int N,
int nnz,
int nnodes,
int attr_forces_grid_size,
int attr_forces_block_size,
cusparseHandle_t &handle,
cusparseMatDescr_t &descr,
thrust::device_vector<float> &sparsePij,
thrust::device_vector<int> &pijRowPtr, // (N + 1)-D vector, should be constant L
thrust::device_vector<int> &pijColInd, // NxL matrix (same shape as sparsePij)
thrust::device_vector<float> &forceProd, // NxL matrix
thrust::device_vector<float> &pts, // (nnodes + 1) x 2 matrix
thrust::device_vector<float> &forces, // N x 2 matrix
thrust::device_vector<float> &ones,
thrust::device_vector<int> &indices) // N x 2 matrix of ones
{
// Computes pij*qij for each i,j
ComputePijxQijKernel<<<attr_forces_grid_size,attr_forces_block_size>>>(N, nnz, nnodes,
thrust::raw_pointer_cast(indices.data()),
thrust::raw_pointer_cast(sparsePij.data()),
thrust::raw_pointer_cast(forceProd.data()),
thrust::raw_pointer_cast(pts.data()));
// ComputePijxQijKernel<<<blocks*FACTOR7,THREADS7>>>(N, nnz, nnodes,
// thrust::raw_pointer_cast(indices.data()),
// thrust::raw_pointer_cast(sparsePij.data()),
// thrust::raw_pointer_cast(forceProd.data()),
// thrust::raw_pointer_cast(pts.data()));
GpuErrorCheck(cudaDeviceSynchronize());
// compute forces_i = sum_j pij*qij*normalization*yi
float alpha = 1.0f;
float beta = 0.0f;
CusparseSafeCall(cusparseScsrmm(handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
N, 2, N, nnz, &alpha, descr,
thrust::raw_pointer_cast(forceProd.data()),
thrust::raw_pointer_cast(pijRowPtr.data()),
thrust::raw_pointer_cast(pijColInd.data()),
thrust::raw_pointer_cast(ones.data()),
N, &beta, thrust::raw_pointer_cast(forces.data()),
N));
GpuErrorCheck(cudaDeviceSynchronize());
thrust::transform(forces.begin(), forces.begin() + N, pts.begin(), forces.begin(), thrust::multiplies<float>());
thrust::transform(forces.begin() + N, forces.end(), pts.begin() + nnodes + 1, forces.begin() + N, thrust::multiplies<float>());
// compute forces_i = forces_i - sum_j pij*qij*normalization*yj
alpha = -1.0f;
beta = 1.0f;
CusparseSafeCall(cusparseScsrmm(handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
N, 2, N, nnz, &alpha, descr,
thrust::raw_pointer_cast(forceProd.data()),
thrust::raw_pointer_cast(pijRowPtr.data()),
thrust::raw_pointer_cast(pijColInd.data()),
thrust::raw_pointer_cast(pts.data()),
nnodes + 1, &beta, thrust::raw_pointer_cast(forces.data()),
N));
GpuErrorCheck(cudaDeviceSynchronize());
}
// TODO: Add -1 notification here... and how to deal with it if it happens
// TODO: Maybe think about getting FAISS to return integers (long-term todo)
__global__ void postprocess_matrix(float* matrix,
long* long_indices,
int* indices,
unsigned int N_POINTS,
unsigned int K)
{
register int TID = threadIdx.x + blockIdx.x * blockDim.x;
if (TID >= N_POINTS*K) return;
// Set pij to 0 for each of the broken values - Note: this should be handled in the ComputePijKernel now
// if (matrix[TID] == 1.0f) matrix[TID] = 0.0f;
indices[TID] = (int) long_indices[TID];
return;
}
thrust::device_vector<float> search_perplexity(cublasHandle_t &handle,
thrust::device_vector<float> &knn_distances,
const float perplexity_target,
const float eps,
const unsigned int N,
const unsigned int K)
{
// use beta instead of sigma (this matches the bhtsne code but not the paper)
// beta is just multiplicative instead of divisive (changes the way binary search works)
thrust::device_vector<float> betas(N, 1.0f);
thrust::device_vector<float> lbs(N, 0.0f);
thrust::device_vector<float> ubs(N, 1000.0f);
thrust::device_vector<float> pij(N*K);
thrust::device_vector<float> entropy(N*K);
thrust::device_vector<int> found(N);
const unsigned int BLOCKSIZE1 = 1024;
const unsigned int NBLOCKS1 = iDivUp(N * K, BLOCKSIZE1);
const unsigned int BLOCKSIZE2 = 128;
const unsigned int NBLOCKS2 = iDivUp(N, BLOCKSIZE2);
int iters = 0;
int all_found = 0;
thrust::device_vector<float> row_sum;
do {
// compute Gaussian Kernel row
ComputePijKernel<<<NBLOCKS1, BLOCKSIZE1>>>(N, K, thrust::raw_pointer_cast(pij.data()),
thrust::raw_pointer_cast(knn_distances.data()),
thrust::raw_pointer_cast(betas.data()));
GpuErrorCheck(cudaDeviceSynchronize());
// compute entropy of current row
row_sum = tsnecuda::util::ReduceSum(handle, pij, K, N, 0);
thrust::transform(pij.begin(), pij.end(), entropy.begin(), tsnecuda::util::FunctionalEntropy());
auto neg_entropy = tsnecuda::util::ReduceAlpha(handle, entropy, K, N, -1.0f, 0);
// binary search for beta
PerplexitySearchKernel<<<NBLOCKS2, BLOCKSIZE2>>>(N, perplexity_target, eps,
thrust::raw_pointer_cast(betas.data()),
thrust::raw_pointer_cast(lbs.data()),