Author SHA1 Message Date
claude aa97abaadc Add Chess960 (FRC) and DFRC support
- castling moves are stored as "king takes own rook" (from = king square, to = castling rook square)
- per-colour castling rook squares (Board::castleRook), so DFRC (different back ranks for white/black) works
- FEN parsing/printing: KQkq (X-FEN) and Shredder-FEN file letters
- Board::CanCastle(): generic castling legality (empty paths, king not attacked, rook x-ray check)
- MakeMove handles arbitrary king/rook start squares (king and rook may stay in place or swap through each other's squares)
- UCI_Chess960 option: castling printed/parsed as king-takes-rook when on, standard e1g1 style otherwise (both are accepted when parsing)
- viri format, perft castle check and castling right updates no longer assume a1/h1/a8/h8
2026-10-11 00:12:02 +02:00
rektdie e984510434 Merge pull request #197 from rektdie/mate-distance-pruning
mate distance pruning | bench 1632393
2026-10-08 15:21:36 +02:00
rektdie c7b545101e mate distance pruning | bench 1632393 2026-10-06 22:13:57 +02:00
rektdie 69068acb99 Merge pull request #196 from rektdie/smp-persist-history
smp persist history | bench 1632393
2026-10-06 21:36:45 +02:00
rektdie cd2265a46b smp persist history | bench 1632393 2026-10-06 18:03:08 +02:00
rektdie cae93f13a5 Merge pull request #195 from rektdie/thread-voting
thread voting | bench 1632393
2026-10-06 17:50:53 +02:00
rektdie 5a1bcf547c thread voting | bench 1632393 2026-10-05 21:40:06 +02:00
rektdie 3a813876f4 prettier printings | bench 1632393 2026-10-05 19:38:58 +02:00
rektdie a1115b3373 go commands + commands helper | bench 1632393 2026-10-05 17:16:19 +02:00
rektdie 3b79f22ec7 Merge pull request #194 from rektdie/datagen-frontend
datagen new ui | bench 1632393
2026-10-03 20:15:32 +02:00
rektdie f3411c524c datagen new ui | bench 1632393 2026-10-03 20:12:36 +02:00
rektdie 134af1abde Merge pull request #193 from rektdie/lazy-acc-with-finny
lazy accumulator updates with finny tables bench 1632393
2026-10-03 16:38:26 +02:00
rektdie 1e41671002 lazy accumulator updates with finny tables 1632393 2026-10-03 16:13:52 +02:00
rektdie dd831d14bf Merge pull request #192 from rektdie/fix-qs-tt-write
check for stop before writing into qs tt (cutnode) | bench 1402552
2026-10-03 15:58:20 +02:00
rektdie ae3a39cf04 check for stop before writing into qs tt (cutnode) | bench 1402552 2026-10-03 15:57:50 +02:00
rektdie aa120b14f9 Merge pull request #191 from rektdie/pvs-see-notmated
pvs see not mated guard | bench 1632393
2026-10-03 09:27:30 +02:00
rektdie 4c67267c8c pvs see not mated guard | bench 1632393 2026-10-03 09:21:09 +02:00
rektdie 2c4292c485 Merge pull request #190 from rektdie/excluded-terminal-decision
when moveseen = 0, returning alpha in case of excluded move | bench 1293332
2026-10-03 09:19:53 +02:00
rektdie f77c4c1fbd when moveseen = 0, returning alpha in case of excluded move | bench 1293332 2026-10-01 22:47:27 +02:00
rektdie e64c6c60b9 Merge pull request #189 from rektdie/fix-se-ss-overwrite
moving ss storing under se to prevent overwriting | bench 1342782
2026-10-01 18:30:02 +02:00
rektdie de1d0e22ff moving ss storing under se to prevent overwriting | bench 1342782 2026-09-30 20:01:33 +02:00
rektdie d593833e9e Merge pull request #188 from rektdie/qs-switch-fix
fix switch statements in qsearch | bench 1402552
2026-09-30 19:58:05 +02:00
rektdie a2297ed04e fix switch statements in qsearch | bench 1402552 2026-09-30 18:40:22 +02:00
22 changed files with 2995 additions and 561 deletions

No files matched your search

+2
View File
@@ -49,6 +49,7 @@ You can interact with the engine via these commands:
- `position startpos`
- `ucinewgame` — Resets the position and game state
- `setoption name UCI_Chess960 value true` — Enables Chess960 (FRC / DFRC) castling notation (king takes own rook, e.g. `e1h1`). Positions can be given as `position fen [FEN]` with X-FEN or Shredder-FEN castling rights
- `quit` — Terminates the program
- `go` — Begins search and returns the best move
- Parameters (all in **milliseconds**):
@@ -57,6 +58,7 @@ You can interact with the engine via these commands:
- `stop` — Stops the current search
- `bench` — Runs a speed benchmark on a set of positions
- `nnue [full]` — Shows a detailed breakdown of the neural network evaluation for the current position (`full` adds histograms, per-step math and top 8 neurons)
The engine can be used in any GUI with **UCI support**.
+151 -51
View File
@@ -7,80 +7,180 @@ namespace ACC {
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored) {
if (perspective == Black)
{
side = 1 - side; // Flip side
square = square ^ 0b111000; // Mirror square
side = 1 - side;
square = square ^ 0b111000;
}
if (mirrored)
square ^= 7;
return side * 64 * 6 + pieceType * 64 + square;
}
// All friendly, for quiets
void AccumulatorPair::addSub(bool stm, int add, int addPT, int sub, int subPT, BucketPair bp) {
int addW = CalculateIndex(White, stm, addPT, add, mirroredWhite);
int addB = CalculateIndex(Black, stm, addPT, add, mirroredBlack);
const int16_t* Row(int bucket, int index) {
return &NNUE::net.accumulator_weights[bucket][static_cast<size_t>(index) * NNUE::HL_SIZE];
}
int subW = CalculateIndex(White, stm, subPT, sub, mirroredWhite);
int subB = CalculateIndex(Black, stm, subPT, sub, mirroredBlack);
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[bp.white][addW * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[bp.black][addB * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB * NNUE::HL_SIZE + i];
void FinnyTable::Reset() {
for (auto& perspective : entries) {
for (auto& mirror : perspective) {
for (auto& entry : mirror) {
entry.acc = NNUE::net.accumulator_biases;
for (auto& color : entry.bb)
for (auto& bb : color)
bb = 0;
}
}
}
}
// Captures
void AccumulatorPair::addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp) {
int addW = CalculateIndex(White, stm, addPT, add, mirroredWhite);
int addB = CalculateIndex(Black, stm, addPT, add, mirroredBlack);
#if defined(_MSC_VER) && !defined(__clang__)
#define ACC_NOINLINE __declspec(noinline)
#else
#define ACC_NOINLINE __attribute__((noinline))
#endif
int subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack);
#if defined(__AVX512F__) && defined(__AVX512BW__)
#include <immintrin.h>
using Vec = __m512i;
static inline Vec vLoad(const int16_t* p) { return _mm512_loadu_si512(p); }
static inline void vStore(int16_t* p, Vec v) { _mm512_storeu_si512(p, v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm512_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm512_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__AVX2__)
#include <immintrin.h>
using Vec = __m256i;
static inline Vec vLoad(const int16_t* p) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); }
static inline void vStore(int16_t* p, Vec v) { _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm256_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm256_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64)
#include <immintrin.h>
using Vec = __m128i;
static inline Vec vLoad(const int16_t* p) { return _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); }
static inline void vStore(int16_t* p, Vec v) { _mm_storeu_si128(reinterpret_cast<__m128i*>(p), v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__aarch64__)
#include <arm_neon.h>
using Vec = int16x8_t;
static inline Vec vLoad(const int16_t* p) { return vld1q_s16(p); }
static inline void vStore(int16_t* p, Vec v) { vst1q_s16(p, v); }
static inline Vec vAdd(Vec a, Vec b) { return vaddq_s16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return vsubq_s16(a, b); }
#define ACC_SIMD 1
#endif
int subW2 = CalculateIndex(White, !stm, subPT2, sub2, mirroredWhite);
int subB2 = CalculateIndex(Black, !stm, subPT2, sub2, mirroredBlack);
#ifdef ACC_SIMD
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[bp.white][addW * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW2 * NNUE::HL_SIZE + i];
constexpr size_t LANES = sizeof(Vec) / sizeof(int16_t);
constexpr size_t TILE = 4;
constexpr size_t STEP = LANES * TILE;
static_assert(NNUE::HL_SIZE % STEP == 0, "HL size must be divisible by the SIMD tile size");
black[i] += NNUE::net.accumulator_weights[bp.black][addB * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB2 * NNUE::HL_SIZE + i];
template <int NA, int NS>
ACC_NOINLINE static void ApplyKernel(int16_t* dst, const int16_t* src,
const int16_t* a1, const int16_t* a2,
const int16_t* s1, const int16_t* s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
Vec r[TILE];
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(src + i + u * LANES);
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a1 + i + u * LANES));
if constexpr (NA > 1)
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a2 + i + u * LANES));
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s1 + i + u * LANES));
if constexpr (NS > 1)
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s2 + i + u * LANES));
for (size_t u = 0; u < TILE; u++) vStore(dst + i + u * LANES, r[u]);
}
}
// Castling
void AccumulatorPair::addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp) {
int addW1 = CalculateIndex(White, stm, addPT1, add1, mirroredWhite);
int addB1 = CalculateIndex(Black, stm, addPT1, add1, mirroredBlack);
ACC_NOINLINE static void InPlaceKernel(int16_t* acc, const int16_t* const* adds, int nAdds,
const int16_t* const* subs, int nSubs) {
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
Vec r[TILE];
int addW2 = CalculateIndex(White, stm, addPT2, add2, mirroredWhite);
int addB2 = CalculateIndex(Black, stm, addPT2, add2, mirroredBlack);
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(acc + i + u * LANES);
int subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack);
for (int j = 0; j < nAdds; j++)
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(adds[j] + i + u * LANES));
int subW2 = CalculateIndex(White, stm, subPT2, sub2, mirroredWhite);
int subB2 = CalculateIndex(Black, stm, subPT2, sub2, mirroredBlack);
for (int j = 0; j < nSubs; j++)
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(subs[j] + i + u * LANES));
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[bp.white][addW1 * NNUE::HL_SIZE + i]
+ NNUE::net.accumulator_weights[bp.white][addW2 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW2 * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[bp.black][addB1 * NNUE::HL_SIZE + i]
+ NNUE::net.accumulator_weights[bp.black][addB2 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB2 * NNUE::HL_SIZE + i];
for (size_t u = 0; u < TILE; u++) vStore(acc + i + u * LANES, r[u]);
}
}
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
if (a2)
ApplyKernel<2, 2>(dst.data(), src.data(), a1, a2, s1, s2);
else if (s2)
ApplyKernel<1, 2>(dst.data(), src.data(), a1, nullptr, s1, s2);
else
ApplyKernel<1, 1>(dst.data(), src.data(), a1, nullptr, s1, nullptr);
}
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
InPlaceKernel(acc.data(), adds, nAdds, subs, nSubs);
}
void AddRow(Accumulator& acc, const int16_t* row) {
const int16_t* rows[1] = {row};
InPlaceKernel(acc.data(), rows, 1, nullptr, 0);
}
#else
using Ptr = int16_t* __restrict;
using CPtr = const int16_t* __restrict;
ACC_NOINLINE static void Kernel1p1m(Ptr dst, CPtr src, CPtr a, CPtr s) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a[i] - s[i]);
}
ACC_NOINLINE static void Kernel1p2m(Ptr dst, CPtr src, CPtr a, CPtr s1, CPtr s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a[i] - s1[i] - s2[i]);
}
ACC_NOINLINE static void Kernel2p2m(Ptr dst, CPtr src, CPtr a1, CPtr a2, CPtr s1, CPtr s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a1[i] + a2[i] - s1[i] - s2[i]);
}
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
if (a2)
Kernel2p2m(dst.data(), src.data(), a1, a2, s1, s2);
else if (s2)
Kernel1p2m(dst.data(), src.data(), a1, s1, s2);
else
Kernel1p1m(dst.data(), src.data(), a1, s1);
}
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
int16_t* p = acc.data();
for (int j = 0; j < nAdds; j++)
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
p[i] = static_cast<int16_t>(p[i] + adds[j][i]);
for (int j = 0; j < nSubs; j++)
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
p[i] = static_cast<int16_t>(p[i] - subs[j][i]);
}
void AddRow(Accumulator& acc, const int16_t* row) {
const int16_t* rows[1] = {row};
ApplyInPlace(acc, rows, 1, nullptr, 0);
}
#endif
}
+79 -9
View File
@@ -1,4 +1,7 @@
#pragma once
#include <array>
#include <vector>
#include <cstdint>
#include "nnue.h"
namespace ACC {
@@ -11,18 +14,85 @@ struct BucketPair {
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
struct AccumulatorPair {
alignas(32) Accumulator white;
alignas(32) Accumulator black;
bool mirroredWhite = false;
bool mirroredBlack = false;
alignas(ALIGNMENT) Accumulator white;
alignas(ALIGNMENT) Accumulator black;
// yoinked from Quinniboi - Prelude
void addSub(bool stm, int add, int addPT, int sub, int subPT, BucketPair bp);
void addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp);
void addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp);
Accumulator& get(bool perspective) { return perspective ? black : white; }
const Accumulator& get(bool perspective) const { return perspective ? black : white; }
};
enum class UpdateType : uint8_t {
None,
Refresh,
Copy,
Delta
};
struct Update {
UpdateType type = UpdateType::None;
uint8_t refreshMask = 0;
bool stm = false;
bool sub2Opp = false;
uint8_t nAdd = 0, nSub = 0;
int8_t add1 = 0, addPT1 = 0, add2 = 0, addPT2 = 0;
int8_t sub1 = 0, subPT1 = 0, sub2 = 0, subPT2 = 0;
void setAddSub(bool s, int add, int addPT, int sub, int subPT) {
type = UpdateType::Delta;
stm = s; sub2Opp = false; nAdd = 1; nSub = 1;
add1 = add; addPT1 = addPT; sub1 = sub; subPT1 = subPT;
}
void setAddSubSub(bool s, int add, int addPT, int sub1_, int subPT1_, int sub2_, int subPT2_) {
type = UpdateType::Delta;
stm = s; sub2Opp = true; nAdd = 1; nSub = 2;
add1 = add; addPT1 = addPT;
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
}
void setAddAddSubSub(bool s, int add1_, int addPT1_, int add2_, int addPT2_, int sub1_, int subPT1_, int sub2_, int subPT2_) {
type = UpdateType::Delta;
stm = s; sub2Opp = false; nAdd = 2; nSub = 2;
add1 = add1_; addPT1 = addPT1_; add2 = add2_; addPT2 = addPT2_;
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
}
void setRefresh() {
*this = Update();
type = UpdateType::Refresh;
}
};
struct FinnyEntry {
alignas(ALIGNMENT) Accumulator acc;
uint64_t bb[2][6];
};
struct FinnyTable {
FinnyEntry entries[2][2][NNUE::INPUT_BUCKETS];
void Reset();
};
struct AccStack {
std::vector<AccumulatorPair> slots;
std::vector<const AccumulatorPair*> cur;
FinnyTable finny;
explicit AccStack(size_t n) : slots(n), cur(n, nullptr) { finny.Reset(); }
AccStack(const AccStack& other) : AccStack(other.slots.size()) {}
AccStack& operator=(const AccStack&) { return *this; }
};
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored);
const int16_t* Row(int bucket, int index);
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2);
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs);
void AddRow(Accumulator& acc, const int16_t* row);
}
+148 -6
View File
@@ -1,13 +1,131 @@
#include <cstring>
#include <string_view>
#include <array>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
#include "benchmark.h"
#include "search.h"
#include "stopwatch.h"
#include "wdl.h"
using namespace SEARCH;
static std::string BenchScoreString(int score, bool &isMate) {
std::stringstream ss;
isMate = std::abs(score) + MAX_DEPTH >= MATE_SCORE;
if (isMate) {
int mateIn = (MATE_SCORE - (std::abs(score) - 1)) / 2;
mateIn = score < 0 ? mateIn * -1 : mateIn;
if (mateIn < 0) {
ss << "-M" << std::abs(mateIn);
} else {
ss << "+M" << mateIn;
}
} else {
ss << std::showpos << std::fixed << std::setprecision(2)
<< (score / 100.0) << std::noshowpos;
}
return ss.str();
}
static std::string BenchCountString(U64 count, const char* suffix) {
std::stringstream ss;
if (count >= 1000000) {
ss << std::fixed << std::setprecision(1) << (count / 1000000.0) << "M" << suffix;
} else if (count >= 1000) {
ss << std::fixed << std::setprecision(1) << (count / 1000.0) << "k" << suffix;
} else {
ss << count << suffix;
}
return ss.str();
}
static void PrintBenchHeader() {
std::cout << termcolor::bold << termcolor::color<244>;
std::cout << std::setw(4) << std::right << "#";
std::cout << std::setw(8) << std::left << " Depth";
std::cout << std::setw(9) << std::right << "Score";
std::cout << std::setw(10) << std::right << "Nodes";
std::cout << std::setw(9) << std::right << "Time";
std::cout << std::setw(9) << std::right << "NPS";
std::cout << " Best";
std::cout << termcolor::reset << std::endl;
std::cout << termcolor::color<238>;
for (int i = 0; i < 64; i++)
std::cout << '-';
std::cout << termcolor::reset << std::endl;
}
static void PrintBenchLine(int index, Board& board, SearchResults& results, SearchContext* ctx, U64 posNodes, int elapsedMs) {
if (index % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
std::cout << std::setw(4) << std::right << index;
std::stringstream depthStr;
depthStr << BENCH_DEPTH << '/' << ctx->seldepth;
std::cout << termcolor::bold << termcolor::bright_white;
std::cout << std::setw(8) << std::left << (" " + depthStr.str());
std::cout << termcolor::reset;
if (index % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
const bool isMateScore = std::abs(results.score) + MAX_DEPTH >= MATE_SCORE;
const int normalizedScore = isMateScore ? results.score : scaleEval(results.score, board);
bool isMate = false;
std::string scoreStr = BenchScoreString(normalizedScore, isMate);
if (isMate) {
int mateIn = (MATE_SCORE - (std::abs(normalizedScore) - 1)) / 2;
mateIn = normalizedScore < 0 ? mateIn * -1 : mateIn;
if (mateIn > 0) {
std::cout << termcolor::bold << termcolor::bright_green;
} else {
std::cout << termcolor::bold << termcolor::bright_red;
}
} else {
if (normalizedScore > 0) {
std::cout << termcolor::bold << termcolor::green;
} else if (normalizedScore < 0) {
std::cout << termcolor::bold << termcolor::red;
}
}
std::cout << std::setw(9) << std::right << scoreStr;
std::cout << termcolor::reset;
if (index % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
std::cout << std::setw(10) << std::right << BenchCountString(posNodes, "");
std::stringstream timeStr;
if (elapsedMs >= 1000) {
timeStr << std::fixed << std::setprecision(1) << (elapsedMs / 1000.0) << "s";
} else {
timeStr << elapsedMs << "ms";
}
std::cout << std::setw(9) << std::right << timeStr.str();
double elapsedSec = elapsedMs / 1000.0;
U64 nps = elapsedSec > 0 ? U64(posNodes / elapsedSec) : posNodes;
std::cout << std::setw(9) << std::right << BenchCountString(nps, "/s");
std::cout << " ";
std::cout << termcolor::bold << termcolor::bright_cyan;
std::cout << results.bestMove.GetMoveString();
std::cout << termcolor::reset << std::endl;
}
constexpr std::array<std::string_view, 50> fenPositions = {
"rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8",
"rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9",
@@ -68,11 +186,35 @@ void RunBenchmark() {
auto ctx = std::make_unique<SearchContext>();
ctx->TT = &BenchTT;
Stopwatch sw;
for (int i = 0; i < fenPositions.size(); i++) {
board.SetByFen(fenPositions[i]);
SearchPosition<bench>(board, SearchParams(), ctx.get());
}
PrintBenchHeader();
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/sw.GetElapsedSec()) << " nps" << std::endl;
Stopwatch sw;
for (size_t i = 0; i < fenPositions.size(); i++) {
board.SetByFen(fenPositions[i]);
U64 nodesBefore = ctx->nodes;
Stopwatch posSw;
SearchResults results = SearchPosition<bench>(board, SearchParams(), ctx.get());
int elapsedMs = posSw.GetElapsedMS();
PrintBenchLine(int(i + 1), board, results, ctx.get(), ctx->nodes - nodesBefore, elapsedMs);
}
double totalSec = sw.GetElapsedSec();
std::cout << termcolor::color<238>;
for (int i = 0; i < 64; i++)
std::cout << '-';
std::cout << termcolor::reset << std::endl;
std::cout << termcolor::bold << termcolor::bright_white;
std::cout << "Positions: " << fenPositions.size();
std::cout << " Nodes: " << BenchCountString(ctx->nodes, "");
std::cout << " Time: ";
if (totalSec >= 1.0) {
std::cout << std::fixed << std::setprecision(1) << totalSec << "s";
} else {
std::cout << int(totalSec * 1000) << "ms";
}
std::cout << " Avg: " << BenchCountString(totalSec > 0 ? U64(ctx->nodes / totalSec) : ctx->nodes, "/s");
std::cout << termcolor::reset << std::endl;
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/totalSec) << " nps" << std::endl;
}
+825 -124
View File
File diff suppressed because it is too large. Load diff
+23 -7
View File
@@ -26,7 +26,9 @@ public:
std::array<Bitboard, 2> pinned;
Bitboard checkers;
ACC::AccumulatorPair accPair;
ACC::Update accUpdate;
bool mirroredWhite = false;
bool mirroredBlack = false;
std::array<Bitboard, 6> pieceThreats;
std::array<Bitboard, 2> colorThreats;
@@ -36,7 +38,11 @@ public:
bool sideToMove = White;
uint8_t castlingRights = 0;
uint8_t castlingRights = 0;
// Squares of the castling rooks, indexed by CastleIdx(color, kingSide).
// Standard chess: h1, a1, h8, a8. Chess960 / DFRC positions override them while parsing the FEN.
std::array<int, 4> castleRook = {h1, a1, h8, a8};
int enPassantTarget = noEPTarget;
short positionIndex = 0;
@@ -48,7 +54,6 @@ public:
U64 pawnKey = 0ULL;
U64 nonPawnKey = 0ULL;
U64 majorKey = 0ULL;
U64 minorKey = 0ULL;
std::array<Bitboard, 4> checkZones;
@@ -57,14 +62,18 @@ public:
std::string GetFen();
void PrintBoard();
void PrintNNUE();
void PrintNNUE(bool full = false);
void AddMove(Move move);
void ResetMoves();
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);
@@ -90,5 +99,12 @@ public:
bool GivesDirectCheck(Move &move);
bool IsLegal(Move &move);
bool IsPseudoLegal(Move &move);
};
bool IsPseudoLegal(Move &move);
// Index of a castling right, same bit order as CASTLING_RIGHTS (white K, white Q, black K, black Q)
static constexpr int CastleIdx(bool color, bool kingSide) { return color * 2 + (kingSide ? 0 : 1); }
bool CanCastle(bool us, bool kingSide);
void AddCastlingRight(char symbol);
char CastlingSymbol(uint8_t right, char standardSymbol) const;
};
+41 -131
View File
@@ -13,8 +13,10 @@
#include <csignal>
#include <cstdlib>
#include <cerrno>
#include <vector>
#include "datagen.h"
#include "datagenui.h"
#include "movegen.h"
#include "search.h"
#include "utils.h"
@@ -277,7 +279,8 @@ static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) {
}
}
static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& basePath, int& fileCounter) {
static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& basePath, int& fileCounter,
std::atomic<int>& files) {
if (gamesBuffer.empty()) return;
int32_t zeroes = 0;
@@ -330,6 +333,7 @@ static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& baseP
return;
}
files.fetch_add(1, std::memory_order_relaxed);
fileCounter++;
}
@@ -395,7 +399,7 @@ static std::string MergeThreadFiles() {
return finalFileName;
}
static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& stopFlag) {
static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag) {
std::vector<Game> gamesBuffer;
gamesBuffer.reserve(GAME_BUFFER);
@@ -416,9 +420,15 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
PlayRandMoves(board, ctx.get());
if (IsGameOver(board, ctx.get())) continue;
ctx->nodes = 0;
const int startingScore = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get()).score;
if (std::abs(startingScore) >= evenityMargin) continue;
stats.nodes.fetch_add(ctx->nodes, std::memory_order_relaxed);
if (std::abs(startingScore) >= evenityMargin) {
stats.rejected.fetch_add(1, std::memory_order_relaxed);
continue;
}
ctx->nodes = 0;
@@ -433,7 +443,9 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
while (!IsGameOver(board, ctx.get())) {
if (g_shutdownRequested) break;
ctx->nodes = 0;
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get());
stats.nodes.fetch_add(ctx->nodes, std::memory_order_relaxed);
if (!results.bestMove) break;
safeResults = results;
@@ -444,7 +456,7 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
board.MakeMove(results.bestMove);
ctx->positionHistory[board.positionIndex] = board.hashKey;
positions++;
stats.positions.fetch_add(1, std::memory_order_relaxed);
MOVEGEN::GenerateMoves<All>(board, true);
}
@@ -455,21 +467,22 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
game.format.packFrom(startpos, staticEval, wdl);
gamesBuffer.emplace_back(game);
stats.games.fetch_add(1, std::memory_order_relaxed);
if (gamesBuffer.size() >= GAME_BUFFER) {
WriteToFile(gamesBuffer, basePath, fileCounter);
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
gamesBuffer.clear();
}
}
} catch (...) {
if (!gamesBuffer.empty()) {
WriteToFile(gamesBuffer, basePath, fileCounter);
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
}
throw;
}
if (!gamesBuffer.empty()) {
WriteToFile(gamesBuffer, basePath, fileCounter);
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
gamesBuffer.clear();
}
@@ -482,23 +495,23 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
struct WinThreadArgs {
int id;
std::atomic<int>* positions;
DatagenStats* stats;
std::atomic<bool>* stopFlag;
};
static unsigned __stdcall WinThreadEntry(void* p) {
std::unique_ptr<WinThreadArgs> args(static_cast<WinThreadArgs*>(p));
PlayGames(args->id, *args->positions, *args->stopFlag);
PlayGames(args->id, *args->stats, *args->stopFlag);
_endthreadex(0);
return 0;
}
static bool CreateWorkerThread(int id,
std::atomic<int>& positions,
DatagenStats& stats,
std::atomic<bool>& stopFlag,
std::vector<HANDLE>& threads,
size_t stackSizeBytes) {
auto* args = new WinThreadArgs{ id, &positions, &stopFlag };
auto* args = new WinThreadArgs{ id, &stats, &stopFlag };
unsigned tid = 0;
HANDLE h = reinterpret_cast<HANDLE>(
@@ -535,7 +548,7 @@ static void JoinWorkerThreads(std::vector<HANDLE>& threads) {
#else
static void* ThreadFunc(void* arg) {
auto* tup = static_cast<std::tuple<int, std::atomic<int>*, std::atomic<bool>*>*>(arg);
auto* tup = static_cast<std::tuple<int, DatagenStats*, std::atomic<bool>*>*>(arg);
PlayGames(std::get<0>(*tup), *std::get<1>(*tup), *std::get<2>(*tup));
delete tup;
return nullptr;
@@ -554,7 +567,7 @@ void Run(int targetPositions, int threads) {
HideCursor();
#endif
std::atomic<int> positions = 0;
DatagenStats stats;
std::atomic<bool> stopFlag = false;
#ifdef _WIN32
@@ -564,7 +577,7 @@ void Run(int targetPositions, int threads) {
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
for (int i = 0; i < threads - 1; ++i) {
CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes);
CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes);
}
#else
std::vector<pthread_t> workerThreads;
@@ -574,7 +587,7 @@ void Run(int targetPositions, int threads) {
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
auto* args = new std::tuple<int, DatagenStats*, std::atomic<bool>*>(i, &stats, &stopFlag);
pthread_t thread;
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
@@ -589,12 +602,13 @@ void Run(int targetPositions, int threads) {
#endif
Stopwatch sw;
while (positions < targetPositions && !g_shutdownRequested) {
PrintProgress(positions, targetPositions, sw, threads);
while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) {
PrintProgress(stats, targetPositions, sw, threads);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(positions, targetPositions, sw, threads);
PrintProgress(stats, targetPositions, sw, threads);
PrintSummary(stats, targetPositions, sw, threads);
stopFlag = true;
@@ -676,7 +690,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
HideCursor();
#endif
std::atomic<int> positions = 0;
DatagenStats stats;
std::atomic<bool> stopFlag = false;
#ifdef _WIN32
@@ -686,7 +700,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
for (int i = 0; i < threads - 1; ++i) {
CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes);
CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes);
}
#else
std::vector<pthread_t> workerThreads;
@@ -696,7 +710,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
auto* args = new std::tuple<int, DatagenStats*, std::atomic<bool>*>(i, &stats, &stopFlag);
pthread_t thread;
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
@@ -711,12 +725,13 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
#endif
Stopwatch sw;
while (positions < targetPositions && !g_shutdownRequested) {
PrintProgress(positions, targetPositions, sw, threads);
while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) {
PrintProgress(stats, targetPositions, sw, threads);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(positions, targetPositions, sw, threads);
PrintProgress(stats, targetPositions, sw, threads);
PrintSummary(stats, targetPositions, sw, threads);
stopFlag = true;
@@ -750,7 +765,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
std::cout << "Uploading file to server..." << std::endl;
std::string uploadUrl = SERVER_URL + "/api/upload/" + sessionId;
if (UploadFile(uploadUrl, mergedFile, username, positions.load())) {
if (UploadFile(uploadUrl, mergedFile, username, stats.positions.load())) {
std::cout << "Upload successful!" << std::endl;
std::error_code ec;
@@ -772,109 +787,4 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
std::cout << "\nOnline mode shutdown complete." << std::endl;
}
void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) {
const std::string COLOR_RESET = "\033[0m";
const std::string COLOR_TITLE = "\033[1;36m";
const std::string COLOR_SECTION = "\033[1;33m";
const std::string COLOR_VALUE = "\033[1;32m";
const std::string COLOR_BAR = "\033[1;34m";
static double lastPositions = 0;
static double lastElapsed = 0;
static double refreshInterval = 1.0;
double elapsed = stopwatch.GetElapsedSec();
double positionsPerSec = 0;
if (elapsed - lastElapsed >= refreshInterval) {
positionsPerSec = (positions - lastPositions) / (elapsed - lastElapsed);
lastPositions = positions;
lastElapsed = elapsed;
}
std::cout << "\033[H";
int width = 60;
std::string title = "Eleanor - Datagen";
int titlePadding = (width - static_cast<int>(title.length())) / 2;
std::cout << COLOR_TITLE << std::setw(titlePadding + static_cast<int>(title.length())) << title << COLOR_RESET << std::endl;
std::cout << std::string(width, '=') << std::endl;
std::cout << std::endl;
std::cout << std::fixed << std::setprecision(0);
std::ostringstream datagenTextStream;
datagenTextStream << std::fixed << std::setprecision(2)
<< "Positions processed: " << positions / 1000.0 << "K | Target: " << targetPositions / 1000.0 << "K";
std::string datagenText = datagenTextStream.str();
int datagenPadding = (width - static_cast<int>(datagenText.length())) / 2;
std::cout << COLOR_SECTION << std::setw(datagenPadding + static_cast<int>(datagenText.length())) << datagenText << COLOR_RESET << std::endl;
std::cout << std::endl;
std::string elapsedText = "Elapsed Time: " + std::to_string(static_cast<int>(round(elapsed))) + " sec";
int elapsedPadding = (width - static_cast<int>(elapsedText.length())) / 2;
std::cout << COLOR_SECTION << std::setw(elapsedPadding + static_cast<int>(elapsedText.length())) << elapsedText << COLOR_RESET << std::endl;
std::string positionsPerSecText = "Positions/sec: " + std::to_string(static_cast<int>(round(positionsPerSec)));
int positionsPerSecPadding = (width - static_cast<int>(positionsPerSecText.length())) / 2;
std::cout << COLOR_VALUE << std::setw(positionsPerSecPadding + static_cast<int>(positionsPerSecText.length())) << positionsPerSecText << COLOR_RESET << std::endl;
std::cout << std::endl;
std::string threadsText = "Threads: " + std::to_string(static_cast<int>(threads));
int threadsTextPadding = (width - static_cast<int>(threadsText.length())) / 2;
std::cout << COLOR_SECTION << std::setw(threadsTextPadding + static_cast<int>(threadsText.length())) << threadsText << COLOR_RESET << std::endl;
std::cout << std::endl;
double remainingTime = 0.0;
if (positions > 0 && elapsed > 0.0) {
double pps = positions / elapsed;
remainingTime = (targetPositions - positions) / pps;
}
remainingTime = (std::max)(0.0, remainingTime);
int remainingHours = static_cast<int>(remainingTime) / 3600;
int remainingMinutes = (static_cast<int>(remainingTime) % 3600) / 60;
int remainingSeconds = static_cast<int>(remainingTime) % 60;
std::ostringstream remainingTimeStream;
remainingTimeStream << "Estimated Time Left: "
<< std::setfill('0') << std::setw(2) << remainingHours << "h "
<< std::setw(2) << remainingMinutes << "m "
<< std::setw(2) << remainingSeconds << "s";
std::string remainingTimeText = remainingTimeStream.str();
int remainingPadding = (width - static_cast<int>(remainingTimeText.length())) / 2;
std::cout << COLOR_SECTION
<< std::setw(remainingPadding + static_cast<int>(remainingTimeText.length()))
<< remainingTimeText << COLOR_RESET << std::endl;
std::cout << std::endl;
int barWidth = 50;
double progress = (double)positions / targetPositions;
int pos = (int)(progress * barWidth);
std::string progressBar = "[";
for (int i = 0; i < barWidth; ++i) {
if (i < pos) progressBar += "=";
else if (i == pos) progressBar += ">";
else progressBar += " ";
}
progressBar += "] " + std::to_string(static_cast<int>(round(progress * 100.0))) + " %";
int progressPadding = (width - static_cast<int>(progressBar.length())) / 2;
std::cout << COLOR_BAR << std::setw(progressPadding + static_cast<int>(progressBar.length()))
<< progressBar << COLOR_RESET << std::endl;
std::cout << std::endl;
}
} // namespace DATAGEN
} // namespace DATAGEN
+10 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "board.h"
#include "utils.h"
#include <atomic>
#include <fstream>
#include "stopwatch.h"
@@ -11,6 +12,15 @@ constexpr int SOFT_NODES = 5000;
constexpr int HARD_NODES = 100000;
constexpr int RAND_MOVES = 8;
// Live counters shared between the worker threads and the frontend.
struct DatagenStats {
std::atomic<int> positions{0};
std::atomic<int> games{0};
std::atomic<int> files{0};
std::atomic<long long> nodes{0};
std::atomic<int> rejected{0};
};
struct MarlinFormat {
uint64_t occupancy; // 8 bytes: Bitboard representing all occupied squares (includes all pieces)
std::array<uint8_t, 16> pieces; // 16 bytes: 64 squares stored in 4-bit format (2 squares per byte)
@@ -62,6 +72,4 @@ struct Game {
void Run(int targetPositions, int threads);
void RunOnline(const std::string& username, int targetPositions, int threads);
void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads);
}
+639
View File
@@ -0,0 +1,639 @@
#include <algorithm>
#include <cctype>
#include <clocale>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <string>
#include <vector>
#include "datagenui.h"
#include "datagen.h"
#include "stopwatch.h"
// OS-dependent terminal detection includes
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#else
#include <unistd.h>
#include <langinfo.h>
#include <sys/ioctl.h>
#endif
namespace DATAGEN {
namespace {
constexpr int kMinWidth = 64;
constexpr int kMaxWidth = 96;
constexpr std::size_t kMaxSamples = 720;
bool Interactive() {
static const bool value = [] {
#ifdef _WIN32
return _isatty(_fileno(stdout)) != 0;
#else
return isatty(STDOUT_FILENO) != 0;
#endif
}();
return value;
}
bool UseColor() {
static const bool value = [] {
#ifdef _WIN32
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
if (out != INVALID_HANDLE_VALUE && GetConsoleMode(out, &mode))
SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
return Interactive() && std::getenv("NO_COLOR") == nullptr;
#else
return Interactive() && std::getenv("NO_COLOR") == nullptr;
#endif
}();
return value;
}
bool UseUnicode() {
static const bool value = [] {
std::setlocale(LC_ALL, "");
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
return true;
#else
const char* codeset = nl_langinfo(CODESET);
return codeset != nullptr
&& (std::strstr(codeset, "UTF-8") != nullptr || std::strstr(codeset, "UTF8") != nullptr);
#endif
}();
return value;
}
int DetectWidth() {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info))
return info.srWindow.Right - info.srWindow.Left + 1;
#else
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0)
return ws.ws_col;
#endif
return 80;
}
std::string Sgr(const char* code) {
return UseColor() ? "\033[" + std::string(code) + "m" : std::string();
}
std::string Reset() { return Sgr("0"); }
std::string Fg(int r, int g, int b) {
if (!UseColor()) return "";
return "\033[38;2;" + std::to_string(r) + ";" + std::to_string(g) + ";" + std::to_string(b) + "m";
}
// Cyan -> spring green across the progress bar.
std::string GradientAt(double t) {
t = std::clamp(t, 0.0, 1.0);
return Fg(static_cast<int>(std::lround(0 + t * 80)),
static_cast<int>(std::lround(180 + t * 75)),
static_cast<int>(std::lround(255 - t * 115)));
}
struct Glyphs {
const char* tl;
const char* tr;
const char* bl;
const char* br;
const char* h;
const char* v;
const char* full;
const char* empty;
const char* dot;
};
Glyphs PickGlyphs() {
if (UseUnicode()) {
return {"\u256D", "\u256E", "\u2570", "\u256F", "\u2500",
"\u2502", "\u2588", "\u2591", "\u00B7"};
}
return {"+", "+", "+", "+", "-", "|", "#", ".", "."};
}
std::vector<std::string> SparkLevels() {
if (UseUnicode()) {
return {"\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"};
}
return {"_", ".", "-", "=", "+", "*", "#", "%", "@"};
}
// Width in terminal cells, ignoring ANSI escapes and counting UTF-8 sequences once.
int VisibleWidth(const std::string& s) {
int len = 0;
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == '\033') {
std::size_t j = i + 1;
if (j < s.size() && s[j] == '[') {
++j;
while (j < s.size()
&& (std::isdigit(static_cast<unsigned char>(s[j])) || s[j] == ';')) {
++j;
}
if (j < s.size()) ++j;
i = j - 1;
continue;
}
}
if ((static_cast<unsigned char>(s[i]) & 0xC0) != 0x80) ++len;
}
return len;
}
std::string PadRight(const std::string& s, int width) {
const int pad = width - VisibleWidth(s);
return pad > 0 ? s + std::string(pad, ' ') : s;
}
// Hard guarantee that nothing ever escapes the frame, whatever the contents.
std::string Truncate(const std::string& s, int maxWidth) {
if (VisibleWidth(s) <= maxWidth) return s;
std::string out;
int len = 0;
bool colored = false;
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == '\033') {
std::size_t j = i + 1;
if (j < s.size() && s[j] == '[') {
++j;
while (j < s.size()
&& (std::isdigit(static_cast<unsigned char>(s[j])) || s[j] == ';')) {
++j;
}
if (j < s.size()) ++j;
out.append(s, i, j - i);
colored = true;
i = j - 1;
continue;
}
}
if ((static_cast<unsigned char>(s[i]) & 0xC0) == 0x80) {
out += s[i];
continue;
}
if (len >= maxWidth) break;
out += s[i];
++len;
}
if (colored) out += Reset();
return out;
}
std::string Rule(const char* left, const char* right, const Glyphs& g, int inner,
const std::string& color) {
std::string s = color + left;
for (int i = 0; i < inner; ++i) s += g.h;
s += right;
s += Reset();
return s;
}
std::string Row(const std::string& content, const Glyphs& g, int inner, const std::string& border) {
return border + g.v + Reset() + PadRight(Truncate(content, inner), inner) + border + g.v + Reset();
}
std::string SplitRow(const std::string& left, const std::string& right, const Glyphs& g, int inner,
const std::string& border) {
const int gap = inner - VisibleWidth(left) - VisibleWidth(right);
return Row(left + std::string(gap > 0 ? gap : 1, ' ') + right, g, inner, border);
}
std::string DotLeaders(const std::string& key, const std::string& value, int width,
const std::string& keyColor, const std::string& valueColor,
const Glyphs& g) {
const int dots = width - VisibleWidth(key) - VisibleWidth(value) - 2;
std::string s = keyColor + key + Reset();
if (dots > 0) {
s += ' ';
for (int i = 0; i < dots; ++i) s += g.dot;
}
return s + ' ' + valueColor + value + Reset();
}
std::string FormatCount(long long value) {
char buf[64];
const double d = static_cast<double>(value);
const double a = std::abs(d);
if (a >= 1e9) std::snprintf(buf, sizeof(buf), "%.2fB", d / 1e9);
else if (a >= 1e6) std::snprintf(buf, sizeof(buf), "%.2fM", d / 1e6);
else if (a >= 1e3) std::snprintf(buf, sizeof(buf), "%.1fK", d / 1e3);
else std::snprintf(buf, sizeof(buf), "%lld", value);
return buf;
}
std::string FormatThousands(long long value) {
std::string digits = std::to_string(value);
for (int i = static_cast<int>(digits.size()) - 3; i > 0; i -= 3)
digits.insert(i, ",");
return digits;
}
std::string FormatDuration(double seconds) {
if (!std::isfinite(seconds) || seconds < 0) return "--";
const long long total = static_cast<long long>(seconds);
const long long h = total / 3600;
const long long m = (total % 3600) / 60;
const long long s = total % 60;
char buf[64];
if (h > 0) std::snprintf(buf, sizeof(buf), "%lldh %02lldm", h, m);
else if (m > 0) std::snprintf(buf, sizeof(buf), "%lldm %02llds", m, s);
else std::snprintf(buf, sizeof(buf), "%llds", s);
return buf;
}
std::string BuildSparkline(const std::deque<double>& samples, int width,
const std::vector<std::string>& levels, const std::string& color) {
if (width <= 0 || samples.empty()) return "";
const int count = static_cast<int>(samples.size());
const int take = std::min(count, width);
const int start = count - take;
double lo = samples[start];
double hi = samples[start];
for (int i = start; i < count; ++i) {
lo = std::min(lo, samples[i]);
hi = std::max(hi, samples[i]);
}
const double range = hi - lo;
const int last = static_cast<int>(levels.size()) - 1;
std::string bar;
// Pad the left side with blanks so "no data yet" is not confused with a low sample.
for (int i = 0; i < width - take; ++i) bar += ' ';
for (int i = start; i < count; ++i) {
const int idx = range > 1e-9
? static_cast<int>(std::lround((samples[i] - lo) / range * last))
: last;
bar += levels[std::clamp(idx, 0, last)];
}
return color + bar + Reset();
}
struct RateTracker {
std::deque<double> samples;
double lastTime = 0.0;
double lastCount = 0.0;
double current = 0.0;
double smoothed = 0.0;
double peak = 0.0;
void sample(double count, double elapsed) {
if (elapsed - lastTime < 1.0) return;
const double window = elapsed - lastTime;
const double instant = window > 0 ? (count - lastCount) / window : 0.0;
lastTime = elapsed;
lastCount = count;
samples.push_back(instant);
if (samples.size() > kMaxSamples) samples.pop_front();
current = instant;
smoothed = smoothed == 0.0 ? instant : smoothed * 0.65 + instant * 0.35;
peak = std::max(peak, instant);
}
void reset() {
samples.clear();
lastTime = lastCount = current = smoothed = peak = 0.0;
}
};
RateTracker& PositionsRate() {
static RateTracker tracker;
return tracker;
}
RateTracker& NodesRate() {
static RateTracker tracker;
return tracker;
}
// Shared header row: "ELEANOR - DATAGEN" on the left, a status pill on the right.
std::string HeaderRow(const Glyphs& g, int inner, const std::string& border,
const std::string& status, const std::string& statusColor) {
const std::string bullet = UseUnicode() ? "\u25CF" : "*";
const std::string left = Sgr("1") + Fg(190, 220, 255) + "ELEANOR"
+ Fg(90, 100, 120) + " " + g.dot + " " + Sgr("0") + Fg(140, 150, 170) + "DATAGEN";
const std::string pill = statusColor + bullet + " " + Sgr("1") + status + Reset();
return SplitRow(" " + left, pill + " ", g, inner, border);
}
struct Snapshot {
long long positions = 0;
long long games = 0;
long long files = 0;
long long nodes = 0;
long long rejected = 0;
double elapsed = 0;
double posSpeed = 0;
double posPeak = 0;
double nodeSpeed = 0;
};
Snapshot TakeSnapshot(const DatagenStats& stats, Stopwatch& stopwatch) {
Snapshot snap;
snap.positions = stats.positions.load(std::memory_order_relaxed);
snap.games = stats.games.load(std::memory_order_relaxed);
snap.files = stats.files.load(std::memory_order_relaxed);
snap.nodes = stats.nodes.load(std::memory_order_relaxed);
snap.rejected = stats.rejected.load(std::memory_order_relaxed);
snap.elapsed = stopwatch.GetElapsedSec();
PositionsRate().sample(static_cast<double>(snap.positions), snap.elapsed);
NodesRate().sample(static_cast<double>(snap.nodes), snap.elapsed);
snap.posSpeed = PositionsRate().smoothed;
snap.posPeak = PositionsRate().peak;
snap.nodeSpeed = NodesRate().smoothed;
return snap;
}
std::string FormatSpeed(double perSecond) {
char buf[64];
if (perSecond >= 1e9) std::snprintf(buf, sizeof(buf), "%.2fB/s", perSecond / 1e9);
else if (perSecond >= 1e6) std::snprintf(buf, sizeof(buf), "%.2fM/s", perSecond / 1e6);
else if (perSecond >= 1e3) std::snprintf(buf, sizeof(buf), "%.1fK/s", perSecond / 1e3);
else std::snprintf(buf, sizeof(buf), "%.0f/s", perSecond);
return buf;
}
void PrintPlainLine(const Snapshot& snap, int targetPositions, int threads) {
const double progress = targetPositions > 0
? 100.0 * snap.positions / targetPositions : 0.0;
const double remaining = snap.posSpeed > 0
? (targetPositions - snap.positions) / snap.posSpeed : 0.0;
std::printf("[datagen] %lld/%d (%.1f%%) %s nodes %s elapsed %s eta %s games %lld files %lld threads %d\n",
snap.positions, targetPositions, progress,
FormatSpeed(snap.posSpeed).c_str(), FormatCount(snap.nodes).c_str(),
FormatDuration(snap.elapsed).c_str(), FormatDuration(remaining).c_str(),
snap.games, snap.files, threads);
std::fflush(stdout);
}
std::vector<std::string> BuildFrame(const Snapshot& snap, int targetPositions, int threads,
bool finished) {
const Glyphs g = PickGlyphs();
const auto levels = SparkLevels();
const int width = std::clamp(DetectWidth(), kMinWidth, kMaxWidth);
const int inner = width - 2;
const std::string accent = Fg(120, 190, 255);
const std::string border = Fg(70, 80, 100);
const std::string label = Fg(130, 140, 160);
const std::string value = Fg(235, 240, 250);
const std::string heading = Sgr("1") + Fg(150, 200, 255);
const std::string good = Fg(120, 235, 160);
const std::string warn = Fg(245, 200, 110);
const double progress = targetPositions > 0
? std::clamp(static_cast<double>(snap.positions) / targetPositions, 0.0, 1.0)
: 0.0;
const double remaining = snap.posSpeed > 0
? std::max(0.0, (targetPositions - snap.positions) / snap.posSpeed) : 0.0;
const double avgGame = snap.games > 0
? static_cast<double>(snap.positions) / snap.games : 0.0;
const long long attempted = snap.games + snap.rejected;
const double acceptRate = attempted > 0
? 100.0 * snap.games / attempted : 0.0;
std::vector<std::string> out;
out.push_back(Rule(g.tl, g.tr, g, inner, border));
out.push_back(HeaderRow(g, inner, border, finished ? "STOPPED" : "GENERATING",
finished ? warn : good));
out.push_back(Rule(g.v, g.v, g, inner, border));
// Headline counters.
{
char pct[32];
std::snprintf(pct, sizeof(pct), "%.1f%%", progress * 100.0);
const std::string left = " " + Sgr("1") + Fg(225, 235, 250) + FormatCount(snap.positions)
+ Fg(110, 120, 140) + " / " + FormatCount(targetPositions)
+ Fg(110, 120, 140) + " positions";
const std::string right = Sgr("1") + GradientAt(progress) + pct + Reset();
out.push_back(SplitRow(left, right + " ", g, inner, border));
const int barWidth = inner - 4;
const int filled = static_cast<int>(std::lround(progress * barWidth));
std::string bar;
for (int i = 0; i < barWidth; ++i) {
if (i < filled) bar += GradientAt(barWidth > 1 ? static_cast<double>(i) / (barWidth - 1) : 0.0) + g.full;
else bar += Fg(45, 50, 62) + g.empty;
}
bar += Reset();
out.push_back(Row(" " + bar, g, inner, border));
}
out.push_back(Row("", g, inner, border));
out.push_back(Rule(g.v, g.v, g, inner, border));
// Two-column statistics.
const int half = (inner - 3) / 2;
const int rightStart = half + 3;
const int rightWidth = inner - rightStart - 2;
auto statRow = [&](const char* lk, const std::string& lv, const char* rk, const std::string& rv) {
const std::string l = DotLeaders(lk, lv, half, label, value, g);
const std::string r = DotLeaders(rk, rv, rightWidth, label, value, g);
out.push_back(Row(" " + l + " " + r, g, inner, border));
};
out.push_back(Row(" " + heading + "THROUGHPUT" + Reset() + " "
+ heading + "SESSION" + Reset(), g, inner, border));
out.push_back(Row("", g, inner, border));
statRow("speed", FormatSpeed(snap.posSpeed), "elapsed", FormatDuration(snap.elapsed));
statRow("peak", FormatSpeed(snap.posPeak), "remaining", FormatDuration(remaining));
statRow("nodes", FormatCount(snap.nodes), "threads", std::to_string(threads));
statRow("node speed", FormatSpeed(snap.nodeSpeed), "progress",
[&] { char b[32]; std::snprintf(b, sizeof(b), "%.1f%%", progress * 100.0); return std::string(b); }());
out.push_back(Row("", g, inner, border));
statRow("games", FormatThousands(snap.games), "files", FormatThousands(snap.files));
statRow("rejected", FormatThousands(snap.rejected), "avg game",
[&] { char b[32]; std::snprintf(b, sizeof(b), "%.1f pos", avgGame); return std::string(b); }());
statRow("accept", [&] { char b[32]; std::snprintf(b, sizeof(b), "%.1f%%", acceptRate); return std::string(b); }(),
"nodes/pos",
[&] { char b[32]; std::snprintf(b, sizeof(b), "%.0f",
snap.positions > 0 ? static_cast<double>(snap.nodes) / snap.positions : 0.0); return std::string(b); }());
// Throughput history.
const int sparkWidth = inner - 4;
out.push_back(Row("", g, inner, border));
out.push_back(Row(" " + label + "throughput history" + Reset(), g, inner, border));
out.push_back(Row(" " + BuildSparkline(PositionsRate().samples, sparkWidth, levels, accent),
g, inner, border));
out.push_back(Rule(g.v, g.v, g, inner, border));
out.push_back(Row(" " + label
+ (finished ? "run finished " + std::string(g.dot) + " data written to data/*.binpack"
: "Ctrl+C to stop safely " + std::string(g.dot) + " data is flushed on exit")
+ Reset(),
g, inner, border));
out.push_back(Rule(g.bl, g.br, g, inner, border));
return out;
}
void DrawFrame(const std::vector<std::string>& frame) {
std::string buffer;
buffer.reserve(frame.size() * 96);
buffer += "\033[H";
for (const std::string& line : frame) {
buffer += line;
buffer += '\n';
}
buffer += "\033[J";
std::fwrite(buffer.data(), 1, buffer.size(), stdout);
std::fflush(stdout);
}
void ClearFrame() {
if (!Interactive()) return;
std::fputs("\033[H\033[J", stdout);
std::fflush(stdout);
}
} // namespace
void PrintProgress(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads) {
const Snapshot snap = TakeSnapshot(stats, stopwatch);
if (!Interactive()) {
PrintPlainLine(snap, targetPositions, threads);
return;
}
DrawFrame(BuildFrame(snap, targetPositions, threads, false));
}
void PrintSummary(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads) {
const Snapshot snap = TakeSnapshot(stats, stopwatch);
if (!Interactive()) {
PrintPlainLine(snap, targetPositions, threads);
return;
}
ClearFrame();
DrawFrame(BuildFrame(snap, targetPositions, threads, true));
}
void PrintUsage() {
const Glyphs g = PickGlyphs();
// Help text is denser than the dashboard, so allow a slightly wider frame.
const int width = std::clamp(DetectWidth(), kMinWidth, 100);
const int inner = width - 2;
const std::string accent = Fg(120, 190, 255);
const std::string border = Fg(70, 80, 100);
const std::string label = Fg(130, 140, 160);
const std::string value = Fg(235, 240, 250);
const std::string heading = Sgr("1") + Fg(150, 200, 255);
std::vector<std::string> out;
out.push_back(Rule(g.tl, g.tr, g, inner, border));
out.push_back(HeaderRow(g, inner, border, "HELP", accent));
out.push_back(Rule(g.v, g.v, g, inner, border));
auto blank = [&]() { out.push_back(Row("", g, inner, border)); };
auto section = [&](const char* name) {
blank();
out.push_back(Row(" " + heading + name + Reset(), g, inner, border));
};
auto line = [&](const std::string& content) {
out.push_back(Row(" " + content, g, inner, border));
};
// A two-column row: fixed-width term on the left, description on the right.
auto term = [&](const std::string& name, const std::string& desc, int nameWidth = 11) {
out.push_back(Row(" " + Sgr("1") + accent + PadRight(name + Reset(), nameWidth) + desc,
g, inner, border));
};
auto note = [&](const std::string& text) {
line(label + g.dot + " " + text + Reset());
};
auto usage = [&](const std::string& args, const std::string& comment) {
const std::string padded = PadRight(value + args + Reset(), 28);
line(comment.empty() ? padded : padded + label + comment + Reset());
};
section("SYNTAX");
usage("Eleanor datagen [positions] [threads] [username]", "");
usage("Eleanor datagen --help", "");
section("ARGUMENTS");
term("positions", "Target size in thousands, multiplied by 1000.", 12);
term("", label + "Default 1 = 1,000 positions.");
term("threads", "Number of worker threads.", 12);
term("", label + "No default, minimum 2.");
term("username", "Enables online mode: registers a session", 12);
term("", "on the coordination server and uploads the data.");
section("EXAMPLES");
usage("Eleanor datagen 1000 22", "1,000,000 positions on 22 threads");
usage("Eleanor datagen 10 8", "10,000 positions on 8 threads");
usage("Eleanor datagen 1000 22 me", "1,000,000 positions, online mode");
section("NOTES");
note("Data is written to data/datagen_<timestamp>.binpack");
note("Press Ctrl+C to stop safely; partial data is flushed and merged.");
note("Each game starts from the initial position after 8-9 random plies.");
note("Openings scored beyond +/-200cp are discarded for evenness.");
note("A threads value of N starts N-1 generators, minimum 2.");
blank();
out.push_back(Rule(g.bl, g.br, g, inner, border));
for (const std::string& l : out) {
std::fputs((l + "\n").c_str(), stdout);
}
std::fflush(stdout);
}
} // namespace DATAGEN
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include "datagen.h"
#include "stopwatch.h"
namespace DATAGEN {
void PrintProgress(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads);
void PrintSummary(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads);
void PrintUsage();
} // namespace DATAGEN
+312 -48
View File
@@ -5,9 +5,14 @@
#include "benchmark.h"
#include "search.h"
#include "datagen.h"
#include "datagenui.h"
#include "nnue.h"
#include "tests.h"
#include <iostream>
#include <string>
#include <vector>
#ifndef EVALFILE
#define EVALFILE "./nnue.bin"
#endif
@@ -29,60 +34,319 @@
INCBIN(EVAL, EVALFILE);
#endif
int main(int argc, char* argv[]) {
auto loadDefaultNet = [&]([[maybe_unused]] bool warnMSVC = false) {
#if defined(_MSC_VER) && !defined(__clang__)
NNUE::net.Load(EVALFILE);
if (warnMSVC)
cerr << "WARNING: This file was compiled with MSVC, this means that an nnue was NOT embedded into the exe." << endl;
#else
NNUE::net = *reinterpret_cast<const NNUE::Network*>(gEVALData);
#endif
};
loadDefaultNet(true);
// Strict integer parsing: returns 0 when the text is not a positive whole number,
// so bad CLI input reports a usage error instead of throwing std::invalid_argument.
static int ParsePositiveInt(const char* text) {
if (text == nullptr || *text == '\0') return 0;
for (const char* c = text; *c != '\0'; ++c) {
if (*c < '0' || *c > '9') return 0;
}
MOVEGEN::initLeaperAttacks();
MOVEGEN::initSliderAttacks();
try {
const long long value = std::stoll(text);
if (value <= 0 || value > 2147483647LL) return 0;
return static_cast<int>(value);
} catch (...) {
return 0;
}
}
static void ArgError(const char* value, const char* name) {
std::cerr << "error: invalid " << name << " value '" << value
<< "'. Expected a positive whole number.\n"
<< "\nRun 'Eleanor datagen --help' for usage.\n";
}
static void PrintUsage() {
std::cout << "Eleanor " << EleanorVersion << " - chess engine" << std::endl;
std::cout << std::endl;
std::cout << "Usage:" << std::endl;
std::cout << " Eleanor" << std::endl;
std::cout << " Eleanor bench" << std::endl;
std::cout << " Eleanor datagen [positions] [threads] [username]" << std::endl;
std::cout << " Eleanor datagen [options]" << std::endl;
std::cout << " Eleanor --help" << std::endl;
std::cout << " Eleanor --version" << std::endl;
std::cout << std::endl;
std::cout << "Commands:" << std::endl;
std::cout << " bench Run benchmark" << std::endl;
std::cout << " datagen Generate training data" << std::endl;
std::cout << " help Show this help" << std::endl;
std::cout << " version Show version" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -h, --help Show this help" << std::endl;
std::cout << " -v, --version Show version" << std::endl;
std::cout << " --bench Same as bench" << std::endl;
std::cout << " --datagen Same as datagen" << std::endl;
std::cout << " -p, --positions N Target size in thousands for datagen" << std::endl;
std::cout << " -t, --threads N Threads for datagen or UCI mode" << std::endl;
std::cout << " -u, --username NAME Online mode username for datagen" << std::endl;
std::cout << " --hash N Hash size in MB for UCI mode" << std::endl;
std::cout << " --evalfile PATH NNUE file to load for UCI mode" << std::endl;
std::cout << std::endl;
std::cout << "Datagen examples:" << std::endl;
std::cout << " Eleanor datagen 1000 22" << std::endl;
std::cout << " Eleanor datagen --positions 1000 --threads 22" << std::endl;
std::cout << " Eleanor datagen 1000 22 myuser" << std::endl;
std::cout << std::endl;
std::cout << "UCI go:" << std::endl;
std::cout << " go depth N" << std::endl;
std::cout << " go mate N" << std::endl;
std::cout << " go nodes N" << std::endl;
std::cout << " go movetime N" << std::endl;
std::cout << " go infinite" << std::endl;
std::cout << " go searchmoves MOVE ..." << std::endl;
std::cout << " go wtime N btime N winc N binc N movestogo N" << std::endl;
}
static void PrintVersion() {
std::cout << "Eleanor " << EleanorVersion << std::endl;
}
int main(int argc, char* argv[]) {
auto loadDefaultNet = [&]([[maybe_unused]] bool warnMSVC = false) {
#if defined(_MSC_VER) && !defined(__clang__)
NNUE::net.Load(EVALFILE);
if (warnMSVC)
cerr << "WARNING: This file was compiled with MSVC, this means that an nnue was NOT embedded into the exe." << endl;
#else
NNUE::net = *reinterpret_cast<const NNUE::Network*>(gEVALData);
#endif
};
loadDefaultNet(true);
MOVEGEN::initLeaperAttacks();
MOVEGEN::initSliderAttacks();
UTILS::InitZobrist();
#ifdef TUNING
SEARCH::RefreshTunableCaches();
#else
SEARCH::InitLMRTable();
#endif
Board board;
if (argc <= 1) {
UCILoop(board);
return 0;
}
std::string first = argv[1];
if (first == "--help" || first == "-h" || first == "help") {
PrintUsage();
return 0;
}
if (first == "--version" || first == "-v" || first == "version") {
PrintVersion();
return 0;
}
if (first == "bench" || first == "--bench") {
if (argc > 2) {
std::string second = argv[2];
if (second == "--help" || second == "-h" || second == "help") {
PrintUsage();
return 0;
}
}
RunBenchmark();
return 0;
}
if (first == "datagen" || first == "--datagen") {
int positions = 0;
int datagenThreads = 1;
std::string username = "";
bool hasPositions = false;
bool hasThreads = false;
std::vector<std::string> positional;
for (int i = 2; i < argc; i++) {
std::string arg = argv[i];
if (arg == "--help" || arg == "-h" || arg == "help") {
DATAGEN::PrintUsage();
return 0;
} else if (arg == "--positions" || arg == "-p") {
if (i + 1 >= argc) {
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
}
positions = ParsePositiveInt(argv[++i]);
if (positions == 0) {
ArgError(argv[i], "positions");
return 1;
}
positions *= 1000;
hasPositions = true;
} else if (arg.rfind("--positions=", 0) == 0) {
positions = ParsePositiveInt(arg.substr(12).c_str());
if (positions == 0) {
ArgError(arg.substr(12).c_str(), "positions");
return 1;
}
positions *= 1000;
hasPositions = true;
} else if (arg == "--threads" || arg == "-t") {
if (i + 1 >= argc) {
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
}
datagenThreads = ParsePositiveInt(argv[++i]);
if (datagenThreads == 0) {
ArgError(argv[i], "threads");
return 1;
}
hasThreads = true;
} else if (arg.rfind("--threads=", 0) == 0) {
datagenThreads = ParsePositiveInt(arg.substr(10).c_str());
if (datagenThreads == 0) {
ArgError(arg.substr(10).c_str(), "threads");
return 1;
}
hasThreads = true;
} else if (arg == "--username" || arg == "-u") {
if (i + 1 >= argc) {
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
}
username = argv[++i];
} else if (arg.rfind("--username=", 0) == 0) {
username = arg.substr(11);
} else if (!arg.empty() && arg[0] == '-') {
std::cerr << "error: unknown option '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
} else {
positional.push_back(arg);
}
}
size_t posIndex = 0;
if (!hasPositions && posIndex < positional.size()) {
positions = ParsePositiveInt(positional[posIndex].c_str());
if (positions == 0) {
ArgError(positional[posIndex].c_str(), "positions");
return 1;
}
positions *= 1000;
hasPositions = true;
posIndex++;
}
if (!hasThreads && posIndex < positional.size()) {
datagenThreads = ParsePositiveInt(positional[posIndex].c_str());
if (datagenThreads == 0) {
ArgError(positional[posIndex].c_str(), "threads");
return 1;
}
hasThreads = true;
posIndex++;
}
if (username.empty() && posIndex < positional.size()) {
username = positional[posIndex];
posIndex++;
}
if (posIndex < positional.size()) {
std::cerr << "error: unexpected argument '" << positional[posIndex] << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
}
if (!hasPositions)
positions = 1000;
if (!hasThreads) {
std::cerr << "error: threads must be at least 2." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
}
if (datagenThreads < 2) {
std::cerr << "error: threads must be at least 2 (got " << datagenThreads << "). The main thread only renders the progress screen, so " << datagenThreads << " leaves no worker to generate." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
return 1;
}
if (!username.empty()) {
DATAGEN::RunOnline(username, positions, datagenThreads);
} else {
DATAGEN::Run(positions, datagenThreads);
}
return 0;
}
if (!first.empty() && first[0] == '-') {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "--help" || arg == "-h" || arg == "help") {
PrintUsage();
return 0;
} else if (arg == "--version" || arg == "-v" || arg == "version") {
PrintVersion();
return 0;
} else if (arg == "--threads" || arg == "-t") {
if (i + 1 >= argc) {
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
return 1;
}
int value = ParsePositiveInt(argv[++i]);
if (value < 1 || value > 512) {
ArgError(argv[i], "threads");
return 1;
}
threads = value;
} else if (arg.rfind("--threads=", 0) == 0) {
int value = ParsePositiveInt(arg.substr(10).c_str());
if (value < 1 || value > 512) {
ArgError(arg.substr(10).c_str(), "threads");
return 1;
}
threads = value;
} else if (arg == "--hash") {
if (i + 1 >= argc) {
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
return 1;
}
int value = ParsePositiveInt(argv[++i]);
if (value < 1 || value > 1024) {
ArgError(argv[i], "hash");
return 1;
}
U64 hashSize = (U64(value) * 1000000ULL) / sizeof(TTBucket);
SharedTT.Resize(hashSize);
} else if (arg.rfind("--hash=", 0) == 0) {
int value = ParsePositiveInt(arg.substr(7).c_str());
if (value < 1 || value > 1024) {
ArgError(arg.substr(7).c_str(), "hash");
return 1;
}
U64 hashSize = (U64(value) * 1000000ULL) / sizeof(TTBucket);
SharedTT.Resize(hashSize);
} else if (arg == "--evalfile") {
if (i + 1 >= argc) {
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
return 1;
}
NNUE::net.Load(argv[++i]);
} else if (arg.rfind("--evalfile=", 0) == 0) {
NNUE::net.Load(arg.substr(11));
} else {
std::cerr << "error: unknown option '" << arg << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
return 1;
}
}
UCILoop(board);
return 0;
}
std::cerr << "error: unknown command '" << first << "'." << std::endl;
std::cerr << std::endl;
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
return 1;
}
Board board;
if (argc > 1) {
if (std::string(argv[1]) == "bench") {
RunBenchmark();
} else if (std::string(argv[1]) == "datagen") {
int positions = 1;
int threads = 1;
std::string username = "";
if (argc > 2) {
positions = std::stoi(argv[2]) * 1000;
if (argc > 3) {
threads = std::stoi(argv[3]);
if (argc > 4) {
username = argv[4];
}
}
}
if (!username.empty()) {
DATAGEN::RunOnline(username, positions, threads);
} else {
DATAGEN::Run(positions, threads);
}
}
} else {
UCILoop(board);
}
return 0;
}
+17 -12
View File
@@ -68,8 +68,21 @@ public:
return (GetFlags() == kingCastle || GetFlags() == queenCastle);
}
// Castling moves are stored as "king takes own castling rook": from = king square, to = rook square.
// This is the UCI_Chess960 notation and it can't clash with a normal king move.
// CastleKingDest() is the square the king actually ends up on (g/c file of the back rank).
int CastleKingDest() {
return (MoveTo() & ~7) + (GetFlags() == kingCastle ? 6 : 2);
}
// Destination square used when printing the move: standard UCI prints the king's
// destination (e1g1), UCI_Chess960 prints the rook square (e1h1).
int PrintTo() {
return (IsCastle() && !UCIChess960) ? CastleKingDest() : MoveTo();
}
void PrintMove() {
std::cout << squareCoords[MoveFrom()] << squareCoords[MoveTo()];
std::cout << squareCoords[MoveFrom()] << squareCoords[PrintTo()];
int flags = GetFlags();
@@ -86,7 +99,7 @@ public:
std::string GetMoveString() {
std::string result = squareCoords[MoveFrom()];
result += squareCoords[MoveTo()];
result += squareCoords[PrintTo()];
int flags = GetFlags();
@@ -110,16 +123,8 @@ public:
viriMove = MoveFrom();
if (flags == kingCastle || flags == queenCastle) {
uint16_t moveTo = 0;
bool side = (MoveFrom() / 8 == 0) ? White : Black;
if (flags == kingCastle) {
moveTo = (side == White) ? h1 : h8;
} else {
moveTo = (side == White) ? a1 : a8;
}
viriMove |= (moveTo << 6);
// Castling is already stored as king takes rook, which is what the viri format expects
viriMove |= (MoveTo() << 6);
viriMove |= 0x8000;
+5 -22
View File
@@ -241,28 +241,11 @@ void GenKingMoves(Board &board) {
moves.PopBit(square);
}
// Generating castles
int kingRight = board.sideToMove ? blackKingRight : whiteKingRight;
int queenRight = board.sideToMove ? blackQueenRight : whiteQueenRight;
if (board.castlingRights & queenRight) {
U64 QueenSide = board.sideToMove ? 0x1f00000000000000 : 0x1f;
U64 mask = board.sideToMove ? 0x1c00000000000000 : 0x1c;
int targetSquare = board.sideToMove ? c8 : c1;
if ((Bitboard(QueenSide) & board.occupied).PopCount() == 2
&& !(mask & board.colorThreats[!board.sideToMove])) {
board.AddMove(Move(kingSquare, targetSquare, queenCastle));
}
}
if (board.castlingRights & kingRight) {
U64 KingSide = board.sideToMove ? 0xf000000000000000 : 0xf0;
U64 mask = board.sideToMove ? 0x7000000000000000 : 0x70;
int targetSquare = board.sideToMove ? g8 : g1;
if ((Bitboard(KingSide) & board.occupied).PopCount() == 2
&& !(mask & board.colorThreats[!board.sideToMove])) {
board.AddMove(Move(kingSquare, targetSquare, kingCastle));
// Generating castles (Chess960 aware): encoded as the king taking its own castling rook
for (const bool kingSide : {false, true}) {
if (board.CanCastle(board.sideToMove, kingSide)) {
board.AddMove(Move(kingSquare, board.castleRook[Board::CastleIdx(board.sideToMove, kingSide)],
kingSide ? kingCastle : queenCastle));
}
}
+13 -16
View File
@@ -15,26 +15,22 @@ void Network::Load(const std::string& path) {
std::cerr << "Failed to open file " + path << std::endl;
}
// HL weights
for (size_t i = 0; i < accumulator_weights.size(); i++) {
for (size_t j = 0; j < accumulator_weights[i].size(); j++) {
file.read(reinterpret_cast<char*>(&accumulator_weights[i][j]), sizeof(int16_t));
}
}
// HL biases
for (size_t i = 0; i < accumulator_biases.size(); i++) {
file.read(reinterpret_cast<char*>(&accumulator_biases[i]), sizeof(int16_t));
}
// Output weights
for (size_t i = 0; i < output_weights.size(); i++) {
for (size_t j = 0; j < output_weights[i].size(); j++) {
file.read(reinterpret_cast<char*>(&output_weights[i][j]), sizeof(int16_t));
}
}
// Output biases
for (size_t i = 0; i < output_bias.size(); i++) {
file.read(reinterpret_cast<char*>(&output_bias[i]), sizeof(int16_t));
}
@@ -135,12 +131,12 @@ using nativeVector = void*;
#endif
static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t outputBucket) {
static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair& acc, const Network& net, size_t outputBucket) {
const size_t VECTOR_SIZE = sizeof(nativeVector) / sizeof(int16_t);
static_assert(HL_SIZE % VECTOR_SIZE == 0, "HL size must be divisible by the native register size of your CPU for vectorization to work");
const ACC::Accumulator& stmAcc = board.sideToMove == White ? board.accPair.white : board.accPair.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? board.accPair.white : board.accPair.black;
const ACC::Accumulator& stmAcc = board.sideToMove == White ? acc.white : acc.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? acc.white : acc.black;
const nativeVector VEC_QA = set1_epi16(QA);
const nativeVector VEC_ZERO = set1_epi16(0);
@@ -148,19 +144,15 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
nativeVector accumulator{};
for (int i = 0; i < HL_SIZE; i += VECTOR_SIZE) {
// Load accumulators
const nativeVector stmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&stmAcc[i]));
const nativeVector nstmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&nstmAcc[i]));
// Clamp values
const nativeVector stmClamped = min_epi16(VEC_QA, max_epi16(stmAccumValues, VEC_ZERO));
const nativeVector nstmClamped = min_epi16(VEC_QA, max_epi16(nstmAccumValues, VEC_ZERO));
// Load weights
const nativeVector stmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i]));
const nativeVector nstmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i + HL_SIZE]));
// SCReLU activation
const nativeVector stmActivated = madd_epi16(stmClamped, mullo_epi16(stmClamped, stmWeights));
const nativeVector nstmActivated = madd_epi16(nstmClamped, mullo_epi16(nstmClamped, nstmWeights));
@@ -171,13 +163,13 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
return reduce_epi32(accumulator);
}
int Forward(const Board& board, const Network& net) {
static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Network& net) {
const size_t divisor = 32 / OUTPUT_BUCKETS;
const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor;
int64_t eval = 0;
eval = VectorizedSCReLU(board, net, outputBucket);
eval = VectorizedSCReLU(board, acc, net, outputBucket);
eval /= QA;
@@ -187,16 +179,21 @@ int Forward(const Board& board, const Network& net) {
return (eval * SCALE) / (QA * QB);
}
int16_t Network::Evaluate(const Board& board, bool datagen) {
// Disabled in datagen
int16_t Network::Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen) {
const int materialScale = datagen ? 4096 : 2048
+ 90 * board.pieces[Knight].PopCount()
+ 90 * board.pieces[Bishop].PopCount()
+ 180 * board.pieces[Rook].PopCount()
+ 360 * board.pieces[Queen].PopCount();
return std::clamp(Forward(board, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
return std::clamp(Forward(board, acc, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
(SEARCH::MATE_SCORE - SEARCH::MAX_DEPTH));
}
int16_t Network::Evaluate(const Board& board, bool datagen) {
ACC::AccumulatorPair acc;
board.RefreshAccumulator(acc);
return Evaluate(board, acc, datagen);
}
}
+6
View File
@@ -5,6 +5,10 @@
class Board;
namespace ACC {
struct AccumulatorPair;
}
#ifdef __AVX512F__
constexpr size_t ALIGNMENT = 64;
#else
@@ -54,6 +58,8 @@ struct Network {
void Load(const std::string& path);
int16_t Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen = false);
int16_t Evaluate(const Board& board, bool datagen = false);
};
+249 -30
View File
@@ -1,46 +1,265 @@
#include "perft.h"
#include "stopwatch.h"
#include "movegen.h"
#include <cassert>
static U64 HelperPerft(Board &board, int depth) {
MOVEGEN::GenerateMoves<All>(board, true);
if (depth == 0) return 1ULL;
#include "termcolor.hpp"
#include <iostream>
#include <iomanip>
#include <string>
struct PerftCounts {
U64 nodes = 0;
U64 captures = 0;
U64 ep = 0;
U64 castles = 0;
U64 promotions = 0;
U64 checks = 0;
U64 discovery = 0;
U64 doubles = 0;
U64 mates = 0;
for (int i = 0; i < board.currentMoveIndex; i++) {
if (!board.IsLegal(board.moveList[i])) continue;
Board copy = board;
copy.MakeMove(board.moveList[i]);
nodes += HelperPerft(copy, depth - 1);
PerftCounts& operator+=(const PerftCounts& other) {
nodes += other.nodes;
captures += other.captures;
ep += other.ep;
castles += other.castles;
promotions += other.promotions;
checks += other.checks;
discovery += other.discovery;
doubles += other.doubles;
mates += other.mates;
return *this;
}
return nodes;
};
static bool IsDirectCheck(Board& pos, Move move) {
int mover = !pos.sideToMove;
int kingSq = (pos.pieces[King] & pos.colors[pos.sideToMove]).getLS1BIndex();
if (kingSq < 0 || kingSq >= 64)
return false;
int to = move.MoveTo();
int flags = move.GetFlags();
if (flags == kingCastle || flags == queenCastle) {
// Castling is stored as "king takes own rook", so the rook's destination follows from the back rank of "to"
int rookTo = (to & ~7) + (flags == kingCastle ? 5 : 3);
Bitboard rookAtt = MOVEGEN::getRookAttack(rookTo, pos.occupied);
return rookAtt.IsSet(kingSq);
}
int endPiece = pos.GetPieceType(to);
if (endPiece == nullPieceType || endPiece == King)
return false;
Bitboard att = MOVEGEN::getPieceAttacks(to, endPiece, mover, pos.occupied);
return att.IsSet(kingSq);
}
static void CountLeaf(Board& pos, Move move, PerftCounts& out) {
out.nodes++;
int flags = move.GetFlags();
if (move.IsCapture())
out.captures++;
if (flags == epCapture)
out.ep++;
if (flags == kingCastle || flags == queenCastle)
out.castles++;
if (move.IsPromo())
out.promotions++;
if (pos.InCheck()) {
out.checks++;
if (pos.checkers.PopCount() == 2)
out.doubles++;
if (!IsDirectCheck(pos, move))
out.discovery++;
MOVEGEN::GenerateMoves<All>(pos, true);
bool hasLegal = false;
for (int i = 0; i < pos.currentMoveIndex; i++) {
Move m = pos.moveList[i];
if (pos.IsLegal(m)) {
hasLegal = true;
break;
}
}
if (!hasLegal)
out.mates++;
}
}
static void PerftRec(Board& board, int depth, PerftCounts& out) {
MOVEGEN::GenerateMoves<All>(board, true);
for (int i = 0; i < board.currentMoveIndex; i++) {
Move move = board.moveList[i];
if (!board.IsLegal(move))
continue;
Board copy = board;
copy.MakeMove(move);
if (depth == 1)
CountLeaf(copy, move, out);
else
PerftRec(copy, depth - 1, out);
}
}
static void PrintPerftHeader() {
std::cout << termcolor::bold << termcolor::color<244>;
std::cout << std::setw(6) << std::left << "Move";
std::cout << std::setw(11) << std::right << "Nodes";
std::cout << std::setw(8) << std::right << "Capt";
std::cout << std::setw(7) << std::right << "E.P.";
std::cout << std::setw(7) << std::right << "Cast";
std::cout << std::setw(7) << std::right << "Promo";
std::cout << std::setw(8) << std::right << "Check";
std::cout << std::setw(7) << std::right << "Disc";
std::cout << std::setw(5) << std::right << "Dbl";
std::cout << std::setw(7) << std::right << "Mate";
std::cout << termcolor::reset << std::endl;
std::cout << termcolor::color<238>;
for (int i = 0; i < 73; i++)
std::cout << '-';
std::cout << termcolor::reset << std::endl;
}
static void PrintPerftBase(int index) {
if (index % 2 == 0)
std::cout << termcolor::color<247>;
else
std::cout << termcolor::color<251>;
}
static void PrintPerftLine(int index, const std::string& moveStr, const PerftCounts& c) {
PrintPerftBase(index);
std::cout << termcolor::bold << termcolor::bright_cyan;
std::cout << std::setw(6) << std::left << (moveStr + ":");
std::cout << termcolor::reset;
PrintPerftBase(index);
std::cout << termcolor::bold << termcolor::bright_white;
std::cout << std::setw(11) << std::right << c.nodes;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.captures > 0)
std::cout << termcolor::bold << termcolor::yellow;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(8) << std::right << c.captures;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.ep > 0)
std::cout << termcolor::bold << termcolor::bright_yellow;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(7) << std::right << c.ep;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.castles > 0)
std::cout << termcolor::bold << termcolor::cyan;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(7) << std::right << c.castles;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.promotions > 0)
std::cout << termcolor::bold << termcolor::magenta;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(7) << std::right << c.promotions;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.checks > 0)
std::cout << termcolor::bold << termcolor::green;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(8) << std::right << c.checks;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.discovery > 0)
std::cout << termcolor::bold << termcolor::bright_magenta;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(7) << std::right << c.discovery;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.doubles > 0)
std::cout << termcolor::bold << termcolor::bright_red;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(5) << std::right << c.doubles;
std::cout << termcolor::reset;
PrintPerftBase(index);
if (c.mates > 0)
std::cout << termcolor::bold << termcolor::red;
else
std::cout << termcolor::color<244>;
std::cout << std::setw(7) << std::right << c.mates;
std::cout << termcolor::reset << std::endl;
}
void Perft(Board &board, int depth) {
//board.SetByFen(StartingFen);
MOVEGEN::GenerateMoves<All>(board, true);
U64 totalNodes = 0;
Stopwatch sw;
for (int i = 0; i < board.currentMoveIndex; i++) {
if (!board.IsLegal(board.moveList[i])) continue;
Board copy = board;
copy.MakeMove(board.moveList[i]);
U64 nodeCount = HelperPerft(copy, depth - 1);
totalNodes += nodeCount;
board.moveList[i].PrintMove();
std::cout << ": " << nodeCount << std::endl;
if (depth <= 0) {
std::cout << std::endl << "Depth: " << depth << std::endl;
std::cout << "Total nodes: 1" << std::endl;
std::cout << "Time took: " << sw.GetElapsedSec() << "s (";
std::cout << int(1 / sw.GetElapsedSec()) << " nodes/sec)" << std::endl;
return;
}
MOVEGEN::GenerateMoves<All>(board, true);
PerftCounts total;
int moveCount = 0;
PrintPerftHeader();
for (int i = 0; i < board.currentMoveIndex; i++) {
Move move = board.moveList[i];
if (!board.IsLegal(move))
continue;
Board copy = board;
copy.MakeMove(move);
PerftCounts local;
if (depth == 1)
CountLeaf(copy, move, local);
else
PerftRec(copy, depth - 1, local);
total += local;
PrintPerftLine(moveCount, move.GetMoveString(), local);
moveCount++;
}
double elapsed = sw.GetElapsedSec();
std::cout << termcolor::color<238>;
for (int i = 0; i < 73; i++)
std::cout << '-';
std::cout << termcolor::reset << std::endl;
PrintPerftLine(moveCount, "Total", total);
std::cout << std::endl;
std::cout << termcolor::bold << termcolor::bright_white;
std::cout << "Depth: " << depth;
std::cout << " Moves: " << moveCount;
std::cout << " Nodes: " << total.nodes;
U64 nps = elapsed > 0 ? U64(double(total.nodes) / elapsed) : total.nodes;
std::cout << " Time: ";
if (elapsed >= 1.0)
std::cout << elapsed << "s";
else
std::cout << int(elapsed * 1000) << "ms";
std::cout << " Avg: " << nps << "/s";
std::cout << termcolor::reset << std::endl;
std::cout << std::endl << "Depth: " << depth << std::endl;
std::cout << "Total nodes: " << totalNodes << std::endl;
std::cout << "Time took: " << sw.GetElapsedSec() << "s (";
std::cout << int(totalNodes / sw.GetElapsedSec()) << " nodes/sec)" << std::endl;
std::cout << "Total nodes: " << total.nodes << std::endl;
std::cout << "Time took: " << elapsed << "s (";
std::cout << int(double(total.nodes) / elapsed) << " nodes/sec)" << std::endl;
}
+243 -63
View File
@@ -13,6 +13,74 @@
namespace SEARCH {
static void PublishRootVote(SearchContext* ctx, const SearchResults& results, int depth) {
if (!ctx->voteTable || !ctx->voteMutex)
return;
Move m = results.bestMove;
if (uint16_t(m) == 0)
return;
if (ctx->threadId < 0 || ctx->threadId >= static_cast<int>(ctx->voteTable->size()))
return;
std::lock_guard<std::mutex> lock(*ctx->voteMutex);
RootVote& slot = (*ctx->voteTable)[ctx->threadId];
slot.bestMove = results.bestMove;
slot.score = results.score;
slot.depth = depth;
}
SearchResults VoteRootMoves(const std::vector<RootVote>& votes) {
struct Tally {
Move move;
int count = 0;
int score = 0;
int depth = 0;
};
std::vector<Tally> tallies;
tallies.reserve(votes.size());
for (const RootVote& v : votes) {
Move mv = v.bestMove;
if (uint16_t(mv) == 0)
continue;
const uint16_t key = mv;
bool found = false;
for (Tally& t : tallies) {
if (uint16_t(t.move) == key) {
t.count++;
if (v.depth > t.depth || (v.depth == t.depth && v.score > t.score)) {
t.score = v.score;
t.depth = v.depth;
t.move = v.bestMove;
}
found = true;
break;
}
}
if (!found) {
Tally t;
t.move = v.bestMove;
t.count = 1;
t.score = v.score;
t.depth = v.depth;
tallies.push_back(t);
}
}
if (tallies.empty())
return SearchResults(0, Move());
Tally* best = &tallies[0];
for (size_t i = 1; i < tallies.size(); i++) {
if (tallies[i].count > best->count
|| (tallies[i].count == best->count && tallies[i].depth > best->depth)
|| (tallies[i].count == best->count && tallies[i].depth == best->depth && tallies[i].score > best->score)) {
best = &tallies[i];
}
}
return SearchResults(best->score, best->move);
}
static WDLTriplet GetRoundedWDL(int score, Board& board) {
WDLTriplet wdl = getWDL(score, board);
@@ -89,12 +157,10 @@ static int AdjustEval(Board &board, SearchContext* ctx, int eval) {
static bool IsTwoFold(Board &board, SearchContext* ctx) {
for (int i = 0; i < board.positionIndex; i++) {
if (ctx->positionHistory[i] == board.hashKey) {
// repetition found
return true;
}
}
// no repetition
return false;
}
@@ -115,7 +181,6 @@ template <bool isPV>
static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, bool improving, bool corrplexity, bool ttpv, bool ttpvFailLow, SearchContext* ctx) {
int reduction = 0;
// Late Move Reduction
reduction = lmrTable[move.IsQuiet()][depth][moveSeen] * 1024;
if (cutnode)
@@ -136,7 +201,6 @@ static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int
if (ttpvFailLow)
reduction += lmrTTPVFailLow;
// History LMR
int historyReduction = 0;
if (move.IsQuiet()) {
@@ -177,7 +241,6 @@ bool SEE(Board& board, Move& move, int threshold) {
int nextVictim = board.GetPieceType(from);
// Next victim is moved piece or promo piece
if (move.IsPromo()) {
nextVictim = move.GetPromoPiece();
}
@@ -270,17 +333,35 @@ static bool IsLoss(int score) {
return score < -WIN_SCORE;
}
template <searchMode mode>
static inline int StaticEval(Board& board, SearchContext* ctx, int ply) {
board.UpdateAccumulator(ctx->accStack, ply);
#ifdef ACC_VERIFY
{
ACC::AccumulatorPair ref;
board.RefreshAccumulator(ref);
if (ref.white != ctx->accStack.cur[ply]->white || ref.black != ctx->accStack.cur[ply]->black) {
std::cerr << "ACC MISMATCH ply " << ply << " fen " << board.GetFen() << std::endl;
std::abort();
}
}
#endif
return NNUE::net.Evaluate(board, *ctx->accStack.cur[ply], mode == datagen);
}
template <bool isPV, searchMode mode>
static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext* ctx) {
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return NNUE::net.Evaluate(board, mode == datagen);
return StaticEval<mode>(board, ctx, ply);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
int bestScore = AdjustEval(board, ctx, NNUE::net.Evaluate(board, mode == datagen));
int bestScore = AdjustEval(board, ctx, StaticEval<mode>(board, ctx, ply));
ctx->ss[ply].eval = bestScore;
TTEntry entry;
@@ -296,9 +377,11 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
case CutNode:
if (entry.score >= beta)
return entry.score;
break;
case AllNode:
if (entry.score <= alpha)
return entry.score;
break;
}
}
@@ -308,12 +391,15 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
switch (entry.nodeType) {
case PV:
bestScore = entry.score;
break;
case CutNode:
if (entry.score > bestScore)
bestScore = entry.score;
break;
case AllNode:
if (entry.score < bestScore)
bestScore = entry.score;
break;
}
}
@@ -338,7 +424,6 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
Move currMove;
while ((currMove = mp.Next())) {
if (!IsLoss(bestScore)) {
// QS FP
if (!inCheck && currMove.IsCapture() &&
fpScore <= alpha && !SEE(board, currMove, 1)) {
@@ -369,6 +454,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
int score = -Quiescence<isPV, mode>(copy, -beta, -alpha, ply + 1, ctx).score;
if (score >= beta) {
if (searchStopped.load(std::memory_order_relaxed)) return 0;
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
return score;
}
@@ -393,11 +479,27 @@ 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;
if (ply) {
const int matedScore = -MATE_SCORE + ply;
if (matedScore > alpha) {
alpha = matedScore;
if (alpha >= beta)
return alpha;
}
const int mateScore = MATE_SCORE - ply;
if (mateScore < beta) {
beta = mateScore;
if (alpha >= beta)
return beta;
}
}
ctx->pvLine.SetLength(ply);
if (ply && (IsDraw(board, ctx))) return 0;
@@ -422,7 +524,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (depth <= 0) return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx);
int rawEval = NNUE::net.Evaluate(board, mode == datagen);
int rawEval = StaticEval<mode>(board, ctx, ply);
const int staticEval = AdjustEval(board, ctx, rawEval);
ctx->ss[ply].eval = staticEval;
@@ -454,7 +556,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (!inCheck && !ctx->excluded) {
if (ply) {
// Reverse Futility Pruning
int margin = rfpBase + rfpMargin * (depth - improving);
if (!ttpv && ttAdjustedEval - margin >= beta && depth < 7) {
return !IsDecisive(ttAdjustedEval) && !IsDecisive(beta)
@@ -462,12 +563,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
: ttAdjustedEval;
}
// Razoring
if (!isPV && depth <= 3 && staticEval + razoringScalar * depth < alpha && entry.nodeType != CutNode) {
return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx).score;
}
// Null Move Pruning
if (ply > ctx->minNmpPly && ttAdjustedEval >= beta + nmpBetaMargin) {
if (depth > 1 && !board.InPossibleZug()) {
Board copy = board;
@@ -500,7 +599,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);
@@ -564,19 +662,27 @@ 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())) {
if (ctx->excluded == currMove)
continue;
if (ply == 0 && !ctx->searchMoves.empty()) {
bool found = false;
for (Move &m : ctx->searchMoves) {
if (m.MoveFrom() == currMove.MoveFrom() && m.MoveTo() == currMove.MoveTo() && m.GetFlags() == currMove.GetFlags()) {
found = true;
break;
}
}
if (!found)
continue;
}
bool notMated = results.score > (-MATE_SCORE + MAX_DEPTH);
int lmrDepth = depth - lmrTable[currMove.IsQuiet()][depth][moveSeen];
// Late move pruning
// If we are near a leaf node we prune moves
// that are late in the list
if (currMove.IsQuiet() && notMated) {
int lmpThreshold = 7 + depth * depth * (1 + improving);
@@ -594,9 +700,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ply > 0) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 1);
if (ply > 1) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 2);
// Futility pruning
// If our static eval is far below alpha, there is only a small chance
// that a quiet move will help us so we skip them
int margin = fpMargin * (lmrDepth + improving) + historyScore / 32;
if (!isPV && ply && currMove.IsQuiet()
@@ -604,10 +707,9 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
continue;
}
// PVS SEE
int SEEThreshold = currMove.IsQuiet() ? seeQuietThreshold * depth : seeNoisyThreshold * depth * depth;
if (ply && depth <= 10 && !SEE(board, currMove, SEEThreshold))
if (ply && depth <= 10 && notMated && !SEE(board, currMove, SEEThreshold))
continue;
@@ -615,14 +717,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
Board copy = board;
copy.MakeMove(currMove);
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
ctx->TT->PrefetchEntry(copy.hashKey);
@@ -642,22 +736,18 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
const int singularScore = PVS<false, mode>(board, sDepth, sBeta-1, sBeta, ply, ctx, cutnode).score;
ctx->excluded = Move();
// Singular extension
if (singularScore < sBeta) {
extension++;
if constexpr (!isPV) {
// Double extension
if (singularScore <= sBeta - 1 - doubleExtMargin) {
extension++;
}
}
}
// Multicut
else if (sBeta >= beta) {
return sBeta;
}
// Negative extension
else if (entry.score >= beta) {
extension--;
} else if (cutnode) {
@@ -670,6 +760,14 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
cutnode |= extension < 0;
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
int newDepth = depth + (copy.InCheck() && !ctx->excluded) - 1 + extension;
@@ -701,7 +799,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
moveSeen++;
// Root
if (!ply) {
ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch;
}
@@ -725,7 +822,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ctx->pvLine.SetMove(ply, currMove);
}
// Fail high (beta cutoff)
if (score >= beta) {
const int bonusDepth = depth + (!inCheck && staticEval <= alpha);
int historyBonus = historyBonusMultiplier * bonusDepth - historyBonusSub;
@@ -765,7 +861,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ply > 0) UpdateContHistNPly(1);
if (ply > 1) UpdateContHistNPly(2);
// Malus
for (int i = 0; i < seenQuietsCount - 1; i++) {
sourceThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveFrom());
targetThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveTo());
@@ -775,12 +870,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
UpdateCaptHist(currMove, captHistoryBonus);
}
// Capthist malus
for (int i = 0; i < seenCapturesCount - currMove.IsCapture(); i++) {
UpdateCaptHist(seenCaptures[i], -captHistoryMalus);
}
// Corrhist update on fail high
if (!ctx->excluded && !inCheck && currMove.IsQuiet() && score > staticEval) {
int corrHistBonus = std::clamp(score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT);
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
@@ -793,11 +886,8 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
if (moveSeen == 0) {
if (inCheck) { // checkmate
return -MATE_SCORE + ply;
} else { // stalemate
return 0;
}
if (ctx->excluded) return alpha;
return inCheck ? -MATE_SCORE + ply : 0;
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
@@ -848,7 +938,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;
@@ -862,6 +951,13 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
if constexpr (mode == bench) {
toDepth = BENCH_DEPTH;
} else if constexpr (mode != datagen) {
int depthLimit = MAX_DEPTH;
if (params.depth > 0)
depthLimit = std::min(params.depth, MAX_DEPTH);
if (params.mate > 0)
depthLimit = std::min({depthLimit, params.mate * 2, MAX_DEPTH});
toDepth = depthLimit;
}
AspirationWindow aw;
@@ -872,9 +968,23 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
ctx->sw.Restart();
bool hasTime = (fullTime > 0) || (params.movetime > 0);
bool useTime = hasTime && !params.infinite;
for (int depth = 1; depth <= toDepth; depth++) {
ctx->timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4);
int softTime = ctx->timeToSearch * 0.65 * nodeScaling;
if (params.movetime > 0 && !params.infinite) {
ctx->timeToSearch = params.movetime;
} else if (useTime) {
ctx->timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4);
} else {
ctx->timeToSearch = 2000000000;
}
int softTime = 2000000000;
if (params.movetime > 0 && !params.infinite) {
softTime = params.movetime;
} else if (useTime) {
softTime = int(ctx->timeToSearch * 0.65 * nodeScaling);
}
ctx->seldepth = 0;
ctx->rootDepth = depth;
@@ -906,12 +1016,14 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
safeResults = currentResults;
}
PublishRootVote(ctx, safeResults, depth);
if constexpr (mode == normal || mode == nodesMode) {
if (ctx->doPrint)
PrintSearchInfo(board, ctx, safeResults, depth, elapsed);
if constexpr (mode == normal) {
if (ctx->sw.GetElapsedMS() >= softTime) {
if (useTime && ctx->sw.GetElapsedMS() >= softTime) {
searchStopped.store(true, std::memory_order_relaxed);
break;
}
@@ -935,8 +1047,12 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c
ctx->TT->IncreaseAge();
}
board.MarkAccumulatorDirty();
ctx->accStack.finny.Reset();
ctx->seldepth = 0;
ctx->nodesTable = {};
ctx->searchMoves = params.searchMoves;
if constexpr (mode != bench) {
ctx->nodes = 0;
@@ -946,14 +1062,30 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c
}
ctx->pvLine.Clear();
if constexpr (mode == normal || mode == nodesMode) {
if (ctx->doPrint && !UCIEnabled)
PrintSearchHeader();
}
SearchResults results = ID<mode>(board, params, ctx);
if constexpr (mode != normal && mode != nodesMode) return results;
if (ctx->voteTable != nullptr) {
return results;
}
if (ctx->doPrint) {
std::cout << "bestmove ";
results.bestMove.PrintMove();
std::cout << std::endl;
if (UCIEnabled) {
std::cout << "bestmove ";
results.bestMove.PrintMove();
std::cout << std::endl;
} else {
std::cout << termcolor::color<244> << "bestmove " << termcolor::reset;
std::cout << termcolor::bold << termcolor::bright_green;
results.bestMove.PrintMove();
std::cout << termcolor::reset << std::endl;
}
}
return results;
@@ -976,6 +1108,27 @@ int MoveEstimatedValue(Board& board, Move& move) {
return value;
}
void PrintSearchHeader() {
if (UCIEnabled)
return;
std::cout << termcolor::bold << termcolor::color<244>;
std::cout << std::setw(7) << std::left << "Depth";
std::cout << std::setw(9) << std::right << "Time";
std::cout << std::setw(9) << std::right << "Score";
std::cout << std::setw(14) << std::right << "W-D-L";
std::cout << std::setw(7) << std::right << "TT";
std::cout << std::setw(9) << std::right << "Nodes";
std::cout << std::setw(9) << std::right << "NPS";
std::cout << " PV";
std::cout << termcolor::reset << std::endl;
std::cout << termcolor::color<238>;
for (int i = 0; i < 72; i++)
std::cout << '-';
std::cout << termcolor::reset << std::endl;
}
void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, int depth, int elapsed) {
WDLTriplet wdl = getWDL(results.score, board);
const bool isMateScore = std::abs(results.score) + MAX_DEPTH >= MATE_SCORE;
@@ -1015,7 +1168,14 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
std::stringstream depthStr;
depthStr << depth << '/' << ctx->seldepth;
std::cout << std::setw(6) << std::left << depthStr.str();
std::cout << termcolor::bold << termcolor::bright_white;
std::cout << std::setw(7) << std::left << depthStr.str();
std::cout << termcolor::reset;
if (depth % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
std::stringstream timeStr;
if (elapsed >= 1000) {
@@ -1023,7 +1183,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
} else {
timeStr << elapsed << "ms";
}
std::cout << std::setw(10) << std::right << timeStr.str();
std::cout << std::setw(9) << std::right << timeStr.str();
std::stringstream scoreStr;
bool isMate = false;
@@ -1045,15 +1205,15 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
if (isMate) {
if (mateIn > 0) {
std::cout << termcolor::bright_green;
std::cout << termcolor::bold << termcolor::bright_green;
} else {
std::cout << termcolor::bright_red;
std::cout << termcolor::bold << termcolor::bright_red;
}
} else {
if (results.score > 0) {
std::cout << termcolor::green;
std::cout << termcolor::bold << termcolor::green;
} else if (results.score < 0) {
std::cout << termcolor::red;
std::cout << termcolor::bold << termcolor::red;
}
}
@@ -1070,11 +1230,31 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
wdlStr << displayWDL.wins << "W "
<< displayWDL.draws << "D "
<< displayWDL.losses << "L";
std::cout << termcolor::color<244>;
std::cout << std::setw(14) << std::right << wdlStr.str();
if (depth % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
std::stringstream hashfullStr;
hashfullStr << "TT: " << (ctx->TT->GetUsedPercentage() + 5) / 10 << '%';
std::cout << std::setw(10) << std::right << hashfullStr.str();
int hashUsed = ctx->TT->GetUsedPercentage();
std::stringstream hashStr;
hashStr << (hashUsed + 5) / 10 << '%';
if (hashUsed >= 950) {
std::cout << termcolor::bright_red;
} else if (hashUsed >= 700) {
std::cout << termcolor::yellow;
} else {
std::cout << termcolor::green;
}
std::cout << std::setw(7) << std::right << hashStr.str();
std::cout << termcolor::reset;
if (depth % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
std::stringstream nodesStr;
if (ctx->nodes >= 1000000) {
@@ -1084,7 +1264,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
} else {
nodesStr << ctx->nodes;
}
std::cout << std::setw(11) << std::right << nodesStr.str();
std::cout << std::setw(9) << std::right << nodesStr.str();
int nps = int(ctx->nodes/ctx->sw.GetElapsedSec());
std::stringstream npsStr;
@@ -1095,7 +1275,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
} else {
npsStr << nps << "/s";
}
std::cout << std::setw(12) << std::right << npsStr.str();
std::cout << std::setw(9) << std::right << npsStr.str();
std::cout << " ";
ctx->pvLine.Print(0, depth % 2 == 0);
+30 -12
View File
@@ -2,6 +2,7 @@
#include "board.h"
#include "uci.h"
#include <vector>
#include <mutex>
#include "move.h"
#include <algorithm>
#include "stopwatch.h"
@@ -34,7 +35,6 @@ constexpr int CORRHIST_MAX = 16384;
constexpr int32_t ScoreNone = -255000;
constexpr int inf = 100000;
// first index: [0] noisy, [1] quiet
inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES];
#ifdef TUNING
@@ -56,9 +56,16 @@ void RefreshTunableCaches();
class SearchContext;
struct RootVote {
Move bestMove;
int score = 0;
int depth = 0;
};
SearchResults VoteRootMoves(const std::vector<RootVote>& votes);
class CaptHistory {
private:
// indexed by [stm][moving pt][capture pt][to]
MultiArray<int, 2, 6, 6, 64> historyMoves;
public:
void Update(bool stm, int moving, int capture, int to, int bonus) {
@@ -78,11 +85,9 @@ public:
class CorrHist {
private:
// indexed by [stm][key]
MultiArray<int, 2, CORRHIST_SIZE> pawnHist;
MultiArray<int, 2, CORRHIST_SIZE> nonPawnHist;
MultiArray<int, 2, CORRHIST_SIZE> majorHist;
MultiArray<int, 2, CORRHIST_SIZE> minorHist;
public:
void Update(Board& board, int depth, int diff, int* entry) {
const int scaledDiff = diff * CORRHIST_GRAIN;
@@ -96,27 +101,23 @@ public:
Update(board, depth, diff, &pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]);
Update(board, depth, diff, &minorHist[board.sideToMove][board.minorKey % CORRHIST_SIZE]);
}
int GetAllHist(Board& board) {
return pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]
+ nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]
+ minorHist[board.sideToMove][board.minorKey % CORRHIST_SIZE];
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE];
}
void Clear() {
std::fill(&pawnHist[0][0], &pawnHist[0][0] + sizeof(pawnHist) / sizeof(int), 0);
std::fill(&nonPawnHist[0][0], &nonPawnHist[0][0] + sizeof(nonPawnHist) / sizeof(int), 0);
std::fill(&majorHist[0][0], &majorHist[0][0] + sizeof(majorHist) / sizeof(int), 0);
std::fill(&minorHist[0][0], &minorHist[0][0] + sizeof(minorHist) / sizeof(int), 0);
}
};
class ContHistory {
private:
// indexed by [other color][prev move piece][stm][prev move to][piece][to]
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
public:
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
@@ -139,7 +140,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) {
@@ -179,7 +179,7 @@ public:
void Print(int n, bool isEven = false) {
for (int i = 0; i < length[n]; i++) {
if (i == 0 && !UCIEnabled) {
std::cout << termcolor::bright_cyan;
std::cout << termcolor::bold << termcolor::bright_cyan;
table[n][i].PrintMove();
std::cout << termcolor::reset;
@@ -191,7 +191,8 @@ public:
} else {
table[n][i].PrintMove();
}
std::cout << ' ';
if (i + 1 < length[n])
std::cout << ' ';
}
}
@@ -224,9 +225,14 @@ class SearchContext {
public:
bool doPrint = false;
int threadId = 0;
std::vector<RootVote>* voteTable = nullptr;
std::mutex* voteMutex = nullptr;
U64 nodes = 0;
U64 nodesToGo = 0;
int timeToSearch = 0;
std::vector<Move> searchMoves;
std::array<U64, 4096> nodesTable{};
@@ -251,6 +257,8 @@ public:
std::array<Stack, MAX_DEPTH> ss{};
ACC::AccStack accStack{MAX_DEPTH + 2};
Stopwatch sw;
SearchContext(){
@@ -264,6 +272,14 @@ public:
ss = {};
positionHistory.resize(1000);
}
void CopyLearningFrom(const SearchContext& other) {
history = other.history;
conthist = other.conthist;
corrhist = other.corrhist;
capthist = other.capthist;
killerMoves = other.killerMoves;
}
};
bool SEE(Board& board, Move& move, int threshold);
@@ -278,5 +294,7 @@ bool IsDraw(Board &board, SearchContext* ctx);
void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, int depth, int elapsed);
void PrintSearchHeader();
int MoveEstimatedValue(Board& board, Move& move);
}
+4 -1
View File
@@ -3,7 +3,10 @@
#include <array>
#include <string_view>
using U64 = uint64_t;
using U64 = uint64_t;
// UCI_Chess960 option: castling moves are printed/parsed as "king takes own rook" when enabled
inline bool UCIChess960 = false;
constexpr std::string_view StartingFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
constexpr std::string_view KiwiPeteFen = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -";
+156 -21
View File
@@ -13,6 +13,7 @@
#include "utils.h"
#include "datagen.h"
#include "tunables.h"
#include "termcolor.hpp"
// OS-dependent threading includes
#ifdef _WIN32
@@ -20,6 +21,8 @@
#else
#include <pthread.h>
#endif
#include <mutex>
#include <atomic>
namespace {
@@ -43,6 +46,47 @@ static std::vector<std::thread> searchThreads;
static std::vector<pthread_t> searchThreads;
#endif
static std::vector<SEARCH::RootVote> rootVotes;
static std::mutex voteMutex;
static std::atomic<bool> votePrinted{false};
static void PrintVotedBestmove(Move move) {
if (UCIEnabled) {
std::cout << "bestmove ";
if (!move)
std::cout << "0000";
else
move.PrintMove();
std::cout << std::endl;
} else {
std::cout << termcolor::color<244> << "bestmove " << termcolor::reset;
if (!move) {
std::cout << "0000" << std::endl;
} else {
std::cout << termcolor::bold << termcolor::bright_green;
move.PrintMove();
std::cout << termcolor::reset << std::endl;
}
}
}
static SearchResults GetVotedResult(const SearchResults& fallback) {
std::lock_guard<std::mutex> lock(voteMutex);
SearchResults voted = SEARCH::VoteRootMoves(rootVotes);
Move m = voted.bestMove;
if (uint16_t(m) == 0)
return fallback;
return voted;
}
static bool TryPrintVotedBestmove(const SearchResults& fallback) {
if (votePrinted.exchange(true, std::memory_order_acq_rel))
return false;
SearchResults voted = GetVotedResult(fallback);
PrintVotedBestmove(voted.bestMove);
return true;
}
static void JoinSearchThreads() {
#ifdef _WIN32
for (auto& thread : searchThreads) {
@@ -64,6 +108,16 @@ static void StopSearchThreads() {
JoinSearchThreads();
}
static void StopSearchThreadsAndVote() {
if (searchThreads.empty()) {
searchStopped.store(true, std::memory_order_relaxed);
return;
}
searchStopped.store(true, std::memory_order_relaxed);
JoinSearchThreads();
TryPrintVotedBestmove(SearchResults(0, Move()));
}
} // namespace
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext* ctx) {
@@ -139,20 +193,31 @@ 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::SearchContext* master) {
SearchResults results = SEARCH::SearchPosition<mode>(board, params, ctx);
int id = ctx->threadId;
if (id == 0) {
master->CopyLearningFrom(*ctx);
}
delete ctx;
if (id == 0) {
searchStopped.store(true, std::memory_order_relaxed);
TryPrintVotedBestmove(results);
}
}
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
ctxCopy->threadId = id;
ctxCopy->voteTable = &rootVotes;
ctxCopy->voteMutex = &voteMutex;
if (id == 0)
ctxCopy->doPrint = true;
if (params.nodes) {
searchThreads.emplace_back(ThreadFunc<SEARCH::nodesMode>, board, params, ctxCopy);
searchThreads.emplace_back(ThreadFunc<SEARCH::nodesMode>, board, params, ctxCopy, ctx);
} else {
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy);
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy, ctx);
}
}
@@ -160,11 +225,20 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
// Unix/Linux implementation using pthread
template <SEARCH::searchMode mode>
static void* ThreadFunc(void* arg) {
auto* tup = static_cast<std::tuple<Board, SearchParams, SEARCH::SearchContext*>*>(arg);
auto* tup = static_cast<std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>*>(arg);
SEARCH::SearchContext* ctx = std::get<2>(*tup);
SEARCH::SearchPosition<mode>(std::get<0>(*tup), std::get<1>(*tup), ctx);
SEARCH::SearchContext* master = std::get<3>(*tup);
SearchResults results = SEARCH::SearchPosition<mode>(std::get<0>(*tup), std::get<1>(*tup), ctx);
int id = ctx->threadId;
if (id == 0) {
master->CopyLearningFrom(*ctx);
}
delete ctx;
delete tup;
if (id == 0) {
searchStopped.store(true, std::memory_order_relaxed);
TryPrintVotedBestmove(results);
}
return nullptr;
}
@@ -174,6 +248,9 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
ctxCopy->threadId = id;
ctxCopy->voteTable = &rootVotes;
ctxCopy->voteMutex = &voteMutex;
if (id == 0)
ctxCopy->doPrint = true;
@@ -181,7 +258,7 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
int rc = 0;
if (params.nodes) {
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>(board, params, ctxCopy, ctx);
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
if (rc != 0) {
delete std::get<2>(*arg);
@@ -189,7 +266,7 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
ctxCopy = nullptr;
}
} else {
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>(board, params, ctxCopy, ctx);
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
if (rc != 0) {
delete std::get<2>(*arg);
@@ -208,6 +285,10 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
}
#endif
static bool IsGoToken(const std::string &token) {
return token == "searchmoves" || token == "ponder" || token == "wtime" || token == "btime" || token == "winc" || token == "binc" || token == "movestogo" || token == "depth" || token == "nodes" || token == "mate" || token == "movetime" || token == "infinite";
}
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) {
StopSearchThreads();
searchStopped.store(false, std::memory_order_relaxed);
@@ -221,17 +302,60 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c
params.binc = ReadParam("binc", command);
params.movesToGo = ReadParam("movestogo", command);
params.nodes = ReadParam("nodes", command);
params.depth = ReadParam("depth", command);
params.mate = ReadParam("mate", command);
params.movetime = ReadParam("movetime", command);
if (command.find("movetime") != std::string::npos) {
params.wtime = ReadParam("movetime", command);
params.btime = ReadParam("movetime", command);
} else if (command.find("infinite") != std::string::npos) {
params.wtime = 99999999;
params.btime = 99999999;
if (params.depth < 0)
params.depth = 0;
if (params.mate < 0)
params.mate = 0;
if (params.movetime < 0)
params.movetime = 0;
if (params.nodes < 0)
params.nodes = 0;
if (params.depth > SEARCH::MAX_DEPTH)
params.depth = SEARCH::MAX_DEPTH;
if (params.mate * 2 > SEARCH::MAX_DEPTH)
params.mate = SEARCH::MAX_DEPTH / 2;
if (command.find("infinite") != std::string::npos)
params.infinite = true;
if (command.find("ponder") != std::string::npos)
params.infinite = true;
size_t searchmovesPos = command.find("searchmoves");
if (searchmovesPos != std::string::npos) {
std::vector<std::string> tokens = UTILS::split(command.substr(searchmovesPos + 11), ' ');
for (std::string &token : tokens) {
if (token.empty())
continue;
if (IsGoToken(token))
break;
if (token.size() < 4)
continue;
Move m = UTILS::parseMove(board, token);
if (m != 0)
params.searchMoves.push_back(m);
}
}
searchThreads.reserve(threads);
for (int i = 0; i < threads; i++) {
ctx->searchMoves = params.searchMoves;
int numThreads = threads;
if (numThreads < 1)
numThreads = 1;
if (numThreads > 512)
numThreads = 512;
{
std::lock_guard<std::mutex> lock(voteMutex);
rootVotes.assign(numThreads, SEARCH::RootVote());
}
votePrinted.store(false, std::memory_order_relaxed);
searchThreads.reserve(numThreads);
for (int i = 0; i < numThreads; i++) {
StartSearchThread(board, params, ctx, i);
}
}
@@ -246,7 +370,17 @@ static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
}
if (command.find("Threads") != std::string::npos) {
threads = ReadParam("value", command);
threads = static_cast<int>(ReadParam("value", command));
if (threads < 1)
threads = 1;
if (threads > 512)
threads = 512;
return;
}
if (command.find("UCI_Chess960") != std::string::npos) {
UCIChess960 = command.find("value true") != std::string::npos
|| command.find("value 1") != std::string::npos;
return;
}
@@ -301,11 +435,12 @@ static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
}
static void PrintEngineInfo() {
std::cout << "id name Eleanor v4.1" << std::endl;
std::cout << "id name Eleanor v" << EleanorVersion << 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;
std::cout << "option name UCI_ShowWDL type check default false" << std::endl;
std::cout << "option name UCI_Chess960 type check default false" << std::endl;
#ifdef TUNING
PrintTunablesUCI();
@@ -355,7 +490,7 @@ void UCILoop(Board &board) {
}
// parse UCI "go" command
if (input.find("go") != std::string::npos) {
if (input == "go" || input.rfind("go ", 0) == 0) {
ParseGo(board, input, ctx.get());
continue;
}
@@ -369,7 +504,7 @@ void UCILoop(Board &board) {
// parse UCI "stop" command
if (input.find("stop") != std::string::npos) {
StopSearchThreads();
StopSearchThreadsAndVote();
continue;
}
@@ -408,7 +543,7 @@ void UCILoop(Board &board) {
}
if (input.find("nnue") != std::string::npos) {
board.PrintNNUE();
board.PrintNNUE(input.find("full") != std::string::npos);
continue;
}
+9
View File
@@ -1,5 +1,7 @@
#pragma once
#include <atomic>
#include <string_view>
#include <vector>
#include "move.h"
#include "board.h"
@@ -8,6 +10,8 @@ inline bool UCIShowWDL = false;
inline int threads = 1;
inline std::atomic<bool> searchStopped = false;
constexpr std::string_view EleanorVersion = "4.1";
class SearchParams {
public:
int wtime = 0;
@@ -16,6 +20,11 @@ public:
int binc = 0;
int movesToGo = 0;
int nodes = 0;
int depth = 0;
int mate = 0;
int movetime = 0;
bool infinite = false;
std::vector<Move> searchMoves;
int threads = 1;
+22 -6
View File
@@ -152,12 +152,28 @@ Move parseMove(Board &board, std::string_view str) {
}
}
} else {
for (Move move : board.moveList) {
bool found = false;
// Exact match first. Castling moves are stored as "king takes own rook",
// so this also covers the UCI_Chess960 castling notation (e1h1).
for (int i = 0; i < board.currentMoveIndex; i++) {
Move move = board.moveList[i];
if (move.MoveFrom() == from && move.MoveTo() == to) {
flag = move.GetFlags();
found = true;
break;
}
}
// Standard UCI castling notation: the king's destination square (e1g1)
if (!found) {
for (int i = 0; i < board.currentMoveIndex; i++) {
Move move = board.moveList[i];
if (move.IsCastle() && move.MoveFrom() == from && move.CastleKingDest() == to) {
return move;
}
}
}
}
return Move(from, to, flag);
@@ -177,11 +193,11 @@ std::array<uint8_t, 16> CompressPieces(Board board) {
int pieceCode = pieceType;
if (pieceType == Rook) {
if ((square == a1 && (board.castlingRights & whiteQueenRight))
|| (square == h1 && (board.castlingRights & whiteKingRight))
|| (square == a8 && (board.castlingRights & blackQueenRight))
|| (square == h8 && (board.castlingRights & blackKingRight)))
pieceCode = UNMOVED_ROOK;
// castling rooks, wherever they started (Chess960 aware)
for (int idx = 0; idx < 4; idx++) {
if ((board.castlingRights & (1 << idx)) && square == board.castleRook[idx] && pieceColor == (idx >> 1))
pieceCode = UNMOVED_ROOK;
}
}
pieceCode |= (pieceColor << 3); // Shift the color to the 3rd bit (bit 3)