From f3411c524c39e9ba13fd9c77a0734cdf81e33c80 Mon Sep 17 00:00:00 2001 From: rektdie Date: Sat, 3 Oct 2026 20:12:36 +0200 Subject: [PATCH] datagen new ui | bench 1632393 --- source/datagen.cpp | 172 +++--------- source/datagen.h | 12 +- source/datagenui.cpp | 639 +++++++++++++++++++++++++++++++++++++++++++ source/datagenui.h | 11 + source/main.cpp | 73 ++++- 5 files changed, 766 insertions(+), 141 deletions(-) create mode 100644 source/datagenui.cpp create mode 100644 source/datagenui.h diff --git a/source/datagen.cpp b/source/datagen.cpp index e52c24e..6303ae6 100644 --- a/source/datagen.cpp +++ b/source/datagen.cpp @@ -13,8 +13,10 @@ #include #include #include +#include #include "datagen.h" +#include "datagenui.h" #include "movegen.h" #include "search.h" #include "utils.h" @@ -277,7 +279,8 @@ static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) { } } -static void WriteToFile(std::vector &gamesBuffer, const std::string& basePath, int& fileCounter) { +static void WriteToFile(std::vector &gamesBuffer, const std::string& basePath, int& fileCounter, + std::atomic& files) { if (gamesBuffer.empty()) return; int32_t zeroes = 0; @@ -330,6 +333,7 @@ static void WriteToFile(std::vector &gamesBuffer, const std::string& baseP return; } + files.fetch_add(1, std::memory_order_relaxed); fileCounter++; } @@ -395,7 +399,7 @@ static std::string MergeThreadFiles() { return finalFileName; } -static void PlayGames(int id, std::atomic& positions, std::atomic& stopFlag) { +static void PlayGames(int id, DatagenStats& stats, std::atomic& stopFlag) { std::vector gamesBuffer; gamesBuffer.reserve(GAME_BUFFER); @@ -416,9 +420,15 @@ static void PlayGames(int id, std::atomic& positions, std::atomic& st PlayRandMoves(board, ctx.get()); if (IsGameOver(board, ctx.get())) continue; + ctx->nodes = 0; const int startingScore = SEARCH::SearchPosition(board, SearchParams(), ctx.get()).score; - if (std::abs(startingScore) >= evenityMargin) continue; + stats.nodes.fetch_add(ctx->nodes, std::memory_order_relaxed); + + if (std::abs(startingScore) >= evenityMargin) { + stats.rejected.fetch_add(1, std::memory_order_relaxed); + continue; + } ctx->nodes = 0; @@ -433,7 +443,9 @@ static void PlayGames(int id, std::atomic& positions, std::atomic& st while (!IsGameOver(board, ctx.get())) { if (g_shutdownRequested) break; + ctx->nodes = 0; SearchResults results = SEARCH::SearchPosition(board, SearchParams(), ctx.get()); + stats.nodes.fetch_add(ctx->nodes, std::memory_order_relaxed); if (!results.bestMove) break; safeResults = results; @@ -444,7 +456,7 @@ static void PlayGames(int id, std::atomic& positions, std::atomic& st board.MakeMove(results.bestMove); ctx->positionHistory[board.positionIndex] = board.hashKey; - positions++; + stats.positions.fetch_add(1, std::memory_order_relaxed); MOVEGEN::GenerateMoves(board, true); } @@ -455,21 +467,22 @@ static void PlayGames(int id, std::atomic& positions, std::atomic& st game.format.packFrom(startpos, staticEval, wdl); gamesBuffer.emplace_back(game); + stats.games.fetch_add(1, std::memory_order_relaxed); if (gamesBuffer.size() >= GAME_BUFFER) { - WriteToFile(gamesBuffer, basePath, fileCounter); + WriteToFile(gamesBuffer, basePath, fileCounter, stats.files); gamesBuffer.clear(); } } } catch (...) { if (!gamesBuffer.empty()) { - WriteToFile(gamesBuffer, basePath, fileCounter); + WriteToFile(gamesBuffer, basePath, fileCounter, stats.files); } throw; } if (!gamesBuffer.empty()) { - WriteToFile(gamesBuffer, basePath, fileCounter); + WriteToFile(gamesBuffer, basePath, fileCounter, stats.files); gamesBuffer.clear(); } @@ -482,23 +495,23 @@ static void PlayGames(int id, std::atomic& positions, std::atomic& st struct WinThreadArgs { int id; - std::atomic* positions; + DatagenStats* stats; std::atomic* stopFlag; }; static unsigned __stdcall WinThreadEntry(void* p) { std::unique_ptr args(static_cast(p)); - PlayGames(args->id, *args->positions, *args->stopFlag); + PlayGames(args->id, *args->stats, *args->stopFlag); _endthreadex(0); return 0; } static bool CreateWorkerThread(int id, - std::atomic& positions, + DatagenStats& stats, std::atomic& stopFlag, std::vector& threads, size_t stackSizeBytes) { - auto* args = new WinThreadArgs{ id, &positions, &stopFlag }; + auto* args = new WinThreadArgs{ id, &stats, &stopFlag }; unsigned tid = 0; HANDLE h = reinterpret_cast( @@ -535,7 +548,7 @@ static void JoinWorkerThreads(std::vector& threads) { #else static void* ThreadFunc(void* arg) { - auto* tup = static_cast*, std::atomic*>*>(arg); + auto* tup = static_cast*>*>(arg); PlayGames(std::get<0>(*tup), *std::get<1>(*tup), *std::get<2>(*tup)); delete tup; return nullptr; @@ -554,7 +567,7 @@ void Run(int targetPositions, int threads) { HideCursor(); #endif - std::atomic positions = 0; + DatagenStats stats; std::atomic stopFlag = false; #ifdef _WIN32 @@ -564,7 +577,7 @@ void Run(int targetPositions, int threads) { const size_t stackSizeBytes = 8ull * 1024ull * 1024ull; for (int i = 0; i < threads - 1; ++i) { - CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes); + CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes); } #else std::vector workerThreads; @@ -574,7 +587,7 @@ void Run(int targetPositions, int threads) { pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); - auto* args = new std::tuple*, std::atomic*>(i, &positions, &stopFlag); + auto* args = new std::tuple*>(i, &stats, &stopFlag); pthread_t thread; if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) { @@ -589,12 +602,13 @@ void Run(int targetPositions, int threads) { #endif Stopwatch sw; - while (positions < targetPositions && !g_shutdownRequested) { - PrintProgress(positions, targetPositions, sw, threads); + while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) { + PrintProgress(stats, targetPositions, sw, threads); std::this_thread::sleep_for(std::chrono::seconds(1)); } - PrintProgress(positions, targetPositions, sw, threads); + PrintProgress(stats, targetPositions, sw, threads); + PrintSummary(stats, targetPositions, sw, threads); stopFlag = true; @@ -676,7 +690,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) { HideCursor(); #endif - std::atomic positions = 0; + DatagenStats stats; std::atomic stopFlag = false; #ifdef _WIN32 @@ -686,7 +700,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) { const size_t stackSizeBytes = 8ull * 1024ull * 1024ull; for (int i = 0; i < threads - 1; ++i) { - CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes); + CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes); } #else std::vector workerThreads; @@ -696,7 +710,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) { pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); - auto* args = new std::tuple*, std::atomic*>(i, &positions, &stopFlag); + auto* args = new std::tuple*>(i, &stats, &stopFlag); pthread_t thread; if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) { @@ -711,12 +725,13 @@ void RunOnline(const std::string& username, int targetPositions, int threads) { #endif Stopwatch sw; - while (positions < targetPositions && !g_shutdownRequested) { - PrintProgress(positions, targetPositions, sw, threads); + while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) { + PrintProgress(stats, targetPositions, sw, threads); std::this_thread::sleep_for(std::chrono::seconds(1)); } - PrintProgress(positions, targetPositions, sw, threads); + PrintProgress(stats, targetPositions, sw, threads); + PrintSummary(stats, targetPositions, sw, threads); stopFlag = true; @@ -750,7 +765,7 @@ void RunOnline(const std::string& username, int targetPositions, int threads) { std::cout << "Uploading file to server..." << std::endl; std::string uploadUrl = SERVER_URL + "/api/upload/" + sessionId; - if (UploadFile(uploadUrl, mergedFile, username, positions.load())) { + if (UploadFile(uploadUrl, mergedFile, username, stats.positions.load())) { std::cout << "Upload successful!" << std::endl; std::error_code ec; @@ -772,109 +787,4 @@ void RunOnline(const std::string& username, int targetPositions, int threads) { std::cout << "\nOnline mode shutdown complete." << std::endl; } -void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) { - const std::string COLOR_RESET = "\033[0m"; - const std::string COLOR_TITLE = "\033[1;36m"; - const std::string COLOR_SECTION = "\033[1;33m"; - const std::string COLOR_VALUE = "\033[1;32m"; - const std::string COLOR_BAR = "\033[1;34m"; - - static double lastPositions = 0; - static double lastElapsed = 0; - static double refreshInterval = 1.0; - - double elapsed = stopwatch.GetElapsedSec(); - double positionsPerSec = 0; - - if (elapsed - lastElapsed >= refreshInterval) { - positionsPerSec = (positions - lastPositions) / (elapsed - lastElapsed); - lastPositions = positions; - lastElapsed = elapsed; - } - - std::cout << "\033[H"; - - int width = 60; - - std::string title = "Eleanor - Datagen"; - int titlePadding = (width - static_cast(title.length())) / 2; - std::cout << COLOR_TITLE << std::setw(titlePadding + static_cast(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(datagenText.length())) / 2; - std::cout << COLOR_SECTION << std::setw(datagenPadding + static_cast(datagenText.length())) << datagenText << COLOR_RESET << std::endl; - - std::cout << std::endl; - - std::string elapsedText = "Elapsed Time: " + std::to_string(static_cast(round(elapsed))) + " sec"; - int elapsedPadding = (width - static_cast(elapsedText.length())) / 2; - std::cout << COLOR_SECTION << std::setw(elapsedPadding + static_cast(elapsedText.length())) << elapsedText << COLOR_RESET << std::endl; - - std::string positionsPerSecText = "Positions/sec: " + std::to_string(static_cast(round(positionsPerSec))); - int positionsPerSecPadding = (width - static_cast(positionsPerSecText.length())) / 2; - std::cout << COLOR_VALUE << std::setw(positionsPerSecPadding + static_cast(positionsPerSecText.length())) << positionsPerSecText << COLOR_RESET << std::endl; - - std::cout << std::endl; - - std::string threadsText = "Threads: " + std::to_string(static_cast(threads)); - int threadsTextPadding = (width - static_cast(threadsText.length())) / 2; - std::cout << COLOR_SECTION << std::setw(threadsTextPadding + static_cast(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(remainingTime) / 3600; - int remainingMinutes = (static_cast(remainingTime) % 3600) / 60; - int remainingSeconds = static_cast(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(remainingTimeText.length())) / 2; - std::cout << COLOR_SECTION - << std::setw(remainingPadding + static_cast(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(round(progress * 100.0))) + " %"; - - int progressPadding = (width - static_cast(progressBar.length())) / 2; - std::cout << COLOR_BAR << std::setw(progressPadding + static_cast(progressBar.length())) - << progressBar << COLOR_RESET << std::endl; - - std::cout << std::endl; -} - -} // namespace DATAGEN +} // namespace DATAGEN \ No newline at end of file diff --git a/source/datagen.h b/source/datagen.h index a769f5b..03539ae 100644 --- a/source/datagen.h +++ b/source/datagen.h @@ -1,6 +1,7 @@ #pragma once #include "board.h" #include "utils.h" +#include #include #include "stopwatch.h" @@ -11,6 +12,15 @@ constexpr int SOFT_NODES = 5000; constexpr int HARD_NODES = 100000; constexpr int RAND_MOVES = 8; +// Live counters shared between the worker threads and the frontend. +struct DatagenStats { + std::atomic positions{0}; + std::atomic games{0}; + std::atomic files{0}; + std::atomic nodes{0}; + std::atomic rejected{0}; +}; + struct MarlinFormat { uint64_t occupancy; // 8 bytes: Bitboard representing all occupied squares (includes all pieces) std::array pieces; // 16 bytes: 64 squares stored in 4-bit format (2 squares per byte) @@ -62,6 +72,4 @@ struct Game { void Run(int targetPositions, int threads); void RunOnline(const std::string& username, int targetPositions, int threads); - -void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads); } diff --git a/source/datagenui.cpp b/source/datagenui.cpp new file mode 100644 index 0000000..16f7b2c --- /dev/null +++ b/source/datagenui.cpp @@ -0,0 +1,639 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "datagenui.h" +#include "datagen.h" +#include "stopwatch.h" + +// OS-dependent terminal detection includes +#ifdef _WIN32 + #include + #include +#else + #include + #include + #include +#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(std::lround(0 + t * 80)), + static_cast(std::lround(180 + t * 75)), + static_cast(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 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(s[j])) || s[j] == ';')) { + ++j; + } + if (j < s.size()) ++j; + i = j - 1; + continue; + } + } + if ((static_cast(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(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(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(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(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(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& samples, int width, + const std::vector& levels, const std::string& color) { + if (width <= 0 || samples.empty()) return ""; + + const int count = static_cast(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(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(std::lround((samples[i] - lo) / range * last)) + : last; + bar += levels[std::clamp(idx, 0, last)]; + } + + return color + bar + Reset(); +} + +struct RateTracker { + std::deque 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(snap.positions), snap.elapsed); + NodesRate().sample(static_cast(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 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(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(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 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(std::lround(progress * barWidth)); + + std::string bar; + for (int i = 0; i < barWidth; ++i) { + if (i < filled) bar += GradientAt(barWidth > 1 ? static_cast(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(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& 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 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_.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 diff --git a/source/datagenui.h b/source/datagenui.h new file mode 100644 index 0000000..aabcffa --- /dev/null +++ b/source/datagenui.h @@ -0,0 +1,11 @@ +#pragma once +#include "datagen.h" +#include "stopwatch.h" + +namespace DATAGEN { + +void PrintProgress(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads); +void PrintSummary(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads); +void PrintUsage(); + +} // namespace DATAGEN diff --git a/source/main.cpp b/source/main.cpp index 6135535..193a48a 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -5,9 +5,13 @@ #include "benchmark.h" #include "search.h" #include "datagen.h" +#include "datagenui.h" #include "nnue.h" #include "tests.h" +#include +#include + #ifndef EVALFILE #define EVALFILE "./nnue.bin" #endif @@ -29,6 +33,30 @@ INCBIN(EVAL, EVALFILE); #endif +// Strict integer parsing: returns 0 when the text is not a positive whole number, +// so bad CLI input reports a usage error instead of throwing std::invalid_argument. +static int ParsePositiveInt(const char* text) { + if (text == nullptr || *text == '\0') return 0; + + for (const char* c = text; *c != '\0'; ++c) { + if (*c < '0' || *c > '9') return 0; + } + + try { + const long long value = std::stoll(text); + if (value <= 0 || value > 2147483647LL) return 0; + return static_cast(value); + } catch (...) { + return 0; + } +} + +static void ArgError(const char* value, const char* name) { + std::cerr << "error: invalid " << name << " value '" << value + << "'. Expected a positive whole number.\n" + << "\nRun 'Eleanor datagen --help' for usage.\n"; +} + int main(int argc, char* argv[]) { auto loadDefaultNet = [&]([[maybe_unused]] bool warnMSVC = false) { #if defined(_MSC_VER) && !defined(__clang__) @@ -53,27 +81,56 @@ int main(int argc, char* argv[]) { SEARCH::InitLMRTable(); #endif - Board board; + Board board; if (argc > 1) { if (std::string(argv[1]) == "bench") { RunBenchmark(); } else if (std::string(argv[1]) == "datagen") { + if (argc > 2) { + const std::string arg = argv[2]; + + if (arg == "--help" || arg == "-h" || arg == "help") { + DATAGEN::PrintUsage(); + return 0; + } + } + int positions = 1; int threads = 1; std::string username = ""; - - if (argc > 2) { - positions = std::stoi(argv[2]) * 1000; - if (argc > 3) { - threads = std::stoi(argv[3]); - if (argc > 4) { + if (argc > 2) { + positions = ParsePositiveInt(argv[2]); + if (positions == 0) { + ArgError(argv[2], "positions"); + return 1; + } + positions *= 1000; + + if (argc > 3) { + threads = ParsePositiveInt(argv[3]); + if (threads == 0) { + ArgError(argv[3], "threads"); + return 1; + } + + if (argc > 4) { username = argv[4]; } } } - + + // Only the main thread renders, so it never generates anything. + // Checked outside the argc guards so a bare "datagen" is caught too. + if (threads < 2) { + std::cerr << "error: threads must be at least 2 (got " << threads + << "). The main thread only renders the progress" + << " screen, so " << threads << " leaves no worker to generate.\n" + << "\nRun 'Eleanor datagen --help' for usage.\n"; + return 1; + } + if (!username.empty()) { DATAGEN::RunOnline(username, positions, threads); } else {