From 6e905fdf2e1c4a1bec8972a8fdff3923d5318d2c Mon Sep 17 00:00:00 2001 From: rektdie Date: Sun, 6 Apr 2025 22:10:41 +0200 Subject: [PATCH 1/3] game buffering in datagen --- source/datagen.cpp | 221 ++++++++++++++++----------------------------- source/datagen.h | 4 + source/stopwatch.h | 1 + 3 files changed, 84 insertions(+), 142 deletions(-) diff --git a/source/datagen.cpp b/source/datagen.cpp index 0f300a0..3673e99 100644 --- a/source/datagen.cpp +++ b/source/datagen.cpp @@ -10,7 +10,6 @@ #include "evaluate.h" #include "search.h" #include "movegen.h" -#include "stopwatch.h" #ifdef _WIN32 #include @@ -80,79 +79,100 @@ static bool IsGameOver(Board &board) { return false; } -std::ostream &operator<<(std::ostream &os, const MarlinFormat &format) { - os.write(reinterpret_cast(&format), sizeof(MarlinFormat)); - return os; +static void WriteToFile(std::vector &gamesBuffer, std::ofstream &file) { + int32_t zeroes = 0; + for (const Game& game : gamesBuffer) { + file.write(reinterpret_cast(&game.format), sizeof(game.format)); + file.write(reinterpret_cast(game.moves.data()), sizeof(ScoredMove) * game.moves.size()); + file.write(reinterpret_cast(&zeroes), 4); + } + file.flush(); } -std::istream &operator>>(std::istream &is, MarlinFormat &format) { - is.read(reinterpret_cast(&format), sizeof(MarlinFormat)); - return is; +void PlayGame(std::atomic& positions, U64 targetPositions, std::vector &gamesBuffer, std::ofstream &file) { + while (positions.load(std::memory_order_relaxed) < targetPositions) { + Game game; + Board board; + + uint8_t wdl = 1; + positionIndex = 0; + std::memset(SEARCH::killerMoves, 0, sizeof(SEARCH::killerMoves)); + SEARCH::history.Clear(); + + PlayRandMoves(board); + + int staticEval = HCE::Evaluate(board); + + SEARCH::SearchResults safeResults; + + MOVEGEN::GenerateMoves(board); + + while (!IsGameOver(board)) { + SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams()); + + if (!results.bestMove) break; + safeResults = results; + + game.moves.push_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(), UTILS::ConvertToWhiteRelative(board, results.score))); + board.MakeMove(results.bestMove); + MOVEGEN::GenerateMoves(board); + + positions.fetch_add(1, std::memory_order_relaxed); + + if (std::abs(safeResults.score) >= std::abs(SEARCH::MATE_SCORE) - SEARCH::MAX_PLY) { + wdl = board.sideToMove ? 2 : 0; + } + } + game.format.packFrom(board, UTILS::ConvertToWhiteRelative(board, staticEval), wdl); + gamesBuffer.push_back(game); + + std::lock_guard guard(mutex); + if (gamesBuffer.size() >= GAME_BUFFER) { + WriteToFile(gamesBuffer, file); + gamesBuffer.clear(); + } + } } -std::ostream &operator<<(std::ostream &os, const ScoredMove &move) { - os.write(reinterpret_cast(&move), sizeof(ScoredMove)); - return os; -} +void Run(int targetPositions, int threads) { + #ifdef _WIN32 + system("cls"); + HideCursor(); + #else + std::cout << "\033[2J\033[H"; + HideCursorLinux(); + #endif -std::istream &operator>>(std::istream &is, ScoredMove &move) { - is.read(reinterpret_cast(&move), sizeof(ScoredMove)); - return is; -} + Stopwatch stopwatch; -std::ostream &operator<<(std::ostream &os, const Game &game) { - os << game.format; + std::atomic positions = 0; + std::vector gamesBuffer; - uint32_t moveCount = game.moves.size(); - os.write(reinterpret_cast(&moveCount), sizeof(moveCount)); + std::ofstream file("data.binpack", std::ios::app | std::ios::binary); - for (const auto &move : game.moves) { - os << move; + for (int i = 0; i < threads; i++) { + auto worker = std::thread(PlayGame, std::ref(positions), targetPositions * 1000, std::ref(gamesBuffer), std::ref(file)); + worker.detach(); } - return os; -} + int lastPrintedPosition = 0; + double lastPrintedTime = stopwatch.GetElapsedSec(); -std::istream &operator>>(std::istream &is, Game &game) { - is >> game.format; - - uint32_t moveCount; - is.read(reinterpret_cast(&moveCount), sizeof(moveCount)); - - game.moves.resize(moveCount); - for (auto &move : game.moves) { - is >> move; + while (positions.load(std::memory_order_relaxed) < targetPositions * 1000) { + // Print progress every second + PrintProgress(positions, targetPositions * 1000, stopwatch, threads); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } - return is; -} + PrintProgress(positions, targetPositions * 1000, stopwatch, threads); + WriteToFile(gamesBuffer, file); -static void WriteToFile(const Game &game, const std::string &filename) { - std::lock_guard lock(mutex); - // Create a buffer to store the serialized data [prevents corruption] - std::vector buffer; - const size_t formatSize = sizeof(MarlinFormat); - buffer.resize(formatSize + sizeof(uint32_t) * game.moves.size() + sizeof(uint32_t)); - - std::memcpy(buffer.data(), &game.format, formatSize); - - size_t offset = formatSize; - - for (const auto &move : game.moves) { - std::memcpy(buffer.data() + offset, &move, sizeof(ScoredMove)); - offset += sizeof(ScoredMove); - } - - uint32_t zero = 0; - std::memcpy(buffer.data() + offset, &zero, sizeof(zero)); - - std::ofstream file(filename, std::ios::binary | std::ios::out | std::ios::app); - if (!file) throw std::runtime_error("Failed to open file for writing"); - - file.write(buffer.data(), buffer.size()); - - file.close(); + #ifdef _WIN32 + ShowCursor(); + #else + ShowCursorLinux(); + #endif } void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) { @@ -225,87 +245,4 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int std::cout << std::string(width, '-') << std::endl; } -void PlayGame(std::atomic& positions, int targetPositions) { - while (positions.load(std::memory_order_relaxed) < targetPositions) { - Game game; - Board board; - - uint8_t wdl = 1; - positionIndex = 0; - std::memset(SEARCH::killerMoves, 0, sizeof(SEARCH::killerMoves)); - SEARCH::history.Clear(); - - PlayRandMoves(board); - - int staticEval = HCE::Evaluate(board); - - SEARCH::SearchResults safeResults; - - MOVEGEN::GenerateMoves(board); - - while (!IsGameOver(board)) { - SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams()); - - if (!results.bestMove) break; - safeResults = results; - - game.moves.push_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(), UTILS::ConvertToWhiteRelative(board, results.score))); - board.MakeMove(results.bestMove); - MOVEGEN::GenerateMoves(board); - - // Increment positions, but do not exceed target - if (positions.load(std::memory_order_relaxed) < targetPositions) { - positions.fetch_add(1, std::memory_order_relaxed); - - if (std::abs(safeResults.score) >= std::abs(SEARCH::MATE_SCORE) - SEARCH::MAX_PLY) { - wdl = board.sideToMove ? 2 : 0; - } - - - } - } - game.format.packFrom(board, UTILS::ConvertToWhiteRelative(board, staticEval), wdl); - WriteToFile(game, "data.binpack"); - } -} - -void Run(int targetPositions, int threads) { - #ifdef _WIN32 - system("cls"); - HideCursor(); - #else - std::cout << "\033[2J\033[H"; - HideCursorLinux(); - #endif - - Stopwatch stopwatch; - - std::atomic positions = 0; - - for (int i = 0; i < threads; i++) { - auto worker = std::thread(PlayGame, std::ref(positions), targetPositions * 1000); - worker.detach(); - } - - int lastPrintedPosition = 0; - double lastPrintedTime = stopwatch.GetElapsedSec(); - - while (positions.load(std::memory_order_relaxed) < targetPositions * 1000) { - // Print progress every second - double currentTime = stopwatch.GetElapsedSec(); - if (currentTime - lastPrintedTime >= 1) { - lastPrintedTime = currentTime; - PrintProgress(positions, targetPositions * 1000, stopwatch, threads); - } - } - - PrintProgress(positions, targetPositions * 1000, stopwatch, threads); - - #ifdef _WIN32 - ShowCursor(); - #else - ShowCursorLinux(); - #endif -} - } \ No newline at end of file diff --git a/source/datagen.h b/source/datagen.h index 28003ea..a60572f 100644 --- a/source/datagen.h +++ b/source/datagen.h @@ -2,9 +2,11 @@ #include "board.h" #include "utils.h" #include +#include "stopwatch.h" namespace DATAGEN { +constexpr int GAME_BUFFER = 1000; constexpr int SOFT_NODES = 5000; constexpr int HARD_NODES = 100000; constexpr int RAND_MOVES = 8; @@ -78,4 +80,6 @@ struct Game { }; void Run(int targetPositions, int threads); + +void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads); } \ No newline at end of file diff --git a/source/stopwatch.h b/source/stopwatch.h index 211f851..fe47086 100644 --- a/source/stopwatch.h +++ b/source/stopwatch.h @@ -1,3 +1,4 @@ +#pragma once #include class Stopwatch { -- 2.47.3 From 52df753effd91a3e569b0b2bd91d40980fa33e93 Mon Sep 17 00:00:00 2001 From: rektdie Date: Mon, 7 Apr 2025 04:43:54 +0200 Subject: [PATCH 2/3] slight improvements but threads still stop randomly --- source/datagen.cpp | 87 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 70 insertions(+), 17 deletions(-) diff --git a/source/datagen.cpp b/source/datagen.cpp index 3673e99..b56345b 100644 --- a/source/datagen.cpp +++ b/source/datagen.cpp @@ -43,7 +43,8 @@ static void ShowCursorLinux() { namespace DATAGEN { -std::mutex mutex; +// Atomic bool for locking +std::atomic bufferLockFlag(false); static void PlayRandMoves(Board &board) { std::random_device dev; @@ -54,6 +55,7 @@ static void PlayRandMoves(Board &board) { std::uniform_int_distribution dist(0, board.currentMoveIndex - 1); bool isLegal = board.MakeMove(board.moveList[dist(rng)]); + if (!isLegal) count--; } @@ -89,8 +91,10 @@ static void WriteToFile(std::vector &gamesBuffer, std::ofstream &file) { file.flush(); } -void PlayGame(std::atomic& positions, U64 targetPositions, std::vector &gamesBuffer, std::ofstream &file) { - while (positions.load(std::memory_order_relaxed) < targetPositions) { +void PlayGame(std::atomic& positions, U64 targetPositions, std::vector &gamesBuffer, + std::ofstream &file, std::atomic& shouldStop) { + while (!shouldStop.load(std::memory_order_relaxed) && + positions.load(std::memory_order_relaxed) < targetPositions) { Game game; Board board; @@ -123,13 +127,30 @@ void PlayGame(std::atomic& positions, U64 targetPositions, std::vector guard(mutex); - if (gamesBuffer.size() >= GAME_BUFFER) { - WriteToFile(gamesBuffer, file); - gamesBuffer.clear(); + // Wait until the lock is available + while (!shouldStop.load(std::memory_order_relaxed) && + bufferLockFlag.exchange(true, std::memory_order_acquire)) { + // Spin-wait + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + // One final check before writing + if (!shouldStop.load(std::memory_order_relaxed)) { + gamesBuffer.push_back(game); + + if (gamesBuffer.size() >= GAME_BUFFER) { + WriteToFile(gamesBuffer, file); + gamesBuffer.clear(); + } + } + + // Unlock the buffer after writing + bufferLockFlag.store(false, std::memory_order_release); } } } @@ -146,27 +167,48 @@ void Run(int targetPositions, int threads) { Stopwatch stopwatch; std::atomic positions = 0; + std::atomic shouldStop(false); std::vector gamesBuffer; + std::vector workers; std::ofstream file("data.binpack", std::ios::app | std::ios::binary); + // Create and start worker threads for (int i = 0; i < threads; i++) { - auto worker = std::thread(PlayGame, std::ref(positions), targetPositions * 1000, std::ref(gamesBuffer), std::ref(file)); - worker.detach(); + workers.push_back(std::thread(PlayGame, std::ref(positions), + targetPositions * 1000, std::ref(gamesBuffer), + std::ref(file), std::ref(shouldStop))); } int lastPrintedPosition = 0; double lastPrintedTime = stopwatch.GetElapsedSec(); + // Monitor progress while (positions.load(std::memory_order_relaxed) < targetPositions * 1000) { - // Print progress every second PrintProgress(positions, targetPositions * 1000, stopwatch, threads); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } - PrintProgress(positions, targetPositions * 1000, stopwatch, threads); - WriteToFile(gamesBuffer, file); + // Signal threads to stop + shouldStop.store(true, std::memory_order_relaxed); + + // Wait for all threads to finish + for (auto& worker : workers) { + if (worker.joinable()) { + worker.join(); + } + } + // Final progress update and buffer flush + PrintProgress(positions, targetPositions * 1000, stopwatch, threads); + + // Final check - lock buffer to ensure exclusive access + while (bufferLockFlag.exchange(true, std::memory_order_acquire)) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + WriteToFile(gamesBuffer, file); + bufferLockFlag.store(false, std::memory_order_release); #ifdef _WIN32 ShowCursor(); @@ -176,8 +218,19 @@ void Run(int targetPositions, int threads) { } void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) { + static double lastPositions = 0; // To track how many positions were processed last time + static double lastElapsed = 0; // To track the last elapsed time for more frequent updates + static double refreshInterval = 1.0; // Update every second + double elapsed = stopwatch.GetElapsedSec(); - double positionsPerSec = elapsed > 0 ? positions / elapsed : 0; + double positionsPerSec = 0; + + // Update positionsPerSec if the time difference is above the threshold + if (elapsed - lastElapsed >= refreshInterval) { + positionsPerSec = (positions - lastPositions) / (elapsed - lastElapsed); + lastPositions = positions; + lastElapsed = elapsed; + } int positionsInThousands = static_cast(round(positions / 1000.0)); int targetInThousands = static_cast(round(targetPositions / 1000.0)); @@ -226,6 +279,7 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int int pos = (int)(progress * barWidth); std::string progressBar = "["; + for (int i = 0; i < barWidth; ++i) { if (i < pos) { progressBar += "="; @@ -235,14 +289,13 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int progressBar += " "; } } + progressBar += "] " + std::to_string(static_cast(round(progress * 100.0))) + " %"; int progressPadding = (width - progressBar.length()) / 2; std::cout << std::setw(progressPadding + progressBar.length()) << progressBar << std::endl; std::cout << std::endl; - - std::cout << std::string(width, '-') << std::endl; } } \ No newline at end of file -- 2.47.3 From ea81850a3d88dd43c1b86f4a71d74104ba0dfbb4 Mon Sep 17 00:00:00 2001 From: rektdie Date: Mon, 7 Apr 2025 13:11:13 +0200 Subject: [PATCH 3/3] better thread handling --- source/datagen.cpp | 165 +++++++++++++++++++++++++-------------------- source/datagen.h | 2 +- 2 files changed, 92 insertions(+), 75 deletions(-) diff --git a/source/datagen.cpp b/source/datagen.cpp index b56345b..1bc1425 100644 --- a/source/datagen.cpp +++ b/source/datagen.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "datagen.h" #include "movegen.h" #include "evaluate.h" @@ -43,8 +44,7 @@ static void ShowCursorLinux() { namespace DATAGEN { -// Atomic bool for locking -std::atomic bufferLockFlag(false); +std::mutex bufferMutex; static void PlayRandMoves(Board &board) { std::random_device dev; @@ -99,58 +99,62 @@ void PlayGame(std::atomic& positions, U64 targetPositions, std::vector(board); - - while (!IsGameOver(board)) { - SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams()); - - if (!results.bestMove) break; - safeResults = results; - - game.moves.push_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(), UTILS::ConvertToWhiteRelative(board, results.score))); - board.MakeMove(results.bestMove); + try { + PlayRandMoves(board); + int staticEval = HCE::Evaluate(board); + SEARCH::SearchResults safeResults; MOVEGEN::GenerateMoves(board); - positions.fetch_add(1, std::memory_order_relaxed); + while (!IsGameOver(board)) { + SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams()); - if (std::abs(safeResults.score) >= std::abs(SEARCH::MATE_SCORE) - SEARCH::MAX_PLY) { - wdl = board.sideToMove ? 2 : 0; - } - } - - // Only add the game to buffer if we haven't been told to stop - if (!shouldStop.load(std::memory_order_relaxed)) { - game.format.packFrom(board, UTILS::ConvertToWhiteRelative(board, staticEval), wdl); + if (!results.bestMove) break; + safeResults = results; - // Wait until the lock is available - while (!shouldStop.load(std::memory_order_relaxed) && - bufferLockFlag.exchange(true, std::memory_order_acquire)) { - // Spin-wait - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } + game.moves.push_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(), UTILS::ConvertToWhiteRelative(board, results.score))); + + // Error checking for move making + if (!board.MakeMove(results.bestMove)) { + // Invalid move - break the loop + break; + } + + MOVEGEN::GenerateMoves(board); + positions.fetch_add(1, std::memory_order_relaxed); - // One final check before writing - if (!shouldStop.load(std::memory_order_relaxed)) { - gamesBuffer.push_back(game); - - if (gamesBuffer.size() >= GAME_BUFFER) { - WriteToFile(gamesBuffer, file); - gamesBuffer.clear(); + if (std::abs(safeResults.score) >= std::abs(SEARCH::MATE_SCORE) - SEARCH::MAX_PLY) { + wdl = board.sideToMove ? 2 : 0; } } + + // Only add the game to buffer if we haven't been told to stop + if (!shouldStop.load(std::memory_order_relaxed)) { + game.format.packFrom(board, UTILS::ConvertToWhiteRelative(board, staticEval), wdl); - // Unlock the buffer after writing - bufferLockFlag.store(false, std::memory_order_release); + // Use a proper lock instead of spin-waiting + { + std::lock_guard lock(bufferMutex); + + // Check again after acquiring the lock + if (!shouldStop.load(std::memory_order_relaxed)) { + gamesBuffer.push_back(game); + + if (gamesBuffer.size() >= GAME_BUFFER) { + WriteToFile(gamesBuffer, file); + gamesBuffer.clear(); + } + } + } + } + } catch (const std::exception& e) { + // Log exception but allow thread to continue + std::cerr << "Thread exception: " << e.what() << std::endl; } } } @@ -171,45 +175,58 @@ void Run(int targetPositions, int threads) { std::vector gamesBuffer; std::vector workers; - std::ofstream file("data.binpack", std::ios::app | std::ios::binary); + try { + std::ofstream file("data.binpack", std::ios::app | std::ios::binary); + if (!file.is_open()) { + throw std::runtime_error("Failed to open output file"); + } - // Create and start worker threads - for (int i = 0; i < threads; i++) { - workers.push_back(std::thread(PlayGame, std::ref(positions), - targetPositions * 1000, std::ref(gamesBuffer), - std::ref(file), std::ref(shouldStop))); - } + // Create and start worker threads + for (int i = 0; i < threads; i++) { + workers.push_back(std::thread(PlayGame, std::ref(positions), + targetPositions * 1000, std::ref(gamesBuffer), + std::ref(file), std::ref(shouldStop))); + } - int lastPrintedPosition = 0; - double lastPrintedTime = stopwatch.GetElapsedSec(); + // Monitor progress + while (positions.load(std::memory_order_relaxed) < targetPositions * 1000) { + PrintProgress(positions, targetPositions * 1000, stopwatch, threads); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } - // Monitor progress - while (positions.load(std::memory_order_relaxed) < targetPositions * 1000) { + // Signal threads to stop + shouldStop.store(true, std::memory_order_relaxed); + + // Wait for all threads to finish + for (auto& worker : workers) { + if (worker.joinable()) { + worker.join(); + } + } + + // Final progress update and buffer flush PrintProgress(positions, targetPositions * 1000, stopwatch, threads); - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - } + + // Final buffer flush with proper synchronization + { + std::lock_guard lock(bufferMutex); + WriteToFile(gamesBuffer, file); + } - // Signal threads to stop - shouldStop.store(true, std::memory_order_relaxed); - - // Wait for all threads to finish - for (auto& worker : workers) { - if (worker.joinable()) { - worker.join(); + } catch (const std::exception& e) { + std::cerr << "Error in data generation: " << e.what() << std::endl; + + // Signal threads to stop in case of error + shouldStop.store(true, std::memory_order_relaxed); + + // Make sure to join any running threads + for (auto& worker : workers) { + if (worker.joinable()) { + worker.join(); + } } } - // Final progress update and buffer flush - PrintProgress(positions, targetPositions * 1000, stopwatch, threads); - - // Final check - lock buffer to ensure exclusive access - while (bufferLockFlag.exchange(true, std::memory_order_acquire)) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - - WriteToFile(gamesBuffer, file); - bufferLockFlag.store(false, std::memory_order_release); - #ifdef _WIN32 ShowCursor(); #else @@ -298,4 +315,4 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int std::cout << std::endl; } -} \ No newline at end of file +} diff --git a/source/datagen.h b/source/datagen.h index a60572f..208d4ff 100644 --- a/source/datagen.h +++ b/source/datagen.h @@ -82,4 +82,4 @@ struct Game { void Run(int targetPositions, int threads); void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads); -} \ No newline at end of file +} -- 2.47.3