Author SHA1 Message Date
rektdie 3b2cb8839b minor corrhist | bench 1406680 2026-09-28 21:19:42 +02:00
8 changed files with 236 additions and 443 deletions

No files matched your search

+51 -151
View File
@@ -7,180 +7,80 @@ namespace ACC {
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored) {
if (perspective == Black)
{
side = 1 - side;
square = square ^ 0b111000;
side = 1 - side; // Flip side
square = square ^ 0b111000; // Mirror square
}
if (mirrored)
square ^= 7;
return side * 64 * 6 + pieceType * 64 + square;
}
const int16_t* Row(int bucket, int index) {
return &NNUE::net.accumulator_weights[bucket][static_cast<size_t>(index) * NNUE::HL_SIZE];
}
// 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);
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;
}
}
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];
}
}
#if defined(_MSC_VER) && !defined(__clang__)
#define ACC_NOINLINE __declspec(noinline)
#else
#define ACC_NOINLINE __attribute__((noinline))
#endif
// 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(__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 subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack);
#ifdef ACC_SIMD
int subW2 = CalculateIndex(White, !stm, subPT2, sub2, mirroredWhite);
int subB2 = CalculateIndex(Black, !stm, subPT2, sub2, mirroredBlack);
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");
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];
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]);
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];
}
}
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];
// 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);
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(acc + i + u * LANES);
int addW2 = CalculateIndex(White, stm, addPT2, add2, mirroredWhite);
int addB2 = CalculateIndex(Black, stm, addPT2, add2, 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 subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1, 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));
int subW2 = CalculateIndex(White, stm, subPT2, sub2, mirroredWhite);
int subB2 = CalculateIndex(Black, stm, subPT2, sub2, mirroredBlack);
for (size_t u = 0; u < TILE; u++) vStore(acc + i + u * LANES, r[u]);
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];
}
}
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
}
+9 -79
View File
@@ -1,7 +1,4 @@
#pragma once
#include <array>
#include <vector>
#include <cstdint>
#include "nnue.h"
namespace ACC {
@@ -14,85 +11,18 @@ struct BucketPair {
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
struct AccumulatorPair {
alignas(ALIGNMENT) Accumulator white;
alignas(ALIGNMENT) Accumulator black;
alignas(32) Accumulator white;
alignas(32) Accumulator black;
bool mirroredWhite = false;
bool mirroredBlack = false;
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; }
// 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);
};
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);
}
+99 -139
View File
@@ -1,4 +1,3 @@
#include <bit>
#include "board.h"
#include "accumulator.h"
#include "movegen.h"
@@ -31,9 +30,7 @@ void Board::Reset() {
pieces = std::array<Bitboard, 6>();
colors = std::array<Bitboard, 2>();
accUpdate.setRefresh();
mirroredWhite = false;
mirroredBlack = false;
accPair = ACC::AccumulatorPair();
pieceThreats = std::array<Bitboard, 6>();
colorThreats = std::array<Bitboard, 2>();
@@ -48,6 +45,7 @@ void Board::Reset() {
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
minorKey = 0ULL;
checkZones = std::array<Bitboard, 4>();
}
@@ -55,6 +53,7 @@ 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, ' ');
@@ -90,6 +89,7 @@ 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,6 +98,7 @@ void Board::SetByFen(std::string_view fen) {
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
minorKey = 0ULL;
occupied = colors[White] | colors[Black];
hashKey = UTILS::GetHashKey(*this);
@@ -111,13 +112,13 @@ void Board::SetByFen(std::string_view fen) {
int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8;
if (whiteKingFile > 3) {
mirroredWhite = true;
accPair.mirroredWhite = true;
}
if (blackKingFile > 3) {
mirroredBlack = true;
accPair.mirroredBlack = true;
}
accUpdate.setRefresh();
ResetAccPair();
}
std::string Board::GetFen() {
@@ -311,6 +312,8 @@ 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];
}
}
}
@@ -331,12 +334,16 @@ 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;
@@ -349,6 +356,7 @@ 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;
@@ -369,13 +377,8 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) {
}
void Board::MakeMove(Move move) {
const bool accParentClean = accUpdate.type == ACC::UpdateType::None;
accUpdate = ACC::Update();
// Null Move
if (!move) {
if (accParentClean) accUpdate.type = ACC::UpdateType::Copy;
else accUpdate.setRefresh();
int newEpTarget = noEPTarget;
sideToMove = !sideToMove;
@@ -400,28 +403,30 @@ void Board::MakeMove(Move move) {
int endPiece = attackerPiece;
uint8_t refreshMask = 0;
bool fullRecalc = false;
const auto bucketPair = GetBuckets();
if (attackerPiece == King) {
const int toFile = move.MoveTo() % 8;
if (attackerColor == White) {
if ((toFile > 3) != mirroredWhite) {
mirroredWhite = !mirroredWhite;
refreshMask |= 1 << White;
if ((toFile > 3) != accPair.mirroredWhite) {
accPair.mirroredWhite = !accPair.mirroredWhite;
fullRecalc = true;
}
} else {
if ((toFile > 3) != mirroredBlack) {
mirroredBlack = !mirroredBlack;
refreshMask |= 1 << Black;
if ((toFile > 3) != accPair.mirroredBlack) {
accPair.mirroredBlack = !accPair.mirroredBlack;
fullRecalc = true;
}
}
if (NNUE::kingBuckets[attackerColor][move.MoveFrom()] != NNUE::kingBuckets[attackerColor][move.MoveTo()]) {
refreshMask |= 1 << attackerColor;
fullRecalc = true;
}
}
// Removing attacker piece from old position
RemovePiece(attackerPiece, move.MoveFrom(), attackerColor);
if (move.IsPromo()) {
@@ -433,16 +438,16 @@ void Board::MakeMove(Move move) {
}
}
{
if (!fullRecalc) {
if (move.IsCapture()) {
if (move.GetFlags() != epCapture) {
accUpdate.setAddSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece);
accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece, bucketPair);
} else {
accUpdate.setAddSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn);
accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn, bucketPair);
}
} else {
if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) {
accUpdate.setAddSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece);
accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, bucketPair);
}
}
}
@@ -471,14 +476,16 @@ 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);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook);
if (!fullRecalc) {
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair);
}
break;
@@ -487,14 +494,16 @@ 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);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook);
if (!fullRecalc) {
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair);
}
break;
@@ -503,12 +512,11 @@ void Board::MakeMove(Move move) {
break;
}
if (!accParentClean || accUpdate.type == ACC::UpdateType::None) {
accUpdate.setRefresh();
} else {
accUpdate.refreshMask = refreshMask;
if (fullRecalc) {
ResetAccPair();
}
// Removing the right to castle on king and rook movement
UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor);
sideToMove = !attackerColor;
@@ -529,6 +537,13 @@ 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()) {
@@ -543,6 +558,7 @@ 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]);
}
@@ -557,141 +573,68 @@ ACC::BucketPair Board::GetBuckets() {
return {NNUE::kingBuckets[White][wKingSq],NNUE::kingBuckets[Black][bKingSq]};
}
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]};
void Board::ResetAccPair() {
Bitboard whitePieces = colors[White];
Bitboard blackPieces = colors[Black];
out.white = NNUE::net.accumulator_biases;
out.black = NNUE::net.accumulator_biases;
accPair.white = NNUE::net.accumulator_biases;
accPair.black = NNUE::net.accumulator_biases;
for (int color = White; color <= Black; color++) {
Bitboard bb = colors[color];
const auto bucketPair = GetBuckets();
while (bb) {
int square = bb.getLS1BIndex();
while (whitePieces) {
int square = whitePieces.getLS1BIndex();
int wInput = ACC::CalculateIndex(White, color, mailbox[square], square, mirroredWhite);
int bInput = ACC::CalculateIndex(Black, color, mailbox[square], square, mirroredBlack);
int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square, accPair.mirroredWhite);
int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square, accPair.mirroredBlack);
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);
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];
}
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];
while (blackPieces) {
int square = blackPieces.getLS1BIndex();
ACC::FinnyEntry& entry = finny.entries[perspective][mirrored][bucket];
int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square, accPair.mirroredWhite);
int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square, accPair.mirroredBlack);
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;
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];
}
blackPieces.PopBit(square);
}
ACC::ApplyInPlace(entry.acc, adds, nAdds, subs, nSubs);
out = entry.acc;
}
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];
const bool stm = accUpdate.stm;
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;
@@ -706,6 +649,7 @@ 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;
@@ -725,6 +669,7 @@ 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);
@@ -846,6 +791,7 @@ 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;
@@ -859,14 +805,18 @@ 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;
}
}
@@ -883,10 +833,12 @@ 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:
@@ -894,9 +846,10 @@ bool Board::IsPseudoLegal(Move &move) {
case doublePawnPush: {
if (movingPiece != Pawn) return false;
if (!us) {
// from must be on starting rank
if (!us) { // white
if (fromRank != 1) return false;
} else {
} else { // black
if (fromRank != 6) return false;
}
const int mid = from + dir;
@@ -911,6 +864,7 @@ 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;
@@ -935,6 +889,7 @@ 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;
@@ -952,9 +907,11 @@ 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 {
@@ -970,13 +927,16 @@ 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();
+4 -9
View File
@@ -26,9 +26,7 @@ public:
std::array<Bitboard, 2> pinned;
Bitboard checkers;
ACC::Update accUpdate;
bool mirroredWhite = false;
bool mirroredBlack = false;
ACC::AccumulatorPair accPair;
std::array<Bitboard, 6> pieceThreats;
std::array<Bitboard, 2> colorThreats;
@@ -50,6 +48,7 @@ public:
U64 pawnKey = 0ULL;
U64 nonPawnKey = 0ULL;
U64 majorKey = 0ULL;
U64 minorKey = 0ULL;
std::array<Bitboard, 4> checkZones;
@@ -65,11 +64,7 @@ public:
void ListMoves();
ACC::BucketPair GetBuckets();
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(); }
void ResetAccPair();
int GetPieceType(int square);
int GetPieceColor(int square);
@@ -96,4 +91,4 @@ public:
bool IsLegal(Move &move);
bool IsPseudoLegal(Move &move);
};
};
+16 -13
View File
@@ -15,22 +15,26 @@ 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));
}
@@ -131,12 +135,12 @@ using nativeVector = void*;
#endif
static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair& acc, const Network& net, size_t outputBucket) {
static int32_t VectorizedSCReLU(const Board& board, 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 ? acc.white : acc.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? acc.white : acc.black;
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 nativeVector VEC_QA = set1_epi16(QA);
const nativeVector VEC_ZERO = set1_epi16(0);
@@ -144,15 +148,19 @@ static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair&
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));
@@ -163,13 +171,13 @@ static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair&
return reduce_epi32(accumulator);
}
static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Network& net) {
int Forward(const Board& board, 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, acc, net, outputBucket);
eval = VectorizedSCReLU(board, net, outputBucket);
eval /= QA;
@@ -179,21 +187,16 @@ static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Ne
return (eval * SCALE) / (QA * QB);
}
int16_t Network::Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen) {
int16_t Network::Evaluate(const Board& board, bool datagen) {
// Disabled in 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, acc, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
return std::clamp(Forward(board, *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,10 +5,6 @@
class Board;
namespace ACC {
struct AccumulatorPair;
}
#ifdef __AVX512F__
constexpr size_t ALIGNMENT = 64;
#else
@@ -58,8 +54,6 @@ 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);
};
+47 -43
View File
@@ -89,10 +89,12 @@ 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;
}
@@ -113,6 +115,7 @@ 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)
@@ -133,6 +136,7 @@ static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int
if (ttpvFailLow)
reduction += lmrTTPVFailLow;
// History LMR
int historyReduction = 0;
if (move.IsQuiet()) {
@@ -173,6 +177,7 @@ 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();
}
@@ -265,35 +270,17 @@ 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 StaticEval<mode>(board, ctx, ply);
return NNUE::net.Evaluate(board, mode == datagen);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
int bestScore = AdjustEval(board, ctx, StaticEval<mode>(board, ctx, ply));
int bestScore = AdjustEval(board, ctx, NNUE::net.Evaluate(board, mode == datagen));
ctx->ss[ply].eval = bestScore;
TTEntry entry;
@@ -309,11 +296,9 @@ 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;
}
}
@@ -323,15 +308,12 @@ 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;
}
}
@@ -356,6 +338,7 @@ 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)) {
@@ -386,7 +369,6 @@ 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;
}
@@ -411,7 +393,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 StaticEval<mode>(board, ctx, ply);
return NNUE::net.Evaluate(board, mode == datagen);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
@@ -440,7 +422,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 = StaticEval<mode>(board, ctx, ply);
int rawEval = NNUE::net.Evaluate(board, mode == datagen);
const int staticEval = AdjustEval(board, ctx, rawEval);
ctx->ss[ply].eval = staticEval;
@@ -472,6 +454,7 @@ 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)
@@ -479,10 +462,12 @@ 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;
@@ -515,8 +500,9 @@ 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 - improving, 1);
const int probcutDepth = std::max(depth - 3, 1);
if (depth >= 7 && std::abs(beta) < MATE_SCORE - MAX_DEPTH
&& (!entry.bestMove || !entry.bestMove.IsQuiet())
@@ -578,6 +564,7 @@ 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())) {
@@ -587,6 +574,9 @@ 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);
@@ -604,6 +594,9 @@ 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()
@@ -611,9 +604,10 @@ 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))
if (ply && depth <= 10 && !SEE(board, currMove, SEEThreshold))
continue;
@@ -621,6 +615,14 @@ 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);
@@ -640,18 +642,22 @@ 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) {
@@ -664,14 +670,6 @@ 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;
@@ -703,6 +701,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
moveSeen++;
// Root
if (!ply) {
ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch;
}
@@ -726,6 +725,7 @@ 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,6 +765,7 @@ 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());
@@ -774,10 +775,12 @@ 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);
@@ -790,8 +793,11 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
if (moveSeen == 0) {
if (ctx->excluded) return alpha;
return inCheck ? -MATE_SCORE + ply : 0;
if (inCheck) { // checkmate
return -MATE_SCORE + ply;
} else { // stalemate
return 0;
}
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
@@ -842,6 +848,7 @@ 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;
@@ -928,9 +935,6 @@ 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) {
+10 -3
View File
@@ -34,6 +34,7 @@ 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
@@ -57,6 +58,7 @@ 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) {
@@ -76,9 +78,11 @@ 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;
@@ -92,23 +96,27 @@ 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];
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]
+ minorHist[board.sideToMove][board.minorKey % 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) {
@@ -131,6 +139,7 @@ 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) {
@@ -242,8 +251,6 @@ public:
std::array<Stack, MAX_DEPTH> ss{};
ACC::AccStack accStack{MAX_DEPTH + 2};
Stopwatch sw;
SearchContext(){