diff --git a/source/accumulator.cpp b/source/accumulator.cpp index 1a3ac43..05992cc 100644 --- a/source/accumulator.cpp +++ b/source/accumulator.cpp @@ -7,80 +7,180 @@ namespace ACC { int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored) { if (perspective == Black) { - side = 1 - side; // Flip side - square = square ^ 0b111000; // Mirror square + side = 1 - side; + square = square ^ 0b111000; } if (mirrored) square ^= 7; - + return side * 64 * 6 + pieceType * 64 + square; } -// All friendly, for quiets -void AccumulatorPair::addSub(bool stm, int add, int addPT, int sub, int subPT, BucketPair bp) { - int addW = CalculateIndex(White, stm, addPT, add, mirroredWhite); - int addB = CalculateIndex(Black, stm, addPT, add, mirroredBlack); +const int16_t* Row(int bucket, int index) { + return &NNUE::net.accumulator_weights[bucket][static_cast(index) * NNUE::HL_SIZE]; +} - int subW = CalculateIndex(White, stm, subPT, sub, mirroredWhite); - int subB = CalculateIndex(Black, stm, subPT, sub, mirroredBlack); - - for (int i = 0; i < NNUE::HL_SIZE; i++) { - white[i] += NNUE::net.accumulator_weights[bp.white][addW * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.white][subW * NNUE::HL_SIZE + i]; - - black[i] += NNUE::net.accumulator_weights[bp.black][addB * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.black][subB * NNUE::HL_SIZE + i]; +void FinnyTable::Reset() { + for (auto& perspective : entries) { + for (auto& mirror : perspective) { + for (auto& entry : mirror) { + entry.acc = NNUE::net.accumulator_biases; + for (auto& color : entry.bb) + for (auto& bb : color) + bb = 0; + } + } } } -// Captures -void AccumulatorPair::addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp) { - int addW = CalculateIndex(White, stm, addPT, add, mirroredWhite); - int addB = CalculateIndex(Black, stm, addPT, add, mirroredBlack); +#if defined(_MSC_VER) && !defined(__clang__) + #define ACC_NOINLINE __declspec(noinline) +#else + #define ACC_NOINLINE __attribute__((noinline)) +#endif - int subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite); - int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack); +#if defined(__AVX512F__) && defined(__AVX512BW__) + #include + using Vec = __m512i; + static inline Vec vLoad(const int16_t* p) { return _mm512_loadu_si512(p); } + static inline void vStore(int16_t* p, Vec v) { _mm512_storeu_si512(p, v); } + static inline Vec vAdd(Vec a, Vec b) { return _mm512_add_epi16(a, b); } + static inline Vec vSub(Vec a, Vec b) { return _mm512_sub_epi16(a, b); } + #define ACC_SIMD 1 +#elif defined(__AVX2__) + #include + using Vec = __m256i; + static inline Vec vLoad(const int16_t* p) { return _mm256_loadu_si256(reinterpret_cast(p)); } + static inline void vStore(int16_t* p, Vec v) { _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v); } + static inline Vec vAdd(Vec a, Vec b) { return _mm256_add_epi16(a, b); } + static inline Vec vSub(Vec a, Vec b) { return _mm256_sub_epi16(a, b); } + #define ACC_SIMD 1 +#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) + #include + using Vec = __m128i; + static inline Vec vLoad(const int16_t* p) { return _mm_loadu_si128(reinterpret_cast(p)); } + static inline void vStore(int16_t* p, Vec v) { _mm_storeu_si128(reinterpret_cast<__m128i*>(p), v); } + static inline Vec vAdd(Vec a, Vec b) { return _mm_add_epi16(a, b); } + static inline Vec vSub(Vec a, Vec b) { return _mm_sub_epi16(a, b); } + #define ACC_SIMD 1 +#elif defined(__aarch64__) + #include + using Vec = int16x8_t; + static inline Vec vLoad(const int16_t* p) { return vld1q_s16(p); } + static inline void vStore(int16_t* p, Vec v) { vst1q_s16(p, v); } + static inline Vec vAdd(Vec a, Vec b) { return vaddq_s16(a, b); } + static inline Vec vSub(Vec a, Vec b) { return vsubq_s16(a, b); } + #define ACC_SIMD 1 +#endif - int subW2 = CalculateIndex(White, !stm, subPT2, sub2, mirroredWhite); - int subB2 = CalculateIndex(Black, !stm, subPT2, sub2, mirroredBlack); +#ifdef ACC_SIMD - for (int i = 0; i < NNUE::HL_SIZE; i++) { - white[i] += NNUE::net.accumulator_weights[bp.white][addW * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.white][subW1 * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.white][subW2 * NNUE::HL_SIZE + i]; +constexpr size_t LANES = sizeof(Vec) / sizeof(int16_t); +constexpr size_t TILE = 4; +constexpr size_t STEP = LANES * TILE; +static_assert(NNUE::HL_SIZE % STEP == 0, "HL size must be divisible by the SIMD tile size"); - black[i] += NNUE::net.accumulator_weights[bp.black][addB * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.black][subB1 * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.black][subB2 * NNUE::HL_SIZE + i]; +template +ACC_NOINLINE static void ApplyKernel(int16_t* dst, const int16_t* src, + const int16_t* a1, const int16_t* a2, + const int16_t* s1, const int16_t* s2) { + for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) { + Vec r[TILE]; + + for (size_t u = 0; u < TILE; u++) r[u] = vLoad(src + i + u * LANES); + for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a1 + i + u * LANES)); + if constexpr (NA > 1) + for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a2 + i + u * LANES)); + for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s1 + i + u * LANES)); + if constexpr (NS > 1) + for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s2 + i + u * LANES)); + + for (size_t u = 0; u < TILE; u++) vStore(dst + i + u * LANES, r[u]); } } -// Castling -void AccumulatorPair::addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp) { - int addW1 = CalculateIndex(White, stm, addPT1, add1, mirroredWhite); - int addB1 = CalculateIndex(Black, stm, addPT1, add1, mirroredBlack); +ACC_NOINLINE static void InPlaceKernel(int16_t* acc, const int16_t* const* adds, int nAdds, + const int16_t* const* subs, int nSubs) { + for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) { + Vec r[TILE]; - int addW2 = CalculateIndex(White, stm, addPT2, add2, mirroredWhite); - int addB2 = CalculateIndex(Black, stm, addPT2, add2, mirroredBlack); + for (size_t u = 0; u < TILE; u++) r[u] = vLoad(acc + i + u * LANES); - int subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite); - int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack); + for (int j = 0; j < nAdds; j++) + for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(adds[j] + i + u * LANES)); - int subW2 = CalculateIndex(White, stm, subPT2, sub2, mirroredWhite); - int subB2 = CalculateIndex(Black, stm, subPT2, sub2, mirroredBlack); + for (int j = 0; j < nSubs; j++) + for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(subs[j] + i + u * LANES)); - for (int i = 0; i < NNUE::HL_SIZE; i++) { - white[i] += NNUE::net.accumulator_weights[bp.white][addW1 * NNUE::HL_SIZE + i] - + NNUE::net.accumulator_weights[bp.white][addW2 * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.white][subW1 * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.white][subW2 * NNUE::HL_SIZE + i]; - - black[i] += NNUE::net.accumulator_weights[bp.black][addB1 * NNUE::HL_SIZE + i] - + NNUE::net.accumulator_weights[bp.black][addB2 * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.black][subB1 * NNUE::HL_SIZE + i] - - NNUE::net.accumulator_weights[bp.black][subB2 * NNUE::HL_SIZE + i]; + for (size_t u = 0; u < TILE; u++) vStore(acc + i + u * LANES, r[u]); } } +void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) { + if (a2) + ApplyKernel<2, 2>(dst.data(), src.data(), a1, a2, s1, s2); + else if (s2) + ApplyKernel<1, 2>(dst.data(), src.data(), a1, nullptr, s1, s2); + else + ApplyKernel<1, 1>(dst.data(), src.data(), a1, nullptr, s1, nullptr); +} + +void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) { + InPlaceKernel(acc.data(), adds, nAdds, subs, nSubs); +} + +void AddRow(Accumulator& acc, const int16_t* row) { + const int16_t* rows[1] = {row}; + InPlaceKernel(acc.data(), rows, 1, nullptr, 0); +} + +#else + +using Ptr = int16_t* __restrict; +using CPtr = const int16_t* __restrict; + +ACC_NOINLINE static void Kernel1p1m(Ptr dst, CPtr src, CPtr a, CPtr s) { + for (size_t i = 0; i < NNUE::HL_SIZE; i++) + dst[i] = static_cast(src[i] + a[i] - s[i]); +} + +ACC_NOINLINE static void Kernel1p2m(Ptr dst, CPtr src, CPtr a, CPtr s1, CPtr s2) { + for (size_t i = 0; i < NNUE::HL_SIZE; i++) + dst[i] = static_cast(src[i] + a[i] - s1[i] - s2[i]); +} + +ACC_NOINLINE static void Kernel2p2m(Ptr dst, CPtr src, CPtr a1, CPtr a2, CPtr s1, CPtr s2) { + for (size_t i = 0; i < NNUE::HL_SIZE; i++) + dst[i] = static_cast(src[i] + a1[i] + a2[i] - s1[i] - s2[i]); +} + +void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) { + if (a2) + Kernel2p2m(dst.data(), src.data(), a1, a2, s1, s2); + else if (s2) + Kernel1p2m(dst.data(), src.data(), a1, s1, s2); + else + Kernel1p1m(dst.data(), src.data(), a1, s1); +} + +void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) { + int16_t* p = acc.data(); + + for (int j = 0; j < nAdds; j++) + for (size_t i = 0; i < NNUE::HL_SIZE; i++) + p[i] = static_cast(p[i] + adds[j][i]); + + for (int j = 0; j < nSubs; j++) + for (size_t i = 0; i < NNUE::HL_SIZE; i++) + p[i] = static_cast(p[i] - subs[j][i]); +} + +void AddRow(Accumulator& acc, const int16_t* row) { + const int16_t* rows[1] = {row}; + ApplyInPlace(acc, rows, 1, nullptr, 0); +} + +#endif + } diff --git a/source/accumulator.h b/source/accumulator.h index 942fa3f..597cabd 100644 --- a/source/accumulator.h +++ b/source/accumulator.h @@ -1,4 +1,7 @@ #pragma once +#include +#include +#include #include "nnue.h" namespace ACC { @@ -11,18 +14,85 @@ struct BucketPair { using Accumulator = std::array; struct AccumulatorPair { - alignas(32) Accumulator white; - alignas(32) Accumulator black; - - bool mirroredWhite = false; - bool mirroredBlack = false; + alignas(ALIGNMENT) Accumulator white; + alignas(ALIGNMENT) Accumulator black; - // yoinked from Quinniboi - Prelude - void addSub(bool stm, int add, int addPT, int sub, int subPT, BucketPair bp); - void addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp); - void addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp); + Accumulator& get(bool perspective) { return perspective ? black : white; } + const Accumulator& get(bool perspective) const { return perspective ? black : white; } +}; + +enum class UpdateType : uint8_t { + None, + Refresh, + Copy, + Delta +}; + +struct Update { + UpdateType type = UpdateType::None; + uint8_t refreshMask = 0; + bool stm = false; + bool sub2Opp = false; + uint8_t nAdd = 0, nSub = 0; + int8_t add1 = 0, addPT1 = 0, add2 = 0, addPT2 = 0; + int8_t sub1 = 0, subPT1 = 0, sub2 = 0, subPT2 = 0; + + void setAddSub(bool s, int add, int addPT, int sub, int subPT) { + type = UpdateType::Delta; + stm = s; sub2Opp = false; nAdd = 1; nSub = 1; + add1 = add; addPT1 = addPT; sub1 = sub; subPT1 = subPT; + } + + void setAddSubSub(bool s, int add, int addPT, int sub1_, int subPT1_, int sub2_, int subPT2_) { + type = UpdateType::Delta; + stm = s; sub2Opp = true; nAdd = 1; nSub = 2; + add1 = add; addPT1 = addPT; + sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_; + } + + void setAddAddSubSub(bool s, int add1_, int addPT1_, int add2_, int addPT2_, int sub1_, int subPT1_, int sub2_, int subPT2_) { + type = UpdateType::Delta; + stm = s; sub2Opp = false; nAdd = 2; nSub = 2; + add1 = add1_; addPT1 = addPT1_; add2 = add2_; addPT2 = addPT2_; + sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_; + } + + void setRefresh() { + *this = Update(); + type = UpdateType::Refresh; + } +}; + +struct FinnyEntry { + alignas(ALIGNMENT) Accumulator acc; + uint64_t bb[2][6]; +}; + +struct FinnyTable { + FinnyEntry entries[2][2][NNUE::INPUT_BUCKETS]; + + void Reset(); +}; + +struct AccStack { + std::vector slots; + std::vector cur; + FinnyTable finny; + + explicit AccStack(size_t n) : slots(n), cur(n, nullptr) { finny.Reset(); } + + AccStack(const AccStack& other) : AccStack(other.slots.size()) {} + AccStack& operator=(const AccStack&) { return *this; } }; int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored); +const int16_t* Row(int bucket, int index); + +void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2); + +void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs); + +void AddRow(Accumulator& acc, const int16_t* row); + } diff --git a/source/board.cpp b/source/board.cpp index 462b527..693d883 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -1,3 +1,4 @@ +#include #include "board.h" #include "accumulator.h" #include "movegen.h" @@ -30,7 +31,9 @@ void Board::Reset() { pieces = std::array(); colors = std::array(); - accPair = ACC::AccumulatorPair(); + accUpdate.setRefresh(); + mirroredWhite = false; + mirroredBlack = false; pieceThreats = std::array(); colorThreats = std::array(); @@ -52,7 +55,6 @@ void Board::Reset() { void Board::SetByFen(std::string_view fen) { Reset(); - // Starting from top left int currSquare = a8; std::vector tokens = UTILS::split(fen, ' '); @@ -88,7 +90,6 @@ void Board::SetByFen(std::string_view fen) { if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]); - // full and half move if (tokens.size() > 4) { halfMoves = std::stoi(tokens[4]); fullMoves = std::stoi(tokens[5]); @@ -110,13 +111,13 @@ void Board::SetByFen(std::string_view fen) { int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8; if (whiteKingFile > 3) { - accPair.mirroredWhite = true; + mirroredWhite = true; } if (blackKingFile > 3) { - accPair.mirroredBlack = true; + mirroredBlack = true; } - ResetAccPair(); + accUpdate.setRefresh(); } std::string Board::GetFen() { @@ -334,10 +335,8 @@ void Board::RemovePiece(int piece, int square, bool color) { } } -// Updates castling rights static void UpdateCastlingRights(Board &board, int square, int type, int color) { if (type == Rook) { - // Removing old rights board.hashKey ^= UTILS::zCastle[board.castlingRights]; int queenSideRook = color ? a8 : a1; int kingSideRook = color ? h8 : h1; @@ -350,7 +349,6 @@ static void UpdateCastlingRights(Board &board, int square, int type, int color) board.hashKey ^= UTILS::zCastle[board.castlingRights]; } else if (type == King) { - // Removing old rights board.hashKey ^= UTILS::zCastle[board.castlingRights]; board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; @@ -371,8 +369,13 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) { } void Board::MakeMove(Move move) { - // Null Move + const bool accParentClean = accUpdate.type == ACC::UpdateType::None; + accUpdate = ACC::Update(); + if (!move) { + if (accParentClean) accUpdate.type = ACC::UpdateType::Copy; + else accUpdate.setRefresh(); + int newEpTarget = noEPTarget; sideToMove = !sideToMove; @@ -397,30 +400,28 @@ void Board::MakeMove(Move move) { int endPiece = attackerPiece; - bool fullRecalc = false; - const auto bucketPair = GetBuckets(); + uint8_t refreshMask = 0; if (attackerPiece == King) { const int toFile = move.MoveTo() % 8; if (attackerColor == White) { - if ((toFile > 3) != accPair.mirroredWhite) { - accPair.mirroredWhite = !accPair.mirroredWhite; - fullRecalc = true; + if ((toFile > 3) != mirroredWhite) { + mirroredWhite = !mirroredWhite; + refreshMask |= 1 << White; } } else { - if ((toFile > 3) != accPair.mirroredBlack) { - accPair.mirroredBlack = !accPair.mirroredBlack; - fullRecalc = true; + if ((toFile > 3) != mirroredBlack) { + mirroredBlack = !mirroredBlack; + refreshMask |= 1 << Black; } } if (NNUE::kingBuckets[attackerColor][move.MoveFrom()] != NNUE::kingBuckets[attackerColor][move.MoveTo()]) { - fullRecalc = true; + refreshMask |= 1 << attackerColor; } } - // Removing attacker piece from old position RemovePiece(attackerPiece, move.MoveFrom(), attackerColor); if (move.IsPromo()) { @@ -432,16 +433,16 @@ void Board::MakeMove(Move move) { } } - if (!fullRecalc) { + { if (move.IsCapture()) { if (move.GetFlags() != epCapture) { - accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece, bucketPair); + accUpdate.setAddSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece); } else { - accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn, bucketPair); + accUpdate.setAddSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn); } } else { if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) { - accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, bucketPair); + accUpdate.setAddSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece); } } } @@ -470,16 +471,14 @@ void Board::MakeMove(Move move) { { int rookSquare = attackerColor ? h8 : h1; - // Removing rook from old position RemovePiece(Rook, rookSquare, attackerColor); - // Setting rook on new position SetPiece(Rook, rookSquare - 2, attackerColor); SetPiece(attackerPiece, move.MoveTo(), attackerColor); - if (!fullRecalc) { - accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair); + { + accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook); } break; @@ -488,16 +487,14 @@ void Board::MakeMove(Move move) { { int rookSquare = attackerColor ? a8 : a1; - // Removing rook from old position RemovePiece(Rook, rookSquare, attackerColor); - // Setting rook on new position SetPiece(Rook, rookSquare + 3, attackerColor); SetPiece(attackerPiece, move.MoveTo(), attackerColor); - if (!fullRecalc) { - accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair); + { + accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook); } break; @@ -506,11 +503,12 @@ void Board::MakeMove(Move move) { break; } - if (fullRecalc) { - ResetAccPair(); + if (!accParentClean || accUpdate.type == ACC::UpdateType::None) { + accUpdate.setRefresh(); + } else { + accUpdate.refreshMask = refreshMask; } - // Removing the right to castle on king and rook movement UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor); sideToMove = !attackerColor; @@ -531,13 +529,6 @@ void Board::MakeMove(Move move) { checkers = CalcCheckers(); CalcCheckZones(); - /* - sideToMove = !sideToMove; - if (InCheck()) { - return false; - } - sideToMove = !sideToMove; - */ if (attackerColor == Black) fullMoves++; if (attackerPiece == Pawn || move.IsCapture()) { @@ -552,7 +543,6 @@ void Board::MakeMove(Move move) { bool Board::InPossibleZug() { Bitboard toCheck; - // For all pieces other than pawns and king for (int piece = Knight; piece <= Queen; piece++) { toCheck |= (pieces[piece] & colors[sideToMove]); } @@ -567,68 +557,141 @@ ACC::BucketPair Board::GetBuckets() { return {NNUE::kingBuckets[White][wKingSq],NNUE::kingBuckets[Black][bKingSq]}; } -void Board::ResetAccPair() { - Bitboard whitePieces = colors[White]; - Bitboard blackPieces = colors[Black]; +void Board::RefreshAccumulator(ACC::AccumulatorPair& out) const { + const int wKingSq = (pieces[King] & colors[White]).getLS1BIndex(); + const int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex(); + const ACC::BucketPair bucketPair = {NNUE::kingBuckets[White][wKingSq], NNUE::kingBuckets[Black][bKingSq]}; - accPair.white = NNUE::net.accumulator_biases; - accPair.black = NNUE::net.accumulator_biases; + out.white = NNUE::net.accumulator_biases; + out.black = NNUE::net.accumulator_biases; - const auto bucketPair = GetBuckets(); + for (int color = White; color <= Black; color++) { + Bitboard bb = colors[color]; - while (whitePieces) { - int square = whitePieces.getLS1BIndex(); + while (bb) { + int square = bb.getLS1BIndex(); - int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square, accPair.mirroredWhite); - int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square, accPair.mirroredBlack); + int wInput = ACC::CalculateIndex(White, color, mailbox[square], square, mirroredWhite); + int bInput = ACC::CalculateIndex(Black, color, mailbox[square], square, mirroredBlack); - for (int i = 0; i < NNUE::HL_SIZE; i++) { - accPair.white[i] += NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE + i]; - accPair.black[i] += NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE + i]; + ACC::AddRow(out.white, &NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE]); + ACC::AddRow(out.black, &NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE]); + + bb.PopBit(square); } + } +} - whitePieces.PopBit(square); +void Board::RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const { + const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack; + const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex(); + const int bucket = NNUE::kingBuckets[perspective][kingSq]; + + ACC::FinnyEntry& entry = finny.entries[perspective][mirrored][bucket]; + + const int16_t* adds[32]; + const int16_t* subs[32]; + int nAdds = 0; + int nSubs = 0; + + for (int color = White; color <= Black; color++) { + for (int pt = Pawn; pt <= King; pt++) { + Bitboard tmp = pieces[pt] & colors[color]; + const uint64_t now = tmp; + const uint64_t old = entry.bb[color][pt]; + + uint64_t added = now & ~old; + uint64_t removed = old & ~now; + + while (added) { + const int square = std::countr_zero(added); + added &= added - 1; + adds[nAdds++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored)); + } + + while (removed) { + const int square = std::countr_zero(removed); + removed &= removed - 1; + subs[nSubs++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored)); + } + + entry.bb[color][pt] = now; + } } - while (blackPieces) { - int square = blackPieces.getLS1BIndex(); + ACC::ApplyInPlace(entry.acc, adds, nAdds, subs, nSubs); + out = entry.acc; +} - int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square, accPair.mirroredWhite); - int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square, accPair.mirroredBlack); +void Board::ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const { + const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack; + const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex(); + const int bucket = NNUE::kingBuckets[perspective][kingSq]; - for (int i = 0; i < NNUE::HL_SIZE; i++) { - accPair.white[i] += NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE + i]; - accPair.black[i] += NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE + i]; - } + const bool stm = accUpdate.stm; - blackPieces.PopBit(square); + const int16_t* a1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT1, accUpdate.add1, mirrored)); + const int16_t* a2 = nullptr; + const int16_t* s1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.subPT1, accUpdate.sub1, mirrored)); + const int16_t* s2 = nullptr; + + if (accUpdate.nAdd == 2) + a2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT2, accUpdate.add2, mirrored)); + + if (accUpdate.nSub == 2) + s2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, accUpdate.sub2Opp ? !stm : stm, accUpdate.subPT2, accUpdate.sub2, mirrored)); + + ACC::Apply(dst, src, a1, a2, s1, s2); +} + +void Board::UpdateAccumulator(ACC::AccStack& stack, int ply) { + using ACC::UpdateType; + + if (accUpdate.type == UpdateType::None) return; + + if (accUpdate.type == UpdateType::Copy && ply > 0) { + stack.cur[ply] = stack.cur[ply - 1]; + accUpdate.type = UpdateType::None; + return; } + + ACC::AccumulatorPair& dst = stack.slots[ply]; + + if (ply == 0 || accUpdate.type != UpdateType::Delta) { + RefreshPerspective(stack.finny, White, dst.white); + RefreshPerspective(stack.finny, Black, dst.black); + } else { + const ACC::AccumulatorPair& prev = *stack.cur[ply - 1]; + + for (int perspective = White; perspective <= Black; perspective++) { + if (accUpdate.refreshMask & (1 << perspective)) + RefreshPerspective(stack.finny, perspective, dst.get(perspective)); + else + ApplyDeltaPerspective(perspective, dst.get(perspective), prev.get(perspective)); + } + } + + stack.cur[ply] = &dst; + accUpdate.type = UpdateType::None; } Bitboard Board::AttacksTo(int square, Bitboard occupancy) { Bitboard attacks; - // Pawn attacks - // Opponent attacks attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]); - // Own piece attacks attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]); - // Knight attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]); - // King attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]); Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy); Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy); - // Rook or queen attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen])); - // Bishop or queen attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen])); return attacks; @@ -643,7 +706,6 @@ static Bitboard rayBetween(int sq1, int sq2) { int df = (f2 > f1) - (f2 < f1); int dr = (r2 > r1) - (r2 < r1); - // must be same rank, file, or diagonal if (df != 0 && dr != 0 && std::abs(f2 - f1) != std::abs(r2 - r1)) return 0ULL; @@ -663,7 +725,6 @@ static Bitboard rayBetween(int sq1, int sq2) { return ray; } -// Returns the full ray from `from` in the direction of `to`, to the edge of the board static Bitboard fullRay(int from, int to) { int df = (to % 8) - (from % 8); int dr = (to / 8) - (from / 8); @@ -785,7 +846,6 @@ bool Board::IsPseudoLegal(Move &move) { const int to = move.MoveTo(); const int flag = move.GetFlags(); - // basic bounds if ((unsigned)from >= 64u || (unsigned)to >= 64u) return false; const int us = sideToMove; @@ -799,18 +859,14 @@ bool Board::IsPseudoLegal(Move &move) { const bool isCapture = move.IsCapture(); const int targetPiece = GetPieceType(to); - // capture consistency (except EP which captures "behind") if (flag == capture) { if (targetPiece == nullPieceType) return false; if (!colors[them].IsSet(to)) return false; } else if (isCapture && flag != epCapture) { - // promo-capture also lands on occupied enemy square if (targetPiece == nullPieceType) return false; if (!colors[them].IsSet(to)) return false; } else if (!isCapture) { - // quiet moves must not land on occupied square if (occupied.IsSet(to)) { - // except castling (king lands on empty anyway) if (flag != kingCastle && flag != queenCastle) return false; } } @@ -827,12 +883,10 @@ bool Board::IsPseudoLegal(Move &move) { }; auto isPawnCaptureTo = [&] { - // diagonal one step forward return (to == from + dir - 1 && toFile == fromFile - 1) || (to == from + dir + 1 && toFile == fromFile + 1); }; - // handle specials by flag first switch (flag) { case quiet: case capture: @@ -840,10 +894,9 @@ bool Board::IsPseudoLegal(Move &move) { case doublePawnPush: { if (movingPiece != Pawn) return false; - // from must be on starting rank - if (!us) { // white + if (!us) { if (fromRank != 1) return false; - } else { // black + } else { if (fromRank != 6) return false; } const int mid = from + dir; @@ -858,7 +911,6 @@ bool Board::IsPseudoLegal(Move &move) { if (to != enPassantTarget) return false; if (!isPawnCaptureTo()) return false; - // target square is empty, captured pawn is behind to const int capSq = to - dir; if (!colors[them].IsSet(capSq)) return false; if (GetPieceType(capSq) != Pawn) return false; @@ -883,7 +935,6 @@ bool Board::IsPseudoLegal(Move &move) { const int targetSq = us ? g8 : g1; if (to != targetSq) return false; - // must be exactly king+rook on that side and no attacked transit squares if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false; if (mask & colorThreats[them]) return false; return true; @@ -901,11 +952,9 @@ bool Board::IsPseudoLegal(Move &move) { } default: - // promotions (quiet + capture) if (!move.IsPromo()) return false; if (movingPiece != Pawn) return false; - // must land on last rank if (!us) { if (toRank != 7) return false; } else { @@ -921,16 +970,13 @@ bool Board::IsPseudoLegal(Move &move) { return true; } - // normal piece movement checks for quiet/capture (non-special) switch (movingPiece) { case Pawn: { - // non-promo pawns cannot land on last rank if (!us) { if (toRank == 7) return false; } else { if (toRank == 0) return false; } if (move.IsCapture()) { if (!isPawnCaptureTo()) return false; - // (regular capture already checked occupancy/enemy above) return true; } else { return isOneStepPawnPush(); diff --git a/source/board.h b/source/board.h index 534964d..d5770e5 100644 --- a/source/board.h +++ b/source/board.h @@ -26,7 +26,9 @@ public: std::array pinned; Bitboard checkers; - ACC::AccumulatorPair accPair; + ACC::Update accUpdate; + bool mirroredWhite = false; + bool mirroredBlack = false; std::array pieceThreats; std::array colorThreats; @@ -63,7 +65,11 @@ public: void ListMoves(); ACC::BucketPair GetBuckets(); - void ResetAccPair(); + void RefreshAccumulator(ACC::AccumulatorPair& out) const; + void UpdateAccumulator(ACC::AccStack& stack, int ply); + void RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const; + void ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const; + void MarkAccumulatorDirty() { accUpdate.setRefresh(); } int GetPieceType(int square); int GetPieceColor(int square); diff --git a/source/nnue.cpp b/source/nnue.cpp index 474da29..193577d 100644 --- a/source/nnue.cpp +++ b/source/nnue.cpp @@ -15,26 +15,22 @@ void Network::Load(const std::string& path) { std::cerr << "Failed to open file " + path << std::endl; } - // HL weights for (size_t i = 0; i < accumulator_weights.size(); i++) { for (size_t j = 0; j < accumulator_weights[i].size(); j++) { file.read(reinterpret_cast(&accumulator_weights[i][j]), sizeof(int16_t)); } } - // HL biases for (size_t i = 0; i < accumulator_biases.size(); i++) { file.read(reinterpret_cast(&accumulator_biases[i]), sizeof(int16_t)); } - // Output weights for (size_t i = 0; i < output_weights.size(); i++) { for (size_t j = 0; j < output_weights[i].size(); j++) { file.read(reinterpret_cast(&output_weights[i][j]), sizeof(int16_t)); } } - // Output biases for (size_t i = 0; i < output_bias.size(); i++) { file.read(reinterpret_cast(&output_bias[i]), sizeof(int16_t)); } @@ -135,12 +131,12 @@ using nativeVector = void*; #endif -static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t outputBucket) { +static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair& acc, const Network& net, size_t outputBucket) { const size_t VECTOR_SIZE = sizeof(nativeVector) / sizeof(int16_t); static_assert(HL_SIZE % VECTOR_SIZE == 0, "HL size must be divisible by the native register size of your CPU for vectorization to work"); - const ACC::Accumulator& stmAcc = board.sideToMove == White ? board.accPair.white : board.accPair.black; - const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? board.accPair.white : board.accPair.black; + const ACC::Accumulator& stmAcc = board.sideToMove == White ? acc.white : acc.black; + const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? acc.white : acc.black; const nativeVector VEC_QA = set1_epi16(QA); const nativeVector VEC_ZERO = set1_epi16(0); @@ -148,19 +144,15 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o nativeVector accumulator{}; for (int i = 0; i < HL_SIZE; i += VECTOR_SIZE) { - // Load accumulators const nativeVector stmAccumValues = load_epi16(reinterpret_cast(&stmAcc[i])); const nativeVector nstmAccumValues = load_epi16(reinterpret_cast(&nstmAcc[i])); - // Clamp values const nativeVector stmClamped = min_epi16(VEC_QA, max_epi16(stmAccumValues, VEC_ZERO)); const nativeVector nstmClamped = min_epi16(VEC_QA, max_epi16(nstmAccumValues, VEC_ZERO)); - // Load weights const nativeVector stmWeights = load_epi16(reinterpret_cast(&net.output_weights[outputBucket][i])); const nativeVector nstmWeights = load_epi16(reinterpret_cast(&net.output_weights[outputBucket][i + HL_SIZE])); - // SCReLU activation const nativeVector stmActivated = madd_epi16(stmClamped, mullo_epi16(stmClamped, stmWeights)); const nativeVector nstmActivated = madd_epi16(nstmClamped, mullo_epi16(nstmClamped, nstmWeights)); @@ -171,13 +163,13 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o return reduce_epi32(accumulator); } -int Forward(const Board& board, const Network& net) { +static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Network& net) { const size_t divisor = 32 / OUTPUT_BUCKETS; const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor; int64_t eval = 0; - eval = VectorizedSCReLU(board, net, outputBucket); + eval = VectorizedSCReLU(board, acc, net, outputBucket); eval /= QA; @@ -187,16 +179,21 @@ int Forward(const Board& board, const Network& net) { return (eval * SCALE) / (QA * QB); } -int16_t Network::Evaluate(const Board& board, bool datagen) { - // Disabled in datagen +int16_t Network::Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen) { const int materialScale = datagen ? 4096 : 2048 + 90 * board.pieces[Knight].PopCount() + 90 * board.pieces[Bishop].PopCount() + 180 * board.pieces[Rook].PopCount() + 360 * board.pieces[Queen].PopCount(); - return std::clamp(Forward(board, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH), + return std::clamp(Forward(board, acc, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH), (SEARCH::MATE_SCORE - SEARCH::MAX_DEPTH)); } +int16_t Network::Evaluate(const Board& board, bool datagen) { + ACC::AccumulatorPair acc; + board.RefreshAccumulator(acc); + return Evaluate(board, acc, datagen); +} + } diff --git a/source/nnue.h b/source/nnue.h index 9ba72cf..69a2279 100644 --- a/source/nnue.h +++ b/source/nnue.h @@ -5,6 +5,10 @@ class Board; +namespace ACC { +struct AccumulatorPair; +} + #ifdef __AVX512F__ constexpr size_t ALIGNMENT = 64; #else @@ -54,6 +58,8 @@ struct Network { void Load(const std::string& path); + int16_t Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen = false); + int16_t Evaluate(const Board& board, bool datagen = false); }; diff --git a/source/search.cpp b/source/search.cpp index ebd61cb..02d709a 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -89,12 +89,10 @@ static int AdjustEval(Board &board, SearchContext* ctx, int eval) { static bool IsTwoFold(Board &board, SearchContext* ctx) { for (int i = 0; i < board.positionIndex; i++) { if (ctx->positionHistory[i] == board.hashKey) { - // repetition found return true; } } - // no repetition return false; } @@ -115,7 +113,6 @@ 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; - // Late Move Reduction reduction = lmrTable[move.IsQuiet()][depth][moveSeen] * 1024; if (cutnode) @@ -136,7 +133,6 @@ static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int if (ttpvFailLow) reduction += lmrTTPVFailLow; - // History LMR int historyReduction = 0; if (move.IsQuiet()) { @@ -177,7 +173,6 @@ bool SEE(Board& board, Move& move, int threshold) { int nextVictim = board.GetPieceType(from); - // Next victim is moved piece or promo piece if (move.IsPromo()) { nextVictim = move.GetPromoPiece(); } @@ -270,17 +265,35 @@ 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 NNUE::net.Evaluate(board, mode == datagen); + return StaticEval(board, ctx, ply); if (ply > ctx->seldepth) ctx->seldepth = ply; - int bestScore = AdjustEval(board, ctx, NNUE::net.Evaluate(board, mode == datagen)); + int bestScore = AdjustEval(board, ctx, StaticEval(board, ctx, ply)); ctx->ss[ply].eval = bestScore; TTEntry entry; @@ -343,7 +356,6 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear Move currMove; while ((currMove = mp.Next())) { if (!IsLoss(bestScore)) { - // QS FP if (!inCheck && currMove.IsCapture() && fpScore <= alpha && !SEE(board, currMove, 1)) { @@ -399,7 +411,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC if (ShouldStop(ctx)) return 0; if (ply + 1 >= MAX_DEPTH) - return NNUE::net.Evaluate(board, mode == datagen); + return StaticEval(board, ctx, ply); if (ply > ctx->seldepth) ctx->seldepth = ply; @@ -428,7 +440,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC if (depth <= 0) return Quiescence(board, alpha, beta, ply, ctx); - int rawEval = NNUE::net.Evaluate(board, mode == datagen); + int rawEval = StaticEval(board, ctx, ply); const int staticEval = AdjustEval(board, ctx, rawEval); ctx->ss[ply].eval = staticEval; @@ -460,7 +472,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC if (!inCheck && !ctx->excluded) { if (ply) { - // Reverse Futility Pruning int margin = rfpBase + rfpMargin * (depth - improving); if (!ttpv && ttAdjustedEval - margin >= beta && depth < 7) { return !IsDecisive(ttAdjustedEval) && !IsDecisive(beta) @@ -468,12 +479,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC : ttAdjustedEval; } - // Razoring if (!isPV && depth <= 3 && staticEval + razoringScalar * depth < alpha && entry.nodeType != CutNode) { return Quiescence(board, alpha, beta, ply, ctx).score; } - // Null Move Pruning if (ply > ctx->minNmpPly && ttAdjustedEval >= beta + nmpBetaMargin) { if (depth > 1 && !board.InPossibleZug()) { Board copy = board; @@ -506,7 +515,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC } } - // Probcut const int probcutBeta = beta + probcutBetaMargin; const int probcutDepth = std::max(depth - 3, 1); @@ -570,7 +578,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC ctx->killerMoves[ply + 1] = Move(); - // Move-loop Move currMove; while ((currMove = mp.Next())) { @@ -580,9 +587,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC bool notMated = results.score > (-MATE_SCORE + MAX_DEPTH); int lmrDepth = depth - lmrTable[currMove.IsQuiet()][depth][moveSeen]; - // Late move pruning - // If we are near a leaf node we prune moves - // that are late in the list if (currMove.IsQuiet() && notMated) { int lmpThreshold = 7 + depth * depth * (1 + improving); @@ -600,9 +604,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC if (ply > 0) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 1); if (ply > 1) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 2); - // Futility pruning - // If our static eval is far below alpha, there is only a small chance - // that a quiet move will help us so we skip them int margin = fpMargin * (lmrDepth + improving) + historyScore / 32; if (!isPV && ply && currMove.IsQuiet() @@ -610,7 +611,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC continue; } - // PVS SEE int SEEThreshold = currMove.IsQuiet() ? seeQuietThreshold * depth : seeNoisyThreshold * depth * depth; if (ply && depth <= 10 && notMated && !SEE(board, currMove, SEEThreshold)) @@ -640,22 +640,18 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC const int singularScore = PVS(board, sDepth, sBeta-1, sBeta, ply, ctx, cutnode).score; ctx->excluded = Move(); - // Singular extension if (singularScore < sBeta) { extension++; if constexpr (!isPV) { - // Double extension if (singularScore <= sBeta - 1 - doubleExtMargin) { extension++; } } } - // Multicut else if (sBeta >= beta) { return sBeta; } - // Negative extension else if (entry.score >= beta) { extension--; } else if (cutnode) { @@ -707,7 +703,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC moveSeen++; - // Root if (!ply) { ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch; } @@ -731,7 +726,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC ctx->pvLine.SetMove(ply, currMove); } - // Fail high (beta cutoff) if (score >= beta) { const int bonusDepth = depth + (!inCheck && staticEval <= alpha); int historyBonus = historyBonusMultiplier * bonusDepth - historyBonusSub; @@ -771,7 +765,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC if (ply > 0) UpdateContHistNPly(1); if (ply > 1) UpdateContHistNPly(2); - // Malus for (int i = 0; i < seenQuietsCount - 1; i++) { sourceThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveFrom()); targetThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveTo()); @@ -781,12 +774,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC UpdateCaptHist(currMove, captHistoryBonus); } - // Capthist malus for (int i = 0; i < seenCapturesCount - currMove.IsCapture(); i++) { UpdateCaptHist(seenCaptures[i], -captHistoryMalus); } - // Corrhist update on fail high if (!ctx->excluded && !inCheck && currMove.IsQuiet() && score > staticEval) { int corrHistBonus = std::clamp(score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT); ctx->corrhist.UpdateAll(board, depth, corrHistBonus); @@ -851,7 +842,6 @@ static double ScaleTime(SearchContext *ctx, Move &move) { return nodeScalingFactor; } -// Iterative deepening template static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) { int fullTime = board.sideToMove ? params.btime : params.wtime; @@ -938,6 +928,9 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c ctx->TT->IncreaseAge(); } + board.MarkAccumulatorDirty(); + ctx->accStack.finny.Reset(); + ctx->seldepth = 0; ctx->nodesTable = {}; if constexpr (mode != bench) { diff --git a/source/search.h b/source/search.h index e636ff6..37ec93a 100644 --- a/source/search.h +++ b/source/search.h @@ -34,7 +34,6 @@ constexpr int CORRHIST_MAX = 16384; constexpr int32_t ScoreNone = -255000; constexpr int inf = 100000; -// first index: [0] noisy, [1] quiet inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES]; #ifdef TUNING @@ -58,7 +57,6 @@ class SearchContext; class CaptHistory { private: - // indexed by [stm][moving pt][capture pt][to] MultiArray historyMoves; public: void Update(bool stm, int moving, int capture, int to, int bonus) { @@ -78,7 +76,6 @@ public: class CorrHist { private: - // indexed by [stm][key] MultiArray pawnHist; MultiArray nonPawnHist; MultiArray majorHist; @@ -112,7 +109,6 @@ public: class ContHistory { private: - // indexed by [other color][prev move piece][stm][prev move to][piece][to] MultiArray contHistMoves; public: void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) { @@ -135,7 +131,6 @@ public: class History { private: - // indexed by [stm][from][to][threatenedSource][threatenedTarget] MultiArray historyMoves; public: void Update(bool stm, Move move, bool source, bool target, int bonus) { @@ -247,6 +242,8 @@ public: std::array ss{}; + ACC::AccStack accStack{MAX_DEPTH + 2}; + Stopwatch sw; SearchContext(){