Author SHA1 Message Date
rektdie 2aaa560dd3 probcut improving | bench 1592105 2026-10-03 17:30:33 +02:00
rektdie 134af1abde Merge pull request #193 from rektdie/lazy-acc-with-finny
lazy accumulator updates with finny tables bench 1632393
2026-10-03 16:38:26 +02:00
rektdie 1e41671002 lazy accumulator updates with finny tables 1632393 2026-10-03 16:13:52 +02:00
rektdie dd831d14bf Merge pull request #192 from rektdie/fix-qs-tt-write
check for stop before writing into qs tt (cutnode) | bench 1402552
2026-10-03 15:58:20 +02:00
rektdie ae3a39cf04 check for stop before writing into qs tt (cutnode) | bench 1402552 2026-10-03 15:57:50 +02:00
rektdie aa120b14f9 Merge pull request #191 from rektdie/pvs-see-notmated
pvs see not mated guard | bench 1632393
2026-10-03 09:27:30 +02:00
rektdie 4c67267c8c pvs see not mated guard | bench 1632393 2026-10-03 09:21:09 +02:00
rektdie 2c4292c485 Merge pull request #190 from rektdie/excluded-terminal-decision
when moveseen = 0, returning alpha in case of excluded move | bench 1293332
2026-10-03 09:19:53 +02:00
rektdie f77c4c1fbd when moveseen = 0, returning alpha in case of excluded move | bench 1293332 2026-10-01 22:47:27 +02:00
rektdie e64c6c60b9 Merge pull request #189 from rektdie/fix-se-ss-overwrite
moving ss storing under se to prevent overwriting | bench 1342782
2026-10-01 18:30:02 +02:00
rektdie de1d0e22ff moving ss storing under se to prevent overwriting | bench 1342782 2026-09-30 20:01:33 +02:00
rektdie d593833e9e Merge pull request #188 from rektdie/qs-switch-fix
fix switch statements in qsearch | bench 1402552
2026-09-30 19:58:05 +02:00
rektdie a2297ed04e fix switch statements in qsearch | bench 1402552 2026-09-30 18:40:22 +02:00
8 changed files with 442 additions and 235 deletions

No files matched your search

+151 -51
View File
@@ -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<size_t>(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 <immintrin.h>
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 <immintrin.h>
using Vec = __m256i;
static inline Vec vLoad(const int16_t* p) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(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 <immintrin.h>
using Vec = __m128i;
static inline Vec vLoad(const int16_t* p) { return _mm_loadu_si128(reinterpret_cast<const __m128i*>(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 <arm_neon.h>
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 <int NA, int NS>
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<int16_t>(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<int16_t>(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<int16_t>(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<int16_t>(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<int16_t>(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
}
+79 -9
View File
@@ -1,4 +1,7 @@
#pragma once
#include <array>
#include <vector>
#include <cstdint>
#include "nnue.h"
namespace ACC {
@@ -11,18 +14,85 @@ struct BucketPair {
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
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<AccumulatorPair> slots;
std::vector<const AccumulatorPair*> 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);
}
+138 -98
View File
@@ -1,3 +1,4 @@
#include <bit>
#include "board.h"
#include "accumulator.h"
#include "movegen.h"
@@ -30,7 +31,9 @@ void Board::Reset() {
pieces = std::array<Bitboard, 6>();
colors = std::array<Bitboard, 2>();
accPair = ACC::AccumulatorPair();
accUpdate.setRefresh();
mirroredWhite = false;
mirroredBlack = false;
pieceThreats = std::array<Bitboard, 6>();
colorThreats = std::array<Bitboard, 2>();
@@ -45,7 +48,6 @@ void Board::Reset() {
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
minorKey = 0ULL;
checkZones = std::array<Bitboard, 4>();
}
@@ -53,7 +55,6 @@ void Board::Reset() {
void Board::SetByFen(std::string_view fen) {
Reset();
// Starting from top left
int currSquare = a8;
std::vector<std::string> tokens = UTILS::split(fen, ' ');
@@ -89,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]);
@@ -98,7 +98,6 @@ void Board::SetByFen(std::string_view fen) {
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
minorKey = 0ULL;
occupied = colors[White] | colors[Black];
hashKey = UTILS::GetHashKey(*this);
@@ -112,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() {
@@ -312,8 +311,6 @@ void Board::SetPiece(int piece, int square, bool color) {
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
} else if (piece == Knight || piece == Bishop) {
minorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
@@ -334,16 +331,12 @@ void Board::RemovePiece(int piece, int square, bool color) {
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
} else if (piece == Knight || piece == Bishop) {
minorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
// 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;
@@ -356,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;
@@ -377,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;
@@ -403,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()) {
@@ -438,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);
}
}
}
@@ -476,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;
@@ -494,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;
@@ -512,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;
@@ -537,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()) {
@@ -558,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]);
}
@@ -573,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;
@@ -649,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;
@@ -669,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);
@@ -791,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;
@@ -805,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;
}
}
@@ -833,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:
@@ -846,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;
@@ -864,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;
@@ -889,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;
@@ -907,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 {
@@ -927,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();
+9 -4
View File
@@ -26,7 +26,9 @@ public:
std::array<Bitboard, 2> pinned;
Bitboard checkers;
ACC::AccumulatorPair accPair;
ACC::Update accUpdate;
bool mirroredWhite = false;
bool mirroredBlack = false;
std::array<Bitboard, 6> pieceThreats;
std::array<Bitboard, 2> colorThreats;
@@ -48,7 +50,6 @@ public:
U64 pawnKey = 0ULL;
U64 nonPawnKey = 0ULL;
U64 majorKey = 0ULL;
U64 minorKey = 0ULL;
std::array<Bitboard, 4> checkZones;
@@ -64,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);
@@ -91,4 +96,4 @@ public:
bool IsLegal(Move &move);
bool IsPseudoLegal(Move &move);
};
};
+13 -16
View File
@@ -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<char*>(&accumulator_weights[i][j]), sizeof(int16_t));
}
}
// HL biases
for (size_t i = 0; i < accumulator_biases.size(); i++) {
file.read(reinterpret_cast<char*>(&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<char*>(&output_weights[i][j]), sizeof(int16_t));
}
}
// Output biases
for (size_t i = 0; i < output_bias.size(); i++) {
file.read(reinterpret_cast<char*>(&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<const nativeVector*>(&stmAcc[i]));
const nativeVector nstmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&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<const nativeVector*>(&net.output_weights[outputBucket][i]));
const nativeVector nstmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&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);
}
}
+6
View File
@@ -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);
};
+43 -47
View File
@@ -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 <bool isPV>
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 <searchMode mode>
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 <bool isPV, searchMode mode>
static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext* ctx) {
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return NNUE::net.Evaluate(board, mode == datagen);
return StaticEval<mode>(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<mode>(board, ctx, ply));
ctx->ss[ply].eval = bestScore;
TTEntry entry;
@@ -296,9 +309,11 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
case CutNode:
if (entry.score >= beta)
return entry.score;
break;
case AllNode:
if (entry.score <= alpha)
return entry.score;
break;
}
}
@@ -308,12 +323,15 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
switch (entry.nodeType) {
case PV:
bestScore = entry.score;
break;
case CutNode:
if (entry.score > bestScore)
bestScore = entry.score;
break;
case AllNode:
if (entry.score < bestScore)
bestScore = entry.score;
break;
}
}
@@ -338,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)) {
@@ -369,6 +386,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
int score = -Quiescence<isPV, mode>(copy, -beta, -alpha, ply + 1, ctx).score;
if (score >= beta) {
if (searchStopped.load(std::memory_order_relaxed)) return 0;
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
return score;
}
@@ -393,7 +411,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return NNUE::net.Evaluate(board, mode == datagen);
return StaticEval<mode>(board, ctx, ply);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
@@ -422,7 +440,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (depth <= 0) return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx);
int rawEval = NNUE::net.Evaluate(board, mode == datagen);
int rawEval = StaticEval<mode>(board, ctx, ply);
const int staticEval = AdjustEval(board, ctx, rawEval);
ctx->ss[ply].eval = staticEval;
@@ -454,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)
@@ -462,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<isPV, mode>(board, alpha, beta, ply, ctx).score;
}
// Null Move Pruning
if (ply > ctx->minNmpPly && ttAdjustedEval >= beta + nmpBetaMargin) {
if (depth > 1 && !board.InPossibleZug()) {
Board copy = board;
@@ -500,9 +515,8 @@ 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);
const int probcutDepth = std::max(depth - 3 - improving, 1);
if (depth >= 7 && std::abs(beta) < MATE_SCORE - MAX_DEPTH
&& (!entry.bestMove || !entry.bestMove.IsQuiet())
@@ -564,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())) {
@@ -574,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);
@@ -594,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()
@@ -604,10 +611,9 @@ 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 && !SEE(board, currMove, SEEThreshold))
if (ply && depth <= 10 && notMated && !SEE(board, currMove, SEEThreshold))
continue;
@@ -615,14 +621,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
Board copy = board;
copy.MakeMove(currMove);
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
ctx->TT->PrefetchEntry(copy.hashKey);
@@ -642,22 +640,18 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
const int singularScore = PVS<false, mode>(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) {
@@ -670,6 +664,14 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
cutnode |= extension < 0;
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
int newDepth = depth + (copy.InCheck() && !ctx->excluded) - 1 + extension;
@@ -701,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;
}
@@ -725,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;
@@ -765,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());
@@ -775,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);
@@ -793,11 +790,8 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
if (moveSeen == 0) {
if (inCheck) { // checkmate
return -MATE_SCORE + ply;
} else { // stalemate
return 0;
}
if (ctx->excluded) return alpha;
return inCheck ? -MATE_SCORE + ply : 0;
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
@@ -848,7 +842,6 @@ static double ScaleTime(SearchContext *ctx, Move &move) {
return nodeScalingFactor;
}
// Iterative deepening
template <searchMode mode>
static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
int fullTime = board.sideToMove ? params.btime : params.wtime;
@@ -935,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) {
+3 -10
View File
@@ -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<int, 2, 6, 6, 64> historyMoves;
public:
void Update(bool stm, int moving, int capture, int to, int bonus) {
@@ -78,11 +76,9 @@ public:
class CorrHist {
private:
// indexed by [stm][key]
MultiArray<int, 2, CORRHIST_SIZE> pawnHist;
MultiArray<int, 2, CORRHIST_SIZE> nonPawnHist;
MultiArray<int, 2, CORRHIST_SIZE> majorHist;
MultiArray<int, 2, CORRHIST_SIZE> minorHist;
public:
void Update(Board& board, int depth, int diff, int* entry) {
const int scaledDiff = diff * CORRHIST_GRAIN;
@@ -96,27 +92,23 @@ public:
Update(board, depth, diff, &pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]);
Update(board, depth, diff, &minorHist[board.sideToMove][board.minorKey % CORRHIST_SIZE]);
}
int GetAllHist(Board& board) {
return pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]
+ nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]
+ minorHist[board.sideToMove][board.minorKey % CORRHIST_SIZE];
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE];
}
void Clear() {
std::fill(&pawnHist[0][0], &pawnHist[0][0] + sizeof(pawnHist) / sizeof(int), 0);
std::fill(&nonPawnHist[0][0], &nonPawnHist[0][0] + sizeof(nonPawnHist) / sizeof(int), 0);
std::fill(&majorHist[0][0], &majorHist[0][0] + sizeof(majorHist) / sizeof(int), 0);
std::fill(&minorHist[0][0], &minorHist[0][0] + sizeof(minorHist) / sizeof(int), 0);
}
};
class ContHistory {
private:
// indexed by [other color][prev move piece][stm][prev move to][piece][to]
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
public:
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
@@ -139,7 +131,6 @@ public:
class History {
private:
// indexed by [stm][from][to][threatenedSource][threatenedTarget]
MultiArray<int, 2, 64, 64, 2, 2> historyMoves;
public:
void Update(bool stm, Move move, bool source, bool target, int bonus) {
@@ -251,6 +242,8 @@ public:
std::array<Stack, MAX_DEPTH> ss{};
ACC::AccStack accStack{MAX_DEPTH + 2};
Stopwatch sw;
SearchContext(){