Corrhist #96

Merged
rektdie merged 4 commits from corrhist into main 2025-09-03 14:22:30 +02:00
5 changed files with 102 additions and 40 deletions
Showing only changes of commit bf7adcb06b - Show all commits

No files matched your search

+41 -32
View File
@@ -9,7 +9,7 @@
void Board::Reset() { void Board::Reset() {
castlingRights = 0; castlingRights = 0;
enPassantTarget = noEPTarget; enPassantTarget = noEPTarget;
halfMoves = 0; halfMoves = 0;
fullMoves = 1; fullMoves = 1;
@@ -31,6 +31,7 @@ void Board::Reset() {
currentMoveIndex = 0; currentMoveIndex = 0;
hashKey = 0ULL; hashKey = 0ULL;
pawnKey = 0ULL;
} }
void Board::SetByFen(std::string_view fen) { void Board::SetByFen(std::string_view fen) {
@@ -88,66 +89,66 @@ void Board::SetByFen(std::string_view fen) {
std::string Board::GetFen() { std::string Board::GetFen() {
std::ostringstream fen; std::ostringstream fen;
for (int rank = 7; rank >= 0; --rank) { for (int rank = 7; rank >= 0; --rank) {
int emptyCount = 0; int emptyCount = 0;
for (int file = 0; file < 8; ++file) { for (int file = 0; file < 8; ++file) {
int square = rank * 8 + file; int square = rank * 8 + file;
const uint64_t squareBit = 1ULL << square; const uint64_t squareBit = 1ULL << square;
if (!(occupied & squareBit)) { if (!(occupied & squareBit)) {
++emptyCount; ++emptyCount;
continue; continue;
} }
if (emptyCount > 0) { if (emptyCount > 0) {
fen << emptyCount; fen << emptyCount;
emptyCount = 0; emptyCount = 0;
} }
static constexpr std::array<char, 6> pieceChars = {'p', 'n', 'b', 'r', 'q', 'k'}; static constexpr std::array<char, 6> pieceChars = {'p', 'n', 'b', 'r', 'q', 'k'};
char pieceChar = '?'; char pieceChar = '?';
for (size_t pieceType = 0; pieceType < pieceChars.size(); ++pieceType) { for (size_t pieceType = 0; pieceType < pieceChars.size(); ++pieceType) {
if (pieces[pieceType] & squareBit) { if (pieces[pieceType] & squareBit) {
pieceChar = pieceChars[pieceType]; pieceChar = pieceChars[pieceType];
break; break;
} }
} }
fen << (colors[White] & squareBit ? static_cast<char>(std::toupper(pieceChar)) : pieceChar); fen << (colors[White] & squareBit ? static_cast<char>(std::toupper(pieceChar)) : pieceChar);
} }
if (emptyCount > 0) { if (emptyCount > 0) {
fen << emptyCount; fen << emptyCount;
} }
if (rank > 0) { if (rank > 0) {
fen << '/'; fen << '/';
} }
} }
fen << ' ' << (sideToMove ? 'b' : 'w'); fen << ' ' << (sideToMove ? 'b' : 'w');
fen << ' '; fen << ' ';
bool hasCastlingRights = false; bool hasCastlingRights = false;
const std::array<std::pair<uint8_t, char>, 4> castlingOptions = { const std::array<std::pair<uint8_t, char>, 4> castlingOptions = {
{{whiteKingRight, 'K'}, {whiteQueenRight, 'Q'}, {blackKingRight, 'k'}, {blackQueenRight, 'q'}} {{whiteKingRight, 'K'}, {whiteQueenRight, 'Q'}, {blackKingRight, 'k'}, {blackQueenRight, 'q'}}
}; };
for (const auto& [right, symbol] : castlingOptions) { for (const auto& [right, symbol] : castlingOptions) {
if (castlingRights & right) { if (castlingRights & right) {
fen << symbol; fen << symbol;
hasCastlingRights = true; hasCastlingRights = true;
} }
} }
if (!hasCastlingRights) { if (!hasCastlingRights) {
fen << '-'; fen << '-';
} }
fen << ' '; fen << ' ';
if (enPassantTarget == noEPTarget) { if (enPassantTarget == noEPTarget) {
fen << '-'; fen << '-';
@@ -156,11 +157,11 @@ std::string Board::GetFen() {
const int rank = enPassantTarget / 8; const int rank = enPassantTarget / 8;
fen << static_cast<char>('a' + file) << (rank + 1); fen << static_cast<char>('a' + file) << (rank + 1);
} }
fen << ' ' << halfMoves; fen << ' ' << halfMoves;
fen << ' ' << fullMoves; fen << ' ' << fullMoves;
return fen.str(); return fen.str();
} }
@@ -271,6 +272,10 @@ void Board::SetPiece(int piece, int square, bool color) {
occupied.SetBit(square); occupied.SetBit(square);
hashKey ^= UTILS::zKeys[color][piece][square]; hashKey ^= UTILS::zKeys[color][piece][square];
if (piece == Pawn) {
pawnKey ^= UTILS::zKeys[color][Pawn][square];
}
} }
void Board::RemovePiece(int piece, int square, bool color) { void Board::RemovePiece(int piece, int square, bool color) {
@@ -279,6 +284,10 @@ void Board::RemovePiece(int piece, int square, bool color) {
occupied.PopBit(square); occupied.PopBit(square);
hashKey ^= UTILS::zKeys[color][piece][square]; hashKey ^= UTILS::zKeys[color][piece][square];
if (piece == Pawn) {
pawnKey ^= UTILS::zKeys[color][Pawn][square];
}
} }
// Updates castling rights // Updates castling rights
@@ -322,23 +331,23 @@ bool Board::MakeMove(Move move) {
// Null Move // Null Move
if (!move) { if (!move) {
int newEpTarget = noEPTarget; int newEpTarget = noEPTarget;
sideToMove = !sideToMove; sideToMove = !sideToMove;
hashKey ^= UTILS::zSide; hashKey ^= UTILS::zSide;
if (enPassantTarget != noEPTarget) { if (enPassantTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; hashKey ^= UTILS::zEnPassant[enPassantTarget % 8];
} }
if (newEpTarget != noEPTarget) { if (newEpTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; hashKey ^= UTILS::zEnPassant[newEpTarget % 8];
} }
enPassantTarget = newEpTarget; enPassantTarget = newEpTarget;
return true; return true;
} }
int newEpTarget = noEPTarget; int newEpTarget = noEPTarget;
int attackerPiece = GetPieceType(move.MoveFrom()); int attackerPiece = GetPieceType(move.MoveFrom());
@@ -397,7 +406,7 @@ bool Board::MakeMove(Move move) {
case kingCastle: case kingCastle:
{ {
int rookSquare = attackerColor ? h8 : h1; int rookSquare = attackerColor ? h8 : h1;
// Removing rook from old position // Removing rook from old position
RemovePiece(Rook, rookSquare, attackerColor); RemovePiece(Rook, rookSquare, attackerColor);
@@ -448,7 +457,7 @@ bool Board::MakeMove(Move move) {
sideToMove = !sideToMove; sideToMove = !sideToMove;
if (InCheck()) { if (InCheck()) {
*this = save; *this = save;
return false; return false;
} }
sideToMove = !sideToMove; sideToMove = !sideToMove;
@@ -458,7 +467,7 @@ bool Board::MakeMove(Move move) {
} else { } else {
halfMoves++; halfMoves++;
} }
positionIndex++; positionIndex++;
return true; return true;
@@ -513,16 +522,16 @@ void Board::ResetAccPair() {
Bitboard Board::AttacksTo(int square, Bitboard occupancy) { Bitboard Board::AttacksTo(int square, Bitboard occupancy) {
Bitboard attacks; Bitboard attacks;
// Pawn attacks // Pawn attacks
// Opponent attacks // Opponent attacks
attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]); attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]);
// Own piece attacks // Own piece attacks
attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]); attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]);
// Knight // Knight
attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]); attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]);
// King // King
+2 -1
View File
@@ -40,6 +40,7 @@ public:
int fullMoves = 1; int fullMoves = 1;
U64 hashKey = 0ULL; U64 hashKey = 0ULL;
U64 pawnKey = 0ULL;
void Reset(); void Reset();
void SetByFen(std::string_view fen); void SetByFen(std::string_view fen);
@@ -56,7 +57,7 @@ public:
int GetPieceType(int square); int GetPieceType(int square);
int GetPieceColor(int square); int GetPieceColor(int square);
bool InCheck(); bool InCheck();
void SetPiece(int piece, int square, bool color); void SetPiece(int piece, int square, bool color);
+21 -2
View File
@@ -4,6 +4,7 @@
#include <cmath> #include <cmath>
#include "datagen.h" #include "datagen.h"
#include "benchmark.h" #include "benchmark.h"
#include "types.h"
namespace SEARCH { namespace SEARCH {
@@ -42,6 +43,14 @@ int16_t ContHistory::GetTwoPly(Board& board, Move& move, SearchContext* ctx, int
return ctx->conthist[otherColor][prevType][prevTo][board.sideToMove][pieceType][to]; return ctx->conthist[otherColor][prevType][prevTo][board.sideToMove][pieceType][to];
} }
static int AdjustEval(Board &board, SearchContext* ctx, int eval) {
int pawnHist = ctx->corrhist.GetPawnHist(board);
int mateFound = MATE_SCORE - MAX_PLY;
return std::clamp(eval + pawnHist / CORRHIST_GRAIN, -mateFound + 1, mateFound - 1);
}
static int ScoreMove(Board &board, Move &move, int ply, SearchContext* ctx) { static int ScoreMove(Board &board, Move &move, int ply, SearchContext* ctx) {
TTEntry current = ctx->TT.GetRawEntry(board.hashKey); TTEntry current = ctx->TT.GetRawEntry(board.hashKey);
if (current.hashKey == board.hashKey && current.bestMove == move) { if (current.hashKey == board.hashKey && current.bestMove == move) {
@@ -270,7 +279,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
if (ply > ctx->seldepth) if (ply > ctx->seldepth)
ctx->seldepth = ply; ctx->seldepth = ply;
int bestScore = NNUE::net.Evaluate(board); int bestScore = AdjustEval(board, ctx, NNUE::net.Evaluate(board));
ctx->ss[ply].eval = bestScore; ctx->ss[ply].eval = bestScore;
if (!ctx->excluded) { if (!ctx->excluded) {
@@ -382,7 +391,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (depth <= 0) return Quiescence<mode>(board, alpha, beta, ply, ctx); if (depth <= 0) return Quiescence<mode>(board, alpha, beta, ply, ctx);
const int staticEval = NNUE::net.Evaluate(board); const int staticEval = AdjustEval(board, ctx, NNUE::net.Evaluate(board));
ctx->ss[ply].eval = staticEval; ctx->ss[ply].eval = staticEval;
const bool improving = [&] const bool improving = [&]
@@ -649,6 +658,16 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ctx->searchStopped) return 0; if (ctx->searchStopped) return 0;
if (!ctx->excluded) if (!ctx->excluded)
if (!board.InCheck() && (results.bestMove.IsQuiet())
&& !(nodeType == CutNode && results.score <= staticEval)
&& !(nodeType == AllNode && results.score >= staticEval)) {
int corrHistBonus = std::clamp(results.score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT);
ctx->corrhist.UpdatePawnHist(board, depth, corrHistBonus);
}
ctx->TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove); ctx->TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove);
return results; return results;
} }
+37 -5
View File
@@ -23,6 +23,12 @@ constexpr int MAX_DEPTH = 128;
constexpr int MAX_PLY = 512; constexpr int MAX_PLY = 512;
constexpr int MAX_HISTORY = 16384; constexpr int MAX_HISTORY = 16384;
constexpr int CORRHIST_WEIGHT_SCALE = 256;
constexpr int CORRHIST_GRAIN = 256;
constexpr int CORRHIST_LIMIT = 1024;
constexpr int CORRHIST_SIZE = 16384;
constexpr int CORRHIST_MAX = 16384;
constexpr int32_t ScoreNone = -255000; constexpr int32_t ScoreNone = -255000;
constexpr int inf = 100000; constexpr int inf = 100000;
@@ -35,6 +41,30 @@ constexpr std::array<int, 6> SEEPieceValues = {
void InitLMRTable(); void InitLMRTable();
class SearchContext; class SearchContext;
class CorrHist {
private:
// indexed by [stm][key]
MultiArray<int, 2, CORRHIST_SIZE> pawnHist;
public:
void UpdatePawnHist(Board& board, int depth, int diff) {
int* entry = &pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE];
const int scaledDiff = diff * CORRHIST_GRAIN;
const int newWeight = 4 * std::min(depth + 1, 16);
*entry = (*entry * (CORRHIST_WEIGHT_SCALE - newWeight) + scaledDiff * newWeight) / CORRHIST_WEIGHT_SCALE;
*entry = std::clamp(*entry, -CORRHIST_MAX, CORRHIST_MAX);
}
int GetPawnHist(Board& board) {
return pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE];
}
void ClearPawnHist() {
std::fill(&pawnHist[0][0], &pawnHist[0][0] + sizeof(pawnHist) / sizeof(int), 0);
}
};
class ContHistory { class ContHistory {
private: private:
// indexed by [other color][prev move piece][stm][prev move to][piece][to] // indexed by [other color][prev move piece][stm][prev move to][piece][to]
@@ -50,7 +80,7 @@ public:
void Clear() { void Clear() {
std::fill(&contHistMoves[0][0][0][0][0][0], &contHistMoves[0][0][0][0][0][0] + sizeof(contHistMoves) / sizeof(int16_t), 0); std::fill(&contHistMoves[0][0][0][0][0][0], &contHistMoves[0][0][0][0][0][0] + sizeof(contHistMoves) / sizeof(int16_t), 0);
} }
int16_t GetOnePly(Board& board, Move& move, SearchContext* ctx, int ply); int16_t GetOnePly(Board& board, Move& move, SearchContext* ctx, int ply);
int16_t GetTwoPly(Board& board, Move& move, SearchContext* ctx, int ply); int16_t GetTwoPly(Board& board, Move& move, SearchContext* ctx, int ply);
@@ -65,7 +95,7 @@ private:
public: public:
void Update(bool stm, Move move, int bonus) { void Update(bool stm, Move move, int bonus) {
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY); int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
historyMoves[stm][move.MoveFrom()][move.MoveTo()] += historyMoves[stm][move.MoveFrom()][move.MoveTo()] +=
clampedBonus - historyMoves[stm][move.MoveFrom()][move.MoveTo()] * std::abs(clampedBonus) / MAX_HISTORY; clampedBonus - historyMoves[stm][move.MoveFrom()][move.MoveTo()] * std::abs(clampedBonus) / MAX_HISTORY;
} }
@@ -96,12 +126,12 @@ public:
length[ply] = length[ply + 1]; length[ply] = length[ply + 1];
} }
void Print(int n) { void Print(int n) {
for (int i = 0; i < length[n]; i++) { for (int i = 0; i < length[n]; i++) {
table[n][i].PrintMove(); table[n][i].PrintMove();
std::cout << ' '; std::cout << ' ';
} }
} }
void Clear() { void Clear() {
@@ -128,13 +158,14 @@ public:
int seldepth = 0; int seldepth = 0;
Move excluded = Move(); Move excluded = Move();
bool doingNullMove = false; bool doingNullMove = false;
bool searchStopped = false; bool searchStopped = false;
PVLine pvLine; PVLine pvLine;
History history; History history;
ContHistory conthist; ContHistory conthist;
CorrHist corrhist;
std::array<std::array<int, MAX_PLY>, 2> killerMoves{}; std::array<std::array<int, MAX_PLY>, 2> killerMoves{};
@@ -150,6 +181,7 @@ public:
pvLine.Clear(); pvLine.Clear();
history.Clear(); history.Clear();
conthist.Clear(); conthist.Clear();
corrhist.ClearPawnHist();
TT.Clear(); TT.Clear();
sw.Restart(); sw.Restart();
killerMoves = {}; killerMoves = {};
+1
View File
@@ -193,6 +193,7 @@ void UCILoop(Board &board) {
ctx->killerMoves = {}; ctx->killerMoves = {};
ctx->history.Clear(); ctx->history.Clear();
ctx->conthist.Clear(); ctx->conthist.Clear();
ctx->corrhist.ClearPawnHist();
ctx->positionHistory = {}; ctx->positionHistory = {};
ctx->ss = {}; ctx->ss = {};