#include "search.h" #include "movegen.h" #include #include #include "datagen.h" #include "benchmark.h" #include "types.h" #include "tunables.h" #include "movepicker.h" #include "wdl.h" #include "termcolor.hpp" #include namespace SEARCH { static void PublishRootVote(SearchContext* ctx, const SearchResults& results, int depth) { if (!ctx->voteTable || !ctx->voteMutex) return; Move m = results.bestMove; if (uint16_t(m) == 0) return; if (ctx->threadId < 0 || ctx->threadId >= static_cast(ctx->voteTable->size())) return; std::lock_guard lock(*ctx->voteMutex); RootVote& slot = (*ctx->voteTable)[ctx->threadId]; slot.bestMove = results.bestMove; slot.score = results.score; slot.depth = depth; } SearchResults VoteRootMoves(const std::vector& votes) { struct Tally { Move move; int count = 0; int score = 0; int depth = 0; }; std::vector tallies; tallies.reserve(votes.size()); for (const RootVote& v : votes) { Move mv = v.bestMove; if (uint16_t(mv) == 0) continue; const uint16_t key = mv; bool found = false; for (Tally& t : tallies) { if (uint16_t(t.move) == key) { t.count++; if (v.depth > t.depth || (v.depth == t.depth && v.score > t.score)) { t.score = v.score; t.depth = v.depth; t.move = v.bestMove; } found = true; break; } } if (!found) { Tally t; t.move = v.bestMove; t.count = 1; t.score = v.score; t.depth = v.depth; tallies.push_back(t); } } if (tallies.empty()) return SearchResults(0, Move()); Tally* best = &tallies[0]; for (size_t i = 1; i < tallies.size(); i++) { if (tallies[i].count > best->count || (tallies[i].count == best->count && tallies[i].depth > best->depth) || (tallies[i].count == best->count && tallies[i].depth == best->depth && tallies[i].score > best->score)) { best = &tallies[i]; } } return SearchResults(best->score, best->move); } static WDLTriplet GetRoundedWDL(int score, Board& board) { WDLTriplet wdl = getWDL(score, board); wdl.wins = (wdl.wins + 5) / 10; wdl.losses = (wdl.losses + 5) / 10; wdl.draws = 100 - wdl.wins - wdl.losses; if (wdl.draws < 0) { if (wdl.wins >= wdl.losses) { wdl.wins += wdl.draws; } else { wdl.losses += wdl.draws; } wdl.draws = 0; } return wdl; } void InitLMRTable() { for (int i = 0; i < 2; i++) { const double base = i ? lmrBaseQuiet : lmrBaseNoisy; const double divisor = i ? lmrDivisorQuiet : lmrDivisorNoisy; for (int depth = 0; depth <= MAX_DEPTH; depth++) { for (int move = 0; move < MAX_MOVES; move++) { if (depth == 0 || move == 0) { lmrTable[i][depth][move] = 0; } else { lmrTable[i][depth][move] = std::floor(base + std::log(depth) * std::log(move) / divisor); } } } } } #ifdef TUNING void InitSEEPieceValues() { SEEPieceValues = { seePawnValue, seeKnightValue, seeBishopValue, seeRookValue, seeQueenValue, 0 }; } void RefreshTunableCaches() { InitLMRTable(); InitSEEPieceValues(); } #endif int16_t ContHistory::GetNPly(Board& board, Move& move, SearchContext* ctx, int ply, int n) { int prevType = ctx->ss[ply-n].pieceType; int prevTo = ctx->ss[ply-n].moveTo; int pieceType = board.GetPieceType(move.MoveFrom()); int to = move.MoveTo(); bool otherColor = ctx->ss[ply-n].side; return ctx->conthist[otherColor][prevType][prevTo][board.sideToMove][pieceType][to]; } static int AdjustEval(Board &board, SearchContext* ctx, int eval) { int corrhist = ctx->corrhist.GetAllHist(board); int mateFound = MATE_SCORE - MAX_DEPTH; int adjusted = eval + corrhist / CORRHIST_GRAIN; const int scaleNumerator = std::max(0, fiftyMoveScaleBase - board.halfMoves); adjusted = adjusted * scaleNumerator / fiftyMoveScaleBase; return std::clamp(adjusted, -mateFound + 1, mateFound - 1); } static bool IsTwoFold(Board &board, SearchContext* ctx) { for (int i = 0; i < board.positionIndex; i++) { if (ctx->positionHistory[i] == board.hashKey) { return true; } } return false; } static bool IsFifty(Board &board) { return (board.halfMoves >= 100); } static bool IsInsuffMat(Board &board) { return (board.occupied.PopCount() <= 3 && !(board.pieces[Pawn] | board.pieces[Queen] | board.pieces[Rook])); } bool IsDraw(Board &board, SearchContext* ctx) { return IsFifty(board) || IsInsuffMat(board) || IsTwoFold(board, ctx); } template static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, bool improving, bool corrplexity, bool ttpv, bool ttpvFailLow, SearchContext* ctx) { int reduction = 0; reduction = lmrTable[move.IsQuiet()][depth][moveSeen] * 1024; if (cutnode) reduction += lmrCutnode; if constexpr (isPV) reduction -= lmrIsPV; if (!improving) reduction += lmrImproving; if (corrplexity) reduction -= lmrCorrplexity; if (ttpv) reduction -= lmrTTPV; if (ttpvFailLow) reduction += lmrTTPVFailLow; int historyReduction = 0; if (move.IsQuiet()) { bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveFrom()); bool targetThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveTo()); historyReduction = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()][sourceThreatened][targetThreatened]; if (ply > 0) { historyReduction += ctx->conthist.GetNPly(board, move, ctx, ply, 1); if (ply > 1) historyReduction += ctx->conthist.GetNPly(board, move, ctx, ply, 2); } } else if (move.IsCapture()) { int attackerType = board.GetPieceType(move.MoveFrom()); int targetType = board.GetPieceType(move.MoveTo()); if (move.GetFlags() == epCapture) { targetType = Pawn; } historyReduction = ctx->capthist[board.sideToMove][attackerType][targetType][move.MoveTo()]; } historyReduction = historyReduction / lmrHistoryDivisor; reduction -= historyReduction * 1024; reduction /= 1024; return std::clamp(reduction, -1, depth - 1); } bool SEE(Board& board, Move& move, int threshold) { int from = move.MoveFrom(); int to = move.MoveTo(); int flags = move.GetFlags(); int nextVictim = board.GetPieceType(from); if (move.IsPromo()) { nextVictim = move.GetPromoPiece(); } int balance = MoveEstimatedValue(board, move) - threshold; if (balance < 0) return 0; balance -= SEEPieceValues[nextVictim]; if (balance >= 0) return 1; Bitboard bishops = board.pieces[Bishop] | board.pieces[Queen]; Bitboard rooks = board.pieces[Rook] | board.pieces[Queen]; Bitboard occupied = board.occupied; occupied.PopBit(from); occupied.SetBit(to); if (flags == epCapture) occupied.SetBit(board.enPassantTarget); Bitboard attackers = board.AttacksTo(to, occupied) & occupied; bool color = !board.sideToMove; while (true) { Bitboard myAttackers = attackers & board.colors[color]; if (!myAttackers) break; for (nextVictim = Pawn; nextVictim <= Queen; nextVictim++) { if (myAttackers & board.pieces[nextVictim]) break; } occupied.PopBit(Bitboard(myAttackers & board.pieces[nextVictim]).getLS1BIndex()); if (nextVictim == Pawn || nextVictim == Bishop || nextVictim == Queen) attackers |= MOVEGEN::getBishopAttack(to, occupied) & bishops; if (nextVictim == Rook || nextVictim == Queen) attackers |= MOVEGEN::getRookAttack(to, occupied) & rooks; attackers &= occupied; color = !color; balance = -balance - 1 - SEEPieceValues[nextVictim]; if (balance >= 0) { if (nextVictim == King && (attackers & board.colors[color])) color = !color; break; } } return board.sideToMove != color; } template 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); return true; } } } else if constexpr (mode == nodesMode) { if (ctx->nodes > ctx->nodesToGo) { searchStopped.store(true, std::memory_order_relaxed); return true; } } else if constexpr (mode == datagen) { if (ctx->nodes > DATAGEN::HARD_NODES) { searchStopped.store(true, std::memory_order_relaxed); return true; } } return false; } static bool IsDecisive(int score) { return std::abs(score) > WIN_SCORE; } static bool IsLoss(int score) { return score < -WIN_SCORE; } template static inline int StaticEval(Board& board, SearchContext* ctx, int ply) { board.UpdateAccumulator(ctx->accStack, ply); #ifdef ACC_VERIFY { ACC::AccumulatorPair ref; board.RefreshAccumulator(ref); if (ref.white != ctx->accStack.cur[ply]->white || ref.black != ctx->accStack.cur[ply]->black) { std::cerr << "ACC MISMATCH ply " << ply << " fen " << board.GetFen() << std::endl; std::abort(); } } #endif return NNUE::net.Evaluate(board, *ctx->accStack.cur[ply], mode == datagen); } template static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext* ctx) { if (ShouldStop(ctx)) return 0; if (ply + 1 >= MAX_DEPTH) return StaticEval(board, ctx, ply); if (ply > ctx->seldepth) ctx->seldepth = ply; int bestScore = AdjustEval(board, ctx, StaticEval(board, ctx, ply)); ctx->ss[ply].eval = bestScore; TTEntry entry; bool ttHit = false; entry = ctx->TT->GetEntry(board.hashKey); if (entry.hashKey == board.hashKey) { ttHit = true; switch (entry.nodeType) { case PV: return entry.score; case CutNode: if (entry.score >= beta) return entry.score; break; case AllNode: if (entry.score <= alpha) return entry.score; break; } } const bool ttpv = isPV | entry.ttpv; if (ttHit) { switch (entry.nodeType) { case PV: bestScore = entry.score; break; case CutNode: if (entry.score > bestScore) bestScore = entry.score; break; case AllNode: if (entry.score < bestScore) bestScore = entry.score; break; } } if (bestScore >= beta) { return bestScore; } if (alpha < bestScore) { alpha = bestScore; } const int fpScore = bestScore + qsFPMargin; MovePicker mp(board, ctx, ply, entry.bestMove); SearchResults results; int nodeType = AllNode; const bool inCheck = board.InCheck(); Move currMove; while ((currMove = mp.Next())) { if (!IsLoss(bestScore)) { if (!inCheck && currMove.IsCapture() && fpScore <= alpha && !SEE(board, currMove, 1)) { bestScore = std::max(bestScore, fpScore); continue; } if (!SEE(board, currMove, seeQsThreshold)) continue; } if (!board.IsLegal(currMove)) continue; Board copy = board; copy.MakeMove(currMove); ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom()); ctx->ss[ply].moveTo = currMove.MoveTo(); ctx->ss[ply].side = board.sideToMove; if (copy.positionIndex >= ctx->positionHistory.size()) { ctx->positionHistory.resize(copy.positionIndex + 100); } ctx->positionHistory[copy.positionIndex] = copy.hashKey; ctx->nodes++; ctx->TT->PrefetchEntry(copy.hashKey); int score = -Quiescence(copy, -beta, -alpha, ply + 1, ctx).score; if (score >= beta) { if (searchStopped.load(std::memory_order_relaxed)) return 0; ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv); return score; } bestScore = std::max(score, bestScore); if (score > alpha) { nodeType = PV; alpha = score; results.bestMove = currMove; } } results.score = bestScore; if (searchStopped.load(std::memory_order_relaxed)) return 0; ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv); return results; } template SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext* ctx, bool cutnode) { if (ShouldStop(ctx)) return 0; if (ply + 1 >= MAX_DEPTH) return StaticEval(board, ctx, ply); if (ply > ctx->seldepth) ctx->seldepth = ply; ctx->pvLine.SetLength(ply); if (ply && (IsDraw(board, ctx))) return 0; TTEntry entry; if (!ctx->excluded) entry = ctx->TT->GetEntry(board.hashKey); const bool ttHit = entry.hashKey == board.hashKey; const bool ttpv = isPV | entry.ttpv; if constexpr (!isPV) { if (ttHit) { if (entry.depth >= depth && ((entry.nodeType == PV) || (entry.nodeType == AllNode && entry.score <= alpha) || (entry.nodeType == CutNode && entry.score >= beta))) { return SearchResults(entry.score, entry.bestMove); } } } if (depth <= 0) return Quiescence(board, alpha, beta, ply, ctx); int rawEval = StaticEval(board, ctx, ply); const int staticEval = AdjustEval(board, ctx, rawEval); ctx->ss[ply].eval = staticEval; int ttAdjustedEval = staticEval; const bool inCheck = board.InCheck(); if (!ctx->excluded && !inCheck && ttHit && ((entry.nodeType == PV) || (entry.nodeType == AllNode && entry.score <= staticEval) || (entry.nodeType == CutNode && entry.score >= staticEval))) { ttAdjustedEval = entry.score; } bool corrplexity = std::abs(rawEval - staticEval) > 70; const bool improving = [&] { if (inCheck) return false; if (ply > 1 && ctx->ss[ply - 2].eval != ScoreNone) return staticEval > ctx->ss[ply - 2].eval; if (ply > 3 && ctx->ss[ply - 4].eval != ScoreNone) return staticEval > ctx->ss[ply - 4].eval; return true; }(); if (!inCheck && !ctx->excluded) { if (ply) { int margin = rfpBase + rfpMargin * (depth - improving); if (!ttpv && ttAdjustedEval - margin >= beta && depth < 7) { return !IsDecisive(ttAdjustedEval) && !IsDecisive(beta) ? ((ttAdjustedEval + beta) / 2) : ttAdjustedEval; } if (!isPV && depth <= 3 && staticEval + razoringScalar * depth < alpha && entry.nodeType != CutNode) { return Quiescence(board, alpha, beta, ply, ctx).score; } if (ply > ctx->minNmpPly && ttAdjustedEval >= beta + nmpBetaMargin) { if (depth > 1 && !board.InPossibleZug()) { Board copy = board; copy.MakeMove(Move()); const int reduction = 4 + improving + depth / 3 + entry.bestMove.IsCapture(); ctx->TT->PrefetchEntry(copy.hashKey); int score = -PVS(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score; 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; } ctx->minNmpPly = ply + (depth - reduction) * 3 / 4; const auto verifResults = PVS(copy, depth - reduction, beta - 1, beta, ply + 1, ctx, true); ctx->minNmpPly = 0; if (verifResults.score >= beta) { return verifResults; } } } } } } const int probcutBeta = beta + probcutBetaMargin; const int probcutDepth = std::max(depth - 3, 1); if (depth >= 7 && std::abs(beta) < MATE_SCORE - MAX_DEPTH && (!entry.bestMove || !entry.bestMove.IsQuiet()) && !(ttHit && entry.depth >= probcutDepth && entry.score < probcutBeta)) { MovePicker mp(board, ctx, ply, entry.bestMove); const int seeThreshold = (probcutBeta - staticEval) * 15 / 16; Move currMove; while ((currMove = mp.Next())) { if (ctx->excluded == currMove) continue; if (!SEE(board, currMove, seeThreshold)) continue; if (!board.IsLegal(currMove)) continue; Board copy = board; copy.MakeMove(currMove); if (copy.positionIndex >= ctx->positionHistory.size()) { ctx->positionHistory.resize(copy.positionIndex + 100); } ctx->positionHistory[copy.positionIndex] = copy.hashKey; ctx->nodes++; int score = -Quiescence(copy, -probcutBeta, -probcutBeta + 1, ply + 1, ctx).score; if (score >= probcutBeta) { score = -PVS(copy, probcutDepth - 1, -probcutBeta, -probcutBeta + 1, ply + 1, ctx, !cutnode).score; } if (searchStopped.load(std::memory_order_relaxed)) return 0; if (score >= probcutBeta) { ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv); return score; } } } MovePicker mp(board, ctx, ply, entry.bestMove); int score = -inf; int nodeType = AllNode; SearchResults results(-inf); int moveSeen = 0; std::array seenQuiets; std::array seenCaptures; int seenQuietsCount = 0; int seenCapturesCount = 0; ctx->killerMoves[ply + 1] = Move(); Move currMove; while ((currMove = mp.Next())) { if (ctx->excluded == currMove) continue; if (ply == 0 && !ctx->searchMoves.empty()) { bool found = false; for (Move &m : ctx->searchMoves) { if (m.MoveFrom() == currMove.MoveFrom() && m.MoveTo() == currMove.MoveTo() && m.GetFlags() == currMove.GetFlags()) { found = true; break; } } if (!found) continue; } bool notMated = results.score > (-MATE_SCORE + MAX_DEPTH); int lmrDepth = depth - lmrTable[currMove.IsQuiet()][depth][moveSeen]; if (currMove.IsQuiet() && notMated) { int lmpThreshold = 7 + depth * depth * (1 + improving); if (moveSeen >= lmpThreshold) { continue; } } bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, currMove.MoveFrom()); bool targetThreatened = board.IsSquareThreatened(board.sideToMove, currMove.MoveTo()); int historyScore = ctx->history[board.sideToMove][currMove.MoveFrom()][currMove.MoveTo()][sourceThreatened][targetThreatened]; if (ply > 0) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 1); if (ply > 1) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 2); int margin = fpMargin * (lmrDepth + improving) + historyScore / 32; if (!isPV && ply && currMove.IsQuiet() && lmrDepth <= 7 && staticEval + margin < alpha && notMated && !board.GivesDirectCheck(currMove)) { continue; } int SEEThreshold = currMove.IsQuiet() ? seeQuietThreshold * depth : seeNoisyThreshold * depth * depth; if (ply && depth <= 10 && notMated && !SEE(board, currMove, SEEThreshold)) continue; if (!board.IsLegal(currMove)) continue; Board copy = board; copy.MakeMove(currMove); ctx->nodes++; ctx->TT->PrefetchEntry(copy.hashKey); int extension = 0; if (ply && ply < ctx->rootDepth * 2 && currMove == entry.bestMove && ctx->excluded == 0) { if (depth >= 8 && ttHit && entry.depth >= depth - 3 && entry.nodeType != AllNode) { const int sBeta = std::max(-inf + 1, entry.score - depth * 2); const int sDepth = (depth - 1) / 2; ctx->excluded = currMove; const int singularScore = PVS(board, sDepth, sBeta-1, sBeta, ply, ctx, cutnode).score; ctx->excluded = Move(); if (singularScore < sBeta) { extension++; if constexpr (!isPV) { if (singularScore <= sBeta - 1 - doubleExtMargin) { extension++; } } } else if (sBeta >= beta) { return sBeta; } else if (entry.score >= beta) { extension--; } else if (cutnode) { extension--; } } else if (depth <= 7 && !inCheck && staticEval <= alpha - ldseMargin && entry.nodeType == CutNode) { extension++; } } cutnode |= extension < 0; ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom()); ctx->ss[ply].moveTo = currMove.MoveTo(); ctx->ss[ply].side = board.sideToMove; if (copy.positionIndex >= ctx->positionHistory.size()) { ctx->positionHistory.resize(copy.positionIndex + 100); } ctx->positionHistory[copy.positionIndex] = copy.hashKey; int newDepth = depth + (copy.InCheck() && !ctx->excluded) - 1 + extension; U64 nodesBeforeSearch = ctx->nodes; if (depth >= 2 && moveSeen >= 2 + (2 * isPV)) { const bool ttpvFailLow = ttpv && ttHit && entry.score <= alpha; int reductions = GetReductions(board, currMove, depth, moveSeen, ply, cutnode, improving, corrplexity, ttpv, ttpvFailLow, ctx); int reduced = newDepth - reductions; score = -PVS(copy, reduced, -alpha - 1, -alpha, ply + 1, ctx, true).score; if (score > alpha && reduced < newDepth) { const bool goDeeper = score > results.score + lmrDeeperBase + 4 * newDepth; const bool goShallower = score < results.score + newDepth; newDepth += goDeeper - goShallower; score = -PVS(copy, newDepth, -alpha - 1, -alpha, ply + 1, ctx, !cutnode).score; } } else if (!isPV || moveSeen > 0) { score = -PVS(copy, newDepth, -alpha - 1, -alpha, ply + 1, ctx, !cutnode).score; } if (isPV && (moveSeen == 0 || score > alpha)) { score = -PVS(copy, newDepth, -beta, -alpha, ply + 1, ctx, false).score; } moveSeen++; if (!ply) { ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch; } if (searchStopped.load(std::memory_order_relaxed)) return 0; if (currMove != 0 && currMove.IsQuiet()) { seenQuiets[seenQuietsCount] = currMove; seenQuietsCount++; } else if (currMove != 0 && currMove.IsCapture()) { seenCaptures[seenCapturesCount] = currMove; seenCapturesCount++; } results.score = std::max(score, results.score); if (score > alpha) { nodeType = PV; alpha = score; results.bestMove = currMove; ctx->pvLine.SetMove(ply, currMove); } if (score >= beta) { const int bonusDepth = depth + (!inCheck && staticEval <= alpha); int historyBonus = historyBonusMultiplier * bonusDepth - historyBonusSub; int historyMalus = historyMalusMultiplier * bonusDepth - historyMalusSub; int contHistoryBonus = contHistoryBonusMultiplier * bonusDepth - contHistoryBonusSub; int contHistoryMalus = contHistoryMalusMultiplier * bonusDepth - contHistoryMalusSub; int captHistoryBonus = captHistoryBonusMultiplier * bonusDepth - captHistoryBonusSub; int captHistoryMalus = captHistoryMalusMultiplier * bonusDepth - captHistoryMalusSub; auto UpdateCaptHist = [&](Move move, int bonus) { int movingPiece = board.GetPieceType(move.MoveFrom()); int capturedPiece = move.GetFlags() == epCapture ? Pawn : board.GetPieceType(move.MoveTo()); ctx->capthist.Update(board.sideToMove, movingPiece, capturedPiece, move.MoveTo(), bonus); }; auto UpdateContHistNPly = [&](int n) { int prevType = ctx->ss[ply - n].pieceType; int prevTo = ctx->ss[ply - n].moveTo; bool otherColor = ctx->ss[ply - n].side; int pieceType = ctx->ss[ply].pieceType; int to = ctx->ss[ply].moveTo; ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pieceType, to, contHistoryBonus); for (int i = 0; i < seenQuietsCount - 1; i++) { int pt = board.GetPieceType(seenQuiets[i].MoveFrom()); int t = seenQuiets[i].MoveTo(); ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pt, t, -contHistoryMalus); } }; if (!currMove.IsCapture()) { ctx->killerMoves[ply] = currMove; ctx->history.Update(board.sideToMove, currMove, sourceThreatened, targetThreatened, historyBonus); if (ply > 0) UpdateContHistNPly(1); if (ply > 1) UpdateContHistNPly(2); for (int i = 0; i < seenQuietsCount - 1; i++) { sourceThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveFrom()); targetThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveTo()); ctx->history.Update(board.sideToMove, seenQuiets[i], sourceThreatened, targetThreatened, -historyMalus); } } else { UpdateCaptHist(currMove, captHistoryBonus); } for (int i = 0; i < seenCapturesCount - currMove.IsCapture(); i++) { UpdateCaptHist(seenCaptures[i], -captHistoryMalus); } if (!ctx->excluded && !inCheck && currMove.IsQuiet() && score > staticEval) { int corrHistBonus = std::clamp(score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT); ctx->corrhist.UpdateAll(board, depth, corrHistBonus); } if (!ctx->excluded) ctx->TT->WriteEntry(board.hashKey, depth, score, CutNode, currMove, ttpv); return score; } } if (moveSeen == 0) { if (ctx->excluded) return alpha; return inCheck ? -MATE_SCORE + ply : 0; } if (searchStopped.load(std::memory_order_relaxed)) return 0; if (!ctx->excluded) { if (!inCheck && ((results.bestMove.IsQuiet() || !results.bestMove)) && !(nodeType == AllNode && results.score >= staticEval)) { int corrHistBonus = std::clamp(results.score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT); ctx->corrhist.UpdateAll(board, depth, corrHistBonus); } ctx->TT->WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove, ttpv); } return results; } class AspirationWindow { public: int delta = aspInitialDelta; int alpha = -inf; int beta = inf; void WidenDown() { alpha -= delta; delta *= 2; } void WidenUp() { beta += delta; delta *= 2; } void Set(int score) { delta = aspInitialDelta; alpha = score - delta; beta = score + delta; } }; static double ScaleTime(SearchContext *ctx, Move &move) { double notBmNodesFraction = ctx->nodesTable[move % 4096] / double(ctx->nodes); double nodeScalingFactor = (1.5f - notBmNodesFraction) * 1.35f; return nodeScalingFactor; } template static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { int fullTime = board.sideToMove ? params.btime : params.wtime; int inc = board.sideToMove ? params.binc : params.winc; int movesToGo = params.movesToGo ? params.movesToGo : 20; SearchResults safeResults; safeResults.score = -inf; int toDepth = MAX_DEPTH; if constexpr (mode == bench) { toDepth = BENCH_DEPTH; } else if constexpr (mode != datagen) { int depthLimit = MAX_DEPTH; if (params.depth > 0) depthLimit = std::min(params.depth, MAX_DEPTH); if (params.mate > 0) depthLimit = std::min({depthLimit, params.mate * 2, MAX_DEPTH}); toDepth = depthLimit; } AspirationWindow aw; int elapsed = 0; double nodeScaling = 1; ctx->sw.Restart(); bool hasTime = (fullTime > 0) || (params.movetime > 0); bool useTime = hasTime && !params.infinite; for (int depth = 1; depth <= toDepth; depth++) { if (params.movetime > 0 && !params.infinite) { ctx->timeToSearch = params.movetime; } else if (useTime) { ctx->timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4); } else { ctx->timeToSearch = 2000000000; } int softTime = 2000000000; if (params.movetime > 0 && !params.infinite) { softTime = params.movetime; } else if (useTime) { softTime = int(ctx->timeToSearch * 0.65 * nodeScaling); } ctx->seldepth = 0; ctx->rootDepth = depth; SearchResults currentResults = PVS(board, depth, aw.alpha, aw.beta, 0, ctx, false); elapsed = ctx->sw.GetElapsedMS(); if (depth > 6) { nodeScaling = ScaleTime(ctx, currentResults.bestMove); } if (aw.alpha != -inf && currentResults.score <= aw.alpha) { aw.WidenDown(); depth--; continue; } if (aw.beta != inf && currentResults.score >= aw.beta) { aw.WidenUp(); depth--; continue; } aw.Set(currentResults.score); if (searchStopped.load(std::memory_order_relaxed)) { break; } else { if (currentResults.bestMove) { safeResults = currentResults; } PublishRootVote(ctx, safeResults, depth); if constexpr (mode == normal || mode == nodesMode) { if (ctx->doPrint) PrintSearchInfo(board, ctx, safeResults, depth, elapsed); if constexpr (mode == normal) { if (useTime && ctx->sw.GetElapsedMS() >= softTime) { searchStopped.store(true, std::memory_order_relaxed); break; } } } else if constexpr (mode == datagen) { if (ctx->nodes >= DATAGEN::SOFT_NODES) { searchStopped.store(true, std::memory_order_relaxed); break; } } } } return safeResults; } template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) { if constexpr (mode == bench || mode == datagen) { searchStopped.store(false, std::memory_order_relaxed); ctx->TT->IncreaseAge(); } board.MarkAccumulatorDirty(); ctx->accStack.finny.Reset(); ctx->seldepth = 0; ctx->nodesTable = {}; ctx->searchMoves = params.searchMoves; if constexpr (mode != bench) { ctx->nodes = 0; if constexpr (mode == nodesMode) { ctx->nodesToGo = params.nodes; } } ctx->pvLine.Clear(); if constexpr (mode == normal || mode == nodesMode) { if (ctx->doPrint && !UCIEnabled) PrintSearchHeader(); } SearchResults results = ID(board, params, ctx); if constexpr (mode != normal && mode != nodesMode) return results; if (ctx->voteTable != nullptr) { return results; } if (ctx->doPrint) { if (UCIEnabled) { std::cout << "bestmove "; results.bestMove.PrintMove(); std::cout << std::endl; } else { std::cout << termcolor::color<244> << "bestmove " << termcolor::reset; std::cout << termcolor::bold << termcolor::bright_green; results.bestMove.PrintMove(); std::cout << termcolor::reset << std::endl; } } return results; } int MoveEstimatedValue(Board& board, Move& move) { int pieceType = board.GetPieceType(move.MoveTo()); int value = pieceType != nullPieceType ? SEEPieceValues[pieceType] : 0; if (move.IsPromo()) { int promoPiece = move.GetPromoPiece(); value += SEEPieceValues[promoPiece] - SEEPieceValues[Pawn]; } else if (move.GetFlags() == epCapture) { value = SEEPieceValues[Pawn]; } else if (move.GetFlags() == queenCastle || move.GetFlags() == kingCastle) { value = 0; } return value; } void PrintSearchHeader() { if (UCIEnabled) return; std::cout << termcolor::bold << termcolor::color<244>; std::cout << std::setw(7) << std::left << "Depth"; std::cout << std::setw(9) << std::right << "Time"; std::cout << std::setw(9) << std::right << "Score"; std::cout << std::setw(14) << std::right << "W-D-L"; std::cout << std::setw(7) << std::right << "TT"; std::cout << std::setw(9) << std::right << "Nodes"; std::cout << std::setw(9) << std::right << "NPS"; std::cout << " PV"; std::cout << termcolor::reset << std::endl; std::cout << termcolor::color<238>; for (int i = 0; i < 72; i++) std::cout << '-'; std::cout << termcolor::reset << std::endl; } void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, int depth, int elapsed) { WDLTriplet wdl = getWDL(results.score, board); const bool isMateScore = std::abs(results.score) + MAX_DEPTH >= MATE_SCORE; const int normalizedScore = isMateScore ? results.score : scaleEval(results.score, board); if (UCIEnabled) { std::cout << "info "; std::cout << "depth " << depth; std::cout << " seldepth " << ctx->seldepth; std::cout << " time " << elapsed; std::cout << " score "; if (isMateScore) { int mateIn = (MATE_SCORE - (std::abs(results.score) - 1)) / 2; mateIn = results.score < 0 ? mateIn * -1 : mateIn; std::cout << "mate " << mateIn; } else { std::cout << "cp " << normalizedScore; } if (UCIShowWDL) { std::cout << " wdl " << wdl.wins << ' ' << wdl.draws << ' ' << wdl.losses; } std::cout << " nodes " << ctx->nodes << " nps " << int(ctx->nodes/ctx->sw.GetElapsedSec()); std::cout << " hashfull " << ctx->TT->GetUsedPercentage(); std::cout << " pv "; ctx->pvLine.Print(0, depth % 2 == 0); std::cout << std::endl; } else { if (depth % 2 == 0) { std::cout << termcolor::color<247>; } else { std::cout << termcolor::color<251>; } std::stringstream depthStr; depthStr << depth << '/' << ctx->seldepth; std::cout << termcolor::bold << termcolor::bright_white; std::cout << std::setw(7) << std::left << depthStr.str(); std::cout << termcolor::reset; if (depth % 2 == 0) { std::cout << termcolor::color<247>; } else { std::cout << termcolor::color<251>; } std::stringstream timeStr; if (elapsed >= 1000) { timeStr << std::fixed << std::setprecision(1) << (elapsed / 1000.0) << "s"; } else { timeStr << elapsed << "ms"; } std::cout << std::setw(9) << std::right << timeStr.str(); std::stringstream scoreStr; bool isMate = false; int mateIn = 0; if (isMateScore) { isMate = true; mateIn = (MATE_SCORE - (std::abs(results.score) - 1)) / 2; mateIn = results.score < 0 ? mateIn * -1 : mateIn; if (mateIn < 0) { scoreStr << "-M" << std::abs(mateIn); } else { scoreStr << "+M" << mateIn; } } else { scoreStr << std::showpos << std::fixed << std::setprecision(2) << (normalizedScore / 100.0) << std::noshowpos; } if (isMate) { if (mateIn > 0) { std::cout << termcolor::bold << termcolor::bright_green; } else { std::cout << termcolor::bold << termcolor::bright_red; } } else { if (results.score > 0) { std::cout << termcolor::bold << termcolor::green; } else if (results.score < 0) { std::cout << termcolor::bold << termcolor::red; } } std::cout << std::setw(9) << std::right << scoreStr.str(); std::cout << termcolor::reset; if (depth % 2 == 0) { std::cout << termcolor::color<247>; } else { std::cout << termcolor::color<251>; } WDLTriplet displayWDL = GetRoundedWDL(results.score, board); std::stringstream wdlStr; wdlStr << displayWDL.wins << "W " << displayWDL.draws << "D " << displayWDL.losses << "L"; std::cout << termcolor::color<244>; std::cout << std::setw(14) << std::right << wdlStr.str(); if (depth % 2 == 0) { std::cout << termcolor::color<247>; } else { std::cout << termcolor::color<251>; } int hashUsed = ctx->TT->GetUsedPercentage(); std::stringstream hashStr; hashStr << (hashUsed + 5) / 10 << '%'; if (hashUsed >= 950) { std::cout << termcolor::bright_red; } else if (hashUsed >= 700) { std::cout << termcolor::yellow; } else { std::cout << termcolor::green; } std::cout << std::setw(7) << std::right << hashStr.str(); std::cout << termcolor::reset; if (depth % 2 == 0) { std::cout << termcolor::color<247>; } else { std::cout << termcolor::color<251>; } std::stringstream nodesStr; if (ctx->nodes >= 1000000) { nodesStr << std::fixed << std::setprecision(1) << (ctx->nodes / 1000000.0) << "M"; } else if (ctx->nodes >= 1000) { nodesStr << std::fixed << std::setprecision(1) << (ctx->nodes / 1000.0) << "k"; } else { nodesStr << ctx->nodes; } std::cout << std::setw(9) << std::right << nodesStr.str(); int nps = int(ctx->nodes/ctx->sw.GetElapsedSec()); std::stringstream npsStr; if (nps >= 1000000) { npsStr << std::fixed << std::setprecision(1) << (nps / 1000000.0) << "M/s"; } else if (nps >= 1000) { npsStr << std::fixed << std::setprecision(1) << (nps / 1000.0) << "k/s"; } else { npsStr << nps << "/s"; } std::cout << std::setw(9) << std::right << npsStr.str(); std::cout << " "; ctx->pvLine.Print(0, depth % 2 == 0); std::cout << termcolor::reset << std::endl; } } template SearchResults PVS(Board&, int, int, int, int, SearchContext* ctx, bool cutnode); template SearchResults PVS(Board&, int, int, int, int, SearchContext* ctx, bool cutnode); template SearchResults PVS(Board&, int, int, int, int, SearchContext* ctx, bool cutnode); template SearchResults PVS(Board&, int, int, int, int, SearchContext* ctx, bool cutnode); template SearchResults PVS(Board&, int, int, int, int, SearchContext* ctx, bool cutnode); template SearchResults PVS(Board&, int, int, int, int, SearchContext* ctx, bool cutnode); template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx); template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx); template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx); template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx); }