Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/syzygy/tbprobe.cpp
376 views
1
/*
2
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
5
Stockfish is free software: you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation, either version 3 of the License, or
8
(at your option) any later version.
9
10
Stockfish is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
GNU General Public License for more details.
14
15
You should have received a copy of the GNU General Public License
16
along with this program. If not, see <http://www.gnu.org/licenses/>.
17
*/
18
19
#include "tbprobe.h"
20
21
#include <algorithm>
22
#include <atomic>
23
#include <cassert>
24
#include <cstdint>
25
#include <cstdlib>
26
#include <cstring>
27
#include <deque>
28
#include <fstream>
29
#include <initializer_list>
30
#include <iostream>
31
#include <mutex>
32
#include <sstream>
33
#include <string_view>
34
#include <sys/stat.h>
35
#include <type_traits>
36
#include <utility>
37
#include <vector>
38
39
#include "../bitboard.h"
40
#include "../misc.h"
41
#include "../movegen.h"
42
#include "../position.h"
43
#include "../search.h"
44
#include "../types.h"
45
#include "../ucioption.h"
46
47
#ifndef _WIN32
48
#include <fcntl.h>
49
#include <sys/mman.h>
50
#include <unistd.h>
51
#else
52
#define WIN32_LEAN_AND_MEAN
53
#ifndef NOMINMAX
54
#define NOMINMAX // Disable macros min() and max()
55
#endif
56
#include <windows.h>
57
#endif
58
59
using namespace Stockfish::Tablebases;
60
61
int Stockfish::Tablebases::MaxCardinality;
62
63
namespace Stockfish {
64
65
namespace {
66
67
constexpr int TBPIECES = 7; // Max number of supported pieces
68
constexpr int MAX_DTZ =
69
1 << 18; // Max DTZ supported times 2, large enough to deal with the syzygy TB limit.
70
71
enum {
72
BigEndian,
73
LittleEndian
74
};
75
enum TBType {
76
WDL,
77
DTZ
78
}; // Used as template parameter
79
80
// Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables
81
enum TBFlag {
82
STM = 1,
83
Mapped = 2,
84
WinPlies = 4,
85
LossPlies = 8,
86
Wide = 16,
87
SingleValue = 128
88
};
89
90
inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
91
inline Square operator^(Square s, int i) { return Square(int(s) ^ i); }
92
93
constexpr std::string_view PieceToChar = " PNBRQK pnbrqk";
94
95
int MapPawns[SQUARE_NB];
96
int MapB1H1H7[SQUARE_NB];
97
int MapA1D1D4[SQUARE_NB];
98
int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
99
100
int Binomial[6][SQUARE_NB]; // [k][n] k elements from a set of n elements
101
int LeadPawnIdx[6][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB]
102
int LeadPawnsSize[6][4]; // [leadPawnsCnt][FILE_A..FILE_D]
103
104
// Comparison function to sort leading pawns in ascending MapPawns[] order
105
bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; }
106
int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); }
107
108
constexpr Value WDL_to_value[] = {-VALUE_MATE + MAX_PLY + 1, VALUE_DRAW - 2, VALUE_DRAW,
109
VALUE_DRAW + 2, VALUE_MATE - MAX_PLY - 1};
110
111
template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
112
inline void swap_endian(T& x) {
113
static_assert(std::is_unsigned_v<T>, "Argument of swap_endian not unsigned");
114
115
uint8_t tmp, *c = (uint8_t*) &x;
116
for (int i = 0; i < Half; ++i)
117
tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
118
}
119
template<>
120
inline void swap_endian<uint8_t>(uint8_t&) {}
121
122
template<typename T, int LE>
123
T number(void* addr) {
124
T v;
125
126
if (uintptr_t(addr) & (alignof(T) - 1)) // Unaligned pointer (very rare)
127
std::memcpy(&v, addr, sizeof(T));
128
else
129
v = *((T*) addr);
130
131
if (LE != IsLittleEndian)
132
swap_endian(v);
133
return v;
134
}
135
136
// DTZ tables don't store valid scores for moves that reset the rule50 counter
137
// like captures and pawn moves but we can easily recover the correct dtz of the
138
// previous move if we know the position's WDL score.
139
int dtz_before_zeroing(WDLScore wdl) {
140
return wdl == WDLWin ? 1
141
: wdl == WDLCursedWin ? 101
142
: wdl == WDLBlessedLoss ? -101
143
: wdl == WDLLoss ? -1
144
: 0;
145
}
146
147
// Return the sign of a number (-1, 0, 1)
148
template<typename T>
149
int sign_of(T val) {
150
return (T(0) < val) - (val < T(0));
151
}
152
153
// Numbers in little-endian used by sparseIndex[] to point into blockLength[]
154
struct SparseEntry {
155
char block[4]; // Number of block
156
char offset[2]; // Offset within the block
157
};
158
159
static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
160
161
using Sym = uint16_t; // Huffman symbol
162
163
struct LR {
164
enum Side {
165
Left,
166
Right
167
};
168
169
uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
170
// bits is the right-hand symbol. If the symbol has length 1,
171
// then the left-hand symbol is the stored value.
172
template<Side S>
173
Sym get() {
174
return S == Left ? ((lr[1] & 0xF) << 8) | lr[0]
175
: S == Right ? (lr[2] << 4) | (lr[1] >> 4)
176
: (assert(false), Sym(-1));
177
}
178
};
179
180
static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
181
182
// Tablebases data layout is structured as following:
183
//
184
// TBFile: memory maps/unmaps the physical .rtbw and .rtbz files
185
// TBTable: one object for each file with corresponding indexing information
186
// TBTables: has ownership of TBTable objects, keeping a list and a hash
187
188
// class TBFile memory maps/unmaps the single .rtbw and .rtbz files. Files are
189
// memory mapped for best performance. Files are mapped at first access: at init
190
// time only existence of the file is checked.
191
class TBFile: public std::ifstream {
192
193
std::string fname;
194
195
public:
196
// Look for and open the file among the Paths directories where the .rtbw
197
// and .rtbz files can be found. Multiple directories are separated by ";"
198
// on Windows and by ":" on Unix-based operating systems.
199
//
200
// Example:
201
// C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
202
static std::string Paths;
203
204
TBFile(const std::string& f) {
205
206
#ifndef _WIN32
207
constexpr char SepChar = ':';
208
#else
209
constexpr char SepChar = ';';
210
#endif
211
std::stringstream ss(Paths);
212
std::string path;
213
214
while (std::getline(ss, path, SepChar))
215
{
216
fname = path + "/" + f;
217
std::ifstream::open(fname);
218
if (is_open())
219
return;
220
}
221
}
222
223
// Memory map the file and check it.
224
uint8_t* map(void** baseAddress, uint64_t* mapping, TBType type) {
225
if (is_open())
226
close(); // Need to re-open to get native file descriptor
227
228
#ifndef _WIN32
229
struct stat statbuf;
230
int fd = ::open(fname.c_str(), O_RDONLY);
231
232
if (fd == -1)
233
return *baseAddress = nullptr, nullptr;
234
235
fstat(fd, &statbuf);
236
237
if (statbuf.st_size % 64 != 16)
238
{
239
std::cerr << "Corrupt tablebase file " << fname << std::endl;
240
exit(EXIT_FAILURE);
241
}
242
243
*mapping = statbuf.st_size;
244
*baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
245
#if defined(MADV_RANDOM)
246
madvise(*baseAddress, statbuf.st_size, MADV_RANDOM);
247
#endif
248
::close(fd);
249
250
if (*baseAddress == MAP_FAILED)
251
{
252
std::cerr << "Could not mmap() " << fname << std::endl;
253
exit(EXIT_FAILURE);
254
}
255
#else
256
// Note FILE_FLAG_RANDOM_ACCESS is only a hint to Windows and as such may get ignored.
257
HANDLE fd = CreateFileA(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
258
OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, nullptr);
259
260
if (fd == INVALID_HANDLE_VALUE)
261
return *baseAddress = nullptr, nullptr;
262
263
DWORD size_high;
264
DWORD size_low = GetFileSize(fd, &size_high);
265
266
if (size_low % 64 != 16)
267
{
268
std::cerr << "Corrupt tablebase file " << fname << std::endl;
269
exit(EXIT_FAILURE);
270
}
271
272
HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
273
CloseHandle(fd);
274
275
if (!mmap)
276
{
277
std::cerr << "CreateFileMapping() failed" << std::endl;
278
exit(EXIT_FAILURE);
279
}
280
281
*mapping = uint64_t(mmap);
282
*baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
283
284
if (!*baseAddress)
285
{
286
std::cerr << "MapViewOfFile() failed, name = " << fname
287
<< ", error = " << GetLastError() << std::endl;
288
exit(EXIT_FAILURE);
289
}
290
#endif
291
uint8_t* data = (uint8_t*) *baseAddress;
292
293
constexpr uint8_t Magics[][4] = {{0xD7, 0x66, 0x0C, 0xA5}, {0x71, 0xE8, 0x23, 0x5D}};
294
295
if (memcmp(data, Magics[type == WDL], 4))
296
{
297
std::cerr << "Corrupted table in file " << fname << std::endl;
298
unmap(*baseAddress, *mapping);
299
return *baseAddress = nullptr, nullptr;
300
}
301
302
return data + 4; // Skip Magics's header
303
}
304
305
static void unmap(void* baseAddress, uint64_t mapping) {
306
307
#ifndef _WIN32
308
munmap(baseAddress, mapping);
309
#else
310
UnmapViewOfFile(baseAddress);
311
CloseHandle((HANDLE) mapping);
312
#endif
313
}
314
};
315
316
std::string TBFile::Paths;
317
318
// struct PairsData contains low-level indexing information to access TB data.
319
// There are 8, 4, or 2 PairsData records for each TBTable, according to the type
320
// of table and if positions have pawns or not. It is populated at first access.
321
struct PairsData {
322
uint8_t flags; // Table flags, see enum TBFlag
323
uint8_t maxSymLen; // Maximum length in bits of the Huffman symbols
324
uint8_t minSymLen; // Minimum length in bits of the Huffman symbols
325
uint32_t blocksNum; // Number of blocks in the TB file
326
size_t sizeofBlock; // Block size in bytes
327
size_t span; // About every span values there is a SparseIndex[] entry
328
Sym* lowestSym; // lowestSym[l] is the symbol of length l with the lowest value
329
LR* btree; // btree[sym] stores the left and right symbols that expand sym
330
uint16_t* blockLength; // Number of stored positions (minus one) for each block: 1..65536
331
uint32_t blockLengthSize; // Size of blockLength[] table: padded so it's bigger than blocksNum
332
SparseEntry* sparseIndex; // Partial indices into blockLength[]
333
size_t sparseIndexSize; // Size of SparseIndex[] table
334
uint8_t* data; // Start of Huffman compressed data
335
std::vector<uint64_t>
336
base64; // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l
337
std::vector<uint8_t>
338
symlen; // Number of values (-1) represented by a given Huffman symbol: 1..256
339
Piece pieces[TBPIECES]; // Position pieces: the order of pieces defines the groups
340
uint64_t groupIdx[TBPIECES + 1]; // Start index used for the encoding of the group's pieces
341
int groupLen[TBPIECES + 1]; // Number of pieces in a given group: KRKN -> (3, 1)
342
uint16_t map_idx[4]; // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss (used in DTZ)
343
};
344
345
// struct TBTable contains indexing information to access the corresponding TBFile.
346
// There are 2 types of TBTable, corresponding to a WDL or a DTZ file. TBTable
347
// is populated at init time but the nested PairsData records are populated at
348
// first access, when the corresponding file is memory mapped.
349
template<TBType Type>
350
struct TBTable {
351
using Ret = std::conditional_t<Type == WDL, WDLScore, int>;
352
353
static constexpr int Sides = Type == WDL ? 2 : 1;
354
355
std::atomic_bool ready;
356
void* baseAddress;
357
uint8_t* map;
358
uint64_t mapping;
359
Key key;
360
Key key2;
361
int pieceCount;
362
bool hasPawns;
363
bool hasUniquePieces;
364
uint8_t pawnCount[2]; // [Lead color / other color]
365
PairsData items[Sides][4]; // [wtm / btm][FILE_A..FILE_D or 0]
366
367
PairsData* get(int stm, int f) { return &items[stm % Sides][hasPawns ? f : 0]; }
368
369
TBTable() :
370
ready(false),
371
baseAddress(nullptr) {}
372
explicit TBTable(const std::string& code);
373
explicit TBTable(const TBTable<WDL>& wdl);
374
375
~TBTable() {
376
if (baseAddress)
377
TBFile::unmap(baseAddress, mapping);
378
}
379
};
380
381
template<>
382
TBTable<WDL>::TBTable(const std::string& code) :
383
TBTable() {
384
385
StateInfo st;
386
Position pos;
387
388
key = pos.set(code, WHITE, &st).material_key();
389
pieceCount = pos.count<ALL_PIECES>();
390
hasPawns = pos.pieces(PAWN);
391
392
hasUniquePieces = false;
393
for (Color c : {WHITE, BLACK})
394
for (PieceType pt = PAWN; pt < KING; ++pt)
395
if (popcount(pos.pieces(c, pt)) == 1)
396
hasUniquePieces = true;
397
398
// Set the leading color. In case both sides have pawns the leading color
399
// is the side with fewer pawns because this leads to better compression.
400
bool c = !pos.count<PAWN>(BLACK)
401
|| (pos.count<PAWN>(WHITE) && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
402
403
pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
404
pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
405
406
key2 = pos.set(code, BLACK, &st).material_key();
407
}
408
409
template<>
410
TBTable<DTZ>::TBTable(const TBTable<WDL>& wdl) :
411
TBTable() {
412
413
// Use the corresponding WDL table to avoid recalculating all from scratch
414
key = wdl.key;
415
key2 = wdl.key2;
416
pieceCount = wdl.pieceCount;
417
hasPawns = wdl.hasPawns;
418
hasUniquePieces = wdl.hasUniquePieces;
419
pawnCount[0] = wdl.pawnCount[0];
420
pawnCount[1] = wdl.pawnCount[1];
421
}
422
423
// class TBTables creates and keeps ownership of the TBTable objects, one for
424
// each TB file found. It supports a fast, hash-based, table lookup. Populated
425
// at init time, accessed at probe time.
426
class TBTables {
427
428
struct Entry {
429
Key key;
430
TBTable<WDL>* wdl;
431
TBTable<DTZ>* dtz;
432
433
template<TBType Type>
434
TBTable<Type>* get() const {
435
return (TBTable<Type>*) (Type == WDL ? (void*) wdl : (void*) dtz);
436
}
437
};
438
439
static constexpr int Size = 1 << 12; // 4K table, indexed by key's 12 lsb
440
static constexpr int Overflow = 1; // Number of elements allowed to map to the last bucket
441
442
Entry hashTable[Size + Overflow];
443
444
std::deque<TBTable<WDL>> wdlTable;
445
std::deque<TBTable<DTZ>> dtzTable;
446
size_t foundDTZFiles = 0;
447
size_t foundWDLFiles = 0;
448
449
void insert(Key key, TBTable<WDL>* wdl, TBTable<DTZ>* dtz) {
450
uint32_t homeBucket = uint32_t(key) & (Size - 1);
451
Entry entry{key, wdl, dtz};
452
453
// Ensure last element is empty to avoid overflow when looking up
454
for (uint32_t bucket = homeBucket; bucket < Size + Overflow - 1; ++bucket)
455
{
456
Key otherKey = hashTable[bucket].key;
457
if (otherKey == key || !hashTable[bucket].get<WDL>())
458
{
459
hashTable[bucket] = entry;
460
return;
461
}
462
463
// Robin Hood hashing: If we've probed for longer than this element,
464
// insert here and search for a new spot for the other element instead.
465
uint32_t otherHomeBucket = uint32_t(otherKey) & (Size - 1);
466
if (otherHomeBucket > homeBucket)
467
{
468
std::swap(entry, hashTable[bucket]);
469
key = otherKey;
470
homeBucket = otherHomeBucket;
471
}
472
}
473
std::cerr << "TB hash table size too low!" << std::endl;
474
exit(EXIT_FAILURE);
475
}
476
477
public:
478
template<TBType Type>
479
TBTable<Type>* get(Key key) {
480
for (const Entry* entry = &hashTable[uint32_t(key) & (Size - 1)];; ++entry)
481
{
482
if (entry->key == key || !entry->get<Type>())
483
return entry->get<Type>();
484
}
485
}
486
487
void clear() {
488
memset(hashTable, 0, sizeof(hashTable));
489
wdlTable.clear();
490
dtzTable.clear();
491
foundDTZFiles = 0;
492
foundWDLFiles = 0;
493
}
494
495
void info() const {
496
sync_cout << "info string Found " << foundWDLFiles << " WDL and " << foundDTZFiles
497
<< " DTZ tablebase files (up to " << MaxCardinality << "-man)." << sync_endl;
498
}
499
500
void add(const std::vector<PieceType>& pieces);
501
};
502
503
TBTables TBTables;
504
505
// If the corresponding file exists two new objects TBTable<WDL> and TBTable<DTZ>
506
// are created and added to the lists and hash table. Called at init time.
507
void TBTables::add(const std::vector<PieceType>& pieces) {
508
509
std::string code;
510
511
for (PieceType pt : pieces)
512
code += PieceToChar[pt];
513
code.insert(code.find('K', 1), "v");
514
515
TBFile file_dtz(code + ".rtbz"); // KRK -> KRvK
516
if (file_dtz.is_open())
517
{
518
file_dtz.close();
519
foundDTZFiles++;
520
}
521
522
TBFile file(code + ".rtbw"); // KRK -> KRvK
523
524
if (!file.is_open()) // Only WDL file is checked
525
return;
526
527
file.close();
528
foundWDLFiles++;
529
530
MaxCardinality = std::max(int(pieces.size()), MaxCardinality);
531
532
wdlTable.emplace_back(code);
533
dtzTable.emplace_back(wdlTable.back());
534
535
// Insert into the hash keys for both colors: KRvK with KR white and black
536
insert(wdlTable.back().key, &wdlTable.back(), &dtzTable.back());
537
insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
538
}
539
540
// TB tables are compressed with canonical Huffman code. The compressed data is divided into
541
// blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
542
// Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
543
// (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
544
// WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
545
// Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
546
// 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
547
// of draws or mostly of wins, but such tables are actually quite common. In principle, the
548
// blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
549
// mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
550
// in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
551
// The generator picks the size that leads to the smallest table. The "book" of symbols and
552
// Huffman codes are the same for all blocks in the table. A non-symmetric pawnless TB file
553
// will have one table for wtm and one for btm, a TB file with pawns will have tables per
554
// file a,b,c,d also, in this case, one set for wtm and one for btm.
555
int decompress_pairs(PairsData* d, uint64_t idx) {
556
557
// Special case where all table positions store the same value
558
if (d->flags & TBFlag::SingleValue)
559
return d->minSymLen;
560
561
// First we need to locate the right block that stores the value at index "idx".
562
// Because each block n stores blockLength[n] + 1 values, the index i of the block
563
// that contains the value at position idx is:
564
//
565
// for (i = -1, sum = 0; sum <= idx; i++)
566
// sum += blockLength[i + 1] + 1;
567
//
568
// This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
569
// point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
570
// that stores the blockLength[] index and the offset within that block of the value
571
// with index I(k), where:
572
//
573
// I(k) = k * d->span + d->span / 2 (1)
574
575
// First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
576
uint32_t k = uint32_t(idx / d->span);
577
578
// Then we read the corresponding SparseIndex[] entry
579
uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
580
int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
581
582
// Now compute the difference idx - I(k). From the definition of k, we know that
583
//
584
// idx = k * d->span + idx % d->span (2)
585
//
586
// So from (1) and (2) we can compute idx - I(K):
587
int diff = idx % d->span - d->span / 2;
588
589
// Sum the above to offset to find the offset corresponding to our idx
590
offset += diff;
591
592
// Move to the previous/next block, until we reach the correct block that contains idx,
593
// that is when 0 <= offset <= d->blockLength[block]
594
while (offset < 0)
595
offset += d->blockLength[--block] + 1;
596
597
while (offset > d->blockLength[block])
598
offset -= d->blockLength[block++] + 1;
599
600
// Finally, we find the start address of our block of canonical Huffman symbols
601
uint32_t* ptr = (uint32_t*) (d->data + (uint64_t(block) * d->sizeofBlock));
602
603
// Read the first 64 bits in our block, this is a (truncated) sequence of
604
// unknown number of symbols of unknown length but we know the first one
605
// is at the beginning of this 64-bit sequence.
606
uint64_t buf64 = number<uint64_t, BigEndian>(ptr);
607
ptr += 2;
608
int buf64Size = 64;
609
Sym sym;
610
611
while (true)
612
{
613
int len = 0; // This is the symbol length - d->min_sym_len
614
615
// Now get the symbol length. For any symbol s64 of length l right-padded
616
// to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
617
// can find the symbol length iterating through base64[].
618
while (buf64 < d->base64[len])
619
++len;
620
621
// All the symbols of a given length are consecutive integers (numerical
622
// sequence property), so we can compute the offset of our symbol of
623
// length len, stored at the beginning of buf64.
624
sym = Sym((buf64 - d->base64[len]) >> (64 - len - d->minSymLen));
625
626
// Now add the value of the lowest symbol of length len to get our symbol
627
sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
628
629
// If our offset is within the number of values represented by symbol sym,
630
// we are done.
631
if (offset < d->symlen[sym] + 1)
632
break;
633
634
// ...otherwise update the offset and continue to iterate
635
offset -= d->symlen[sym] + 1;
636
len += d->minSymLen; // Get the real length
637
buf64 <<= len; // Consume the just processed symbol
638
buf64Size -= len;
639
640
if (buf64Size <= 32)
641
{ // Refill the buffer
642
buf64Size += 32;
643
buf64 |= uint64_t(number<uint32_t, BigEndian>(ptr++)) << (64 - buf64Size);
644
}
645
}
646
647
// Now we have our symbol that expands into d->symlen[sym] + 1 symbols.
648
// We binary-search for our value recursively expanding into the left and
649
// right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
650
// that will store the value we need.
651
while (d->symlen[sym])
652
{
653
Sym left = d->btree[sym].get<LR::Left>();
654
655
// If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
656
// expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
657
// we know that, for instance, the tenth value (offset = 10) will be on
658
// the left side because in Recursive Pairing child symbols are adjacent.
659
if (offset < d->symlen[left] + 1)
660
sym = left;
661
else
662
{
663
offset -= d->symlen[left] + 1;
664
sym = d->btree[sym].get<LR::Right>();
665
}
666
}
667
668
return d->btree[sym].get<LR::Left>();
669
}
670
671
bool check_dtz_stm(TBTable<WDL>*, int, File) { return true; }
672
673
bool check_dtz_stm(TBTable<DTZ>* entry, int stm, File f) {
674
675
auto flags = entry->get(stm, f)->flags;
676
return (flags & TBFlag::STM) == stm || ((entry->key == entry->key2) && !entry->hasPawns);
677
}
678
679
// DTZ scores are sorted by frequency of occurrence and then assigned the
680
// values 0, 1, 2, ... in order of decreasing frequency. This is done for each
681
// of the four WDLScore values. The mapping information necessary to reconstruct
682
// the original values are stored in the TB file and read during map[] init.
683
WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); }
684
685
int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) {
686
687
constexpr int WDLMap[] = {1, 3, 0, 2, 0};
688
689
auto flags = entry->get(0, f)->flags;
690
691
uint8_t* map = entry->map;
692
uint16_t* idx = entry->get(0, f)->map_idx;
693
if (flags & TBFlag::Mapped)
694
{
695
if (flags & TBFlag::Wide)
696
value = ((uint16_t*) map)[idx[WDLMap[wdl + 2]] + value];
697
else
698
value = map[idx[WDLMap[wdl + 2]] + value];
699
}
700
701
// DTZ tables store distance to zero in number of moves or plies. We
702
// want to return plies, so we have to convert to plies when needed.
703
if ((wdl == WDLWin && !(flags & TBFlag::WinPlies))
704
|| (wdl == WDLLoss && !(flags & TBFlag::LossPlies)) || wdl == WDLCursedWin
705
|| wdl == WDLBlessedLoss)
706
value *= 2;
707
708
return value + 1;
709
}
710
711
// A temporary fix for the compiler bug with AVX-512. (#4450)
712
#ifdef USE_AVX512
713
#if defined(__clang__) && defined(__clang_major__) && __clang_major__ >= 15
714
#define CLANG_AVX512_BUG_FIX __attribute__((optnone))
715
#endif
716
#endif
717
718
#ifndef CLANG_AVX512_BUG_FIX
719
#define CLANG_AVX512_BUG_FIX
720
#endif
721
722
// Compute a unique index out of a position and use it to probe the TB file. To
723
// encode k pieces of the same type and color, first sort the pieces by square in
724
// ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
725
//
726
// idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
727
//
728
template<typename T, typename Ret = typename T::Ret>
729
CLANG_AVX512_BUG_FIX Ret
730
do_probe_table(const Position& pos, T* entry, WDLScore wdl, ProbeState* result) {
731
732
Square squares[TBPIECES];
733
Piece pieces[TBPIECES];
734
uint64_t idx;
735
int next = 0, size = 0, leadPawnsCnt = 0;
736
PairsData* d;
737
Bitboard b, leadPawns = 0;
738
File tbFile = FILE_A;
739
740
// A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
741
// If both sides have the same pieces keys are equal. In this case TB tables
742
// only stores the 'white to move' case, so if the position to lookup has black
743
// to move, we need to switch the color and flip the squares before to lookup.
744
bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
745
746
// TB files are calculated for white as the stronger side. For instance, we
747
// have KRvK, not KvKR. A position where the stronger side is white will have
748
// its material key == entry->key, otherwise we have to switch the color and
749
// flip the squares before to lookup.
750
bool blackStronger = (pos.material_key() != entry->key);
751
752
int flipColor = (symmetricBlackToMove || blackStronger) * 8;
753
int flipSquares = (symmetricBlackToMove || blackStronger) * 56;
754
int stm = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
755
756
// For pawns, TB files store 4 separate tables according if leading pawn is on
757
// file a, b, c or d after reordering. The leading pawn is the one with maximum
758
// MapPawns[] value, that is the one most toward the edges and with lowest rank.
759
if (entry->hasPawns)
760
{
761
762
// In all the 4 tables, pawns are at the beginning of the piece sequence and
763
// their color is the reference one. So we just pick the first one.
764
Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor);
765
766
assert(type_of(pc) == PAWN);
767
768
leadPawns = b = pos.pieces(color_of(pc), PAWN);
769
do
770
squares[size++] = pop_lsb(b) ^ flipSquares;
771
while (b);
772
773
leadPawnsCnt = size;
774
775
std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
776
777
tbFile = File(edge_distance(file_of(squares[0])));
778
}
779
780
// DTZ tables are one-sided, i.e. they store positions only for white to
781
// move or only for black to move, so check for side to move to be stm,
782
// early exit otherwise.
783
if (!check_dtz_stm(entry, stm, tbFile))
784
return *result = CHANGE_STM, Ret();
785
786
// Now we are ready to get all the position pieces (but the lead pawns) and
787
// directly map them to the correct color and square.
788
b = pos.pieces() ^ leadPawns;
789
do
790
{
791
Square s = pop_lsb(b);
792
squares[size] = s ^ flipSquares;
793
pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
794
} while (b);
795
796
assert(size >= 2);
797
798
d = entry->get(stm, tbFile);
799
800
// Then we reorder the pieces to have the same sequence as the one stored
801
// in pieces[i]: the sequence that ensures the best compression.
802
for (int i = leadPawnsCnt; i < size - 1; ++i)
803
for (int j = i + 1; j < size; ++j)
804
if (d->pieces[i] == pieces[j])
805
{
806
std::swap(pieces[i], pieces[j]);
807
std::swap(squares[i], squares[j]);
808
break;
809
}
810
811
// Now we map again the squares so that the square of the lead piece is in
812
// the triangle A1-D1-D4.
813
if (file_of(squares[0]) > FILE_D)
814
for (int i = 0; i < size; ++i)
815
squares[i] = flip_file(squares[i]);
816
817
// Encode leading pawns starting with the one with minimum MapPawns[] and
818
// proceeding in ascending order.
819
if (entry->hasPawns)
820
{
821
idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
822
823
std::stable_sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
824
825
for (int i = 1; i < leadPawnsCnt; ++i)
826
idx += Binomial[i][MapPawns[squares[i]]];
827
828
goto encode_remaining; // With pawns we have finished special treatments
829
}
830
831
// In positions without pawns, we further flip the squares to ensure leading
832
// piece is below RANK_5.
833
if (rank_of(squares[0]) > RANK_4)
834
for (int i = 0; i < size; ++i)
835
squares[i] = flip_rank(squares[i]);
836
837
// Look for the first piece of the leading group not on the A1-D4 diagonal
838
// and ensure it is mapped below the diagonal.
839
for (int i = 0; i < d->groupLen[0]; ++i)
840
{
841
if (!off_A1H8(squares[i]))
842
continue;
843
844
if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C1
845
for (int j = i; j < size; ++j)
846
squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
847
break;
848
}
849
850
// Encode the leading group.
851
//
852
// Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
853
// and bK (each 0...63). The simplest way to map this position to an index
854
// is like this:
855
//
856
// index = wK * 64 * 64 + wR * 64 + bK;
857
//
858
// But this way the TB is going to have 64*64*64 = 262144 positions, with
859
// lots of positions being equivalent (because they are mirrors of each
860
// other) and lots of positions being invalid (two pieces on one square,
861
// adjacent kings, etc.).
862
// Usually the first step is to take the wK and bK together. There are just
863
// 462 ways legal and not-mirrored ways to place the wK and bK on the board.
864
// Once we have placed the wK and bK, there are 62 squares left for the wR
865
// Mapping its square from 0..63 to available squares 0..61 can be done like:
866
//
867
// wR -= (wR > wK) + (wR > bK);
868
//
869
// In words: if wR "comes later" than wK, we deduct 1, and the same if wR
870
// "comes later" than bK. In case of two same pieces like KRRvK we want to
871
// place the two Rs "together". If we have 62 squares left, we can place two
872
// Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
873
// swapped and still get the same position.)
874
//
875
// In case we have at least 3 unique pieces (including kings) we encode them
876
// together.
877
if (entry->hasUniquePieces)
878
{
879
880
int adjust1 = squares[1] > squares[0];
881
int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
882
883
// First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
884
// triangle to 0...5. There are 63 squares for second piece and 62
885
// (mapped to 0...61) for the third.
886
if (off_A1H8(squares[0]))
887
idx = (MapA1D1D4[squares[0]] * 63 + (squares[1] - adjust1)) * 62 + squares[2] - adjust2;
888
889
// First piece is on a1-h8 diagonal, second below: map this occurrence to
890
// 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
891
// to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
892
else if (off_A1H8(squares[1]))
893
idx = (6 * 63 + rank_of(squares[0]) * 28 + MapB1H1H7[squares[1]]) * 62 + squares[2]
894
- adjust2;
895
896
// First two pieces are on a1-h8 diagonal, third below
897
else if (off_A1H8(squares[2]))
898
idx = 6 * 63 * 62 + 4 * 28 * 62 + rank_of(squares[0]) * 7 * 28
899
+ (rank_of(squares[1]) - adjust1) * 28 + MapB1H1H7[squares[2]];
900
901
// All 3 pieces on the diagonal a1-h8
902
else
903
idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28 + rank_of(squares[0]) * 7 * 6
904
+ (rank_of(squares[1]) - adjust1) * 6 + (rank_of(squares[2]) - adjust2);
905
}
906
else
907
// We don't have at least 3 unique pieces, like in KRRvKBB, just map
908
// the kings.
909
idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
910
911
encode_remaining:
912
idx *= d->groupIdx[0];
913
Square* groupSq = squares + d->groupLen[0];
914
915
// Encode remaining pawns and then pieces according to square, in ascending order
916
bool remainingPawns = entry->hasPawns && entry->pawnCount[1];
917
918
while (d->groupLen[++next])
919
{
920
std::stable_sort(groupSq, groupSq + d->groupLen[next]);
921
uint64_t n = 0;
922
923
// Map down a square if "comes later" than a square in the previous
924
// groups (similar to what was done earlier for leading group pieces).
925
for (int i = 0; i < d->groupLen[next]; ++i)
926
{
927
auto f = [&](Square s) { return groupSq[i] > s; };
928
auto adjust = std::count_if(squares, groupSq, f);
929
n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
930
}
931
932
remainingPawns = false;
933
idx += n * d->groupIdx[next];
934
groupSq += d->groupLen[next];
935
}
936
937
// Now that we have the index, decompress the pair and get the score
938
return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
939
}
940
941
// Group together pieces that will be encoded together. The general rule is that
942
// a group contains pieces of the same type and color. The exception is the leading
943
// group that, in case of positions without pawns, can be formed by 3 different
944
// pieces (default) or by the king pair when there is not a unique piece apart
945
// from the kings. When there are pawns, pawns are always first in pieces[].
946
//
947
// As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
948
//
949
// The actual grouping depends on the TB generator and can be inferred from the
950
// sequence of pieces in piece[] array.
951
template<typename T>
952
void set_groups(T& e, PairsData* d, int order[], File f) {
953
954
int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
955
d->groupLen[n] = 1;
956
957
// Number of pieces per group is stored in groupLen[], for instance in KRKN
958
// the encoder will default on '111', so groupLen[] will be (3, 1).
959
for (int i = 1; i < e.pieceCount; ++i)
960
if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
961
d->groupLen[n]++;
962
else
963
d->groupLen[++n] = 1;
964
965
d->groupLen[++n] = 0; // Zero-terminated
966
967
// The sequence in pieces[] defines the groups, but not the order in which
968
// they are encoded. If the pieces in a group g can be combined on the board
969
// in N(g) different ways, then the position encoding will be of the form:
970
//
971
// g1 * N(g2) * N(g3) + g2 * N(g3) + g3
972
//
973
// This ensures unique encoding for the whole position. The order of the
974
// groups is a per-table parameter and could not follow the canonical leading
975
// pawns/pieces -> remaining pawns -> remaining pieces. In particular the
976
// first group is at order[0] position and the remaining pawns, when present,
977
// are at order[1] position.
978
bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
979
int next = pp ? 2 : 1;
980
int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
981
uint64_t idx = 1;
982
983
for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
984
if (k == order[0]) // Leading pawns or pieces
985
{
986
d->groupIdx[0] = idx;
987
idx *= e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f] : e.hasUniquePieces ? 31332 : 462;
988
}
989
else if (k == order[1]) // Remaining pawns
990
{
991
d->groupIdx[1] = idx;
992
idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
993
}
994
else // Remaining pieces
995
{
996
d->groupIdx[next] = idx;
997
idx *= Binomial[d->groupLen[next]][freeSquares];
998
freeSquares -= d->groupLen[next++];
999
}
1000
1001
d->groupIdx[n] = idx;
1002
}
1003
1004
// In Recursive Pairing each symbol represents a pair of children symbols. So
1005
// read d->btree[] symbols data and expand each one in his left and right child
1006
// symbol until reaching the leaves that represent the symbol value.
1007
uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
1008
1009
visited[s] = true; // We can set it now because tree is acyclic
1010
Sym sr = d->btree[s].get<LR::Right>();
1011
1012
if (sr == 0xFFF)
1013
return 0;
1014
1015
Sym sl = d->btree[s].get<LR::Left>();
1016
1017
if (!visited[sl])
1018
d->symlen[sl] = set_symlen(d, sl, visited);
1019
1020
if (!visited[sr])
1021
d->symlen[sr] = set_symlen(d, sr, visited);
1022
1023
return d->symlen[sl] + d->symlen[sr] + 1;
1024
}
1025
1026
uint8_t* set_sizes(PairsData* d, uint8_t* data) {
1027
1028
d->flags = *data++;
1029
1030
if (d->flags & TBFlag::SingleValue)
1031
{
1032
d->blocksNum = d->blockLengthSize = 0;
1033
d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
1034
d->minSymLen = *data++; // Here we store the single value
1035
return data;
1036
}
1037
1038
// groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
1039
// element stores the biggest index that is the tb size.
1040
uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
1041
1042
d->sizeofBlock = 1ULL << *data++;
1043
d->span = 1ULL << *data++;
1044
d->sparseIndexSize = size_t((tbSize + d->span - 1) / d->span); // Round up
1045
auto padding = number<uint8_t, LittleEndian>(data++);
1046
d->blocksNum = number<uint32_t, LittleEndian>(data);
1047
data += sizeof(uint32_t);
1048
d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
1049
// does not point out of range.
1050
d->maxSymLen = *data++;
1051
d->minSymLen = *data++;
1052
d->lowestSym = (Sym*) data;
1053
d->base64.resize(d->maxSymLen - d->minSymLen + 1);
1054
1055
// See https://en.wikipedia.org/wiki/Huffman_coding
1056
// The canonical code is ordered such that longer symbols (in terms of
1057
// the number of bits of their Huffman code) have a lower numeric value,
1058
// so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
1059
// Starting from this we compute a base64[] table indexed by symbol length
1060
// and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
1061
1062
// Implementation note: we first cast the unsigned size_t "base64.size()"
1063
// to a signed int "base64_size" variable and then we are able to subtract 2,
1064
// avoiding unsigned overflow warnings.
1065
1066
int base64_size = static_cast<int>(d->base64.size());
1067
for (int i = base64_size - 2; i >= 0; --i)
1068
{
1069
d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
1070
- number<Sym, LittleEndian>(&d->lowestSym[i + 1]))
1071
/ 2;
1072
1073
assert(d->base64[i] * 2 >= d->base64[i + 1]);
1074
}
1075
1076
// Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
1077
// than d->base64[i+1] and given the above assert condition, we ensure that
1078
// d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
1079
// and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
1080
for (int i = 0; i < base64_size; ++i)
1081
d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
1082
1083
data += base64_size * sizeof(Sym);
1084
d->symlen.resize(number<uint16_t, LittleEndian>(data));
1085
data += sizeof(uint16_t);
1086
d->btree = (LR*) data;
1087
1088
// The compression scheme used is "Recursive Pairing", that replaces the most
1089
// frequent adjacent pair of symbols in the source message by a new symbol,
1090
// reevaluating the frequencies of all of the symbol pairs with respect to
1091
// the extended alphabet, and then repeating the process.
1092
// See https://web.archive.org/web/20201106232444/http://www.larsson.dogma.net/dcc99.pdf
1093
std::vector<bool> visited(d->symlen.size());
1094
1095
for (std::size_t sym = 0; sym < d->symlen.size(); ++sym)
1096
if (!visited[sym])
1097
d->symlen[sym] = set_symlen(d, sym, visited);
1098
1099
return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
1100
}
1101
1102
uint8_t* set_dtz_map(TBTable<WDL>&, uint8_t* data, File) { return data; }
1103
1104
uint8_t* set_dtz_map(TBTable<DTZ>& e, uint8_t* data, File maxFile) {
1105
1106
e.map = data;
1107
1108
for (File f = FILE_A; f <= maxFile; ++f)
1109
{
1110
auto flags = e.get(0, f)->flags;
1111
if (flags & TBFlag::Mapped)
1112
{
1113
if (flags & TBFlag::Wide)
1114
{
1115
data += uintptr_t(data) & 1; // Word alignment, we may have a mixed table
1116
for (int i = 0; i < 4; ++i)
1117
{ // Sequence like 3,x,x,x,1,x,0,2,x,x
1118
e.get(0, f)->map_idx[i] = uint16_t((uint16_t*) data - (uint16_t*) e.map + 1);
1119
data += 2 * number<uint16_t, LittleEndian>(data) + 2;
1120
}
1121
}
1122
else
1123
{
1124
for (int i = 0; i < 4; ++i)
1125
{
1126
e.get(0, f)->map_idx[i] = uint16_t(data - e.map + 1);
1127
data += *data + 1;
1128
}
1129
}
1130
}
1131
}
1132
1133
return data += uintptr_t(data) & 1; // Word alignment
1134
}
1135
1136
// Populate entry's PairsData records with data from the just memory-mapped file.
1137
// Called at first access.
1138
template<typename T>
1139
void set(T& e, uint8_t* data) {
1140
1141
PairsData* d;
1142
1143
enum {
1144
Split = 1,
1145
HasPawns = 2
1146
};
1147
1148
assert(e.hasPawns == bool(*data & HasPawns));
1149
assert((e.key != e.key2) == bool(*data & Split));
1150
1151
data++; // First byte stores flags
1152
1153
const int sides = T::Sides == 2 && (e.key != e.key2) ? 2 : 1;
1154
const File maxFile = e.hasPawns ? FILE_D : FILE_A;
1155
1156
bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
1157
1158
assert(!pp || e.pawnCount[0]);
1159
1160
for (File f = FILE_A; f <= maxFile; ++f)
1161
{
1162
1163
for (int i = 0; i < sides; i++)
1164
*e.get(i, f) = PairsData();
1165
1166
int order[][2] = {{*data & 0xF, pp ? *(data + 1) & 0xF : 0xF},
1167
{*data >> 4, pp ? *(data + 1) >> 4 : 0xF}};
1168
data += 1 + pp;
1169
1170
for (int k = 0; k < e.pieceCount; ++k, ++data)
1171
for (int i = 0; i < sides; i++)
1172
e.get(i, f)->pieces[k] = Piece(i ? *data >> 4 : *data & 0xF);
1173
1174
for (int i = 0; i < sides; ++i)
1175
set_groups(e, e.get(i, f), order[i], f);
1176
}
1177
1178
data += uintptr_t(data) & 1; // Word alignment
1179
1180
for (File f = FILE_A; f <= maxFile; ++f)
1181
for (int i = 0; i < sides; i++)
1182
data = set_sizes(e.get(i, f), data);
1183
1184
data = set_dtz_map(e, data, maxFile);
1185
1186
for (File f = FILE_A; f <= maxFile; ++f)
1187
for (int i = 0; i < sides; i++)
1188
{
1189
(d = e.get(i, f))->sparseIndex = (SparseEntry*) data;
1190
data += d->sparseIndexSize * sizeof(SparseEntry);
1191
}
1192
1193
for (File f = FILE_A; f <= maxFile; ++f)
1194
for (int i = 0; i < sides; i++)
1195
{
1196
(d = e.get(i, f))->blockLength = (uint16_t*) data;
1197
data += d->blockLengthSize * sizeof(uint16_t);
1198
}
1199
1200
for (File f = FILE_A; f <= maxFile; ++f)
1201
for (int i = 0; i < sides; i++)
1202
{
1203
data = (uint8_t*) ((uintptr_t(data) + 0x3F) & ~0x3F); // 64 byte alignment
1204
(d = e.get(i, f))->data = data;
1205
data += d->blocksNum * d->sizeofBlock;
1206
}
1207
}
1208
1209
// If the TB file corresponding to the given position is already memory-mapped
1210
// then return its base address, otherwise, try to memory map and init it. Called
1211
// at every probe, memory map, and init only at first access. Function is thread
1212
// safe and can be called concurrently.
1213
template<TBType Type>
1214
void* mapped(TBTable<Type>& e, const Position& pos) {
1215
1216
static std::mutex mutex;
1217
1218
// Use 'acquire' to avoid a thread reading 'ready' == true while
1219
// another is still working. (compiler reordering may cause this).
1220
if (e.ready.load(std::memory_order_acquire))
1221
return e.baseAddress; // Could be nullptr if file does not exist
1222
1223
std::scoped_lock<std::mutex> lk(mutex);
1224
1225
if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock
1226
return e.baseAddress;
1227
1228
// Pieces strings in decreasing order for each color, like ("KPP","KR")
1229
std::string fname, w, b;
1230
for (PieceType pt = KING; pt >= PAWN; --pt)
1231
{
1232
w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]);
1233
b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]);
1234
}
1235
1236
fname =
1237
(e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w) + (Type == WDL ? ".rtbw" : ".rtbz");
1238
1239
uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, Type);
1240
1241
if (data)
1242
set(e, data);
1243
1244
e.ready.store(true, std::memory_order_release);
1245
return e.baseAddress;
1246
}
1247
1248
template<TBType Type, typename Ret = typename TBTable<Type>::Ret>
1249
Ret probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
1250
1251
if (pos.count<ALL_PIECES>() == 2) // KvK
1252
return Ret(WDLDraw);
1253
1254
TBTable<Type>* entry = TBTables.get<Type>(pos.material_key());
1255
1256
if (!entry || !mapped(*entry, pos))
1257
return *result = FAIL, Ret();
1258
1259
return do_probe_table(pos, entry, wdl, result);
1260
}
1261
1262
// For a position where the side to move has a winning capture it is not necessary
1263
// to store a winning value so the generator treats such positions as "don't care"
1264
// and tries to assign to it a value that improves the compression ratio. Similarly,
1265
// if the side to move has a drawing capture, then the position is at least drawn.
1266
// If the position is won, then the TB needs to store a win value. But if the
1267
// position is drawn, the TB may store a loss value if that is better for compression.
1268
// All of this means that during probing, the engine must look at captures and probe
1269
// their results and must probe the position itself. The "best" result of these
1270
// probes is the correct result for the position.
1271
// DTZ tables do not store values when a following move is a zeroing winning move
1272
// (winning capture or winning pawn move). Also, DTZ store wrong values for positions
1273
// where the best move is an ep-move (even if losing). So in all these cases set
1274
// the state to ZEROING_BEST_MOVE.
1275
template<bool CheckZeroingMoves>
1276
WDLScore search(Position& pos, ProbeState* result) {
1277
1278
WDLScore value, bestValue = WDLLoss;
1279
StateInfo st;
1280
1281
auto moveList = MoveList<LEGAL>(pos);
1282
size_t totalCount = moveList.size(), moveCount = 0;
1283
1284
for (const Move move : moveList)
1285
{
1286
if (!pos.capture(move) && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
1287
continue;
1288
1289
moveCount++;
1290
1291
pos.do_move(move, st);
1292
value = -search<false>(pos, result);
1293
pos.undo_move(move);
1294
1295
if (*result == FAIL)
1296
return WDLDraw;
1297
1298
if (value > bestValue)
1299
{
1300
bestValue = value;
1301
1302
if (value >= WDLWin)
1303
{
1304
*result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
1305
return value;
1306
}
1307
}
1308
}
1309
1310
// In case we have already searched all the legal moves we don't have to probe
1311
// the TB because the stored score could be wrong. For instance TB tables
1312
// do not contain information on position with ep rights, so in this case
1313
// the result of probe_wdl_table is wrong. Also in case of only capture
1314
// moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
1315
// return with ZEROING_BEST_MOVE set.
1316
bool noMoreMoves = (moveCount && moveCount == totalCount);
1317
1318
if (noMoreMoves)
1319
value = bestValue;
1320
else
1321
{
1322
value = probe_table<WDL>(pos, result);
1323
1324
if (*result == FAIL)
1325
return WDLDraw;
1326
}
1327
1328
// DTZ stores a "don't care" value if bestValue is a win
1329
if (bestValue >= value)
1330
return *result = (bestValue > WDLDraw || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
1331
1332
return *result = OK, value;
1333
}
1334
1335
} // namespace
1336
1337
1338
// Called at startup and after every change to
1339
// "SyzygyPath" UCI option to (re)create the various tables. It is not thread
1340
// safe, nor it needs to be.
1341
void Tablebases::init(const std::string& paths) {
1342
1343
TBTables.clear();
1344
MaxCardinality = 0;
1345
TBFile::Paths = paths;
1346
1347
if (paths.empty())
1348
return;
1349
1350
// MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
1351
int code = 0;
1352
for (Square s = SQ_A1; s <= SQ_H8; ++s)
1353
if (off_A1H8(s) < 0)
1354
MapB1H1H7[s] = code++;
1355
1356
// MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
1357
std::vector<Square> diagonal;
1358
code = 0;
1359
for (Square s = SQ_A1; s <= SQ_D4; ++s)
1360
if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
1361
MapA1D1D4[s] = code++;
1362
1363
else if (!off_A1H8(s) && file_of(s) <= FILE_D)
1364
diagonal.push_back(s);
1365
1366
// Diagonal squares are encoded as last ones
1367
for (auto s : diagonal)
1368
MapA1D1D4[s] = code++;
1369
1370
// MapKK[] encodes all the 462 possible legal positions of two kings where
1371
// the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
1372
// diagonal, the other one shall not be above the a1-h8 diagonal.
1373
std::vector<std::pair<int, Square>> bothOnDiagonal;
1374
code = 0;
1375
for (int idx = 0; idx < 10; idx++)
1376
for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
1377
if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
1378
{
1379
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
1380
if ((PseudoAttacks[KING][s1] | s1) & s2)
1381
continue; // Illegal position
1382
1383
else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
1384
continue; // First on diagonal, second above
1385
1386
else if (!off_A1H8(s1) && !off_A1H8(s2))
1387
bothOnDiagonal.emplace_back(idx, s2);
1388
1389
else
1390
MapKK[idx][s2] = code++;
1391
}
1392
1393
// Legal positions with both kings on a diagonal are encoded as last ones
1394
for (auto p : bothOnDiagonal)
1395
MapKK[p.first][p.second] = code++;
1396
1397
// Binomial[] stores the Binomial Coefficients using Pascal rule. There
1398
// are Binomial[k][n] ways to choose k elements from a set of n elements.
1399
Binomial[0][0] = 1;
1400
1401
for (int n = 1; n < 64; n++) // Squares
1402
for (int k = 0; k < 6 && k <= n; ++k) // Pieces
1403
Binomial[k][n] =
1404
(k > 0 ? Binomial[k - 1][n - 1] : 0) + (k < n ? Binomial[k][n - 1] : 0);
1405
1406
// MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
1407
// available squares when the leading one is in 's'. Moreover the pawn with
1408
// highest MapPawns[] is the leading pawn, the one nearest the edge, and
1409
// among pawns with the same file, the one with the lowest rank.
1410
int availableSquares = 47; // Available squares when lead pawn is in a2
1411
1412
// Init the tables for the encoding of leading pawns group: with 7-men TB we
1413
// can have up to 5 leading pawns (KPPPPPK).
1414
for (int leadPawnsCnt = 1; leadPawnsCnt <= 5; ++leadPawnsCnt)
1415
for (File f = FILE_A; f <= FILE_D; ++f)
1416
{
1417
// Restart the index at every file because TB table is split
1418
// by file, so we can reuse the same index for different files.
1419
int idx = 0;
1420
1421
// Sum all possible combinations for a given file, starting with
1422
// the leading pawn on rank 2 and increasing the rank.
1423
for (Rank r = RANK_2; r <= RANK_7; ++r)
1424
{
1425
Square sq = make_square(f, r);
1426
1427
// Compute MapPawns[] at first pass.
1428
// If sq is the leading pawn square, any other pawn cannot be
1429
// below or more toward the edge of sq. There are 47 available
1430
// squares when sq = a2 and reduced by 2 for any rank increase
1431
// due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
1432
if (leadPawnsCnt == 1)
1433
{
1434
MapPawns[sq] = availableSquares--;
1435
MapPawns[flip_file(sq)] = availableSquares--;
1436
}
1437
LeadPawnIdx[leadPawnsCnt][sq] = idx;
1438
idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
1439
}
1440
// After a file is traversed, store the cumulated per-file index
1441
LeadPawnsSize[leadPawnsCnt][f] = idx;
1442
}
1443
1444
// Add entries in TB tables if the corresponding ".rtbw" file exists
1445
for (PieceType p1 = PAWN; p1 < KING; ++p1)
1446
{
1447
TBTables.add({KING, p1, KING});
1448
1449
for (PieceType p2 = PAWN; p2 <= p1; ++p2)
1450
{
1451
TBTables.add({KING, p1, p2, KING});
1452
TBTables.add({KING, p1, KING, p2});
1453
1454
for (PieceType p3 = PAWN; p3 < KING; ++p3)
1455
TBTables.add({KING, p1, p2, KING, p3});
1456
1457
for (PieceType p3 = PAWN; p3 <= p2; ++p3)
1458
{
1459
TBTables.add({KING, p1, p2, p3, KING});
1460
1461
for (PieceType p4 = PAWN; p4 <= p3; ++p4)
1462
{
1463
TBTables.add({KING, p1, p2, p3, p4, KING});
1464
1465
for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1466
TBTables.add({KING, p1, p2, p3, p4, p5, KING});
1467
1468
for (PieceType p5 = PAWN; p5 < KING; ++p5)
1469
TBTables.add({KING, p1, p2, p3, p4, KING, p5});
1470
}
1471
1472
for (PieceType p4 = PAWN; p4 < KING; ++p4)
1473
{
1474
TBTables.add({KING, p1, p2, p3, KING, p4});
1475
1476
for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1477
TBTables.add({KING, p1, p2, p3, KING, p4, p5});
1478
}
1479
}
1480
1481
for (PieceType p3 = PAWN; p3 <= p1; ++p3)
1482
for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
1483
TBTables.add({KING, p1, p2, KING, p3, p4});
1484
}
1485
}
1486
1487
TBTables.info();
1488
}
1489
1490
// Probe the WDL table for a particular position.
1491
// If *result != FAIL, the probe was successful.
1492
// The return value is from the point of view of the side to move:
1493
// -2 : loss
1494
// -1 : loss, but draw under 50-move rule
1495
// 0 : draw
1496
// 1 : win, but draw under 50-move rule
1497
// 2 : win
1498
WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
1499
1500
*result = OK;
1501
return search<false>(pos, result);
1502
}
1503
1504
// Probe the DTZ table for a particular position.
1505
// If *result != FAIL, the probe was successful.
1506
// The return value is from the point of view of the side to move:
1507
// n < -100 : loss, but draw under 50-move rule
1508
// -100 <= n < -1 : loss in n ply (assuming 50-move counter == 0)
1509
// -1 : loss, the side to move is mated
1510
// 0 : draw
1511
// 1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1512
// 100 < n : win, but draw under 50-move rule
1513
//
1514
// The return value n can be off by 1: a return value -n can mean a loss
1515
// in n+1 ply and a return value +n can mean a win in n+1 ply. This
1516
// cannot happen for tables with positions exactly on the "edge" of
1517
// the 50-move rule.
1518
//
1519
// This implies that if dtz > 0 is returned, the position is certainly
1520
// a win if dtz + 50-move-counter <= 99. Care must be taken that the engine
1521
// picks moves that preserve dtz + 50-move-counter <= 99.
1522
//
1523
// If n = 100 immediately after a capture or pawn move, then the position
1524
// is also certainly a win, and during the whole phase until the next
1525
// capture or pawn move, the inequality to be preserved is
1526
// dtz + 50-move-counter <= 100.
1527
//
1528
// In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1529
// then do not accept moves leading to dtz + 50-move-counter == 100.
1530
int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
1531
1532
*result = OK;
1533
WDLScore wdl = search<true>(pos, result);
1534
1535
if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
1536
return 0;
1537
1538
// DTZ stores a 'don't care value in this case, or even a plain wrong
1539
// one as in case the best move is a losing ep, so it cannot be probed.
1540
if (*result == ZEROING_BEST_MOVE)
1541
return dtz_before_zeroing(wdl);
1542
1543
int dtz = probe_table<DTZ>(pos, result, wdl);
1544
1545
if (*result == FAIL)
1546
return 0;
1547
1548
if (*result != CHANGE_STM)
1549
return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
1550
1551
// DTZ stores results for the other side, so we need to do a 1-ply search and
1552
// find the winning move that minimizes DTZ.
1553
StateInfo st;
1554
int minDTZ = 0xFFFF;
1555
1556
for (const Move move : MoveList<LEGAL>(pos))
1557
{
1558
bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
1559
1560
pos.do_move(move, st);
1561
1562
// For zeroing moves we want the dtz of the move _before_ doing it,
1563
// otherwise we will get the dtz of the next move sequence. Search the
1564
// position after the move to get the score sign (because even in a
1565
// winning position we could make a losing capture or go for a draw).
1566
dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result)) : -probe_dtz(pos, result);
1567
1568
// If the move mates, force minDTZ to 1
1569
if (dtz == 1 && pos.checkers() && MoveList<LEGAL>(pos).size() == 0)
1570
minDTZ = 1;
1571
1572
// Convert result from 1-ply search. Zeroing moves are already accounted
1573
// by dtz_before_zeroing() that returns the DTZ of the previous move.
1574
if (!zeroing)
1575
dtz += sign_of(dtz);
1576
1577
// Skip the draws and if we are winning only pick positive dtz
1578
if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
1579
minDTZ = dtz;
1580
1581
pos.undo_move(move);
1582
1583
if (*result == FAIL)
1584
return 0;
1585
}
1586
1587
// When there are no legal moves, the position is mate: we return -1
1588
return minDTZ == 0xFFFF ? -1 : minDTZ;
1589
}
1590
1591
1592
// Use the DTZ tables to rank root moves.
1593
//
1594
// A return value false indicates that not all probes were successful.
1595
bool Tablebases::root_probe(Position& pos,
1596
Search::RootMoves& rootMoves,
1597
bool rule50,
1598
bool rankDTZ) {
1599
1600
ProbeState result = OK;
1601
StateInfo st;
1602
1603
// Obtain 50-move counter for the root position
1604
int cnt50 = pos.rule50_count();
1605
1606
// Check whether a position was repeated since the last zeroing move.
1607
bool rep = pos.has_repeated();
1608
1609
int dtz, bound = rule50 ? (MAX_DTZ / 2 - 100) : 1;
1610
1611
// Probe and rank each move
1612
for (auto& m : rootMoves)
1613
{
1614
pos.do_move(m.pv[0], st);
1615
1616
// Calculate dtz for the current move counting from the root position
1617
if (pos.rule50_count() == 0)
1618
{
1619
// In case of a zeroing move, dtz is one of -101/-1/0/1/101
1620
WDLScore wdl = -probe_wdl(pos, &result);
1621
dtz = dtz_before_zeroing(wdl);
1622
}
1623
else if ((rule50 && pos.is_draw(1)) || pos.is_repetition(1))
1624
{
1625
// In case a root move leads to a draw by repetition or 50-move rule,
1626
// we set dtz to zero. Note: since we are only 1 ply from the root,
1627
// this must be a true 3-fold repetition inside the game history.
1628
dtz = 0;
1629
}
1630
else
1631
{
1632
// Otherwise, take dtz for the new position and correct by 1 ply
1633
dtz = -probe_dtz(pos, &result);
1634
dtz = dtz > 0 ? dtz + 1 : dtz < 0 ? dtz - 1 : dtz;
1635
}
1636
1637
// Make sure that a mating move is assigned a dtz value of 1
1638
if (pos.checkers() && dtz == 2 && MoveList<LEGAL>(pos).size() == 0)
1639
dtz = 1;
1640
1641
pos.undo_move(m.pv[0]);
1642
1643
if (result == FAIL)
1644
return false;
1645
1646
// Better moves are ranked higher. Certain wins are ranked equally.
1647
// Losing moves are ranked equally unless a 50-move draw is in sight.
1648
int r = dtz > 0 ? (dtz + cnt50 <= 99 && !rep ? MAX_DTZ - (rankDTZ ? dtz : 0)
1649
: MAX_DTZ / 2 - (dtz + cnt50))
1650
: dtz < 0 ? (-dtz * 2 + cnt50 < 100 ? -MAX_DTZ - (rankDTZ ? dtz : 0)
1651
: -MAX_DTZ / 2 + (-dtz + cnt50))
1652
: 0;
1653
m.tbRank = r;
1654
1655
// Determine the score to be displayed for this move. Assign at least
1656
// 1 cp to cursed wins and let it grow to 49 cp as the positions gets
1657
// closer to a real win.
1658
m.tbScore = r >= bound ? VALUE_MATE - MAX_PLY - 1
1659
: r > 0 ? Value((std::max(3, r - (MAX_DTZ / 2 - 200)) * int(PawnValue)) / 200)
1660
: r == 0 ? VALUE_DRAW
1661
: r > -bound
1662
? Value((std::min(-3, r + (MAX_DTZ / 2 - 200)) * int(PawnValue)) / 200)
1663
: -VALUE_MATE + MAX_PLY + 1;
1664
}
1665
1666
return true;
1667
}
1668
1669
1670
// Use the WDL tables to rank root moves.
1671
// This is a fallback for the case that some or all DTZ tables are missing.
1672
//
1673
// A return value false indicates that not all probes were successful.
1674
bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, bool rule50) {
1675
1676
static const int WDL_to_rank[] = {-MAX_DTZ, -MAX_DTZ + 101, 0, MAX_DTZ - 101, MAX_DTZ};
1677
1678
ProbeState result = OK;
1679
StateInfo st;
1680
WDLScore wdl;
1681
1682
1683
// Probe and rank each move
1684
for (auto& m : rootMoves)
1685
{
1686
pos.do_move(m.pv[0], st);
1687
1688
if (pos.is_draw(1))
1689
wdl = WDLDraw;
1690
else
1691
wdl = -probe_wdl(pos, &result);
1692
1693
pos.undo_move(m.pv[0]);
1694
1695
if (result == FAIL)
1696
return false;
1697
1698
m.tbRank = WDL_to_rank[wdl + 2];
1699
1700
if (!rule50)
1701
wdl = wdl > WDLDraw ? WDLWin : wdl < WDLDraw ? WDLLoss : WDLDraw;
1702
m.tbScore = WDL_to_value[wdl + 2];
1703
}
1704
1705
return true;
1706
}
1707
1708
Config Tablebases::rank_root_moves(const OptionsMap& options,
1709
Position& pos,
1710
Search::RootMoves& rootMoves,
1711
bool rankDTZ) {
1712
Config config;
1713
1714
if (rootMoves.empty())
1715
return config;
1716
1717
config.rootInTB = false;
1718
config.useRule50 = bool(options["Syzygy50MoveRule"]);
1719
config.probeDepth = int(options["SyzygyProbeDepth"]);
1720
config.cardinality = int(options["SyzygyProbeLimit"]);
1721
1722
bool dtz_available = true;
1723
1724
// Tables with fewer pieces than SyzygyProbeLimit are searched with
1725
// probeDepth == DEPTH_ZERO
1726
if (config.cardinality > MaxCardinality)
1727
{
1728
config.cardinality = MaxCardinality;
1729
config.probeDepth = 0;
1730
}
1731
1732
if (config.cardinality >= popcount(pos.pieces()) && !pos.can_castle(ANY_CASTLING))
1733
{
1734
// Rank moves using DTZ tables
1735
config.rootInTB = root_probe(pos, rootMoves, options["Syzygy50MoveRule"], rankDTZ);
1736
1737
if (!config.rootInTB)
1738
{
1739
// DTZ tables are missing; try to rank moves using WDL tables
1740
dtz_available = false;
1741
config.rootInTB = root_probe_wdl(pos, rootMoves, options["Syzygy50MoveRule"]);
1742
}
1743
}
1744
1745
if (config.rootInTB)
1746
{
1747
// Sort moves according to TB rank
1748
std::stable_sort(
1749
rootMoves.begin(), rootMoves.end(),
1750
[](const Search::RootMove& a, const Search::RootMove& b) { return a.tbRank > b.tbRank; });
1751
1752
// Probe during search only if DTZ is not available and we are winning
1753
if (dtz_available || rootMoves[0].tbScore <= VALUE_DRAW)
1754
config.cardinality = 0;
1755
}
1756
else
1757
{
1758
// Clean up if root_probe() and root_probe_wdl() have failed
1759
for (auto& m : rootMoves)
1760
m.tbRank = 0;
1761
}
1762
1763
return config;
1764
}
1765
} // namespace Stockfish
1766
1767