-
Notifications
You must be signed in to change notification settings - Fork 2
/
perft_bb.h
1684 lines (1383 loc) · 63.1 KB
/
perft_bb.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
// functions for computing perft using bitboard board representation
// the routines that actually generate the moves
#include "MoveGeneratorBitboard.h"
#define MAX_GPUs 8
void *preAllocatedBufferHost[MAX_GPUs];
__device__ void *preAllocatedBuffer;
__device__ uint32 preAllocatedMemoryUsed;
// use parallel scan and interval expand algorithms (from modern gpu lib) for
// performing the move list scan and 'expand' operation to set correct board pointers (of parent boards) for second level child moves
// Another possible idea to avoid this operation is to have GenerateMoves() generate another array containing the indices
// of the parent boards that generated the move (i.e, the global thread index for generateMoves kernel)
// A scan will still be needed to figure out starting address to write, but we won't need the interval expand
#include "moderngpu-master/include/kernels/scan.cuh"
#include "moderngpu-master/include/kernels/intervalmove.cuh"
#if COUNT_NUM_COUNT_MOVES == 1
__device__ uint64 numCountMoves;
#endif
#if PRINT_HASH_STATS == 1
// stats for each depth
// numProbes - no. of times hash table was probed (looked up)
// numHits - no. of times we got what we wanted
// numWrites - no. of times an entry was written or updated in hash table
__device__ uint64 numProbes[MAX_GAME_LENGTH];
__device__ uint64 numHits[MAX_GAME_LENGTH];
__device__ uint64 numStores[MAX_GAME_LENGTH];
#endif
// helper routines for CPU perft
uint32 countMoves(HexaBitBoardPosition *pos)
{
uint32 nMoves;
int chance = pos->chance;
#if USE_TEMPLATE_CHANCE_OPT == 1
if (chance == BLACK)
{
nMoves = MoveGeneratorBitboard::countMoves<BLACK>(pos);
}
else
{
nMoves = MoveGeneratorBitboard::countMoves<WHITE>(pos);
}
#else
nMoves = MoveGeneratorBitboard::countMoves(pos, chance);
#endif
return nMoves;
}
uint32 generateBoards(HexaBitBoardPosition *pos, HexaBitBoardPosition *newPositions)
{
uint32 nMoves;
int chance = pos->chance;
#if USE_TEMPLATE_CHANCE_OPT == 1
if (chance == BLACK)
{
nMoves = MoveGeneratorBitboard::generateBoards<BLACK>(pos, newPositions);
}
else
{
nMoves = MoveGeneratorBitboard::generateBoards<WHITE>(pos, newPositions);
}
#else
nMoves = MoveGeneratorBitboard::generateBoards(pos, newPositions, chance);
#endif
return nMoves;
}
// A very simple CPU routine - only for estimating launch depth
// this version doesn't use incremental hash
uint64 perft_bb(HexaBitBoardPosition *pos, uint32 depth)
{
HexaBitBoardPosition newPositions[MAX_MOVES];
uint32 nMoves = 0;
if (depth == 1)
{
nMoves = countMoves(pos);
return nMoves;
}
nMoves = generateBoards(pos, newPositions);
uint64 count = 0;
for (uint32 i=0; i < nMoves; i++)
{
uint64 childPerft = perft_bb(&newPositions[i], depth - 1);
count += childPerft;
}
return count;
}
// fixed
#define WARP_SIZE 32
#define ALIGN_UP(addr, align) (((addr) + (align) - 1) & (~((align) - 1)))
#define MEM_ALIGNMENT 16
// set this to true if devicMalloc can be called from multiple threads
#define MULTI_THREADED_MALLOC 1
template<typename T>
__device__ __forceinline__ int deviceMalloc(T **ptr, uint32 size)
{
// align up the size to nearest 16 bytes (as some structures might have assumed 16 byte alignment?)
size = ALIGN_UP(size, MEM_ALIGNMENT);
#if MULTI_THREADED_MALLOC == 1
uint32 startOffset = atomicAdd(&preAllocatedMemoryUsed, size);
#else
uint32 startOffset = preAllocatedMemoryUsed;
preAllocatedMemoryUsed += size;
#endif
if (startOffset >= PREALLOCATED_MEMORY_SIZE)
{
//printf("\nFailed allocating %d bytes\n", size);
//return -1;
}
*ptr = (T*) ((uint8 *)preAllocatedBuffer + startOffset);
//printf("\nAllocated %d bytes at address: %X\n", size, *ptr);
return S_OK;
}
// makes the given move on the given position
__device__ __forceinline__ void makeMove(HexaBitBoardPosition *pos, CMove move, int chance)
{
uint64 unused;
#if USE_TEMPLATE_CHANCE_OPT == 1
if (chance == BLACK)
{
MoveGeneratorBitboard::makeMove<BLACK, false>(pos, unused, move);
}
else
{
MoveGeneratorBitboard::makeMove<WHITE, false>(pos, unused, move);
}
#else
MoveGeneratorBitboard::makeMove(pos, unused, move, chance, false);
#endif
}
// this one also updates the hash
CUDA_CALLABLE_MEMBER __forceinline__ HashKey128b makeMoveAndUpdateHash(HexaBitBoardPosition *pos, HashKey128b hash, CMove move, int chance)
{
#if USE_TEMPLATE_CHANCE_OPT == 1
if (chance == BLACK)
{
MoveGeneratorBitboard::makeMove<BLACK, true>(pos, hash, move);
}
else
{
MoveGeneratorBitboard::makeMove<WHITE, true>(pos, hash, move);
}
#else
MoveGeneratorBitboard::makeMove(pos, hash, move, chance, true);
#endif
return hash;
}
__host__ __device__ __forceinline__ uint32 countMoves(HexaBitBoardPosition *pos, uint8 color)
{
#if USE_TEMPLATE_CHANCE_OPT == 1
if (color == BLACK)
{
return MoveGeneratorBitboard::countMoves<BLACK>(pos);
}
else
{
return MoveGeneratorBitboard::countMoves<WHITE>(pos);
}
#else
return MoveGeneratorBitboard::countMoves(pos, color);
#endif
}
__host__ __device__ __forceinline__ uint32 generateBoards(HexaBitBoardPosition *pos, uint8 color, HexaBitBoardPosition *childBoards)
{
#if USE_TEMPLATE_CHANCE_OPT == 1
if (color == BLACK)
{
return MoveGeneratorBitboard::generateBoards<BLACK>(pos, childBoards);
}
else
{
return MoveGeneratorBitboard::generateBoards<WHITE>(pos, childBoards);
}
#else
return MoveGeneratorBitboard::generateBoards(pos, childBoards, color);
#endif
}
__host__ __device__ __forceinline__ uint32 generateMoves(HexaBitBoardPosition *pos, uint8 color, CMove *genMoves)
{
#if USE_TEMPLATE_CHANCE_OPT == 1
if (color == BLACK)
{
return MoveGeneratorBitboard::generateMoves<BLACK>(pos, genMoves);
}
else
{
return MoveGeneratorBitboard::generateMoves<WHITE>(pos, genMoves);
}
#else
return MoveGeneratorBitboard::generateMoves(pos, genMoves, color);
#endif
}
// shared memory scan for entire thread block
__device__ __forceinline__ void scan(uint32 *sharedArray)
{
uint32 diff = 1;
while(diff < blockDim.x)
{
uint32 val1, val2;
if (threadIdx.x >= diff)
{
val1 = sharedArray[threadIdx.x];
val2 = sharedArray[threadIdx.x - diff];
}
__syncthreads();
if (threadIdx.x >= diff)
{
sharedArray[threadIdx.x] = val1 + val2;
}
diff *= 2;
__syncthreads();
}
}
// fast reduction for the warp
__device__ __forceinline__ void warpReduce(int &x)
{
#pragma unroll
for(int mask = 16; mask > 0 ; mask >>= 1)
x += __shfl_xor(x, mask);
}
// fast scan for the warp
__device__ __forceinline__ void warpScan(int &x, int landId)
{
#pragma unroll
for( int offset = 1 ; offset < WARP_SIZE ; offset <<= 1 )
{
float y = __shfl_up(x, offset);
if(landId >= offset)
x += y;
}
}
#define MAX_PERFT_DEPTH 16
struct TTInfo128b
{
// gpu pointers to the hash tables
void *hashTable[MAX_PERFT_DEPTH];
// cpu pointers to the hash tables
void *cpuTable[MAX_PERFT_DEPTH];
// mask of index and hash bits for each transposition table
uint64 indexBits[MAX_PERFT_DEPTH];
uint64 hashBits[MAX_PERFT_DEPTH];
bool shallowHash[MAX_PERFT_DEPTH];
};
union sharedMemAllocs
{
struct
{
// scratch space of 1 element per thread used to perform thread-block wide operations
// (mostly scans)
uint32 movesForThread[BLOCK_SIZE];
// pointers to various arrays allocated in device memory
HexaBitBoardPosition *currentLevelBoards; // [BLOCK_SIZE]
uint32 *perft4Counters; // [BLOCK_SIZE], only used by depth4 kernel
union
{
uint64 *perftCounters; // [BLOCK_SIZE], only used by the main kernel
uint32 *perft3Counters; // [BLOCK_SIZE] when used by the depth3 kernel
// and [numFirstLevelMoves] when used by depth4 kernel
};
uint64 *currentLevelHashes; // [BLOCK_SIZE]
// first level move counts isn't stored anywhere (it's in register 'nMoves')
// numFirstLevelMoves isn't stored in shared memory
CMove *allFirstLevelChildMoves; // [numFirstLevelMoves]
HexaBitBoardPosition *allFirstLevelChildBoards; // [numFirstLevelMoves]
uint32 *allSecondLevelMoveCounts; // [numFirstLevelMoves]
uint64 **counterPointers; // [numFirstLevelMoves] (only used by main kernel)
uint64 *firstLevelHashes; // [numFirstLevelMoves]
int *firstToCurrentLevelIndices;// [numFirstLevelMoves] used instead of boardpointers in the new depth3 hash kernel
uint32 *perft2Counters; // [numFirstLevelMoves] when used in the depth3 hash kernel
// and [numSecondLevelMoves] when used by depth4 hash kernel
uint32 numAllSecondLevelMoves;
CMove *allSecondLevelChildMoves; // [numAllSecondLevelMoves]
HexaBitBoardPosition **boardPointers; // [numAllSecondLevelMoves] (second time)
int *secondToFirstLevelIndices; // [numAllSecondLevelMoves] used instead of boardpointers in the new depth3 hash kernel
};
};
#if LIMIT_REGISTER_USE == 1
__launch_bounds__( BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void perft_bb_gpu_single_level(HexaBitBoardPosition **positions, CMove *moves, uint64 *globalPerftCounter, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
HexaBitBoardPosition pos;
CMove move;
uint8 color;
// 1. first just count the moves (and store it in shared memory for each thread in block)
int nMoves = 0;
if (index < nThreads)
{
pos = *(positions[index]);
move = moves[index];
color = pos.chance;
makeMove(&pos, move, color);
color = !color;
nMoves = countMoves(&pos, color);
}
// on Kepler, atomics are so fast that one atomic instruction per leaf node is also fast enough (faster than full reduction)!
// warp-wide reduction seems a little bit faster
warpReduce(nMoves);
int laneId = threadIdx.x & 0x1f;
if (laneId == 0)
{
atomicAdd (globalPerftCounter, nMoves);
}
return;
}
// this version gets a list of moves, and a list of pointers to BitBoards
// first it makes the move to get the new board and then counts the moves possible on the board
// positions - array of pointers to old boards
// generatedMoves - moves to be made
#if LIMIT_REGISTER_USE == 1
__launch_bounds__( BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void makeMove_and_perft_single_level(HexaBitBoardPosition **positions, CMove *generatedMoves, uint64 *globalPerftCounter, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index >= nThreads)
return;
HexaBitBoardPosition *posPointer = positions[index];
HexaBitBoardPosition pos = *posPointer;
int color = pos.chance;
CMove move = generatedMoves[index];
makeMove(&pos, move, color);
// 2. count moves at this position
int nMoves = 0;
nMoves = countMoves(&pos, !color);
// 3. add the count to global counter
// on Kepler, atomics are so fast that one atomic instruction per leaf node is also fast enough (faster than full reduction)!
// warp-wide reduction seems a little bit faster
warpReduce(nMoves);
int laneId = threadIdx.x & 0x1f;
if (laneId == 0)
{
atomicAdd (globalPerftCounter, nMoves);
}
}
// same as above function but works with indices
#if LIMIT_REGISTER_USE == 1
__launch_bounds__(BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void makeMove_and_perft_single_level_indices(HexaBitBoardPosition *positions, int *indices, CMove *moves, uint64 *globalPerftCounter, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index >= nThreads)
return;
uint32 boardIndex = indices[index];
HexaBitBoardPosition pos = positions[boardIndex];
int color = pos.chance;
CMove move = moves[index];
makeMove(&pos, move, color);
// 2. count moves at this position
int nMoves = 0;
nMoves = countMoves(&pos, !color);
// 3. add the count to global counter
// on Kepler, atomics are so fast that one atomic instruction per leaf node is also fast enough (faster than full reduction)!
// warp-wide reduction seems a little bit faster
warpReduce(nMoves);
int laneId = threadIdx.x & 0x1f;
if (laneId == 0)
{
atomicAdd(globalPerftCounter, nMoves);
}
}
// this version gets seperate perft counter per thread
// perftCounters[] is array of pointers to perft counters - where each thread should atomically add the computed perft
#if LIMIT_REGISTER_USE == 1
__launch_bounds__( BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void makeMove_and_perft_single_level(HexaBitBoardPosition **positions, CMove *generatedMoves, uint64 **perftCounters, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index >= nThreads)
return;
HexaBitBoardPosition *posPointer = positions[index];
HexaBitBoardPosition pos = *posPointer;
int color = pos.chance;
CMove move = generatedMoves[index];
makeMove(&pos, move, color);
// 2. count moves at this position
int nMoves = 0;
nMoves = countMoves(&pos, !color);
// 3. add the count to global counter
uint64 *perftCounter = perftCounters[index];
// basically check if all threads in the warp are going to atomic add to the same counter,
// and if so perform warpReduce and do a single atomic add
// last 32 bits of counter pointer
#if 1
int counterIndex = (int) (((uint64) perftCounter) & 0xFFFFFFFF);
int firstLaneCounter = __shfl(counterIndex, 0);
if (__all(firstLaneCounter == counterIndex))
{
warpReduce(nMoves);
int laneId = threadIdx.x & 0x1f;
if (laneId == 0)
{
atomicAdd (perftCounter, nMoves);
}
}
else
#endif
{
atomicAdd (perftCounter, nMoves);
}
}
// this version uses the indices[] array to index into parentPositions[] and parentCounters[] arrays
#if LIMIT_REGISTER_USE == 1
__launch_bounds__( BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void makeMove_and_perft_single_level_indices(HexaBitBoardPosition *parentBoards, uint32 *parentCounters,
int *indices, CMove *moves, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index >= nThreads)
return;
int parentIndex = indices[index];
HexaBitBoardPosition pos = parentBoards[parentIndex];
int color = pos.chance;
CMove move = moves[index];
makeMove(&pos, move, color);
// 2. count moves at this position
int nMoves = 0;
nMoves = countMoves(&pos, !color);
// 3. add the count to global counter
uint32 *perftCounter = parentCounters + parentIndex;
// basically check if all threads in the warp are going to atomic add to the same counter,
// and if so perform warpReduce and do a single atomic add
int firstLaneIndex = __shfl(parentIndex, 0);
if (__all(firstLaneIndex == parentIndex))
{
warpReduce(nMoves);
int laneId = threadIdx.x & 0x1f;
if (laneId == 0)
{
atomicAdd (perftCounter, nMoves);
}
}
else
{
atomicAdd (perftCounter, nMoves);
}
}
// moveCounts are per each thread
// this function first reads input position from *positions[] - which is an array of pointers
// then it makes the given move (moves[] array)
// puts the updated board in outPositions[] array
// and finally counts the no. of moves possible for each element in outPositions.
// the move counts are returned in moveCounts[] array
template <bool genBoard>
#if LIMIT_REGISTER_USE == 1
__launch_bounds__( BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void makemove_and_count_moves_single_level(HexaBitBoardPosition **positions, CMove *moves, HexaBitBoardPosition *outPositions, uint32 *moveCounts, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
HexaBitBoardPosition pos;
CMove move;
uint8 color;
// just count the no. of moves for each board and save it in moveCounts array
int nMoves = 0;
if (index < nThreads)
{
pos = *(positions[index]);
move = moves[index];
color = pos.chance;
makeMove(&pos, move, color);
color = !color;
if (genBoard)
outPositions[index] = pos;
nMoves = countMoves(&pos, color);
moveCounts[index] = nMoves;
}
}
// this kernel does several things
// 1. Figures out the parent board position using indices[] array to lookup in parentBoards[] array
// 2. makes the move on parent board to produce current board. Writes it to outPositions[].
// 3. Counts moves at current board position and writes it to moveCounts[].
#if LIMIT_REGISTER_USE == 1
__launch_bounds__(BLOCK_SIZE, MIN_BLOCKS_PER_MP)
#endif
__global__ void makemove_and_count_moves_single_level(HexaBitBoardPosition *parentBoards, int *indices, CMove *moves,
HexaBitBoardPosition *outPositions, int *moveCounts, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
// count the no. of moves for each board and save it in moveCounts array
int nMoves = 0;
if (index < nThreads)
{
int parentIndex = indices[index];
HexaBitBoardPosition pos = parentBoards[parentIndex];
CMove move = moves[index];
//Utils::displayCompactMove(move);
uint8 color = pos.chance;
makeMove(&pos, move, color);
nMoves = countMoves(&pos, !color);
outPositions[index] = pos;
moveCounts[index] = nMoves;
}
}
#if 0
// serial recursive perft routine for testing
__device__ __host__ uint32 serial_perft_test(HexaBitBoardPosition *pos, int depth)
{
uint8 color = pos->chance;
uint32 nMoves = countMoves(pos, color);
if (depth == 1)
return nMoves;
HexaBitBoardPosition *childPositions;
#ifdef __CUDA_ARCH__
deviceMalloc(&childPositions, sizeof(HexaBitBoardPosition) * nMoves);
#else
childPositions = (HexaBitBoardPosition*) malloc(sizeof(HexaBitBoardPosition)* nMoves);
#endif
generateBoards(pos, color, childPositions);
uint32 p = 0;
for (int i = 0; i < nMoves; i++)
{
p += serial_perft_test(&(childPositions[i]), depth - 1);
}
return p;
}
#endif
// this kernel does several things
// 1. Figures out the parent board position using indices[] array to lookup in parentBoards[] array
// 2. makes the move on parent board to produce current board. Writes it to outPositions[], also updates outHashes with new hash
// 3. looks up the transposition table to see if the current board is present, and if so, updates the perftCounter directly
// 4. which perft counter to update and the hash of parent board is also found by
// indexing using indices[] array into parentHashes[]/parentCounters[] arrays
// 5. clears the perftCountersCurrentDepth[] array passed in
// this should be called for 'shallow' depths - i.e, the ones where each TT entry is just 128 bytes (and perft value fits in 24 bits)
// use the next function for deeper depths (that need > 32 bit perft values)
template <typename PT, typename CT>
__global__ void makemove_and_count_moves_single_level_hash128b(HexaBitBoardPosition *parentBoards, HashKey128b *parentHashes,
PT *parentCounters, int *indices, CMove *moves,
HashKey128b *hashTable, uint64 hashBits, uint64 indexBits,
HexaBitBoardPosition *outPositions, HashKey128b *outHashes,
int *moveCounts, CT *perftCountersCurrentDepth,
int nThreads, int depth)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
// count the no. of moves for each board and save it in moveCounts array
int nMoves = 0;
if (index < nThreads)
{
int parentIndex = indices[index];
HexaBitBoardPosition pos = parentBoards[parentIndex];
HashKey128b hash = parentHashes[parentIndex];
PT *perftCounter = parentCounters + parentIndex;
CMove move = moves[index];
uint8 color = pos.chance;
hash = makeMoveAndUpdateHash(&pos, hash, move, color);
#if PRINT_HASH_STATS == 1
atomicAdd(&numProbes[depth], 1);
#endif
// check in transposition table
HashKey128b entry = hashTable[hash.lowPart & indexBits];
entry.highPart = entry.highPart ^ entry.lowPart;
if ((entry.highPart == hash.highPart) && ((entry.lowPart & hashBits) == (hash.lowPart & hashBits)))
{
uint32 perftFromHash = (entry.lowPart & indexBits);
#if 0
// for testing
if (serial_perft_test(&pos, depth) != perftFromHash)
{
printf("\nwrong perft found in hash!!!\n");
perftFromHash = serial_perft_test(&pos, depth);
}
#endif
// hash hit
#if PRINT_HASH_STATS == 1
atomicAdd(&numHits[depth], 1);
#endif
atomicAdd(perftCounter, perftFromHash);
// mark it invalid so that no further work gets done on this board
pos.whitePieces = 0; // mark it invalid so that generatemoves doesn't generate moves
hash.highPart = 0; // mark it invalid so that PerftNFromNminus1 kernel ignores this
}
else
{
nMoves = countMoves(&pos, !color);
}
outPositions[index] = pos;
outHashes[index] = hash;
moveCounts[index] = nMoves;
perftCountersCurrentDepth[index] = 0;
}
}
// same as above function - but using deep hash tables
__global__ void makemove_and_count_moves_single_level_hash128b_deep(HexaBitBoardPosition *parentBoards, HashKey128b *parentHashes,
uint64 *parentCounters, int *indices, CMove *moves,
HashEntryPerft128b *hashTable, uint64 hashBits, uint64 indexBits,
HexaBitBoardPosition *outPositions, HashKey128b *outHashes,
int *moveCounts, uint64 *perftCountersCurrentDepth,
int nThreads, int depth)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
// count the no. of moves for each board and save it in moveCounts array
int nMoves = 0;
if (index < nThreads)
{
int parentIndex = indices[index];
HexaBitBoardPosition pos = parentBoards[parentIndex];
HashKey128b hash = parentHashes[parentIndex];
uint64 *perftCounter = parentCounters + parentIndex;
CMove move = moves[index];
uint8 color = pos.chance;
hash = makeMoveAndUpdateHash(&pos, hash, move, color);
#if PRINT_HASH_STATS == 1
atomicAdd(&numProbes[depth], 1);
#endif
// check in transposition table
HashEntryPerft128b entry = hashTable[hash.lowPart & indexBits];
// extract data from the entry using XORs (hash part is stored XOR'ed with data for lockless hashing scheme)
entry.hashKey.highPart ^= entry.perftVal;
entry.hashKey.lowPart ^= entry.perftVal;
if ((entry.hashKey.highPart == hash.highPart) && ((entry.hashKey.lowPart & hashBits) == (hash.lowPart & hashBits))
&& (entry.depth == depth))
{
// hash hit
#if PRINT_HASH_STATS == 1
atomicAdd(&numHits[depth], 1);
#endif
atomicAdd(perftCounter, entry.perftVal);
// mark it invalid so that no further work gets done on this board
pos.whitePieces = 0; // mark it invalid so that generatemoves doesn't generate moves
hash.highPart = 0; // mark it invalid so that perftNFromPerftNminus1 kernel doesn't process this
}
else
{
nMoves = countMoves(&pos, !color);
}
outPositions[index] = pos;
outHashes[index] = hash;
moveCounts[index] = nMoves;
perftCountersCurrentDepth[index] = 0;
}
}
#if FIND_DUPLICATES_IN_BFS == 1
// write current board's index (in current level of BFS) to the hash table location so that we can figure out the duplicate entries
__global__ void writeIndexInHashForDuplicates(HashKey128b *hashTable, uint64 hashBits, uint64 indexBits,
HashKey128b *hashes, int nThreads)
{
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < nThreads && index <= indexBits)
{
HashKey128b hash = hashes[index];
if (hash.highPart)
{
// write 'index' in the hash table
// this is to track duplicates, the hash entry will be overwritten later (once the actual perft value is known)
HashKey128b curEntry = hash;
curEntry.lowPart = (curEntry.lowPart & hashBits) | (index & indexBits);
hashTable[hash.lowPart & indexBits] = curEntry;
}
}
}
template <typename CT>
__global__ void checkandMarkDuplicates(HashKey128b *hashTable, uint64 hashBits, uint64 indexBits,
HashKey128b *hashes, HexaBitBoardPosition *positions,
CT *perftCountersCurrentDepth, int *moveCounts, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < nThreads && index < indexBits)
{
HashKey128b hash = hashes[index];
if (hash.highPart)
{
HashKey128b entry = hashTable[hash.lowPart & indexBits];
if ((entry.highPart == hash.highPart) && ((entry.lowPart & hashBits) == (hash.lowPart & hashBits)))
{
uint32 indexInHash = (entry.lowPart & indexBits);
if (indexInHash != index)
{
// duplicate entry!
moveCounts[index] = 0; // mark it invalid so that it doesn't get expanded
positions[index].whitePieces = 0; // mark it invalid so that generatemoves doesn't generate moves
hashes[index].highPart = ~0ull; // mark so that PerftNFromNminus1 kernel treats this in special way
perftCountersCurrentDepth[index] = indexInHash; // pick perft value from this index
}
}
else
{
// hard luck!
// multiple positions in the same level mapping to same hash table entry
}
}
}
}
#endif
// For shallow depths only!
//
// compute perft N from perft N-1 (using excessive atomic adds)
// also store perft (N-1) entry in the given hash table (hashes[] array is for positions at N-1 level)
// 'depth' is the value of (n-1)
template <typename PT>
__global__ void calcPerftNFromPerftNminus1_hash128b(PT *perftNCounters, int *indices,
uint32 *perftNminus1Counters, HashKey128b *hashes, HexaBitBoardPosition *boards,
HashKey128b *hashTable, uint64 hashBits, uint64 indexBits,
int nThreads, int depth)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < nThreads)
{
HashKey128b hash = hashes[index];
if (hash.highPart) // hash == 0 means invalid entry - entry for which there was a hash hit
{
PT *perftNCounter = perftNCounters + indices[index];
uint32 perftNminus1 = perftNminus1Counters[index];
#if FIND_DUPLICATES_IN_BFS == 1
if (hash.highPart == ~0ull)
{
// this was a duplicate position and the value stored is actually pointer to the original index
perftNminus1 = perftNminus1Counters[perftNminus1];
atomicAdd(perftNCounter, perftNminus1);
}
else
#endif
{
// get perft(N) from perft(N-1)
// TODO: try replacing this atomic add with some parallel reduction trick (warp wide?)
atomicAdd(perftNCounter, perftNminus1);
//if (perftNminus1 > indexBits)
// printf("\nGot perft bigger than size in hash table\n");
// store in hash table
// it's assumed that perft value will fit in remaining (~hashMask) bits
HashKey128b hashEntry = HashKey128b((hash.lowPart & hashBits) | perftNminus1, hash.highPart);
hashEntry.highPart ^= hashEntry.lowPart;
hashTable[hash.lowPart & indexBits] = hashEntry;
#if PRINT_HASH_STATS == 1
atomicAdd(&numStores[depth], 1);
#endif
}
}
}
}
// same as above kernel but for levels that need deep hash tables
__global__ void calcPerftNFromPerftNminus1_hash128b_deep(uint64 *perftNCounters, int *indices,
uint64 *perftNminus1Counters, HashKey128b *hashes,
HashEntryPerft128b *hashTable, uint64 hashBits, uint64 indexBits,
int nThreads, int depth)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < nThreads)
{
HashKey128b hash = hashes[index];
if (hash.highPart) // hash == 0 means invalid entry - entry for which there was a hash hit
{
uint64 *perftNCounter = perftNCounters + indices[index];
uint64 perftNminus1 = perftNminus1Counters[index];
#if FIND_DUPLICATES_IN_BFS == 1
if (hash.highPart == ~0ull)
{
// this was a duplicate position and the value stored is actually pointer to the original index
perftNminus1 = perftNminus1Counters[perftNminus1];
atomicAdd(perftNCounter, perftNminus1);
}
else
#endif
{
// get perft(N) from perft(N-1)
// TODO: try replacing this atomic add with some parallel reduction trick (warp wide?)
atomicAdd(perftNCounter, perftNminus1);
// store in hash table
HashEntryPerft128b oldEntry = hashTable[hash.lowPart & indexBits];
// extract data from the entry using XORs (hash part is stored XOR'ed with data for lockless hashing scheme)
oldEntry.hashKey.highPart ^= oldEntry.perftVal;
oldEntry.hashKey.lowPart ^= oldEntry.perftVal;
// replace only if old entry was shallower (or of same depth)
if (oldEntry.depth <= depth)
{
HashEntryPerft128b newEntry;
newEntry.perftVal = perftNminus1;
newEntry.hashKey.highPart = hash.highPart;
newEntry.hashKey.lowPart = (hash.lowPart & hashBits);
newEntry.depth = depth;
// XOR hash part with data part for lockless hashing
newEntry.hashKey.lowPart ^= newEntry.perftVal;
newEntry.hashKey.highPart ^= newEntry.perftVal;
hashTable[hash.lowPart & indexBits] = newEntry;
#if PRINT_HASH_STATS == 1
atomicAdd(&numStores[depth], 1);
#endif
}
}
}
}
}
// childPositions is array of pointers
__global__ void generate_boards_single_level(HexaBitBoardPosition *positions, HexaBitBoardPosition **childPositions, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
HexaBitBoardPosition pos = positions[index];
HexaBitBoardPosition *childBoards = childPositions[index];
uint8 color = pos.chance;
if (index < nThreads)
{
generateBoards(&pos, color, childBoards);
}
}
// positions[] array contains positions on which move have to be generated.
// generatedMovesBase contains the starting address of the memory allocated for storing the generated moves
// moveListIndex points to the start index in the above memory for storing generated moves for current board position
__global__ void generate_moves_single_level(HexaBitBoardPosition *positions, CMove *generatedMovesBase, int *moveListIndex, int nThreads)
{
// exctact one element of work
uint32 index = blockIdx.x * blockDim.x + threadIdx.x;
HexaBitBoardPosition pos = positions[index];
CMove *genMoves = generatedMovesBase + moveListIndex[index];
uint8 color = pos.chance;
if (index < nThreads && pos.whitePieces) // pos.whitePieces == 0 indicates an invalid board (hash hit)
{
generateMoves(&pos, color, genMoves);
}
}
#if 0
// makes the given moves on the given board positions