Someone lit a fire under the Stockfish team

Discussion of anything and everything relating to chess playing software and machines.

Moderators: hgm, Rebel, chrisw

User avatar
Eelco de Groot
Posts: 4561
Joined: Sun Mar 12, 2006 2:40 am
Full name:   

Re: Someone lit a fire under the Stockfish team

Post by Eelco de Groot »

Kaissa checks 'evals' that are one or more pawns above alpha, deeper in the verification search, because in that case depth of verification search is very low and at the same time result of the verification search has to drop one or more pawns, to alpha for nullmove pruning to fail. So that is a hard task for the verification even though in most cases the nullmove pruning is justified because of the large eval that was returned by TT probe or evaluation.

Probably other Matefinders can do this too?
Debugging is twice as hard as writing the code in the first
place. Therefore, if you write the code as cleverly as possible, you
are, by definition, not smart enough to debug it.
-- Brian W. Kernighan
Dann Corbit
Posts: 12538
Joined: Wed Mar 08, 2006 8:57 pm
Location: Redmond, WA USA

Re: Someone lit a fire under the Stockfish team

Post by Dann Corbit »

Redone, with a fix for temporary loss of mobility

Code: Select all

/*
  Stockfish, a UCI chess playing engine derived from Glaurung 2.1
  Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
  Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
  Copyright (C) 2015-2018 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad

  Stockfish is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Stockfish is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http&#58;//www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>   // For std&#58;&#58;memset
#include <iostream>
#include <sstream>

#include "evaluate.h"
#include "misc.h"
#include "movegen.h"
#include "movepick.h"
#include "position.h"
#include "search.h"
#include "timeman.h"
#include "thread.h"
#include "tt.h"
#include "uci.h"
#include "syzygy/tbprobe.h"

namespace Search &#123;

LimitsType Limits;
&#125;

namespace Tablebases &#123;

int Cardinality;
bool RootInTB;
bool UseRule50;
Depth ProbeDepth;
Value Score;
&#125;

namespace TB = Tablebases;

using std&#58;&#58;string;
using Eval&#58;&#58;evaluate;
using namespace Search;

namespace &#123;

// Different node types, used as a template parameter
enum NodeType &#123; NonPV, PV &#125;;

// Sizes and phases of the skip-blocks, used for distributing search depths across the threads
const int SkipSize&#91;&#93;  = &#123; 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 &#125;;
const int SkipPhase&#91;&#93; = &#123; 0, 1, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7 &#125;;

// Razor and futility margins
const int RazorMargin1 = 590;
const int RazorMargin2 = 604;
Value futility_margin&#40;Depth d, bool improving&#41; &#123;
    return Value&#40;&#40;175 - 50 * improving&#41; * d / ONE_PLY&#41;;
&#125;

// Futility and reductions lookup tables, initialized at startup
int FutilityMoveCounts&#91;2&#93;&#91;16&#93;; // &#91;improving&#93;&#91;depth&#93;
int Reductions&#91;2&#93;&#91;2&#93;&#91;64&#93;&#91;64&#93;;  // &#91;pv&#93;&#91;improving&#93;&#91;depth&#93;&#91;moveNumber&#93;

template <bool PvNode> Depth reduction&#40;bool i, Depth d, int mn&#41; &#123;
    return Reductions&#91;PvNode&#93;&#91;i&#93;&#91;std&#58;&#58;min&#40;d / ONE_PLY, 63&#41;&#93;&#91;std&#58;&#58;min&#40;mn, 63&#41;&#93; * ONE_PLY;
&#125;

// History and stats update bonus, based on depth
int stat_bonus&#40;Depth depth&#41; &#123;
    int d = depth / ONE_PLY;
    return d > 17 ? 0 &#58; d * d + 2 * d - 2;
&#125;

// Skill structure is used to implement strength limit
struct Skill &#123;
    explicit Skill&#40;int l&#41; &#58; level&#40;l&#41; &#123;&#125;
    bool enabled&#40;) const &#123;
        return level < 20;
    &#125;
    bool time_to_pick&#40;Depth depth&#41; const &#123;
        return depth / ONE_PLY == 1 + level;
    &#125;
    Move pick_best&#40;size_t multiPV&#41;;

    int level;
    Move best = MOVE_NONE;
&#125;;

template <NodeType NT>
Value search&#40;Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode, bool skipEarlyPruning, int cramped=0&#41;;

template <NodeType NT, bool InCheck>
Value qsearch&#40;Position& pos, Stack* ss, Value alpha, Value beta, Depth depth = DEPTH_ZERO&#41;;

Value value_to_tt&#40;Value v, int ply&#41;;
Value value_from_tt&#40;Value v, int ply&#41;;
void update_pv&#40;Move* pv, Move move, Move* childPv&#41;;
void update_continuation_histories&#40;Stack* ss, Piece pc, Square to, int bonus&#41;;
void update_quiet_stats&#40;const Position& pos, Stack* ss, Move move, Move* quiets, int quietsCnt, int bonus&#41;;
void update_capture_stats&#40;const Position& pos, Move move, Move* captures, int captureCnt, int bonus&#41;;

inline bool gives_check&#40;const Position& pos, Move move&#41; &#123;
    Color us = pos.side_to_move&#40;);
    return  type_of&#40;move&#41; == NORMAL && !&#40;pos.blockers_for_king&#40;~us&#41; & pos.pieces&#40;us&#41;)
            ? pos.check_squares&#40;type_of&#40;pos.moved_piece&#40;move&#41;)) & to_sq&#40;move&#41;
            &#58; pos.gives_check&#40;move&#41;;
&#125;

// perft&#40;) is our utility to verify move generation. All the leaf nodes up
// to the given depth are generated and counted, and the sum is returned.
template<bool Root>
uint64_t perft&#40;Position& pos, Depth depth&#41; &#123;

    StateInfo st;
    uint64_t cnt, nodes = 0;
    const bool leaf = &#40;depth == 2 * ONE_PLY&#41;;

    for &#40;const auto& m &#58; MoveList<LEGAL>&#40;pos&#41;)
    &#123;
        if &#40;Root && depth <= ONE_PLY&#41;
            cnt = 1, nodes++;
        else
        &#123;
            pos.do_move&#40;m, st&#41;;
            cnt = leaf ? MoveList<LEGAL>&#40;pos&#41;.size&#40;) &#58; perft<false>&#40;pos, depth - ONE_PLY&#41;;
            nodes += cnt;
            pos.undo_move&#40;m&#41;;
        &#125;
        if &#40;Root&#41;
            sync_cout << UCI&#58;&#58;move&#40;m, pos.is_chess960&#40;)) << "&#58; " << cnt << sync_endl;
    &#125;
    return nodes;
&#125;

&#125; // namespace


/// Search&#58;&#58;init&#40;) is called at startup to initialize various lookup tables

void Search&#58;&#58;init&#40;) &#123;

    for &#40;int imp = 0; imp <= 1; ++imp&#41;
        for &#40;int d = 1; d < 64; ++d&#41;
            for &#40;int mc = 1; mc < 64; ++mc&#41;
            &#123;
                double r = log&#40;d&#41; * log&#40;mc&#41; / 1.95;

                Reductions&#91;NonPV&#93;&#91;imp&#93;&#91;d&#93;&#91;mc&#93; = int&#40;std&#58;&#58;round&#40;r&#41;);
                Reductions&#91;PV&#93;&#91;imp&#93;&#91;d&#93;&#91;mc&#93; = std&#58;&#58;max&#40;Reductions&#91;NonPV&#93;&#91;imp&#93;&#91;d&#93;&#91;mc&#93; - 1, 0&#41;;

                // Increase reduction for non-PV nodes when eval is not improving
                if (!imp && Reductions&#91;NonPV&#93;&#91;imp&#93;&#91;d&#93;&#91;mc&#93; >= 2&#41;
                    Reductions&#91;NonPV&#93;&#91;imp&#93;&#91;d&#93;&#91;mc&#93;++;
            &#125;

    for &#40;int d = 0; d < 16; ++d&#41;
    &#123;
        FutilityMoveCounts&#91;0&#93;&#91;d&#93; = int&#40;2.4 + 0.74 * pow&#40;d, 1.78&#41;);
        FutilityMoveCounts&#91;1&#93;&#91;d&#93; = int&#40;5.0 + 1.00 * pow&#40;d, 2.00&#41;);
    &#125;
&#125;


/// Search&#58;&#58;clear&#40;) resets search state to its initial value

void Search&#58;&#58;clear&#40;) &#123;

    Threads.main&#40;)->wait_for_search_finished&#40;);

    Time.availableNodes = 0;
    TT.clear&#40;);
    Threads.clear&#40;);
&#125;


/// MainThread&#58;&#58;search&#40;) is called by the main thread when the program receives
/// the UCI 'go' command. It searches from the root position and outputs the "bestmove".

void MainThread&#58;&#58;search&#40;) &#123;

    if &#40;Limits.perft&#41;
    &#123;
        nodes = perft<true>&#40;rootPos, Limits.perft * ONE_PLY&#41;;
        sync_cout << "\nNodes searched&#58; " << nodes << "\n" << sync_endl;
        return;
    &#125;

    Color us = rootPos.side_to_move&#40;);
    Time.init&#40;Limits, us, rootPos.game_ply&#40;));
    TT.new_search&#40;);

    if &#40;rootMoves.empty&#40;))
    &#123;
        rootMoves.emplace_back&#40;MOVE_NONE&#41;;
        sync_cout << "info depth 0 score "
                  << UCI&#58;&#58;value&#40;rootPos.checkers&#40;) ? -VALUE_MATE &#58; VALUE_DRAW&#41;
                  << sync_endl;
    &#125;
    else
    &#123;
        for &#40;Thread* th &#58; Threads&#41;
            if &#40;th != this&#41;
                th->start_searching&#40;);

        Thread&#58;&#58;search&#40;); // Let's start searching!
    &#125;

    // When we reach the maximum depth, we can arrive here without a raise of
    // Threads.stop. However, if we are pondering or in an infinite search,
    // the UCI protocol states that we shouldn't print the best move before the
    // GUI sends a "stop" or "ponderhit" command. We therefore simply wait here
    // until the GUI sends one of those commands &#40;which also raises Threads.stop&#41;.
    Threads.stopOnPonderhit = true;

    while (!Threads.stop && &#40;Threads.ponder || Limits.infinite&#41;)
    &#123;&#125; // Busy wait for a stop or a ponder reset

    // Stop the threads if not already stopped &#40;also raise the stop if
    // "ponderhit" just reset Threads.ponder&#41;.
    Threads.stop = true;

    // Wait until all threads have finished
    for &#40;Thread* th &#58; Threads&#41;
        if &#40;th != this&#41;
            th->wait_for_search_finished&#40;);

    // When playing in 'nodes as time' mode, subtract the searched nodes from
    // the available ones before exiting.
    if &#40;Limits.npmsec&#41;
        Time.availableNodes += Limits.inc&#91;us&#93; - Threads.nodes_searched&#40;);

    // Check if there are threads with a better score than main thread
    Thread* bestThread = this;
    if (    Options&#91;"MultiPV"&#93; == 1
            && !Limits.depth
            && !Skill&#40;Options&#91;"Skill Level"&#93;).enabled&#40;)
            &&  rootMoves&#91;0&#93;.pv&#91;0&#93; != MOVE_NONE&#41;
    &#123;
        for &#40;Thread* th &#58; Threads&#41;
        &#123;
            Depth depthDiff = th->completedDepth - bestThread->completedDepth;
            Value scoreDiff = th->rootMoves&#91;0&#93;.score - bestThread->rootMoves&#91;0&#93;.score;

            // Select the thread with the best score, always if it is a mate
            if (    scoreDiff > 0
                    && &#40;depthDiff >= 0 || th->rootMoves&#91;0&#93;.score >= VALUE_MATE_IN_MAX_PLY&#41;)
                bestThread = th;
        &#125;
    &#125;

    previousScore = bestThread->rootMoves&#91;0&#93;.score;

    // Send again PV info if we have a new best thread
    if &#40;bestThread != this&#41;
        sync_cout << UCI&#58;&#58;pv&#40;bestThread->rootPos, bestThread->completedDepth, -VALUE_INFINITE, VALUE_INFINITE&#41; << sync_endl;

    sync_cout << "bestmove " << UCI&#58;&#58;move&#40;bestThread->rootMoves&#91;0&#93;.pv&#91;0&#93;, rootPos.is_chess960&#40;));

    if &#40;bestThread->rootMoves&#91;0&#93;.pv.size&#40;) > 1 || bestThread->rootMoves&#91;0&#93;.extract_ponder_from_tt&#40;rootPos&#41;)
        std&#58;&#58;cout << " ponder " << UCI&#58;&#58;move&#40;bestThread->rootMoves&#91;0&#93;.pv&#91;1&#93;, rootPos.is_chess960&#40;));

    std&#58;&#58;cout << sync_endl;
&#125;


/// Thread&#58;&#58;search&#40;) is the main iterative deepening loop. It calls search&#40;)
/// repeatedly with increasing depth until the allocated thinking time has been
/// consumed, the user stops the search, or the maximum search depth is reached.

void Thread&#58;&#58;search&#40;) &#123;

    Stack stack&#91;MAX_PLY+7&#93;, *ss = stack+4; // To reference from &#40;ss-4&#41; to &#40;ss+2&#41;
    Value bestValue, alpha, beta, delta;
    Move  lastBestMove = MOVE_NONE;
    Depth lastBestMoveDepth = DEPTH_ZERO;
    MainThread* mainThread = &#40;this == Threads.main&#40;) ? Threads.main&#40;) &#58; nullptr&#41;;
    double timeReduction = 1.0;
    Color us = rootPos.side_to_move&#40;);

    std&#58;&#58;memset&#40;ss-4, 0, 7 * sizeof&#40;Stack&#41;);
    for &#40;int i = 4; i > 0; i--)
        &#40;ss-i&#41;->contHistory = this->contHistory&#91;NO_PIECE&#93;&#91;0&#93;.get&#40;); // Use as sentinel

    bestValue = delta = alpha = -VALUE_INFINITE;
    beta = VALUE_INFINITE;

    if &#40;mainThread&#41;
        mainThread->bestMoveChanges = 0, mainThread->failedLow = false;

    size_t multiPV = Options&#91;"MultiPV"&#93;;
    Skill skill&#40;Options&#91;"Skill Level"&#93;);

    // When playing with strength handicap enable MultiPV search that we will
    // use behind the scenes to retrieve a set of possible moves.
    if &#40;skill.enabled&#40;))
        multiPV = std&#58;&#58;max&#40;multiPV, &#40;size_t&#41;4&#41;;

    multiPV = std&#58;&#58;min&#40;multiPV, rootMoves.size&#40;));

    int ct = Options&#91;"Contempt"&#93; * PawnValueEg / 100; // From centipawns
    Eval&#58;&#58;Contempt = &#40;us == WHITE ?  make_score&#40;ct, ct / 2&#41;
                      &#58; -make_score&#40;ct, ct / 2&#41;);

    // Iterative deepening loop until requested to stop or the target depth is reached
    while (   &#40;rootDepth += ONE_PLY&#41; < DEPTH_MAX
              && !Threads.stop
              && !&#40;Limits.depth && mainThread && rootDepth / ONE_PLY > Limits.depth&#41;)
    &#123;
        // Distribute search depths across the helper threads
        if &#40;idx > 0&#41;
        &#123;
            int i = &#40;idx - 1&#41; % 20;
            if ((&#40;rootDepth / ONE_PLY + rootPos.game_ply&#40;) + SkipPhase&#91;i&#93;) / SkipSize&#91;i&#93;) % 2&#41;
                continue;  // Retry with an incremented rootDepth
        &#125;

        // Age out PV variability metric
        if &#40;mainThread&#41;
            mainThread->bestMoveChanges *= 0.517, mainThread->failedLow = false;

        // Save the last iteration's scores before first PV line is searched and
        // all the move scores except the &#40;new&#41; PV are set to -VALUE_INFINITE.
        for &#40;RootMove& rm &#58; rootMoves&#41;
            rm.previousScore = rm.score;

        // MultiPV loop. We perform a full root search for each PV line
        for &#40;PVIdx = 0; PVIdx < multiPV && !Threads.stop; ++PVIdx&#41;
        &#123;
            // Reset UCI info selDepth for each depth and each PV line
            selDepth = 0;

            // Reset aspiration window starting size
            if &#40;rootDepth >= 5 * ONE_PLY&#41;
            &#123;
                delta = Value&#40;18&#41;;
                alpha = std&#58;&#58;max&#40;rootMoves&#91;PVIdx&#93;.previousScore - delta,-VALUE_INFINITE&#41;;
                beta  = std&#58;&#58;min&#40;rootMoves&#91;PVIdx&#93;.previousScore + delta, VALUE_INFINITE&#41;;

                ct =  Options&#91;"Contempt"&#93; * PawnValueEg / 100; // From centipawns

                // Adjust contempt based on current bestValue &#40;dynamic contempt&#41;
                ct += int&#40;std&#58;&#58;round&#40;48 * atan&#40;float&#40;bestValue&#41; / 128&#41;));

                Eval&#58;&#58;Contempt = &#40;us == WHITE ?  make_score&#40;ct, ct / 2&#41;
                                  &#58; -make_score&#40;ct, ct / 2&#41;);
            &#125;

            // Start with a small aspiration window and, in the case of a fail
            // high/low, re-search with a bigger window until we don't fail
            // high/low anymore.
            while &#40;true&#41;
            &#123;
                bestValue = &#58;&#58;search<PV>&#40;rootPos, ss, alpha, beta, rootDepth, false, false&#41;;

                // Bring the best move to the front. It is critical that sorting
                // is done with a stable algorithm because all the values but the
                // first and eventually the new best one are set to -VALUE_INFINITE
                // and we want to keep the same order for all the moves except the
                // new PV that goes to the front. Note that in case of MultiPV
                // search the already searched PV lines are preserved.
                std&#58;&#58;stable_sort&#40;rootMoves.begin&#40;) + PVIdx, rootMoves.end&#40;));

                // If search has been stopped, we break immediately. Sorting is
                // safe because RootMoves is still valid, although it refers to
                // the previous iteration.
                if &#40;Threads.stop&#41;
                    break;

                // When failing high/low give some update &#40;without cluttering
                // the UI&#41; before a re-search.
                if (   mainThread
                        && multiPV == 1
                        && &#40;bestValue <= alpha || bestValue >= beta&#41;
                        && Time.elapsed&#40;) > 3000&#41;
                    sync_cout << UCI&#58;&#58;pv&#40;rootPos, rootDepth, alpha, beta&#41; << sync_endl;

                // In case of failing low/high increase aspiration window and
                // re-search, otherwise exit the loop.
                if &#40;bestValue <= alpha&#41;
                &#123;
                    beta = &#40;alpha + beta&#41; / 2;
                    alpha = std&#58;&#58;max&#40;bestValue - delta, -VALUE_INFINITE&#41;;

                    if &#40;mainThread&#41;
                    &#123;
                        mainThread->failedLow = true;
                        Threads.stopOnPonderhit = false;
                    &#125;
                &#125;
                else if &#40;bestValue >= beta&#41;
                    beta = std&#58;&#58;min&#40;bestValue + delta, VALUE_INFINITE&#41;;
                else
                    break;

                delta += delta / 4 + 5;

                assert&#40;alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE&#41;;
            &#125;

            // Sort the PV lines searched so far and update the GUI
            std&#58;&#58;stable_sort&#40;rootMoves.begin&#40;), rootMoves.begin&#40;) + PVIdx + 1&#41;;

            if (    mainThread
                    && &#40;Threads.stop || PVIdx + 1 == multiPV || Time.elapsed&#40;) > 3000&#41;)
                sync_cout << UCI&#58;&#58;pv&#40;rootPos, rootDepth, alpha, beta&#41; << sync_endl;
        &#125;

        if (!Threads.stop&#41;
            completedDepth = rootDepth;

        if &#40;rootMoves&#91;0&#93;.pv&#91;0&#93; != lastBestMove&#41; &#123;
            lastBestMove = rootMoves&#91;0&#93;.pv&#91;0&#93;;
            lastBestMoveDepth = rootDepth;
        &#125;

        // Have we found a "mate in x"?
        if (   Limits.mate
                && bestValue >= VALUE_MATE_IN_MAX_PLY
                && VALUE_MATE - bestValue <= 2 * Limits.mate&#41;
            Threads.stop = true;

        if (!mainThread&#41;
            continue;

        // If skill level is enabled and time is up, pick a sub-optimal best move
        if &#40;skill.enabled&#40;) && skill.time_to_pick&#40;rootDepth&#41;)
            skill.pick_best&#40;multiPV&#41;;

        // Do we have time for the next iteration? Can we stop searching now?
        if (    Limits.use_time_management&#40;)
                && !Threads.stop
                && !Threads.stopOnPonderhit&#41;
        &#123;
            const int F&#91;&#93; = &#123; mainThread->failedLow,
                              bestValue - mainThread->previousScore
                            &#125;;

            int improvingFactor = std&#58;&#58;max&#40;246, std&#58;&#58;min&#40;832, 306 + 119 * F&#91;0&#93; - 6 * F&#91;1&#93;));

            // If the bestMove is stable over several iterations, reduce time accordingly
            timeReduction = 1.0;
            for &#40;int i &#58; &#123;
                        3, 4, 5
                    &#125;)
                if &#40;lastBestMoveDepth * i < completedDepth&#41;
                    timeReduction *= 1.25;

            // Use part of the gained time from a previous stable move for the current move
            double unstablePvFactor = 1.0 + mainThread->bestMoveChanges;
            unstablePvFactor *= std&#58;&#58;pow&#40;mainThread->previousTimeReduction, 0.528&#41; / timeReduction;

            // Stop the search if we have only one legal move, or if available time elapsed
            if (   rootMoves.size&#40;) == 1
                    || Time.elapsed&#40;) > Time.optimum&#40;) * unstablePvFactor * improvingFactor / 581&#41;
            &#123;
                // If we are allowed to ponder do not stop the search now but
                // keep pondering until the GUI sends "ponderhit" or "stop".
                if &#40;Threads.ponder&#41;
                    Threads.stopOnPonderhit = true;
                else
                    Threads.stop = true;
            &#125;
        &#125;
    &#125;

    if (!mainThread&#41;
        return;

    mainThread->previousTimeReduction = timeReduction;

    // If skill level is enabled, swap best PV line with the sub-optimal one
    if &#40;skill.enabled&#40;))
        std&#58;&#58;swap&#40;rootMoves&#91;0&#93;, *std&#58;&#58;find&#40;rootMoves.begin&#40;), rootMoves.end&#40;),
                                           skill.best ? skill.best &#58; skill.pick_best&#40;multiPV&#41;));
&#125;


namespace &#123;

// search<>() is the main search function for both PV and non-PV nodes

template <NodeType NT>
Value search&#40;Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode, bool skipEarlyPruning, int cramped&#41; &#123;

    const bool PvNode = NT == PV;
    const bool rootNode = PvNode && ss->ply == 0;

    assert&#40;-VALUE_INFINITE <= alpha && alpha < beta && beta <= VALUE_INFINITE&#41;;
    assert&#40;PvNode || &#40;alpha == beta - 1&#41;);
    assert&#40;DEPTH_ZERO < depth && depth < DEPTH_MAX&#41;;
    assert&#40;!&#40;PvNode && cutNode&#41;);
    assert&#40;depth / ONE_PLY * ONE_PLY == depth&#41;;

    size_t maxmove = 0;
    Move pv&#91;MAX_PLY+1&#93;, capturesSearched&#91;32&#93;, quietsSearched&#91;64&#93;;
    StateInfo st;
    TTEntry* tte;
    Key posKey;
    Move ttMove, move, excludedMove, bestMove;
    Depth extension, newDepth;
    Value bestValue, value, ttValue, eval, maxValue;
    bool ttHit, inCheck, givesCheck, singularExtensionNode, improving;
    bool captureOrPromotion, doFullDepthSearch, moveCountPruning, skipQuiets, ttCapture, pvExact;
    Piece movedPiece;
    int moveCount, captureCount, quietCount;

    // Step 1. Initialize node
    Thread* thisThread = pos.this_thread&#40;);
    inCheck = pos.checkers&#40;);
    moveCount = captureCount = quietCount = ss->moveCount = 0;
    bestValue = -VALUE_INFINITE;
    maxValue = VALUE_INFINITE;

    // Check for the available remaining time
    if &#40;thisThread == Threads.main&#40;))
        static_cast<MainThread*>&#40;thisThread&#41;->check_time&#40;);

    // Used to send selDepth info to GUI &#40;selDepth counts from 1, ply from 0&#41;
    if &#40;PvNode && thisThread->selDepth < ss->ply + 1&#41;
        thisThread->selDepth = ss->ply + 1;

    if (!rootNode&#41;
    &#123;
        // Step 2. Check for aborted search and immediate draw
        if (   Threads.stop.load&#40;std&#58;&#58;memory_order_relaxed&#41;
                || pos.is_draw&#40;ss->ply&#41;
                || ss->ply >= MAX_PLY&#41;
            return &#40;ss->ply >= MAX_PLY && !inCheck&#41; ? evaluate&#40;pos&#41; &#58; VALUE_DRAW;

        // Step 3. Mate distance pruning. Even if we mate at the next move our score
        // would be at best mate_in&#40;ss->ply+1&#41;, but if alpha is already bigger because
        // a shorter mate was found upward in the tree then there is no need to search
        // because we will never beat the current alpha. Same logic but with reversed
        // signs applies also in the opposite condition of being mated instead of giving
        // mate. In this case return a fail-high score.
        alpha = std&#58;&#58;max&#40;mated_in&#40;ss->ply&#41;, alpha&#41;;
        beta = std&#58;&#58;min&#40;mate_in&#40;ss->ply+1&#41;, beta&#41;;
        if &#40;alpha >= beta&#41;
            return alpha;
    &#125;

    assert&#40;0 <= ss->ply && ss->ply < MAX_PLY&#41;;

    &#40;ss+1&#41;->ply = ss->ply + 1;
    ss->currentMove = &#40;ss+1&#41;->excludedMove = bestMove = MOVE_NONE;
    ss->contHistory = thisThread->contHistory&#91;NO_PIECE&#93;&#91;0&#93;.get&#40;);
    &#40;ss+2&#41;->killers&#91;0&#93; = &#40;ss+2&#41;->killers&#91;1&#93; = MOVE_NONE;
    Square prevSq = to_sq&#40;&#40;ss-1&#41;->currentMove&#41;;

    // Initialize statScore to zero for the grandchildren of the current position.
    // So statScore is shared between all grandchildren and only the first grandchild
    // starts with statScore = 0. Later grandchildren start with the last calculated
    // statScore of the previous grandchild. This influences the reduction rules in
    // LMR which are based on the statScore of parent position.
    &#40;ss+2&#41;->statScore = 0;

    // Step 4. Transposition table lookup. We don't want the score of a partial
    // search to overwrite a previous full search TT value, so we use a different
    // position key in case of an excluded move.
    excludedMove = ss->excludedMove;
    posKey = pos.key&#40;) ^ Key&#40;excludedMove << 16&#41;; // Isn't a very good hash
    tte = TT.probe&#40;posKey, ttHit&#41;;
    ttValue = ttHit ? value_from_tt&#40;tte->value&#40;), ss->ply&#41; &#58; VALUE_NONE;
    ttMove =  rootNode ? thisThread->rootMoves&#91;thisThread->PVIdx&#93;.pv&#91;0&#93;
              &#58; ttHit    ? tte->move&#40;) &#58; MOVE_NONE;

    // At non-PV nodes we check for an early TT cutoff
    if (  !PvNode
            && ttHit
            && tte->depth&#40;) >= depth
            && ttValue != VALUE_NONE // Possible in case of TT access race
            && &#40;ttValue >= beta ? &#40;tte->bound&#40;) & BOUND_LOWER&#41;
                &#58; &#40;tte->bound&#40;) & BOUND_UPPER&#41;))
    &#123;
        // If ttMove is quiet, update move sorting heuristics on TT hit
        if &#40;ttMove&#41;
        &#123;
            if &#40;ttValue >= beta&#41;
            &#123;
                if (!pos.capture_or_promotion&#40;ttMove&#41;)
                    update_quiet_stats&#40;pos, ss, ttMove, nullptr, 0, stat_bonus&#40;depth&#41;);

                // Extra penalty for a quiet TT move in previous ply when it gets refuted
                if (&#40;ss-1&#41;->moveCount == 1 && !pos.captured_piece&#40;))
                    update_continuation_histories&#40;ss-1, pos.piece_on&#40;prevSq&#41;, prevSq, -stat_bonus&#40;depth + ONE_PLY&#41;);
            &#125;
            // Penalty for a quiet ttMove that fails low
            else if (!pos.capture_or_promotion&#40;ttMove&#41;)
            &#123;
                int penalty = -stat_bonus&#40;depth&#41;;
                thisThread->mainHistory&#91;pos.side_to_move&#40;)&#93;&#91;from_to&#40;ttMove&#41;&#93; << penalty;
                update_continuation_histories&#40;ss, pos.moved_piece&#40;ttMove&#41;, to_sq&#40;ttMove&#41;, penalty&#41;;
            &#125;
        &#125;
        return ttValue;
    &#125;

    // Step 5. Tablebases probe
    if (!rootNode && TB&#58;&#58;Cardinality&#41;
    &#123;
        int piecesCount = pos.count<ALL_PIECES>();

        if (    piecesCount <= TB&#58;&#58;Cardinality
                && &#40;piecesCount <  TB&#58;&#58;Cardinality || depth >= TB&#58;&#58;ProbeDepth&#41;
                &&  pos.rule50_count&#40;) == 0
                && !pos.can_castle&#40;ANY_CASTLING&#41;)
        &#123;
            TB&#58;&#58;ProbeState err;
            TB&#58;&#58;WDLScore wdl = Tablebases&#58;&#58;probe_wdl&#40;pos, &err&#41;;

            if &#40;err != TB&#58;&#58;ProbeState&#58;&#58;FAIL&#41;
            &#123;
                thisThread->tbHits.fetch_add&#40;1, std&#58;&#58;memory_order_relaxed&#41;;

                int drawScore = TB&#58;&#58;UseRule50 ? 1 &#58; 0;

                value =  wdl < -drawScore ? -VALUE_MATE + MAX_PLY + ss->ply + 1
                         &#58; wdl >  drawScore ?  VALUE_MATE - MAX_PLY - ss->ply - 1
                         &#58;  VALUE_DRAW + 2 * wdl * drawScore;

                Bound b =  wdl < -drawScore ? BOUND_UPPER
                           &#58; wdl >  drawScore ? BOUND_LOWER &#58; BOUND_EXACT;

                if (    b == BOUND_EXACT
                        || &#40;b == BOUND_LOWER ? value >= beta &#58; value <= alpha&#41;)
                &#123;
                    tte->save&#40;posKey, value_to_tt&#40;value, ss->ply&#41;, b,
                              std&#58;&#58;min&#40;DEPTH_MAX - ONE_PLY, depth + 6 * ONE_PLY&#41;,
                              MOVE_NONE, VALUE_NONE, TT.generation&#40;));

                    return value;
                &#125;

                if &#40;PvNode&#41;
                &#123;
                    if &#40;b == BOUND_LOWER&#41;
                        bestValue = value, alpha = std&#58;&#58;max&#40;alpha, bestValue&#41;;
                    else
                        maxValue = value;
                &#125;
            &#125;
        &#125;
    &#125;

    // Step 6. Evaluate the position statically
    if &#40;inCheck&#41;
    &#123;
        ss->staticEval = eval = VALUE_NONE;
        goto moves_loop;
    &#125;
    else if &#40;ttHit&#41;
    &#123;
        // Never assume anything on values stored in TT
        if (&#40;ss->staticEval = eval = tte->eval&#40;)) == VALUE_NONE&#41;
            eval = ss->staticEval = evaluate&#40;pos&#41;;

        // Can ttValue be used as a better position evaluation?
        if (    ttValue != VALUE_NONE
                && &#40;tte->bound&#40;) & &#40;ttValue > eval ? BOUND_LOWER &#58; BOUND_UPPER&#41;))
            eval = ttValue;
    &#125;
    else
    &#123;
        ss->staticEval = eval =
                             &#40;ss-1&#41;->currentMove != MOVE_NULL ? evaluate&#40;pos&#41;
                             &#58; -&#40;ss-1&#41;->staticEval + 2 * Eval&#58;&#58;Tempo;

        tte->save&#40;posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE,
                  ss->staticEval, TT.generation&#40;));
    &#125;

    improving =   ss->staticEval >= &#40;ss-2&#41;->staticEval
                  /* || ss->staticEval == VALUE_NONE Already implicit in the previous condition */
                  ||&#40;ss-2&#41;->staticEval == VALUE_NONE;
                  
    maxmove = MoveList<LEGAL>&#40;pos&#41;.size&#40;);
    if ( maxmove <= Options&#91;"Cramped"&#93; )
    &#123;
        cramped = 2; // We want the cramped heuristic to live for at least two plies, but go away if the mobility pinch was temporary
    &#125;
    else
    &#123;
        if &#40;cramped&#41;
            cramped--;
    &#125;
    if &#40;skipEarlyPruning || !pos.non_pawn_material&#40;pos.side_to_move&#40;)) || cramped&#41;
        goto moves_loop;

    // Step 7. Razoring &#40;skipped when in check&#41;
    if (  !PvNode
            && depth <= 2 * ONE_PLY&#41;
    &#123;
        if (   depth == ONE_PLY
                && eval + RazorMargin1 <= alpha&#41;
            return qsearch<NonPV, false>&#40;pos, ss, alpha, alpha+1&#41;;

        else if &#40;eval + RazorMargin2 <= alpha&#41;
        &#123;
            Value ralpha = alpha - RazorMargin2;
            Value v = qsearch<NonPV, false>&#40;pos, ss, ralpha, ralpha+1&#41;;

            if &#40;v <= ralpha&#41;
                return v;
        &#125;
    &#125;

    // Step 8. Futility pruning&#58; child node &#40;skipped when in check&#41;
    if (   !rootNode
            &&  depth < 7 * ONE_PLY
            &&  eval - futility_margin&#40;depth, improving&#41; >= beta
            &&  eval < VALUE_KNOWN_WIN&#41; // Do not return unproven wins
        return eval;

    // Step 9. Null move search with verification search
    if (   !PvNode
            &&  eval >= beta
            &&  ss->staticEval >= beta - 36 * depth / ONE_PLY + 225
            && &#40;ss->ply >= thisThread->nmp_ply || ss->ply % 2 != thisThread->nmp_odd&#41;)
    &#123;
        assert&#40;eval - beta >= 0&#41;;

        // Null move dynamic reduction based on depth and value
        Depth R = (&#40;823 + 67 * depth / ONE_PLY&#41; / 256 + std&#58;&#58;min&#40;&#40;eval - beta&#41; / PawnValueMg, 3&#41;) * ONE_PLY;

        ss->currentMove = MOVE_NULL;
        ss->contHistory = thisThread->contHistory&#91;NO_PIECE&#93;&#91;0&#93;.get&#40;);

        pos.do_null_move&#40;st&#41;;
        Value nullValue = depth-R < ONE_PLY ? -qsearch<NonPV, false>&#40;pos, ss+1, -beta, -beta+1&#41;
                          &#58; - search<NonPV>&#40;pos, ss+1, -beta, -beta+1, depth-R, !cutNode, true, cramped&#41;;
        pos.undo_null_move&#40;);

        if &#40;nullValue >= beta&#41;
        &#123;
            // Do not return unproven mate scores
            if &#40;nullValue >= VALUE_MATE_IN_MAX_PLY&#41;
                nullValue = beta;

            if &#40;abs&#40;beta&#41; < VALUE_KNOWN_WIN && &#40;depth < 13 * ONE_PLY || thisThread->nmp_ply&#41;)
                return nullValue;

            // Do verification search at high depths. Disable null move pruning
            // for side to move for the first part of the remaining search tree.
            thisThread->nmp_ply = ss->ply + 3 * &#40;depth-R&#41; / 4;
            thisThread->nmp_odd = ss->ply % 2;

            Value v = depth-R < ONE_PLY ? qsearch<NonPV, false>&#40;pos, ss, beta-1, beta&#41;
                      &#58;  search<NonPV>&#40;pos, ss, beta-1, beta, depth-R, false, true&#41;;

            thisThread->nmp_odd = thisThread->nmp_ply = 0;

            if &#40;v >= beta&#41;
                return nullValue;
        &#125;
    &#125;

    // Step 10. ProbCut &#40;skipped when in check&#41;
    // If we have a good enough capture and a reduced search returns a value
    // much above beta, we can &#40;almost&#41; safely prune the previous move.
    if (   !PvNode
            &&  depth >= 5 * ONE_PLY
            &&  abs&#40;beta&#41; < VALUE_MATE_IN_MAX_PLY&#41;
    &#123;
        assert&#40;is_ok&#40;&#40;ss-1&#41;->currentMove&#41;);

        Value rbeta = std&#58;&#58;min&#40;beta + 200, VALUE_INFINITE&#41;;
        MovePicker mp&#40;pos, ttMove, rbeta - ss->staticEval, &thisThread->captureHistory&#41;;
        int probCutCount = 0;

        while (  &#40;move = mp.next_move&#40;)) != MOVE_NONE
                 && probCutCount < depth / ONE_PLY - 3&#41;
            if &#40;pos.legal&#40;move&#41;)
            &#123;
                probCutCount++;

                ss->currentMove = move;
                ss->contHistory = thisThread->contHistory&#91;pos.moved_piece&#40;move&#41;&#93;&#91;to_sq&#40;move&#41;&#93;.get&#40;);

                assert&#40;depth >= 5 * ONE_PLY&#41;;

                pos.do_move&#40;move, st&#41;;

                // Perform a preliminary search at depth 1 to verify that the move holds.
                // We will only do this search if the depth is not 5, thus avoiding two
                // searches at depth 1 in a row.
                if &#40;depth != 5 * ONE_PLY&#41;
                    value = -search<NonPV>&#40;pos, ss+1, -rbeta, -rbeta+1, ONE_PLY, !cutNode, true, cramped&#41;;

                // If the first search was skipped or was performed and held, perform
                // the regular search.
                if &#40;depth == 5 * ONE_PLY || value >= rbeta&#41;
                    value = -search<NonPV>&#40;pos, ss+1, -rbeta, -rbeta+1, depth - 4 * ONE_PLY, !cutNode, false, cramped&#41;;

                pos.undo_move&#40;move&#41;;

                if &#40;value >= rbeta&#41;
                    return value;
            &#125;
    &#125;

    // Step 11. Internal iterative deepening &#40;skipped when in check&#41;
    if (    depth >= 6 * ONE_PLY
            && !ttMove
            && &#40;PvNode || ss->staticEval + 256 >= beta&#41;)
    &#123;
        Depth d = 3 * depth / 4 - 2 * ONE_PLY;
        search<NT>&#40;pos, ss, alpha, beta, d, cutNode, true, cramped&#41;;

        tte = TT.probe&#40;posKey, ttHit&#41;;
        ttValue = ttHit ? value_from_tt&#40;tte->value&#40;), ss->ply&#41; &#58; VALUE_NONE;
        ttMove = ttHit ? tte->move&#40;) &#58; MOVE_NONE;
    &#125;

moves_loop&#58; // When in check, search starts from here

    const PieceToHistory* contHist&#91;&#93; = &#123; &#40;ss-1&#41;->contHistory, &#40;ss-2&#41;->contHistory, nullptr, &#40;ss-4&#41;->contHistory &#125;;
    Move countermove = thisThread->counterMoves&#91;pos.piece_on&#40;prevSq&#41;&#93;&#91;prevSq&#93;;

    MovePicker mp&#40;pos, ttMove, depth, &thisThread->mainHistory, &thisThread->captureHistory, contHist, countermove, ss->killers&#41;;
    value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
    improving =   ss->staticEval >= &#40;ss-2&#41;->staticEval
                  /* || ss->staticEval == VALUE_NONE Already implicit in the previous condition */
                  ||&#40;ss-2&#41;->staticEval == VALUE_NONE;

    singularExtensionNode =   !rootNode
                              &&  depth >= 8 * ONE_PLY
                              &&  ttMove != MOVE_NONE
                              &&  ttValue != VALUE_NONE
                              && !excludedMove // Recursive singular search is not allowed
                              && &#40;tte->bound&#40;) & BOUND_LOWER&#41;
                              &&  tte->depth&#40;) >= depth - 3 * ONE_PLY;
    skipQuiets = false;
    ttCapture = false;
    pvExact = PvNode && ttHit && tte->bound&#40;) == BOUND_EXACT;

    // Step 12. Loop through all pseudo-legal moves until no moves remain
    // or a beta cutoff occurs.
    while (&#40;move = mp.next_move&#40;skipQuiets&#41;) != MOVE_NONE&#41;
    &#123;
        assert&#40;is_ok&#40;move&#41;);

        if &#40;move == excludedMove&#41;
            continue;

        // At root obey the "searchmoves" option and skip moves not listed in Root
        // Move List. As a consequence any illegal move is also skipped. In MultiPV
        // mode we also skip PV moves which have been already searched.
        if &#40;rootNode && !std&#58;&#58;count&#40;thisThread->rootMoves.begin&#40;) + thisThread->PVIdx,
                                    thisThread->rootMoves.end&#40;), move&#41;)
            continue;

        ss->moveCount = ++moveCount;

        if &#40;rootNode && thisThread == Threads.main&#40;) && Time.elapsed&#40;) > 3000&#41;
            sync_cout << "info depth " << depth / ONE_PLY
                      << " currmove " << UCI&#58;&#58;move&#40;move, pos.is_chess960&#40;))
                      << " currmovenumber " << moveCount + thisThread->PVIdx << sync_endl;
        if &#40;PvNode&#41;
            &#40;ss+1&#41;->pv = nullptr;

        extension = DEPTH_ZERO;
        captureOrPromotion = pos.capture_or_promotion&#40;move&#41;;
        movedPiece = pos.moved_piece&#40;move&#41;;
        givesCheck = gives_check&#40;pos, move&#41;;

        moveCountPruning =   depth < 16 * ONE_PLY
                             && moveCount >= FutilityMoveCounts&#91;improving&#93;&#91;depth / ONE_PLY&#93;;

        // Step 13. Extensions

        // Singular extension search. If all moves but one fail low on a search
        // of &#40;alpha-s, beta-s&#41;, and just one fails high on &#40;alpha, beta&#41;, then
        // that move is singular and should be extended. To verify this we do a
        // reduced search on on all the other moves but the ttMove and if the
        // result is lower than ttValue minus a margin then we will extend the ttMove.
        if (    singularExtensionNode
                &&  move == ttMove
                &&  pos.legal&#40;move&#41;)
        &#123;
            Value rBeta = std&#58;&#58;max&#40;ttValue - 2 * depth / ONE_PLY, -VALUE_MATE&#41;;
            ss->excludedMove = move;
            value = search<NonPV>&#40;pos, ss, rBeta - 1, rBeta, depth / 2, cutNode, true, cramped&#41;;
            ss->excludedMove = MOVE_NONE;

            if &#40;value < rBeta&#41;
                extension = ONE_PLY;
        &#125;
        else if (    givesCheck // Check extension
                     && !moveCountPruning
                     &&  pos.see_ge&#40;move&#41;)
            extension = ONE_PLY;

        // Calculate new depth for this move
        newDepth = depth - ONE_PLY + extension;

        // Step 14. Pruning at shallow depth
        if (  !rootNode
                && pos.non_pawn_material&#40;pos.side_to_move&#40;))
                && bestValue > VALUE_MATED_IN_MAX_PLY&#41;
        &#123;
            if (   !captureOrPromotion
                    && !givesCheck
                    && (!pos.advanced_pawn_push&#40;move&#41; || pos.non_pawn_material&#40;) >= Value&#40;5000&#41;))
            &#123;
                // Move count based pruning
                if &#40;moveCountPruning&#41;
                &#123;
                    skipQuiets = true;
                    continue;
                &#125;

                // Reduced depth of the next LMR search
                int lmrDepth = std&#58;&#58;max&#40;newDepth - reduction<PvNode>&#40;improving, depth, moveCount&#41;, DEPTH_ZERO&#41; / ONE_PLY;

                // Countermoves based pruning
                if (   lmrDepth < 3
                        && (*contHist&#91;0&#93;)&#91;movedPiece&#93;&#91;to_sq&#40;move&#41;&#93; < CounterMovePruneThreshold
                        && (*contHist&#91;1&#93;)&#91;movedPiece&#93;&#91;to_sq&#40;move&#41;&#93; < CounterMovePruneThreshold&#41;
                    continue;

                // Futility pruning&#58; parent node
                if (   lmrDepth < 7
                        && !inCheck
                        && ss->staticEval + 256 + 200 * lmrDepth <= alpha&#41;
                    continue;

                // Prune moves with negative SEE
                if (   lmrDepth < 8
                        && !pos.see_ge&#40;move, Value&#40;-35 * lmrDepth * lmrDepth&#41;))
                    continue;
            &#125;
            else if (    depth < 7 * ONE_PLY
                         && !extension
                         && !pos.see_ge&#40;move, -PawnValueEg * &#40;depth / ONE_PLY&#41;))
                continue;
        &#125;

        // Speculative prefetch as early as possible
        prefetch&#40;TT.first_entry&#40;pos.key_after&#40;move&#41;));

        // Check for legality just before making the move
        if (!rootNode && !pos.legal&#40;move&#41;)
        &#123;
            ss->moveCount = --moveCount;
            continue;
        &#125;

        if &#40;move == ttMove && captureOrPromotion&#41;
            ttCapture = true;

        // Update the current move &#40;this must be done after singular extension search&#41;
        ss->currentMove = move;
        ss->contHistory = thisThread->contHistory&#91;movedPiece&#93;&#91;to_sq&#40;move&#41;&#93;.get&#40;);

        // Step 15. Make the move
        pos.do_move&#40;move, st, givesCheck&#41;;

        // Step 16. Reduced depth search &#40;LMR&#41;. If the move fails high it will be
        // re-searched at full depth.
        if (    depth >= 3 * ONE_PLY
                &&  moveCount > 1
                && (!captureOrPromotion || moveCountPruning&#41;)
        &#123;
            Depth r = reduction<PvNode>&#40;improving, depth, moveCount&#41;;

            if &#40;captureOrPromotion&#41;
                r -= r ? ONE_PLY &#58; DEPTH_ZERO;
            else
            &#123;
                // Decrease reduction if opponent's move count is high
                if (&#40;ss-1&#41;->moveCount > 15&#41;
                    r -= ONE_PLY;

                // Decrease reduction for exact PV nodes
                if &#40;pvExact&#41;
                    r -= ONE_PLY;

                // Increase reduction if ttMove is a capture
                if &#40;ttCapture&#41;
                    r += ONE_PLY;

                // Increase reduction for cut nodes
                if &#40;cutNode&#41;
                    r += 2 * ONE_PLY;

                // Decrease reduction for moves that escape a capture. Filter out
                // castling moves, because they are coded as "king captures rook" and
                // hence break make_move&#40;).
                else if (    type_of&#40;move&#41; == NORMAL
                             && !pos.see_ge&#40;make_move&#40;to_sq&#40;move&#41;, from_sq&#40;move&#41;)))
                    r -= 2 * ONE_PLY;

                ss->statScore =  thisThread->mainHistory&#91;~pos.side_to_move&#40;)&#93;&#91;from_to&#40;move&#41;&#93;
                                 + (*contHist&#91;0&#93;)&#91;movedPiece&#93;&#91;to_sq&#40;move&#41;&#93;
                                 + (*contHist&#91;1&#93;)&#91;movedPiece&#93;&#91;to_sq&#40;move&#41;&#93;
                                 + (*contHist&#91;3&#93;)&#91;movedPiece&#93;&#91;to_sq&#40;move&#41;&#93;
                                 - 4000;

                // Decrease/increase reduction by comparing opponent's stat score
                if &#40;ss->statScore >= 0 && &#40;ss-1&#41;->statScore < 0&#41;
                    r -= ONE_PLY;

                else if (&#40;ss-1&#41;->statScore >= 0 && ss->statScore < 0&#41;
                    r += ONE_PLY;

                // Decrease/increase reduction for moves with a good/bad history
                r = std&#58;&#58;max&#40;DEPTH_ZERO, &#40;r / ONE_PLY - ss->statScore / 20000&#41; * ONE_PLY&#41;;
            &#125;

            Depth d = std&#58;&#58;max&#40;newDepth - r, ONE_PLY&#41;;

            value = -search<NonPV>&#40;pos, ss+1, -&#40;alpha+1&#41;, -alpha, d, true, false, cramped&#41;;

            doFullDepthSearch = &#40;value > alpha && d != newDepth&#41;;
        &#125;
        else
            doFullDepthSearch = !PvNode || moveCount > 1;

        // Step 17. Full depth search when LMR is skipped or fails high
        if &#40;doFullDepthSearch&#41;
            value = newDepth <   ONE_PLY ?
                    givesCheck ? -qsearch<NonPV,  true>&#40;pos, ss+1, -&#40;alpha+1&#41;, -alpha&#41;
                    &#58; -qsearch<NonPV, false>&#40;pos, ss+1, -&#40;alpha+1&#41;, -alpha&#41;
                    &#58; - search<NonPV>&#40;pos, ss+1, -&#40;alpha+1&#41;, -alpha, newDepth, !cutNode, false, cramped&#41;;

        // For PV nodes only, do a full PV search on the first move or after a fail
        // high &#40;in the latter case search only if value < beta&#41;, otherwise let the
        // parent node fail low with value <= alpha and try another move.
        if &#40;PvNode && &#40;moveCount == 1 || &#40;value > alpha && &#40;rootNode || value < beta&#41;)))
        &#123;
            &#40;ss+1&#41;->pv = pv;
            &#40;ss+1&#41;->pv&#91;0&#93; = MOVE_NONE;

            value = newDepth <   ONE_PLY ?
                    givesCheck ? -qsearch<PV,  true>&#40;pos, ss+1, -beta, -alpha&#41;
                    &#58; -qsearch<PV, false>&#40;pos, ss+1, -beta, -alpha&#41;
                    &#58; - search<PV>&#40;pos, ss+1, -beta, -alpha, newDepth, false, false, cramped&#41;;
        &#125;

        // Step 18. Undo move
        pos.undo_move&#40;move&#41;;

        assert&#40;value > -VALUE_INFINITE && value < VALUE_INFINITE&#41;;

        // Step 19. Check for a new best move
        // Finished searching the move. If a stop occurred, the return value of
        // the search cannot be trusted, and we return immediately without
        // updating best move, PV and TT.
        if &#40;Threads.stop.load&#40;std&#58;&#58;memory_order_relaxed&#41;)
            return VALUE_ZERO;

        if &#40;rootNode&#41;
        &#123;
            RootMove& rm = *std&#58;&#58;find&#40;thisThread->rootMoves.begin&#40;),
                                      thisThread->rootMoves.end&#40;), move&#41;;

            // PV move or new best move?
            if &#40;moveCount == 1 || value > alpha&#41;
            &#123;
                rm.score = value;
                rm.selDepth = thisThread->selDepth;
                rm.pv.resize&#40;1&#41;;

                assert&#40;&#40;ss+1&#41;->pv&#41;;

                for &#40;Move* m = &#40;ss+1&#41;->pv; *m != MOVE_NONE; ++m&#41;
                    rm.pv.push_back&#40;*m&#41;;

                // We record how often the best move has been changed in each
                // iteration. This information is used for time management&#58; When
                // the best move changes frequently, we allocate some more time.
                if &#40;moveCount > 1 && thisThread == Threads.main&#40;))
                    ++static_cast<MainThread*>&#40;thisThread&#41;->bestMoveChanges;
            &#125;
            else
                // All other moves but the PV are set to the lowest value&#58; this
                // is not a problem when sorting because the sort is stable and the
                // move position in the list is preserved - just the PV is pushed up.
                rm.score = -VALUE_INFINITE;
        &#125;

        if &#40;value > bestValue&#41;
        &#123;
            bestValue = value;

            if &#40;value > alpha&#41;
            &#123;
                bestMove = move;

                if &#40;PvNode && !rootNode&#41; // Update pv even in fail-high case
                    update_pv&#40;ss->pv, move, &#40;ss+1&#41;->pv&#41;;

                if &#40;PvNode && value < beta&#41; // Update alpha! Always alpha < beta
                    alpha = value;
                else
                &#123;
                    assert&#40;value >= beta&#41;; // Fail high
                    break;
                &#125;
            &#125;
        &#125;

        if &#40;move != bestMove&#41;
        &#123;
            if &#40;captureOrPromotion && captureCount < 32&#41;
                capturesSearched&#91;captureCount++&#93; = move;

            else if (!captureOrPromotion && quietCount < 64&#41;
                quietsSearched&#91;quietCount++&#93; = move;
        &#125;
    &#125;

    // The following condition would detect a stop only after move loop has been
    // completed. But in this case bestValue is valid because we have fully
    // searched our subtree, and we can anyhow save the result in TT.
    /*
       if &#40;Threads.stop&#41;
        return VALUE_DRAW;
    */

    // Step 20. Check for mate and stalemate
    // All legal moves have been searched and if there are no legal moves, it
    // must be a mate or a stalemate. If we are in a singular extension search then
    // return a fail low score.
    assert&#40;moveCount || !inCheck || excludedMove || !maxmove&#41;;

    if (!moveCount&#41;
        bestValue = excludedMove ? alpha
                    &#58;     inCheck ? mated_in&#40;ss->ply&#41; &#58; VALUE_DRAW;
    else if &#40;bestMove&#41;
    &#123;
        // Quiet best move&#58; update move sorting heuristics
        if (!pos.capture_or_promotion&#40;bestMove&#41;)
            update_quiet_stats&#40;pos, ss, bestMove, quietsSearched, quietCount, stat_bonus&#40;depth&#41;);
        else
            update_capture_stats&#40;pos, bestMove, capturesSearched, captureCount, stat_bonus&#40;depth&#41;);

        // Extra penalty for a quiet TT move in previous ply when it gets refuted
        if (&#40;ss-1&#41;->moveCount == 1 && !pos.captured_piece&#40;))
            update_continuation_histories&#40;ss-1, pos.piece_on&#40;prevSq&#41;, prevSq, -stat_bonus&#40;depth + ONE_PLY&#41;);
    &#125;
    // Bonus for prior countermove that caused the fail low
    else if (    depth >= 3 * ONE_PLY
                 && !pos.captured_piece&#40;)
                 && is_ok&#40;&#40;ss-1&#41;->currentMove&#41;)
        update_continuation_histories&#40;ss-1, pos.piece_on&#40;prevSq&#41;, prevSq, stat_bonus&#40;depth&#41;);

    if &#40;PvNode&#41;
        bestValue = std&#58;&#58;min&#40;bestValue, maxValue&#41;;

    if (!excludedMove&#41;
        tte->save&#40;posKey, value_to_tt&#40;bestValue, ss->ply&#41;,
                  bestValue >= beta ? BOUND_LOWER &#58;
                  PvNode && bestMove ? BOUND_EXACT &#58; BOUND_UPPER,
                  depth, bestMove, ss->staticEval, TT.generation&#40;));

    assert&#40;bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE&#41;;

    return bestValue;
&#125;


// qsearch&#40;) is the quiescence search function, which is called by the main
// search function with depth zero, or recursively with depth less than ONE_PLY.

template <NodeType NT, bool InCheck>
Value qsearch&#40;Position& pos, Stack* ss, Value alpha, Value beta, Depth depth&#41; &#123;

    const bool PvNode = NT == PV;

    assert&#40;alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE&#41;;
    assert&#40;PvNode || &#40;alpha == beta - 1&#41;);
    assert&#40;depth <= DEPTH_ZERO&#41;;
    assert&#40;depth / ONE_PLY * ONE_PLY == depth&#41;;
    assert&#40;InCheck == bool&#40;pos.checkers&#40;)));

    Move pv&#91;MAX_PLY+1&#93;;
    StateInfo st;
    TTEntry* tte;
    Key posKey;
    Move ttMove, move, bestMove;
    Depth ttDepth;
    Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
    bool ttHit, givesCheck, evasionPrunable;
    int moveCount;

    if &#40;PvNode&#41;
    &#123;
        oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
        &#40;ss+1&#41;->pv = pv;
        ss->pv&#91;0&#93; = MOVE_NONE;
    &#125;

    &#40;ss+1&#41;->ply = ss->ply + 1;
    ss->currentMove = bestMove = MOVE_NONE;
    moveCount = 0;

    // Check for an immediate draw or maximum ply reached
    if (   pos.is_draw&#40;ss->ply&#41;
            || ss->ply >= MAX_PLY&#41;
        return &#40;ss->ply >= MAX_PLY && !InCheck&#41; ? evaluate&#40;pos&#41; &#58; VALUE_DRAW;

    assert&#40;0 <= ss->ply && ss->ply < MAX_PLY&#41;;

    // Decide whether or not to include checks&#58; this fixes also the type of
    // TT entry depth that we are going to use. Note that in qsearch we use
    // only two types of depth in TT&#58; DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
    ttDepth = InCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
              &#58; DEPTH_QS_NO_CHECKS;
    // Transposition table lookup
    posKey = pos.key&#40;);
    tte = TT.probe&#40;posKey, ttHit&#41;;
    ttValue = ttHit ? value_from_tt&#40;tte->value&#40;), ss->ply&#41; &#58; VALUE_NONE;
    ttMove = ttHit ? tte->move&#40;) &#58; MOVE_NONE;

    if (  !PvNode
            && ttHit
            && tte->depth&#40;) >= ttDepth
            && ttValue != VALUE_NONE // Only in case of TT access race
            && &#40;ttValue >= beta ? &#40;tte->bound&#40;) &  BOUND_LOWER&#41;
                &#58; &#40;tte->bound&#40;) &  BOUND_UPPER&#41;))
        return ttValue;

    // Evaluate the position statically
    if &#40;InCheck&#41;
    &#123;
        ss->staticEval = VALUE_NONE;
        bestValue = futilityBase = -VALUE_INFINITE;
    &#125;
    else
    &#123;
        if &#40;ttHit&#41;
        &#123;
            // Never assume anything on values stored in TT
            if (&#40;ss->staticEval = bestValue = tte->eval&#40;)) == VALUE_NONE&#41;
                ss->staticEval = bestValue = evaluate&#40;pos&#41;;

            // Can ttValue be used as a better position evaluation?
            if (   ttValue != VALUE_NONE
                    && &#40;tte->bound&#40;) & &#40;ttValue > bestValue ? BOUND_LOWER &#58; BOUND_UPPER&#41;))
                bestValue = ttValue;
        &#125;
        else
            ss->staticEval = bestValue =
                                 &#40;ss-1&#41;->currentMove != MOVE_NULL ? evaluate&#40;pos&#41;
                                 &#58; -&#40;ss-1&#41;->staticEval + 2 * Eval&#58;&#58;Tempo;

        // Stand pat. Return immediately if static value is at least beta
        if &#40;bestValue >= beta&#41;
        &#123;
            if (!ttHit&#41;
                tte->save&#40;posKey, value_to_tt&#40;bestValue, ss->ply&#41;, BOUND_LOWER,
                          DEPTH_NONE, MOVE_NONE, ss->staticEval, TT.generation&#40;));

            return bestValue;
        &#125;

        if &#40;PvNode && bestValue > alpha&#41;
            alpha = bestValue;

        futilityBase = bestValue + 128;
    &#125;

    // Initialize a MovePicker object for the current position, and prepare
    // to search the moves. Because the depth is <= 0 here, only captures,
    // queen promotions and checks &#40;only if depth >= DEPTH_QS_CHECKS&#41; will
    // be generated.
    MovePicker mp&#40;pos, ttMove, depth, &pos.this_thread&#40;)->mainHistory, &pos.this_thread&#40;)->captureHistory, to_sq&#40;&#40;ss-1&#41;->currentMove&#41;);

    // Loop through the moves until no moves remain or a beta cutoff occurs
    while (&#40;move = mp.next_move&#40;)) != MOVE_NONE&#41;
    &#123;
        assert&#40;is_ok&#40;move&#41;);

        givesCheck = gives_check&#40;pos, move&#41;;

        moveCount++;

        // Futility pruning
        if (   !InCheck
                && !givesCheck
                &&  futilityBase > -VALUE_KNOWN_WIN
                && !pos.advanced_pawn_push&#40;move&#41;)
        &#123;
            assert&#40;type_of&#40;move&#41; != ENPASSANT&#41;; // Due to !pos.advanced_pawn_push

            futilityValue = futilityBase + PieceValue&#91;EG&#93;&#91;pos.piece_on&#40;to_sq&#40;move&#41;)&#93;;

            if &#40;futilityValue <= alpha&#41;
            &#123;
                bestValue = std&#58;&#58;max&#40;bestValue, futilityValue&#41;;
                continue;
            &#125;

            if &#40;futilityBase <= alpha && !pos.see_ge&#40;move, VALUE_ZERO + 1&#41;)
            &#123;
                bestValue = std&#58;&#58;max&#40;bestValue, futilityBase&#41;;
                continue;
            &#125;
        &#125;

        // Detect non-capture evasions that are candidates to be pruned
        evasionPrunable =    InCheck
                             &&  &#40;depth != DEPTH_ZERO || moveCount > 2&#41;
                             &&  bestValue > VALUE_MATED_IN_MAX_PLY
                             && !pos.capture&#40;move&#41;;

        // Don't search moves with negative SEE values
        if (  (!InCheck || evasionPrunable&#41;
                && !pos.see_ge&#40;move&#41;)
            continue;

        // Speculative prefetch as early as possible
        prefetch&#40;TT.first_entry&#40;pos.key_after&#40;move&#41;));

        // Check for legality just before making the move
        if (!pos.legal&#40;move&#41;)
        &#123;
            moveCount--;
            continue;
        &#125;

        ss->currentMove = move;

        // Make and search the move
        pos.do_move&#40;move, st, givesCheck&#41;;
        value = givesCheck ? -qsearch<NT,  true>&#40;pos, ss+1, -beta, -alpha, depth - ONE_PLY&#41;
                &#58; -qsearch<NT, false>&#40;pos, ss+1, -beta, -alpha, depth - ONE_PLY&#41;;
        pos.undo_move&#40;move&#41;;

        assert&#40;value > -VALUE_INFINITE && value < VALUE_INFINITE&#41;;

        // Check for a new best move
        if &#40;value > bestValue&#41;
        &#123;
            bestValue = value;

            if &#40;value > alpha&#41;
            &#123;
                if &#40;PvNode&#41; // Update pv even in fail-high case
                    update_pv&#40;ss->pv, move, &#40;ss+1&#41;->pv&#41;;

                if &#40;PvNode && value < beta&#41; // Update alpha here!
                &#123;
                    alpha = value;
                    bestMove = move;
                &#125;
                else // Fail high
                &#123;
                    tte->save&#40;posKey, value_to_tt&#40;value, ss->ply&#41;, BOUND_LOWER,
                              ttDepth, move, ss->staticEval, TT.generation&#40;));

                    return value;
                &#125;
            &#125;
        &#125;
    &#125;

    // All legal moves have been searched. A special case&#58; If we're in check
    // and no legal moves were found, it is checkmate.
    if &#40;InCheck && bestValue == -VALUE_INFINITE&#41;
        return mated_in&#40;ss->ply&#41;; // Plies to mate from the root

    tte->save&#40;posKey, value_to_tt&#40;bestValue, ss->ply&#41;,
              PvNode && bestValue > oldAlpha ? BOUND_EXACT &#58; BOUND_UPPER,
              ttDepth, bestMove, ss->staticEval, TT.generation&#40;));

    assert&#40;bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE&#41;;

    return bestValue;
&#125;

[/code]
Taking ideas is not a vice, it is a virtue. We have another word for this. It is called learning.
But sharing ideas is an even greater virtue. We have another word for this. It is called teaching.
CheckersGuy
Posts: 273
Joined: Wed Aug 24, 2016 9:49 pm

Re: Someone lit a fire under the Stockfish team

Post by CheckersGuy »

Next time just post a link to a repo or something else instead of that wall of text :lol:
Jouni
Posts: 3281
Joined: Wed Mar 08, 2006 8:15 pm

Re: Someone lit a fire under the Stockfish team

Post by Jouni »

When I look at NCM testing (averaged!) SF9 was 151,4 over SF7. And now we are at 154,2. So +2,8 ELO gain after a lot of patches :? .
Jouni
Dann Corbit
Posts: 12538
Joined: Wed Mar 08, 2006 8:57 pm
Location: Redmond, WA USA

Re: Someone lit a fire under the Stockfish team

Post by Dann Corbit »

Jouni wrote:When I look at NCM testing (averaged!) SF9 was 151,4 over SF7. And now we are at 154,2. So +2,8 ELO gain after a lot of patches :? .
It takes about a year to get 50 Elo.
I am waiting on Pohl to test the current stuff.
Taking ideas is not a vice, it is a virtue. We have another word for this. It is called learning.
But sharing ideas is an even greater virtue. We have another word for this. It is called teaching.
zenpawn
Posts: 349
Joined: Sat Aug 06, 2016 8:31 pm
Location: United States

Re: Someone lit a fire under the Stockfish team

Post by zenpawn »

Dann Corbit wrote:Redone, with a fix for temporary loss of mobility
Did this ever get tested via Fishtest? I'm curious how it did/will do, as while it also helped my engine solve the mate-in-5 posted earlier, it did worse in a 1000-game match vs Nemeton than without the change. Rather unfortunate, since it's nice not to have these blindspots.
JJJ
Posts: 1346
Joined: Sat Apr 19, 2014 1:47 pm

Re: Someone lit a fire under the Stockfish team

Post by JJJ »

Stockfish dev is already + 13 elo from Stockfish 9. NCM is not very accurate.
User avatar
Eelco de Groot
Posts: 4561
Joined: Sun Mar 12, 2006 2:40 am
Full name:   

Re: Someone lit a fire under the Stockfish team

Post by Eelco de Groot »

A nice LTC pass for this latest patch from Vondele, and that for a SEE change :) Statistically you can't infer much from the number of games to pass SPRT but still nice!
Refine SEE threshold for capture pruning.

eloDoc suggests that this part of search is worth ~18 Elo.
This patch refines the depth dependence of the SEE threshold.

passed STC:
LLR: 2.96 (-2.94,2.94) [0.00,5.00]
Total: 21398 W: 4474 L: 4245 D: 12679
http://tests.stockfishchess.org/tests/v ... 1a560aae07

passed LTC:
LLR: 2.95 (-2.94,2.94) [0.00,5.00]
Total: 9028 W: 1439 L: 1285 D: 6304
http://tests.stockfishchess.org/tests/v ... 1a560aae11

Closes #1527
eloDoc sounds good, but I admit I have no idea what it is...
Debugging is twice as hard as writing the code in the first
place. Therefore, if you write the code as cleverly as possible, you
are, by definition, not smart enough to debug it.
-- Brian W. Kernighan
Vizvezdenec
Posts: 52
Joined: Fri Jan 12, 2018 1:30 am

Re: Someone lit a fire under the Stockfish team

Post by Vizvezdenec »

It's depth dependant SEE threshhold, basically some tweak of SEE pruning.
User avatar
Eelco de Groot
Posts: 4561
Joined: Sun Mar 12, 2006 2:40 am
Full name:   

Re: Someone lit a fire under the Stockfish team

Post by Eelco de Groot »

Vizvezdenec wrote:It's depth dependant SEE threshhold, basically some tweak of SEE pruning.
Aha, thanks Michael, then I understand a bit better the positive effect it has on Elo at longer time controls.
Debugging is twice as hard as writing the code in the first
place. Therefore, if you write the code as cleverly as possible, you
are, by definition, not smart enough to debug it.
-- Brian W. Kernighan