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

No files matched your search

+51 -151
View File
@@ -7,180 +7,80 @@ namespace ACC {
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored) {
if (perspective == Black)
{
side = 1 - side;
square = square ^ 0b111000;
side = 1 - side; // Flip side
square = square ^ 0b111000; // Mirror square
}
if (mirrored)
square ^= 7;
return side * 64 * 6 + pieceType * 64 + square;
}
const int16_t* Row(int bucket, int index) {
return &NNUE::net.accumulator_weights[bucket][static_cast<size_t>(index) * NNUE::HL_SIZE];
}
// All friendly, for quiets
void AccumulatorPair::addSub(bool stm, int add, int addPT, int sub, int subPT, BucketPair bp) {
int addW = CalculateIndex(White, stm, addPT, add, mirroredWhite);
int addB = CalculateIndex(Black, stm, addPT, add, mirroredBlack);
void FinnyTable::Reset() {
for (auto& perspective : entries) {
for (auto& mirror : perspective) {
for (auto& entry : mirror) {
entry.acc = NNUE::net.accumulator_biases;
for (auto& color : entry.bb)
for (auto& bb : color)
bb = 0;
}
}
int subW = CalculateIndex(White, stm, subPT, sub, mirroredWhite);
int subB = CalculateIndex(Black, stm, subPT, sub, mirroredBlack);
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[bp.white][addW * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[bp.black][addB * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB * NNUE::HL_SIZE + i];
}
}
#if defined(_MSC_VER) && !defined(__clang__)
#define ACC_NOINLINE __declspec(noinline)
#else
#define ACC_NOINLINE __attribute__((noinline))
#endif
// Captures
void AccumulatorPair::addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp) {
int addW = CalculateIndex(White, stm, addPT, add, mirroredWhite);
int addB = CalculateIndex(Black, stm, addPT, add, mirroredBlack);
#if defined(__AVX512F__) && defined(__AVX512BW__)
#include <immintrin.h>
using Vec = __m512i;
static inline Vec vLoad(const int16_t* p) { return _mm512_loadu_si512(p); }
static inline void vStore(int16_t* p, Vec v) { _mm512_storeu_si512(p, v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm512_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm512_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__AVX2__)
#include <immintrin.h>
using Vec = __m256i;
static inline Vec vLoad(const int16_t* p) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); }
static inline void vStore(int16_t* p, Vec v) { _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm256_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm256_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64)
#include <immintrin.h>
using Vec = __m128i;
static inline Vec vLoad(const int16_t* p) { return _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); }
static inline void vStore(int16_t* p, Vec v) { _mm_storeu_si128(reinterpret_cast<__m128i*>(p), v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__aarch64__)
#include <arm_neon.h>
using Vec = int16x8_t;
static inline Vec vLoad(const int16_t* p) { return vld1q_s16(p); }
static inline void vStore(int16_t* p, Vec v) { vst1q_s16(p, v); }
static inline Vec vAdd(Vec a, Vec b) { return vaddq_s16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return vsubq_s16(a, b); }
#define ACC_SIMD 1
#endif
int subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack);
#ifdef ACC_SIMD
int subW2 = CalculateIndex(White, !stm, subPT2, sub2, mirroredWhite);
int subB2 = CalculateIndex(Black, !stm, subPT2, sub2, mirroredBlack);
constexpr size_t LANES = sizeof(Vec) / sizeof(int16_t);
constexpr size_t TILE = 4;
constexpr size_t STEP = LANES * TILE;
static_assert(NNUE::HL_SIZE % STEP == 0, "HL size must be divisible by the SIMD tile size");
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[bp.white][addW * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW2 * NNUE::HL_SIZE + i];
template <int NA, int NS>
ACC_NOINLINE static void ApplyKernel(int16_t* dst, const int16_t* src,
const int16_t* a1, const int16_t* a2,
const int16_t* s1, const int16_t* s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
Vec r[TILE];
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(src + i + u * LANES);
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a1 + i + u * LANES));
if constexpr (NA > 1)
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a2 + i + u * LANES));
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s1 + i + u * LANES));
if constexpr (NS > 1)
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s2 + i + u * LANES));
for (size_t u = 0; u < TILE; u++) vStore(dst + i + u * LANES, r[u]);
black[i] += NNUE::net.accumulator_weights[bp.black][addB * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB2 * NNUE::HL_SIZE + i];
}
}
ACC_NOINLINE static void InPlaceKernel(int16_t* acc, const int16_t* const* adds, int nAdds,
const int16_t* const* subs, int nSubs) {
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
Vec r[TILE];
// Castling
void AccumulatorPair::addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp) {
int addW1 = CalculateIndex(White, stm, addPT1, add1, mirroredWhite);
int addB1 = CalculateIndex(Black, stm, addPT1, add1, mirroredBlack);
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(acc + i + u * LANES);
int addW2 = CalculateIndex(White, stm, addPT2, add2, mirroredWhite);
int addB2 = CalculateIndex(Black, stm, addPT2, add2, mirroredBlack);
for (int j = 0; j < nAdds; j++)
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(adds[j] + i + u * LANES));
int subW1 = CalculateIndex(White, stm, subPT1, sub1, mirroredWhite);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1, mirroredBlack);
for (int j = 0; j < nSubs; j++)
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(subs[j] + i + u * LANES));
int subW2 = CalculateIndex(White, stm, subPT2, sub2, mirroredWhite);
int subB2 = CalculateIndex(Black, stm, subPT2, sub2, mirroredBlack);
for (size_t u = 0; u < TILE; u++) vStore(acc + i + u * LANES, r[u]);
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[bp.white][addW1 * NNUE::HL_SIZE + i]
+ NNUE::net.accumulator_weights[bp.white][addW2 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.white][subW2 * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[bp.black][addB1 * NNUE::HL_SIZE + i]
+ NNUE::net.accumulator_weights[bp.black][addB2 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB1 * NNUE::HL_SIZE + i]
- NNUE::net.accumulator_weights[bp.black][subB2 * NNUE::HL_SIZE + i];
}
}
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
if (a2)
ApplyKernel<2, 2>(dst.data(), src.data(), a1, a2, s1, s2);
else if (s2)
ApplyKernel<1, 2>(dst.data(), src.data(), a1, nullptr, s1, s2);
else
ApplyKernel<1, 1>(dst.data(), src.data(), a1, nullptr, s1, nullptr);
}
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
InPlaceKernel(acc.data(), adds, nAdds, subs, nSubs);
}
void AddRow(Accumulator& acc, const int16_t* row) {
const int16_t* rows[1] = {row};
InPlaceKernel(acc.data(), rows, 1, nullptr, 0);
}
#else
using Ptr = int16_t* __restrict;
using CPtr = const int16_t* __restrict;
ACC_NOINLINE static void Kernel1p1m(Ptr dst, CPtr src, CPtr a, CPtr s) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a[i] - s[i]);
}
ACC_NOINLINE static void Kernel1p2m(Ptr dst, CPtr src, CPtr a, CPtr s1, CPtr s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a[i] - s1[i] - s2[i]);
}
ACC_NOINLINE static void Kernel2p2m(Ptr dst, CPtr src, CPtr a1, CPtr a2, CPtr s1, CPtr s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a1[i] + a2[i] - s1[i] - s2[i]);
}
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
if (a2)
Kernel2p2m(dst.data(), src.data(), a1, a2, s1, s2);
else if (s2)
Kernel1p2m(dst.data(), src.data(), a1, s1, s2);
else
Kernel1p1m(dst.data(), src.data(), a1, s1);
}
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
int16_t* p = acc.data();
for (int j = 0; j < nAdds; j++)
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
p[i] = static_cast<int16_t>(p[i] + adds[j][i]);
for (int j = 0; j < nSubs; j++)
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
p[i] = static_cast<int16_t>(p[i] - subs[j][i]);
}
void AddRow(Accumulator& acc, const int16_t* row) {
const int16_t* rows[1] = {row};
ApplyInPlace(acc, rows, 1, nullptr, 0);
}
#endif
}
+9 -79
View File
@@ -1,7 +1,4 @@
#pragma once
#include <array>
#include <vector>
#include <cstdint>
#include "nnue.h"
namespace ACC {
@@ -14,85 +11,18 @@ struct BucketPair {
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
struct AccumulatorPair {
alignas(ALIGNMENT) Accumulator white;
alignas(ALIGNMENT) Accumulator black;
alignas(32) Accumulator white;
alignas(32) Accumulator black;
bool mirroredWhite = false;
bool mirroredBlack = false;
Accumulator& get(bool perspective) { return perspective ? black : white; }
const Accumulator& get(bool perspective) const { return perspective ? black : white; }
};
enum class UpdateType : uint8_t {
None,
Refresh,
Copy,
Delta
};
struct Update {
UpdateType type = UpdateType::None;
uint8_t refreshMask = 0;
bool stm = false;
bool sub2Opp = false;
uint8_t nAdd = 0, nSub = 0;
int8_t add1 = 0, addPT1 = 0, add2 = 0, addPT2 = 0;
int8_t sub1 = 0, subPT1 = 0, sub2 = 0, subPT2 = 0;
void setAddSub(bool s, int add, int addPT, int sub, int subPT) {
type = UpdateType::Delta;
stm = s; sub2Opp = false; nAdd = 1; nSub = 1;
add1 = add; addPT1 = addPT; sub1 = sub; subPT1 = subPT;
}
void setAddSubSub(bool s, int add, int addPT, int sub1_, int subPT1_, int sub2_, int subPT2_) {
type = UpdateType::Delta;
stm = s; sub2Opp = true; nAdd = 1; nSub = 2;
add1 = add; addPT1 = addPT;
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
}
void setAddAddSubSub(bool s, int add1_, int addPT1_, int add2_, int addPT2_, int sub1_, int subPT1_, int sub2_, int subPT2_) {
type = UpdateType::Delta;
stm = s; sub2Opp = false; nAdd = 2; nSub = 2;
add1 = add1_; addPT1 = addPT1_; add2 = add2_; addPT2 = addPT2_;
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
}
void setRefresh() {
*this = Update();
type = UpdateType::Refresh;
}
};
struct FinnyEntry {
alignas(ALIGNMENT) Accumulator acc;
uint64_t bb[2][6];
};
struct FinnyTable {
FinnyEntry entries[2][2][NNUE::INPUT_BUCKETS];
void Reset();
};
struct AccStack {
std::vector<AccumulatorPair> slots;
std::vector<const AccumulatorPair*> cur;
FinnyTable finny;
explicit AccStack(size_t n) : slots(n), cur(n, nullptr) { finny.Reset(); }
AccStack(const AccStack& other) : AccStack(other.slots.size()) {}
AccStack& operator=(const AccStack&) { return *this; }
// yoinked from Quinniboi - Prelude
void addSub(bool stm, int add, int addPT, int sub, int subPT, BucketPair bp);
void addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp);
void addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2, BucketPair bp);
};
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored);
const int16_t* Row(int bucket, int index);
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2);
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs);
void AddRow(Accumulator& acc, const int16_t* row);
}
+99 -139
View File
@@ -1,4 +1,3 @@
#include <bit>
#include "board.h"
#include "accumulator.h"
#include "movegen.h"
@@ -31,9 +30,7 @@ void Board::Reset() {
pieces = std::array<Bitboard, 6>();
colors = std::array<Bitboard, 2>();
accUpdate.setRefresh();
mirroredWhite = false;
mirroredBlack = false;
accPair = ACC::AccumulatorPair();
pieceThreats = std::array<Bitboard, 6>();
colorThreats = std::array<Bitboard, 2>();
@@ -48,6 +45,7 @@ void Board::Reset() {
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
minorKey = 0ULL;
checkZones = std::array<Bitboard, 4>();
}
@@ -55,6 +53,7 @@ void Board::Reset() {
void Board::SetByFen(std::string_view fen) {
Reset();
// Starting from top left
int currSquare = a8;
std::vector<std::string> tokens = UTILS::split(fen, ' ');
@@ -90,6 +89,7 @@ void Board::SetByFen(std::string_view fen) {
if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]);
// full and half move
if (tokens.size() > 4) {
halfMoves = std::stoi(tokens[4]);
fullMoves = std::stoi(tokens[5]);
@@ -98,6 +98,7 @@ void Board::SetByFen(std::string_view fen) {
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
minorKey = 0ULL;
occupied = colors[White] | colors[Black];
hashKey = UTILS::GetHashKey(*this);
@@ -111,13 +112,13 @@ void Board::SetByFen(std::string_view fen) {
int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8;
if (whiteKingFile > 3) {
mirroredWhite = true;
accPair.mirroredWhite = true;
}
if (blackKingFile > 3) {
mirroredBlack = true;
accPair.mirroredBlack = true;
}
accUpdate.setRefresh();
ResetAccPair();
}
std::string Board::GetFen() {
@@ -311,6 +312,8 @@ void Board::SetPiece(int piece, int square, bool color) {
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
} else if (piece == Knight || piece == Bishop) {
minorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
@@ -331,12 +334,16 @@ void Board::RemovePiece(int piece, int square, bool color) {
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
} else if (piece == Knight || piece == Bishop) {
minorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
// Updates castling rights
static void UpdateCastlingRights(Board &board, int square, int type, int color) {
if (type == Rook) {
// Removing old rights
board.hashKey ^= UTILS::zCastle[board.castlingRights];
int queenSideRook = color ? a8 : a1;
int kingSideRook = color ? h8 : h1;
@@ -349,6 +356,7 @@ static void UpdateCastlingRights(Board &board, int square, int type, int color)
board.hashKey ^= UTILS::zCastle[board.castlingRights];
} else if (type == King) {
// Removing old rights
board.hashKey ^= UTILS::zCastle[board.castlingRights];
board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight;
@@ -369,13 +377,8 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) {
}
void Board::MakeMove(Move move) {
const bool accParentClean = accUpdate.type == ACC::UpdateType::None;
accUpdate = ACC::Update();
// Null Move
if (!move) {
if (accParentClean) accUpdate.type = ACC::UpdateType::Copy;
else accUpdate.setRefresh();
int newEpTarget = noEPTarget;
sideToMove = !sideToMove;
@@ -400,28 +403,30 @@ void Board::MakeMove(Move move) {
int endPiece = attackerPiece;
uint8_t refreshMask = 0;
bool fullRecalc = false;
const auto bucketPair = GetBuckets();
if (attackerPiece == King) {
const int toFile = move.MoveTo() % 8;
if (attackerColor == White) {
if ((toFile > 3) != mirroredWhite) {
mirroredWhite = !mirroredWhite;
refreshMask |= 1 << White;
if ((toFile > 3) != accPair.mirroredWhite) {
accPair.mirroredWhite = !accPair.mirroredWhite;
fullRecalc = true;
}
} else {
if ((toFile > 3) != mirroredBlack) {
mirroredBlack = !mirroredBlack;
refreshMask |= 1 << Black;
if ((toFile > 3) != accPair.mirroredBlack) {
accPair.mirroredBlack = !accPair.mirroredBlack;
fullRecalc = true;
}
}
if (NNUE::kingBuckets[attackerColor][move.MoveFrom()] != NNUE::kingBuckets[attackerColor][move.MoveTo()]) {
refreshMask |= 1 << attackerColor;
fullRecalc = true;
}
}
// Removing attacker piece from old position
RemovePiece(attackerPiece, move.MoveFrom(), attackerColor);
if (move.IsPromo()) {
@@ -433,16 +438,16 @@ void Board::MakeMove(Move move) {
}
}
{
if (!fullRecalc) {
if (move.IsCapture()) {
if (move.GetFlags() != epCapture) {
accUpdate.setAddSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece);
accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece, bucketPair);
} else {
accUpdate.setAddSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn);
accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn, bucketPair);
}
} else {
if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) {
accUpdate.setAddSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece);
accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, bucketPair);
}
}
}
@@ -471,14 +476,16 @@ void Board::MakeMove(Move move) {
{
int rookSquare = attackerColor ? h8 : h1;
// Removing rook from old position
RemovePiece(Rook, rookSquare, attackerColor);
// Setting rook on new position
SetPiece(Rook, rookSquare - 2, attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook);
if (!fullRecalc) {
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair);
}
break;
@@ -487,14 +494,16 @@ void Board::MakeMove(Move move) {
{
int rookSquare = attackerColor ? a8 : a1;
// Removing rook from old position
RemovePiece(Rook, rookSquare, attackerColor);
// Setting rook on new position
SetPiece(Rook, rookSquare + 3, attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook);
if (!fullRecalc) {
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook, bucketPair);
}
break;
@@ -503,12 +512,11 @@ void Board::MakeMove(Move move) {
break;
}
if (!accParentClean || accUpdate.type == ACC::UpdateType::None) {
accUpdate.setRefresh();
} else {
accUpdate.refreshMask = refreshMask;
if (fullRecalc) {
ResetAccPair();
}
// Removing the right to castle on king and rook movement
UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor);
sideToMove = !attackerColor;
@@ -529,6 +537,13 @@ void Board::MakeMove(Move move) {
checkers = CalcCheckers();
CalcCheckZones();
/*
sideToMove = !sideToMove;
if (InCheck()) {
return false;
}
sideToMove = !sideToMove;
*/
if (attackerColor == Black) fullMoves++;
if (attackerPiece == Pawn || move.IsCapture()) {
@@ -543,6 +558,7 @@ void Board::MakeMove(Move move) {
bool Board::InPossibleZug() {
Bitboard toCheck;
// For all pieces other than pawns and king
for (int piece = Knight; piece <= Queen; piece++) {
toCheck |= (pieces[piece] & colors[sideToMove]);
}
@@ -557,141 +573,68 @@ ACC::BucketPair Board::GetBuckets() {
return {NNUE::kingBuckets[White][wKingSq],NNUE::kingBuckets[Black][bKingSq]};
}
void Board::RefreshAccumulator(ACC::AccumulatorPair& out) const {
const int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
const int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
const ACC::BucketPair bucketPair = {NNUE::kingBuckets[White][wKingSq], NNUE::kingBuckets[Black][bKingSq]};
void Board::ResetAccPair() {
Bitboard whitePieces = colors[White];
Bitboard blackPieces = colors[Black];
out.white = NNUE::net.accumulator_biases;
out.black = NNUE::net.accumulator_biases;
accPair.white = NNUE::net.accumulator_biases;
accPair.black = NNUE::net.accumulator_biases;
for (int color = White; color <= Black; color++) {
Bitboard bb = colors[color];
const auto bucketPair = GetBuckets();
while (bb) {
int square = bb.getLS1BIndex();
while (whitePieces) {
int square = whitePieces.getLS1BIndex();
int wInput = ACC::CalculateIndex(White, color, mailbox[square], square, mirroredWhite);
int bInput = ACC::CalculateIndex(Black, color, mailbox[square], square, mirroredBlack);
int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square, accPair.mirroredWhite);
int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square, accPair.mirroredBlack);
ACC::AddRow(out.white, &NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE]);
ACC::AddRow(out.black, &NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE]);
bb.PopBit(square);
for (int i = 0; i < NNUE::HL_SIZE; i++) {
accPair.white[i] += NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE + i];
accPair.black[i] += NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE + i];
}
whitePieces.PopBit(square);
}
}
void Board::RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const {
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
const int bucket = NNUE::kingBuckets[perspective][kingSq];
while (blackPieces) {
int square = blackPieces.getLS1BIndex();
ACC::FinnyEntry& entry = finny.entries[perspective][mirrored][bucket];
int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square, accPair.mirroredWhite);
int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square, accPair.mirroredBlack);
const int16_t* adds[32];
const int16_t* subs[32];
int nAdds = 0;
int nSubs = 0;
for (int color = White; color <= Black; color++) {
for (int pt = Pawn; pt <= King; pt++) {
Bitboard tmp = pieces[pt] & colors[color];
const uint64_t now = tmp;
const uint64_t old = entry.bb[color][pt];
uint64_t added = now & ~old;
uint64_t removed = old & ~now;
while (added) {
const int square = std::countr_zero(added);
added &= added - 1;
adds[nAdds++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
}
while (removed) {
const int square = std::countr_zero(removed);
removed &= removed - 1;
subs[nSubs++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
}
entry.bb[color][pt] = now;
for (int i = 0; i < NNUE::HL_SIZE; i++) {
accPair.white[i] += NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE + i];
accPair.black[i] += NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE + i];
}
blackPieces.PopBit(square);
}
ACC::ApplyInPlace(entry.acc, adds, nAdds, subs, nSubs);
out = entry.acc;
}
void Board::ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const {
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
const int bucket = NNUE::kingBuckets[perspective][kingSq];
const bool stm = accUpdate.stm;
const int16_t* a1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT1, accUpdate.add1, mirrored));
const int16_t* a2 = nullptr;
const int16_t* s1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.subPT1, accUpdate.sub1, mirrored));
const int16_t* s2 = nullptr;
if (accUpdate.nAdd == 2)
a2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT2, accUpdate.add2, mirrored));
if (accUpdate.nSub == 2)
s2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, accUpdate.sub2Opp ? !stm : stm, accUpdate.subPT2, accUpdate.sub2, mirrored));
ACC::Apply(dst, src, a1, a2, s1, s2);
}
void Board::UpdateAccumulator(ACC::AccStack& stack, int ply) {
using ACC::UpdateType;
if (accUpdate.type == UpdateType::None) return;
if (accUpdate.type == UpdateType::Copy && ply > 0) {
stack.cur[ply] = stack.cur[ply - 1];
accUpdate.type = UpdateType::None;
return;
}
ACC::AccumulatorPair& dst = stack.slots[ply];
if (ply == 0 || accUpdate.type != UpdateType::Delta) {
RefreshPerspective(stack.finny, White, dst.white);
RefreshPerspective(stack.finny, Black, dst.black);
} else {
const ACC::AccumulatorPair& prev = *stack.cur[ply - 1];
for (int perspective = White; perspective <= Black; perspective++) {
if (accUpdate.refreshMask & (1 << perspective))
RefreshPerspective(stack.finny, perspective, dst.get(perspective));
else
ApplyDeltaPerspective(perspective, dst.get(perspective), prev.get(perspective));
}
}
stack.cur[ply] = &dst;
accUpdate.type = UpdateType::None;
}
Bitboard Board::AttacksTo(int square, Bitboard occupancy) {
Bitboard attacks;
// Pawn attacks
// Opponent attacks
attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]);
// Own piece attacks
attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]);
// Knight
attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]);
// King
attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]);
Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy);
Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy);
// Rook or queen
attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen]));
// Bishop or queen
attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen]));
return attacks;
@@ -706,6 +649,7 @@ static Bitboard rayBetween(int sq1, int sq2) {
int df = (f2 > f1) - (f2 < f1);
int dr = (r2 > r1) - (r2 < r1);
// must be same rank, file, or diagonal
if (df != 0 && dr != 0 && std::abs(f2 - f1) != std::abs(r2 - r1))
return 0ULL;
@@ -725,6 +669,7 @@ static Bitboard rayBetween(int sq1, int sq2) {
return ray;
}
// Returns the full ray from `from` in the direction of `to`, to the edge of the board
static Bitboard fullRay(int from, int to) {
int df = (to % 8) - (from % 8);
int dr = (to / 8) - (from / 8);
@@ -846,6 +791,7 @@ bool Board::IsPseudoLegal(Move &move) {
const int to = move.MoveTo();
const int flag = move.GetFlags();
// basic bounds
if ((unsigned)from >= 64u || (unsigned)to >= 64u) return false;
const int us = sideToMove;
@@ -859,14 +805,18 @@ bool Board::IsPseudoLegal(Move &move) {
const bool isCapture = move.IsCapture();
const int targetPiece = GetPieceType(to);
// capture consistency (except EP which captures "behind")
if (flag == capture) {
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (isCapture && flag != epCapture) {
// promo-capture also lands on occupied enemy square
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (!isCapture) {
// quiet moves must not land on occupied square
if (occupied.IsSet(to)) {
// except castling (king lands on empty anyway)
if (flag != kingCastle && flag != queenCastle) return false;
}
}
@@ -883,10 +833,12 @@ bool Board::IsPseudoLegal(Move &move) {
};
auto isPawnCaptureTo = [&] {
// diagonal one step forward
return (to == from + dir - 1 && toFile == fromFile - 1)
|| (to == from + dir + 1 && toFile == fromFile + 1);
};
// handle specials by flag first
switch (flag) {
case quiet:
case capture:
@@ -894,9 +846,10 @@ bool Board::IsPseudoLegal(Move &move) {
case doublePawnPush: {
if (movingPiece != Pawn) return false;
if (!us) {
// from must be on starting rank
if (!us) { // white
if (fromRank != 1) return false;
} else {
} else { // black
if (fromRank != 6) return false;
}
const int mid = from + dir;
@@ -911,6 +864,7 @@ bool Board::IsPseudoLegal(Move &move) {
if (to != enPassantTarget) return false;
if (!isPawnCaptureTo()) return false;
// target square is empty, captured pawn is behind to
const int capSq = to - dir;
if (!colors[them].IsSet(capSq)) return false;
if (GetPieceType(capSq) != Pawn) return false;
@@ -935,6 +889,7 @@ bool Board::IsPseudoLegal(Move &move) {
const int targetSq = us ? g8 : g1;
if (to != targetSq) return false;
// must be exactly king+rook on that side and no attacked transit squares
if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
@@ -952,9 +907,11 @@ bool Board::IsPseudoLegal(Move &move) {
}
default:
// promotions (quiet + capture)
if (!move.IsPromo()) return false;
if (movingPiece != Pawn) return false;
// must land on last rank
if (!us) {
if (toRank != 7) return false;
} else {
@@ -970,13 +927,16 @@ bool Board::IsPseudoLegal(Move &move) {
return true;
}
// normal piece movement checks for quiet/capture (non-special)
switch (movingPiece) {
case Pawn: {
// non-promo pawns cannot land on last rank
if (!us) { if (toRank == 7) return false; }
else { if (toRank == 0) return false; }
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
// (regular capture already checked occupancy/enemy above)
return true;
} else {
return isOneStepPawnPush();
+4 -9
View File
@@ -26,9 +26,7 @@ public:
std::array<Bitboard, 2> pinned;
Bitboard checkers;
ACC::Update accUpdate;
bool mirroredWhite = false;
bool mirroredBlack = false;
ACC::AccumulatorPair accPair;
std::array<Bitboard, 6> pieceThreats;
std::array<Bitboard, 2> colorThreats;
@@ -50,6 +48,7 @@ public:
U64 pawnKey = 0ULL;
U64 nonPawnKey = 0ULL;
U64 majorKey = 0ULL;
U64 minorKey = 0ULL;
std::array<Bitboard, 4> checkZones;
@@ -65,11 +64,7 @@ public:
void ListMoves();
ACC::BucketPair GetBuckets();
void RefreshAccumulator(ACC::AccumulatorPair& out) const;
void UpdateAccumulator(ACC::AccStack& stack, int ply);
void RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const;
void ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const;
void MarkAccumulatorDirty() { accUpdate.setRefresh(); }
void ResetAccPair();
int GetPieceType(int square);
int GetPieceColor(int square);
@@ -96,4 +91,4 @@ public:
bool IsLegal(Move &move);
bool IsPseudoLegal(Move &move);
};
};
+131 -41
View File
@@ -13,10 +13,8 @@
#include <csignal>
#include <cstdlib>
#include <cerrno>
#include <vector>
#include "datagen.h"
#include "datagenui.h"
#include "movegen.h"
#include "search.h"
#include "utils.h"
@@ -279,8 +277,7 @@ static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) {
}
}
static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& basePath, int& fileCounter,
std::atomic<int>& files) {
static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& basePath, int& fileCounter) {
if (gamesBuffer.empty()) return;
int32_t zeroes = 0;
@@ -333,7 +330,6 @@ static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& baseP
return;
}
files.fetch_add(1, std::memory_order_relaxed);
fileCounter++;
}
@@ -399,7 +395,7 @@ static std::string MergeThreadFiles() {
return finalFileName;
}
static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag) {
static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& stopFlag) {
std::vector<Game> gamesBuffer;
gamesBuffer.reserve(GAME_BUFFER);
@@ -420,15 +416,9 @@ static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag)
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;
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;
}
if (std::abs(startingScore) >= evenityMargin) continue;
ctx->nodes = 0;
@@ -443,9 +433,7 @@ static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag)
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;
@@ -456,7 +444,7 @@ static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag)
board.MakeMove(results.bestMove);
ctx->positionHistory[board.positionIndex] = board.hashKey;
stats.positions.fetch_add(1, std::memory_order_relaxed);
positions++;
MOVEGEN::GenerateMoves<All>(board, true);
}
@@ -467,22 +455,21 @@ static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag)
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, stats.files);
WriteToFile(gamesBuffer, basePath, fileCounter);
gamesBuffer.clear();
}
}
} catch (...) {
if (!gamesBuffer.empty()) {
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
WriteToFile(gamesBuffer, basePath, fileCounter);
}
throw;
}
if (!gamesBuffer.empty()) {
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
WriteToFile(gamesBuffer, basePath, fileCounter);
gamesBuffer.clear();
}
@@ -495,23 +482,23 @@ static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag)
struct WinThreadArgs {
int id;
DatagenStats* stats;
std::atomic<int>* positions;
std::atomic<bool>* stopFlag;
};
static unsigned __stdcall WinThreadEntry(void* p) {
std::unique_ptr<WinThreadArgs> args(static_cast<WinThreadArgs*>(p));
PlayGames(args->id, *args->stats, *args->stopFlag);
PlayGames(args->id, *args->positions, *args->stopFlag);
_endthreadex(0);
return 0;
}
static bool CreateWorkerThread(int id,
DatagenStats& stats,
std::atomic<int>& positions,
std::atomic<bool>& stopFlag,
std::vector<HANDLE>& threads,
size_t stackSizeBytes) {
auto* args = new WinThreadArgs{ id, &stats, &stopFlag };
auto* args = new WinThreadArgs{ id, &positions, &stopFlag };
unsigned tid = 0;
HANDLE h = reinterpret_cast<HANDLE>(
@@ -548,7 +535,7 @@ static void JoinWorkerThreads(std::vector<HANDLE>& threads) {
#else
static void* ThreadFunc(void* arg) {
auto* tup = static_cast<std::tuple<int, DatagenStats*, std::atomic<bool>*>*>(arg);
auto* tup = static_cast<std::tuple<int, std::atomic<int>*, std::atomic<bool>*>*>(arg);
PlayGames(std::get<0>(*tup), *std::get<1>(*tup), *std::get<2>(*tup));
delete tup;
return nullptr;
@@ -567,7 +554,7 @@ void Run(int targetPositions, int threads) {
HideCursor();
#endif
DatagenStats stats;
std::atomic<int> positions = 0;
std::atomic<bool> stopFlag = false;
#ifdef _WIN32
@@ -577,7 +564,7 @@ void Run(int targetPositions, int threads) {
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
for (int i = 0; i < threads - 1; ++i) {
CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes);
CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes);
}
#else
std::vector<pthread_t> workerThreads;
@@ -587,7 +574,7 @@ void Run(int targetPositions, int threads) {
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
auto* args = new std::tuple<int, DatagenStats*, std::atomic<bool>*>(i, &stats, &stopFlag);
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
pthread_t thread;
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
@@ -602,13 +589,12 @@ void Run(int targetPositions, int threads) {
#endif
Stopwatch sw;
while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) {
PrintProgress(stats, targetPositions, sw, threads);
while (positions < targetPositions && !g_shutdownRequested) {
PrintProgress(positions, targetPositions, sw, threads);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(stats, targetPositions, sw, threads);
PrintSummary(stats, targetPositions, sw, threads);
PrintProgress(positions, targetPositions, sw, threads);
stopFlag = true;
@@ -690,7 +676,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
HideCursor();
#endif
DatagenStats stats;
std::atomic<int> positions = 0;
std::atomic<bool> stopFlag = false;
#ifdef _WIN32
@@ -700,7 +686,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, stats, stopFlag, workerThreads, stackSizeBytes);
CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes);
}
#else
std::vector<pthread_t> workerThreads;
@@ -710,7 +696,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, DatagenStats*, std::atomic<bool>*>(i, &stats, &stopFlag);
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
pthread_t thread;
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
@@ -725,13 +711,12 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
#endif
Stopwatch sw;
while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) {
PrintProgress(stats, targetPositions, sw, threads);
while (positions < targetPositions && !g_shutdownRequested) {
PrintProgress(positions, targetPositions, sw, threads);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(stats, targetPositions, sw, threads);
PrintSummary(stats, targetPositions, sw, threads);
PrintProgress(positions, targetPositions, sw, threads);
stopFlag = true;
@@ -765,7 +750,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, stats.positions.load())) {
if (UploadFile(uploadUrl, mergedFile, username, positions.load())) {
std::cout << "Upload successful!" << std::endl;
std::error_code ec;
@@ -787,4 +772,109 @@ void RunOnline(const std::string& username, int targetPositions, int threads) {
std::cout << "\nOnline mode shutdown complete." << std::endl;
}
} // namespace DATAGEN
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
+2 -10
View File
@@ -1,7 +1,6 @@
#pragma once
#include "board.h"
#include "utils.h"
#include <atomic>
#include <fstream>
#include "stopwatch.h"
@@ -12,15 +11,6 @@ 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)
@@ -72,4 +62,6 @@ 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
@@ -1,639 +0,0 @@
#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
@@ -1,11 +0,0 @@
#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
+6 -63
View File
@@ -5,13 +5,9 @@
#include "benchmark.h"
#include "search.h"
#include "datagen.h"
#include "datagenui.h"
#include "nnue.h"
#include "tests.h"
#include <iostream>
#include <string>
#ifndef EVALFILE
#define EVALFILE "./nnue.bin"
#endif
@@ -33,30 +29,6 @@
INCBIN(EVAL, EVALFILE);
#endif
// 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;
}
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";
}
int main(int argc, char* argv[]) {
auto loadDefaultNet = [&]([[maybe_unused]] bool warnMSVC = false) {
#if defined(_MSC_VER) && !defined(__clang__)
@@ -81,56 +53,27 @@ int main(int argc, char* argv[]) {
SEARCH::InitLMRTable();
#endif
Board board;
Board board;
if (argc > 1) {
if (std::string(argv[1]) == "bench") {
RunBenchmark();
} else if (std::string(argv[1]) == "datagen") {
if (argc > 2) {
const std::string arg = argv[2];
if (arg == "--help" || arg == "-h" || arg == "help") {
DATAGEN::PrintUsage();
return 0;
}
}
int positions = 1;
int threads = 1;
std::string username = "";
if (argc > 2) {
positions = ParsePositiveInt(argv[2]);
if (positions == 0) {
ArgError(argv[2], "positions");
return 1;
}
positions *= 1000;
positions = std::stoi(argv[2]) * 1000;
if (argc > 3) {
threads = ParsePositiveInt(argv[3]);
if (threads == 0) {
ArgError(argv[3], "threads");
return 1;
}
threads = std::stoi(argv[3]);
if (argc > 4) {
username = argv[4];
}
}
}
// Only the main thread renders, so it never generates anything.
// Checked outside the argc guards so a bare "datagen" is caught too.
if (threads < 2) {
std::cerr << "error: threads must be at least 2 (got " << threads
<< "). The main thread only renders the progress"
<< " screen, so " << threads << " leaves no worker to generate.\n"
<< "\nRun 'Eleanor datagen --help' for usage.\n";
return 1;
}
if (!username.empty()) {
DATAGEN::RunOnline(username, positions, threads);
} else {
+16 -13
View File
@@ -15,22 +15,26 @@ void Network::Load(const std::string& path) {
std::cerr << "Failed to open file " + path << std::endl;
}
// HL weights
for (size_t i = 0; i < accumulator_weights.size(); i++) {
for (size_t j = 0; j < accumulator_weights[i].size(); j++) {
file.read(reinterpret_cast<char*>(&accumulator_weights[i][j]), sizeof(int16_t));
}
}
// HL biases
for (size_t i = 0; i < accumulator_biases.size(); i++) {
file.read(reinterpret_cast<char*>(&accumulator_biases[i]), sizeof(int16_t));
}
// Output weights
for (size_t i = 0; i < output_weights.size(); i++) {
for (size_t j = 0; j < output_weights[i].size(); j++) {
file.read(reinterpret_cast<char*>(&output_weights[i][j]), sizeof(int16_t));
}
}
// Output biases
for (size_t i = 0; i < output_bias.size(); i++) {
file.read(reinterpret_cast<char*>(&output_bias[i]), sizeof(int16_t));
}
@@ -131,12 +135,12 @@ using nativeVector = void*;
#endif
static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair& acc, const Network& net, size_t outputBucket) {
static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t outputBucket) {
const size_t VECTOR_SIZE = sizeof(nativeVector) / sizeof(int16_t);
static_assert(HL_SIZE % VECTOR_SIZE == 0, "HL size must be divisible by the native register size of your CPU for vectorization to work");
const ACC::Accumulator& stmAcc = board.sideToMove == White ? acc.white : acc.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? acc.white : acc.black;
const ACC::Accumulator& stmAcc = board.sideToMove == White ? board.accPair.white : board.accPair.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? board.accPair.white : board.accPair.black;
const nativeVector VEC_QA = set1_epi16(QA);
const nativeVector VEC_ZERO = set1_epi16(0);
@@ -144,15 +148,19 @@ static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair&
nativeVector accumulator{};
for (int i = 0; i < HL_SIZE; i += VECTOR_SIZE) {
// Load accumulators
const nativeVector stmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&stmAcc[i]));
const nativeVector nstmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&nstmAcc[i]));
// Clamp values
const nativeVector stmClamped = min_epi16(VEC_QA, max_epi16(stmAccumValues, VEC_ZERO));
const nativeVector nstmClamped = min_epi16(VEC_QA, max_epi16(nstmAccumValues, VEC_ZERO));
// Load weights
const nativeVector stmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i]));
const nativeVector nstmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i + HL_SIZE]));
// SCReLU activation
const nativeVector stmActivated = madd_epi16(stmClamped, mullo_epi16(stmClamped, stmWeights));
const nativeVector nstmActivated = madd_epi16(nstmClamped, mullo_epi16(nstmClamped, nstmWeights));
@@ -163,13 +171,13 @@ static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair&
return reduce_epi32(accumulator);
}
static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Network& net) {
int Forward(const Board& board, const Network& net) {
const size_t divisor = 32 / OUTPUT_BUCKETS;
const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor;
int64_t eval = 0;
eval = VectorizedSCReLU(board, acc, net, outputBucket);
eval = VectorizedSCReLU(board, net, outputBucket);
eval /= QA;
@@ -179,21 +187,16 @@ static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Ne
return (eval * SCALE) / (QA * QB);
}
int16_t Network::Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen) {
int16_t Network::Evaluate(const Board& board, bool datagen) {
// Disabled in datagen
const int materialScale = datagen ? 4096 : 2048
+ 90 * board.pieces[Knight].PopCount()
+ 90 * board.pieces[Bishop].PopCount()
+ 180 * board.pieces[Rook].PopCount()
+ 360 * board.pieces[Queen].PopCount();
return std::clamp(Forward(board, acc, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
return std::clamp(Forward(board, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
(SEARCH::MATE_SCORE - SEARCH::MAX_DEPTH));
}
int16_t Network::Evaluate(const Board& board, bool datagen) {
ACC::AccumulatorPair acc;
board.RefreshAccumulator(acc);
return Evaluate(board, acc, datagen);
}
}
-6
View File
@@ -5,10 +5,6 @@
class Board;
namespace ACC {
struct AccumulatorPair;
}
#ifdef __AVX512F__
constexpr size_t ALIGNMENT = 64;
#else
@@ -58,8 +54,6 @@ struct Network {
void Load(const std::string& path);
int16_t Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen = false);
int16_t Evaluate(const Board& board, bool datagen = false);
};
+50 -45
View File
@@ -89,10 +89,12 @@ static int AdjustEval(Board &board, SearchContext* ctx, int eval) {
static bool IsTwoFold(Board &board, SearchContext* ctx) {
for (int i = 0; i < board.positionIndex; i++) {
if (ctx->positionHistory[i] == board.hashKey) {
// repetition found
return true;
}
}
// no repetition
return false;
}
@@ -113,6 +115,7 @@ template <bool isPV>
static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, bool improving, bool corrplexity, bool ttpv, bool ttpvFailLow, SearchContext* ctx) {
int reduction = 0;
// Late Move Reduction
reduction = lmrTable[move.IsQuiet()][depth][moveSeen] * 1024;
if (cutnode)
@@ -133,6 +136,7 @@ static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int
if (ttpvFailLow)
reduction += lmrTTPVFailLow;
// History LMR
int historyReduction = 0;
if (move.IsQuiet()) {
@@ -173,6 +177,7 @@ bool SEE(Board& board, Move& move, int threshold) {
int nextVictim = board.GetPieceType(from);
// Next victim is moved piece or promo piece
if (move.IsPromo()) {
nextVictim = move.GetPromoPiece();
}
@@ -265,42 +270,24 @@ static bool IsLoss(int score) {
return score < -WIN_SCORE;
}
template <searchMode mode>
static inline int StaticEval(Board& board, SearchContext* ctx, int ply) {
board.UpdateAccumulator(ctx->accStack, ply);
#ifdef ACC_VERIFY
{
ACC::AccumulatorPair ref;
board.RefreshAccumulator(ref);
if (ref.white != ctx->accStack.cur[ply]->white || ref.black != ctx->accStack.cur[ply]->black) {
std::cerr << "ACC MISMATCH ply " << ply << " fen " << board.GetFen() << std::endl;
std::abort();
}
}
#endif
return NNUE::net.Evaluate(board, *ctx->accStack.cur[ply], mode == datagen);
}
template <bool isPV, searchMode mode>
static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext* ctx) {
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return StaticEval<mode>(board, ctx, ply);
return NNUE::net.Evaluate(board, mode == datagen);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
int bestScore = AdjustEval(board, ctx, StaticEval<mode>(board, ctx, ply));
int bestScore = AdjustEval(board, ctx, NNUE::net.Evaluate(board, mode == datagen));
ctx->ss[ply].eval = bestScore;
TTEntry entry;
bool ttHit = false;
entry = ctx->TT->GetEntry(board.hashKey);
if (entry.hashKey == PackHashKey(board.hashKey) && entry.depth > 0) {
if (entry.hashKey == board.hashKey) {
ttHit = true;
switch (entry.nodeType) {
@@ -309,11 +296,9 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
case CutNode:
if (entry.score >= beta)
return entry.score;
break;
case AllNode:
if (entry.score <= alpha)
return entry.score;
break;
}
}
@@ -323,15 +308,12 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
switch (entry.nodeType) {
case PV:
bestScore = entry.score;
break;
case CutNode:
if (entry.score > bestScore)
bestScore = entry.score;
break;
case AllNode:
if (entry.score < bestScore)
bestScore = entry.score;
break;
}
}
@@ -356,6 +338,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
Move currMove;
while ((currMove = mp.Next())) {
if (!IsLoss(bestScore)) {
// QS FP
if (!inCheck && currMove.IsCapture() &&
fpScore <= alpha && !SEE(board, currMove, 1)) {
@@ -386,7 +369,6 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
int score = -Quiescence<isPV, mode>(copy, -beta, -alpha, ply + 1, ctx).score;
if (score >= beta) {
if (searchStopped.load(std::memory_order_relaxed)) return 0;
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
return score;
}
@@ -411,7 +393,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return StaticEval<mode>(board, ctx, ply);
return NNUE::net.Evaluate(board, mode == datagen);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
@@ -423,12 +405,13 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (!ctx->excluded)
entry = ctx->TT->GetEntry(board.hashKey);
const bool ttHit = entry.hashKey == PackHashKey(board.hashKey) && entry.depth >= depth;
const bool ttHit = entry.hashKey == board.hashKey;
const bool ttpv = isPV | entry.ttpv;
if constexpr (!isPV) {
if (ttHit) {
if (((entry.nodeType == PV) ||
if (entry.depth >= depth &&
((entry.nodeType == PV) ||
(entry.nodeType == AllNode && entry.score <= alpha) ||
(entry.nodeType == CutNode && entry.score >= beta))) {
@@ -439,7 +422,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (depth <= 0) return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx);
int rawEval = StaticEval<mode>(board, ctx, ply);
int rawEval = NNUE::net.Evaluate(board, mode == datagen);
const int staticEval = AdjustEval(board, ctx, rawEval);
ctx->ss[ply].eval = staticEval;
@@ -471,6 +454,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (!inCheck && !ctx->excluded) {
if (ply) {
// Reverse Futility Pruning
int margin = rfpBase + rfpMargin * (depth - improving);
if (!ttpv && ttAdjustedEval - margin >= beta && depth < 7) {
return !IsDecisive(ttAdjustedEval) && !IsDecisive(beta)
@@ -478,10 +462,12 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
: ttAdjustedEval;
}
// Razoring
if (!isPV && depth <= 3 && staticEval + razoringScalar * depth < alpha && entry.nodeType != CutNode) {
return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx).score;
}
// Null Move Pruning
if (ply > ctx->minNmpPly && ttAdjustedEval >= beta + nmpBetaMargin) {
if (depth > 1 && !board.InPossibleZug()) {
Board copy = board;
@@ -514,6 +500,7 @@ 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);
@@ -577,6 +564,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ctx->killerMoves[ply + 1] = Move();
// Move-loop
Move currMove;
while ((currMove = mp.Next())) {
@@ -586,6 +574,9 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
bool notMated = results.score > (-MATE_SCORE + MAX_DEPTH);
int lmrDepth = depth - lmrTable[currMove.IsQuiet()][depth][moveSeen];
// Late move pruning
// If we are near a leaf node we prune moves
// that are late in the list
if (currMove.IsQuiet() && notMated) {
int lmpThreshold = 7 + depth * depth * (1 + improving);
@@ -603,6 +594,9 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ply > 0) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 1);
if (ply > 1) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 2);
// Futility pruning
// If our static eval is far below alpha, there is only a small chance
// that a quiet move will help us so we skip them
int margin = fpMargin * (lmrDepth + improving) + historyScore / 32;
if (!isPV && ply && currMove.IsQuiet()
@@ -610,9 +604,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
continue;
}
// PVS SEE
int SEEThreshold = currMove.IsQuiet() ? seeQuietThreshold * depth : seeNoisyThreshold * depth * depth;
if (ply && depth <= 10 && notMated && !SEE(board, currMove, SEEThreshold))
if (ply && depth <= 10 && !SEE(board, currMove, SEEThreshold))
continue;
@@ -620,6 +615,14 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
Board copy = board;
copy.MakeMove(currMove);
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
ctx->TT->PrefetchEntry(copy.hashKey);
@@ -639,18 +642,22 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
const int singularScore = PVS<false, mode>(board, sDepth, sBeta-1, sBeta, ply, ctx, cutnode).score;
ctx->excluded = Move();
// Singular extension
if (singularScore < sBeta) {
extension++;
if constexpr (!isPV) {
// Double extension
if (singularScore <= sBeta - 1 - doubleExtMargin) {
extension++;
}
}
}
// Multicut
else if (sBeta >= beta) {
return sBeta;
}
// Negative extension
else if (entry.score >= beta) {
extension--;
} else if (cutnode) {
@@ -663,14 +670,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
cutnode |= extension < 0;
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
int newDepth = depth + (copy.InCheck() && !ctx->excluded) - 1 + extension;
@@ -702,6 +701,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
moveSeen++;
// Root
if (!ply) {
ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch;
}
@@ -725,6 +725,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
ctx->pvLine.SetMove(ply, currMove);
}
// Fail high (beta cutoff)
if (score >= beta) {
const int bonusDepth = depth + (!inCheck && staticEval <= alpha);
int historyBonus = historyBonusMultiplier * bonusDepth - historyBonusSub;
@@ -764,6 +765,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
if (ply > 0) UpdateContHistNPly(1);
if (ply > 1) UpdateContHistNPly(2);
// Malus
for (int i = 0; i < seenQuietsCount - 1; i++) {
sourceThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveFrom());
targetThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveTo());
@@ -773,10 +775,12 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
UpdateCaptHist(currMove, captHistoryBonus);
}
// Capthist malus
for (int i = 0; i < seenCapturesCount - currMove.IsCapture(); i++) {
UpdateCaptHist(seenCaptures[i], -captHistoryMalus);
}
// Corrhist update on fail high
if (!ctx->excluded && !inCheck && currMove.IsQuiet() && score > staticEval) {
int corrHistBonus = std::clamp(score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT);
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
@@ -789,8 +793,11 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
if (moveSeen == 0) {
if (ctx->excluded) return alpha;
return inCheck ? -MATE_SCORE + ply : 0;
if (inCheck) { // checkmate
return -MATE_SCORE + ply;
} else { // stalemate
return 0;
}
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
@@ -841,6 +848,7 @@ static double ScaleTime(SearchContext *ctx, Move &move) {
return nodeScalingFactor;
}
// Iterative deepening
template <searchMode mode>
static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
int fullTime = board.sideToMove ? params.btime : params.wtime;
@@ -927,9 +935,6 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c
ctx->TT->IncreaseAge();
}
board.MarkAccumulatorDirty();
ctx->accStack.finny.Reset();
ctx->seldepth = 0;
ctx->nodesTable = {};
if constexpr (mode != bench) {
+10 -3
View File
@@ -34,6 +34,7 @@ constexpr int CORRHIST_MAX = 16384;
constexpr int32_t ScoreNone = -255000;
constexpr int inf = 100000;
// first index: [0] noisy, [1] quiet
inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES];
#ifdef TUNING
@@ -57,6 +58,7 @@ class SearchContext;
class CaptHistory {
private:
// indexed by [stm][moving pt][capture pt][to]
MultiArray<int, 2, 6, 6, 64> historyMoves;
public:
void Update(bool stm, int moving, int capture, int to, int bonus) {
@@ -76,9 +78,11 @@ public:
class CorrHist {
private:
// indexed by [stm][key]
MultiArray<int, 2, CORRHIST_SIZE> pawnHist;
MultiArray<int, 2, CORRHIST_SIZE> nonPawnHist;
MultiArray<int, 2, CORRHIST_SIZE> majorHist;
MultiArray<int, 2, CORRHIST_SIZE> minorHist;
public:
void Update(Board& board, int depth, int diff, int* entry) {
const int scaledDiff = diff * CORRHIST_GRAIN;
@@ -92,23 +96,27 @@ public:
Update(board, depth, diff, &pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]);
Update(board, depth, diff, &minorHist[board.sideToMove][board.minorKey % CORRHIST_SIZE]);
}
int GetAllHist(Board& board) {
return pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]
+ nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE];
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]
+ minorHist[board.sideToMove][board.minorKey % CORRHIST_SIZE];
}
void Clear() {
std::fill(&pawnHist[0][0], &pawnHist[0][0] + sizeof(pawnHist) / sizeof(int), 0);
std::fill(&nonPawnHist[0][0], &nonPawnHist[0][0] + sizeof(nonPawnHist) / sizeof(int), 0);
std::fill(&majorHist[0][0], &majorHist[0][0] + sizeof(majorHist) / sizeof(int), 0);
std::fill(&minorHist[0][0], &minorHist[0][0] + sizeof(minorHist) / sizeof(int), 0);
}
};
class ContHistory {
private:
// indexed by [other color][prev move piece][stm][prev move to][piece][to]
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
public:
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
@@ -131,6 +139,7 @@ public:
class History {
private:
// indexed by [stm][from][to][threatenedSource][threatenedTarget]
MultiArray<int, 2, 64, 64, 2, 2> historyMoves;
public:
void Update(bool stm, Move move, bool source, bool target, int bonus) {
@@ -242,8 +251,6 @@ public:
std::array<Stack, MAX_DEPTH> ss{};
ACC::AccStack accStack{MAX_DEPTH + 2};
Stopwatch sw;
SearchContext(){
+4 -5
View File
@@ -4,12 +4,11 @@ TTable SharedTT;
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) {
TTBucket *bucket = &table[hashKey % table.size()];
const uint16_t packedKey = PackHashKey(hashKey);
TTEntry *current = nullptr;
if (bucket->depthPreferred && bucket->depthPreferred.hashKey == packedKey) {
if (bucket->depthPreferred && bucket->depthPreferred.hashKey == hashKey) {
current = &bucket->depthPreferred;
} else if (bucket->alwaysReplace && bucket->alwaysReplace.hashKey == packedKey) {
} else if (bucket->alwaysReplace && bucket->alwaysReplace.hashKey == hashKey) {
current = &bucket->alwaysReplace;
} else if (!bucket->alwaysReplace) {
current = &bucket->alwaysReplace;
@@ -28,7 +27,7 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b
}
}
const bool samePosition = current->hashKey == packedKey;
const bool samePosition = current->hashKey == hashKey;
const bool exactBound = nodeType == PV;
const bool entryFromCurrentAge = current->age == age;
const int writeDepth = depth + 4 + ttpv * 2;
@@ -37,7 +36,7 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b
return;
}
current->hashKey = packedKey;
current->hashKey = hashKey;
current->nodeType = nodeType;
current->score = score;
current->depth = depth;
+3 -14
View File
@@ -19,16 +19,9 @@ public:
}
};
constexpr U64 hashKeyMask = 0xFFFF;
// only the lowest bits of the hashkey are stored, the rest is only used for indexing
inline uint16_t PackHashKey(U64 &hashKey) {
return uint16_t(hashKey & hashKeyMask);
}
class TTEntry {
public:
uint16_t hashKey = 0;
U64 hashKey = 0;
int16_t score = 0;
Move bestMove = Move();
uint8_t depth = 0;
@@ -53,8 +46,6 @@ public:
TTEntry alwaysReplace;
};
static_assert(sizeof(TTEntry) == 10);
// 1024 MB
constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTBucket);
// 8 MB
@@ -93,11 +84,9 @@ public:
TTEntry GetEntry(U64 &hashKey) {
TTBucket *current = &table[hashKey % table.size()];
const uint16_t packedKey = PackHashKey(hashKey);
if (current->depthPreferred.hashKey == packedKey) {
if (current->depthPreferred.hashKey == hashKey) {
return current->depthPreferred;
} else if (current->alwaysReplace.hashKey == packedKey) {
} else if (current->alwaysReplace.hashKey == hashKey) {
return current->alwaysReplace;
}