From eac21b424a58cd996f4355433a83bbae94bef1a8 Mon Sep 17 00:00:00 2001 From: rektdie Date: Tue, 24 Feb 2026 23:27:30 +0100 Subject: [PATCH 1/4] old crashing lazy-smp | bench 1801941 --- source/benchmark.cpp | 2 ++ source/search.cpp | 59 +++++++++++++++++++++++--------------------- source/search.h | 6 ++--- source/tt.cpp | 4 ++- source/tt.h | 2 ++ source/uci.cpp | 44 ++++++++++++++++++++++----------- source/uci.h | 4 +++ 7 files changed, 74 insertions(+), 47 deletions(-) diff --git a/source/benchmark.cpp b/source/benchmark.cpp index 2e0b73e..8f26ea9 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -64,7 +64,9 @@ constexpr std::array fenPositions = { void RunBenchmark() { Board board; + TTable BenchTT; auto ctx = std::make_unique(); + ctx->TT = &BenchTT; Stopwatch sw; for (int i = 0; i < fenPositions.size(); i++) { diff --git a/source/search.cpp b/source/search.cpp index 0ee8e1e..a6c5602 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -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(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(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 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; diff --git a/source/search.h b/source/search.h index 6592d95..3fd3db5 100644 --- a/source/search.h +++ b/source/search.h @@ -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 positionHistory; - TTable TT; + TTable* TT = &SharedTT; std::array ss{}; @@ -242,7 +243,6 @@ public: conthist.Clear(); corrhist.Clear(); capthist.Clear(); - TT.Clear(); sw.Restart(); killerMoves = {}; ss = {}; diff --git a/source/tt.cpp b/source/tt.cpp index 0468905..2eaa1a2 100644 --- a/source/tt.cpp +++ b/source/tt.cpp @@ -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; -} +} \ No newline at end of file diff --git a/source/tt.h b/source/tt.h index 83a227b..48861ab 100644 --- a/source/tt.h +++ b/source/tt.h @@ -96,3 +96,5 @@ public: void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv); }; + +extern TTable SharedTT; \ No newline at end of file diff --git a/source/uci.cpp b/source/uci.cpp index 5da33ae..5b222b1 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -91,17 +91,19 @@ static double ReadParam(const std::string& param, const std::string &command) { template static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) { SEARCH::SearchPosition(*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, &board, params, ctx); + searchThread = std::thread(ThreadFunc, &board, params, ctxCopy); } else { - searchThread = std::thread(ThreadFunc, &board, params, ctx); + searchThread = std::thread(ThreadFunc, &board, params, ctxCopy); } - searchThread.detach(); } @@ -109,24 +111,29 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC // Unix/Linux implementation using pthread template static void* ThreadFunc(void* arg) { - auto* tup = static_cast*>(arg); - SEARCH::SearchPosition(*std::get<0>(*tup), std::get<1>(*tup), std::get<2>(*tup)); + auto* tup = static_cast*>(arg); + SEARCH::SearchContext* ctx = std::get<2>(*tup); + SEARCH::SearchPosition(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, params, ctx); + auto* arg = new std::tuple(board, params, ctxCopy); pthread_create(&thread, &attr, ThreadFunc, arg); } else { - auto* arg = new std::tuple(&board, params, ctx); + auto* arg = new std::tuple(board, params, ctxCopy); pthread_create(&thread, &attr, ThreadFunc, 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; } diff --git a/source/uci.h b/source/uci.h index 48cebb5..21fb131 100644 --- a/source/uci.h +++ b/source/uci.h @@ -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(){} }; -- 2.47.3 From 64b2e3d9b143e901386231e48a0ec4eed92479ec Mon Sep 17 00:00:00 2001 From: rektdie Date: Tue, 24 Feb 2026 23:34:26 +0100 Subject: [PATCH 2/4] maybe fixed crashes | bench 1801941 --- source/search.cpp | 24 ++++++++++++------------ source/tt.cpp | 4 ++-- source/tt.h | 11 ++++++----- source/uci.cpp | 46 ++++++++++++++++++++++++++++++++++++++-------- source/uci.h | 3 ++- 5 files changed, 60 insertions(+), 28 deletions(-) diff --git a/source/search.cpp b/source/search.cpp index a6c5602..824c031 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -207,18 +207,18 @@ static bool ShouldStop(SearchContext* ctx) { if constexpr (mode == normal) { if (ctx->nodes % 1024 == 0) { if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) { - searchStopped = true; + searchStopped.store(true, std::memory_order_relaxed); return true; } } } else if constexpr (mode == nodesMode) { if (ctx->nodes > ctx->nodesToGo) { - searchStopped = true; + searchStopped.store(true, std::memory_order_relaxed); return true; } } else if constexpr (mode == datagen) { if (ctx->nodes > DATAGEN::HARD_NODES) { - searchStopped = true; + searchStopped.store(true, std::memory_order_relaxed); return true; } } @@ -314,7 +314,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear } results.score = bestScore; - if (searchStopped) return 0; + if (searchStopped.load(std::memory_order_relaxed)) return 0; if (!ctx->excluded) { ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv); } @@ -410,7 +410,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC int score = -PVS(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score; - if (searchStopped) return 0; + if (searchStopped.load(std::memory_order_relaxed)) return 0; if (score >= beta) { if (depth <= 14 || ctx->minNmpPly > 0) { return score > MATE_SCORE - MAX_DEPTH ? beta : score; @@ -469,7 +469,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC ply + 1, ctx, !cutnode).score; } - if (searchStopped) return 0; + if (searchStopped.load(std::memory_order_relaxed)) return 0; if (score >= probcutBeta) { ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv); @@ -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 (searchStopped) return 0; + if (searchStopped.load(std::memory_order_relaxed)) return 0; if (currMove != 0 && currMove.IsQuiet()) { seenQuiets[seenQuietsCount] = currMove; @@ -754,7 +754,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC } } - if (searchStopped) return 0; + if (searchStopped.load(std::memory_order_relaxed)) return 0; if (!ctx->excluded) { if (!board.InCheck() && ((results.bestMove.IsQuiet() || !results.bestMove)) @@ -864,7 +864,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { aw.Set(currentResults.score); - if (searchStopped) { + if (searchStopped.load(std::memory_order_relaxed)) { break; } else { if (currentResults.bestMove) { @@ -877,13 +877,13 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { if constexpr (mode == normal) { if (ctx->sw.GetElapsedMS() >= softTime) { - searchStopped = true; + searchStopped.store(true, std::memory_order_relaxed); break; } } } else if constexpr (mode == datagen) { if (ctx->nodes >= DATAGEN::SOFT_NODES) { - searchStopped = true; + searchStopped.store(true, std::memory_order_relaxed); break; } } @@ -895,7 +895,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) { - searchStopped = false; + searchStopped.store(false, std::memory_order_relaxed); ctx->seldepth = 0; ctx->nodesTable = {}; if constexpr (mode != bench) { diff --git a/source/tt.cpp b/source/tt.cpp index 2eaa1a2..8ed48ff 100644 --- a/source/tt.cpp +++ b/source/tt.cpp @@ -2,7 +2,7 @@ TTable SharedTT; -void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) { +void TTable::WriteEntry(const U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) { TTBucket *bucket = &table[hashKey % table.size()]; TTEntry *current = nullptr; @@ -24,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; -} \ No newline at end of file +} diff --git a/source/tt.h b/source/tt.h index 48861ab..6df5c4c 100644 --- a/source/tt.h +++ b/source/tt.h @@ -68,11 +68,11 @@ public: table.resize(size); } - void PrefetchEntry(U64 &hashKey) { + void PrefetchEntry(const U64 &hashKey) { __builtin_prefetch(&table[hashKey % table.size()]); } - TTEntry GetEntry(U64 &hashKey) { + TTEntry GetEntry(const U64 &hashKey) { TTBucket *current = &table[hashKey % table.size()]; if (current->depthPreferred.hashKey == hashKey) { return current->depthPreferred; @@ -86,15 +86,16 @@ public: // returns used space per mill int GetUsedPercentage() { int count = 0; + const U64 sampleSize = std::min(1000, table.size()); - for (int i = 0; i < 1000; i++) { + for (U64 i = 0; i < sampleSize; i++) { if (table[i].depthPreferred || table[i].alwaysReplace) count++; } return count; } - void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv); + void WriteEntry(const U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv); }; -extern TTable SharedTT; \ No newline at end of file +extern TTable SharedTT; diff --git a/source/uci.cpp b/source/uci.cpp index 5b222b1..0e57fb6 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "types.h" #include "movegen.h" #include "search.h" @@ -88,27 +89,38 @@ static double ReadParam(const std::string& param, const std::string &command) { #ifdef _WIN32 // Windows implementation using std::thread +static std::vector activeThreads; + template -static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) { - SEARCH::SearchPosition(*board, params, ctx); +static void ThreadFunc(Board board, SearchParams params, SEARCH::SearchContext* ctx) { + SEARCH::SearchPosition(board, params, ctx); delete 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, &board, params, ctxCopy); + activeThreads.emplace_back(ThreadFunc, board, params, ctxCopy); } else { - searchThread = std::thread(ThreadFunc, &board, params, ctxCopy); + activeThreads.emplace_back(ThreadFunc, board, params, ctxCopy); } - searchThread.detach(); +} + +static void WaitForSearchThreads() { + for (auto &thread : activeThreads) { + if (thread.joinable()) { + thread.join(); + } + } + activeThreads.clear(); } #else // Unix/Linux implementation using pthread +static std::vector activeThreads; + template static void* ThreadFunc(void* arg) { auto* tup = static_cast*>(arg); @@ -138,10 +150,22 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC } pthread_attr_destroy(&attr); - pthread_detach(thread); + activeThreads.push_back(thread); +} + +static void WaitForSearchThreads() { + for (pthread_t thread : activeThreads) { + pthread_join(thread, nullptr); + } + activeThreads.clear(); } #endif +static void StopAndWaitForSearchThreads() { + searchStopped.store(true, std::memory_order_relaxed); + WaitForSearchThreads(); +} + static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) { SearchParams params; @@ -160,6 +184,8 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c params.btime = 99999999; } + StopAndWaitForSearchThreads(); + for (int i = 0; i < threads; i++) { StartSearchThread(board, params, ctx, i); } @@ -167,12 +193,14 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c static void SetOption(std::string& command, SEARCH::SearchContext* ctx) { if (command.find("Hash") != std::string::npos) { + StopAndWaitForSearchThreads(); U64 hashSize = (ReadParam("value", command) * 1000000ULL) / sizeof(TTEntry); ctx->TT->Resize(hashSize); return; } if (command.find("Threads") != std::string::npos) { + StopAndWaitForSearchThreads(); threads = ReadParam("value", command); return; } @@ -256,6 +284,7 @@ void UCILoop(Board &board) { // parse UCI "ucinewgame" command if (input.find("ucinewgame") != std::string::npos) { + StopAndWaitForSearchThreads(); board.SetByFen(StartingFen); // Clearing @@ -279,6 +308,7 @@ void UCILoop(Board &board) { // parse UCI "quit" command if (input.find("quit") != std::string::npos) { + StopAndWaitForSearchThreads(); // stop the loop break; } @@ -286,7 +316,7 @@ void UCILoop(Board &board) { // parse UCI "stop" command if (input.find("stop") != std::string::npos) { // stop the loop - searchStopped = true; + StopAndWaitForSearchThreads(); continue; } diff --git a/source/uci.h b/source/uci.h index 21fb131..2e6ca21 100644 --- a/source/uci.h +++ b/source/uci.h @@ -1,10 +1,11 @@ #pragma once #include "move.h" #include "board.h" +#include inline bool UCIEnabled = false; inline int threads = 1; -inline bool searchStopped = false; +inline std::atomic_bool searchStopped = false; class SearchParams { public: -- 2.47.3 From 079959e6d4eff898b2188205e161a52055b70ecd Mon Sep 17 00:00:00 2001 From: rektdie Date: Tue, 24 Feb 2026 23:39:59 +0100 Subject: [PATCH 3/4] Revert "maybe fixed crashes | bench 1801941" This reverts commit 64b2e3d9b143e901386231e48a0ec4eed92479ec. --- source/search.cpp | 24 ++++++++++++------------ source/tt.cpp | 4 ++-- source/tt.h | 11 +++++------ source/uci.cpp | 46 ++++++++-------------------------------------- source/uci.h | 3 +-- 5 files changed, 28 insertions(+), 60 deletions(-) diff --git a/source/search.cpp b/source/search.cpp index 824c031..a6c5602 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -207,18 +207,18 @@ static bool ShouldStop(SearchContext* ctx) { if constexpr (mode == normal) { if (ctx->nodes % 1024 == 0) { if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) { - searchStopped.store(true, std::memory_order_relaxed); + searchStopped = true; return true; } } } else if constexpr (mode == nodesMode) { if (ctx->nodes > ctx->nodesToGo) { - searchStopped.store(true, std::memory_order_relaxed); + searchStopped = true; return true; } } else if constexpr (mode == datagen) { if (ctx->nodes > DATAGEN::HARD_NODES) { - searchStopped.store(true, std::memory_order_relaxed); + searchStopped = true; return true; } } @@ -314,7 +314,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear } results.score = bestScore; - if (searchStopped.load(std::memory_order_relaxed)) return 0; + if (searchStopped) return 0; if (!ctx->excluded) { ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv); } @@ -410,7 +410,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC int score = -PVS(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score; - if (searchStopped.load(std::memory_order_relaxed)) return 0; + if (searchStopped) return 0; if (score >= beta) { if (depth <= 14 || ctx->minNmpPly > 0) { return score > MATE_SCORE - MAX_DEPTH ? beta : score; @@ -469,7 +469,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC ply + 1, ctx, !cutnode).score; } - if (searchStopped.load(std::memory_order_relaxed)) return 0; + if (searchStopped) return 0; if (score >= probcutBeta) { ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv); @@ -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 (searchStopped.load(std::memory_order_relaxed)) return 0; + if (searchStopped) return 0; if (currMove != 0 && currMove.IsQuiet()) { seenQuiets[seenQuietsCount] = currMove; @@ -754,7 +754,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC } } - if (searchStopped.load(std::memory_order_relaxed)) return 0; + if (searchStopped) return 0; if (!ctx->excluded) { if (!board.InCheck() && ((results.bestMove.IsQuiet() || !results.bestMove)) @@ -864,7 +864,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { aw.Set(currentResults.score); - if (searchStopped.load(std::memory_order_relaxed)) { + if (searchStopped) { break; } else { if (currentResults.bestMove) { @@ -877,13 +877,13 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { if constexpr (mode == normal) { if (ctx->sw.GetElapsedMS() >= softTime) { - searchStopped.store(true, std::memory_order_relaxed); + searchStopped = true; break; } } } else if constexpr (mode == datagen) { if (ctx->nodes >= DATAGEN::SOFT_NODES) { - searchStopped.store(true, std::memory_order_relaxed); + searchStopped = true; break; } } @@ -895,7 +895,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) { - searchStopped.store(false, std::memory_order_relaxed); + searchStopped = false; ctx->seldepth = 0; ctx->nodesTable = {}; if constexpr (mode != bench) { diff --git a/source/tt.cpp b/source/tt.cpp index 8ed48ff..2eaa1a2 100644 --- a/source/tt.cpp +++ b/source/tt.cpp @@ -2,7 +2,7 @@ TTable SharedTT; -void TTable::WriteEntry(const U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) { +void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) { TTBucket *bucket = &table[hashKey % table.size()]; TTEntry *current = nullptr; @@ -24,4 +24,4 @@ void TTable::WriteEntry(const U64 &hashKey, int depth, int score, int nodeType, current->depth = depth; current->bestMove = bestMove; current->ttpv = ttpv; -} +} \ No newline at end of file diff --git a/source/tt.h b/source/tt.h index 6df5c4c..48861ab 100644 --- a/source/tt.h +++ b/source/tt.h @@ -68,11 +68,11 @@ public: table.resize(size); } - void PrefetchEntry(const U64 &hashKey) { + void PrefetchEntry(U64 &hashKey) { __builtin_prefetch(&table[hashKey % table.size()]); } - TTEntry GetEntry(const U64 &hashKey) { + TTEntry GetEntry(U64 &hashKey) { TTBucket *current = &table[hashKey % table.size()]; if (current->depthPreferred.hashKey == hashKey) { return current->depthPreferred; @@ -86,16 +86,15 @@ public: // returns used space per mill int GetUsedPercentage() { int count = 0; - const U64 sampleSize = std::min(1000, table.size()); - for (U64 i = 0; i < sampleSize; i++) { + for (int i = 0; i < 1000; i++) { if (table[i].depthPreferred || table[i].alwaysReplace) count++; } return count; } - void WriteEntry(const U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv); + void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv); }; -extern TTable SharedTT; +extern TTable SharedTT; \ No newline at end of file diff --git a/source/uci.cpp b/source/uci.cpp index 0e57fb6..5b222b1 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -4,7 +4,6 @@ #include #include #include -#include #include "types.h" #include "movegen.h" #include "search.h" @@ -89,38 +88,27 @@ static double ReadParam(const std::string& param, const std::string &command) { #ifdef _WIN32 // Windows implementation using std::thread -static std::vector activeThreads; - template -static void ThreadFunc(Board board, SearchParams params, SEARCH::SearchContext* ctx) { - SEARCH::SearchPosition(board, params, ctx); +static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) { + SEARCH::SearchPosition(*board, params, ctx); delete 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) { - activeThreads.emplace_back(ThreadFunc, board, params, ctxCopy); + searchThread = std::thread(ThreadFunc, &board, params, ctxCopy); } else { - activeThreads.emplace_back(ThreadFunc, board, params, ctxCopy); + searchThread = std::thread(ThreadFunc, &board, params, ctxCopy); } -} - -static void WaitForSearchThreads() { - for (auto &thread : activeThreads) { - if (thread.joinable()) { - thread.join(); - } - } - activeThreads.clear(); + searchThread.detach(); } #else // Unix/Linux implementation using pthread -static std::vector activeThreads; - template static void* ThreadFunc(void* arg) { auto* tup = static_cast*>(arg); @@ -150,22 +138,10 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC } pthread_attr_destroy(&attr); - activeThreads.push_back(thread); -} - -static void WaitForSearchThreads() { - for (pthread_t thread : activeThreads) { - pthread_join(thread, nullptr); - } - activeThreads.clear(); + pthread_detach(thread); } #endif -static void StopAndWaitForSearchThreads() { - searchStopped.store(true, std::memory_order_relaxed); - WaitForSearchThreads(); -} - static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) { SearchParams params; @@ -184,8 +160,6 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c params.btime = 99999999; } - StopAndWaitForSearchThreads(); - for (int i = 0; i < threads; i++) { StartSearchThread(board, params, ctx, i); } @@ -193,14 +167,12 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c static void SetOption(std::string& command, SEARCH::SearchContext* ctx) { if (command.find("Hash") != std::string::npos) { - StopAndWaitForSearchThreads(); U64 hashSize = (ReadParam("value", command) * 1000000ULL) / sizeof(TTEntry); ctx->TT->Resize(hashSize); return; } if (command.find("Threads") != std::string::npos) { - StopAndWaitForSearchThreads(); threads = ReadParam("value", command); return; } @@ -284,7 +256,6 @@ void UCILoop(Board &board) { // parse UCI "ucinewgame" command if (input.find("ucinewgame") != std::string::npos) { - StopAndWaitForSearchThreads(); board.SetByFen(StartingFen); // Clearing @@ -308,7 +279,6 @@ void UCILoop(Board &board) { // parse UCI "quit" command if (input.find("quit") != std::string::npos) { - StopAndWaitForSearchThreads(); // stop the loop break; } @@ -316,7 +286,7 @@ void UCILoop(Board &board) { // parse UCI "stop" command if (input.find("stop") != std::string::npos) { // stop the loop - StopAndWaitForSearchThreads(); + searchStopped = true; continue; } diff --git a/source/uci.h b/source/uci.h index 2e6ca21..21fb131 100644 --- a/source/uci.h +++ b/source/uci.h @@ -1,11 +1,10 @@ #pragma once #include "move.h" #include "board.h" -#include inline bool UCIEnabled = false; inline int threads = 1; -inline std::atomic_bool searchStopped = false; +inline bool searchStopped = false; class SearchParams { public: -- 2.47.3 From b929963f91e2f46cb1e3fdb89c130f974e707e06 Mon Sep 17 00:00:00 2001 From: rektdie Date: Wed, 25 Feb 2026 01:17:15 +0100 Subject: [PATCH 4/4] added pseudo legality checking and testing tt move in movepicker | bench 1801941 --- source/board.cpp | 185 ++++++++++++++++++++++++++++++++++++++++++++ source/board.h | 1 + source/movepicker.h | 2 +- 3 files changed, 187 insertions(+), 1 deletion(-) diff --git a/source/board.cpp b/source/board.cpp index c060c4e..536bd6d 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -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; + } +} \ No newline at end of file diff --git a/source/board.h b/source/board.h index 6ecda1b..cab41f4 100644 --- a/source/board.h +++ b/source/board.h @@ -80,4 +80,5 @@ public: Bitboard CalcPinned(bool color); bool IsLegal(Move &move); + bool IsPseudoLegal(Move &move); }; diff --git a/source/movepicker.h b/source/movepicker.h index e2e4c61..b0361b2 100644 --- a/source/movepicker.h +++ b/source/movepicker.h @@ -40,7 +40,7 @@ public: case TT: { stage = Rest; - if (ttMove) + if (ttMove && board.IsPseudoLegal(ttMove)) return ttMove; break; } -- 2.47.3