Lazy smp #145

Merged
rektdie merged 4 commits from lazy-smp into main 2026-02-25 09:02:30 +01:00
10 changed files with 261 additions and 48 deletions

No files matched your search

+2
View File
@@ -64,7 +64,9 @@ constexpr std::array<std::string_view, 50> fenPositions = {
void RunBenchmark() {
Board board;
TTable BenchTT;
auto ctx = std::make_unique<SearchContext>();
ctx->TT = &BenchTT;
Stopwatch sw;
for (int i = 0; i < fenPositions.size(); i++) {
+185
View File
@@ -726,3 +726,188 @@ bool Board::IsLegal(Move &move) {
return (rayBetween(kingSquare, checkerSquare) | checkers).IsSet(to);
}
bool Board::IsPseudoLegal(Move &move) {
if (!move) return true;
const int from = move.MoveFrom();
const int to = move.MoveTo();
const int flag = move.GetFlags();
// basic bounds
if ((unsigned)from >= 64u || (unsigned)to >= 64u) return false;
const int us = sideToMove;
const int them = !sideToMove;
const int movingPiece = GetPieceType(from);
if (movingPiece == nullPieceType) return false;
if (!colors[us].IsSet(from)) return false;
if (colors[us].IsSet(to)) return false;
const bool isCapture = move.IsCapture();
const int targetPiece = GetPieceType(to);
// capture consistency (except EP which captures "behind")
if (flag == capture) {
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (isCapture && flag != epCapture) {
// promo-capture also lands on occupied enemy square
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (!isCapture) {
// quiet moves must not land on occupied square
if (occupied.IsSet(to)) {
// except castling (king lands on empty anyway)
if (flag != kingCastle && flag != queenCastle) return false;
}
}
const int fromFile = from & 7;
const int toFile = to & 7;
const int fromRank = from >> 3;
const int toRank = to >> 3;
const int dir = us ? south : north;
auto isOneStepPawnPush = [&] {
return to == from + dir && !occupied.IsSet(to);
};
auto isPawnCaptureTo = [&] {
// diagonal one step forward
return (to == from + dir - 1 && toFile == fromFile - 1)
|| (to == from + dir + 1 && toFile == fromFile + 1);
};
// handle specials by flag first
switch (flag) {
case quiet:
case capture:
break;
case doublePawnPush: {
if (movingPiece != Pawn) return false;
// from must be on starting rank
if (!us) { // white
if (fromRank != 1) return false;
} else { // black
if (fromRank != 6) return false;
}
const int mid = from + dir;
if (to != from + 2 * dir) return false;
if (occupied.IsSet(mid) || occupied.IsSet(to)) return false;
return true;
}
case epCapture: {
if (movingPiece != Pawn) return false;
if (enPassantTarget == noEPTarget) return false;
if (to != enPassantTarget) return false;
if (!isPawnCaptureTo()) return false;
// target square is empty, captured pawn is behind to
const int capSq = to - dir;
if (!colors[them].IsSet(capSq)) return false;
if (GetPieceType(capSq) != Pawn) return false;
if (occupied.IsSet(to)) return false;
return true;
}
case kingCastle:
case queenCastle: {
if (movingPiece != King) return false;
const int kingSquare = (colors[us] & pieces[King]).getLS1BIndex();
if (from != kingSquare) return false;
const int kingRight = us ? blackKingRight : whiteKingRight;
const int queenRight = us ? blackQueenRight : whiteQueenRight;
if (flag == kingCastle) {
if (!(castlingRights & kingRight)) return false;
const U64 KingSide = us ? 0xf000000000000000ULL : 0xf0ULL;
const U64 mask = us ? 0x7000000000000000ULL : 0x70ULL;
const int targetSq = us ? g8 : g1;
if (to != targetSq) return false;
// must be exactly king+rook on that side and no attacked transit squares
if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
} else {
if (!(castlingRights & queenRight)) return false;
const U64 QueenSide = us ? 0x1f00000000000000ULL : 0x1fULL;
const U64 mask = us ? 0x1c00000000000000ULL : 0x1cULL;
const int targetSq = us ? c8 : c1;
if (to != targetSq) return false;
if ((Bitboard(QueenSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
}
}
default:
// promotions (quiet + capture)
if (!move.IsPromo()) return false;
if (movingPiece != Pawn) return false;
// must land on last rank
if (!us) {
if (toRank != 7) return false;
} else {
if (toRank != 0) return false;
}
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
if (!colors[them].IsSet(to)) return false;
} else {
if (!isOneStepPawnPush()) return false;
}
return true;
}
// normal piece movement checks for quiet/capture (non-special)
switch (movingPiece) {
case Pawn: {
// non-promo pawns cannot land on last rank
if (!us) { if (toRank == 7) return false; }
else { if (toRank == 0) return false; }
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
// (regular capture already checked occupancy/enemy above)
return true;
} else {
return isOneStepPawnPush();
}
}
case Knight:
return (MOVEGEN::knightAttacks[from] & Bitboard::GetSquare(to)) != 0;
case Bishop: {
Bitboard att = MOVEGEN::getBishopAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case Rook: {
Bitboard att = MOVEGEN::getRookAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case Queen: {
Bitboard att = MOVEGEN::getBishopAttack(from, occupied) | MOVEGEN::getRookAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case King:
return (MOVEGEN::kingAttacks[from] & Bitboard::GetSquare(to)) != 0;
default:
return false;
}
}
+1
View File
@@ -80,4 +80,5 @@ public:
Bitboard CalcPinned(bool color);
bool IsLegal(Move &move);
bool IsPseudoLegal(Move &move);
};
+1 -1
View File
@@ -40,7 +40,7 @@ public:
case TT: {
stage = Rest;
if (ttMove)
if (ttMove && board.IsPseudoLegal(ttMove))
return ttMove;
break;
}
+31 -28
View File
@@ -207,18 +207,18 @@ static bool ShouldStop(SearchContext* ctx) {
if constexpr (mode == normal) {
if (ctx->nodes % 1024 == 0) {
if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) {
ctx->searchStopped = true;
searchStopped = true;
return true;
}
}
} else if constexpr (mode == nodesMode) {
if (ctx->nodes > ctx->nodesToGo) {
ctx->searchStopped = true;
searchStopped = true;
return true;
}
} else if constexpr (mode == datagen) {
if (ctx->nodes > DATAGEN::HARD_NODES) {
ctx->searchStopped = true;
searchStopped = true;
return true;
}
}
@@ -241,7 +241,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
TTEntry entry;
if (!ctx->excluded) {
entry = ctx->TT.GetEntry(board.hashKey);
entry = ctx->TT->GetEntry(board.hashKey);
if (entry.hashKey == board.hashKey) {
bestScore = entry.score;
}
@@ -293,13 +293,13 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
ctx->TT.PrefetchEntry(copy.hashKey);
ctx->TT->PrefetchEntry(copy.hashKey);
int score = -Quiescence<isPV, mode>(copy, -beta, -alpha, ply + 1, ctx).score;
if (score >= beta) {
if (!ctx->excluded) {
ctx->TT.WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
}
return score;
}
@@ -314,9 +314,9 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
}
results.score = bestScore;
if (ctx->searchStopped) return 0;
if (searchStopped) return 0;
if (!ctx->excluded) {
ctx->TT.WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv);
ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv);
}
return results;
}
@@ -338,7 +338,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
TTEntry entry;
if (!ctx->excluded)
entry = ctx->TT.GetEntry(board.hashKey);
entry = ctx->TT->GetEntry(board.hashKey);
const bool ttHit = entry.hashKey == board.hashKey;
const bool ttpv = isPV | entry.ttpv;
@@ -406,11 +406,11 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
const int reduction = 4 + improving + depth / 3;
ctx->TT.PrefetchEntry(copy.hashKey);
ctx->TT->PrefetchEntry(copy.hashKey);
int score = -PVS<false, mode>(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score;
if (ctx->searchStopped) return 0;
if (searchStopped) return 0;
if (score >= beta) {
if (depth <= 14 || ctx->minNmpPly > 0) {
return score > MATE_SCORE - MAX_DEPTH ? beta : score;
@@ -469,10 +469,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ply + 1, ctx, !cutnode).score;
}
if (ctx->searchStopped) return 0;
if (searchStopped) return 0;
if (score >= probcutBeta) {
ctx->TT.WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv);
ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv);
return score;
}
@@ -551,7 +551,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
ctx->TT.PrefetchEntry(copy.hashKey);
ctx->TT->PrefetchEntry(copy.hashKey);
int extension = 0;
@@ -640,7 +640,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch;
}
if (ctx->searchStopped) return 0;
if (searchStopped) return 0;
if (currMove != 0 && currMove.IsQuiet()) {
seenQuiets[seenQuietsCount] = currMove;
@@ -732,7 +732,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
if (!ctx->excluded)
ctx->TT.WriteEntry(board.hashKey, depth, score, CutNode, currMove, ttpv);
ctx->TT->WriteEntry(board.hashKey, depth, score, CutNode, currMove, ttpv);
return score;
}
@@ -754,7 +754,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
}
if (ctx->searchStopped) return 0;
if (searchStopped) return 0;
if (!ctx->excluded) {
if (!board.InCheck() && ((results.bestMove.IsQuiet() || !results.bestMove))
@@ -765,7 +765,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
}
ctx->TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove, ttpv);
ctx->TT->WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove, ttpv);
}
return results;
}
@@ -824,7 +824,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
double nodeScaling = 1;
if (!UCIEnabled && (mode == normal || mode == nodesMode)) {
if (!UCIEnabled && ctx->doPrint && (mode == normal || mode == nodesMode)) {
std::cout << termcolor::bold;
std::cout << std::setw(6) << std::left << "Depth"
<< std::setw(10) << std::right << "Time"
@@ -864,7 +864,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
aw.Set(currentResults.score);
if (ctx->searchStopped) {
if (searchStopped) {
break;
} else {
if (currentResults.bestMove) {
@@ -872,17 +872,18 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
}
if constexpr (mode == normal || mode == nodesMode) {
PrintSearchInfo(ctx, safeResults, depth, elapsed);
if (ctx->doPrint)
PrintSearchInfo(ctx, safeResults, depth, elapsed);
if constexpr (mode == normal) {
if (ctx->sw.GetElapsedMS() >= softTime) {
ctx->searchStopped = true;
searchStopped = true;
break;
}
}
} else if constexpr (mode == datagen) {
if (ctx->nodes >= DATAGEN::SOFT_NODES) {
ctx->searchStopped = true;
searchStopped = true;
break;
}
}
@@ -894,7 +895,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
template <searchMode mode>
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) {
ctx->searchStopped = false;
searchStopped = false;
ctx->seldepth = 0;
ctx->nodesTable = {};
if constexpr (mode != bench) {
@@ -910,9 +911,11 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c
if constexpr (mode != normal && mode != nodesMode) return results;
std::cout << "bestmove ";
results.bestMove.PrintMove();
std::cout << std::endl;
if (ctx->doPrint) {
std::cout << "bestmove ";
results.bestMove.PrintMove();
std::cout << std::endl;
}
return results;
}
@@ -957,7 +960,7 @@ void PrintSearchInfo(SearchContext* ctx, SearchResults& results, int depth, int
}
std::cout << " nodes " << ctx->nodes << " nps " << int(ctx->nodes/ctx->sw.GetElapsedSec());
std::cout << " hashfull " << ctx->TT.GetUsedPercentage();
std::cout << " hashfull " << ctx->TT->GetUsedPercentage();
std::cout << " pv ";
ctx->pvLine.Print(0, depth % 2 == 0);
std::cout << std::endl;
+3 -3
View File
@@ -207,6 +207,8 @@ public:
class SearchContext {
public:
bool doPrint = false;
U64 nodes = 0;
U64 nodesToGo = 0;
int timeToSearch = 0;
@@ -218,7 +220,6 @@ public:
Move excluded = Move();
int minNmpPly = 0;
bool searchStopped = false;
PVLine pvLine;
History history;
@@ -230,7 +231,7 @@ public:
std::vector<U64> positionHistory;
TTable TT;
TTable* TT = &SharedTT;
std::array<Stack, MAX_DEPTH> ss{};
@@ -242,7 +243,6 @@ public:
conthist.Clear();
corrhist.Clear();
capthist.Clear();
TT.Clear();
sw.Restart();
killerMoves = {};
ss = {};
+3 -1
View File
@@ -1,5 +1,7 @@
#include "tt.h"
TTable SharedTT;
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) {
TTBucket *bucket = &table[hashKey % table.size()];
TTEntry *current = nullptr;
@@ -22,4 +24,4 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b
current->depth = depth;
current->bestMove = bestMove;
current->ttpv = ttpv;
}
}
+2
View File
@@ -96,3 +96,5 @@ public:
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv);
};
extern TTable SharedTT;
+29 -15
View File
@@ -91,17 +91,19 @@ static double ReadParam(const std::string& param, const std::string &command) {
template <SEARCH::searchMode mode>
static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) {
SEARCH::SearchPosition<mode>(*board, params, ctx);
delete ctx;
}
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx) {
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
std::thread searchThread;
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
if (id == 0)
ctxCopy->doPrint = true;
if (params.nodes) {
searchThread = std::thread(ThreadFunc<SEARCH::nodesMode>, &board, params, ctx);
searchThread = std::thread(ThreadFunc<SEARCH::nodesMode>, &board, params, ctxCopy);
} else {
searchThread = std::thread(ThreadFunc<SEARCH::normal>, &board, params, ctx);
searchThread = std::thread(ThreadFunc<SEARCH::normal>, &board, params, ctxCopy);
}
searchThread.detach();
}
@@ -109,24 +111,29 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
// Unix/Linux implementation using pthread
template <SEARCH::searchMode mode>
static void* ThreadFunc(void* arg) {
auto* tup = static_cast<std::tuple<Board*, SearchParams, SEARCH::SearchContext*>*>(arg);
SEARCH::SearchPosition<mode>(*std::get<0>(*tup), std::get<1>(*tup), std::get<2>(*tup));
auto* tup = static_cast<std::tuple<Board, SearchParams, SEARCH::SearchContext*>*>(arg);
SEARCH::SearchContext* ctx = std::get<2>(*tup);
SEARCH::SearchPosition<mode>(std::get<0>(*tup), std::get<1>(*tup), ctx);
delete ctx;
delete tup;
return nullptr;
}
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx) {
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
pthread_t thread;
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
if (id == 0)
ctxCopy->doPrint = true;
if (params.nodes) {
auto* arg = new std::tuple<Board*, SearchParams, SEARCH::SearchContext*>(&board, params, ctx);
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
} else {
auto* arg = new std::tuple<Board*, SearchParams, SEARCH::SearchContext*>(&board, params, ctx);
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
}
@@ -153,13 +160,20 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c
params.btime = 99999999;
}
StartSearchThread(board, params, ctx);
for (int i = 0; i < threads; i++) {
StartSearchThread(board, params, ctx, i);
}
}
static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
if (command.find("Hash") != std::string::npos) {
U64 hashSize = (ReadParam("value", command) * 1000000ULL) / sizeof(TTEntry);
ctx->TT.Resize(hashSize);
ctx->TT->Resize(hashSize);
return;
}
if (command.find("Threads") != std::string::npos) {
threads = ReadParam("value", command);
return;
}
@@ -209,7 +223,7 @@ static void PrintEngineInfo() {
std::cout << "id name Eleanor v3.0" << std::endl;
std::cout << "id author rektdie" << std::endl;
std::cout << "option name Hash type spin default 8 min 1 max 1024" << std::endl;
std::cout << "option name Threads type spin default 1 min 1 max 1" << std::endl;
std::cout << "option name Threads type spin default 1 min 1 max 512" << std::endl;
#ifdef TUNING
PrintTunablesUCI();
@@ -245,7 +259,7 @@ void UCILoop(Board &board) {
board.SetByFen(StartingFen);
// Clearing
ctx->TT.Clear();
ctx->TT->Clear();
ctx->killerMoves = {};
ctx->history.Clear();
@@ -272,7 +286,7 @@ void UCILoop(Board &board) {
// parse UCI "stop" command
if (input.find("stop") != std::string::npos) {
// stop the loop
ctx->searchStopped = true;
searchStopped = true;
continue;
}
+4
View File
@@ -3,6 +3,8 @@
#include "board.h"
inline bool UCIEnabled = false;
inline int threads = 1;
inline bool searchStopped = false;
class SearchParams {
public:
@@ -13,6 +15,8 @@ public:
int movesToGo = 0;
int nodes = 0;
int threads = 1;
SearchParams(){}
};