Compare commits
25
Commits
v4.0
...
fix-tt-mate-ply
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edfa6ead28 | ||
|
|
134af1abde | ||
|
|
1e41671002 | ||
|
|
dd831d14bf | ||
|
|
ae3a39cf04 | ||
|
|
aa120b14f9 | ||
|
|
4c67267c8c | ||
|
|
2c4292c485 | ||
|
|
f77c4c1fbd | ||
|
|
e64c6c60b9 | ||
|
|
de1d0e22ff | ||
|
|
d593833e9e | ||
|
|
a2297ed04e | ||
|
|
ecd57607f3 | ||
|
|
be9982eb75 | ||
|
|
babe3d0db0 | ||
|
|
30e54c2b71 | ||
|
|
1470ad34a8 | ||
|
|
f23a59730b | ||
|
|
dbd56e0c21 | ||
|
|
390ee23e75 | ||
|
|
4ebdeb54f6 | ||
|
|
4e437d52fc | ||
|
|
a3255581fb | ||
|
|
24a36414f8 |
No files matched your search
@@ -5,14 +5,16 @@ OBJ_DIR := obj
|
||||
EXE ?= Eleanor
|
||||
EVALFILE := ./nnue.bin
|
||||
|
||||
CXX := clang++
|
||||
|
||||
ifeq ($(OS),Windows_NT)
|
||||
UNAME_S := Windows
|
||||
ARCH := x86_64
|
||||
EXE_EXT := .exe
|
||||
MKDIR := mkdir
|
||||
RM := rmdir /s /q
|
||||
DEL := del /q
|
||||
PLATFORM := windows
|
||||
CXX := g++
|
||||
else
|
||||
UNAME_S := $(shell uname -s)
|
||||
ARCH := $(shell uname -m)
|
||||
@@ -20,7 +22,6 @@ else
|
||||
MKDIR := mkdir -p
|
||||
RM := rm -rf
|
||||
DEL := rm -f
|
||||
CXX := clang++
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
PLATFORM := mac
|
||||
else
|
||||
@@ -28,6 +29,8 @@ else
|
||||
endif
|
||||
endif
|
||||
|
||||
CXX_BASE := $(notdir $(firstword $(CXX)))
|
||||
CXX_DRIVER_FLAGS :=
|
||||
CXXFLAGS := -std=c++20 -O3 -flto -Wall
|
||||
LDFLAGS := -O3 -flto
|
||||
|
||||
@@ -39,6 +42,9 @@ ifeq ($(PLATFORM),mac)
|
||||
endif
|
||||
else ifeq ($(PLATFORM),windows)
|
||||
ARCH_FLAGS := -march=native
|
||||
CXX_DRIVER_FLAGS += --target=$(ARCH)-w64-windows-gnu
|
||||
CXXFLAGS += -pthread
|
||||
LDFLAGS += -pthread
|
||||
LDFLAGS += -static -Wl,--stack,8388608
|
||||
else
|
||||
ifeq ($(ARCH),aarch64)
|
||||
@@ -58,10 +64,10 @@ SRCS := $(wildcard $(SRC_DIR)/*.cpp)
|
||||
OBJS := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRCS))
|
||||
|
||||
$(EXE)$(EXE_EXT): $(OBJS)
|
||||
$(CXX) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
|
||||
$(CXX) $(CXX_DRIVER_FLAGS) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
|
||||
|
||||
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
|
||||
$(CXX) $(CXXFLAGS) -c -o $@ $<
|
||||
$(CXX) $(CXX_DRIVER_FLAGS) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
$(OBJ_DIR):
|
||||
$(MKDIR) $(OBJ_DIR)
|
||||
|
||||
@@ -12,12 +12,12 @@
|
||||

|
||||
|
||||
|
||||
| Version | Release Date | [CCRL 40/15](https://www.computerchess.org.uk/ccrl/4040/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CCRL Blitz](https://www.computerchess.org.uk/ccrl/404/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) |
|
||||
| --- | --- | --- | --- |
|
||||
| 4.0 | 2026-04-18 | - | -
|
||||
| 3.0 | 2025-12-05 | 3405 (#84) | 3495 (#79-80)
|
||||
| 2.0 | 2025-08-23 | 3312 (#115) | 3392 (#105)
|
||||
| 1.0 | 2025-06-02 | 2856 (#244) | 2759 (#256)
|
||||
| Version | Release Date | [CCRL 40/15](https://www.computerchess.org.uk/ccrl/4040/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CCRL Blitz](https://www.computerchess.org.uk/ccrl/404/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CEGT 40/20](http://www.cegt.net/40_40%20Rating%20List/40_40%20SingleVersion/rangliste.html)
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 4.1 | 2026-04-22 | 3528 (#60-61) | 3590 (#64) | 3443 (#59)
|
||||
| 3.0 | 2025-12-05 | 3405 (#84) | 3495 (#79-80) | -
|
||||
| 2.0 | 2025-08-23 | 3312 (#115) | 3392 (#105) | -
|
||||
| 1.0 | 2025-06-02 | 2856 (#244) | 2759 (#256) | -
|
||||
|
||||
</div>
|
||||
|
||||
@@ -32,7 +32,8 @@ A 1536-hidden-layer *perspective net* with 8 input buckets, 8 output buckets and
|
||||
## Installation
|
||||
|
||||
> **Prerequisites:**
|
||||
> - `clang++` on linux, `g++` on windows
|
||||
> - `clang++` compiler
|
||||
> - On Windows, `clang++` must have access to a MinGW GNU toolchain/runtime because the build targets `x86_64-w64-windows-gnu`
|
||||
> - Access to `make` command
|
||||
|
||||
1. Clone the repository
|
||||
|
||||
+151
-51
@@ -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
@@ -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
-92
@@ -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>();
|
||||
@@ -52,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, ' ');
|
||||
@@ -88,7 +90,6 @@ void Board::SetByFen(std::string_view fen) {
|
||||
|
||||
if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]);
|
||||
|
||||
// full and half move
|
||||
if (tokens.size() > 4) {
|
||||
halfMoves = std::stoi(tokens[4]);
|
||||
fullMoves = std::stoi(tokens[5]);
|
||||
@@ -110,13 +111,13 @@ void Board::SetByFen(std::string_view fen) {
|
||||
int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8;
|
||||
|
||||
if (whiteKingFile > 3) {
|
||||
accPair.mirroredWhite = true;
|
||||
mirroredWhite = true;
|
||||
}
|
||||
if (blackKingFile > 3) {
|
||||
accPair.mirroredBlack = true;
|
||||
mirroredBlack = true;
|
||||
}
|
||||
|
||||
ResetAccPair();
|
||||
accUpdate.setRefresh();
|
||||
}
|
||||
|
||||
std::string Board::GetFen() {
|
||||
@@ -334,10 +335,8 @@ void Board::RemovePiece(int piece, int square, bool color) {
|
||||
}
|
||||
}
|
||||
|
||||
// Updates castling rights
|
||||
static void UpdateCastlingRights(Board &board, int square, int type, int color) {
|
||||
if (type == Rook) {
|
||||
// Removing old rights
|
||||
board.hashKey ^= UTILS::zCastle[board.castlingRights];
|
||||
int queenSideRook = color ? a8 : a1;
|
||||
int kingSideRook = color ? h8 : h1;
|
||||
@@ -350,7 +349,6 @@ static void UpdateCastlingRights(Board &board, int square, int type, int color)
|
||||
|
||||
board.hashKey ^= UTILS::zCastle[board.castlingRights];
|
||||
} else if (type == King) {
|
||||
// Removing old rights
|
||||
board.hashKey ^= UTILS::zCastle[board.castlingRights];
|
||||
|
||||
board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight;
|
||||
@@ -371,8 +369,13 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) {
|
||||
}
|
||||
|
||||
void Board::MakeMove(Move move) {
|
||||
// Null Move
|
||||
const bool accParentClean = accUpdate.type == ACC::UpdateType::None;
|
||||
accUpdate = ACC::Update();
|
||||
|
||||
if (!move) {
|
||||
if (accParentClean) accUpdate.type = ACC::UpdateType::Copy;
|
||||
else accUpdate.setRefresh();
|
||||
|
||||
int newEpTarget = noEPTarget;
|
||||
|
||||
sideToMove = !sideToMove;
|
||||
@@ -397,30 +400,28 @@ void Board::MakeMove(Move move) {
|
||||
|
||||
int endPiece = attackerPiece;
|
||||
|
||||
bool fullRecalc = false;
|
||||
const auto bucketPair = GetBuckets();
|
||||
uint8_t refreshMask = 0;
|
||||
|
||||
if (attackerPiece == King) {
|
||||
const int toFile = move.MoveTo() % 8;
|
||||
|
||||
if (attackerColor == White) {
|
||||
if ((toFile > 3) != accPair.mirroredWhite) {
|
||||
accPair.mirroredWhite = !accPair.mirroredWhite;
|
||||
fullRecalc = true;
|
||||
if ((toFile > 3) != mirroredWhite) {
|
||||
mirroredWhite = !mirroredWhite;
|
||||
refreshMask |= 1 << White;
|
||||
}
|
||||
} else {
|
||||
if ((toFile > 3) != accPair.mirroredBlack) {
|
||||
accPair.mirroredBlack = !accPair.mirroredBlack;
|
||||
fullRecalc = true;
|
||||
if ((toFile > 3) != mirroredBlack) {
|
||||
mirroredBlack = !mirroredBlack;
|
||||
refreshMask |= 1 << Black;
|
||||
}
|
||||
}
|
||||
|
||||
if (NNUE::kingBuckets[attackerColor][move.MoveFrom()] != NNUE::kingBuckets[attackerColor][move.MoveTo()]) {
|
||||
fullRecalc = true;
|
||||
refreshMask |= 1 << attackerColor;
|
||||
}
|
||||
}
|
||||
|
||||
// Removing attacker piece from old position
|
||||
RemovePiece(attackerPiece, move.MoveFrom(), attackerColor);
|
||||
|
||||
if (move.IsPromo()) {
|
||||
@@ -432,16 +433,16 @@ void Board::MakeMove(Move move) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!fullRecalc) {
|
||||
{
|
||||
if (move.IsCapture()) {
|
||||
if (move.GetFlags() != epCapture) {
|
||||
accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece, bucketPair);
|
||||
accUpdate.setAddSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece);
|
||||
} else {
|
||||
accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn, bucketPair);
|
||||
accUpdate.setAddSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn);
|
||||
}
|
||||
} else {
|
||||
if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) {
|
||||
accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, bucketPair);
|
||||
accUpdate.setAddSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -470,16 +471,14 @@ void Board::MakeMove(Move move) {
|
||||
{
|
||||
int rookSquare = attackerColor ? h8 : h1;
|
||||
|
||||
// Removing rook from old position
|
||||
RemovePiece(Rook, rookSquare, attackerColor);
|
||||
|
||||
// Setting rook on new position
|
||||
SetPiece(Rook, rookSquare - 2, attackerColor);
|
||||
|
||||
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
|
||||
|
||||
if (!fullRecalc) {
|
||||
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair);
|
||||
{
|
||||
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -488,16 +487,14 @@ void Board::MakeMove(Move move) {
|
||||
{
|
||||
int rookSquare = attackerColor ? a8 : a1;
|
||||
|
||||
// Removing rook from old position
|
||||
RemovePiece(Rook, rookSquare, attackerColor);
|
||||
|
||||
// Setting rook on new position
|
||||
SetPiece(Rook, rookSquare + 3, attackerColor);
|
||||
|
||||
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
|
||||
|
||||
if (!fullRecalc) {
|
||||
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair);
|
||||
{
|
||||
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -506,11 +503,12 @@ void Board::MakeMove(Move move) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (fullRecalc) {
|
||||
ResetAccPair();
|
||||
if (!accParentClean || accUpdate.type == ACC::UpdateType::None) {
|
||||
accUpdate.setRefresh();
|
||||
} else {
|
||||
accUpdate.refreshMask = refreshMask;
|
||||
}
|
||||
|
||||
// Removing the right to castle on king and rook movement
|
||||
UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor);
|
||||
|
||||
sideToMove = !attackerColor;
|
||||
@@ -531,13 +529,6 @@ void Board::MakeMove(Move move) {
|
||||
checkers = CalcCheckers();
|
||||
CalcCheckZones();
|
||||
|
||||
/*
|
||||
sideToMove = !sideToMove;
|
||||
if (InCheck()) {
|
||||
return false;
|
||||
}
|
||||
sideToMove = !sideToMove;
|
||||
*/
|
||||
|
||||
if (attackerColor == Black) fullMoves++;
|
||||
if (attackerPiece == Pawn || move.IsCapture()) {
|
||||
@@ -552,7 +543,6 @@ void Board::MakeMove(Move move) {
|
||||
bool Board::InPossibleZug() {
|
||||
Bitboard toCheck;
|
||||
|
||||
// For all pieces other than pawns and king
|
||||
for (int piece = Knight; piece <= Queen; piece++) {
|
||||
toCheck |= (pieces[piece] & colors[sideToMove]);
|
||||
}
|
||||
@@ -567,68 +557,141 @@ ACC::BucketPair Board::GetBuckets() {
|
||||
return {NNUE::kingBuckets[White][wKingSq],NNUE::kingBuckets[Black][bKingSq]};
|
||||
}
|
||||
|
||||
void Board::ResetAccPair() {
|
||||
Bitboard whitePieces = colors[White];
|
||||
Bitboard blackPieces = colors[Black];
|
||||
void Board::RefreshAccumulator(ACC::AccumulatorPair& out) const {
|
||||
const int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
|
||||
const int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
|
||||
const ACC::BucketPair bucketPair = {NNUE::kingBuckets[White][wKingSq], NNUE::kingBuckets[Black][bKingSq]};
|
||||
|
||||
accPair.white = NNUE::net.accumulator_biases;
|
||||
accPair.black = NNUE::net.accumulator_biases;
|
||||
out.white = NNUE::net.accumulator_biases;
|
||||
out.black = NNUE::net.accumulator_biases;
|
||||
|
||||
const auto bucketPair = GetBuckets();
|
||||
for (int color = White; color <= Black; color++) {
|
||||
Bitboard bb = colors[color];
|
||||
|
||||
while (whitePieces) {
|
||||
int square = whitePieces.getLS1BIndex();
|
||||
while (bb) {
|
||||
int square = bb.getLS1BIndex();
|
||||
|
||||
int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square, accPair.mirroredWhite);
|
||||
int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square, accPair.mirroredBlack);
|
||||
int wInput = ACC::CalculateIndex(White, color, mailbox[square], square, mirroredWhite);
|
||||
int bInput = ACC::CalculateIndex(Black, color, mailbox[square], square, mirroredBlack);
|
||||
|
||||
for (int i = 0; i < NNUE::HL_SIZE; i++) {
|
||||
accPair.white[i] += NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE + i];
|
||||
accPair.black[i] += NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE + i];
|
||||
ACC::AddRow(out.white, &NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE]);
|
||||
ACC::AddRow(out.black, &NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE]);
|
||||
|
||||
bb.PopBit(square);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
whitePieces.PopBit(square);
|
||||
void Board::RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const {
|
||||
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
|
||||
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
|
||||
const int bucket = NNUE::kingBuckets[perspective][kingSq];
|
||||
|
||||
ACC::FinnyEntry& entry = finny.entries[perspective][mirrored][bucket];
|
||||
|
||||
const int16_t* adds[32];
|
||||
const int16_t* subs[32];
|
||||
int nAdds = 0;
|
||||
int nSubs = 0;
|
||||
|
||||
for (int color = White; color <= Black; color++) {
|
||||
for (int pt = Pawn; pt <= King; pt++) {
|
||||
Bitboard tmp = pieces[pt] & colors[color];
|
||||
const uint64_t now = tmp;
|
||||
const uint64_t old = entry.bb[color][pt];
|
||||
|
||||
uint64_t added = now & ~old;
|
||||
uint64_t removed = old & ~now;
|
||||
|
||||
while (added) {
|
||||
const int square = std::countr_zero(added);
|
||||
added &= added - 1;
|
||||
adds[nAdds++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
|
||||
}
|
||||
|
||||
while (removed) {
|
||||
const int square = std::countr_zero(removed);
|
||||
removed &= removed - 1;
|
||||
subs[nSubs++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
|
||||
}
|
||||
|
||||
entry.bb[color][pt] = now;
|
||||
}
|
||||
}
|
||||
|
||||
while (blackPieces) {
|
||||
int square = blackPieces.getLS1BIndex();
|
||||
ACC::ApplyInPlace(entry.acc, adds, nAdds, subs, nSubs);
|
||||
out = entry.acc;
|
||||
}
|
||||
|
||||
int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square, accPair.mirroredWhite);
|
||||
int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square, accPair.mirroredBlack);
|
||||
void Board::ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const {
|
||||
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
|
||||
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
|
||||
const int bucket = NNUE::kingBuckets[perspective][kingSq];
|
||||
|
||||
for (int i = 0; i < NNUE::HL_SIZE; i++) {
|
||||
accPair.white[i] += NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE + i];
|
||||
accPair.black[i] += NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE + i];
|
||||
}
|
||||
const bool stm = accUpdate.stm;
|
||||
|
||||
blackPieces.PopBit(square);
|
||||
const int16_t* a1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT1, accUpdate.add1, mirrored));
|
||||
const int16_t* a2 = nullptr;
|
||||
const int16_t* s1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.subPT1, accUpdate.sub1, mirrored));
|
||||
const int16_t* s2 = nullptr;
|
||||
|
||||
if (accUpdate.nAdd == 2)
|
||||
a2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT2, accUpdate.add2, mirrored));
|
||||
|
||||
if (accUpdate.nSub == 2)
|
||||
s2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, accUpdate.sub2Opp ? !stm : stm, accUpdate.subPT2, accUpdate.sub2, mirrored));
|
||||
|
||||
ACC::Apply(dst, src, a1, a2, s1, s2);
|
||||
}
|
||||
|
||||
void Board::UpdateAccumulator(ACC::AccStack& stack, int ply) {
|
||||
using ACC::UpdateType;
|
||||
|
||||
if (accUpdate.type == UpdateType::None) return;
|
||||
|
||||
if (accUpdate.type == UpdateType::Copy && ply > 0) {
|
||||
stack.cur[ply] = stack.cur[ply - 1];
|
||||
accUpdate.type = UpdateType::None;
|
||||
return;
|
||||
}
|
||||
|
||||
ACC::AccumulatorPair& dst = stack.slots[ply];
|
||||
|
||||
if (ply == 0 || accUpdate.type != UpdateType::Delta) {
|
||||
RefreshPerspective(stack.finny, White, dst.white);
|
||||
RefreshPerspective(stack.finny, Black, dst.black);
|
||||
} else {
|
||||
const ACC::AccumulatorPair& prev = *stack.cur[ply - 1];
|
||||
|
||||
for (int perspective = White; perspective <= Black; perspective++) {
|
||||
if (accUpdate.refreshMask & (1 << perspective))
|
||||
RefreshPerspective(stack.finny, perspective, dst.get(perspective));
|
||||
else
|
||||
ApplyDeltaPerspective(perspective, dst.get(perspective), prev.get(perspective));
|
||||
}
|
||||
}
|
||||
|
||||
stack.cur[ply] = &dst;
|
||||
accUpdate.type = UpdateType::None;
|
||||
}
|
||||
|
||||
Bitboard Board::AttacksTo(int square, Bitboard occupancy) {
|
||||
Bitboard attacks;
|
||||
|
||||
// Pawn attacks
|
||||
|
||||
// Opponent attacks
|
||||
attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]);
|
||||
|
||||
// Own piece attacks
|
||||
attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]);
|
||||
|
||||
// Knight
|
||||
attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]);
|
||||
|
||||
// King
|
||||
attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]);
|
||||
|
||||
Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy);
|
||||
Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy);
|
||||
|
||||
// Rook or queen
|
||||
attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen]));
|
||||
|
||||
// Bishop or queen
|
||||
attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen]));
|
||||
|
||||
return attacks;
|
||||
@@ -643,7 +706,6 @@ static Bitboard rayBetween(int sq1, int sq2) {
|
||||
int df = (f2 > f1) - (f2 < f1);
|
||||
int dr = (r2 > r1) - (r2 < r1);
|
||||
|
||||
// must be same rank, file, or diagonal
|
||||
if (df != 0 && dr != 0 && std::abs(f2 - f1) != std::abs(r2 - r1))
|
||||
return 0ULL;
|
||||
|
||||
@@ -663,7 +725,6 @@ static Bitboard rayBetween(int sq1, int sq2) {
|
||||
return ray;
|
||||
}
|
||||
|
||||
// Returns the full ray from `from` in the direction of `to`, to the edge of the board
|
||||
static Bitboard fullRay(int from, int to) {
|
||||
int df = (to % 8) - (from % 8);
|
||||
int dr = (to / 8) - (from / 8);
|
||||
@@ -785,7 +846,6 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
const int to = move.MoveTo();
|
||||
const int flag = move.GetFlags();
|
||||
|
||||
// basic bounds
|
||||
if ((unsigned)from >= 64u || (unsigned)to >= 64u) return false;
|
||||
|
||||
const int us = sideToMove;
|
||||
@@ -799,18 +859,14 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
const bool isCapture = move.IsCapture();
|
||||
const int targetPiece = GetPieceType(to);
|
||||
|
||||
// capture consistency (except EP which captures "behind")
|
||||
if (flag == capture) {
|
||||
if (targetPiece == nullPieceType) return false;
|
||||
if (!colors[them].IsSet(to)) return false;
|
||||
} else if (isCapture && flag != epCapture) {
|
||||
// promo-capture also lands on occupied enemy square
|
||||
if (targetPiece == nullPieceType) return false;
|
||||
if (!colors[them].IsSet(to)) return false;
|
||||
} else if (!isCapture) {
|
||||
// quiet moves must not land on occupied square
|
||||
if (occupied.IsSet(to)) {
|
||||
// except castling (king lands on empty anyway)
|
||||
if (flag != kingCastle && flag != queenCastle) return false;
|
||||
}
|
||||
}
|
||||
@@ -827,12 +883,10 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
};
|
||||
|
||||
auto isPawnCaptureTo = [&] {
|
||||
// diagonal one step forward
|
||||
return (to == from + dir - 1 && toFile == fromFile - 1)
|
||||
|| (to == from + dir + 1 && toFile == fromFile + 1);
|
||||
};
|
||||
|
||||
// handle specials by flag first
|
||||
switch (flag) {
|
||||
case quiet:
|
||||
case capture:
|
||||
@@ -840,10 +894,9 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
|
||||
case doublePawnPush: {
|
||||
if (movingPiece != Pawn) return false;
|
||||
// from must be on starting rank
|
||||
if (!us) { // white
|
||||
if (!us) {
|
||||
if (fromRank != 1) return false;
|
||||
} else { // black
|
||||
} else {
|
||||
if (fromRank != 6) return false;
|
||||
}
|
||||
const int mid = from + dir;
|
||||
@@ -858,7 +911,6 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
if (to != enPassantTarget) return false;
|
||||
if (!isPawnCaptureTo()) return false;
|
||||
|
||||
// target square is empty, captured pawn is behind to
|
||||
const int capSq = to - dir;
|
||||
if (!colors[them].IsSet(capSq)) return false;
|
||||
if (GetPieceType(capSq) != Pawn) return false;
|
||||
@@ -883,7 +935,6 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
const int targetSq = us ? g8 : g1;
|
||||
if (to != targetSq) return false;
|
||||
|
||||
// must be exactly king+rook on that side and no attacked transit squares
|
||||
if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false;
|
||||
if (mask & colorThreats[them]) return false;
|
||||
return true;
|
||||
@@ -901,11 +952,9 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
}
|
||||
|
||||
default:
|
||||
// promotions (quiet + capture)
|
||||
if (!move.IsPromo()) return false;
|
||||
if (movingPiece != Pawn) return false;
|
||||
|
||||
// must land on last rank
|
||||
if (!us) {
|
||||
if (toRank != 7) return false;
|
||||
} else {
|
||||
@@ -921,16 +970,13 @@ bool Board::IsPseudoLegal(Move &move) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// normal piece movement checks for quiet/capture (non-special)
|
||||
switch (movingPiece) {
|
||||
case Pawn: {
|
||||
// non-promo pawns cannot land on last rank
|
||||
if (!us) { if (toRank == 7) return false; }
|
||||
else { if (toRank == 0) return false; }
|
||||
|
||||
if (move.IsCapture()) {
|
||||
if (!isPawnCaptureTo()) return false;
|
||||
// (regular capture already checked occupancy/enemy above)
|
||||
return true;
|
||||
} else {
|
||||
return isOneStepPawnPush();
|
||||
|
||||
+8
-2
@@ -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;
|
||||
@@ -63,7 +65,11 @@ public:
|
||||
void ListMoves();
|
||||
|
||||
ACC::BucketPair GetBuckets();
|
||||
void ResetAccPair();
|
||||
void RefreshAccumulator(ACC::AccumulatorPair& out) const;
|
||||
void UpdateAccumulator(ACC::AccStack& stack, int ply);
|
||||
void RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const;
|
||||
void ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const;
|
||||
void MarkAccumulatorDirty() { accUpdate.setRefresh(); }
|
||||
|
||||
int GetPieceType(int square);
|
||||
int GetPieceColor(int square);
|
||||
|
||||
+203
-203
@@ -1,203 +1,203 @@
|
||||
#pragma once
|
||||
#include "bitboard.h"
|
||||
#include "move.h"
|
||||
#include "board.h"
|
||||
|
||||
enum MovegenMode {
|
||||
Quiet,
|
||||
Noisy,
|
||||
All
|
||||
};
|
||||
|
||||
namespace MOVEGEN {
|
||||
|
||||
inline Bitboard pawnAttacks[2][64];
|
||||
inline Bitboard knightAttacks[64];
|
||||
inline Bitboard kingAttacks[64];
|
||||
|
||||
void initLeaperAttacks();
|
||||
void initSliderAttacks();
|
||||
|
||||
Bitboard getBishopAttack(int square, U64 occupancy);
|
||||
Bitboard getRookAttack(int square, U64 occupancy);
|
||||
Bitboard getQueenAttack(int square, U64 occupancy);
|
||||
Bitboard getPawnPushes(int square, bool color, Bitboard &occupancy);
|
||||
Bitboard getPieceAttacks(int square, int piece, int color, U64 occupancy);
|
||||
|
||||
template <MovegenMode mode>
|
||||
void GenPawnMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenKnightMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenRookMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenBishopMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenQueenMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenKingMoves(Board &board);
|
||||
|
||||
template <MovegenMode mode>
|
||||
void GenerateMoves(Board &board, bool clear);
|
||||
|
||||
void GenThreatMaps(Board &board);
|
||||
|
||||
// bishop relevant occupancy bit count
|
||||
constexpr int bishopRelevantBits[64] = {
|
||||
6, 5, 5, 5, 5, 5, 5, 6,
|
||||
5, 5, 5, 5, 5, 5, 5, 5,
|
||||
5, 5, 7, 7, 7, 7, 5, 5,
|
||||
5, 5, 7, 9, 9, 7, 5, 5,
|
||||
5, 5, 7, 9, 9, 7, 5, 5,
|
||||
5, 5, 7, 7, 7, 7, 5, 5,
|
||||
5, 5, 5, 5, 5, 5, 5, 5,
|
||||
6, 5, 5, 5, 5, 5, 5, 6
|
||||
};
|
||||
|
||||
// rook relevant occupancy bit count
|
||||
constexpr int rookRelevantBits[64] = {
|
||||
12, 11, 11, 11, 11, 11, 11, 12,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
12, 11, 11, 11, 11, 11, 11, 12
|
||||
};
|
||||
|
||||
constexpr U64 rookMagicNumbers[64] = {
|
||||
0x8a80104000800020ULL,
|
||||
0x140002000100040ULL,
|
||||
0x2801880a0017001ULL,
|
||||
0x100081001000420ULL,
|
||||
0x200020010080420ULL,
|
||||
0x3001c0002010008ULL,
|
||||
0x8480008002000100ULL,
|
||||
0x2080088004402900ULL,
|
||||
0x800098204000ULL,
|
||||
0x2024401000200040ULL,
|
||||
0x100802000801000ULL,
|
||||
0x120800800801000ULL,
|
||||
0x208808088000400ULL,
|
||||
0x2802200800400ULL,
|
||||
0x2200800100020080ULL,
|
||||
0x801000060821100ULL,
|
||||
0x80044006422000ULL,
|
||||
0x100808020004000ULL,
|
||||
0x12108a0010204200ULL,
|
||||
0x140848010000802ULL,
|
||||
0x481828014002800ULL,
|
||||
0x8094004002004100ULL,
|
||||
0x4010040010010802ULL,
|
||||
0x20008806104ULL,
|
||||
0x100400080208000ULL,
|
||||
0x2040002120081000ULL,
|
||||
0x21200680100081ULL,
|
||||
0x20100080080080ULL,
|
||||
0x2000a00200410ULL,
|
||||
0x20080800400ULL,
|
||||
0x80088400100102ULL,
|
||||
0x80004600042881ULL,
|
||||
0x4040008040800020ULL,
|
||||
0x440003000200801ULL,
|
||||
0x4200011004500ULL,
|
||||
0x188020010100100ULL,
|
||||
0x14800401802800ULL,
|
||||
0x2080040080800200ULL,
|
||||
0x124080204001001ULL,
|
||||
0x200046502000484ULL,
|
||||
0x480400080088020ULL,
|
||||
0x1000422010034000ULL,
|
||||
0x30200100110040ULL,
|
||||
0x100021010009ULL,
|
||||
0x2002080100110004ULL,
|
||||
0x202008004008002ULL,
|
||||
0x20020004010100ULL,
|
||||
0x2048440040820001ULL,
|
||||
0x101002200408200ULL,
|
||||
0x40802000401080ULL,
|
||||
0x4008142004410100ULL,
|
||||
0x2060820c0120200ULL,
|
||||
0x1001004080100ULL,
|
||||
0x20c020080040080ULL,
|
||||
0x2935610830022400ULL,
|
||||
0x44440041009200ULL,
|
||||
0x280001040802101ULL,
|
||||
0x2100190040002085ULL,
|
||||
0x80c0084100102001ULL,
|
||||
0x4024081001000421ULL,
|
||||
0x20030a0244872ULL,
|
||||
0x12001008414402ULL,
|
||||
0x2006104900a0804ULL,
|
||||
0x1004081002402ULL
|
||||
};
|
||||
|
||||
constexpr U64 bishopMagicNumbers[64] = {
|
||||
0x40040844404084ULL,
|
||||
0x2004208a004208ULL,
|
||||
0x10190041080202ULL,
|
||||
0x108060845042010ULL,
|
||||
0x581104180800210ULL,
|
||||
0x2112080446200010ULL,
|
||||
0x1080820820060210ULL,
|
||||
0x3c0808410220200ULL,
|
||||
0x4050404440404ULL,
|
||||
0x21001420088ULL,
|
||||
0x24d0080801082102ULL,
|
||||
0x1020a0a020400ULL,
|
||||
0x40308200402ULL,
|
||||
0x4011002100800ULL,
|
||||
0x401484104104005ULL,
|
||||
0x801010402020200ULL,
|
||||
0x400210c3880100ULL,
|
||||
0x404022024108200ULL,
|
||||
0x810018200204102ULL,
|
||||
0x4002801a02003ULL,
|
||||
0x85040820080400ULL,
|
||||
0x810102c808880400ULL,
|
||||
0xe900410884800ULL,
|
||||
0x8002020480840102ULL,
|
||||
0x220200865090201ULL,
|
||||
0x2010100a02021202ULL,
|
||||
0x152048408022401ULL,
|
||||
0x20080002081110ULL,
|
||||
0x4001001021004000ULL,
|
||||
0x800040400a011002ULL,
|
||||
0xe4004081011002ULL,
|
||||
0x1c004001012080ULL,
|
||||
0x8004200962a00220ULL,
|
||||
0x8422100208500202ULL,
|
||||
0x2000402200300c08ULL,
|
||||
0x8646020080080080ULL,
|
||||
0x80020a0200100808ULL,
|
||||
0x2010004880111000ULL,
|
||||
0x623000a080011400ULL,
|
||||
0x42008c0340209202ULL,
|
||||
0x209188240001000ULL,
|
||||
0x400408a884001800ULL,
|
||||
0x110400a6080400ULL,
|
||||
0x1840060a44020800ULL,
|
||||
0x90080104000041ULL,
|
||||
0x201011000808101ULL,
|
||||
0x1a2208080504f080ULL,
|
||||
0x8012020600211212ULL,
|
||||
0x500861011240000ULL,
|
||||
0x180806108200800ULL,
|
||||
0x4000020e01040044ULL,
|
||||
0x300000261044000aULL,
|
||||
0x802241102020002ULL,
|
||||
0x20906061210001ULL,
|
||||
0x5a84841004010310ULL,
|
||||
0x4010801011c04ULL,
|
||||
0xa010109502200ULL,
|
||||
0x4a02012000ULL,
|
||||
0x500201010098b028ULL,
|
||||
0x8040002811040900ULL,
|
||||
0x28000010020204ULL,
|
||||
0x6000020202d0240ULL,
|
||||
0x8918844842082200ULL,
|
||||
0x4010011029020020ULL
|
||||
};
|
||||
#include "movegen.tpp"
|
||||
}
|
||||
#pragma once
|
||||
#include "bitboard.h"
|
||||
#include "move.h"
|
||||
#include "board.h"
|
||||
|
||||
enum MovegenMode {
|
||||
Quiet,
|
||||
Noisy,
|
||||
All
|
||||
};
|
||||
|
||||
namespace MOVEGEN {
|
||||
|
||||
inline Bitboard pawnAttacks[2][64];
|
||||
inline Bitboard knightAttacks[64];
|
||||
inline Bitboard kingAttacks[64];
|
||||
|
||||
void initLeaperAttacks();
|
||||
void initSliderAttacks();
|
||||
|
||||
Bitboard getBishopAttack(int square, U64 occupancy);
|
||||
Bitboard getRookAttack(int square, U64 occupancy);
|
||||
Bitboard getQueenAttack(int square, U64 occupancy);
|
||||
Bitboard getPawnPushes(int square, bool color, Bitboard &occupancy);
|
||||
Bitboard getPieceAttacks(int square, int piece, int color, U64 occupancy);
|
||||
|
||||
template <MovegenMode mode>
|
||||
void GenPawnMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenKnightMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenRookMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenBishopMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenQueenMoves(Board &board);
|
||||
template <MovegenMode mode>
|
||||
void GenKingMoves(Board &board);
|
||||
|
||||
template <MovegenMode mode>
|
||||
void GenerateMoves(Board &board, bool clear, bool recalcThreats = true);
|
||||
|
||||
void GenThreatMaps(Board &board);
|
||||
|
||||
// bishop relevant occupancy bit count
|
||||
constexpr int bishopRelevantBits[64] = {
|
||||
6, 5, 5, 5, 5, 5, 5, 6,
|
||||
5, 5, 5, 5, 5, 5, 5, 5,
|
||||
5, 5, 7, 7, 7, 7, 5, 5,
|
||||
5, 5, 7, 9, 9, 7, 5, 5,
|
||||
5, 5, 7, 9, 9, 7, 5, 5,
|
||||
5, 5, 7, 7, 7, 7, 5, 5,
|
||||
5, 5, 5, 5, 5, 5, 5, 5,
|
||||
6, 5, 5, 5, 5, 5, 5, 6
|
||||
};
|
||||
|
||||
// rook relevant occupancy bit count
|
||||
constexpr int rookRelevantBits[64] = {
|
||||
12, 11, 11, 11, 11, 11, 11, 12,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
11, 10, 10, 10, 10, 10, 10, 11,
|
||||
12, 11, 11, 11, 11, 11, 11, 12
|
||||
};
|
||||
|
||||
constexpr U64 rookMagicNumbers[64] = {
|
||||
0x8a80104000800020ULL,
|
||||
0x140002000100040ULL,
|
||||
0x2801880a0017001ULL,
|
||||
0x100081001000420ULL,
|
||||
0x200020010080420ULL,
|
||||
0x3001c0002010008ULL,
|
||||
0x8480008002000100ULL,
|
||||
0x2080088004402900ULL,
|
||||
0x800098204000ULL,
|
||||
0x2024401000200040ULL,
|
||||
0x100802000801000ULL,
|
||||
0x120800800801000ULL,
|
||||
0x208808088000400ULL,
|
||||
0x2802200800400ULL,
|
||||
0x2200800100020080ULL,
|
||||
0x801000060821100ULL,
|
||||
0x80044006422000ULL,
|
||||
0x100808020004000ULL,
|
||||
0x12108a0010204200ULL,
|
||||
0x140848010000802ULL,
|
||||
0x481828014002800ULL,
|
||||
0x8094004002004100ULL,
|
||||
0x4010040010010802ULL,
|
||||
0x20008806104ULL,
|
||||
0x100400080208000ULL,
|
||||
0x2040002120081000ULL,
|
||||
0x21200680100081ULL,
|
||||
0x20100080080080ULL,
|
||||
0x2000a00200410ULL,
|
||||
0x20080800400ULL,
|
||||
0x80088400100102ULL,
|
||||
0x80004600042881ULL,
|
||||
0x4040008040800020ULL,
|
||||
0x440003000200801ULL,
|
||||
0x4200011004500ULL,
|
||||
0x188020010100100ULL,
|
||||
0x14800401802800ULL,
|
||||
0x2080040080800200ULL,
|
||||
0x124080204001001ULL,
|
||||
0x200046502000484ULL,
|
||||
0x480400080088020ULL,
|
||||
0x1000422010034000ULL,
|
||||
0x30200100110040ULL,
|
||||
0x100021010009ULL,
|
||||
0x2002080100110004ULL,
|
||||
0x202008004008002ULL,
|
||||
0x20020004010100ULL,
|
||||
0x2048440040820001ULL,
|
||||
0x101002200408200ULL,
|
||||
0x40802000401080ULL,
|
||||
0x4008142004410100ULL,
|
||||
0x2060820c0120200ULL,
|
||||
0x1001004080100ULL,
|
||||
0x20c020080040080ULL,
|
||||
0x2935610830022400ULL,
|
||||
0x44440041009200ULL,
|
||||
0x280001040802101ULL,
|
||||
0x2100190040002085ULL,
|
||||
0x80c0084100102001ULL,
|
||||
0x4024081001000421ULL,
|
||||
0x20030a0244872ULL,
|
||||
0x12001008414402ULL,
|
||||
0x2006104900a0804ULL,
|
||||
0x1004081002402ULL
|
||||
};
|
||||
|
||||
constexpr U64 bishopMagicNumbers[64] = {
|
||||
0x40040844404084ULL,
|
||||
0x2004208a004208ULL,
|
||||
0x10190041080202ULL,
|
||||
0x108060845042010ULL,
|
||||
0x581104180800210ULL,
|
||||
0x2112080446200010ULL,
|
||||
0x1080820820060210ULL,
|
||||
0x3c0808410220200ULL,
|
||||
0x4050404440404ULL,
|
||||
0x21001420088ULL,
|
||||
0x24d0080801082102ULL,
|
||||
0x1020a0a020400ULL,
|
||||
0x40308200402ULL,
|
||||
0x4011002100800ULL,
|
||||
0x401484104104005ULL,
|
||||
0x801010402020200ULL,
|
||||
0x400210c3880100ULL,
|
||||
0x404022024108200ULL,
|
||||
0x810018200204102ULL,
|
||||
0x4002801a02003ULL,
|
||||
0x85040820080400ULL,
|
||||
0x810102c808880400ULL,
|
||||
0xe900410884800ULL,
|
||||
0x8002020480840102ULL,
|
||||
0x220200865090201ULL,
|
||||
0x2010100a02021202ULL,
|
||||
0x152048408022401ULL,
|
||||
0x20080002081110ULL,
|
||||
0x4001001021004000ULL,
|
||||
0x800040400a011002ULL,
|
||||
0xe4004081011002ULL,
|
||||
0x1c004001012080ULL,
|
||||
0x8004200962a00220ULL,
|
||||
0x8422100208500202ULL,
|
||||
0x2000402200300c08ULL,
|
||||
0x8646020080080080ULL,
|
||||
0x80020a0200100808ULL,
|
||||
0x2010004880111000ULL,
|
||||
0x623000a080011400ULL,
|
||||
0x42008c0340209202ULL,
|
||||
0x209188240001000ULL,
|
||||
0x400408a884001800ULL,
|
||||
0x110400a6080400ULL,
|
||||
0x1840060a44020800ULL,
|
||||
0x90080104000041ULL,
|
||||
0x201011000808101ULL,
|
||||
0x1a2208080504f080ULL,
|
||||
0x8012020600211212ULL,
|
||||
0x500861011240000ULL,
|
||||
0x180806108200800ULL,
|
||||
0x4000020e01040044ULL,
|
||||
0x300000261044000aULL,
|
||||
0x802241102020002ULL,
|
||||
0x20906061210001ULL,
|
||||
0x5a84841004010310ULL,
|
||||
0x4010801011c04ULL,
|
||||
0xa010109502200ULL,
|
||||
0x4a02012000ULL,
|
||||
0x500201010098b028ULL,
|
||||
0x8040002811040900ULL,
|
||||
0x28000010020204ULL,
|
||||
0x6000020202d0240ULL,
|
||||
0x8918844842082200ULL,
|
||||
0x4010011029020020ULL
|
||||
};
|
||||
#include "movegen.tpp"
|
||||
}
|
||||
+4
-4
@@ -270,14 +270,14 @@ void GenKingMoves(Board &board) {
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
void GenerateMoves(Board &board, bool clear) {
|
||||
void GenerateMoves(Board &board, bool clear, bool recalcThreats) {
|
||||
if (clear) {
|
||||
board.ResetMoves();
|
||||
board.pieceThreats = {};
|
||||
board.colorThreats = {};
|
||||
}
|
||||
|
||||
GenThreatMaps(board);
|
||||
if (recalcThreats) {
|
||||
GenThreatMaps(board);
|
||||
}
|
||||
|
||||
GenPawnMoves<mode>(board);
|
||||
GenKnightMoves<mode>(board);
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
#include "movepicker.h"
|
||||
#include "search.h"
|
||||
#include "tunables.h"
|
||||
#include <utility>
|
||||
|
||||
namespace SEARCH {
|
||||
|
||||
template <MovegenMode mode>
|
||||
MovePicker<mode>::MovePicker(Board &b, SearchContext *c, int p, Move tt)
|
||||
: board(b), ctx(c), ply(p), ttMove(tt), killerMove(), stage(PickStage::TTMove) {
|
||||
|
||||
if (!ttMove || !board.IsPseudoLegal(ttMove)) {
|
||||
ttMove = Move();
|
||||
}
|
||||
|
||||
if constexpr (mode == Noisy) {
|
||||
if (ttMove && !(ttMove.IsCapture() || ttMove.IsPromo())) {
|
||||
ttMove = Move();
|
||||
}
|
||||
} else {
|
||||
Move killer = ctx->killerMoves[ply];
|
||||
|
||||
if (killer && killer != ttMove && !killer.IsCapture() && !killer.IsPromo()
|
||||
&& board.IsPseudoLegal(killer)) {
|
||||
killerMove = killer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
int MovePicker<mode>::ScoreNoisyMove(Move move) {
|
||||
int score = MoveEstimatedValue(board, move) * noisyScoreScale;
|
||||
|
||||
if (move.IsCapture()) {
|
||||
int attackerType = board.GetPieceType(move.MoveFrom());
|
||||
int targetType = (move.GetFlags() == epCapture) ? Pawn : board.GetPieceType(move.MoveTo());
|
||||
|
||||
score += ctx->capthist[board.sideToMove][attackerType][targetType][move.MoveTo()];
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
int MovePicker<mode>::ScoreQuietMove(Move move) {
|
||||
bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveFrom());
|
||||
bool targetThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveTo());
|
||||
|
||||
int score = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()][sourceThreatened][targetThreatened];
|
||||
|
||||
if (ply > 0) score += ctx->conthist.GetNPly(board, move, ctx, ply, 1);
|
||||
if (ply > 1) score += ctx->conthist.GetNPly(board, move, ctx, ply, 2);
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
void MovePicker<mode>::ScoreNoisyRange() {
|
||||
noisyStart = 0;
|
||||
|
||||
MOVEGEN::GenerateMoves<Noisy>(board, true, false);
|
||||
|
||||
int rawEnd = board.currentMoveIndex;
|
||||
int write = noisyStart;
|
||||
|
||||
for (int read = noisyStart; read < rawEnd; read++) {
|
||||
Move m = board.moveList[read];
|
||||
if (m == ttMove || m == killerMove) continue;
|
||||
|
||||
board.moveList[write] = m;
|
||||
scores[write] = ScoreNoisyMove(m);
|
||||
write++;
|
||||
}
|
||||
|
||||
noisyEnd = write;
|
||||
board.currentMoveIndex = noisyEnd;
|
||||
|
||||
int goodWrite = noisyStart;
|
||||
|
||||
for (int i = noisyStart; i < noisyEnd; i++) {
|
||||
Move m = board.moveList[i];
|
||||
|
||||
if (SEE(board, m, seeOrderingThreshold)) {
|
||||
if (i != goodWrite) {
|
||||
std::swap(board.moveList[i], board.moveList[goodWrite]);
|
||||
std::swap(scores[i], scores[goodWrite]);
|
||||
}
|
||||
goodWrite++;
|
||||
}
|
||||
}
|
||||
|
||||
goodNoisyEnd = goodWrite;
|
||||
noisyCursor = noisyStart;
|
||||
badNoisyCursor = goodNoisyEnd;
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
void MovePicker<mode>::ScoreQuietRange() {
|
||||
quietStart = noisyEnd;
|
||||
|
||||
MOVEGEN::GenerateMoves<Quiet>(board, false, false);
|
||||
|
||||
int rawEnd = board.currentMoveIndex;
|
||||
int write = quietStart;
|
||||
|
||||
for (int read = quietStart; read < rawEnd; read++) {
|
||||
Move m = board.moveList[read];
|
||||
if (m == ttMove || m == killerMove) continue;
|
||||
|
||||
board.moveList[write] = m;
|
||||
scores[write] = ScoreQuietMove(m);
|
||||
write++;
|
||||
}
|
||||
|
||||
quietEnd = write;
|
||||
board.currentMoveIndex = quietEnd;
|
||||
quietCursor = quietStart;
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
Move MovePicker<mode>::PopBest(int &cursor, int end) {
|
||||
if (cursor >= end) return Move();
|
||||
|
||||
int bestIdx = cursor;
|
||||
|
||||
for (int i = cursor + 1; i < end; i++) {
|
||||
if (scores[i] > scores[bestIdx]) bestIdx = i;
|
||||
}
|
||||
|
||||
if (bestIdx != cursor) {
|
||||
std::swap(board.moveList[bestIdx], board.moveList[cursor]);
|
||||
std::swap(scores[bestIdx], scores[cursor]);
|
||||
}
|
||||
|
||||
Move best = board.moveList[cursor];
|
||||
cursor++;
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
template <MovegenMode mode>
|
||||
Move MovePicker<mode>::Next() {
|
||||
while (true) {
|
||||
switch (stage) {
|
||||
case PickStage::TTMove: {
|
||||
stage = PickStage::GenNoisy;
|
||||
if (ttMove) return ttMove;
|
||||
continue;
|
||||
}
|
||||
|
||||
case PickStage::GenNoisy: {
|
||||
ScoreNoisyRange();
|
||||
stage = PickStage::GoodNoisy;
|
||||
continue;
|
||||
}
|
||||
|
||||
case PickStage::GoodNoisy: {
|
||||
Move m = PopBest(noisyCursor, goodNoisyEnd);
|
||||
if (m) return m;
|
||||
|
||||
if constexpr (mode == Noisy) {
|
||||
stage = PickStage::BadNoisy;
|
||||
} else {
|
||||
stage = PickStage::Killer;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
case PickStage::Killer: {
|
||||
stage = PickStage::GenQuiet;
|
||||
if (killerMove) return killerMove;
|
||||
continue;
|
||||
}
|
||||
|
||||
case PickStage::GenQuiet: {
|
||||
ScoreQuietRange();
|
||||
stage = PickStage::Quiet;
|
||||
continue;
|
||||
}
|
||||
|
||||
case PickStage::Quiet: {
|
||||
Move m = PopBest(quietCursor, quietEnd);
|
||||
if (m) return m;
|
||||
|
||||
stage = PickStage::BadNoisy;
|
||||
continue;
|
||||
}
|
||||
|
||||
case PickStage::BadNoisy: {
|
||||
Move m = PopBest(badNoisyCursor, noisyEnd);
|
||||
if (m) return m;
|
||||
|
||||
stage = PickStage::Finished;
|
||||
return Move();
|
||||
}
|
||||
|
||||
case PickStage::Finished:
|
||||
return Move();
|
||||
|
||||
default:
|
||||
return Move();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template class MovePicker<Noisy>;
|
||||
template class MovePicker<All>;
|
||||
|
||||
}
|
||||
+39
-133
@@ -1,155 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include "search.h"
|
||||
#include <array>
|
||||
#include "board.h"
|
||||
#include "movegen.h"
|
||||
|
||||
#include <limits>
|
||||
namespace SEARCH {
|
||||
|
||||
using namespace SEARCH;
|
||||
class SearchContext;
|
||||
|
||||
enum class PickStage {
|
||||
TTMove,
|
||||
GenNoisy,
|
||||
GoodNoisy,
|
||||
Killer,
|
||||
GenQuiet,
|
||||
Quiet,
|
||||
BadNoisy,
|
||||
Finished
|
||||
};
|
||||
|
||||
template <MovegenMode mode>
|
||||
class MovePicker {
|
||||
private:
|
||||
enum Stage {
|
||||
TT,
|
||||
Rest,
|
||||
End
|
||||
};
|
||||
|
||||
Board& board;
|
||||
SearchContext* ctx;
|
||||
Move ttMove;
|
||||
int ply;
|
||||
Stage stage;
|
||||
|
||||
int index;
|
||||
bool generated;
|
||||
|
||||
int scores[MAX_MOVES];
|
||||
|
||||
public:
|
||||
MovePicker(Board& b, SearchContext* c, int p, Move tt)
|
||||
: board(b), ctx(c), ttMove(tt), ply(p), stage(TT), index(0), generated(false)
|
||||
{
|
||||
}
|
||||
MovePicker(Board &board, SearchContext *ctx, int ply, Move ttMove);
|
||||
|
||||
Move Next() {
|
||||
while (true) {
|
||||
switch (stage) {
|
||||
|
||||
case TT: {
|
||||
stage = Rest;
|
||||
|
||||
if (ttMove && board.IsPseudoLegal(ttMove))
|
||||
return ttMove;
|
||||
break;
|
||||
}
|
||||
|
||||
case Rest: {
|
||||
|
||||
if (!generated) {
|
||||
generated = true;
|
||||
|
||||
MOVEGEN::GenerateMoves<mode>(board, true);
|
||||
|
||||
ScoreAllMoves();
|
||||
index = 0;
|
||||
}
|
||||
|
||||
while (index < board.currentMoveIndex) {
|
||||
int idx = FindNext();
|
||||
Move m = board.moveList[idx];
|
||||
|
||||
if (m == ttMove)
|
||||
continue;
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
stage = End;
|
||||
break;
|
||||
}
|
||||
|
||||
case End:
|
||||
return Move();
|
||||
}
|
||||
}
|
||||
}
|
||||
Move Next();
|
||||
|
||||
private:
|
||||
Board &board;
|
||||
SearchContext *ctx;
|
||||
int ply;
|
||||
|
||||
int ScoreMove(Move& move) {
|
||||
Move ttMove;
|
||||
Move killerMove;
|
||||
|
||||
if (move.IsCapture()) {
|
||||
PickStage stage;
|
||||
|
||||
int attackerType = board.GetPieceType(move.MoveFrom());
|
||||
int targetType = board.GetPieceType(move.MoveTo());
|
||||
int noisyStart = 0;
|
||||
int noisyEnd = 0;
|
||||
int goodNoisyEnd = 0;
|
||||
|
||||
if (move.GetFlags() == epCapture)
|
||||
targetType = Pawn;
|
||||
int quietStart = 0;
|
||||
int quietEnd = 0;
|
||||
|
||||
int capthistScore =
|
||||
ctx->capthist[board.sideToMove][attackerType][targetType][move.MoveTo()];
|
||||
int noisyCursor = 0;
|
||||
int badNoisyCursor = 0;
|
||||
int quietCursor = 0;
|
||||
|
||||
return 50000 * SEE(board, move, seeOrderingThreshold)
|
||||
+ (100 * targetType - attackerType + 105)
|
||||
+ capthistScore;
|
||||
}
|
||||
std::array<int, MAX_MOVES> scores{};
|
||||
|
||||
if (ctx->killerMoves[ply] == move)
|
||||
return 41000;
|
||||
void ScoreNoisyRange();
|
||||
|
||||
bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveFrom());
|
||||
bool targetThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveTo());
|
||||
void ScoreQuietRange();
|
||||
|
||||
int historyScore =
|
||||
ctx->history[board.sideToMove]
|
||||
[move.MoveFrom()]
|
||||
[move.MoveTo()]
|
||||
[sourceThreatened]
|
||||
[targetThreatened];
|
||||
int ScoreNoisyMove(Move move);
|
||||
int ScoreQuietMove(Move move);
|
||||
|
||||
int conthistScore = 0;
|
||||
Move PopBest(int &cursor, int end);
|
||||
};
|
||||
|
||||
if (ply > 0) {
|
||||
conthistScore = ctx->conthist.GetNPly(board, move, ctx, ply, 1);
|
||||
|
||||
if (ply > 1)
|
||||
conthistScore += ctx->conthist.GetNPly(board, move, ctx, ply, 2);
|
||||
}
|
||||
|
||||
return 20000 + historyScore + conthistScore;
|
||||
}
|
||||
|
||||
void ScoreAllMoves() {
|
||||
int moveCount = board.currentMoveIndex;
|
||||
for (int i = 0; i < moveCount; i++)
|
||||
scores[i] = ScoreMove(board.moveList[i]);
|
||||
}
|
||||
|
||||
int FindNext() {
|
||||
const auto toU64 = [](int s) {
|
||||
int64_t widened = s;
|
||||
widened -= std::numeric_limits<int32_t>::min();
|
||||
return static_cast<uint64_t>(widened) << 32;
|
||||
};
|
||||
|
||||
int moveCount = board.currentMoveIndex;
|
||||
|
||||
uint64_t best = toU64(scores[index]) | static_cast<uint64_t>(256 - index);
|
||||
for (int i = index + 1; i < moveCount; i++) {
|
||||
uint64_t curr = toU64(scores[i]) | static_cast<uint64_t>(256 - i);
|
||||
if (curr > best)
|
||||
best = curr;
|
||||
}
|
||||
|
||||
int bestIdx = 256 - static_cast<int>(best & 0xFFFFFFFF);
|
||||
|
||||
if (bestIdx != index) {
|
||||
std::swap(board.moveList[index], board.moveList[bestIdx]);
|
||||
std::swap(scores[index], scores[bestIdx]);
|
||||
}
|
||||
|
||||
return index++;
|
||||
}
|
||||
};
|
||||
}
|
||||
+13
-16
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
|
||||
+80
-66
@@ -78,18 +78,21 @@ static int AdjustEval(Board &board, SearchContext* ctx, int eval) {
|
||||
|
||||
int mateFound = MATE_SCORE - MAX_DEPTH;
|
||||
|
||||
return std::clamp(eval + corrhist / CORRHIST_GRAIN, -mateFound + 1, mateFound - 1);
|
||||
int adjusted = eval + corrhist / CORRHIST_GRAIN;
|
||||
|
||||
const int scaleNumerator = std::max(0, fiftyMoveScaleBase - board.halfMoves);
|
||||
adjusted = adjusted * scaleNumerator / fiftyMoveScaleBase;
|
||||
|
||||
return std::clamp(adjusted, -mateFound + 1, mateFound - 1);
|
||||
}
|
||||
|
||||
static bool IsTwoFold(Board &board, SearchContext* ctx) {
|
||||
for (int i = 0; i < board.positionIndex; i++) {
|
||||
if (ctx->positionHistory[i] == board.hashKey) {
|
||||
// repetition found
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// no repetition
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -110,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)
|
||||
@@ -131,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()) {
|
||||
@@ -172,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();
|
||||
}
|
||||
@@ -236,20 +236,20 @@ bool SEE(Board& board, Move& move, int threshold) {
|
||||
template <searchMode mode>
|
||||
static bool ShouldStop(SearchContext* ctx) {
|
||||
if constexpr (mode == normal) {
|
||||
if (ctx->nodes % 1024 == 0) {
|
||||
if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) {
|
||||
searchStopped = true;
|
||||
if (ctx->nodes % 1024 == 0) {
|
||||
if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) {
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if constexpr (mode == nodesMode) {
|
||||
if (ctx->nodes > ctx->nodesToGo) {
|
||||
searchStopped = true;
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
return true;
|
||||
}
|
||||
} else if constexpr (mode == datagen) {
|
||||
if (ctx->nodes > DATAGEN::HARD_NODES) {
|
||||
searchStopped = true;
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -265,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;
|
||||
@@ -284,6 +302,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
|
||||
if (entry.hashKey == board.hashKey) {
|
||||
ttHit = true;
|
||||
entry.score = ScoreFromTT(entry.score, ply);
|
||||
|
||||
switch (entry.nodeType) {
|
||||
case PV:
|
||||
@@ -291,9 +310,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,12 +324,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,7 +357,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)) {
|
||||
|
||||
@@ -364,7 +387,8 @@ 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) {
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, ScoreToTT(score, ply), CutNode, currMove, ttpv);
|
||||
return score;
|
||||
}
|
||||
|
||||
@@ -378,8 +402,8 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
}
|
||||
|
||||
results.score = bestScore;
|
||||
if (searchStopped) return 0;
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv);
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, ScoreToTT(results.score, ply), nodeType, results.bestMove, ttpv);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -388,7 +412,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;
|
||||
@@ -403,6 +427,9 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
const bool ttHit = entry.hashKey == board.hashKey;
|
||||
const bool ttpv = isPV | entry.ttpv;
|
||||
|
||||
if (ttHit)
|
||||
entry.score = ScoreFromTT(entry.score, ply);
|
||||
|
||||
if constexpr (!isPV) {
|
||||
if (ttHit) {
|
||||
if (entry.depth >= depth &&
|
||||
@@ -417,7 +444,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;
|
||||
|
||||
@@ -449,7 +476,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)
|
||||
@@ -457,12 +483,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;
|
||||
@@ -474,7 +498,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
|
||||
int score = -PVS<false, mode>(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score;
|
||||
|
||||
if (searchStopped) return 0;
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
if (score >= beta) {
|
||||
if (depth <= 14 || ctx->minNmpPly > 0) {
|
||||
return score > MATE_SCORE - MAX_DEPTH ? beta : score;
|
||||
@@ -495,7 +519,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
}
|
||||
}
|
||||
|
||||
// Probcut
|
||||
const int probcutBeta = beta + probcutBetaMargin;
|
||||
const int probcutDepth = std::max(depth - 3, 1);
|
||||
|
||||
@@ -533,10 +556,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
ply + 1, ctx, !cutnode).score;
|
||||
}
|
||||
|
||||
if (searchStopped) return 0;
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
|
||||
if (score >= probcutBeta) {
|
||||
ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, probcutDepth, ScoreToTT(score, ply), CutNode, currMove, ttpv);
|
||||
|
||||
return score;
|
||||
}
|
||||
@@ -559,7 +582,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())) {
|
||||
|
||||
@@ -569,9 +591,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);
|
||||
@@ -589,9 +608,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()
|
||||
@@ -599,10 +615,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;
|
||||
|
||||
|
||||
@@ -610,14 +625,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);
|
||||
@@ -637,22 +644,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) {
|
||||
@@ -665,6 +668,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;
|
||||
|
||||
@@ -696,12 +707,11 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
|
||||
moveSeen++;
|
||||
|
||||
// Root
|
||||
if (!ply) {
|
||||
ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch;
|
||||
}
|
||||
|
||||
if (searchStopped) return 0;
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
|
||||
if (currMove != 0 && currMove.IsQuiet()) {
|
||||
seenQuiets[seenQuietsCount] = currMove;
|
||||
@@ -720,7 +730,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;
|
||||
@@ -760,7 +769,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());
|
||||
@@ -770,26 +778,27 @@ 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);
|
||||
}
|
||||
|
||||
if (!ctx->excluded && !inCheck && currMove.IsQuiet() && score > staticEval) {
|
||||
int corrHistBonus = std::clamp(score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT);
|
||||
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
|
||||
}
|
||||
|
||||
if (!ctx->excluded)
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, score, CutNode, currMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, ScoreToTT(score, ply), CutNode, currMove, ttpv);
|
||||
return score;
|
||||
}
|
||||
}
|
||||
|
||||
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) return 0;
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
if (!ctx->excluded) {
|
||||
|
||||
if (!inCheck && ((results.bestMove.IsQuiet() || !results.bestMove))
|
||||
@@ -800,7 +809,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
|
||||
}
|
||||
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, ScoreToTT(results.score, ply), nodeType, results.bestMove, ttpv);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -837,7 +846,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;
|
||||
@@ -888,7 +896,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
|
||||
aw.Set(currentResults.score);
|
||||
|
||||
if (searchStopped) {
|
||||
if (searchStopped.load(std::memory_order_relaxed)) {
|
||||
break;
|
||||
} else {
|
||||
if (currentResults.bestMove) {
|
||||
@@ -901,13 +909,13 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
|
||||
if constexpr (mode == normal) {
|
||||
if (ctx->sw.GetElapsedMS() >= softTime) {
|
||||
searchStopped = true;
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if constexpr (mode == datagen) {
|
||||
if (ctx->nodes >= DATAGEN::SOFT_NODES) {
|
||||
searchStopped = true;
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -919,8 +927,14 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
|
||||
template <searchMode mode>
|
||||
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
searchStopped = false;
|
||||
ctx->TT->IncreaseAge();
|
||||
if constexpr (mode == bench || mode == datagen) {
|
||||
searchStopped.store(false, std::memory_order_relaxed);
|
||||
ctx->TT->IncreaseAge();
|
||||
}
|
||||
|
||||
board.MarkAccumulatorDirty();
|
||||
ctx->accStack.finny.Reset();
|
||||
|
||||
ctx->seldepth = 0;
|
||||
ctx->nodesTable = {};
|
||||
if constexpr (mode != bench) {
|
||||
|
||||
+18
-5
@@ -34,7 +34,22 @@ constexpr int CORRHIST_MAX = 16384;
|
||||
constexpr int32_t ScoreNone = -255000;
|
||||
constexpr int inf = 100000;
|
||||
|
||||
// first index: [0] noisy, [1] quiet
|
||||
inline int ScoreToTT(int score, int ply) {
|
||||
if (score >= MATE_SCORE - MAX_DEPTH)
|
||||
return score + ply;
|
||||
if (score <= -MATE_SCORE + MAX_DEPTH)
|
||||
return score - ply;
|
||||
return score;
|
||||
}
|
||||
|
||||
inline int ScoreFromTT(int score, int ply) {
|
||||
if (score >= MATE_SCORE - MAX_DEPTH)
|
||||
return score - ply;
|
||||
if (score <= -MATE_SCORE + MAX_DEPTH)
|
||||
return score + ply;
|
||||
return score;
|
||||
}
|
||||
|
||||
inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES];
|
||||
|
||||
#ifdef TUNING
|
||||
@@ -58,7 +73,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,7 +92,6 @@ 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;
|
||||
@@ -112,7 +125,6 @@ public:
|
||||
|
||||
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) {
|
||||
@@ -135,7 +147,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) {
|
||||
@@ -247,6 +258,8 @@ public:
|
||||
|
||||
std::array<Stack, MAX_DEPTH> ss{};
|
||||
|
||||
ACC::AccStack accStack{MAX_DEPTH + 2};
|
||||
|
||||
Stopwatch sw;
|
||||
|
||||
SearchContext(){
|
||||
|
||||
+1
-1
@@ -47,4 +47,4 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b
|
||||
|
||||
current->age = age;
|
||||
current->ttpv = ttpv;
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -67,13 +67,11 @@ public:
|
||||
TTable() : table(defaultHash) {};
|
||||
|
||||
void Resize(U64 size) {
|
||||
table.resize(size);
|
||||
table.assign(size, {});
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
U64 size = table.size();
|
||||
table.clear();
|
||||
table.resize(size);
|
||||
std::fill(table.begin(), table.end(), TTBucket());
|
||||
}
|
||||
|
||||
void PrefetchEntry(U64 &hashKey) {
|
||||
@@ -109,4 +107,4 @@ public:
|
||||
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv);
|
||||
};
|
||||
|
||||
extern TTable SharedTT;
|
||||
extern TTable SharedTT;
|
||||
+3
-1
@@ -41,6 +41,7 @@
|
||||
X_INT(seeQsThreshold, -13, -120, 120) \
|
||||
X_INT(seeOrderingThreshold, -102, -200, 0) \
|
||||
X_INT(ldseMargin, 26, 0, 96) \
|
||||
X_INT(noisyScoreScale, 32, 0, 96) \
|
||||
X_INT(historyBonusMultiplier, 306, 280, 320) \
|
||||
X_INT(historyBonusSub, 252, 235, 265) \
|
||||
X_INT(historyMalusMultiplier, 301, 280, 320) \
|
||||
@@ -52,7 +53,8 @@
|
||||
X_INT(captHistoryBonusMultiplier, 302, 280, 320) \
|
||||
X_INT(captHistoryBonusSub, 249, 235, 265) \
|
||||
X_INT(captHistoryMalusMultiplier, 300, 280, 320) \
|
||||
X_INT(captHistoryMalusSub, 249, 235, 265)
|
||||
X_INT(captHistoryMalusSub, 249, 235, 265) \
|
||||
X_INT(fiftyMoveScaleBase, 200, 100, 400)
|
||||
|
||||
#ifdef TUNING
|
||||
#define X_DOUBLE(name, default_val, min_val, max_val) \
|
||||
|
||||
+89
-15
@@ -4,6 +4,7 @@
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <memory>
|
||||
#include <algorithm>
|
||||
#include "types.h"
|
||||
#include "movegen.h"
|
||||
#include "search.h"
|
||||
@@ -20,9 +21,55 @@
|
||||
#include <pthread.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr size_t DefaultPositionHistorySize = 1000;
|
||||
|
||||
static void EnsurePositionHistory(SEARCH::SearchContext* ctx, int positionIndex) {
|
||||
if (positionIndex >= static_cast<int>(ctx->positionHistory.size())) {
|
||||
ctx->positionHistory.resize(positionIndex + 100);
|
||||
}
|
||||
}
|
||||
|
||||
static void ResetPositionHistory(SEARCH::SearchContext* ctx, const Board& board) {
|
||||
const size_t historySize = std::max(DefaultPositionHistorySize, static_cast<size_t>(board.positionIndex + 100));
|
||||
ctx->positionHistory.assign(historySize, 0);
|
||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
static std::vector<std::thread> searchThreads;
|
||||
#else
|
||||
static std::vector<pthread_t> searchThreads;
|
||||
#endif
|
||||
|
||||
static void JoinSearchThreads() {
|
||||
#ifdef _WIN32
|
||||
for (auto& thread : searchThreads) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
#else
|
||||
for (pthread_t& thread : searchThreads) {
|
||||
pthread_join(thread, nullptr);
|
||||
}
|
||||
#endif
|
||||
|
||||
searchThreads.clear();
|
||||
}
|
||||
|
||||
static void StopSearchThreads() {
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
JoinSearchThreads();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext* ctx) {
|
||||
if (command.find("startpos") != std::string::npos) {
|
||||
board.SetByFen(StartingFen);
|
||||
ResetPositionHistory(ctx, board);
|
||||
}
|
||||
|
||||
int fenIndex = command.find("fen");
|
||||
@@ -34,6 +81,8 @@ static void ParsePosition(Board &board, std::string_view command, SEARCH::Search
|
||||
} else {
|
||||
board.SetByFen(command.substr(fenIndex + 4, command.length() - (fenIndex + 3)));
|
||||
}
|
||||
|
||||
ResetPositionHistory(ctx, board);
|
||||
}
|
||||
|
||||
if (movesIndex != std::string::npos) {
|
||||
@@ -41,6 +90,7 @@ static void ParsePosition(Board &board, std::string_view command, SEARCH::Search
|
||||
|
||||
for (std::string_view move : moves) {
|
||||
board.MakeMove(UTILS::parseMove(board, move));
|
||||
EnsurePositionHistory(ctx, board.positionIndex);
|
||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||
}
|
||||
}
|
||||
@@ -89,22 +139,21 @@ static double ReadParam(const std::string& param, const std::string &command) {
|
||||
#ifdef _WIN32
|
||||
// Windows implementation using std::thread
|
||||
template <SEARCH::searchMode mode>
|
||||
static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) {
|
||||
SEARCH::SearchPosition<mode>(*board, params, ctx);
|
||||
static void ThreadFunc(Board board, SearchParams params, SEARCH::SearchContext* ctx) {
|
||||
SEARCH::SearchPosition<mode>(board, params, ctx);
|
||||
delete ctx;
|
||||
}
|
||||
|
||||
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
|
||||
std::thread searchThread;
|
||||
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
|
||||
if (id == 0)
|
||||
ctxCopy->doPrint = true;
|
||||
|
||||
if (params.nodes) {
|
||||
searchThread = std::thread(ThreadFunc<SEARCH::nodesMode>, &board, params, ctxCopy);
|
||||
searchThreads.emplace_back(ThreadFunc<SEARCH::nodesMode>, board, params, ctxCopy);
|
||||
} else {
|
||||
searchThread = std::thread(ThreadFunc<SEARCH::normal>, &board, params, ctxCopy);
|
||||
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy);
|
||||
}
|
||||
searchThread.detach();
|
||||
}
|
||||
|
||||
#else
|
||||
@@ -124,25 +173,46 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
|
||||
|
||||
pthread_t thread;
|
||||
|
||||
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
|
||||
if (id == 0)
|
||||
ctxCopy->doPrint = true;
|
||||
|
||||
pthread_t thread;
|
||||
int rc = 0;
|
||||
|
||||
if (params.nodes) {
|
||||
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
|
||||
pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
|
||||
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
|
||||
if (rc != 0) {
|
||||
delete std::get<2>(*arg);
|
||||
delete arg;
|
||||
ctxCopy = nullptr;
|
||||
}
|
||||
} else {
|
||||
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
|
||||
pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
|
||||
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
|
||||
if (rc != 0) {
|
||||
delete std::get<2>(*arg);
|
||||
delete arg;
|
||||
ctxCopy = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_attr_destroy(&attr);
|
||||
pthread_detach(thread);
|
||||
|
||||
if (rc == 0) {
|
||||
searchThreads.push_back(thread);
|
||||
} else {
|
||||
delete ctxCopy;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) {
|
||||
StopSearchThreads();
|
||||
searchStopped.store(false, std::memory_order_relaxed);
|
||||
ctx->TT->IncreaseAge();
|
||||
|
||||
SearchParams params;
|
||||
|
||||
params.wtime = ReadParam("wtime", command);
|
||||
@@ -160,12 +230,15 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c
|
||||
params.btime = 99999999;
|
||||
}
|
||||
|
||||
searchThreads.reserve(threads);
|
||||
for (int i = 0; i < threads; i++) {
|
||||
StartSearchThread(board, params, ctx, i);
|
||||
}
|
||||
}
|
||||
|
||||
static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
|
||||
StopSearchThreads();
|
||||
|
||||
if (command.find("Hash") != std::string::npos) {
|
||||
U64 hashSize = (ReadParam("value", command) * 1000000ULL) / sizeof(TTEntry);
|
||||
ctx->TT->Resize(hashSize);
|
||||
@@ -228,7 +301,7 @@ static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
|
||||
}
|
||||
|
||||
static void PrintEngineInfo() {
|
||||
std::cout << "id name Eleanor v4.0" << std::endl;
|
||||
std::cout << "id name Eleanor v4.1" << std::endl;
|
||||
std::cout << "id author rektdie" << std::endl;
|
||||
std::cout << "option name Hash type spin default 8 min 1 max 1024" << std::endl;
|
||||
std::cout << "option name Threads type spin default 1 min 1 max 512" << std::endl;
|
||||
@@ -265,6 +338,7 @@ void UCILoop(Board &board) {
|
||||
|
||||
// parse UCI "ucinewgame" command
|
||||
if (input.find("ucinewgame") != std::string::npos) {
|
||||
StopSearchThreads();
|
||||
board.SetByFen(StartingFen);
|
||||
|
||||
// Clearing
|
||||
@@ -274,7 +348,7 @@ void UCILoop(Board &board) {
|
||||
ctx->history.Clear();
|
||||
ctx->conthist.Clear();
|
||||
ctx->corrhist.Clear();
|
||||
ctx->positionHistory = {};
|
||||
ResetPositionHistory(ctx.get(), board);
|
||||
ctx->ss = {};
|
||||
|
||||
continue;
|
||||
@@ -288,14 +362,14 @@ void UCILoop(Board &board) {
|
||||
|
||||
// parse UCI "quit" command
|
||||
if (input.find("quit") != std::string::npos) {
|
||||
StopSearchThreads();
|
||||
// stop the loop
|
||||
break;
|
||||
}
|
||||
|
||||
// parse UCI "stop" command
|
||||
if (input.find("stop") != std::string::npos) {
|
||||
// stop the loop
|
||||
searchStopped = true;
|
||||
StopSearchThreads();
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,11 +1,12 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include "move.h"
|
||||
#include "board.h"
|
||||
|
||||
inline bool UCIEnabled = false;
|
||||
inline bool UCIShowWDL = false;
|
||||
inline int threads = 1;
|
||||
inline bool searchStopped = false;
|
||||
inline std::atomic<bool> searchStopped = false;
|
||||
|
||||
class SearchParams {
|
||||
public:
|
||||
|
||||
Reference in new issue
Block a user