-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlauncher.h
1723 lines (1426 loc) · 53.4 KB
/
launcher.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
// launcher utils
// read set of positions and occurence counts from a file, compute perfts and sum them up
#define PERFT_RECORDS_MODE 0
// the set of positions are in a text file (with FEN and occurence counts)
// default is binary file
#define PERFT_RECORD_TEXT_MODE 0
// can't make this bigger than 6/7, as the _simple kernel (breadth first search) gets called directly
// breadth first search uses lot of memory and can can't hold bigger tree
#define GPU_LAUNCH_DEPTH 6
// launch all boards at last level in a single kernel launch
// enable this with GPU_LAUNCH_DEPTH 6
// - allows better use of CPU side hash, but maybe slightly less GPU utilization
#define SINGLE_LAUNCH_FOR_LAST_LEVEL 1
// print divided perft values (subtotals) after reaching this depth
#define DIVIDED_PERFT_DEPTH 10
// use multiple CPU threads to split the tree at greater depth
#define PARALLEL_THREAD_GPU_SPLIT 1
// depth at which work is split among multiple GPUs
#define MIN_SPLIT_DEPTH 9
// launch one level of work serially on GPU
#define ENABLE_GPU_SERIAL_LEVEL 0
// use a hash table to store *all* positions at depth 7/8, etc
#define USE_COMPLETE_TT_AT_LAST_CPU_LEVEL 1
// store a level (depth-4) of positions in a persistent disk hash
// useful for save/restore of work AND also
// for parallel perft over network with multiple nodes
#define ENABLE_DISK_HASH 1
// min problem size to make use of DISK_HASH
#define DISK_HASH_MIN_DEPTH 11
#define DISK_HASH_LEVEL 2
#if ENABLE_DISK_HASH == 1
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
// ~4096 entries for the main hash table part
#define DISK_TT_BITS 12
#endif
// use complete hash for all levels
#define USE_COMPLETE_HASH_ALL_LEVELS 1
// the perf calculation is running over a network with multiple systems (nodes)
// each node broadcasts work computed by itself to all other nodes to avoid duplication
// the work items recieved from other nodes are added to current node's complete TT
// a new node can also request the *entire* completeTT to be sent from one of the existing nodes
#define MULTI_NODE_NETWORK_MODE 1
uint64 numItemsFromPeers = 0;
#define MEASURE_GPU_ACTIVE_TIME 1
// size of transposition tables for each depth
// depth1 transposition table has special purpose -> to find duplicates for 'deep' levels during BFS
// 20 bits -> 1 million entries (16 MB)
// 25 bits -> 32 million entries (512 MB)
// 26 bits -> 64 million ... (1 GB)
// 27 bits -> 128 million ... (2 GB)
// 28 bits -> 256 million ... (4 GB)
// depth-> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
const bool shallow[] = {true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false};
#if 1
// settings for P100 (16 GB card) + 32 GB+ sysmem
const uint32 ttBits[] = {0, 24, 25, 27, 28, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const bool sysmem[] = {true, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true};
const int sharedHashBits = 25;
// 1 billion entries for the main hash table part
#define COMPLETE_TT_BITS 30
//#define COMPLETE_TT_BITS 27
// 128 million entries (for each chunk of chained part)
#define COMPLETE_HASH_CHAIN_ALLOC_SIZE 128*1024*1024
#elif 0
// settings for 8 GB card (GTX 1080) + just 4 GB sysmem
const uint32 ttBits[] = { 0, 23, 25, 26, 26, 26, 26, 27, 26, 0, 0, 0, 0, 0, 0, 0 };
const bool sysmem[] = { true, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true };
const int sharedHashBits = 26;
// 16 million entries for the main hash table part
#define COMPLETE_TT_BITS 24
// 128 million entries (for chained part)
#define COMPLETE_HASH_CHAIN_ALLOC_SIZE 128*1024*1024
#elif 0
// settings for home PC (GTX 970: 4 GB card + 8 GB sysmem)
const uint32 ttBits[] = {0, 20, 25, 26, 26, 25, 26, 25, 25, 0, 0, 0, 0, 0, 0, 0};
const bool sysmem[] = {true, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true};
const int sharedHashBits = 25;
// 16 million entries for the main hash table part
#define COMPLETE_TT_BITS 24
// 128 million entries (for chained part)
#define COMPLETE_HASH_CHAIN_ALLOC_SIZE 128*1024*1024
#else
// settings for laptop (2 GB card + 16 GB sysmem)
const uint32 ttBits[] = {0, 22, 25, 27, 27, 26, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const bool sysmem[] = {true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true};
const int sharedHashBits = 20;
// 16 million entries for the main hash table part
#define COMPLETE_TT_BITS 24
// 128 million entries (for chained part)
#define COMPLETE_HASH_CHAIN_ALLOC_SIZE 128*1024*1024
#endif
const bool sharedsysmem = true;
#define COMPLETE_TT_INDEX_BITS GET_TT_INDEX_BITS(COMPLETE_TT_BITS)
// launcher routines
double gpuTime = 0.0;
std::mutex timerCS;
CompleteHashEntry *completeTT = NULL;
CompleteHashEntry *chainMemory = NULL;
volatile uint64 chainIndex = 0;
volatile uint64 completeTTSize = 0;
volatile uint64 chainMemorySize = 0;
int numGPUs = 0;
#if USE_TRANSPOSITION_TABLE == 1
// TODO: avoid these global vars?
TTInfo128b TransTables128b[MAX_GPUs];
HexaBitBoardPosition *gpuBoard[MAX_GPUs];
uint64 *gpu_perft[MAX_GPUs];
HashKey128b *gpuHashes[MAX_GPUs];
// to avoid allocating sysmem tables multiple times!
// HACKY! - TODO: get rid of this and have the function allocate memory for all GPUs itself
bool sysmemTablesAllocated = false;
void allocAndClearMem(void **devPointer, void **hostPointer, size_t size, bool sysmem, int depth)
{
#if USE_COMPLETE_TT_AT_LAST_CPU_LEVEL == 1
if (depth == GPU_LAUNCH_DEPTH)
{
// no need of this level's hash table
*devPointer = NULL;
*hostPointer = NULL;
return;
}
#endif
// still need these hash tables for smaller perfts that go to GPU directly!
#if 0 //USE_COMPLETE_HASH_ALL_LEVELS == 1
// no need of any regular hash tables on CPU side
if (depth < GPU_LAUNCH_DEPTH)
{
// no need of this level's hash table
*devPointer = NULL;
*hostPointer = NULL;
return;
}
#endif
cudaError_t res;
void *temp = NULL;
*devPointer = NULL;
if (sysmem)
{
if (depth >= GPU_LAUNCH_DEPTH)
{
if (sysmemTablesAllocated)
{
temp = TransTables128b[0].cpuTable[depth];
}
else
{
// plain system memory
temp = malloc(size);
if (!temp)
{
printf("\nFailed allocating pure sysmem for transposition table!\n");
exit(0);
}
}
}
else
{
// try allocating in system memory
if (sysmemTablesAllocated)
{
temp = TransTables128b[0].cpuTable[depth];
*devPointer = TransTables128b[0].hashTable[depth];
}
else
{
res = cudaHostAlloc(&temp, size, cudaHostAllocMapped | /*cudaHostAllocWriteCombined |*/ cudaHostAllocPortable);
if (res != cudaSuccess)
{
printf("\nFailed to allocate sysmem transposition table for depth %d of %llu bytes, with error: %s\n", depth, size, cudaGetErrorString(res));
exit(0);
}
res = cudaHostGetDevicePointer(devPointer, temp, 0);
if (res != S_OK)
{
printf("\nFailed to get GPU mapping for sysmem hash table, with error: %s\n", cudaGetErrorString(res));
exit(0);
}
}
}
}
else
{
res = cudaMalloc(devPointer, size);
if (res != cudaSuccess)
{
printf("\nFailed to allocate GPU transposition table of %llu bytes, with error: %s\n", size, cudaGetErrorString(res));
exit(0);
}
}
*hostPointer = temp;
if (devPointer)
{
hugeMemset(devPointer, size);
}
else
{
assert(*hostPointer);
memset(*hostPointer, 0, size);
}
}
CompleteHashEntry *chainMemoryChunks[1024];
volatile int nChunks = 0;
void allocChainMemoryChunk()
{
chainMemorySize = COMPLETE_HASH_CHAIN_ALLOC_SIZE * sizeof(CompleteHashEntry);
chainMemory = (CompleteHashEntry *)malloc(chainMemorySize);
if (!chainMemory)
{
printf("\nFailed allocating chainMemory chunk %d!\n", nChunks);
exit(0);
}
memset(chainMemory, 0, chainMemorySize);
chainMemoryChunks[nChunks++] = chainMemory;
chainIndex = 0;
}
void allocCompleteTT()
{
#if USE_COMPLETE_TT_AT_LAST_CPU_LEVEL == 1
if (completeTT == NULL)
{
completeTTSize = GET_TT_SIZE_FROM_BITS(COMPLETE_TT_BITS) * sizeof(CompleteHashEntry);
completeTT = (CompleteHashEntry *)malloc(completeTTSize);
if (!completeTT)
{
printf("\nFailed allocating completeTT!\n");
exit(0);
}
memset(completeTT, 0, completeTTSize);
memset(chainMemoryChunks, 0, sizeof(chainMemoryChunks));
allocChainMemoryChunk();
}
#endif
}
void freeCompleteTT()
{
if (completeTT)
free(completeTT);
for (int i=0;i<nChunks;i++)
free(chainMemoryChunks[i]);
}
void setupHashTables128b(TTInfo128b &tt)
{
// allocate the shared hash table
void *sharedTable, *sharedTableCPU;
allocAndClearMem(&sharedTable, &sharedTableCPU, GET_TT_SIZE_FROM_BITS(sharedHashBits) * sizeof(HashEntryPerft128b), sharedsysmem, 9);
memset(&tt, 0, sizeof(tt));
for (int i = 1; i < MAX_PERFT_DEPTH; i++)
{
tt.shallowHash[i] = shallow[i];
uint32 bits = ttBits[i];
if (bits)
{
allocAndClearMem(&tt.hashTable[i], &tt.cpuTable[i],
GET_TT_SIZE_FROM_BITS(bits) * (shallow[i] ? sizeof(HashKey128b) : sizeof(HashEntryPerft128b)), sysmem[i], i);
}
else
{
tt.hashTable[i] = sharedTable;
tt.cpuTable[i] = sharedTableCPU;
bits = sharedHashBits;
}
tt.indexBits[i] = GET_TT_INDEX_BITS(bits);
tt.hashBits[i] = GET_TT_HASH_BITS(bits);
}
sysmemTablesAllocated = true;
}
void freeHashTables()
{
bool sharedDeleted = false;
for (int g = 0; g < numGPUs; g++)
{
cudaSetDevice(g);
for (int i = 1; i < MAX_PERFT_DEPTH; i++)
{
uint32 bits = ttBits[i];
if (bits == 0)
{
if (!sharedDeleted)
{
// delete the shared sysmem hash table
free(TransTables128b[g].cpuTable[i]);
sharedDeleted = true;
}
}
else if(sysmem[i])
{
if (g == 0)
{
if (i >= GPU_LAUNCH_DEPTH)
{
if (TransTables128b[g].cpuTable[i])
free(TransTables128b[g].cpuTable[i]);
}
else
{
cudaFree(TransTables128b[g].hashTable[i]);
}
}
}
else
{
cudaFree(TransTables128b[g].hashTable[i]);
}
}
}
cudaSetDevice(0);
memset(TransTables128b, 0, sizeof(TransTables128b));
}
// quick and dirty move-list sorting routine
// only purpose is to get all quiet moves at the start and hope for better hash table usage
void sortMoves(CMove *moves, int nMoves)
{
int nq = 0;
CMove sortedMoves[MAX_MOVES];
for (int i = 0; i < nMoves; i++)
{
if (moves[i].getFlags() == CM_FLAG_QUIET_MOVE)
{
sortedMoves[nq++] = moves[i];
}
}
int s = 0, u = 0;
for (int i = 0; i < nMoves; i++)
{
if (moves[i].getFlags() == CM_FLAG_QUIET_MOVE)
{
sortedMoves[s++] = moves[i];
}
else
{
sortedMoves[nq + (u++)] = moves[i];
}
}
memcpy(moves, sortedMoves, sizeof(CMove)* nMoves);
}
void randomizeMoves(CMove *moves, int nMoves)
{
for (int i=0;i<nMoves;i++)
{
int j = std::rand() % nMoves;
CMove otherMove = moves[j];
moves[j] = moves[i];
moves[i] = otherMove;
}
}
InfInt perft_bb_cpu_launcher(HexaBitBoardPosition *pos, uint32 depth, char *dispPrefix);
thread_local int activeGpu = 0;
enum eThreadStatus
{
THREAD_IDLE = 0,
WORK_SUBMITTED = 1,
THREAD_TERMINATE_REQUEST = 2,
THREAD_TERMINATED = 3,
THREAD_CREATED = 4
};
// 2 way communication between main thread and worker threads
volatile eThreadStatus threadStatus[MAX_GPUs];
// main thread -> worker threads
volatile HexaBitBoardPosition *posForThread[MAX_GPUs];
volatile char *dispStringForThread[MAX_GPUs];
// worker threads -> main thread
volatile InfInt *perftForThread[MAX_GPUs];
std::mutex criticalSection;
std::mutex diskCS;
void worker_thread_start(uint32 depth, uint32 gpuId)
{
cudaSetDevice(gpuId);
activeGpu = gpuId;
threadStatus[gpuId] = THREAD_IDLE;
// wait for work
while (1)
{
if (threadStatus[gpuId] == THREAD_TERMINATE_REQUEST)
{
break;
}
else if (threadStatus[gpuId] == THREAD_IDLE)
{
continue;
}
else if (threadStatus[gpuId] == WORK_SUBMITTED)
{
InfInt perftVal = perft_bb_cpu_launcher((HexaBitBoardPosition *)posForThread[gpuId], depth, (char*)dispStringForThread[gpuId]);
if (depth >= DIVIDED_PERFT_DEPTH)
{
criticalSection.lock();
//printf("%s %20llu\n", dispStringForThread[gpuId], perftVal);
printf("%s %20s\n", dispStringForThread[gpuId], perftVal.toString().c_str());
fflush(stdout);
criticalSection.unlock();
}
*((InfInt *)perftForThread[gpuId]) = perftVal;
threadStatus[gpuId] = THREAD_IDLE;
}
}
threadStatus[gpuId] = THREAD_TERMINATED;
}
// launch work on multiple threads (each associated with a single GPU),
// wait for enough parallel work is done, and only then wait for the threads to finish
InfInt perft_multi_threaded_gpu_launcher(HexaBitBoardPosition *pos, uint32 depth, char *dispPrefix)
{
CMove genMoves[MAX_MOVES];
HexaBitBoardPosition childPos;
HexaBitBoardPosition childBoards[MAX_MOVES];
char childStrings[MAX_MOVES][128];
InfInt perftResults[MAX_MOVES];
int nMoves = generateMoves(pos, pos->chance, genMoves);
// doesn't help :-/
//#if ENABLE_DISK_HASH == 1
// randomizeMoves(genMoves, nMoves);
//#else
sortMoves(genMoves, nMoves);
//#endif
std::thread threads[MAX_GPUs];
// Launch a thread for each GPU
for (int i = 0; i < numGPUs; ++i)
{
// create the thread
threadStatus[i] = THREAD_CREATED;
threads[i] = std::thread(worker_thread_start, depth - 1, i);
// wait for the thread to get initialized
while (threadStatus[i] != THREAD_IDLE);
}
for (int i = 0; i < nMoves; i++)
{
char moveString[10];
Utils::getCompactMoveString(genMoves[i], moveString);
strcpy(childStrings[i], dispPrefix);
strcat(childStrings[i], moveString);
childPos = *pos;
uint64 fakeHash = 0;
if (pos->chance == WHITE)
MoveGeneratorBitboard::makeMove<WHITE, false>(&childPos, fakeHash, genMoves[i]);
else
MoveGeneratorBitboard::makeMove<BLACK, false>(&childPos, fakeHash, genMoves[i]);
childBoards[i] = childPos;
// find an idle worker thread to submit work
int chosenThread = -1;
while (chosenThread == -1)
{
for (int t = 0; t < numGPUs; t++)
if (threadStatus[t] == THREAD_IDLE)
{
chosenThread = t;
break;
}
}
// submit work on the worker thread
posForThread[chosenThread] = &childBoards[i];
dispStringForThread[chosenThread] = childStrings[i];
perftForThread[chosenThread] = &perftResults[i];
threadStatus[chosenThread] = WORK_SUBMITTED;
}
// Ankan - TODO: if there is any thread idle, give it same position as some other active thread
// it will at least do something useful.
while(1)
{
bool allIdle = true;
for (int t = 0; t < numGPUs; t++)
{
if (threadStatus[t] == THREAD_IDLE)
{
for (int t2 = 0; t2 < numGPUs; t2++)
if (threadStatus[t2] != THREAD_IDLE)
{
posForThread[t] = posForThread[t2];
dispStringForThread[t] = dispStringForThread[t2];
InfInt temp;
perftForThread[t] = &temp;
threadStatus[t] = WORK_SUBMITTED;
allIdle = false;
}
}
}
if(allIdle)
break;
}
// wait for all threads to terminate
for (int t = 0; t < numGPUs; t++)
{
while (threadStatus[t] != THREAD_IDLE);
threadStatus[t] = THREAD_TERMINATE_REQUEST;
while (threadStatus[t] != THREAD_TERMINATED);
threads[t].join();
}
InfInt count = 0;
for (int i = 0; i < nMoves; i++)
{
count += perftResults[i];
}
return count;
}
// TODO: what happens to pending writes? No CS protection there!
// - lockless XOR trick should give (some?) protection
void lockCompleteTT()
{
criticalSection.lock();
}
void unlockCompleteTT()
{
criticalSection.unlock();
}
// returns non-null entryPtr if not found
uint64 completeTTProbe(HashKey128b hash, int depth, CompleteHashEntry **pEntryPtr, bool finalHash = false)
{
if (!finalHash)
{
hash ^= (ZOB_KEY_128(depth) * depth);
}
uint64 ttVal = 0; // value from transposition table in case of hash hit
*pEntryPtr = NULL; // new entry to update in case of hash miss
CompleteHashEntry *entry;
criticalSection.lock();
entry = &completeTT[hash.lowPart & COMPLETE_TT_INDEX_BITS];
while (1)
{
if (entry->hash == HashKey128b(0,0))
{
// blank record
// mark in-use (so that other parallel thread doesn't overwrite it)
// with this approach there is a (very!) small chance that duplicate entries might get added for the same position.
// ... but it should always be correct.
entry->hash = HashKey128b(ALLSET,ALLSET);
entry->nextIndex = ~0;
entry->nextTT = ~0;
*pEntryPtr = entry;
//printf("g %d: %llu ", depth, hash.lowPart); // Ankan - for testing
break;
}
// XOR with perft value to extract hash part
HashKey128b entryHash = entry->hash;
entryHash.highPart ^= entry->perft;
entryHash.lowPart ^= entry->perft;
if (entryHash == hash)
{
// hash hit
ttVal = entry->perft;
break;
}
if (entry->nextIndex == ~0)
{
chainIndex++;
if (chainIndex > COMPLETE_HASH_CHAIN_ALLOC_SIZE)
{
allocChainMemoryChunk();
}
entry->nextIndex = chainIndex;
entry->nextTT = (nChunks - 1);
}
entry = &(chainMemoryChunks[entry->nextTT][entry->nextIndex]);
}
criticalSection.unlock();
return ttVal;
}
void enqueueWorkItem(CompleteHashEntry *item);
void completeTTStore(CompleteHashEntry *entryPtr, HashKey128b hash, int depth, uint64 perft)
{
hash ^= (ZOB_KEY_128(depth) * depth);
// XOR trick to prevent random bit flip errors (and also half read network entries)
hash.highPart ^= perft;
hash.lowPart ^= perft;
criticalSection.lock(); // Ankan - remove this likely not needed (very low probablity)
entryPtr->hash = hash;
entryPtr->perft = perft;
criticalSection.unlock();
#if MULTI_NODE_NETWORK_MODE == 1
enqueueWorkItem(entryPtr);
#endif
}
void completeTTUpdateFromNetwork(HashKey128b hash, uint64 perft)
{
CompleteHashEntry *pEntry;
HashKey128b actualHash = hash;
actualHash.highPart ^= perft;
actualHash.lowPart ^= perft;
completeTTProbe(actualHash, 0, &pEntry, true);
if (pEntry)
{
pEntry->hash = hash;
pEntry->perft = perft;
numItemsFromPeers++;
}
}
#if ENABLE_DISK_HASH == 1
uint64 diskTTProbe(HashKey128b posHash128b, int depth, DiskHashEntry* pDiskEntry, uint64 *pDiskHashIndex)
{
DiskHashEntry diskEntry = {};
uint64 diskEntryIndex = 0;
// check disk hash
uint64 ttVal = ALLSET;
int fd = open("perfthash.dat", O_RDWR);
uint64 index = posHash128b.lowPart & GET_TT_INDEX_BITS(DISK_TT_BITS);
diskCS.lock(); // protect against parallel access in same process!
// protect against parallel access across nodes of cluster
// this doesn't seem to work (causes cluster to hang!)
// flock(fd, LOCK_EX);
// use a lockfile instead
int lfd;
while((lfd = open(".lock", O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1) ;
close(lfd);
lseek(fd, index*sizeof(DiskHashEntry), SEEK_SET);
read(fd, &diskEntry, sizeof(DiskHashEntry));
while(1)
{
if(diskEntry.hash == HashKey128b(0,0))
{
// blank record
// mark in-use (so that other parallel thread doesn't overwrite it)
diskEntry.hash = HashKey128b(ALLSET,ALLSET);
diskEntry.next = ~0;
diskEntry.depth = depth;
diskEntryIndex = index;
lseek(fd, index*sizeof(DiskHashEntry), SEEK_SET);
write(fd, &diskEntry, sizeof(DiskHashEntry));
break;
}
if (diskEntry.hash == posHash128b && diskEntry.depth == depth)
{
// hash hit
ttVal = diskEntry.perft;
break;
}
if (diskEntry.next == ~0)
{
// add new entry to chain
uint64 nextIndex = lseek(fd, 0, SEEK_END) / sizeof(DiskHashEntry);
diskEntry.next = nextIndex;
lseek(fd, index*sizeof(DiskHashEntry), SEEK_SET);
write(fd, &diskEntry, sizeof(DiskHashEntry));
DiskHashEntry blankRecord = {};
lseek(fd, nextIndex * sizeof(DiskHashEntry), SEEK_SET);
write(fd, &blankRecord, sizeof(DiskHashEntry));
}
// go to the next entry in chain
index = diskEntry.next;
lseek(fd, index*sizeof(DiskHashEntry), SEEK_SET);
read(fd, &diskEntry, sizeof(DiskHashEntry));
}
//flock(fd, LOCK_UN);
close(fd);
remove(".lock");
diskCS.unlock();
*pDiskEntry = diskEntry;
*pDiskHashIndex = diskEntryIndex;
return ttVal;
}
void diskTTStore(DiskHashEntry *diskEntry, uint64 diskEntryIndex, HashKey128b posHash128b, int depth, uint64 perft)
{
diskEntry->hash = posHash128b;
diskEntry->perft = perft;
diskEntry->depth = depth;
diskEntry->next = ~0; // possible bug here! should read from the disk and check
diskCS.lock(); // avoid parallel file access from same process
int fd = open("perfthash.dat", O_RDWR);
lseek(fd, diskEntryIndex * sizeof(DiskHashEntry), SEEK_SET);
write(fd, diskEntry, sizeof(DiskHashEntry));
close(fd);
diskCS.unlock();
}
#endif
int diskHashDepth = 0; // set to search depth - 4
int splitDepth = MIN_SPLIT_DEPTH;
uint32 maxMemoryUsage = 0;
int numRegularLaunches = 0;
int numRetryLaunches = 0;
// launch last two levels
// attemps to overlap CPU and GPU time
// - cpu time to check hash table
// - gpu time for perft calculation
#if 0
uint64 perft_bb_second_last_level_launcher(HexaBitBoardPosition *pos, uint32 depth)
{
HashKey128b hash = MoveGeneratorBitboard::computeZobristKey128b(pos);
// first level children
CMove firstLevelMoves[MAX_MOVES];
uint64 firstLevelPerfts[MAX_MOVES];
int firstLevelNewBoards = 0;
CompleteHashEntry *firstLevelHashEntries[MAX_MOVES];
uint8 color = pos->chance;
int nMoves = generateMoves(pos, color, firstLevelMoves);
sortMoves(moves, nMoves);
uint64 perft = 0;
for(j=0;j<nMoves;j++)
{
HexaBitBoardPosition curPos = *pos;
HashKey128b curHash = makeMoveAndUpdateHash(&curPos, hash, firstLevelMoves[j], color);
// check in hash table
CompleteHashEntry *entryPtr;
uint64 ttVal = completeTTProbe(newHash, depth+1, &entryPtr);
if (entryPtr == NULL)
{
perft += ttVal;
continue;
}
firstLevelHashEntries[firstLevelNewBoards++] = entryPtr;
uint64 count = 0;
// second level moves and boards
HexaBitBoardPosition childBoards[MAX_MOVES];
CMove moves[MAX_MOVES];
HashKey128b hashes[MAX_MOVES];
uint64 perfts[MAX_MOVES];
uint8 color = pos->chance;
int nChildMoves = generateMoves(curPos, color, moves);
sortMoves(moves, nChildMoves);
int nNewBoards = 0;
CompleteHashEntry *newEntryPointer[MAX_MOVES];
for (int i = 0; i < nMoves; i++)
{
childBoards[nNewBoards] = *curPos;
HashKey128b newHash = makeMoveAndUpdateHash(&childBoards[nNewBoards], curHash, moves[i], color);
CompleteHashEntry *entryPtr;
uint64 ttVal = completeTTProbe(newHash, depth + 2, &entryPtr);
if (entryPtr == NULL)
{
count += ttVal;
continue;
}
newEntryPointer[nNewBoards] = entryPtr;
hashes[nNewBoards] = newHash;
nNewBoards++;
}
numRegularLaunches += nNewBoards;
#if MEASURE_GPU_ACTIVE_TIME == 1
START_TIMER
#endif
// copy host->device in one go
cudaMemcpy(gpuBoard[activeGpu], childBoards, sizeof(HexaBitBoardPosition)*nNewBoards, cudaMemcpyHostToDevice);
cudaMemset(gpu_perft[activeGpu], 0, sizeof(uint64)*nNewBoards);
cudaMemcpy(gpuHashes[activeGpu], hashes, sizeof(HashKey128b)*nNewBoards, cudaMemcpyHostToDevice);
int batchSize = nNewBoards;
memset(perfts, 0xFF, sizeof(uint64)*nNewBoards);
while(1)
{
bool done = true;
for (int i = 0; i < nNewBoards;)
{
if (perfts[i] == ALLSET)
{
int count = ((nNewBoards - i) > batchSize) ? batchSize : nNewBoards - i;
// skip the ones already computed
while (perfts[i + count - 1] != ALLSET) count--;
if (batchSize != nNewBoards)
numRetryLaunches++;
perft_bb_gpu_simple_hash << <1, 1 >> > (count, &gpuBoard[activeGpu][i], &gpuHashes[activeGpu][i], &gpu_perft[activeGpu][i], depth - 1, preAllocatedBufferHost[activeGpu],
TransTables128b[activeGpu], true);
cudaError_t err = cudaMemcpy(&perfts[i], &gpu_perft[activeGpu][i], sizeof(uint64) * count, cudaMemcpyDeviceToHost);
if (perfts[i] == ALLSET)
{
done = false;
for (int j = 0; j < count; j++)
perfts[i + j] = ALLSET;
cudaMemset(&gpu_perft[activeGpu][i], 0, sizeof(uint64) * count);
}
i += count;
}
else
{
i++;
}
}
if (done)
break;
// some bug here??!!!
if (batchSize == 1)
{
printf("\nCan't even fit a single launch! Exiting\n");
exit(0);
}
batchSize = (batchSize + 3) / 4;
}
// update memory usage estimation
uint32 currentMemUsage = 0;
cudaError_t s = cudaMemcpyFromSymbol(¤tMemUsage, maxMemoryUsed, sizeof(int), 0, cudaMemcpyDeviceToHost);
if (currentMemUsage > maxMemoryUsage)
{
maxMemoryUsage = currentMemUsage;
}
// collect perft results and update hash table
for (int i = 0; i < nNewBoards; i++)
{
if (perfts[i] == ALLSET)
{
printf("\nUnexpected ERROR? Exiting!!\n");
exit(0);
}
count += perfts[i];
HashKey128b posHash128b = hashes[i];
completeTTStore(newEntryPointer[i], hashes[i], depth+2, perfts[i]);
}
return count;
}
}
#endif
// launch all boards of the last level without waiting for previous work to finish
// tiny bit improvement in GPU utilization
uint64 perft_bb_last_level_launcher(HexaBitBoardPosition *pos, uint32 depth)
{
HashKey128b hash = MoveGeneratorBitboard::computeZobristKey128b(pos);
HexaBitBoardPosition childBoards[MAX_MOVES];
CMove moves[MAX_MOVES];
HashKey128b hashes[MAX_MOVES];
uint64 perfts[MAX_MOVES];
// generate moves for the current board and call the breadth first routine for all child boards
uint8 color = pos->chance;
int nMoves = generateMoves(pos, color, moves);
sortMoves(moves, nMoves);
HashEntryPerft128b *hashTable = (HashEntryPerft128b *)TransTables128b[0].cpuTable[depth - 1];
uint64 indexBits = TransTables128b[0].indexBits[depth - 1];
uint64 hashBits = TransTables128b[0].hashBits[depth - 1];
#if USE_COMPLETE_TT_AT_LAST_CPU_LEVEL == 1
CompleteHashEntry *newEntryPointer[MAX_MOVES];
#endif
int nNewBoards = 0;
uint64 count = 0;
for (int i = 0; i < nMoves; i++)
{
childBoards[nNewBoards] = *pos;
HashKey128b newHash = makeMoveAndUpdateHash(&childBoards[nNewBoards], hash, moves[i], color);
// check in hash table
#if USE_COMPLETE_TT_AT_LAST_CPU_LEVEL == 1
if (depth == GPU_LAUNCH_DEPTH + 1)
{
CompleteHashEntry *entryPtr;
uint64 ttVal = completeTTProbe(newHash, GPU_LAUNCH_DEPTH, &entryPtr);