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