Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edfa6ead28 |
No files matched your search
@@ -57,7 +57,6 @@ 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**.
|
||||
|
||||
|
||||
+3
-145
@@ -1,131 +1,13 @@
|
||||
#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",
|
||||
@@ -186,35 +68,11 @@ void RunBenchmark() {
|
||||
auto ctx = std::make_unique<SearchContext>();
|
||||
ctx->TT = &BenchTT;
|
||||
|
||||
PrintBenchHeader();
|
||||
|
||||
Stopwatch sw;
|
||||
for (size_t i = 0; i < fenPositions.size(); i++) {
|
||||
for (int 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);
|
||||
SearchPosition<bench>(board, SearchParams(), ctx.get());
|
||||
}
|
||||
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;
|
||||
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/sw.GetElapsedSec()) << " nps" << std::endl;
|
||||
}
|
||||
+2
-513
@@ -5,19 +5,11 @@
|
||||
#include "nnue.h"
|
||||
#include "tt.h"
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <algorithm>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
#include <ranges>
|
||||
#include <string_view>
|
||||
#include <cassert>
|
||||
#include "types.h"
|
||||
#include "utils.h"
|
||||
#include "wdl.h"
|
||||
#include "search.h"
|
||||
#include "termcolor.hpp"
|
||||
|
||||
void Board::Reset() {
|
||||
castlingRights = 0;
|
||||
@@ -259,511 +251,8 @@ void Board::PrintBoard() {
|
||||
std::cout << " Fen: " << GetFen() << std::endl;
|
||||
}
|
||||
|
||||
void Board::PrintNNUE(bool full) {
|
||||
ACC::AccumulatorPair acc;
|
||||
RefreshAccumulator(acc);
|
||||
|
||||
const int pieceCount = occupied.PopCount();
|
||||
const size_t divisor = 32 / NNUE::OUTPUT_BUCKETS;
|
||||
const size_t outBucket = (pieceCount - 2) / divisor;
|
||||
|
||||
const int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
|
||||
const int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
|
||||
const ACC::BucketPair buckets = GetBuckets();
|
||||
|
||||
const bool stmIsWhite = (sideToMove == White);
|
||||
const ACC::Accumulator& stmAcc = stmIsWhite ? acc.white : acc.black;
|
||||
const ACC::Accumulator& nstmAcc = stmIsWhite ? acc.black : acc.white;
|
||||
|
||||
auto bar = [](int value, int maxValue, int width) {
|
||||
std::string s;
|
||||
int filled = maxValue > 0 ? (value * width + maxValue / 2) / maxValue : 0;
|
||||
for (int i = 0; i < width; i++)
|
||||
s += (i < filled) ? '#' : '.';
|
||||
return s;
|
||||
};
|
||||
|
||||
auto section = [](const char* name) {
|
||||
std::cout << termcolor::bold << termcolor::color<244>;
|
||||
std::cout << "-- " << name << " --";
|
||||
std::cout << termcolor::reset << std::endl;
|
||||
};
|
||||
|
||||
auto pieceLetter = [&](int sq) {
|
||||
int pt = mailbox[sq];
|
||||
if (pt == nullPieceType)
|
||||
return ' ';
|
||||
bool white = colors[White].IsSet(sq);
|
||||
return PIECE_LETTERS[pt * 2 + (white ? White : Black)];
|
||||
};
|
||||
|
||||
auto boardRow = [&](int rank) {
|
||||
std::ostringstream row;
|
||||
row << termcolor::color<244> << rank + 1 << termcolor::reset << " ";
|
||||
for (int file = 0; file < 8; file++) {
|
||||
int sq = rank * 8 + file;
|
||||
int pt = mailbox[sq];
|
||||
bool isKingSq = (sq == wKingSq) || (sq == bKingSq);
|
||||
if (pt == nullPieceType) {
|
||||
row << termcolor::color<240> << ". " << termcolor::reset;
|
||||
} else {
|
||||
bool white = colors[White].IsSet(sq);
|
||||
if (isKingSq)
|
||||
row << termcolor::bold << termcolor::reverse;
|
||||
if (white)
|
||||
row << termcolor::bright_white;
|
||||
else
|
||||
row << termcolor::yellow;
|
||||
row << pieceLetter(sq) << ' ';
|
||||
row << termcolor::reset;
|
||||
}
|
||||
}
|
||||
return row.str();
|
||||
};
|
||||
|
||||
auto bucketMapRow = [&](bool forWhite, int rank) {
|
||||
std::ostringstream row;
|
||||
int kingSq = forWhite ? wKingSq : bKingSq;
|
||||
for (int file = 0; file < 8; file++) {
|
||||
int sq = rank * 8 + file;
|
||||
int b = NNUE::kingBuckets[forWhite ? White : Black][sq];
|
||||
if (sq == kingSq)
|
||||
row << termcolor::bold << termcolor::reverse << termcolor::bright_cyan;
|
||||
else
|
||||
row << termcolor::color<244>;
|
||||
row << b << ' ';
|
||||
row << termcolor::reset;
|
||||
}
|
||||
return row.str();
|
||||
};
|
||||
|
||||
auto printBoardAndMaps = [&]() {
|
||||
std::cout << " a b c d e f g h White regions Black regions" << std::endl;
|
||||
for (int rank = 7; rank >= 0; rank--) {
|
||||
std::cout << boardRow(rank) << " " << bucketMapRow(true, rank);
|
||||
std::cout << " " << bucketMapRow(false, rank) << std::endl;
|
||||
}
|
||||
std::cout << " a b c d e f g h" << termcolor::color<244> << " Kings highlighted" << termcolor::reset << std::endl;
|
||||
};
|
||||
|
||||
auto printGauge = [&](double pawns, const std::string& valueStr, bool positive, bool isMate) {
|
||||
const int width = 41;
|
||||
const int center = width / 2;
|
||||
double cl = std::clamp(pawns, -5.0, 5.0);
|
||||
int mark = center + int(std::round(cl / 5.0 * center));
|
||||
mark = std::clamp(mark, 0, width - 1);
|
||||
std::cout << " ";
|
||||
for (int i = 0; i < width; i++) {
|
||||
if (i == mark) {
|
||||
std::cout << termcolor::bold << termcolor::bright_white << 'O';
|
||||
} else if (i == center) {
|
||||
std::cout << termcolor::color<244> << '+';
|
||||
} else if (i < center) {
|
||||
std::cout << termcolor::red << '-';
|
||||
} else {
|
||||
std::cout << termcolor::green << '-';
|
||||
}
|
||||
std::cout << termcolor::reset;
|
||||
}
|
||||
std::cout << " ";
|
||||
if (isMate) {
|
||||
if (positive)
|
||||
std::cout << termcolor::bold << termcolor::bright_green;
|
||||
else
|
||||
std::cout << termcolor::bold << termcolor::bright_red;
|
||||
} else if (positive) {
|
||||
std::cout << termcolor::bold << termcolor::green;
|
||||
} else {
|
||||
std::cout << termcolor::bold << termcolor::red;
|
||||
}
|
||||
std::cout << valueStr << termcolor::reset << std::endl;
|
||||
std::cout << " " << termcolor::color<244> << "-5" << std::string(center - 2, ' ') << "0"
|
||||
<< std::string(center - 2, ' ') << "+5" << termcolor::reset << std::endl;
|
||||
};
|
||||
|
||||
auto printWdlBar = [&](const WDLTriplet& t) {
|
||||
const int width = 32;
|
||||
int w = (t.wins * width + 500) / 1000;
|
||||
int l = (t.losses * width + 500) / 1000;
|
||||
int d = width - w - l;
|
||||
std::cout << " ";
|
||||
std::cout << termcolor::bright_green;
|
||||
for (int i = 0; i < w; i++) std::cout << '#';
|
||||
std::cout << termcolor::color<244>;
|
||||
for (int i = 0; i < d; i++) std::cout << '#';
|
||||
std::cout << termcolor::bright_red;
|
||||
for (int i = 0; i < l; i++) std::cout << '#';
|
||||
std::cout << termcolor::reset << std::endl;
|
||||
};
|
||||
|
||||
struct AccStats {
|
||||
int16_t mn = 0;
|
||||
int16_t mx = 0;
|
||||
double mean = 0;
|
||||
double absMean = 0;
|
||||
int zeros = 0;
|
||||
int saturated = 0;
|
||||
};
|
||||
|
||||
auto accStats = [](const ACC::Accumulator& a) {
|
||||
AccStats s;
|
||||
s.mn = a[0];
|
||||
s.mx = a[0];
|
||||
int64_t sum = 0;
|
||||
int64_t absSum = 0;
|
||||
for (size_t i = 0; i < NNUE::HL_SIZE; i++) {
|
||||
s.mn = std::min(s.mn, a[i]);
|
||||
s.mx = std::max(s.mx, a[i]);
|
||||
sum += a[i];
|
||||
absSum += std::abs(a[i]);
|
||||
int32_t c = std::clamp<int32_t>(a[i], 0, NNUE::QA);
|
||||
if (c == 0)
|
||||
s.zeros++;
|
||||
if (c >= NNUE::QA)
|
||||
s.saturated++;
|
||||
}
|
||||
s.mean = double(sum) / double(NNUE::HL_SIZE);
|
||||
s.absMean = double(absSum) / double(NNUE::HL_SIZE);
|
||||
return s;
|
||||
};
|
||||
|
||||
auto perspectivePart = [&](const ACC::Accumulator& a, size_t base, std::vector<std::tuple<int64_t,int,int16_t,int16_t>>* top) {
|
||||
int64_t part = 0;
|
||||
for (size_t i = 0; i < NNUE::HL_SIZE; i++) {
|
||||
int32_t c = std::clamp<int32_t>(a[i], 0, NNUE::QA);
|
||||
int16_t w = NNUE::net.output_weights[outBucket][base + i];
|
||||
int16_t prod = int16_t(c * w);
|
||||
int64_t contrib = int64_t(c) * prod;
|
||||
part += contrib;
|
||||
if (top && (c > 0))
|
||||
top->emplace_back(std::llabs(contrib), int(i), int16_t(c), w);
|
||||
}
|
||||
return part;
|
||||
};
|
||||
|
||||
std::vector<std::tuple<int64_t,int,int16_t,int16_t>> stmTop;
|
||||
std::vector<std::tuple<int64_t,int,int16_t,int16_t>> nstmTop;
|
||||
stmTop.reserve(NNUE::HL_SIZE);
|
||||
nstmTop.reserve(NNUE::HL_SIZE);
|
||||
const int64_t stmPart = perspectivePart(stmAcc, 0, &stmTop);
|
||||
const int64_t nstmPart = perspectivePart(nstmAcc, NNUE::HL_SIZE, &nstmTop);
|
||||
const int64_t preBias = (stmPart + nstmPart) / NNUE::QA;
|
||||
const int16_t bias = NNUE::net.output_bias[outBucket];
|
||||
const int64_t biased = preBias + bias;
|
||||
const int64_t rawEval = (biased * NNUE::SCALE) / (NNUE::QA * NNUE::QB);
|
||||
|
||||
const int nN = pieces[Knight].PopCount();
|
||||
const int nB = pieces[Bishop].PopCount();
|
||||
const int nR = pieces[Rook].PopCount();
|
||||
const int nQ = pieces[Queen].PopCount();
|
||||
const int materialScale = 2048 + 90 * nN + 90 * nB + 180 * nR + 360 * nQ;
|
||||
const int16_t finalEval = std::clamp<int64_t>(rawEval * materialScale / 4096,
|
||||
(-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH), (SEARCH::MATE_SCORE - SEARCH::MAX_DEPTH));
|
||||
|
||||
const bool isMateScore = std::abs(finalEval) + SEARCH::MAX_DEPTH >= SEARCH::MATE_SCORE;
|
||||
const int normalized = isMateScore ? finalEval : scaleEval(finalEval, *this);
|
||||
const WDLTriplet wdl = getWDL(finalEval, *this);
|
||||
|
||||
std::cout << termcolor::bold << termcolor::bright_white;
|
||||
std::cout << "NNUE evaluation detail";
|
||||
std::cout << termcolor::reset << std::endl;
|
||||
std::cout << termcolor::color<244> << "FEN: " << termcolor::reset << GetFen() << std::endl;
|
||||
std::cout << termcolor::color<244> << "Side to move: " << termcolor::reset;
|
||||
if (!sideToMove) {
|
||||
std::cout << termcolor::bold << termcolor::bright_white << "White";
|
||||
} else {
|
||||
std::cout << termcolor::bold << termcolor::color<208> << "Black";
|
||||
}
|
||||
std::cout << termcolor::reset << " " << termcolor::color<244> << "Pieces: " << termcolor::reset << pieceCount << std::endl;
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
section("Position");
|
||||
printBoardAndMaps();
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
section("Architecture");
|
||||
std::cout << " HL " << termcolor::bold << termcolor::bright_white << NNUE::HL_SIZE << termcolor::reset;
|
||||
std::cout << " Input " << termcolor::bold << termcolor::bright_white << NNUE::INPUT_SIZE << termcolor::reset;
|
||||
std::cout << " In-buckets " << termcolor::bold << termcolor::bright_white << NNUE::INPUT_BUCKETS << termcolor::reset;
|
||||
std::cout << " Out-buckets " << termcolor::bold << termcolor::bright_white << NNUE::OUTPUT_BUCKETS << termcolor::reset << std::endl;
|
||||
std::cout << " QA " << termcolor::bold << termcolor::bright_white << NNUE::QA << termcolor::reset;
|
||||
std::cout << " QB " << termcolor::bold << termcolor::bright_white << NNUE::QB << termcolor::reset;
|
||||
std::cout << " Scale " << termcolor::bold << termcolor::bright_white << NNUE::SCALE << termcolor::reset << std::endl;
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
section("Buckets");
|
||||
std::cout << " Out ";
|
||||
for (size_t b = 0; b < NNUE::OUTPUT_BUCKETS; b++) {
|
||||
if (b == outBucket)
|
||||
std::cout << termcolor::bold << termcolor::bright_cyan << '[' << b << ']' << termcolor::reset;
|
||||
else
|
||||
std::cout << termcolor::color<244> << ' ' << b << ' ' << termcolor::reset;
|
||||
}
|
||||
std::cout << termcolor::color<244> << " ((" << pieceCount << " - 2) / " << divisor << ")" << termcolor::reset << std::endl;
|
||||
std::cout << " Kings " << termcolor::bold << termcolor::bright_white << squareCoords[wKingSq] << "->" << buckets.white << termcolor::reset;
|
||||
std::cout << (mirroredWhite ? "(m)" : "") << " ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << squareCoords[bKingSq] << "->" << buckets.black << termcolor::reset;
|
||||
std::cout << (mirroredBlack ? "(m)" : "") << " Feats ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << pieceCount << termcolor::reset << std::endl;
|
||||
if (full) {
|
||||
std::cout << " Material ";
|
||||
std::cout << "N " << termcolor::bold << termcolor::bright_white << nN << termcolor::reset;
|
||||
std::cout << " B " << termcolor::bold << termcolor::bright_white << nB << termcolor::reset;
|
||||
std::cout << " R " << termcolor::bold << termcolor::bright_white << nR << termcolor::reset;
|
||||
std::cout << " Q " << termcolor::bold << termcolor::bright_white << nQ << termcolor::reset;
|
||||
std::cout << " scale = 2048+90N+90B+180R+360Q = ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << materialScale << termcolor::reset;
|
||||
std::cout << termcolor::color<244> << " (/4096)" << termcolor::reset << std::endl;
|
||||
} else {
|
||||
std::cout << " Material scale ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << materialScale << termcolor::reset;
|
||||
std::cout << termcolor::color<244> << " (/4096)" << termcolor::reset << std::endl;
|
||||
}
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
section("Accumulators");
|
||||
for (int p = 0; p < 2; p++) {
|
||||
const bool isWhite = (p == 0);
|
||||
const ACC::Accumulator& a = isWhite ? acc.white : acc.black;
|
||||
const AccStats s = accStats(a);
|
||||
const int active = int(NNUE::HL_SIZE) - s.zeros;
|
||||
std::cout << " " << (isWhite ? "White" : "Black");
|
||||
if ((stmIsWhite && isWhite) || (!stmIsWhite && !isWhite))
|
||||
std::cout << termcolor::bold << termcolor::bright_cyan << " (STM)" << termcolor::reset;
|
||||
else
|
||||
std::cout << termcolor::color<244> << " (NSTM)" << termcolor::reset;
|
||||
std::cout << " min " << termcolor::bold << termcolor::bright_white << s.mn << termcolor::reset;
|
||||
std::cout << " max " << termcolor::bold << termcolor::bright_white << s.mx << termcolor::reset;
|
||||
std::cout << " mean ";
|
||||
std::cout << termcolor::bright_white << std::fixed << std::setprecision(1) << s.mean << termcolor::reset;
|
||||
if (full) {
|
||||
std::cout << " |mean| ";
|
||||
std::cout << termcolor::bright_white << std::fixed << std::setprecision(1) << s.absMean << termcolor::reset;
|
||||
std::cout << std::endl;
|
||||
std::cout << " active " << termcolor::bold << termcolor::green << active << termcolor::reset;
|
||||
std::cout << termcolor::color<244> << " / " << NNUE::HL_SIZE << termcolor::reset;
|
||||
std::cout << " zero " << termcolor::color<244> << s.zeros << termcolor::reset;
|
||||
std::cout << " saturated(QA) ";
|
||||
if (s.saturated > 0)
|
||||
std::cout << termcolor::bold << termcolor::yellow << s.saturated << termcolor::reset;
|
||||
else
|
||||
std::cout << termcolor::color<244> << "0" << termcolor::reset;
|
||||
std::cout << std::endl;
|
||||
} else {
|
||||
std::cout << " act " << termcolor::bold << termcolor::green << active << termcolor::reset;
|
||||
std::cout << termcolor::color<244> << "/" << NNUE::HL_SIZE << " sat ";
|
||||
if (s.saturated > 0)
|
||||
std::cout << termcolor::reset << termcolor::bold << termcolor::yellow << s.saturated << termcolor::reset;
|
||||
else
|
||||
std::cout << "0" << termcolor::reset;
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
if (full) {
|
||||
int bins[8] = {};
|
||||
for (size_t i = 0; i < NNUE::HL_SIZE; i++) {
|
||||
int32_t c = std::clamp<int32_t>(a[i], 0, NNUE::QA);
|
||||
int bin = std::min(7, (c * 8) / (NNUE::QA + 1));
|
||||
bins[bin]++;
|
||||
}
|
||||
int binMax = *std::max_element(bins, bins + 8);
|
||||
std::cout << " act ";
|
||||
std::cout << termcolor::green << bar(bins[0], binMax, 8) << termcolor::reset;
|
||||
std::cout << ' ' << termcolor::color<244> << "0" << termcolor::reset;
|
||||
std::cout << ' ' << termcolor::green << bar(bins[7], binMax, 8) << termcolor::reset;
|
||||
std::cout << ' ' << termcolor::color<244> << "QA" << termcolor::reset;
|
||||
std::cout << termcolor::color<244> << " peak bin " << (std::max_element(bins, bins + 8) - bins);
|
||||
std::cout << " (" << binMax << ")" << termcolor::reset << std::endl;
|
||||
}
|
||||
}
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
section("Output layer");
|
||||
if (full) {
|
||||
std::cout << " bias[" << outBucket << "] = ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << bias << termcolor::reset << std::endl;
|
||||
std::cout << " STM" << termcolor::color<244> << (stmIsWhite ? " (White)" : " (Black)") << termcolor::reset;
|
||||
std::cout << " part = " << termcolor::bold << termcolor::bright_white << stmPart << termcolor::reset << std::endl;
|
||||
std::cout << " NSTM" << termcolor::color<244> << (stmIsWhite ? " (Black)" : " (White)") << termcolor::reset;
|
||||
std::cout << " part = " << termcolor::bold << termcolor::bright_white << nstmPart << termcolor::reset << std::endl;
|
||||
std::cout << " (STM+NSTM) / QA + bias = ";
|
||||
std::cout << termcolor::bright_white << "(" << stmPart;
|
||||
if (nstmPart < 0)
|
||||
std::cout << " - " << -nstmPart;
|
||||
else
|
||||
std::cout << " + " << nstmPart;
|
||||
std::cout << ") / " << NNUE::QA << " + " << bias;
|
||||
std::cout << " = " << biased << termcolor::reset << std::endl;
|
||||
std::cout << " x Scale / (QA x QB) = " << termcolor::bright_white << biased << " x " << NNUE::SCALE;
|
||||
std::cout << " / (" << NNUE::QA << " x " << NNUE::QB << ") = " << rawEval << termcolor::reset << std::endl;
|
||||
std::cout << " x material / 4096 = " << termcolor::bright_white << rawEval << " x " << materialScale << " / 4096";
|
||||
std::cout << " = " << (rawEval * materialScale / 4096) << termcolor::reset << std::endl;
|
||||
} else {
|
||||
std::cout << " parts STM " << termcolor::bold << termcolor::bright_white << stmPart << termcolor::reset;
|
||||
std::cout << " NSTM " << termcolor::bold << termcolor::bright_white << nstmPart << termcolor::reset;
|
||||
std::cout << " bias " << termcolor::bold << termcolor::bright_white << bias << termcolor::reset;
|
||||
std::cout << " -> raw " << termcolor::bold << termcolor::bright_white << rawEval << termcolor::reset;
|
||||
std::cout << " x" << materialScale << "/4096" << std::endl;
|
||||
}
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
auto humanShort = [](int64_t v) {
|
||||
std::ostringstream os;
|
||||
int64_t a = v < 0 ? -v : v;
|
||||
if (a >= 1000000)
|
||||
os << (v < 0 ? "-" : "") << std::fixed << std::setprecision(1) << (a / 1000000.0) << 'M';
|
||||
else if (a >= 1000)
|
||||
os << (v < 0 ? "-" : "") << std::fixed << std::setprecision(1) << (a / 1000.0) << 'k';
|
||||
else
|
||||
os << v;
|
||||
return os.str();
|
||||
};
|
||||
|
||||
auto denseEntry = [&](int idx, int16_t act, int16_t w, int64_t contrib, int64_t maxAbs) {
|
||||
std::ostringstream os;
|
||||
int barLen = int((std::llabs(contrib) * 10 + maxAbs / 2) / maxAbs);
|
||||
os << ' ' << std::setw(4) << idx << ' ' << std::setw(4) << act << ' ' << std::setw(6) << w << ' ';
|
||||
if (contrib >= 0)
|
||||
os << termcolor::green;
|
||||
else
|
||||
os << termcolor::red;
|
||||
os << std::setw(7) << humanShort(contrib);
|
||||
for (int k = 0; k < barLen; k++) os << '#';
|
||||
for (int k = barLen; k < 10; k++) os << ' ';
|
||||
os << termcolor::reset;
|
||||
return os.str();
|
||||
};
|
||||
|
||||
auto printTopPair = [&](const char* leftLabel, std::vector<std::tuple<int64_t,int,int16_t,int16_t>>& left,
|
||||
const char* rightLabel, std::vector<std::tuple<int64_t,int,int16_t,int16_t>>& right, size_t count) {
|
||||
auto byAbs = [](const auto& x, const auto& y) { return std::get<0>(x) > std::get<0>(y); };
|
||||
size_t nl = std::min(count, left.size());
|
||||
size_t nr = std::min(count, right.size());
|
||||
size_t n = std::max(nl, nr);
|
||||
if (nl > 0) std::partial_sort(left.begin(), left.begin() + nl, left.end(), byAbs);
|
||||
if (nr > 0) std::partial_sort(right.begin(), right.begin() + nr, right.end(), byAbs);
|
||||
int64_t maxAbs = 1;
|
||||
if (nl > 0) maxAbs = std::max(maxAbs, std::get<0>(left[0]));
|
||||
if (nr > 0) maxAbs = std::max(maxAbs, std::get<0>(right[0]));
|
||||
std::cout << " " << termcolor::bold << termcolor::bright_white << leftLabel << termcolor::reset;
|
||||
std::cout << std::string(36 - std::string(leftLabel).size(), ' ') << " ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << rightLabel << termcolor::reset << std::endl;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
std::cout << " ";
|
||||
if (i < nl) {
|
||||
int idx; int16_t act; int16_t w; int64_t ab;
|
||||
std::tie(ab, idx, act, w) = left[i];
|
||||
std::cout << denseEntry(idx, act, w, int64_t(act) * int16_t(act * w), maxAbs);
|
||||
} else {
|
||||
std::cout << std::string(36, ' ');
|
||||
}
|
||||
std::cout << " ";
|
||||
if (i < nr) {
|
||||
int idx; int16_t act; int16_t w; int64_t ab;
|
||||
std::tie(ab, idx, act, w) = right[i];
|
||||
std::cout << denseEntry(idx, act, w, int64_t(act) * int16_t(act * w), maxAbs);
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
auto printTop = [&](const char* label, std::vector<std::tuple<int64_t,int,int16_t,int16_t>>& v, size_t count) {
|
||||
std::cout << " Top " << label << " neurons" << termcolor::color<244> << " (idx act w contrib)" << termcolor::reset << std::endl;
|
||||
size_t n = std::min(count, v.size());
|
||||
std::partial_sort(v.begin(), v.begin() + n, v.end(),
|
||||
[](const auto& x, const auto& y) { return std::get<0>(x) > std::get<0>(y); });
|
||||
int64_t maxAbs = n > 0 ? std::get<0>(v[0]) : 1;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
int64_t ab;
|
||||
int idx;
|
||||
int16_t act;
|
||||
int16_t w;
|
||||
std::tie(ab, idx, act, w) = v[i];
|
||||
int64_t contrib = int64_t(act) * int16_t(act * w);
|
||||
int barLen = int((ab * 14 + maxAbs / 2) / maxAbs);
|
||||
std::cout << " ";
|
||||
std::cout << termcolor::color<244> << "#" << termcolor::reset;
|
||||
std::cout << termcolor::bold << termcolor::bright_white << std::setw(5) << idx << termcolor::reset;
|
||||
std::cout << " act " << termcolor::bright_white << std::setw(4) << act << termcolor::reset;
|
||||
std::cout << " w " << std::setw(7) << w;
|
||||
std::cout << " c ";
|
||||
if (contrib >= 0)
|
||||
std::cout << termcolor::green;
|
||||
else
|
||||
std::cout << termcolor::red;
|
||||
std::cout << std::setw(11) << contrib;
|
||||
for (int k = 0; k < barLen; k++) std::cout << '#';
|
||||
std::cout << termcolor::reset << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
section("Top neurons");
|
||||
if (full) {
|
||||
printTop(stmIsWhite ? "White/STM" : "Black/STM", stmTop, 8);
|
||||
printTop(stmIsWhite ? "Black/NSTM" : "White/NSTM", nstmTop, 8);
|
||||
} else {
|
||||
printTopPair(stmIsWhite ? "STM White" : "STM Black", stmTop,
|
||||
stmIsWhite ? "NSTM Black" : "NSTM White", nstmTop, 3);
|
||||
std::cout << termcolor::color<244> << " (idx act w contrib, nnue full for top 8)" << termcolor::reset << std::endl;
|
||||
}
|
||||
if (full)
|
||||
std::cout << std::endl;
|
||||
|
||||
section("Eval");
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (isMateScore) {
|
||||
int mateIn = (SEARCH::MATE_SCORE - (std::abs(finalEval) - 1)) / 2;
|
||||
mateIn = finalEval < 0 ? mateIn * -1 : mateIn;
|
||||
ss << ((mateIn < 0) ? "-M" : "+M") << std::abs(mateIn);
|
||||
printGauge(mateIn > 0 ? 5.0 : -5.0, ss.str(), mateIn > 0, true);
|
||||
} else {
|
||||
ss << std::showpos << std::fixed << std::setprecision(2) << (normalized / 100.0) << std::noshowpos;
|
||||
printGauge(normalized / 100.0, ss.str(), normalized > 0, false);
|
||||
}
|
||||
}
|
||||
std::cout << " Raw ";
|
||||
std::cout << termcolor::bold << termcolor::bright_white << rawEval << termcolor::reset;
|
||||
std::cout << " Normalized ";
|
||||
if (isMateScore) {
|
||||
int mateIn = (SEARCH::MATE_SCORE - (std::abs(finalEval) - 1)) / 2;
|
||||
mateIn = finalEval < 0 ? mateIn * -1 : mateIn;
|
||||
if (mateIn > 0)
|
||||
std::cout << termcolor::bold << termcolor::bright_green;
|
||||
else
|
||||
std::cout << termcolor::bold << termcolor::bright_red;
|
||||
std::cout << ((mateIn < 0) ? "-M" : "+M") << std::abs(mateIn);
|
||||
std::cout << termcolor::reset;
|
||||
} else {
|
||||
if (normalized > 0)
|
||||
std::cout << termcolor::bold << termcolor::green;
|
||||
else if (normalized < 0)
|
||||
std::cout << termcolor::bold << termcolor::red;
|
||||
else
|
||||
std::cout << termcolor::bright_white;
|
||||
std::stringstream ss;
|
||||
ss << std::showpos << std::fixed << std::setprecision(2) << (normalized / 100.0) << std::noshowpos;
|
||||
std::cout << ss.str();
|
||||
std::cout << termcolor::reset;
|
||||
}
|
||||
std::cout << " WDL " << termcolor::color<244>;
|
||||
std::cout << wdl.wins << "W " << wdl.draws << "D " << wdl.losses << "L";
|
||||
std::cout << termcolor::reset << std::endl;
|
||||
printWdlBar(wdl);
|
||||
std::cout << " Final eval: ";
|
||||
if (finalEval > 0)
|
||||
std::cout << termcolor::bold << termcolor::green;
|
||||
else if (finalEval < 0)
|
||||
std::cout << termcolor::bold << termcolor::red;
|
||||
else
|
||||
std::cout << termcolor::bold << termcolor::bright_white;
|
||||
std::cout << finalEval << termcolor::reset << std::endl;
|
||||
void Board::PrintNNUE() {
|
||||
std::cout << "Final eval: " << NNUE::net.Evaluate(*this) << std::endl;
|
||||
}
|
||||
|
||||
void Board::AddMove(Move move) {
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ public:
|
||||
std::string GetFen();
|
||||
void PrintBoard();
|
||||
|
||||
void PrintNNUE(bool full = false);
|
||||
void PrintNNUE();
|
||||
|
||||
void AddMove(Move move);
|
||||
void ResetMoves();
|
||||
|
||||
+131
-41
@@ -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
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
+48
-312
@@ -5,14 +5,9 @@
|
||||
#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
|
||||
@@ -34,319 +29,60 @@
|
||||
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;
|
||||
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);
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
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();
|
||||
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;
|
||||
}
|
||||
+26
-245
@@ -1,265 +1,46 @@
|
||||
#include "perft.h"
|
||||
#include "stopwatch.h"
|
||||
#include "movegen.h"
|
||||
#include "termcolor.hpp"
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <string>
|
||||
#include <cassert>
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
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) {
|
||||
int rookFrom = mover ? (flags == kingCastle ? h8 : a8) : (flags == kingCastle ? h1 : a1);
|
||||
int rookTo = flags == kingCastle ? rookFrom - 2 : rookFrom + 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) {
|
||||
static U64 HelperPerft(Board &board, int depth) {
|
||||
MOVEGEN::GenerateMoves<All>(board, true);
|
||||
|
||||
if (depth == 0) return 1ULL;
|
||||
|
||||
U64 nodes = 0;
|
||||
|
||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||
Move move = board.moveList[i];
|
||||
if (!board.IsLegal(move))
|
||||
continue;
|
||||
if (!board.IsLegal(board.moveList[i])) continue;
|
||||
|
||||
Board copy = board;
|
||||
copy.MakeMove(move);
|
||||
if (depth == 1)
|
||||
CountLeaf(copy, move, out);
|
||||
else
|
||||
PerftRec(copy, depth - 1, out);
|
||||
copy.MakeMove(board.moveList[i]);
|
||||
|
||||
nodes += HelperPerft(copy, depth - 1);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
return nodes;
|
||||
}
|
||||
|
||||
void Perft(Board &board, int depth) {
|
||||
Stopwatch sw;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
//board.SetByFen(StartingFen);
|
||||
MOVEGEN::GenerateMoves<All>(board, true);
|
||||
|
||||
PerftCounts total;
|
||||
int moveCount = 0;
|
||||
|
||||
PrintPerftHeader();
|
||||
U64 totalNodes = 0;
|
||||
|
||||
Stopwatch sw;
|
||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||
Move move = board.moveList[i];
|
||||
if (!board.IsLegal(move))
|
||||
continue;
|
||||
if (!board.IsLegal(board.moveList[i])) 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++;
|
||||
copy.MakeMove(board.moveList[i]);
|
||||
U64 nodeCount = HelperPerft(copy, depth - 1);
|
||||
totalNodes += nodeCount;
|
||||
board.moveList[i].PrintMove();
|
||||
|
||||
std::cout << ": " << nodeCount << std::endl;
|
||||
}
|
||||
|
||||
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: " << total.nodes << std::endl;
|
||||
std::cout << "Time took: " << elapsed << "s (";
|
||||
std::cout << int(double(total.nodes) / elapsed) << " nodes/sec)" << 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;
|
||||
}
|
||||
+26
-206
@@ -13,74 +13,6 @@
|
||||
|
||||
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);
|
||||
|
||||
@@ -370,6 +302,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
|
||||
if (entry.hashKey == board.hashKey) {
|
||||
ttHit = true;
|
||||
entry.score = ScoreFromTT(entry.score, ply);
|
||||
|
||||
switch (entry.nodeType) {
|
||||
case PV:
|
||||
@@ -455,7 +388,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
|
||||
if (score >= beta) {
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, ScoreToTT(score, ply), CutNode, currMove, ttpv);
|
||||
return score;
|
||||
}
|
||||
|
||||
@@ -470,7 +403,7 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
|
||||
results.score = bestScore;
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, 0, ScoreToTT(results.score, ply), nodeType, results.bestMove, ttpv);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -484,22 +417,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
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;
|
||||
|
||||
@@ -510,6 +427,9 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
const bool ttHit = entry.hashKey == board.hashKey;
|
||||
const bool ttpv = isPV | entry.ttpv;
|
||||
|
||||
if (ttHit)
|
||||
entry.score = ScoreFromTT(entry.score, ply);
|
||||
|
||||
if constexpr (!isPV) {
|
||||
if (ttHit) {
|
||||
if (entry.depth >= depth &&
|
||||
@@ -639,7 +559,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
if (searchStopped.load(std::memory_order_relaxed)) return 0;
|
||||
|
||||
if (score >= probcutBeta) {
|
||||
ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, probcutDepth, ScoreToTT(score, ply), CutNode, currMove, ttpv);
|
||||
|
||||
return score;
|
||||
}
|
||||
@@ -668,18 +588,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
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];
|
||||
|
||||
@@ -880,7 +788,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
}
|
||||
|
||||
if (!ctx->excluded)
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, score, CutNode, currMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, ScoreToTT(score, ply), CutNode, currMove, ttpv);
|
||||
return score;
|
||||
}
|
||||
}
|
||||
@@ -901,7 +809,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
|
||||
}
|
||||
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove, ttpv);
|
||||
ctx->TT->WriteEntry(board.hashKey, depth, ScoreToTT(results.score, ply), nodeType, results.bestMove, ttpv);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -951,13 +859,6 @@ 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;
|
||||
@@ -968,23 +869,9 @@ 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++) {
|
||||
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->timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4);
|
||||
int softTime = ctx->timeToSearch * 0.65 * nodeScaling;
|
||||
ctx->seldepth = 0;
|
||||
ctx->rootDepth = depth;
|
||||
|
||||
@@ -1016,14 +903,12 @@ 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 (useTime && ctx->sw.GetElapsedMS() >= softTime) {
|
||||
if (ctx->sw.GetElapsedMS() >= softTime) {
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
break;
|
||||
}
|
||||
@@ -1052,7 +937,6 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c
|
||||
|
||||
ctx->seldepth = 0;
|
||||
ctx->nodesTable = {};
|
||||
ctx->searchMoves = params.searchMoves;
|
||||
if constexpr (mode != bench) {
|
||||
ctx->nodes = 0;
|
||||
|
||||
@@ -1062,30 +946,14 @@ 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) {
|
||||
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;
|
||||
}
|
||||
std::cout << "bestmove ";
|
||||
results.bestMove.PrintMove();
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
return results;
|
||||
@@ -1108,27 +976,6 @@ 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;
|
||||
@@ -1168,14 +1015,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
|
||||
|
||||
std::stringstream depthStr;
|
||||
depthStr << depth << '/' << ctx->seldepth;
|
||||
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::cout << std::setw(6) << std::left << depthStr.str();
|
||||
|
||||
std::stringstream timeStr;
|
||||
if (elapsed >= 1000) {
|
||||
@@ -1183,7 +1023,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
|
||||
} else {
|
||||
timeStr << elapsed << "ms";
|
||||
}
|
||||
std::cout << std::setw(9) << std::right << timeStr.str();
|
||||
std::cout << std::setw(10) << std::right << timeStr.str();
|
||||
|
||||
std::stringstream scoreStr;
|
||||
bool isMate = false;
|
||||
@@ -1205,15 +1045,15 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
|
||||
|
||||
if (isMate) {
|
||||
if (mateIn > 0) {
|
||||
std::cout << termcolor::bold << termcolor::bright_green;
|
||||
std::cout << termcolor::bright_green;
|
||||
} else {
|
||||
std::cout << termcolor::bold << termcolor::bright_red;
|
||||
std::cout << termcolor::bright_red;
|
||||
}
|
||||
} else {
|
||||
if (results.score > 0) {
|
||||
std::cout << termcolor::bold << termcolor::green;
|
||||
std::cout << termcolor::green;
|
||||
} else if (results.score < 0) {
|
||||
std::cout << termcolor::bold << termcolor::red;
|
||||
std::cout << termcolor::red;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1230,31 +1070,11 @@ 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>;
|
||||
}
|
||||
|
||||
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 hashfullStr;
|
||||
hashfullStr << "TT: " << (ctx->TT->GetUsedPercentage() + 5) / 10 << '%';
|
||||
std::cout << std::setw(10) << std::right << hashfullStr.str();
|
||||
|
||||
std::stringstream nodesStr;
|
||||
if (ctx->nodes >= 1000000) {
|
||||
@@ -1264,7 +1084,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
|
||||
} else {
|
||||
nodesStr << ctx->nodes;
|
||||
}
|
||||
std::cout << std::setw(9) << std::right << nodesStr.str();
|
||||
std::cout << std::setw(11) << std::right << nodesStr.str();
|
||||
|
||||
int nps = int(ctx->nodes/ctx->sw.GetElapsedSec());
|
||||
std::stringstream npsStr;
|
||||
@@ -1275,7 +1095,7 @@ void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, i
|
||||
} else {
|
||||
npsStr << nps << "/s";
|
||||
}
|
||||
std::cout << std::setw(9) << std::right << npsStr.str();
|
||||
std::cout << std::setw(12) << std::right << npsStr.str();
|
||||
|
||||
std::cout << " ";
|
||||
ctx->pvLine.Print(0, depth % 2 == 0);
|
||||
|
||||
+18
-27
@@ -2,7 +2,6 @@
|
||||
#include "board.h"
|
||||
#include "uci.h"
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include "move.h"
|
||||
#include <algorithm>
|
||||
#include "stopwatch.h"
|
||||
@@ -35,6 +34,22 @@ constexpr int CORRHIST_MAX = 16384;
|
||||
constexpr int32_t ScoreNone = -255000;
|
||||
constexpr int inf = 100000;
|
||||
|
||||
inline int ScoreToTT(int score, int ply) {
|
||||
if (score >= MATE_SCORE - MAX_DEPTH)
|
||||
return score + ply;
|
||||
if (score <= -MATE_SCORE + MAX_DEPTH)
|
||||
return score - ply;
|
||||
return score;
|
||||
}
|
||||
|
||||
inline int ScoreFromTT(int score, int ply) {
|
||||
if (score >= MATE_SCORE - MAX_DEPTH)
|
||||
return score - ply;
|
||||
if (score <= -MATE_SCORE + MAX_DEPTH)
|
||||
return score + ply;
|
||||
return score;
|
||||
}
|
||||
|
||||
inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES];
|
||||
|
||||
#ifdef TUNING
|
||||
@@ -56,14 +71,6 @@ void RefreshTunableCaches();
|
||||
|
||||
class SearchContext;
|
||||
|
||||
struct RootVote {
|
||||
Move bestMove;
|
||||
int score = 0;
|
||||
int depth = 0;
|
||||
};
|
||||
|
||||
SearchResults VoteRootMoves(const std::vector<RootVote>& votes);
|
||||
|
||||
class CaptHistory {
|
||||
private:
|
||||
MultiArray<int, 2, 6, 6, 64> historyMoves;
|
||||
@@ -179,7 +186,7 @@ public:
|
||||
void Print(int n, bool isEven = false) {
|
||||
for (int i = 0; i < length[n]; i++) {
|
||||
if (i == 0 && !UCIEnabled) {
|
||||
std::cout << termcolor::bold << termcolor::bright_cyan;
|
||||
std::cout << termcolor::bright_cyan;
|
||||
table[n][i].PrintMove();
|
||||
std::cout << termcolor::reset;
|
||||
|
||||
@@ -191,8 +198,7 @@ public:
|
||||
} else {
|
||||
table[n][i].PrintMove();
|
||||
}
|
||||
if (i + 1 < length[n])
|
||||
std::cout << ' ';
|
||||
std::cout << ' ';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,14 +231,9 @@ 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{};
|
||||
|
||||
@@ -272,14 +273,6 @@ 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);
|
||||
@@ -294,7 +287,5 @@ 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);
|
||||
}
|
||||
+21
-149
@@ -13,7 +13,6 @@
|
||||
#include "utils.h"
|
||||
#include "datagen.h"
|
||||
#include "tunables.h"
|
||||
#include "termcolor.hpp"
|
||||
|
||||
// OS-dependent threading includes
|
||||
#ifdef _WIN32
|
||||
@@ -21,8 +20,6 @@
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#endif
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -46,47 +43,6 @@ 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) {
|
||||
@@ -108,16 +64,6 @@ 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) {
|
||||
@@ -193,31 +139,20 @@ 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::SearchContext* master) {
|
||||
SearchResults results = SEARCH::SearchPosition<mode>(board, params, ctx);
|
||||
int id = ctx->threadId;
|
||||
if (id == 0) {
|
||||
master->CopyLearningFrom(*ctx);
|
||||
}
|
||||
static void ThreadFunc(Board board, SearchParams params, SEARCH::SearchContext* ctx) {
|
||||
SEARCH::SearchPosition<mode>(board, params, 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, ctx);
|
||||
searchThreads.emplace_back(ThreadFunc<SEARCH::nodesMode>, board, params, ctxCopy);
|
||||
} else {
|
||||
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy, ctx);
|
||||
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,20 +160,11 @@ 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*, SEARCH::SearchContext*>*>(arg);
|
||||
auto* tup = static_cast<std::tuple<Board, SearchParams, SEARCH::SearchContext*>*>(arg);
|
||||
SEARCH::SearchContext* ctx = std::get<2>(*tup);
|
||||
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);
|
||||
}
|
||||
SEARCH::SearchPosition<mode>(std::get<0>(*tup), std::get<1>(*tup), ctx);
|
||||
delete ctx;
|
||||
delete tup;
|
||||
if (id == 0) {
|
||||
searchStopped.store(true, std::memory_order_relaxed);
|
||||
TryPrintVotedBestmove(results);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -248,9 +174,6 @@ 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;
|
||||
|
||||
@@ -258,7 +181,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*, SEARCH::SearchContext*>(board, params, ctxCopy, ctx);
|
||||
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
|
||||
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
|
||||
if (rc != 0) {
|
||||
delete std::get<2>(*arg);
|
||||
@@ -266,7 +189,7 @@ static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchC
|
||||
ctxCopy = nullptr;
|
||||
}
|
||||
} else {
|
||||
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>(board, params, ctxCopy, ctx);
|
||||
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
|
||||
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
|
||||
if (rc != 0) {
|
||||
delete std::get<2>(*arg);
|
||||
@@ -285,10 +208,6 @@ 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);
|
||||
@@ -302,60 +221,17 @@ 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 (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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
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++) {
|
||||
searchThreads.reserve(threads);
|
||||
for (int i = 0; i < threads; i++) {
|
||||
StartSearchThread(board, params, ctx, i);
|
||||
}
|
||||
}
|
||||
@@ -370,11 +246,7 @@ static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
|
||||
}
|
||||
|
||||
if (command.find("Threads") != std::string::npos) {
|
||||
threads = static_cast<int>(ReadParam("value", command));
|
||||
if (threads < 1)
|
||||
threads = 1;
|
||||
if (threads > 512)
|
||||
threads = 512;
|
||||
threads = ReadParam("value", command);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -429,7 +301,7 @@ static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
|
||||
}
|
||||
|
||||
static void PrintEngineInfo() {
|
||||
std::cout << "id name Eleanor v" << EleanorVersion << std::endl;
|
||||
std::cout << "id name Eleanor v4.1" << std::endl;
|
||||
std::cout << "id author rektdie" << std::endl;
|
||||
std::cout << "option name Hash type spin default 8 min 1 max 1024" << std::endl;
|
||||
std::cout << "option name Threads type spin default 1 min 1 max 512" << std::endl;
|
||||
@@ -483,7 +355,7 @@ void UCILoop(Board &board) {
|
||||
}
|
||||
|
||||
// parse UCI "go" command
|
||||
if (input == "go" || input.rfind("go ", 0) == 0) {
|
||||
if (input.find("go") != std::string::npos) {
|
||||
ParseGo(board, input, ctx.get());
|
||||
continue;
|
||||
}
|
||||
@@ -497,7 +369,7 @@ void UCILoop(Board &board) {
|
||||
|
||||
// parse UCI "stop" command
|
||||
if (input.find("stop") != std::string::npos) {
|
||||
StopSearchThreadsAndVote();
|
||||
StopSearchThreads();
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -536,7 +408,7 @@ void UCILoop(Board &board) {
|
||||
}
|
||||
|
||||
if (input.find("nnue") != std::string::npos) {
|
||||
board.PrintNNUE(input.find("full") != std::string::npos);
|
||||
board.PrintNNUE();
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include "move.h"
|
||||
#include "board.h"
|
||||
|
||||
@@ -10,8 +8,6 @@ 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;
|
||||
@@ -20,11 +16,6 @@ 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;
|
||||
|
||||
|
||||
Reference in new issue
Block a user